From 0ef3433a1fe74af0df941ccb723eb6c9cf51f363 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Jare=C5=A1?= Date: Tue, 6 May 2025 12:42:37 +0200 Subject: [PATCH 001/541] Update branding to MSTest 3.10 and MTP 1.8 (#5563) --- eng/Versions.props | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/eng/Versions.props b/eng/Versions.props index 73f0048b6b..5c2268ba95 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -1,9 +1,9 @@ - 3.9.0 + 3.10.0 - 1.7.0 + 1.8.0 preview From 2b3a9fd44e2cbb1c52362a211b025b9eddbd8ec1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Jare=C5=A1?= Date: Wed, 7 May 2025 09:47:18 +0200 Subject: [PATCH 002/541] Fix alpha branding on devops extension in rtm build (#5566) --- .../Microsoft.Testing.Extensions.AzureDevOpsReport.csproj | 1 + 1 file changed, 1 insertion(+) diff --git a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Microsoft.Testing.Extensions.AzureDevOpsReport.csproj b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Microsoft.Testing.Extensions.AzureDevOpsReport.csproj index c509126613..03f70cd149 100644 --- a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Microsoft.Testing.Extensions.AzureDevOpsReport.csproj +++ b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Microsoft.Testing.Extensions.AzureDevOpsReport.csproj @@ -6,6 +6,7 @@ 1.0.0 alpha + true From 4473c0aaebae6f08811d50b449a2164e78cc042d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Jare=C5=A1?= Date: Fri, 9 May 2025 12:31:04 +0200 Subject: [PATCH 003/541] Add 3.9.0 changelog (#5572) --- docs/Changelog-Platform.md | 84 ++++++++++++++++++++++++++++++++++++++ docs/Changelog.md | 74 +++++++++++++++++++++++++++++++++ 2 files changed, 158 insertions(+) diff --git a/docs/Changelog-Platform.md b/docs/Changelog-Platform.md index 766d06c90e..2b7c67ebba 100644 --- a/docs/Changelog-Platform.md +++ b/docs/Changelog-Platform.md @@ -4,6 +4,90 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) +## [1.7.0] - 2025-03-17 + +See full log [here](https://github.com/microsoft/testfx/compare/v3.8.3...v3.9.0) + +### Added + +* [Source Breaking (only for framework authors)]: Support test artifacts in VS by @Youssef1313 in [#5323](https://github.com/microsoft/testfx/pull/5323) +* Add (alpha) Azure DevOps extension to report errors by @nohwnd in [#5260](https://github.com/microsoft/testfx/pull/5260) +* Add banner for MSTest.Engine by @Youssef1313 in [#5051](https://github.com/microsoft/testfx/pull/5051) +* Use terminal logger for discovery by @nohwnd in [#4907](https://github.com/microsoft/testfx/pull/4907) +* Add RetryContext.FirstRunResults by @Youssef1313 in [#5314](https://github.com/microsoft/testfx/pull/5314) +* VSTestBridge: Add traits as TestMetadataProperty by @Youssef1313 in [#5316](https://github.com/microsoft/testfx/pull/5316) +* Mark APIs not supported in wasi by @Youssef1313 in [#5367](https://github.com/microsoft/testfx/pull/5367) +* Show disk info when hang dump fails by @Youssef1313 in [#5404](https://github.com/microsoft/testfx/pull/5404) +* Implement analyzer for RetryAttribute to be present on test methods by @Youssef1313 in [#5437](https://github.com/microsoft/testfx/pull/5437) +* Add TestMethodIdentifierProperty constructor with arity parameter by @Youssef1313 in [#5528](https://github.com/microsoft/testfx/pull/5528) + +### Fixed + +* Kill testhost if writing hang dump fails by @Youssef1313 in [#5538](https://github.com/microsoft/testfx/pull/5538) +* Simplify generated file name by using DefaultLanguageSourceExtension by @Youssef1313 in [#5026](https://github.com/microsoft/testfx/pull/5026) +* Fix handling of unsupported platforms of CancelKeyPress by @Youssef1313 in [#5038](https://github.com/microsoft/testfx/pull/5038) +* Refactor logic around GetCurrentTestApplicationFullPath by @Youssef1313 in [#5037](https://github.com/microsoft/testfx/pull/5037) +* Enable platform compatibility warnings for android, ios, tvos, and browser by @Youssef1313 in [#5046](https://github.com/microsoft/testfx/pull/5046) +* Improve MSTest.SourceGeneration incrementality by @Youssef1313 in [#5053](https://github.com/microsoft/testfx/pull/5053) +* remove redundant IPlatformOutputDeviceManager by @SimonCropp in [#4848](https://github.com/microsoft/testfx/pull/4848) +* Avoid using unsupported APIs by @Youssef1313 in [#5057](https://github.com/microsoft/testfx/pull/5057) +* Fix binlog base name for .NET Framework tests by @Youssef1313 in [#5102](https://github.com/microsoft/testfx/pull/5102) +* Improve ExecutionContext propagation by @Youssef1313 in [#5156](https://github.com/microsoft/testfx/pull/5156) +* use StringBuilder AppendJoin by @SimonCropp in [#5167](https://github.com/microsoft/testfx/pull/5167) +* Update README.md with MSTest.Sdk information by @stan-sz in [#5214](https://github.com/microsoft/testfx/pull/5214) +* Add assembly name by @nohwnd in [#5235](https://github.com/microsoft/testfx/pull/5235) +* Correct branding as Microsoft.Testing.Platform by @Youssef1313 in [#5240](https://github.com/microsoft/testfx/pull/5240) +* Remove extra space by @nohwnd in [#5238](https://github.com/microsoft/testfx/pull/5238) +* Fix Retry for dotnet test by @Youssef1313 in [#5261](https://github.com/microsoft/testfx/pull/5261) +* Onboard to new dotnet test experience by @Evangelink in [#5111](https://github.com/microsoft/testfx/pull/5111) +* Add InstanceId to communication with dotnet test by @mariam-abdulla in [#5279](https://github.com/microsoft/testfx/pull/5279) +* Add instance id to dotnet test protocol by @mariam-abdulla in [#5287](https://github.com/microsoft/testfx/pull/5287) +* Use FileAccess.Read when reading testconfig.json file by @Youssef1313 in [#5264](https://github.com/microsoft/testfx/pull/5264) +* Fix double empty line by @nohwnd in [#5317](https://github.com/microsoft/testfx/pull/5317) +* Remove SessionUid from FileArtifactProperty by @Youssef1313 in [#5347](https://github.com/microsoft/testfx/pull/5347) +* Fix typo in DotnetTestDataConsumer causes only first artifact to be sent by @Youssef1313 in [#5349](https://github.com/microsoft/testfx/pull/5349) +* fix nullability in GetRepoRoot by @SimonCropp in [#5392](https://github.com/microsoft/testfx/pull/5392) +* remove redundant null check in FormatInnerExceptions by @SimonCropp in [#5397](https://github.com/microsoft/testfx/pull/5397) +* fix nullability of CreateBindCtx by @SimonCropp in [#5385](https://github.com/microsoft/testfx/pull/5385) +* remove redundant control flow statements by @SimonCropp in [#5403](https://github.com/microsoft/testfx/pull/5403) +* fix nullability of InvokeTestingPlatformTask _outputFileName by @SimonCropp in [#5394](https://github.com/microsoft/testfx/pull/5394) +* fix nullability of argument in GetProcessExitCodeAsync_IgnoreExitCodes by @SimonCropp in [#5386](https://github.com/microsoft/testfx/pull/5386) +* remove redundant null check for OpenBaseKey return by @SimonCropp in [#5395](https://github.com/microsoft/testfx/pull/5395) +* remove redundant null check in GetStringFromIndexOrDefault by @SimonCropp in [#5396](https://github.com/microsoft/testfx/pull/5396) +* fix nullability in FileLoggerProvider by @SimonCropp in [#5398](https://github.com/microsoft/testfx/pull/5398) +* remove un-used TestNodeProcessor by @SimonCropp in [#5430](https://github.com/microsoft/testfx/pull/5430) +* Rename MTP entrypoint to MicrosoftTestingPlatformEntryPoint by @Youssef1313 in [#5423](https://github.com/microsoft/testfx/pull/5423) +* use null propagation and mark as warning in editorconfig by @SimonCropp in [#5383](https://github.com/microsoft/testfx/pull/5383) +* FindNode cant return null by @SimonCropp in [#5448](https://github.com/microsoft/testfx/pull/5448) +* remove un-used methods in UnicodeCharacterUtilities by @SimonCropp in [#5444](https://github.com/microsoft/testfx/pull/5444) +* remove ServerLogMessageInMemoryStore by @SimonCropp in [#5456](https://github.com/microsoft/testfx/pull/5456) +* Remove some redundant casts and mark as a warning for rider and R# by @SimonCropp in [#5459](https://github.com/microsoft/testfx/pull/5459) +* Use GetFileNameWithoutExtension for crashdump file name to be consistent with hangdump by @Youssef1313 in [#5454](https://github.com/microsoft/testfx/pull/5454) +* Remove dead --internal-vstest-adapter by @Youssef1313 in [#5450](https://github.com/microsoft/testfx/pull/5450) +* Consistent command-line options provider properties by @Youssef1313 in [#5452](https://github.com/microsoft/testfx/pull/5452) +* Update Fakes dependency by @stan-sz in [#5482](https://github.com/microsoft/testfx/pull/5482) +* Use PlatformVersion.Version as the server version by @Youssef1313 in [#5486](https://github.com/microsoft/testfx/pull/5486) +* Handle DebugOrTraceTrxMessage in TrxReportEngine by @Youssef1313 in [#5510](https://github.com/microsoft/testfx/pull/5510) +* Few improvements to AzDO extension by @Youssef1313 in [#5513](https://github.com/microsoft/testfx/pull/5513) +* VSTestBridge+MSTest: Use TestMethodIdentifierProperty and stop sending VSTest-specifics by @Youssef1313 in [#5409](https://github.com/microsoft/testfx/pull/5409) +* Add vstest.TestCase.CodeFilePath and vstest.TestCase.LineNumber by @Youssef1313 in [#5539](https://github.com/microsoft/testfx/pull/5539) + +### Artifacts + +* MSTest: [3.9.0](https://www.nuget.org/packages/MSTest/3.9.0) +* MSTest.TestFramework: [3.9.0](https://www.nuget.org/packages/MSTest.TestFramework/3.9.0) +* MSTest.TestAdapter: [3.9.0](https://www.nuget.org/packages/MSTest.TestAdapter/3.9.0) +* MSTest.Analyzers: [3.9.0](https://www.nuget.org/packages/MSTest.Analyzers/3.9.0) +* MSTest.Sdk: [3.9.0](https://www.nuget.org/packages/MSTest.Sdk/3.9.0) +* Microsoft.Testing.Extensions.CrashDump: [1.7.0](https://www.nuget.org/packages/Microsoft.Testing.Extensions.CrashDump/1.7.0) +* Microsoft.Testing.Extensions.HangDump: [1.7.0](https://www.nuget.org/packages/Microsoft.Testing.Extensions.HangDump/1.7.0) +* Microsoft.Testing.Extensions.HotReload: [1.7.0](https://www.nuget.org/packages/Microsoft.Testing.Extensions.HotReload/1.7.0) +* Microsoft.Testing.Extensions.Retry: [1.7.0](https://www.nuget.org/packages/Microsoft.Testing.Extensions.Retry/1.7.0) +* Microsoft.Testing.Extensions.TrxReport: [1.7.0](https://www.nuget.org/packages/Microsoft.Testing.Extensions.TrxReport/1.7.0) +* Microsoft.Testing.Extensions.AzureDevOpsReport [1.0.0-alpha.25256.6](https://www.nuget.org/packages/Microsoft.Testing.Extensions.AzureDevOpsReport/1.0.0-alpha.25256.6) +* MSTest.SourceGeneration: [1.0.0-alpha.25256.6](https://www.nuget.org/packages/MSTest.SourceGeneration/1.0.0-alpha.25256.6) +* MSTest.Engine: [1.0.0-alpha.25256.6](https://www.nuget.org/packages/MSTest.Engine/1.0.0-alpha.25256.6) + ## [1.6.3] - 2025-03-17 See full log [here](https://github.com/microsoft/testfx/compare/v3.8.2...v3.8.3) diff --git a/docs/Changelog.md b/docs/Changelog.md index 24e4e4da1b..4e38beb338 100644 --- a/docs/Changelog.md +++ b/docs/Changelog.md @@ -4,6 +4,80 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) +## [3.9.0] - 2025-05-07 + +See full log [here](https://github.com/microsoft/testfx/compare/v3.8.3...v3.9.0) + +### Added + +* Allow async test methods for UITestMethod on UWP and WinUI by @Youssef1313 in [#5297](https://github.com/microsoft/testfx/pull/5297) +* Add analyzer for duplicate data row by @Youssef1313 in [#5144](https://github.com/microsoft/testfx/pull/5144) +* Add `Func` overloads for Assert.Throws[Exactly] by @Youssef1313 in [#5313](https://github.com/microsoft/testfx/pull/5313) +* Add TestRunCount to TestContext by @Youssef1313 in [#5425](https://github.com/microsoft/testfx/pull/5425) + +### Fixed + +* Fix ClassCleanup not called when the first test in class is ignored by @Youssef1313 in [#5070](https://github.com/microsoft/testfx/pull/5070) +* Write warnings outside of appdomain by @nohwnd in [#5371](https://github.com/microsoft/testfx/pull/5371) +* Fix MSTEST0038 message by @Youssef1313 in [#5008](https://github.com/microsoft/testfx/pull/5008) +* Fix parameterized test treated as ignored when using VSTest in Test Explorer by @Youssef1313 in [#5020](https://github.com/microsoft/testfx/pull/5020) +* Avoid handling tuples for test methods with only object[] parameter by @Youssef1313 in [#5013](https://github.com/microsoft/testfx/pull/5013) +* Follow-up to ignore fix by @Youssef1313 in [#5042](https://github.com/microsoft/testfx/pull/5042) +* Fix discard handling for newer Assert.Throws codefix by @Youssef1313 in [#5117](https://github.com/microsoft/testfx/pull/5117) +* Ship props/targets of MSTest.TestFramework and MSTest.TestAdapter in both build and buildTransitive by @Youssef1313 in [#5220](https://github.com/microsoft/testfx/pull/5220) +* Fix TestFailedException outcome not propagating to TestResult outcome by @Youssef1313 in [#5236](https://github.com/microsoft/testfx/pull/5236) +* Fix stackoverflow in Assert.DoesNotContain by @Youssef1313 in [#5275](https://github.com/microsoft/testfx/pull/5275) +* Fix typo in docs for StringAssert.That by @YoshiRulz in [#5281](https://github.com/microsoft/testfx/pull/5281) +* Fix TypeCache re-calculating info when running in parallel by @Youssef1313 in [#5291](https://github.com/microsoft/testfx/pull/5291) +* Fix test property not considering the test class correctly by @Youssef1313 in [#5293](https://github.com/microsoft/testfx/pull/5293) +* Fix typo in TestMethodAttribute documentation by @bjornhellander in [#5300](https://github.com/microsoft/testfx/pull/5300) +* Fix parameterized UI tests for WinUI by @Youssef1313 in [#5305](https://github.com/microsoft/testfx/pull/5305) +* Fix MSTEST0032 false positive with nullability analysis by @Youssef1313 in [#5315](https://github.com/microsoft/testfx/pull/5315) +* Move System.Threading.Tasks.Extensions to TestFramework by @Youssef1313 in [#5330](https://github.com/microsoft/testfx/pull/5330) +* remove redundant null check in WriteExceptionAsync by @SimonCropp in [#5393](https://github.com/microsoft/testfx/pull/5393) +* remove redundant null checks in DeploymentItemUtility by @SimonCropp in [#5399](https://github.com/microsoft/testfx/pull/5399) +* add disable CS0618 to MSTestSettingsTests by @SimonCropp in [#5389](https://github.com/microsoft/testfx/pull/5389) +* remove redundant catch by @SimonCropp in [#5376](https://github.com/microsoft/testfx/pull/5376) +* remove redundant ReflectHelper constructor by @SimonCropp in [#5379](https://github.com/microsoft/testfx/pull/5379) +* remove redundant braces and mark as error in rider and R# by @SimonCropp in [#5380](https://github.com/microsoft/testfx/pull/5380) +* avoid redundant where and mark as an error for rider and r# by @SimonCropp in [#5384](https://github.com/microsoft/testfx/pull/5384) +* Update MSTestSettingsTests.cs by @SimonCropp in [#5388](https://github.com/microsoft/testfx/pull/5388) +* remove redundant null checks in UnitTestRunnerTests by @SimonCropp in [#5390](https://github.com/microsoft/testfx/pull/5390) +* remove redundant null checks in AssemblyEnumeratorTests by @SimonCropp in [#5391](https://github.com/microsoft/testfx/pull/5391) +* remove redundant null check in UnitTestElement by @SimonCropp in [#5400](https://github.com/microsoft/testfx/pull/5400) +* fix nullability in TestableMSTestAdapterSettings by @SimonCropp in [#5387](https://github.com/microsoft/testfx/pull/5387) +* Downgrade error entries in .editorconfig to warning by @Youssef1313 in [#5416](https://github.com/microsoft/testfx/pull/5416) +* Conditional expression can be rewritten as null-coalescing and mark as warning by @SimonCropp in [#5429](https://github.com/microsoft/testfx/pull/5429) +* remove un-used IParameterInfo by @SimonCropp in [#5431](https://github.com/microsoft/testfx/pull/5431) +* remove Trimming, AOT, and SingleFile config from MSTest.SourceGeneration by @SimonCropp in [#5433](https://github.com/microsoft/testfx/pull/5433) +* Add test for TestContext.TestRunCount by @Youssef1313 in [#5440](https://github.com/microsoft/testfx/pull/5440) +* Add test for TestProperty attribute by @Youssef1313 in [#5439](https://github.com/microsoft/testfx/pull/5439) +* remove dead code from SourceGeneration by @SimonCropp in [#5446](https://github.com/microsoft/testfx/pull/5446) +* use-char-based-replace-in-string by @SimonCropp in [#5447](https://github.com/microsoft/testfx/pull/5447) +* remove un-used static class EquatableArray by @SimonCropp in [#5445](https://github.com/microsoft/testfx/pull/5445) +* Fix exception in assembly initialize shown as aggregate exception by @Youssef1313 in [#5498](https://github.com/microsoft/testfx/pull/5498) +* Skip analyzing TestContext fields that are generated via primary constructor parameters by @Youssef1313 in [#5501](https://github.com/microsoft/testfx/pull/5501) +* Fix MSTEST0017 (actual/expected order) false negative for conversions by @Youssef1313 in [#5502](https://github.com/microsoft/testfx/pull/5502) +* Avoid overwriting TestFailureException by @Youssef1313 in [#5505](https://github.com/microsoft/testfx/pull/5505) +* Add some unit tests for Assert.Contains/DoesNotContain by @Evangelink in [#5541](https://github.com/microsoft/testfx/pull/5541) +* Fix false positive of Assert.IsTrue(x == null) when x is a pointer type by @Youssef1313 in [#5548](https://github.com/microsoft/testfx/pull/5548) + +### Artifacts + +* MSTest: [3.9.0](https://www.nuget.org/packages/MSTest/3.9.0) +* MSTest.TestFramework: [3.9.0](https://www.nuget.org/packages/MSTest.TestFramework/3.9.0) +* MSTest.TestAdapter: [3.9.0](https://www.nuget.org/packages/MSTest.TestAdapter/3.9.0) +* MSTest.Analyzers: [3.9.0](https://www.nuget.org/packages/MSTest.Analyzers/3.9.0) +* MSTest.Sdk: [3.9.0](https://www.nuget.org/packages/MSTest.Sdk/3.9.0) +* Microsoft.Testing.Extensions.CrashDump: [1.7.0](https://www.nuget.org/packages/Microsoft.Testing.Extensions.CrashDump/1.7.0) +* Microsoft.Testing.Extensions.HangDump: [1.7.0](https://www.nuget.org/packages/Microsoft.Testing.Extensions.HangDump/1.7.0) +* Microsoft.Testing.Extensions.HotReload: [1.7.0](https://www.nuget.org/packages/Microsoft.Testing.Extensions.HotReload/1.7.0) +* Microsoft.Testing.Extensions.Retry: [1.7.0](https://www.nuget.org/packages/Microsoft.Testing.Extensions.Retry/1.7.0) +* Microsoft.Testing.Extensions.TrxReport: [1.7.0](https://www.nuget.org/packages/Microsoft.Testing.Extensions.TrxReport/1.7.0) +* Microsoft.Testing.Extensions.AzureDevOpsReport [1.0.0-alpha.25256.6](https://www.nuget.org/packages/Microsoft.Testing.Extensions.AzureDevOpsReport/1.0.0-alpha.25256.6) +* MSTest.SourceGeneration: [1.0.0-alpha.25256.6](https://www.nuget.org/packages/MSTest.SourceGeneration/1.0.0-alpha.25256.6) +* MSTest.Engine: [1.0.0-alpha.25256.6](https://www.nuget.org/packages/MSTest.Engine/1.0.0-alpha.25256.6) + ## [3.8.3] - 2025-03-17 See full log [here](https://github.com/microsoft/testfx/compare/v3.8.2...v3.8.3) From 1588fe73c51488062c0795a174879f2acae8cbd7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Jare=C5=A1?= Date: Mon, 12 May 2025 10:48:15 +0200 Subject: [PATCH 004/541] Add public api files (#5561) --- .../MSTest.Analyzers.CodeFixes.csproj | 5 + .../PublicAPI.Shipped.txt | 1 + .../PublicAPI.Unshipped.txt | 116 ++++++++++++++++++ .../MSTest.Analyzers.Package.csproj | 5 + .../PublicAPI.Shipped.txt | 1 + .../PublicAPI.Unshipped.txt | 1 + .../MSTest.GlobalConfigsGenerator.csproj | 5 + .../PublicAPI.Shipped.txt | 1 + .../PublicAPI.Unshipped.txt | 1 + .../MSTest.Internal.Analyzers.csproj | 5 + .../PublicAPI.Shipped.txt | 1 + .../PublicAPI.Unshipped.txt | 5 + .../MSTest.SourceGeneration.csproj | 2 + .../PublicAPI.Shipped.txt | 1 + .../PublicAPI.Unshipped.txt | 1 + ...icrosoft.Testing.Extensions.MSBuild.csproj | 5 + .../PublicAPI.Shipped.txt | 1 + .../PublicAPI.Unshipped.txt | 5 + .../Microsoft.Testing.Platform.MSBuild.csproj | 11 +- .../PublicAPI.Shipped.txt | 1 + .../PublicAPI.Unshipped.txt | 84 +++++++++++++ 21 files changed, 255 insertions(+), 3 deletions(-) create mode 100644 src/Analyzers/MSTest.Analyzers.CodeFixes/PublicAPI.Shipped.txt create mode 100644 src/Analyzers/MSTest.Analyzers.CodeFixes/PublicAPI.Unshipped.txt create mode 100644 src/Analyzers/MSTest.Analyzers.Package/PublicAPI.Shipped.txt create mode 100644 src/Analyzers/MSTest.Analyzers.Package/PublicAPI.Unshipped.txt create mode 100644 src/Analyzers/MSTest.GlobalConfigsGenerator/PublicAPI.Shipped.txt create mode 100644 src/Analyzers/MSTest.GlobalConfigsGenerator/PublicAPI.Unshipped.txt create mode 100644 src/Analyzers/MSTest.Internal.Analyzers/PublicAPI.Shipped.txt create mode 100644 src/Analyzers/MSTest.Internal.Analyzers/PublicAPI.Unshipped.txt create mode 100644 src/Analyzers/MSTest.SourceGeneration/PublicAPI.Shipped.txt create mode 100644 src/Analyzers/MSTest.SourceGeneration/PublicAPI.Unshipped.txt create mode 100644 src/Platform/Microsoft.Testing.Extensions.MSBuild/PublicAPI.Shipped.txt create mode 100644 src/Platform/Microsoft.Testing.Extensions.MSBuild/PublicAPI.Unshipped.txt create mode 100644 src/Platform/Microsoft.Testing.Platform.MSBuild/PublicAPI.Shipped.txt create mode 100644 src/Platform/Microsoft.Testing.Platform.MSBuild/PublicAPI.Unshipped.txt diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/MSTest.Analyzers.CodeFixes.csproj b/src/Analyzers/MSTest.Analyzers.CodeFixes/MSTest.Analyzers.CodeFixes.csproj index 90c2706c8f..42a1a88308 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/MSTest.Analyzers.CodeFixes.csproj +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/MSTest.Analyzers.CodeFixes.csproj @@ -6,6 +6,11 @@ MSTest.Analyzers + + + + + diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/PublicAPI.Shipped.txt b/src/Analyzers/MSTest.Analyzers.CodeFixes/PublicAPI.Shipped.txt new file mode 100644 index 0000000000..7dc5c58110 --- /dev/null +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/PublicAPI.Shipped.txt @@ -0,0 +1 @@ +#nullable enable diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/PublicAPI.Unshipped.txt b/src/Analyzers/MSTest.Analyzers.CodeFixes/PublicAPI.Unshipped.txt new file mode 100644 index 0000000000..712126dc7e --- /dev/null +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/PublicAPI.Unshipped.txt @@ -0,0 +1,116 @@ +#nullable enable +MSTest.Analyzers.AddTestClassFixer +MSTest.Analyzers.AddTestClassFixer.AddTestClassFixer() -> void +MSTest.Analyzers.AssemblyCleanupShouldBeValidFixer +MSTest.Analyzers.AssemblyCleanupShouldBeValidFixer.AssemblyCleanupShouldBeValidFixer() -> void +MSTest.Analyzers.AssemblyInitializeShouldBeValidFixer +MSTest.Analyzers.AssemblyInitializeShouldBeValidFixer.AssemblyInitializeShouldBeValidFixer() -> void +MSTest.Analyzers.AssertionArgsShouldAvoidConditionalAccessFixer +MSTest.Analyzers.AssertionArgsShouldAvoidConditionalAccessFixer.AssertionArgsShouldAvoidConditionalAccessFixer() -> void +MSTest.Analyzers.AssertionArgsShouldBePassedInCorrectOrderFixer +MSTest.Analyzers.AssertionArgsShouldBePassedInCorrectOrderFixer.AssertionArgsShouldBePassedInCorrectOrderFixer() -> void +MSTest.Analyzers.AvoidAssertAreSameWithValueTypesFixer +MSTest.Analyzers.AvoidAssertAreSameWithValueTypesFixer.AvoidAssertAreSameWithValueTypesFixer() -> void +MSTest.Analyzers.AvoidExpectedExceptionAttributeFixer +MSTest.Analyzers.AvoidExpectedExceptionAttributeFixer.AvoidExpectedExceptionAttributeFixer() -> void +MSTest.Analyzers.ClassCleanupShouldBeValidFixer +MSTest.Analyzers.ClassCleanupShouldBeValidFixer.ClassCleanupShouldBeValidFixer() -> void +MSTest.Analyzers.ClassInitializeShouldBeValidFixer +MSTest.Analyzers.ClassInitializeShouldBeValidFixer.ClassInitializeShouldBeValidFixer() -> void +MSTest.Analyzers.PreferAssertFailOverAlwaysFalseConditionsFixer +MSTest.Analyzers.PreferAssertFailOverAlwaysFalseConditionsFixer.PreferAssertFailOverAlwaysFalseConditionsFixer() -> void +MSTest.Analyzers.PreferConstructorOverTestInitializeFixer +MSTest.Analyzers.PreferConstructorOverTestInitializeFixer.PreferConstructorOverTestInitializeFixer() -> void +MSTest.Analyzers.PreferDisposeOverTestCleanupFixer +MSTest.Analyzers.PreferDisposeOverTestCleanupFixer.PreferDisposeOverTestCleanupFixer() -> void +MSTest.Analyzers.PreferTestCleanupOverDisposeFixer +MSTest.Analyzers.PreferTestCleanupOverDisposeFixer.PreferTestCleanupOverDisposeFixer() -> void +MSTest.Analyzers.PreferTestInitializeOverConstructorFixer +MSTest.Analyzers.PreferTestInitializeOverConstructorFixer.PreferTestInitializeOverConstructorFixer() -> void +MSTest.Analyzers.PublicMethodShouldBeTestMethodFixer +MSTest.Analyzers.PublicMethodShouldBeTestMethodFixer.PublicMethodShouldBeTestMethodFixer() -> void +MSTest.Analyzers.TestClassShouldBeValidFixer +MSTest.Analyzers.TestClassShouldBeValidFixer.TestClassShouldBeValidFixer() -> void +MSTest.Analyzers.TestCleanupShouldBeValidFixer +MSTest.Analyzers.TestCleanupShouldBeValidFixer.TestCleanupShouldBeValidFixer() -> void +MSTest.Analyzers.TestContextShouldBeValidFixer +MSTest.Analyzers.TestContextShouldBeValidFixer.TestContextShouldBeValidFixer() -> void +MSTest.Analyzers.TestInitializeShouldBeValidFixer +MSTest.Analyzers.TestInitializeShouldBeValidFixer.TestInitializeShouldBeValidFixer() -> void +MSTest.Analyzers.TestMethodShouldBeValidCodeFixProvider +MSTest.Analyzers.TestMethodShouldBeValidCodeFixProvider.TestMethodShouldBeValidCodeFixProvider() -> void +MSTest.Analyzers.UseAttributeOnTestMethodFixer +MSTest.Analyzers.UseAttributeOnTestMethodFixer.UseAttributeOnTestMethodFixer() -> void +MSTest.Analyzers.UseNewerAssertThrowsFixer +MSTest.Analyzers.UseNewerAssertThrowsFixer.UseNewerAssertThrowsFixer() -> void +MSTest.Analyzers.UseProperAssertMethodsFixer +MSTest.Analyzers.UseProperAssertMethodsFixer.UseProperAssertMethodsFixer() -> void +override MSTest.Analyzers.AddTestClassFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! +override MSTest.Analyzers.AddTestClassFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! +override MSTest.Analyzers.AssemblyCleanupShouldBeValidFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! +override MSTest.Analyzers.AssemblyCleanupShouldBeValidFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! +override MSTest.Analyzers.AssemblyInitializeShouldBeValidFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! +override MSTest.Analyzers.AssemblyInitializeShouldBeValidFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! +override MSTest.Analyzers.AssertionArgsShouldAvoidConditionalAccessFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! +override MSTest.Analyzers.AssertionArgsShouldAvoidConditionalAccessFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! +override MSTest.Analyzers.AssertionArgsShouldBePassedInCorrectOrderFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! +override MSTest.Analyzers.AssertionArgsShouldBePassedInCorrectOrderFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! +override MSTest.Analyzers.AvoidAssertAreSameWithValueTypesFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! +override MSTest.Analyzers.AvoidAssertAreSameWithValueTypesFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! +override MSTest.Analyzers.AvoidExpectedExceptionAttributeFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! +override MSTest.Analyzers.ClassCleanupShouldBeValidFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! +override MSTest.Analyzers.ClassCleanupShouldBeValidFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! +override MSTest.Analyzers.ClassInitializeShouldBeValidFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! +override MSTest.Analyzers.ClassInitializeShouldBeValidFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! +override MSTest.Analyzers.PreferAssertFailOverAlwaysFalseConditionsFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! +override MSTest.Analyzers.PreferAssertFailOverAlwaysFalseConditionsFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! +override MSTest.Analyzers.PreferConstructorOverTestInitializeFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray +override MSTest.Analyzers.PreferConstructorOverTestInitializeFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! +override MSTest.Analyzers.PreferConstructorOverTestInitializeFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! +override MSTest.Analyzers.PreferDisposeOverTestCleanupFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray +override MSTest.Analyzers.PreferDisposeOverTestCleanupFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! +override MSTest.Analyzers.PreferDisposeOverTestCleanupFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! +override MSTest.Analyzers.PreferTestCleanupOverDisposeFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray +override MSTest.Analyzers.PreferTestCleanupOverDisposeFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! +override MSTest.Analyzers.PreferTestCleanupOverDisposeFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! +override MSTest.Analyzers.PreferTestInitializeOverConstructorFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray +override MSTest.Analyzers.PreferTestInitializeOverConstructorFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! +override MSTest.Analyzers.PreferTestInitializeOverConstructorFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! +override MSTest.Analyzers.PublicMethodShouldBeTestMethodFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray +override MSTest.Analyzers.PublicMethodShouldBeTestMethodFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! +override MSTest.Analyzers.PublicMethodShouldBeTestMethodFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! +override MSTest.Analyzers.TestClassShouldBeValidFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! +override MSTest.Analyzers.TestClassShouldBeValidFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! +override MSTest.Analyzers.TestCleanupShouldBeValidFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! +override MSTest.Analyzers.TestCleanupShouldBeValidFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! +override MSTest.Analyzers.TestContextShouldBeValidFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! +override MSTest.Analyzers.TestContextShouldBeValidFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! +override MSTest.Analyzers.TestInitializeShouldBeValidFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! +override MSTest.Analyzers.TestInitializeShouldBeValidFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! +override MSTest.Analyzers.TestMethodShouldBeValidCodeFixProvider.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray +override MSTest.Analyzers.TestMethodShouldBeValidCodeFixProvider.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! +override MSTest.Analyzers.TestMethodShouldBeValidCodeFixProvider.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! +override MSTest.Analyzers.UseAttributeOnTestMethodFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! +override MSTest.Analyzers.UseNewerAssertThrowsFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! +override MSTest.Analyzers.UseNewerAssertThrowsFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! +override MSTest.Analyzers.UseProperAssertMethodsFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! +override MSTest.Analyzers.UseProperAssertMethodsFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! +override sealed MSTest.Analyzers.AddTestClassFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray +override sealed MSTest.Analyzers.AssemblyCleanupShouldBeValidFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray +override sealed MSTest.Analyzers.AssemblyInitializeShouldBeValidFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray +override sealed MSTest.Analyzers.AssertionArgsShouldAvoidConditionalAccessFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray +override sealed MSTest.Analyzers.AssertionArgsShouldBePassedInCorrectOrderFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray +override sealed MSTest.Analyzers.AvoidAssertAreSameWithValueTypesFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray +override sealed MSTest.Analyzers.AvoidExpectedExceptionAttributeFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray +override sealed MSTest.Analyzers.AvoidExpectedExceptionAttributeFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! +override sealed MSTest.Analyzers.ClassCleanupShouldBeValidFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray +override sealed MSTest.Analyzers.ClassInitializeShouldBeValidFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray +override sealed MSTest.Analyzers.PreferAssertFailOverAlwaysFalseConditionsFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray +override sealed MSTest.Analyzers.TestClassShouldBeValidFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray +override sealed MSTest.Analyzers.TestCleanupShouldBeValidFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray +override sealed MSTest.Analyzers.TestContextShouldBeValidFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray +override sealed MSTest.Analyzers.TestInitializeShouldBeValidFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray +override sealed MSTest.Analyzers.UseAttributeOnTestMethodFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray +override sealed MSTest.Analyzers.UseAttributeOnTestMethodFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! +override sealed MSTest.Analyzers.UseNewerAssertThrowsFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray +override sealed MSTest.Analyzers.UseProperAssertMethodsFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray diff --git a/src/Analyzers/MSTest.Analyzers.Package/MSTest.Analyzers.Package.csproj b/src/Analyzers/MSTest.Analyzers.Package/MSTest.Analyzers.Package.csproj index dbeb1dfb27..1cbbe6129d 100644 --- a/src/Analyzers/MSTest.Analyzers.Package/MSTest.Analyzers.Package.csproj +++ b/src/Analyzers/MSTest.Analyzers.Package/MSTest.Analyzers.Package.csproj @@ -21,6 +21,11 @@ $(TargetsForTfmSpecificContentInPackage);_AddAnalyzersToOutput + + + + + diff --git a/src/Analyzers/MSTest.Analyzers.Package/PublicAPI.Shipped.txt b/src/Analyzers/MSTest.Analyzers.Package/PublicAPI.Shipped.txt new file mode 100644 index 0000000000..7dc5c58110 --- /dev/null +++ b/src/Analyzers/MSTest.Analyzers.Package/PublicAPI.Shipped.txt @@ -0,0 +1 @@ +#nullable enable diff --git a/src/Analyzers/MSTest.Analyzers.Package/PublicAPI.Unshipped.txt b/src/Analyzers/MSTest.Analyzers.Package/PublicAPI.Unshipped.txt new file mode 100644 index 0000000000..7dc5c58110 --- /dev/null +++ b/src/Analyzers/MSTest.Analyzers.Package/PublicAPI.Unshipped.txt @@ -0,0 +1 @@ +#nullable enable diff --git a/src/Analyzers/MSTest.GlobalConfigsGenerator/MSTest.GlobalConfigsGenerator.csproj b/src/Analyzers/MSTest.GlobalConfigsGenerator/MSTest.GlobalConfigsGenerator.csproj index f224aa6f8a..9fad71fb91 100644 --- a/src/Analyzers/MSTest.GlobalConfigsGenerator/MSTest.GlobalConfigsGenerator.csproj +++ b/src/Analyzers/MSTest.GlobalConfigsGenerator/MSTest.GlobalConfigsGenerator.csproj @@ -7,6 +7,11 @@ false + + + + + diff --git a/src/Analyzers/MSTest.GlobalConfigsGenerator/PublicAPI.Shipped.txt b/src/Analyzers/MSTest.GlobalConfigsGenerator/PublicAPI.Shipped.txt new file mode 100644 index 0000000000..7dc5c58110 --- /dev/null +++ b/src/Analyzers/MSTest.GlobalConfigsGenerator/PublicAPI.Shipped.txt @@ -0,0 +1 @@ +#nullable enable diff --git a/src/Analyzers/MSTest.GlobalConfigsGenerator/PublicAPI.Unshipped.txt b/src/Analyzers/MSTest.GlobalConfigsGenerator/PublicAPI.Unshipped.txt new file mode 100644 index 0000000000..7dc5c58110 --- /dev/null +++ b/src/Analyzers/MSTest.GlobalConfigsGenerator/PublicAPI.Unshipped.txt @@ -0,0 +1 @@ +#nullable enable diff --git a/src/Analyzers/MSTest.Internal.Analyzers/MSTest.Internal.Analyzers.csproj b/src/Analyzers/MSTest.Internal.Analyzers/MSTest.Internal.Analyzers.csproj index d2e12ea51d..a06c6a49e7 100644 --- a/src/Analyzers/MSTest.Internal.Analyzers/MSTest.Internal.Analyzers.csproj +++ b/src/Analyzers/MSTest.Internal.Analyzers/MSTest.Internal.Analyzers.csproj @@ -10,6 +10,11 @@ *$(MSBuildProjectFile)* + + + + + diff --git a/src/Analyzers/MSTest.Internal.Analyzers/PublicAPI.Shipped.txt b/src/Analyzers/MSTest.Internal.Analyzers/PublicAPI.Shipped.txt new file mode 100644 index 0000000000..7dc5c58110 --- /dev/null +++ b/src/Analyzers/MSTest.Internal.Analyzers/PublicAPI.Shipped.txt @@ -0,0 +1 @@ +#nullable enable diff --git a/src/Analyzers/MSTest.Internal.Analyzers/PublicAPI.Unshipped.txt b/src/Analyzers/MSTest.Internal.Analyzers/PublicAPI.Unshipped.txt new file mode 100644 index 0000000000..8e80ba85b6 --- /dev/null +++ b/src/Analyzers/MSTest.Internal.Analyzers/PublicAPI.Unshipped.txt @@ -0,0 +1,5 @@ +#nullable enable +MSTest.Internal.Analyzers.MSTestObsoleteTypesSuppressor +MSTest.Internal.Analyzers.MSTestObsoleteTypesSuppressor.MSTestObsoleteTypesSuppressor() -> void +override MSTest.Internal.Analyzers.MSTestObsoleteTypesSuppressor.ReportSuppressions(Microsoft.CodeAnalysis.Diagnostics.SuppressionAnalysisContext context) -> void +override MSTest.Internal.Analyzers.MSTestObsoleteTypesSuppressor.SupportedSuppressions.get -> System.Collections.Immutable.ImmutableArray diff --git a/src/Analyzers/MSTest.SourceGeneration/MSTest.SourceGeneration.csproj b/src/Analyzers/MSTest.SourceGeneration/MSTest.SourceGeneration.csproj index af7c69027c..bd8d24cc2d 100644 --- a/src/Analyzers/MSTest.SourceGeneration/MSTest.SourceGeneration.csproj +++ b/src/Analyzers/MSTest.SourceGeneration/MSTest.SourceGeneration.csproj @@ -33,6 +33,8 @@ This package provides the C# source generators for MSTest test framework.]]> + + diff --git a/src/Analyzers/MSTest.SourceGeneration/PublicAPI.Shipped.txt b/src/Analyzers/MSTest.SourceGeneration/PublicAPI.Shipped.txt new file mode 100644 index 0000000000..7dc5c58110 --- /dev/null +++ b/src/Analyzers/MSTest.SourceGeneration/PublicAPI.Shipped.txt @@ -0,0 +1 @@ +#nullable enable diff --git a/src/Analyzers/MSTest.SourceGeneration/PublicAPI.Unshipped.txt b/src/Analyzers/MSTest.SourceGeneration/PublicAPI.Unshipped.txt new file mode 100644 index 0000000000..7dc5c58110 --- /dev/null +++ b/src/Analyzers/MSTest.SourceGeneration/PublicAPI.Unshipped.txt @@ -0,0 +1 @@ +#nullable enable diff --git a/src/Platform/Microsoft.Testing.Extensions.MSBuild/Microsoft.Testing.Extensions.MSBuild.csproj b/src/Platform/Microsoft.Testing.Extensions.MSBuild/Microsoft.Testing.Extensions.MSBuild.csproj index ba0721a0bd..b830523061 100644 --- a/src/Platform/Microsoft.Testing.Extensions.MSBuild/Microsoft.Testing.Extensions.MSBuild.csproj +++ b/src/Platform/Microsoft.Testing.Extensions.MSBuild/Microsoft.Testing.Extensions.MSBuild.csproj @@ -6,6 +6,11 @@ false + + + + + diff --git a/src/Platform/Microsoft.Testing.Extensions.MSBuild/PublicAPI.Shipped.txt b/src/Platform/Microsoft.Testing.Extensions.MSBuild/PublicAPI.Shipped.txt new file mode 100644 index 0000000000..7dc5c58110 --- /dev/null +++ b/src/Platform/Microsoft.Testing.Extensions.MSBuild/PublicAPI.Shipped.txt @@ -0,0 +1 @@ +#nullable enable diff --git a/src/Platform/Microsoft.Testing.Extensions.MSBuild/PublicAPI.Unshipped.txt b/src/Platform/Microsoft.Testing.Extensions.MSBuild/PublicAPI.Unshipped.txt new file mode 100644 index 0000000000..a82cec2234 --- /dev/null +++ b/src/Platform/Microsoft.Testing.Extensions.MSBuild/PublicAPI.Unshipped.txt @@ -0,0 +1,5 @@ +#nullable enable +Microsoft.Testing.Platform.MSBuild.MSBuildExtensions +Microsoft.Testing.Platform.MSBuild.TestingPlatformBuilderHook +static Microsoft.Testing.Platform.MSBuild.MSBuildExtensions.AddMSBuild(this Microsoft.Testing.Platform.Builder.ITestApplicationBuilder! builder) -> void +static Microsoft.Testing.Platform.MSBuild.TestingPlatformBuilderHook.AddExtensions(Microsoft.Testing.Platform.Builder.ITestApplicationBuilder! testApplicationBuilder, string![]! _) -> void diff --git a/src/Platform/Microsoft.Testing.Platform.MSBuild/Microsoft.Testing.Platform.MSBuild.csproj b/src/Platform/Microsoft.Testing.Platform.MSBuild/Microsoft.Testing.Platform.MSBuild.csproj index 3d9603f9a6..807811070c 100644 --- a/src/Platform/Microsoft.Testing.Platform.MSBuild/Microsoft.Testing.Platform.MSBuild.csproj +++ b/src/Platform/Microsoft.Testing.Platform.MSBuild/Microsoft.Testing.Platform.MSBuild.csproj @@ -45,12 +45,17 @@ This package provides MSBuild integration of the platform, its extensions and co - - - + + + + + + + + diff --git a/src/Platform/Microsoft.Testing.Platform.MSBuild/PublicAPI.Shipped.txt b/src/Platform/Microsoft.Testing.Platform.MSBuild/PublicAPI.Shipped.txt new file mode 100644 index 0000000000..7dc5c58110 --- /dev/null +++ b/src/Platform/Microsoft.Testing.Platform.MSBuild/PublicAPI.Shipped.txt @@ -0,0 +1 @@ +#nullable enable diff --git a/src/Platform/Microsoft.Testing.Platform.MSBuild/PublicAPI.Unshipped.txt b/src/Platform/Microsoft.Testing.Platform.MSBuild/PublicAPI.Unshipped.txt new file mode 100644 index 0000000000..7276566dda --- /dev/null +++ b/src/Platform/Microsoft.Testing.Platform.MSBuild/PublicAPI.Unshipped.txt @@ -0,0 +1,84 @@ +#nullable enable +Microsoft.Testing.Platform.MSBuild.ConfigurationFileTask +Microsoft.Testing.Platform.MSBuild.ConfigurationFileTask.AssemblyName.get -> Microsoft.Build.Framework.ITaskItem! +Microsoft.Testing.Platform.MSBuild.ConfigurationFileTask.AssemblyName.set -> void +Microsoft.Testing.Platform.MSBuild.ConfigurationFileTask.ConfigurationFileTask() -> void +Microsoft.Testing.Platform.MSBuild.ConfigurationFileTask.FinalTestingPlatformConfigurationFile.get -> Microsoft.Build.Framework.ITaskItem! +Microsoft.Testing.Platform.MSBuild.ConfigurationFileTask.FinalTestingPlatformConfigurationFile.set -> void +Microsoft.Testing.Platform.MSBuild.ConfigurationFileTask.MSBuildProjectDirectory.get -> Microsoft.Build.Framework.ITaskItem! +Microsoft.Testing.Platform.MSBuild.ConfigurationFileTask.MSBuildProjectDirectory.set -> void +Microsoft.Testing.Platform.MSBuild.ConfigurationFileTask.OutputPath.get -> Microsoft.Build.Framework.ITaskItem! +Microsoft.Testing.Platform.MSBuild.ConfigurationFileTask.OutputPath.set -> void +Microsoft.Testing.Platform.MSBuild.ConfigurationFileTask.TestingPlatformConfigurationFileSource.get -> Microsoft.Build.Framework.ITaskItem! +Microsoft.Testing.Platform.MSBuild.ConfigurationFileTask.TestingPlatformConfigurationFileSource.set -> void +Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask +Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.AssemblyName.get -> Microsoft.Build.Framework.ITaskItem? +Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.AssemblyName.set -> void +Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.Dispose() -> void +Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.DotnetHostPath.get -> Microsoft.Build.Framework.ITaskItem? +Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.DotnetHostPath.set -> void +Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.InvokeTestingPlatformTask() -> void +Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.IsExecutable.get -> Microsoft.Build.Framework.ITaskItem? +Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.IsExecutable.set -> void +Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.NativeExecutableExtension.get -> Microsoft.Build.Framework.ITaskItem? +Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.NativeExecutableExtension.set -> void +Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.ProjectFullPath.get -> Microsoft.Build.Framework.ITaskItem! +Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.ProjectFullPath.set -> void +Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.TargetDir.get -> Microsoft.Build.Framework.ITaskItem? +Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.TargetDir.set -> void +Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.TargetFramework.get -> Microsoft.Build.Framework.ITaskItem! +Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.TargetFramework.set -> void +Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.TargetFrameworkIdentifier.get -> Microsoft.Build.Framework.ITaskItem! +Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.TargetFrameworkIdentifier.set -> void +Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.TargetPath.get -> Microsoft.Build.Framework.ITaskItem! +Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.TargetPath.set -> void +Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.TestArchitecture.get -> Microsoft.Build.Framework.ITaskItem! +Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.TestArchitecture.set -> void +Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.TestingPlatformCaptureOutput.get -> Microsoft.Build.Framework.ITaskItem! +Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.TestingPlatformCaptureOutput.set -> void +Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.TestingPlatformCommandLineArguments.get -> Microsoft.Build.Framework.ITaskItem? +Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.TestingPlatformCommandLineArguments.set -> void +Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.TestingPlatformShowTestsFailure.get -> Microsoft.Build.Framework.ITaskItem! +Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.TestingPlatformShowTestsFailure.set -> void +Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.UseAppHost.get -> Microsoft.Build.Framework.ITaskItem? +Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.UseAppHost.set -> void +Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.VSTestCLIRunSettings.get -> Microsoft.Build.Framework.ITaskItem![]? +Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.VSTestCLIRunSettings.set -> void +Microsoft.Testing.Platform.MSBuild.TestingPlatformEntryPointTask +Microsoft.Testing.Platform.MSBuild.TestingPlatformEntryPointTask.Language.get -> Microsoft.Build.Framework.ITaskItem! +Microsoft.Testing.Platform.MSBuild.TestingPlatformEntryPointTask.Language.set -> void +Microsoft.Testing.Platform.MSBuild.TestingPlatformEntryPointTask.RootNamespace.get -> string? +Microsoft.Testing.Platform.MSBuild.TestingPlatformEntryPointTask.RootNamespace.set -> void +Microsoft.Testing.Platform.MSBuild.TestingPlatformEntryPointTask.TestingPlatformEntryPointGeneratedFilePath.get -> Microsoft.Build.Framework.ITaskItem! +Microsoft.Testing.Platform.MSBuild.TestingPlatformEntryPointTask.TestingPlatformEntryPointGeneratedFilePath.set -> void +Microsoft.Testing.Platform.MSBuild.TestingPlatformEntryPointTask.TestingPlatformEntryPointSourcePath.get -> Microsoft.Build.Framework.ITaskItem! +Microsoft.Testing.Platform.MSBuild.TestingPlatformEntryPointTask.TestingPlatformEntryPointSourcePath.set -> void +Microsoft.Testing.Platform.MSBuild.TestingPlatformEntryPointTask.TestingPlatformEntryPointTask() -> void +Microsoft.Testing.Platform.MSBuild.TestingPlatformSelfRegisteredExtensions +Microsoft.Testing.Platform.MSBuild.TestingPlatformSelfRegisteredExtensions.Language.get -> Microsoft.Build.Framework.ITaskItem! +Microsoft.Testing.Platform.MSBuild.TestingPlatformSelfRegisteredExtensions.Language.set -> void +Microsoft.Testing.Platform.MSBuild.TestingPlatformSelfRegisteredExtensions.RootNamespace.get -> string? +Microsoft.Testing.Platform.MSBuild.TestingPlatformSelfRegisteredExtensions.RootNamespace.set -> void +Microsoft.Testing.Platform.MSBuild.TestingPlatformSelfRegisteredExtensions.SelfRegisteredExtensionsBuilderHook.get -> Microsoft.Build.Framework.ITaskItem![]! +Microsoft.Testing.Platform.MSBuild.TestingPlatformSelfRegisteredExtensions.SelfRegisteredExtensionsBuilderHook.set -> void +Microsoft.Testing.Platform.MSBuild.TestingPlatformSelfRegisteredExtensions.SelfRegisteredExtensionsGeneratedFilePath.get -> Microsoft.Build.Framework.ITaskItem! +Microsoft.Testing.Platform.MSBuild.TestingPlatformSelfRegisteredExtensions.SelfRegisteredExtensionsGeneratedFilePath.set -> void +Microsoft.Testing.Platform.MSBuild.TestingPlatformSelfRegisteredExtensions.SelfRegisteredExtensionsSourcePath.get -> Microsoft.Build.Framework.ITaskItem! +Microsoft.Testing.Platform.MSBuild.TestingPlatformSelfRegisteredExtensions.SelfRegisteredExtensionsSourcePath.set -> void +Microsoft.Testing.Platform.MSBuild.TestingPlatformSelfRegisteredExtensions.TestingPlatformSelfRegisteredExtensions() -> void +override Microsoft.Testing.Platform.MSBuild.ConfigurationFileTask.Execute() -> bool +override Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.Execute() -> bool +override Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.GenerateCommandLineCommands() -> string! +override Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.GenerateFullPathToTool() -> string? +override Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.HandleTaskExecutionErrors() -> bool +override Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.LogEventsFromTextOutput(string! singleLine, Microsoft.Build.Framework.MessageImportance messageImportance) -> void +override Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.LogToolCommand(string! message) -> void +override Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.ProcessStarted() -> void +override Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.StandardErrorLoggingImportance.get -> Microsoft.Build.Framework.MessageImportance +override Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.StandardOutputLoggingImportance.get -> Microsoft.Build.Framework.MessageImportance +override Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.ToolExe.get -> string! +override Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.ToolExe.set -> void +override Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.ToolName.get -> string! +override Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.ValidateParameters() -> bool +override Microsoft.Testing.Platform.MSBuild.TestingPlatformEntryPointTask.Execute() -> bool +override Microsoft.Testing.Platform.MSBuild.TestingPlatformSelfRegisteredExtensions.Execute() -> bool From 9a016c071b017918233cbf99e1d21144fb9ce5f3 Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Mon, 12 May 2025 19:30:39 +1000 Subject: [PATCH 005/541] remove redundant Empty constructor and mark as warning (#5378) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Jakub Jareš --- .editorconfig | 3 +++ samples/Playground/Program.cs | 2 +- .../Serializers/ExitSignalActivityIndicatorTaskRequest.cs | 2 +- .../Serializers/GetInProgressTestsRequest.cs | 2 +- .../Serializers/SessionEndSerializer.cs | 2 +- .../ServerMode/JsonRpc/RpcMessages.cs | 2 +- 6 files changed, 8 insertions(+), 5 deletions(-) diff --git a/.editorconfig b/.editorconfig index 3513ec6283..430647d9df 100644 --- a/.editorconfig +++ b/.editorconfig @@ -683,6 +683,9 @@ csharp_style_unused_value_expression_statement_preference = discard_variable:sil # IDE0290: Use primary constructor csharp_style_prefer_primary_constructors = false +# Empty constructor +resharper_empty_constructor_highlighting = warning + # Redundant empty argument list on object creation expression resharper_redundant_empty_object_creation_argument_list_highlighting = warning diff --git a/samples/Playground/Program.cs b/samples/Playground/Program.cs index 4a3d04350a..205088910d 100644 --- a/samples/Playground/Program.cs +++ b/samples/Playground/Program.cs @@ -76,7 +76,7 @@ public static async Task Main(string[] args) } } -internal sealed class DummyAdapter() : ITestFramework, IDataProducer +internal sealed class DummyAdapter : ITestFramework, IDataProducer { public string Uid => nameof(DummyAdapter); diff --git a/src/Platform/Microsoft.Testing.Extensions.HangDump/Serializers/ExitSignalActivityIndicatorTaskRequest.cs b/src/Platform/Microsoft.Testing.Extensions.HangDump/Serializers/ExitSignalActivityIndicatorTaskRequest.cs index a1f76cf3b9..72ab5a9bd0 100644 --- a/src/Platform/Microsoft.Testing.Extensions.HangDump/Serializers/ExitSignalActivityIndicatorTaskRequest.cs +++ b/src/Platform/Microsoft.Testing.Extensions.HangDump/Serializers/ExitSignalActivityIndicatorTaskRequest.cs @@ -6,7 +6,7 @@ namespace Microsoft.Testing.Extensions.HangDump.Serializers; -internal sealed class ExitSignalActivityIndicatorTaskRequest() : IRequest; +internal sealed class ExitSignalActivityIndicatorTaskRequest : IRequest; internal sealed class ExitSignalActivityIndicatorTaskRequestSerializer : BaseSerializer, INamedPipeSerializer { diff --git a/src/Platform/Microsoft.Testing.Extensions.HangDump/Serializers/GetInProgressTestsRequest.cs b/src/Platform/Microsoft.Testing.Extensions.HangDump/Serializers/GetInProgressTestsRequest.cs index 2a68a98905..05cbf08b45 100644 --- a/src/Platform/Microsoft.Testing.Extensions.HangDump/Serializers/GetInProgressTestsRequest.cs +++ b/src/Platform/Microsoft.Testing.Extensions.HangDump/Serializers/GetInProgressTestsRequest.cs @@ -6,7 +6,7 @@ namespace Microsoft.Testing.Extensions.HangDump.Serializers; -internal sealed class GetInProgressTestsRequest() : IRequest; +internal sealed class GetInProgressTestsRequest : IRequest; internal sealed class GetInProgressTestsRequestSerializer : BaseSerializer, INamedPipeSerializer { diff --git a/src/Platform/Microsoft.Testing.Extensions.HangDump/Serializers/SessionEndSerializer.cs b/src/Platform/Microsoft.Testing.Extensions.HangDump/Serializers/SessionEndSerializer.cs index 23cd132c19..8e547f6974 100644 --- a/src/Platform/Microsoft.Testing.Extensions.HangDump/Serializers/SessionEndSerializer.cs +++ b/src/Platform/Microsoft.Testing.Extensions.HangDump/Serializers/SessionEndSerializer.cs @@ -6,7 +6,7 @@ namespace Microsoft.Testing.Extensions.HangDump.Serializers; -internal sealed class SessionEndSerializerRequest() : IRequest; +internal sealed class SessionEndSerializerRequest : IRequest; internal sealed class SessionEndSerializerRequestSerializer : BaseSerializer, INamedPipeSerializer { diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/RpcMessages.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/RpcMessages.cs index 941f900ed7..ae0efe1c4d 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/RpcMessages.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/RpcMessages.cs @@ -6,7 +6,7 @@ namespace Microsoft.Testing.Platform.ServerMode; -internal abstract record RpcMessage(); +internal abstract record RpcMessage; /// /// A request is a message for which the server should return a corresponding From 4c22fc1a877ca02faf2ea8ba82efb48d65fe47ce Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Jare=C5=A1?= Date: Mon, 12 May 2025 21:37:15 +0200 Subject: [PATCH 006/541] Shipped api 3.9 (#5578) --- .../PublicAPI/PublicAPI.Shipped.txt | 1 + .../PublicAPI/PublicAPI.Unshipped.txt | 1 - .../PublicAPI/uwp/PublicAPI.Shipped.txt | 1 + .../PublicAPI/uwp/PublicAPI.Unshipped.txt | 1 - .../PublicAPI/PublicAPI.Shipped.txt | 4 +- .../PublicAPI/PublicAPI.Unshipped.txt | 4 - .../PublicAPI.Shipped.txt | 115 ++++++++++++++++++ .../PublicAPI.Unshipped.txt | 115 ------------------ .../MSTest.Analyzers/PublicAPI.Shipped.txt | 8 ++ .../MSTest.Analyzers/PublicAPI.Unshipped.txt | 8 -- .../PublicAPI.Shipped.txt | 4 + .../PublicAPI.Unshipped.txt | 4 - .../PublicAPI/PublicAPI.Shipped.txt | 4 + .../PublicAPI/PublicAPI.Unshipped.txt | 4 - .../PublicAPI.Shipped.txt | 4 + .../PublicAPI.Unshipped.txt | 4 - .../PublicAPI.Shipped.txt | 83 +++++++++++++ .../PublicAPI.Unshipped.txt | 83 ------------- .../PublicAPI/PublicAPI.Shipped.txt | 23 ++++ .../PublicAPI/PublicAPI.Unshipped.txt | 23 ---- .../PublicAPI/PublicAPI.Shipped.txt | 1 + .../PublicAPI/PublicAPI.Unshipped.txt | 1 - .../PublicAPI/PublicAPI.Shipped.txt | 10 ++ .../PublicAPI/PublicAPI.Unshipped.txt | 10 -- 24 files changed, 256 insertions(+), 260 deletions(-) diff --git a/src/Adapter/MSTest.TestAdapter/PublicAPI/PublicAPI.Shipped.txt b/src/Adapter/MSTest.TestAdapter/PublicAPI/PublicAPI.Shipped.txt index 1a24faebf6..88c46e7489 100644 --- a/src/Adapter/MSTest.TestAdapter/PublicAPI/PublicAPI.Shipped.txt +++ b/src/Adapter/MSTest.TestAdapter/PublicAPI/PublicAPI.Shipped.txt @@ -150,3 +150,4 @@ static Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.RunConfigurationSe static Microsoft.VisualStudio.TestTools.UnitTesting.TestApplicationBuilderExtensions.AddMSTest(this Microsoft.Testing.Platform.Builder.ITestApplicationBuilder! testApplicationBuilder, System.Func!>! getTestAssemblies) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.TestingPlatformBuilderHook.AddExtensions(Microsoft.Testing.Platform.Builder.ITestApplicationBuilder! testApplicationBuilder, string![]! arguments) -> void virtual Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestMethodInfo.Invoke(object?[]? arguments) -> Microsoft.VisualStudio.TestTools.UnitTesting.TestResult! +virtual Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestMethodInfo.InvokeAsync(object?[]? arguments) -> System.Threading.Tasks.Task! diff --git a/src/Adapter/MSTest.TestAdapter/PublicAPI/PublicAPI.Unshipped.txt b/src/Adapter/MSTest.TestAdapter/PublicAPI/PublicAPI.Unshipped.txt index 22b19265a6..7dc5c58110 100644 --- a/src/Adapter/MSTest.TestAdapter/PublicAPI/PublicAPI.Unshipped.txt +++ b/src/Adapter/MSTest.TestAdapter/PublicAPI/PublicAPI.Unshipped.txt @@ -1,2 +1 @@ #nullable enable -virtual Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestMethodInfo.InvokeAsync(object?[]? arguments) -> System.Threading.Tasks.Task! diff --git a/src/Adapter/MSTest.TestAdapter/PublicAPI/uwp/PublicAPI.Shipped.txt b/src/Adapter/MSTest.TestAdapter/PublicAPI/uwp/PublicAPI.Shipped.txt index 100104fa6b..bb20af004b 100644 --- a/src/Adapter/MSTest.TestAdapter/PublicAPI/uwp/PublicAPI.Shipped.txt +++ b/src/Adapter/MSTest.TestAdapter/PublicAPI/uwp/PublicAPI.Shipped.txt @@ -146,3 +146,4 @@ static Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.MSTestSettings.Pop static Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.MSTestSettings.RunConfigurationSettings.get -> Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.RunConfigurationSettings! static Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.RunConfigurationSettings.PopulateSettings(Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter.IDiscoveryContext? context) -> Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.RunConfigurationSettings! virtual Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestMethodInfo.Invoke(object?[]? arguments) -> Microsoft.VisualStudio.TestTools.UnitTesting.TestResult! +virtual Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestMethodInfo.InvokeAsync(object?[]? arguments) -> System.Threading.Tasks.Task! diff --git a/src/Adapter/MSTest.TestAdapter/PublicAPI/uwp/PublicAPI.Unshipped.txt b/src/Adapter/MSTest.TestAdapter/PublicAPI/uwp/PublicAPI.Unshipped.txt index 22b19265a6..7dc5c58110 100644 --- a/src/Adapter/MSTest.TestAdapter/PublicAPI/uwp/PublicAPI.Unshipped.txt +++ b/src/Adapter/MSTest.TestAdapter/PublicAPI/uwp/PublicAPI.Unshipped.txt @@ -1,2 +1 @@ #nullable enable -virtual Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestMethodInfo.InvokeAsync(object?[]? arguments) -> System.Threading.Tasks.Task! diff --git a/src/Adapter/MSTestAdapter.PlatformServices/PublicAPI/PublicAPI.Shipped.txt b/src/Adapter/MSTestAdapter.PlatformServices/PublicAPI/PublicAPI.Shipped.txt index 6a36504523..f7f5bbea05 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/PublicAPI/PublicAPI.Shipped.txt +++ b/src/Adapter/MSTestAdapter.PlatformServices/PublicAPI/PublicAPI.Shipped.txt @@ -11,7 +11,7 @@ Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.FileOperation Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.FileOperations.FileOperations() -> void Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.FileOperations.GetAssemblyPath(System.Reflection.Assembly! assembly) -> string? Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.FileOperations.GetFullFilePath(string! assemblyFileName) -> string! -Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.FileOperations.GetNavigationData(object! navigationSession, string! className, string! methodName, out int minLineNumber, out string? fileName) -> void +Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.FileOperations.GetNavigationData(object? navigationSession, string! className, string! methodName, out int minLineNumber, out string? fileName) -> void Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.FileOperations.LoadAssembly(string! assemblyName, bool isReflectionOnly) -> System.Reflection.Assembly! Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Interface.IAdapterTraceLogger Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Interface.IAdapterTraceLogger.LogError(string! format, params object?[]! args) -> void @@ -81,7 +81,7 @@ Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Interface.Obj Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Interface.ObjectModel.ITestMethod.Name.get -> string! Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Interface.ObjectModel.ITestMethod.TestIdGenerationStrategy.get -> Microsoft.VisualStudio.TestTools.UnitTesting.TestIdGenerationStrategy Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.MSTestSettingsProvider -Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.MSTestSettingsProvider.GetProperties(string! source) -> System.Collections.Generic.IDictionary! +Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.MSTestSettingsProvider.GetProperties(string? source) -> System.Collections.Generic.IDictionary! Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.MSTestSettingsProvider.Load(System.Xml.XmlReader! reader) -> void Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.MSTestSettingsProvider.MSTestSettingsProvider() -> void Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.ReflectionOperations diff --git a/src/Adapter/MSTestAdapter.PlatformServices/PublicAPI/PublicAPI.Unshipped.txt b/src/Adapter/MSTestAdapter.PlatformServices/PublicAPI/PublicAPI.Unshipped.txt index 6a828f7e91..7dc5c58110 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/PublicAPI/PublicAPI.Unshipped.txt +++ b/src/Adapter/MSTestAdapter.PlatformServices/PublicAPI/PublicAPI.Unshipped.txt @@ -1,5 +1 @@ #nullable enable -*REMOVED*Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.FileOperations.GetNavigationData(object! navigationSession, string! className, string! methodName, out int minLineNumber, out string? fileName) -> void -Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.FileOperations.GetNavigationData(object? navigationSession, string! className, string! methodName, out int minLineNumber, out string? fileName) -> void -*REMOVED*Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.MSTestSettingsProvider.GetProperties(string! source) -> System.Collections.Generic.IDictionary! -Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.MSTestSettingsProvider.GetProperties(string? source) -> System.Collections.Generic.IDictionary! diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/PublicAPI.Shipped.txt b/src/Analyzers/MSTest.Analyzers.CodeFixes/PublicAPI.Shipped.txt index 7dc5c58110..712126dc7e 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/PublicAPI.Shipped.txt +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/PublicAPI.Shipped.txt @@ -1 +1,116 @@ #nullable enable +MSTest.Analyzers.AddTestClassFixer +MSTest.Analyzers.AddTestClassFixer.AddTestClassFixer() -> void +MSTest.Analyzers.AssemblyCleanupShouldBeValidFixer +MSTest.Analyzers.AssemblyCleanupShouldBeValidFixer.AssemblyCleanupShouldBeValidFixer() -> void +MSTest.Analyzers.AssemblyInitializeShouldBeValidFixer +MSTest.Analyzers.AssemblyInitializeShouldBeValidFixer.AssemblyInitializeShouldBeValidFixer() -> void +MSTest.Analyzers.AssertionArgsShouldAvoidConditionalAccessFixer +MSTest.Analyzers.AssertionArgsShouldAvoidConditionalAccessFixer.AssertionArgsShouldAvoidConditionalAccessFixer() -> void +MSTest.Analyzers.AssertionArgsShouldBePassedInCorrectOrderFixer +MSTest.Analyzers.AssertionArgsShouldBePassedInCorrectOrderFixer.AssertionArgsShouldBePassedInCorrectOrderFixer() -> void +MSTest.Analyzers.AvoidAssertAreSameWithValueTypesFixer +MSTest.Analyzers.AvoidAssertAreSameWithValueTypesFixer.AvoidAssertAreSameWithValueTypesFixer() -> void +MSTest.Analyzers.AvoidExpectedExceptionAttributeFixer +MSTest.Analyzers.AvoidExpectedExceptionAttributeFixer.AvoidExpectedExceptionAttributeFixer() -> void +MSTest.Analyzers.ClassCleanupShouldBeValidFixer +MSTest.Analyzers.ClassCleanupShouldBeValidFixer.ClassCleanupShouldBeValidFixer() -> void +MSTest.Analyzers.ClassInitializeShouldBeValidFixer +MSTest.Analyzers.ClassInitializeShouldBeValidFixer.ClassInitializeShouldBeValidFixer() -> void +MSTest.Analyzers.PreferAssertFailOverAlwaysFalseConditionsFixer +MSTest.Analyzers.PreferAssertFailOverAlwaysFalseConditionsFixer.PreferAssertFailOverAlwaysFalseConditionsFixer() -> void +MSTest.Analyzers.PreferConstructorOverTestInitializeFixer +MSTest.Analyzers.PreferConstructorOverTestInitializeFixer.PreferConstructorOverTestInitializeFixer() -> void +MSTest.Analyzers.PreferDisposeOverTestCleanupFixer +MSTest.Analyzers.PreferDisposeOverTestCleanupFixer.PreferDisposeOverTestCleanupFixer() -> void +MSTest.Analyzers.PreferTestCleanupOverDisposeFixer +MSTest.Analyzers.PreferTestCleanupOverDisposeFixer.PreferTestCleanupOverDisposeFixer() -> void +MSTest.Analyzers.PreferTestInitializeOverConstructorFixer +MSTest.Analyzers.PreferTestInitializeOverConstructorFixer.PreferTestInitializeOverConstructorFixer() -> void +MSTest.Analyzers.PublicMethodShouldBeTestMethodFixer +MSTest.Analyzers.PublicMethodShouldBeTestMethodFixer.PublicMethodShouldBeTestMethodFixer() -> void +MSTest.Analyzers.TestClassShouldBeValidFixer +MSTest.Analyzers.TestClassShouldBeValidFixer.TestClassShouldBeValidFixer() -> void +MSTest.Analyzers.TestCleanupShouldBeValidFixer +MSTest.Analyzers.TestCleanupShouldBeValidFixer.TestCleanupShouldBeValidFixer() -> void +MSTest.Analyzers.TestContextShouldBeValidFixer +MSTest.Analyzers.TestContextShouldBeValidFixer.TestContextShouldBeValidFixer() -> void +MSTest.Analyzers.TestInitializeShouldBeValidFixer +MSTest.Analyzers.TestInitializeShouldBeValidFixer.TestInitializeShouldBeValidFixer() -> void +MSTest.Analyzers.TestMethodShouldBeValidCodeFixProvider +MSTest.Analyzers.TestMethodShouldBeValidCodeFixProvider.TestMethodShouldBeValidCodeFixProvider() -> void +MSTest.Analyzers.UseAttributeOnTestMethodFixer +MSTest.Analyzers.UseAttributeOnTestMethodFixer.UseAttributeOnTestMethodFixer() -> void +MSTest.Analyzers.UseNewerAssertThrowsFixer +MSTest.Analyzers.UseNewerAssertThrowsFixer.UseNewerAssertThrowsFixer() -> void +MSTest.Analyzers.UseProperAssertMethodsFixer +MSTest.Analyzers.UseProperAssertMethodsFixer.UseProperAssertMethodsFixer() -> void +override MSTest.Analyzers.AddTestClassFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! +override MSTest.Analyzers.AddTestClassFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! +override MSTest.Analyzers.AssemblyCleanupShouldBeValidFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! +override MSTest.Analyzers.AssemblyCleanupShouldBeValidFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! +override MSTest.Analyzers.AssemblyInitializeShouldBeValidFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! +override MSTest.Analyzers.AssemblyInitializeShouldBeValidFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! +override MSTest.Analyzers.AssertionArgsShouldAvoidConditionalAccessFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! +override MSTest.Analyzers.AssertionArgsShouldAvoidConditionalAccessFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! +override MSTest.Analyzers.AssertionArgsShouldBePassedInCorrectOrderFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! +override MSTest.Analyzers.AssertionArgsShouldBePassedInCorrectOrderFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! +override MSTest.Analyzers.AvoidAssertAreSameWithValueTypesFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! +override MSTest.Analyzers.AvoidAssertAreSameWithValueTypesFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! +override MSTest.Analyzers.AvoidExpectedExceptionAttributeFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! +override MSTest.Analyzers.ClassCleanupShouldBeValidFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! +override MSTest.Analyzers.ClassCleanupShouldBeValidFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! +override MSTest.Analyzers.ClassInitializeShouldBeValidFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! +override MSTest.Analyzers.ClassInitializeShouldBeValidFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! +override MSTest.Analyzers.PreferAssertFailOverAlwaysFalseConditionsFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! +override MSTest.Analyzers.PreferAssertFailOverAlwaysFalseConditionsFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! +override MSTest.Analyzers.PreferConstructorOverTestInitializeFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray +override MSTest.Analyzers.PreferConstructorOverTestInitializeFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! +override MSTest.Analyzers.PreferConstructorOverTestInitializeFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! +override MSTest.Analyzers.PreferDisposeOverTestCleanupFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray +override MSTest.Analyzers.PreferDisposeOverTestCleanupFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! +override MSTest.Analyzers.PreferDisposeOverTestCleanupFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! +override MSTest.Analyzers.PreferTestCleanupOverDisposeFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray +override MSTest.Analyzers.PreferTestCleanupOverDisposeFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! +override MSTest.Analyzers.PreferTestCleanupOverDisposeFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! +override MSTest.Analyzers.PreferTestInitializeOverConstructorFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray +override MSTest.Analyzers.PreferTestInitializeOverConstructorFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! +override MSTest.Analyzers.PreferTestInitializeOverConstructorFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! +override MSTest.Analyzers.PublicMethodShouldBeTestMethodFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray +override MSTest.Analyzers.PublicMethodShouldBeTestMethodFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! +override MSTest.Analyzers.PublicMethodShouldBeTestMethodFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! +override MSTest.Analyzers.TestClassShouldBeValidFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! +override MSTest.Analyzers.TestClassShouldBeValidFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! +override MSTest.Analyzers.TestCleanupShouldBeValidFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! +override MSTest.Analyzers.TestCleanupShouldBeValidFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! +override MSTest.Analyzers.TestContextShouldBeValidFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! +override MSTest.Analyzers.TestContextShouldBeValidFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! +override MSTest.Analyzers.TestInitializeShouldBeValidFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! +override MSTest.Analyzers.TestInitializeShouldBeValidFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! +override MSTest.Analyzers.TestMethodShouldBeValidCodeFixProvider.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray +override MSTest.Analyzers.TestMethodShouldBeValidCodeFixProvider.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! +override MSTest.Analyzers.TestMethodShouldBeValidCodeFixProvider.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! +override MSTest.Analyzers.UseAttributeOnTestMethodFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! +override MSTest.Analyzers.UseNewerAssertThrowsFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! +override MSTest.Analyzers.UseNewerAssertThrowsFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! +override MSTest.Analyzers.UseProperAssertMethodsFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! +override MSTest.Analyzers.UseProperAssertMethodsFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! +override sealed MSTest.Analyzers.AddTestClassFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray +override sealed MSTest.Analyzers.AssemblyCleanupShouldBeValidFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray +override sealed MSTest.Analyzers.AssemblyInitializeShouldBeValidFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray +override sealed MSTest.Analyzers.AssertionArgsShouldAvoidConditionalAccessFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray +override sealed MSTest.Analyzers.AssertionArgsShouldBePassedInCorrectOrderFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray +override sealed MSTest.Analyzers.AvoidAssertAreSameWithValueTypesFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray +override sealed MSTest.Analyzers.AvoidExpectedExceptionAttributeFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray +override sealed MSTest.Analyzers.AvoidExpectedExceptionAttributeFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! +override sealed MSTest.Analyzers.ClassCleanupShouldBeValidFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray +override sealed MSTest.Analyzers.ClassInitializeShouldBeValidFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray +override sealed MSTest.Analyzers.PreferAssertFailOverAlwaysFalseConditionsFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray +override sealed MSTest.Analyzers.TestClassShouldBeValidFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray +override sealed MSTest.Analyzers.TestCleanupShouldBeValidFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray +override sealed MSTest.Analyzers.TestContextShouldBeValidFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray +override sealed MSTest.Analyzers.TestInitializeShouldBeValidFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray +override sealed MSTest.Analyzers.UseAttributeOnTestMethodFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray +override sealed MSTest.Analyzers.UseAttributeOnTestMethodFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! +override sealed MSTest.Analyzers.UseNewerAssertThrowsFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray +override sealed MSTest.Analyzers.UseProperAssertMethodsFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/PublicAPI.Unshipped.txt b/src/Analyzers/MSTest.Analyzers.CodeFixes/PublicAPI.Unshipped.txt index 712126dc7e..7dc5c58110 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/PublicAPI.Unshipped.txt +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/PublicAPI.Unshipped.txt @@ -1,116 +1 @@ #nullable enable -MSTest.Analyzers.AddTestClassFixer -MSTest.Analyzers.AddTestClassFixer.AddTestClassFixer() -> void -MSTest.Analyzers.AssemblyCleanupShouldBeValidFixer -MSTest.Analyzers.AssemblyCleanupShouldBeValidFixer.AssemblyCleanupShouldBeValidFixer() -> void -MSTest.Analyzers.AssemblyInitializeShouldBeValidFixer -MSTest.Analyzers.AssemblyInitializeShouldBeValidFixer.AssemblyInitializeShouldBeValidFixer() -> void -MSTest.Analyzers.AssertionArgsShouldAvoidConditionalAccessFixer -MSTest.Analyzers.AssertionArgsShouldAvoidConditionalAccessFixer.AssertionArgsShouldAvoidConditionalAccessFixer() -> void -MSTest.Analyzers.AssertionArgsShouldBePassedInCorrectOrderFixer -MSTest.Analyzers.AssertionArgsShouldBePassedInCorrectOrderFixer.AssertionArgsShouldBePassedInCorrectOrderFixer() -> void -MSTest.Analyzers.AvoidAssertAreSameWithValueTypesFixer -MSTest.Analyzers.AvoidAssertAreSameWithValueTypesFixer.AvoidAssertAreSameWithValueTypesFixer() -> void -MSTest.Analyzers.AvoidExpectedExceptionAttributeFixer -MSTest.Analyzers.AvoidExpectedExceptionAttributeFixer.AvoidExpectedExceptionAttributeFixer() -> void -MSTest.Analyzers.ClassCleanupShouldBeValidFixer -MSTest.Analyzers.ClassCleanupShouldBeValidFixer.ClassCleanupShouldBeValidFixer() -> void -MSTest.Analyzers.ClassInitializeShouldBeValidFixer -MSTest.Analyzers.ClassInitializeShouldBeValidFixer.ClassInitializeShouldBeValidFixer() -> void -MSTest.Analyzers.PreferAssertFailOverAlwaysFalseConditionsFixer -MSTest.Analyzers.PreferAssertFailOverAlwaysFalseConditionsFixer.PreferAssertFailOverAlwaysFalseConditionsFixer() -> void -MSTest.Analyzers.PreferConstructorOverTestInitializeFixer -MSTest.Analyzers.PreferConstructorOverTestInitializeFixer.PreferConstructorOverTestInitializeFixer() -> void -MSTest.Analyzers.PreferDisposeOverTestCleanupFixer -MSTest.Analyzers.PreferDisposeOverTestCleanupFixer.PreferDisposeOverTestCleanupFixer() -> void -MSTest.Analyzers.PreferTestCleanupOverDisposeFixer -MSTest.Analyzers.PreferTestCleanupOverDisposeFixer.PreferTestCleanupOverDisposeFixer() -> void -MSTest.Analyzers.PreferTestInitializeOverConstructorFixer -MSTest.Analyzers.PreferTestInitializeOverConstructorFixer.PreferTestInitializeOverConstructorFixer() -> void -MSTest.Analyzers.PublicMethodShouldBeTestMethodFixer -MSTest.Analyzers.PublicMethodShouldBeTestMethodFixer.PublicMethodShouldBeTestMethodFixer() -> void -MSTest.Analyzers.TestClassShouldBeValidFixer -MSTest.Analyzers.TestClassShouldBeValidFixer.TestClassShouldBeValidFixer() -> void -MSTest.Analyzers.TestCleanupShouldBeValidFixer -MSTest.Analyzers.TestCleanupShouldBeValidFixer.TestCleanupShouldBeValidFixer() -> void -MSTest.Analyzers.TestContextShouldBeValidFixer -MSTest.Analyzers.TestContextShouldBeValidFixer.TestContextShouldBeValidFixer() -> void -MSTest.Analyzers.TestInitializeShouldBeValidFixer -MSTest.Analyzers.TestInitializeShouldBeValidFixer.TestInitializeShouldBeValidFixer() -> void -MSTest.Analyzers.TestMethodShouldBeValidCodeFixProvider -MSTest.Analyzers.TestMethodShouldBeValidCodeFixProvider.TestMethodShouldBeValidCodeFixProvider() -> void -MSTest.Analyzers.UseAttributeOnTestMethodFixer -MSTest.Analyzers.UseAttributeOnTestMethodFixer.UseAttributeOnTestMethodFixer() -> void -MSTest.Analyzers.UseNewerAssertThrowsFixer -MSTest.Analyzers.UseNewerAssertThrowsFixer.UseNewerAssertThrowsFixer() -> void -MSTest.Analyzers.UseProperAssertMethodsFixer -MSTest.Analyzers.UseProperAssertMethodsFixer.UseProperAssertMethodsFixer() -> void -override MSTest.Analyzers.AddTestClassFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! -override MSTest.Analyzers.AddTestClassFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! -override MSTest.Analyzers.AssemblyCleanupShouldBeValidFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! -override MSTest.Analyzers.AssemblyCleanupShouldBeValidFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! -override MSTest.Analyzers.AssemblyInitializeShouldBeValidFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! -override MSTest.Analyzers.AssemblyInitializeShouldBeValidFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! -override MSTest.Analyzers.AssertionArgsShouldAvoidConditionalAccessFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! -override MSTest.Analyzers.AssertionArgsShouldAvoidConditionalAccessFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! -override MSTest.Analyzers.AssertionArgsShouldBePassedInCorrectOrderFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! -override MSTest.Analyzers.AssertionArgsShouldBePassedInCorrectOrderFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! -override MSTest.Analyzers.AvoidAssertAreSameWithValueTypesFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! -override MSTest.Analyzers.AvoidAssertAreSameWithValueTypesFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! -override MSTest.Analyzers.AvoidExpectedExceptionAttributeFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! -override MSTest.Analyzers.ClassCleanupShouldBeValidFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! -override MSTest.Analyzers.ClassCleanupShouldBeValidFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! -override MSTest.Analyzers.ClassInitializeShouldBeValidFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! -override MSTest.Analyzers.ClassInitializeShouldBeValidFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! -override MSTest.Analyzers.PreferAssertFailOverAlwaysFalseConditionsFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! -override MSTest.Analyzers.PreferAssertFailOverAlwaysFalseConditionsFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! -override MSTest.Analyzers.PreferConstructorOverTestInitializeFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray -override MSTest.Analyzers.PreferConstructorOverTestInitializeFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! -override MSTest.Analyzers.PreferConstructorOverTestInitializeFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! -override MSTest.Analyzers.PreferDisposeOverTestCleanupFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray -override MSTest.Analyzers.PreferDisposeOverTestCleanupFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! -override MSTest.Analyzers.PreferDisposeOverTestCleanupFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! -override MSTest.Analyzers.PreferTestCleanupOverDisposeFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray -override MSTest.Analyzers.PreferTestCleanupOverDisposeFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! -override MSTest.Analyzers.PreferTestCleanupOverDisposeFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! -override MSTest.Analyzers.PreferTestInitializeOverConstructorFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray -override MSTest.Analyzers.PreferTestInitializeOverConstructorFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! -override MSTest.Analyzers.PreferTestInitializeOverConstructorFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! -override MSTest.Analyzers.PublicMethodShouldBeTestMethodFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray -override MSTest.Analyzers.PublicMethodShouldBeTestMethodFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! -override MSTest.Analyzers.PublicMethodShouldBeTestMethodFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! -override MSTest.Analyzers.TestClassShouldBeValidFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! -override MSTest.Analyzers.TestClassShouldBeValidFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! -override MSTest.Analyzers.TestCleanupShouldBeValidFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! -override MSTest.Analyzers.TestCleanupShouldBeValidFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! -override MSTest.Analyzers.TestContextShouldBeValidFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! -override MSTest.Analyzers.TestContextShouldBeValidFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! -override MSTest.Analyzers.TestInitializeShouldBeValidFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! -override MSTest.Analyzers.TestInitializeShouldBeValidFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! -override MSTest.Analyzers.TestMethodShouldBeValidCodeFixProvider.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray -override MSTest.Analyzers.TestMethodShouldBeValidCodeFixProvider.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! -override MSTest.Analyzers.TestMethodShouldBeValidCodeFixProvider.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! -override MSTest.Analyzers.UseAttributeOnTestMethodFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! -override MSTest.Analyzers.UseNewerAssertThrowsFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! -override MSTest.Analyzers.UseNewerAssertThrowsFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! -override MSTest.Analyzers.UseProperAssertMethodsFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! -override MSTest.Analyzers.UseProperAssertMethodsFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! -override sealed MSTest.Analyzers.AddTestClassFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray -override sealed MSTest.Analyzers.AssemblyCleanupShouldBeValidFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray -override sealed MSTest.Analyzers.AssemblyInitializeShouldBeValidFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray -override sealed MSTest.Analyzers.AssertionArgsShouldAvoidConditionalAccessFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray -override sealed MSTest.Analyzers.AssertionArgsShouldBePassedInCorrectOrderFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray -override sealed MSTest.Analyzers.AvoidAssertAreSameWithValueTypesFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray -override sealed MSTest.Analyzers.AvoidExpectedExceptionAttributeFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray -override sealed MSTest.Analyzers.AvoidExpectedExceptionAttributeFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! -override sealed MSTest.Analyzers.ClassCleanupShouldBeValidFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray -override sealed MSTest.Analyzers.ClassInitializeShouldBeValidFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray -override sealed MSTest.Analyzers.PreferAssertFailOverAlwaysFalseConditionsFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray -override sealed MSTest.Analyzers.TestClassShouldBeValidFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray -override sealed MSTest.Analyzers.TestCleanupShouldBeValidFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray -override sealed MSTest.Analyzers.TestContextShouldBeValidFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray -override sealed MSTest.Analyzers.TestInitializeShouldBeValidFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray -override sealed MSTest.Analyzers.UseAttributeOnTestMethodFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray -override sealed MSTest.Analyzers.UseAttributeOnTestMethodFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! -override sealed MSTest.Analyzers.UseNewerAssertThrowsFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray -override sealed MSTest.Analyzers.UseProperAssertMethodsFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray diff --git a/src/Analyzers/MSTest.Analyzers/PublicAPI.Shipped.txt b/src/Analyzers/MSTest.Analyzers/PublicAPI.Shipped.txt index 56544445f9..8c2dc7036b 100644 --- a/src/Analyzers/MSTest.Analyzers/PublicAPI.Shipped.txt +++ b/src/Analyzers/MSTest.Analyzers/PublicAPI.Shipped.txt @@ -27,6 +27,8 @@ MSTest.Analyzers.DoNotUseShadowingAnalyzer MSTest.Analyzers.DoNotUseShadowingAnalyzer.DoNotUseShadowingAnalyzer() -> void MSTest.Analyzers.DoNotUseSystemDescriptionAttributeAnalyzer MSTest.Analyzers.DoNotUseSystemDescriptionAttributeAnalyzer.DoNotUseSystemDescriptionAttributeAnalyzer() -> void +MSTest.Analyzers.DuplicateDataRowAnalyzer +MSTest.Analyzers.DuplicateDataRowAnalyzer.DuplicateDataRowAnalyzer() -> void MSTest.Analyzers.DynamicDataShouldBeValidAnalyzer MSTest.Analyzers.DynamicDataShouldBeValidAnalyzer.DynamicDataShouldBeValidAnalyzer() -> void MSTest.Analyzers.NonNullableReferenceNotInitializedSuppressor @@ -77,6 +79,8 @@ MSTest.Analyzers.UseDeploymentItemWithTestMethodOrTestClassAnalyzer MSTest.Analyzers.UseDeploymentItemWithTestMethodOrTestClassAnalyzer.UseDeploymentItemWithTestMethodOrTestClassAnalyzer() -> void MSTest.Analyzers.UseParallelizeAttributeAnalyzer MSTest.Analyzers.UseParallelizeAttributeAnalyzer.UseParallelizeAttributeAnalyzer() -> void +MSTest.Analyzers.UseRetryWithTestMethodAnalyzer +MSTest.Analyzers.UseRetryWithTestMethodAnalyzer.UseRetryWithTestMethodAnalyzer() -> void override MSTest.Analyzers.AssemblyCleanupShouldBeValidAnalyzer.Initialize(Microsoft.CodeAnalysis.Diagnostics.AnalysisContext! context) -> void override MSTest.Analyzers.AssemblyCleanupShouldBeValidAnalyzer.SupportedDiagnostics.get -> System.Collections.Immutable.ImmutableArray override MSTest.Analyzers.AssemblyInitializeShouldBeValidAnalyzer.Initialize(Microsoft.CodeAnalysis.Diagnostics.AnalysisContext! context) -> void @@ -105,6 +109,8 @@ override MSTest.Analyzers.DoNotUseShadowingAnalyzer.Initialize(Microsoft.CodeAna override MSTest.Analyzers.DoNotUseShadowingAnalyzer.SupportedDiagnostics.get -> System.Collections.Immutable.ImmutableArray override MSTest.Analyzers.DoNotUseSystemDescriptionAttributeAnalyzer.Initialize(Microsoft.CodeAnalysis.Diagnostics.AnalysisContext! context) -> void override MSTest.Analyzers.DoNotUseSystemDescriptionAttributeAnalyzer.SupportedDiagnostics.get -> System.Collections.Immutable.ImmutableArray +override MSTest.Analyzers.DuplicateDataRowAnalyzer.Initialize(Microsoft.CodeAnalysis.Diagnostics.AnalysisContext! context) -> void +override MSTest.Analyzers.DuplicateDataRowAnalyzer.SupportedDiagnostics.get -> System.Collections.Immutable.ImmutableArray override MSTest.Analyzers.DynamicDataShouldBeValidAnalyzer.Initialize(Microsoft.CodeAnalysis.Diagnostics.AnalysisContext! context) -> void override MSTest.Analyzers.DynamicDataShouldBeValidAnalyzer.SupportedDiagnostics.get -> System.Collections.Immutable.ImmutableArray override MSTest.Analyzers.NonNullableReferenceNotInitializedSuppressor.ReportSuppressions(Microsoft.CodeAnalysis.Diagnostics.SuppressionAnalysisContext context) -> void @@ -155,3 +161,5 @@ override MSTest.Analyzers.UseDeploymentItemWithTestMethodOrTestClassAnalyzer.Ini override MSTest.Analyzers.UseDeploymentItemWithTestMethodOrTestClassAnalyzer.SupportedDiagnostics.get -> System.Collections.Immutable.ImmutableArray override MSTest.Analyzers.UseParallelizeAttributeAnalyzer.Initialize(Microsoft.CodeAnalysis.Diagnostics.AnalysisContext! context) -> void override MSTest.Analyzers.UseParallelizeAttributeAnalyzer.SupportedDiagnostics.get -> System.Collections.Immutable.ImmutableArray +override MSTest.Analyzers.UseRetryWithTestMethodAnalyzer.Initialize(Microsoft.CodeAnalysis.Diagnostics.AnalysisContext! context) -> void +override MSTest.Analyzers.UseRetryWithTestMethodAnalyzer.SupportedDiagnostics.get -> System.Collections.Immutable.ImmutableArray diff --git a/src/Analyzers/MSTest.Analyzers/PublicAPI.Unshipped.txt b/src/Analyzers/MSTest.Analyzers/PublicAPI.Unshipped.txt index ffbf652d09..7dc5c58110 100644 --- a/src/Analyzers/MSTest.Analyzers/PublicAPI.Unshipped.txt +++ b/src/Analyzers/MSTest.Analyzers/PublicAPI.Unshipped.txt @@ -1,9 +1 @@ #nullable enable -MSTest.Analyzers.DuplicateDataRowAnalyzer -MSTest.Analyzers.DuplicateDataRowAnalyzer.DuplicateDataRowAnalyzer() -> void -MSTest.Analyzers.UseRetryWithTestMethodAnalyzer -MSTest.Analyzers.UseRetryWithTestMethodAnalyzer.UseRetryWithTestMethodAnalyzer() -> void -override MSTest.Analyzers.DuplicateDataRowAnalyzer.Initialize(Microsoft.CodeAnalysis.Diagnostics.AnalysisContext! context) -> void -override MSTest.Analyzers.DuplicateDataRowAnalyzer.SupportedDiagnostics.get -> System.Collections.Immutable.ImmutableArray -override MSTest.Analyzers.UseRetryWithTestMethodAnalyzer.Initialize(Microsoft.CodeAnalysis.Diagnostics.AnalysisContext! context) -> void -override MSTest.Analyzers.UseRetryWithTestMethodAnalyzer.SupportedDiagnostics.get -> System.Collections.Immutable.ImmutableArray diff --git a/src/Analyzers/MSTest.Internal.Analyzers/PublicAPI.Shipped.txt b/src/Analyzers/MSTest.Internal.Analyzers/PublicAPI.Shipped.txt index 7dc5c58110..8e80ba85b6 100644 --- a/src/Analyzers/MSTest.Internal.Analyzers/PublicAPI.Shipped.txt +++ b/src/Analyzers/MSTest.Internal.Analyzers/PublicAPI.Shipped.txt @@ -1 +1,5 @@ #nullable enable +MSTest.Internal.Analyzers.MSTestObsoleteTypesSuppressor +MSTest.Internal.Analyzers.MSTestObsoleteTypesSuppressor.MSTestObsoleteTypesSuppressor() -> void +override MSTest.Internal.Analyzers.MSTestObsoleteTypesSuppressor.ReportSuppressions(Microsoft.CodeAnalysis.Diagnostics.SuppressionAnalysisContext context) -> void +override MSTest.Internal.Analyzers.MSTestObsoleteTypesSuppressor.SupportedSuppressions.get -> System.Collections.Immutable.ImmutableArray diff --git a/src/Analyzers/MSTest.Internal.Analyzers/PublicAPI.Unshipped.txt b/src/Analyzers/MSTest.Internal.Analyzers/PublicAPI.Unshipped.txt index 8e80ba85b6..7dc5c58110 100644 --- a/src/Analyzers/MSTest.Internal.Analyzers/PublicAPI.Unshipped.txt +++ b/src/Analyzers/MSTest.Internal.Analyzers/PublicAPI.Unshipped.txt @@ -1,5 +1 @@ #nullable enable -MSTest.Internal.Analyzers.MSTestObsoleteTypesSuppressor -MSTest.Internal.Analyzers.MSTestObsoleteTypesSuppressor.MSTestObsoleteTypesSuppressor() -> void -override MSTest.Internal.Analyzers.MSTestObsoleteTypesSuppressor.ReportSuppressions(Microsoft.CodeAnalysis.Diagnostics.SuppressionAnalysisContext context) -> void -override MSTest.Internal.Analyzers.MSTestObsoleteTypesSuppressor.SupportedSuppressions.get -> System.Collections.Immutable.ImmutableArray diff --git a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/PublicAPI/PublicAPI.Shipped.txt b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/PublicAPI/PublicAPI.Shipped.txt index 7dc5c58110..3b7a744721 100644 --- a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/PublicAPI/PublicAPI.Shipped.txt +++ b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/PublicAPI/PublicAPI.Shipped.txt @@ -1 +1,5 @@ #nullable enable +Microsoft.Testing.Extensions.AzureDevOpsExtensions +Microsoft.Testing.Extensions.AzureDevOpsReport.TestingPlatformBuilderHook +static Microsoft.Testing.Extensions.AzureDevOpsExtensions.AddAzureDevOpsProvider(this Microsoft.Testing.Platform.Builder.ITestApplicationBuilder! builder) -> void +static Microsoft.Testing.Extensions.AzureDevOpsReport.TestingPlatformBuilderHook.AddExtensions(Microsoft.Testing.Platform.Builder.ITestApplicationBuilder! testApplicationBuilder, string![]! _) -> void diff --git a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/PublicAPI/PublicAPI.Unshipped.txt b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/PublicAPI/PublicAPI.Unshipped.txt index 2ad77b868e..7dc5c58110 100644 --- a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/PublicAPI/PublicAPI.Unshipped.txt +++ b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/PublicAPI/PublicAPI.Unshipped.txt @@ -1,5 +1 @@ #nullable enable -Microsoft.Testing.Extensions.AzureDevOpsReport.TestingPlatformBuilderHook -Microsoft.Testing.Extensions.AzureDevOpsExtensions -static Microsoft.Testing.Extensions.AzureDevOpsReport.TestingPlatformBuilderHook.AddExtensions(Microsoft.Testing.Platform.Builder.ITestApplicationBuilder! testApplicationBuilder, string![]! _) -> void -static Microsoft.Testing.Extensions.AzureDevOpsExtensions.AddAzureDevOpsProvider(this Microsoft.Testing.Platform.Builder.ITestApplicationBuilder! builder) -> void diff --git a/src/Platform/Microsoft.Testing.Extensions.MSBuild/PublicAPI.Shipped.txt b/src/Platform/Microsoft.Testing.Extensions.MSBuild/PublicAPI.Shipped.txt index 7dc5c58110..a82cec2234 100644 --- a/src/Platform/Microsoft.Testing.Extensions.MSBuild/PublicAPI.Shipped.txt +++ b/src/Platform/Microsoft.Testing.Extensions.MSBuild/PublicAPI.Shipped.txt @@ -1 +1,5 @@ #nullable enable +Microsoft.Testing.Platform.MSBuild.MSBuildExtensions +Microsoft.Testing.Platform.MSBuild.TestingPlatformBuilderHook +static Microsoft.Testing.Platform.MSBuild.MSBuildExtensions.AddMSBuild(this Microsoft.Testing.Platform.Builder.ITestApplicationBuilder! builder) -> void +static Microsoft.Testing.Platform.MSBuild.TestingPlatformBuilderHook.AddExtensions(Microsoft.Testing.Platform.Builder.ITestApplicationBuilder! testApplicationBuilder, string![]! _) -> void diff --git a/src/Platform/Microsoft.Testing.Extensions.MSBuild/PublicAPI.Unshipped.txt b/src/Platform/Microsoft.Testing.Extensions.MSBuild/PublicAPI.Unshipped.txt index a82cec2234..7dc5c58110 100644 --- a/src/Platform/Microsoft.Testing.Extensions.MSBuild/PublicAPI.Unshipped.txt +++ b/src/Platform/Microsoft.Testing.Extensions.MSBuild/PublicAPI.Unshipped.txt @@ -1,5 +1 @@ #nullable enable -Microsoft.Testing.Platform.MSBuild.MSBuildExtensions -Microsoft.Testing.Platform.MSBuild.TestingPlatformBuilderHook -static Microsoft.Testing.Platform.MSBuild.MSBuildExtensions.AddMSBuild(this Microsoft.Testing.Platform.Builder.ITestApplicationBuilder! builder) -> void -static Microsoft.Testing.Platform.MSBuild.TestingPlatformBuilderHook.AddExtensions(Microsoft.Testing.Platform.Builder.ITestApplicationBuilder! testApplicationBuilder, string![]! _) -> void diff --git a/src/Platform/Microsoft.Testing.Platform.MSBuild/PublicAPI.Shipped.txt b/src/Platform/Microsoft.Testing.Platform.MSBuild/PublicAPI.Shipped.txt index 7dc5c58110..7276566dda 100644 --- a/src/Platform/Microsoft.Testing.Platform.MSBuild/PublicAPI.Shipped.txt +++ b/src/Platform/Microsoft.Testing.Platform.MSBuild/PublicAPI.Shipped.txt @@ -1 +1,84 @@ #nullable enable +Microsoft.Testing.Platform.MSBuild.ConfigurationFileTask +Microsoft.Testing.Platform.MSBuild.ConfigurationFileTask.AssemblyName.get -> Microsoft.Build.Framework.ITaskItem! +Microsoft.Testing.Platform.MSBuild.ConfigurationFileTask.AssemblyName.set -> void +Microsoft.Testing.Platform.MSBuild.ConfigurationFileTask.ConfigurationFileTask() -> void +Microsoft.Testing.Platform.MSBuild.ConfigurationFileTask.FinalTestingPlatformConfigurationFile.get -> Microsoft.Build.Framework.ITaskItem! +Microsoft.Testing.Platform.MSBuild.ConfigurationFileTask.FinalTestingPlatformConfigurationFile.set -> void +Microsoft.Testing.Platform.MSBuild.ConfigurationFileTask.MSBuildProjectDirectory.get -> Microsoft.Build.Framework.ITaskItem! +Microsoft.Testing.Platform.MSBuild.ConfigurationFileTask.MSBuildProjectDirectory.set -> void +Microsoft.Testing.Platform.MSBuild.ConfigurationFileTask.OutputPath.get -> Microsoft.Build.Framework.ITaskItem! +Microsoft.Testing.Platform.MSBuild.ConfigurationFileTask.OutputPath.set -> void +Microsoft.Testing.Platform.MSBuild.ConfigurationFileTask.TestingPlatformConfigurationFileSource.get -> Microsoft.Build.Framework.ITaskItem! +Microsoft.Testing.Platform.MSBuild.ConfigurationFileTask.TestingPlatformConfigurationFileSource.set -> void +Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask +Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.AssemblyName.get -> Microsoft.Build.Framework.ITaskItem? +Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.AssemblyName.set -> void +Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.Dispose() -> void +Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.DotnetHostPath.get -> Microsoft.Build.Framework.ITaskItem? +Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.DotnetHostPath.set -> void +Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.InvokeTestingPlatformTask() -> void +Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.IsExecutable.get -> Microsoft.Build.Framework.ITaskItem? +Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.IsExecutable.set -> void +Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.NativeExecutableExtension.get -> Microsoft.Build.Framework.ITaskItem? +Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.NativeExecutableExtension.set -> void +Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.ProjectFullPath.get -> Microsoft.Build.Framework.ITaskItem! +Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.ProjectFullPath.set -> void +Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.TargetDir.get -> Microsoft.Build.Framework.ITaskItem? +Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.TargetDir.set -> void +Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.TargetFramework.get -> Microsoft.Build.Framework.ITaskItem! +Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.TargetFramework.set -> void +Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.TargetFrameworkIdentifier.get -> Microsoft.Build.Framework.ITaskItem! +Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.TargetFrameworkIdentifier.set -> void +Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.TargetPath.get -> Microsoft.Build.Framework.ITaskItem! +Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.TargetPath.set -> void +Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.TestArchitecture.get -> Microsoft.Build.Framework.ITaskItem! +Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.TestArchitecture.set -> void +Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.TestingPlatformCaptureOutput.get -> Microsoft.Build.Framework.ITaskItem! +Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.TestingPlatformCaptureOutput.set -> void +Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.TestingPlatformCommandLineArguments.get -> Microsoft.Build.Framework.ITaskItem? +Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.TestingPlatformCommandLineArguments.set -> void +Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.TestingPlatformShowTestsFailure.get -> Microsoft.Build.Framework.ITaskItem! +Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.TestingPlatformShowTestsFailure.set -> void +Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.UseAppHost.get -> Microsoft.Build.Framework.ITaskItem? +Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.UseAppHost.set -> void +Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.VSTestCLIRunSettings.get -> Microsoft.Build.Framework.ITaskItem![]? +Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.VSTestCLIRunSettings.set -> void +Microsoft.Testing.Platform.MSBuild.TestingPlatformEntryPointTask +Microsoft.Testing.Platform.MSBuild.TestingPlatformEntryPointTask.Language.get -> Microsoft.Build.Framework.ITaskItem! +Microsoft.Testing.Platform.MSBuild.TestingPlatformEntryPointTask.Language.set -> void +Microsoft.Testing.Platform.MSBuild.TestingPlatformEntryPointTask.RootNamespace.get -> string? +Microsoft.Testing.Platform.MSBuild.TestingPlatformEntryPointTask.RootNamespace.set -> void +Microsoft.Testing.Platform.MSBuild.TestingPlatformEntryPointTask.TestingPlatformEntryPointGeneratedFilePath.get -> Microsoft.Build.Framework.ITaskItem! +Microsoft.Testing.Platform.MSBuild.TestingPlatformEntryPointTask.TestingPlatformEntryPointGeneratedFilePath.set -> void +Microsoft.Testing.Platform.MSBuild.TestingPlatformEntryPointTask.TestingPlatformEntryPointSourcePath.get -> Microsoft.Build.Framework.ITaskItem! +Microsoft.Testing.Platform.MSBuild.TestingPlatformEntryPointTask.TestingPlatformEntryPointSourcePath.set -> void +Microsoft.Testing.Platform.MSBuild.TestingPlatformEntryPointTask.TestingPlatformEntryPointTask() -> void +Microsoft.Testing.Platform.MSBuild.TestingPlatformSelfRegisteredExtensions +Microsoft.Testing.Platform.MSBuild.TestingPlatformSelfRegisteredExtensions.Language.get -> Microsoft.Build.Framework.ITaskItem! +Microsoft.Testing.Platform.MSBuild.TestingPlatformSelfRegisteredExtensions.Language.set -> void +Microsoft.Testing.Platform.MSBuild.TestingPlatformSelfRegisteredExtensions.RootNamespace.get -> string? +Microsoft.Testing.Platform.MSBuild.TestingPlatformSelfRegisteredExtensions.RootNamespace.set -> void +Microsoft.Testing.Platform.MSBuild.TestingPlatformSelfRegisteredExtensions.SelfRegisteredExtensionsBuilderHook.get -> Microsoft.Build.Framework.ITaskItem![]! +Microsoft.Testing.Platform.MSBuild.TestingPlatformSelfRegisteredExtensions.SelfRegisteredExtensionsBuilderHook.set -> void +Microsoft.Testing.Platform.MSBuild.TestingPlatformSelfRegisteredExtensions.SelfRegisteredExtensionsGeneratedFilePath.get -> Microsoft.Build.Framework.ITaskItem! +Microsoft.Testing.Platform.MSBuild.TestingPlatformSelfRegisteredExtensions.SelfRegisteredExtensionsGeneratedFilePath.set -> void +Microsoft.Testing.Platform.MSBuild.TestingPlatformSelfRegisteredExtensions.SelfRegisteredExtensionsSourcePath.get -> Microsoft.Build.Framework.ITaskItem! +Microsoft.Testing.Platform.MSBuild.TestingPlatformSelfRegisteredExtensions.SelfRegisteredExtensionsSourcePath.set -> void +Microsoft.Testing.Platform.MSBuild.TestingPlatformSelfRegisteredExtensions.TestingPlatformSelfRegisteredExtensions() -> void +override Microsoft.Testing.Platform.MSBuild.ConfigurationFileTask.Execute() -> bool +override Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.Execute() -> bool +override Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.GenerateCommandLineCommands() -> string! +override Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.GenerateFullPathToTool() -> string? +override Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.HandleTaskExecutionErrors() -> bool +override Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.LogEventsFromTextOutput(string! singleLine, Microsoft.Build.Framework.MessageImportance messageImportance) -> void +override Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.LogToolCommand(string! message) -> void +override Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.ProcessStarted() -> void +override Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.StandardErrorLoggingImportance.get -> Microsoft.Build.Framework.MessageImportance +override Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.StandardOutputLoggingImportance.get -> Microsoft.Build.Framework.MessageImportance +override Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.ToolExe.get -> string! +override Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.ToolExe.set -> void +override Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.ToolName.get -> string! +override Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.ValidateParameters() -> bool +override Microsoft.Testing.Platform.MSBuild.TestingPlatformEntryPointTask.Execute() -> bool +override Microsoft.Testing.Platform.MSBuild.TestingPlatformSelfRegisteredExtensions.Execute() -> bool diff --git a/src/Platform/Microsoft.Testing.Platform.MSBuild/PublicAPI.Unshipped.txt b/src/Platform/Microsoft.Testing.Platform.MSBuild/PublicAPI.Unshipped.txt index 7276566dda..7dc5c58110 100644 --- a/src/Platform/Microsoft.Testing.Platform.MSBuild/PublicAPI.Unshipped.txt +++ b/src/Platform/Microsoft.Testing.Platform.MSBuild/PublicAPI.Unshipped.txt @@ -1,84 +1 @@ #nullable enable -Microsoft.Testing.Platform.MSBuild.ConfigurationFileTask -Microsoft.Testing.Platform.MSBuild.ConfigurationFileTask.AssemblyName.get -> Microsoft.Build.Framework.ITaskItem! -Microsoft.Testing.Platform.MSBuild.ConfigurationFileTask.AssemblyName.set -> void -Microsoft.Testing.Platform.MSBuild.ConfigurationFileTask.ConfigurationFileTask() -> void -Microsoft.Testing.Platform.MSBuild.ConfigurationFileTask.FinalTestingPlatformConfigurationFile.get -> Microsoft.Build.Framework.ITaskItem! -Microsoft.Testing.Platform.MSBuild.ConfigurationFileTask.FinalTestingPlatformConfigurationFile.set -> void -Microsoft.Testing.Platform.MSBuild.ConfigurationFileTask.MSBuildProjectDirectory.get -> Microsoft.Build.Framework.ITaskItem! -Microsoft.Testing.Platform.MSBuild.ConfigurationFileTask.MSBuildProjectDirectory.set -> void -Microsoft.Testing.Platform.MSBuild.ConfigurationFileTask.OutputPath.get -> Microsoft.Build.Framework.ITaskItem! -Microsoft.Testing.Platform.MSBuild.ConfigurationFileTask.OutputPath.set -> void -Microsoft.Testing.Platform.MSBuild.ConfigurationFileTask.TestingPlatformConfigurationFileSource.get -> Microsoft.Build.Framework.ITaskItem! -Microsoft.Testing.Platform.MSBuild.ConfigurationFileTask.TestingPlatformConfigurationFileSource.set -> void -Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask -Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.AssemblyName.get -> Microsoft.Build.Framework.ITaskItem? -Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.AssemblyName.set -> void -Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.Dispose() -> void -Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.DotnetHostPath.get -> Microsoft.Build.Framework.ITaskItem? -Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.DotnetHostPath.set -> void -Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.InvokeTestingPlatformTask() -> void -Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.IsExecutable.get -> Microsoft.Build.Framework.ITaskItem? -Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.IsExecutable.set -> void -Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.NativeExecutableExtension.get -> Microsoft.Build.Framework.ITaskItem? -Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.NativeExecutableExtension.set -> void -Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.ProjectFullPath.get -> Microsoft.Build.Framework.ITaskItem! -Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.ProjectFullPath.set -> void -Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.TargetDir.get -> Microsoft.Build.Framework.ITaskItem? -Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.TargetDir.set -> void -Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.TargetFramework.get -> Microsoft.Build.Framework.ITaskItem! -Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.TargetFramework.set -> void -Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.TargetFrameworkIdentifier.get -> Microsoft.Build.Framework.ITaskItem! -Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.TargetFrameworkIdentifier.set -> void -Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.TargetPath.get -> Microsoft.Build.Framework.ITaskItem! -Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.TargetPath.set -> void -Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.TestArchitecture.get -> Microsoft.Build.Framework.ITaskItem! -Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.TestArchitecture.set -> void -Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.TestingPlatformCaptureOutput.get -> Microsoft.Build.Framework.ITaskItem! -Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.TestingPlatformCaptureOutput.set -> void -Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.TestingPlatformCommandLineArguments.get -> Microsoft.Build.Framework.ITaskItem? -Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.TestingPlatformCommandLineArguments.set -> void -Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.TestingPlatformShowTestsFailure.get -> Microsoft.Build.Framework.ITaskItem! -Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.TestingPlatformShowTestsFailure.set -> void -Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.UseAppHost.get -> Microsoft.Build.Framework.ITaskItem? -Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.UseAppHost.set -> void -Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.VSTestCLIRunSettings.get -> Microsoft.Build.Framework.ITaskItem![]? -Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.VSTestCLIRunSettings.set -> void -Microsoft.Testing.Platform.MSBuild.TestingPlatformEntryPointTask -Microsoft.Testing.Platform.MSBuild.TestingPlatformEntryPointTask.Language.get -> Microsoft.Build.Framework.ITaskItem! -Microsoft.Testing.Platform.MSBuild.TestingPlatformEntryPointTask.Language.set -> void -Microsoft.Testing.Platform.MSBuild.TestingPlatformEntryPointTask.RootNamespace.get -> string? -Microsoft.Testing.Platform.MSBuild.TestingPlatformEntryPointTask.RootNamespace.set -> void -Microsoft.Testing.Platform.MSBuild.TestingPlatformEntryPointTask.TestingPlatformEntryPointGeneratedFilePath.get -> Microsoft.Build.Framework.ITaskItem! -Microsoft.Testing.Platform.MSBuild.TestingPlatformEntryPointTask.TestingPlatformEntryPointGeneratedFilePath.set -> void -Microsoft.Testing.Platform.MSBuild.TestingPlatformEntryPointTask.TestingPlatformEntryPointSourcePath.get -> Microsoft.Build.Framework.ITaskItem! -Microsoft.Testing.Platform.MSBuild.TestingPlatformEntryPointTask.TestingPlatformEntryPointSourcePath.set -> void -Microsoft.Testing.Platform.MSBuild.TestingPlatformEntryPointTask.TestingPlatformEntryPointTask() -> void -Microsoft.Testing.Platform.MSBuild.TestingPlatformSelfRegisteredExtensions -Microsoft.Testing.Platform.MSBuild.TestingPlatformSelfRegisteredExtensions.Language.get -> Microsoft.Build.Framework.ITaskItem! -Microsoft.Testing.Platform.MSBuild.TestingPlatformSelfRegisteredExtensions.Language.set -> void -Microsoft.Testing.Platform.MSBuild.TestingPlatformSelfRegisteredExtensions.RootNamespace.get -> string? -Microsoft.Testing.Platform.MSBuild.TestingPlatformSelfRegisteredExtensions.RootNamespace.set -> void -Microsoft.Testing.Platform.MSBuild.TestingPlatformSelfRegisteredExtensions.SelfRegisteredExtensionsBuilderHook.get -> Microsoft.Build.Framework.ITaskItem![]! -Microsoft.Testing.Platform.MSBuild.TestingPlatformSelfRegisteredExtensions.SelfRegisteredExtensionsBuilderHook.set -> void -Microsoft.Testing.Platform.MSBuild.TestingPlatformSelfRegisteredExtensions.SelfRegisteredExtensionsGeneratedFilePath.get -> Microsoft.Build.Framework.ITaskItem! -Microsoft.Testing.Platform.MSBuild.TestingPlatformSelfRegisteredExtensions.SelfRegisteredExtensionsGeneratedFilePath.set -> void -Microsoft.Testing.Platform.MSBuild.TestingPlatformSelfRegisteredExtensions.SelfRegisteredExtensionsSourcePath.get -> Microsoft.Build.Framework.ITaskItem! -Microsoft.Testing.Platform.MSBuild.TestingPlatformSelfRegisteredExtensions.SelfRegisteredExtensionsSourcePath.set -> void -Microsoft.Testing.Platform.MSBuild.TestingPlatformSelfRegisteredExtensions.TestingPlatformSelfRegisteredExtensions() -> void -override Microsoft.Testing.Platform.MSBuild.ConfigurationFileTask.Execute() -> bool -override Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.Execute() -> bool -override Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.GenerateCommandLineCommands() -> string! -override Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.GenerateFullPathToTool() -> string? -override Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.HandleTaskExecutionErrors() -> bool -override Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.LogEventsFromTextOutput(string! singleLine, Microsoft.Build.Framework.MessageImportance messageImportance) -> void -override Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.LogToolCommand(string! message) -> void -override Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.ProcessStarted() -> void -override Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.StandardErrorLoggingImportance.get -> Microsoft.Build.Framework.MessageImportance -override Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.StandardOutputLoggingImportance.get -> Microsoft.Build.Framework.MessageImportance -override Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.ToolExe.get -> string! -override Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.ToolExe.set -> void -override Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.ToolName.get -> string! -override Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.ValidateParameters() -> bool -override Microsoft.Testing.Platform.MSBuild.TestingPlatformEntryPointTask.Execute() -> bool -override Microsoft.Testing.Platform.MSBuild.TestingPlatformSelfRegisteredExtensions.Execute() -> bool diff --git a/src/Platform/Microsoft.Testing.Platform/PublicAPI/PublicAPI.Shipped.txt b/src/Platform/Microsoft.Testing.Platform/PublicAPI/PublicAPI.Shipped.txt index 88740559f6..a3663087b9 100644 --- a/src/Platform/Microsoft.Testing.Platform/PublicAPI/PublicAPI.Shipped.txt +++ b/src/Platform/Microsoft.Testing.Platform/PublicAPI/PublicAPI.Shipped.txt @@ -174,6 +174,16 @@ Microsoft.Testing.Platform.Extensions.Messages.FailedTestNodeStateProperty.Faile Microsoft.Testing.Platform.Extensions.Messages.FileArtifact Microsoft.Testing.Platform.Extensions.Messages.FileArtifact.FileArtifact(System.IO.FileInfo! fileInfo, string! displayName, string? description = null) -> void Microsoft.Testing.Platform.Extensions.Messages.FileArtifact.FileInfo.get -> System.IO.FileInfo! +Microsoft.Testing.Platform.Extensions.Messages.FileArtifactProperty +Microsoft.Testing.Platform.Extensions.Messages.FileArtifactProperty.Deconstruct(out System.IO.FileInfo! FileInfo, out string! DisplayName, out string? Description) -> void +Microsoft.Testing.Platform.Extensions.Messages.FileArtifactProperty.Description.get -> string? +Microsoft.Testing.Platform.Extensions.Messages.FileArtifactProperty.Description.init -> void +Microsoft.Testing.Platform.Extensions.Messages.FileArtifactProperty.DisplayName.get -> string! +Microsoft.Testing.Platform.Extensions.Messages.FileArtifactProperty.DisplayName.init -> void +Microsoft.Testing.Platform.Extensions.Messages.FileArtifactProperty.FileArtifactProperty(Microsoft.Testing.Platform.Extensions.Messages.FileArtifactProperty! original) -> void +Microsoft.Testing.Platform.Extensions.Messages.FileArtifactProperty.FileArtifactProperty(System.IO.FileInfo! FileInfo, string! DisplayName, string? Description = null) -> void +Microsoft.Testing.Platform.Extensions.Messages.FileArtifactProperty.FileInfo.get -> System.IO.FileInfo! +Microsoft.Testing.Platform.Extensions.Messages.FileArtifactProperty.FileInfo.init -> void Microsoft.Testing.Platform.Extensions.Messages.FileLocationProperty Microsoft.Testing.Platform.Extensions.Messages.FileLocationProperty.FileLocationProperty(string! FilePath, Microsoft.Testing.Platform.Extensions.Messages.LinePositionSpan LineSpan) -> void Microsoft.Testing.Platform.Extensions.Messages.FileLocationProperty.FilePath.get -> string! @@ -252,6 +262,9 @@ Microsoft.Testing.Platform.Extensions.Messages.TestMetadataProperty.Value.init - Microsoft.Testing.Platform.Extensions.Messages.TestMethodIdentifierProperty Microsoft.Testing.Platform.Extensions.Messages.TestMethodIdentifierProperty.AssemblyFullName.get -> string! Microsoft.Testing.Platform.Extensions.Messages.TestMethodIdentifierProperty.AssemblyFullName.init -> void +Microsoft.Testing.Platform.Extensions.Messages.TestMethodIdentifierProperty.Deconstruct(out string! AssemblyFullName, out string! Namespace, out string! TypeName, out string! MethodName, out int MethodArity, out string![]! ParameterTypeFullNames, out string! ReturnTypeFullName) -> void +Microsoft.Testing.Platform.Extensions.Messages.TestMethodIdentifierProperty.MethodArity.get -> int +Microsoft.Testing.Platform.Extensions.Messages.TestMethodIdentifierProperty.MethodArity.init -> void Microsoft.Testing.Platform.Extensions.Messages.TestMethodIdentifierProperty.MethodName.get -> string! Microsoft.Testing.Platform.Extensions.Messages.TestMethodIdentifierProperty.MethodName.init -> void Microsoft.Testing.Platform.Extensions.Messages.TestMethodIdentifierProperty.Namespace.get -> string! @@ -260,6 +273,7 @@ Microsoft.Testing.Platform.Extensions.Messages.TestMethodIdentifierProperty.Para Microsoft.Testing.Platform.Extensions.Messages.TestMethodIdentifierProperty.ParameterTypeFullNames.init -> void Microsoft.Testing.Platform.Extensions.Messages.TestMethodIdentifierProperty.ReturnTypeFullName.get -> string! Microsoft.Testing.Platform.Extensions.Messages.TestMethodIdentifierProperty.ReturnTypeFullName.init -> void +Microsoft.Testing.Platform.Extensions.Messages.TestMethodIdentifierProperty.TestMethodIdentifierProperty(string! AssemblyFullName, string! Namespace, string! TypeName, string! MethodName, int MethodArity, string![]! ParameterTypeFullNames, string! ReturnTypeFullName) -> void Microsoft.Testing.Platform.Extensions.Messages.TestMethodIdentifierProperty.TestMethodIdentifierProperty(string! AssemblyFullName, string! Namespace, string! TypeName, string! MethodName, string![]! ParameterTypeFullNames, string! ReturnTypeFullName) -> void Microsoft.Testing.Platform.Extensions.Messages.TestMethodIdentifierProperty.TypeName.get -> string! Microsoft.Testing.Platform.Extensions.Messages.TestMethodIdentifierProperty.TypeName.init -> void @@ -470,6 +484,9 @@ override Microsoft.Testing.Platform.Extensions.CommandLine.CommandLineOption.Equ override Microsoft.Testing.Platform.Extensions.CommandLine.CommandLineOption.GetHashCode() -> int override Microsoft.Testing.Platform.Extensions.Messages.DataWithSessionUid.ToString() -> string! override Microsoft.Testing.Platform.Extensions.Messages.FileArtifact.ToString() -> string! +override Microsoft.Testing.Platform.Extensions.Messages.FileArtifactProperty.Equals(object? obj) -> bool +override Microsoft.Testing.Platform.Extensions.Messages.FileArtifactProperty.GetHashCode() -> int +override Microsoft.Testing.Platform.Extensions.Messages.FileArtifactProperty.ToString() -> string! override Microsoft.Testing.Platform.Extensions.Messages.PropertyBagData.ToString() -> string! override Microsoft.Testing.Platform.Extensions.Messages.SessionFileArtifact.ToString() -> string! override Microsoft.Testing.Platform.Extensions.Messages.TestNode.ToString() -> string! @@ -487,6 +504,8 @@ static Microsoft.Testing.Platform.Configurations.ConfigurationExtensions.GetTest static Microsoft.Testing.Platform.Extensions.CommandLine.ArgumentArity.operator !=(Microsoft.Testing.Platform.Extensions.CommandLine.ArgumentArity left, Microsoft.Testing.Platform.Extensions.CommandLine.ArgumentArity right) -> bool static Microsoft.Testing.Platform.Extensions.CommandLine.ArgumentArity.operator ==(Microsoft.Testing.Platform.Extensions.CommandLine.ArgumentArity left, Microsoft.Testing.Platform.Extensions.CommandLine.ArgumentArity right) -> bool static Microsoft.Testing.Platform.Extensions.Messages.DiscoveredTestNodeStateProperty.CachedInstance.get -> Microsoft.Testing.Platform.Extensions.Messages.DiscoveredTestNodeStateProperty! +static Microsoft.Testing.Platform.Extensions.Messages.FileArtifactProperty.operator !=(Microsoft.Testing.Platform.Extensions.Messages.FileArtifactProperty? left, Microsoft.Testing.Platform.Extensions.Messages.FileArtifactProperty? right) -> bool +static Microsoft.Testing.Platform.Extensions.Messages.FileArtifactProperty.operator ==(Microsoft.Testing.Platform.Extensions.Messages.FileArtifactProperty? left, Microsoft.Testing.Platform.Extensions.Messages.FileArtifactProperty? right) -> bool static Microsoft.Testing.Platform.Extensions.Messages.InProgressTestNodeStateProperty.CachedInstance.get -> Microsoft.Testing.Platform.Extensions.Messages.InProgressTestNodeStateProperty! static Microsoft.Testing.Platform.Extensions.Messages.PassedTestNodeStateProperty.CachedInstance.get -> Microsoft.Testing.Platform.Extensions.Messages.PassedTestNodeStateProperty! static Microsoft.Testing.Platform.Extensions.Messages.SkippedTestNodeStateProperty.CachedInstance.get -> Microsoft.Testing.Platform.Extensions.Messages.SkippedTestNodeStateProperty! @@ -529,3 +548,7 @@ static readonly Microsoft.Testing.Platform.Extensions.CommandLine.ArgumentArity. static readonly Microsoft.Testing.Platform.Extensions.CommandLine.ArgumentArity.ZeroOrOne -> Microsoft.Testing.Platform.Extensions.CommandLine.ArgumentArity static readonly Microsoft.Testing.Platform.TestHost.WellKnownClients.TestingPlatformConsole -> string! static readonly Microsoft.Testing.Platform.TestHost.WellKnownClients.VisualStudio -> string! +virtual Microsoft.Testing.Platform.Extensions.Messages.FileArtifactProperty.$() -> Microsoft.Testing.Platform.Extensions.Messages.FileArtifactProperty! +virtual Microsoft.Testing.Platform.Extensions.Messages.FileArtifactProperty.EqualityContract.get -> System.Type! +virtual Microsoft.Testing.Platform.Extensions.Messages.FileArtifactProperty.Equals(Microsoft.Testing.Platform.Extensions.Messages.FileArtifactProperty? other) -> bool +virtual Microsoft.Testing.Platform.Extensions.Messages.FileArtifactProperty.PrintMembers(System.Text.StringBuilder! builder) -> bool diff --git a/src/Platform/Microsoft.Testing.Platform/PublicAPI/PublicAPI.Unshipped.txt b/src/Platform/Microsoft.Testing.Platform/PublicAPI/PublicAPI.Unshipped.txt index 27ec037846..7dc5c58110 100644 --- a/src/Platform/Microsoft.Testing.Platform/PublicAPI/PublicAPI.Unshipped.txt +++ b/src/Platform/Microsoft.Testing.Platform/PublicAPI/PublicAPI.Unshipped.txt @@ -1,24 +1 @@ #nullable enable -Microsoft.Testing.Platform.Extensions.Messages.FileArtifactProperty -Microsoft.Testing.Platform.Extensions.Messages.FileArtifactProperty.Deconstruct(out System.IO.FileInfo! FileInfo, out string! DisplayName, out string? Description) -> void -Microsoft.Testing.Platform.Extensions.Messages.FileArtifactProperty.Description.get -> string? -Microsoft.Testing.Platform.Extensions.Messages.FileArtifactProperty.Description.init -> void -Microsoft.Testing.Platform.Extensions.Messages.FileArtifactProperty.DisplayName.get -> string! -Microsoft.Testing.Platform.Extensions.Messages.FileArtifactProperty.DisplayName.init -> void -Microsoft.Testing.Platform.Extensions.Messages.FileArtifactProperty.FileArtifactProperty(Microsoft.Testing.Platform.Extensions.Messages.FileArtifactProperty! original) -> void -Microsoft.Testing.Platform.Extensions.Messages.FileArtifactProperty.FileArtifactProperty(System.IO.FileInfo! FileInfo, string! DisplayName, string? Description = null) -> void -Microsoft.Testing.Platform.Extensions.Messages.FileArtifactProperty.FileInfo.get -> System.IO.FileInfo! -Microsoft.Testing.Platform.Extensions.Messages.FileArtifactProperty.FileInfo.init -> void -Microsoft.Testing.Platform.Extensions.Messages.TestMethodIdentifierProperty.Deconstruct(out string! AssemblyFullName, out string! Namespace, out string! TypeName, out string! MethodName, out int MethodArity, out string![]! ParameterTypeFullNames, out string! ReturnTypeFullName) -> void -Microsoft.Testing.Platform.Extensions.Messages.TestMethodIdentifierProperty.MethodArity.get -> int -Microsoft.Testing.Platform.Extensions.Messages.TestMethodIdentifierProperty.MethodArity.init -> void -Microsoft.Testing.Platform.Extensions.Messages.TestMethodIdentifierProperty.TestMethodIdentifierProperty(string! AssemblyFullName, string! Namespace, string! TypeName, string! MethodName, int MethodArity, string![]! ParameterTypeFullNames, string! ReturnTypeFullName) -> void -override Microsoft.Testing.Platform.Extensions.Messages.FileArtifactProperty.Equals(object? obj) -> bool -override Microsoft.Testing.Platform.Extensions.Messages.FileArtifactProperty.GetHashCode() -> int -override Microsoft.Testing.Platform.Extensions.Messages.FileArtifactProperty.ToString() -> string! -static Microsoft.Testing.Platform.Extensions.Messages.FileArtifactProperty.operator !=(Microsoft.Testing.Platform.Extensions.Messages.FileArtifactProperty? left, Microsoft.Testing.Platform.Extensions.Messages.FileArtifactProperty? right) -> bool -static Microsoft.Testing.Platform.Extensions.Messages.FileArtifactProperty.operator ==(Microsoft.Testing.Platform.Extensions.Messages.FileArtifactProperty? left, Microsoft.Testing.Platform.Extensions.Messages.FileArtifactProperty? right) -> bool -virtual Microsoft.Testing.Platform.Extensions.Messages.FileArtifactProperty.$() -> Microsoft.Testing.Platform.Extensions.Messages.FileArtifactProperty! -virtual Microsoft.Testing.Platform.Extensions.Messages.FileArtifactProperty.EqualityContract.get -> System.Type! -virtual Microsoft.Testing.Platform.Extensions.Messages.FileArtifactProperty.Equals(Microsoft.Testing.Platform.Extensions.Messages.FileArtifactProperty? other) -> bool -virtual Microsoft.Testing.Platform.Extensions.Messages.FileArtifactProperty.PrintMembers(System.Text.StringBuilder! builder) -> bool diff --git a/src/TestFramework/TestFramework.Extensions/PublicAPI/PublicAPI.Shipped.txt b/src/TestFramework/TestFramework.Extensions/PublicAPI/PublicAPI.Shipped.txt index 1e3ad80187..b50cde008f 100644 --- a/src/TestFramework/TestFramework.Extensions/PublicAPI/PublicAPI.Shipped.txt +++ b/src/TestFramework/TestFramework.Extensions/PublicAPI/PublicAPI.Shipped.txt @@ -18,6 +18,7 @@ Microsoft.VisualStudio.TestTools.UnitTesting.TestContext.TestDisplayName.get -> Microsoft.VisualStudio.TestTools.UnitTesting.TestContext.TestDisplayName.set -> void Microsoft.VisualStudio.TestTools.UnitTesting.TestContext.TestException.get -> System.Exception? Microsoft.VisualStudio.TestTools.UnitTesting.TestContext.TestException.set -> void +Microsoft.VisualStudio.TestTools.UnitTesting.TestContext.TestRunCount.get -> int virtual Microsoft.VisualStudio.TestTools.UnitTesting.TestContext.CancellationTokenSource.get -> System.Threading.CancellationTokenSource! virtual Microsoft.VisualStudio.TestTools.UnitTesting.TestContext.CancellationTokenSource.set -> void virtual Microsoft.VisualStudio.TestTools.UnitTesting.TestContext.CurrentTestOutcome.get -> Microsoft.VisualStudio.TestTools.UnitTesting.UnitTestOutcome diff --git a/src/TestFramework/TestFramework.Extensions/PublicAPI/PublicAPI.Unshipped.txt b/src/TestFramework/TestFramework.Extensions/PublicAPI/PublicAPI.Unshipped.txt index 3fbc1ee8a4..7dc5c58110 100644 --- a/src/TestFramework/TestFramework.Extensions/PublicAPI/PublicAPI.Unshipped.txt +++ b/src/TestFramework/TestFramework.Extensions/PublicAPI/PublicAPI.Unshipped.txt @@ -1,2 +1 @@ #nullable enable -Microsoft.VisualStudio.TestTools.UnitTesting.TestContext.TestRunCount.get -> int diff --git a/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Shipped.txt b/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Shipped.txt index 12691b823c..6264cadf2f 100644 --- a/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Shipped.txt +++ b/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Shipped.txt @@ -2,6 +2,7 @@ [MSTESTEXP]abstract Microsoft.VisualStudio.TestTools.UnitTesting.RetryBaseAttribute.ExecuteAsync(Microsoft.VisualStudio.TestTools.UnitTesting.RetryContext retryContext) -> System.Threading.Tasks.Task! [MSTESTEXP]Microsoft.VisualStudio.TestTools.UnitTesting.RetryContext [MSTESTEXP]Microsoft.VisualStudio.TestTools.UnitTesting.RetryContext.ExecuteTaskGetter.get -> System.Func!>! +[MSTESTEXP]Microsoft.VisualStudio.TestTools.UnitTesting.RetryContext.FirstRunResults.get -> Microsoft.VisualStudio.TestTools.UnitTesting.TestResult![]! [MSTESTEXP]Microsoft.VisualStudio.TestTools.UnitTesting.RetryContext.RetryContext() -> void [MSTESTEXP]Microsoft.VisualStudio.TestTools.UnitTesting.RetryResult [MSTESTEXP]Microsoft.VisualStudio.TestTools.UnitTesting.RetryResult.AddResult(Microsoft.VisualStudio.TestTools.UnitTesting.TestResult![]! testResults) -> void @@ -243,10 +244,12 @@ Microsoft.VisualStudio.TestTools.UnitTesting.AssertFailedException Microsoft.VisualStudio.TestTools.UnitTesting.AssertFailedException.AssertFailedException() -> void Microsoft.VisualStudio.TestTools.UnitTesting.AssertFailedException.AssertFailedException(string! msg, System.Exception! ex) -> void Microsoft.VisualStudio.TestTools.UnitTesting.AssertFailedException.AssertFailedException(string! msg) -> void +Microsoft.VisualStudio.TestTools.UnitTesting.AssertFailedException.AssertFailedException(System.Runtime.Serialization.SerializationInfo! info, System.Runtime.Serialization.StreamingContext context) -> void Microsoft.VisualStudio.TestTools.UnitTesting.AssertInconclusiveException Microsoft.VisualStudio.TestTools.UnitTesting.AssertInconclusiveException.AssertInconclusiveException() -> void Microsoft.VisualStudio.TestTools.UnitTesting.AssertInconclusiveException.AssertInconclusiveException(string! msg, System.Exception! ex) -> void Microsoft.VisualStudio.TestTools.UnitTesting.AssertInconclusiveException.AssertInconclusiveException(string! msg) -> void +Microsoft.VisualStudio.TestTools.UnitTesting.AssertInconclusiveException.AssertInconclusiveException(System.Runtime.Serialization.SerializationInfo! info, System.Runtime.Serialization.StreamingContext context) -> void Microsoft.VisualStudio.TestTools.UnitTesting.ClassCleanupAttribute Microsoft.VisualStudio.TestTools.UnitTesting.ClassCleanupAttribute.ClassCleanupAttribute() -> void Microsoft.VisualStudio.TestTools.UnitTesting.ClassCleanupAttribute.ClassCleanupAttribute(Microsoft.VisualStudio.TestTools.UnitTesting.ClassCleanupBehavior cleanupBehavior) -> void @@ -369,6 +372,7 @@ Microsoft.VisualStudio.TestTools.UnitTesting.InternalTestFailureException Microsoft.VisualStudio.TestTools.UnitTesting.InternalTestFailureException.InternalTestFailureException() -> void Microsoft.VisualStudio.TestTools.UnitTesting.InternalTestFailureException.InternalTestFailureException(string! msg, System.Exception! ex) -> void Microsoft.VisualStudio.TestTools.UnitTesting.InternalTestFailureException.InternalTestFailureException(string! msg) -> void +Microsoft.VisualStudio.TestTools.UnitTesting.InternalTestFailureException.InternalTestFailureException(System.Runtime.Serialization.SerializationInfo! info, System.Runtime.Serialization.StreamingContext context) -> void Microsoft.VisualStudio.TestTools.UnitTesting.ITestDataSource Microsoft.VisualStudio.TestTools.UnitTesting.ITestDataSource.GetData(System.Reflection.MethodInfo! methodInfo) -> System.Collections.Generic.IEnumerable! Microsoft.VisualStudio.TestTools.UnitTesting.ITestDataSource.GetDisplayName(System.Reflection.MethodInfo! methodInfo, object?[]? data) -> string? @@ -382,6 +386,7 @@ Microsoft.VisualStudio.TestTools.UnitTesting.ITestMethod.Arguments.get -> object Microsoft.VisualStudio.TestTools.UnitTesting.ITestMethod.GetAllAttributes(bool inherit) -> System.Attribute![]? Microsoft.VisualStudio.TestTools.UnitTesting.ITestMethod.GetAttributes(bool inherit) -> TAttributeType![]! Microsoft.VisualStudio.TestTools.UnitTesting.ITestMethod.Invoke(object![]? arguments) -> Microsoft.VisualStudio.TestTools.UnitTesting.TestResult! +Microsoft.VisualStudio.TestTools.UnitTesting.ITestMethod.InvokeAsync(object![]? arguments) -> System.Threading.Tasks.Task! Microsoft.VisualStudio.TestTools.UnitTesting.ITestMethod.MethodInfo.get -> System.Reflection.MethodInfo! Microsoft.VisualStudio.TestTools.UnitTesting.ITestMethod.ParameterTypes.get -> System.Reflection.ParameterInfo![]! Microsoft.VisualStudio.TestTools.UnitTesting.ITestMethod.ReturnType.get -> System.Type! @@ -512,6 +517,7 @@ Microsoft.VisualStudio.TestTools.UnitTesting.UnitTestAssertException Microsoft.VisualStudio.TestTools.UnitTesting.UnitTestAssertException.UnitTestAssertException() -> void Microsoft.VisualStudio.TestTools.UnitTesting.UnitTestAssertException.UnitTestAssertException(string! msg, System.Exception! ex) -> void Microsoft.VisualStudio.TestTools.UnitTesting.UnitTestAssertException.UnitTestAssertException(string! msg) -> void +Microsoft.VisualStudio.TestTools.UnitTesting.UnitTestAssertException.UnitTestAssertException(System.Runtime.Serialization.SerializationInfo! info, System.Runtime.Serialization.StreamingContext context) -> void Microsoft.VisualStudio.TestTools.UnitTesting.UnitTestOutcome Microsoft.VisualStudio.TestTools.UnitTesting.UnitTestOutcome.Aborted = 6 -> Microsoft.VisualStudio.TestTools.UnitTesting.UnitTestOutcome Microsoft.VisualStudio.TestTools.UnitTesting.UnitTestOutcome.Error = 4 -> Microsoft.VisualStudio.TestTools.UnitTesting.UnitTestOutcome @@ -714,11 +720,15 @@ static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.That.get -> Microsoft static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.Throws(System.Action! action, ref Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AssertNonStrictThrowsInterpolatedStringHandler message) -> TException! static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.Throws(System.Action! action, string! message = "", params object![]! messageArgs) -> TException! static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.Throws(System.Action! action, System.Func! messageBuilder) -> TException! +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.Throws(System.Func! action, string! message = "", params object![]! messageArgs) -> TException! +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.Throws(System.Func! action, System.Func! messageBuilder) -> TException! static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.ThrowsAsync(System.Func! action, string! message = "", params object![]! messageArgs) -> System.Threading.Tasks.Task! static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.ThrowsAsync(System.Func! action, System.Func! messageBuilder) -> System.Threading.Tasks.Task! static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.ThrowsExactly(System.Action! action, ref Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AssertThrowsExactlyInterpolatedStringHandler message) -> TException! static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.ThrowsExactly(System.Action! action, string! message = "", params object![]! messageArgs) -> TException! static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.ThrowsExactly(System.Action! action, System.Func! messageBuilder) -> TException! +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.ThrowsExactly(System.Func! action, string! message = "", params object![]! messageArgs) -> TException! +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.ThrowsExactly(System.Func! action, System.Func! messageBuilder) -> TException! static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.ThrowsExactlyAsync(System.Func! action, string! message = "", params object![]! messageArgs) -> System.Threading.Tasks.Task! static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.ThrowsExactlyAsync(System.Func! action, System.Func! messageBuilder) -> System.Threading.Tasks.Task! static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.ThrowsException(System.Action! action, string! message, params object?[]? parameters) -> T! diff --git a/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Unshipped.txt b/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Unshipped.txt index 284951033c..7dc5c58110 100644 --- a/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Unshipped.txt +++ b/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Unshipped.txt @@ -1,11 +1 @@ #nullable enable -Microsoft.VisualStudio.TestTools.UnitTesting.AssertFailedException.AssertFailedException(System.Runtime.Serialization.SerializationInfo! info, System.Runtime.Serialization.StreamingContext context) -> void -Microsoft.VisualStudio.TestTools.UnitTesting.AssertInconclusiveException.AssertInconclusiveException(System.Runtime.Serialization.SerializationInfo! info, System.Runtime.Serialization.StreamingContext context) -> void -Microsoft.VisualStudio.TestTools.UnitTesting.InternalTestFailureException.InternalTestFailureException(System.Runtime.Serialization.SerializationInfo! info, System.Runtime.Serialization.StreamingContext context) -> void -Microsoft.VisualStudio.TestTools.UnitTesting.ITestMethod.InvokeAsync(object![]? arguments) -> System.Threading.Tasks.Task! -Microsoft.VisualStudio.TestTools.UnitTesting.UnitTestAssertException.UnitTestAssertException(System.Runtime.Serialization.SerializationInfo! info, System.Runtime.Serialization.StreamingContext context) -> void -static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.Throws(System.Func! action, string! message = "", params object![]! messageArgs) -> TException! -static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.Throws(System.Func! action, System.Func! messageBuilder) -> TException! -static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.ThrowsExactly(System.Func! action, string! message = "", params object![]! messageArgs) -> TException! -static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.ThrowsExactly(System.Func! action, System.Func! messageBuilder) -> TException! -[MSTESTEXP]Microsoft.VisualStudio.TestTools.UnitTesting.RetryContext.FirstRunResults.get -> Microsoft.VisualStudio.TestTools.UnitTesting.TestResult![]! From 47dee826a0a3eb7a2d9d089ed8aba9d2dabfe82e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Jare=C5=A1?= Date: Mon, 12 May 2025 21:37:42 +0200 Subject: [PATCH 007/541] Move analyzers to shipped (#5577) --- .../MSTest.Analyzers/AnalyzerReleases.Shipped.md | 11 ++++++++++- .../MSTest.Analyzers/AnalyzerReleases.Unshipped.md | 2 -- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/src/Analyzers/MSTest.Analyzers/AnalyzerReleases.Shipped.md b/src/Analyzers/MSTest.Analyzers/AnalyzerReleases.Shipped.md index e3dd53f75e..d0c52ee782 100644 --- a/src/Analyzers/MSTest.Analyzers/AnalyzerReleases.Shipped.md +++ b/src/Analyzers/MSTest.Analyzers/AnalyzerReleases.Shipped.md @@ -1,4 +1,13 @@ -## Release 3.8.0 +## Release 3.9.0 + +### New Rules + +Rule ID | Category | Severity | Notes +--------|----------|----------|------- +MSTEST0042 | Usage | Warning | DuplicateDataRowAnalyzer, [Documentation](https://learn.microsoft.com/dotnet/core/testing/mstest-analyzers/mstest0042) +MSTEST0043 | Usage | Warning | UseRetryWithTestMethodAnalyzer, [Documentation](https://learn.microsoft.com/dotnet/core/testing/mstest-analyzers/mstest0043) + +## Release 3.8.0 ### New Rules diff --git a/src/Analyzers/MSTest.Analyzers/AnalyzerReleases.Unshipped.md b/src/Analyzers/MSTest.Analyzers/AnalyzerReleases.Unshipped.md index fbfaf78376..7b845f4860 100644 --- a/src/Analyzers/MSTest.Analyzers/AnalyzerReleases.Unshipped.md +++ b/src/Analyzers/MSTest.Analyzers/AnalyzerReleases.Unshipped.md @@ -5,5 +5,3 @@ Rule ID | Category | Severity | Notes --------|----------|----------|------- -MSTEST0042 | Usage | Warning | DuplicateDataRowAnalyzer, [Documentation](https://learn.microsoft.com/dotnet/core/testing/mstest-analyzers/mstest0042) -MSTEST0043 | Usage | Warning | UseRetryWithTestMethodAnalyzer, [Documentation](https://learn.microsoft.com/dotnet/core/testing/mstest-analyzers/mstest0043) From 7f47c26b682dc8b937b8cd2375fa1b976e39e6a1 Mon Sep 17 00:00:00 2001 From: stan-sz <37585349+stan-sz@users.noreply.github.com> Date: Fri, 16 May 2025 13:01:20 +0200 Subject: [PATCH 008/541] Update Fakes dependency to 17.14.1 (#5580) --- Directory.Packages.props | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Directory.Packages.props b/Directory.Packages.props index b276b09c02..b12c03a835 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -23,7 +23,7 @@ 17.13.0 1.50.0 - 17.14.0-beta.25202.4 + 17.14.1 1.5.0-preview.24577.4 4.5.4 From a6502391016300f0e4ec299038ccc9775ea75fa9 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Mon, 19 May 2025 20:25:01 +0200 Subject: [PATCH 009/541] Make ConditionBaseAttribute.Mode public (#5593) --- .../Attributes/TestMethod/ConditionBaseAttribute.cs | 5 ++++- .../TestFramework/PublicAPI/PublicAPI.Unshipped.txt | 1 + 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/src/TestFramework/TestFramework/Attributes/TestMethod/ConditionBaseAttribute.cs b/src/TestFramework/TestFramework/Attributes/TestMethod/ConditionBaseAttribute.cs index 7a5d8168fd..3d5edc7905 100644 --- a/src/TestFramework/TestFramework/Attributes/TestMethod/ConditionBaseAttribute.cs +++ b/src/TestFramework/TestFramework/Attributes/TestMethod/ConditionBaseAttribute.cs @@ -19,7 +19,10 @@ public abstract class ConditionBaseAttribute : Attribute protected ConditionBaseAttribute(ConditionMode mode) => Mode = mode; - internal ConditionMode Mode { get; } + /// + /// Gets the condition mode. + /// + public ConditionMode Mode { get; } /// /// Gets the ignore message (in case returns ) indicating diff --git a/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Unshipped.txt b/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Unshipped.txt index 7dc5c58110..758e4cf563 100644 --- a/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Unshipped.txt +++ b/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Unshipped.txt @@ -1 +1,2 @@ #nullable enable +Microsoft.VisualStudio.TestTools.UnitTesting.ConditionBaseAttribute.Mode.get -> Microsoft.VisualStudio.TestTools.UnitTesting.ConditionMode From 83676790a94c6b53f667f5e4505e9d671c46951a Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Tue, 20 May 2025 09:10:10 +0200 Subject: [PATCH 010/541] OSConditionAttribute: Make ignore message depend on ConditionMode (#5587) --- .../Attributes/TestMethod/OSConditionAttribute.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/TestFramework/TestFramework/Attributes/TestMethod/OSConditionAttribute.cs b/src/TestFramework/TestFramework/Attributes/TestMethod/OSConditionAttribute.cs index 49906ede5d..fdc05ac0e7 100644 --- a/src/TestFramework/TestFramework/Attributes/TestMethod/OSConditionAttribute.cs +++ b/src/TestFramework/TestFramework/Attributes/TestMethod/OSConditionAttribute.cs @@ -32,7 +32,9 @@ public OSConditionAttribute(ConditionMode mode, OperatingSystems operatingSystem : base(mode) { _operatingSystems = operatingSystems; - IgnoreMessage = $"Test is only supported on {operatingSystems}"; + IgnoreMessage = mode == ConditionMode.Include + ? $"Test is only supported on {operatingSystems}" + : $"Test is not supported on {operatingSystems}"; } /// From b58d8e7aaac2011a2d0c3f254d85f5c742634a00 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Tue, 20 May 2025 09:10:49 +0200 Subject: [PATCH 011/541] Delete unused classes (#5590) --- .../ServerMode/JsonRpc/Json/Json.cs | 7 ----- .../Json/JsonCollectionDeserializer.cs | 29 ----------------- .../Json/JsonPropertyBagDeserializer.cs | 14 --------- .../ServerMode/JsonTests.cs | 31 +------------------ 4 files changed, 1 insertion(+), 80 deletions(-) delete mode 100644 src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/Json/JsonPropertyBagDeserializer.cs diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/Json/Json.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/Json/Json.cs index d7b1b73607..cac6d8afaa 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/Json/Json.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/Json/Json.cs @@ -639,13 +639,6 @@ public T Deserialize(ReadOnlyMemory utf8Json) return Bind(document.RootElement, null); } - internal T Bind(IEnumerable properties) - => !_deserializers.TryGetValue(typeof(T), out JsonDeserializer? deserializer) - ? throw new InvalidOperationException($"Cannot find deserializer for {typeof(T)}.") - : deserializer is not JsonPropertyCollectionDeserializer propertyBagDeserializer - ? throw new InvalidOperationException("we need property bag deserializer") - : propertyBagDeserializer.CreateObject(this, properties); - internal T Bind(JsonElement element, string? property = null) { if (property is not null) diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/Json/JsonCollectionDeserializer.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/Json/JsonCollectionDeserializer.cs index b22ae843f5..53570dcbcf 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/Json/JsonCollectionDeserializer.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/Json/JsonCollectionDeserializer.cs @@ -9,32 +9,3 @@ internal abstract class JsonCollectionDeserializer : JsonDeserializ { internal abstract TCollection CreateObject(Json json, JsonElement element); } - -internal sealed class JsonCollectionDeserializer(Func createCollection, Action addItem) : JsonCollectionDeserializer - where TCollection : ICollection -{ - private readonly Func _createCollection = createCollection; - private readonly Action _addItem = addItem; - - public TCollection CreateCollection(JsonElement jsonElement) - => _createCollection(jsonElement); - - public void AddItem(TCollection collection, TItem item) - => _addItem(collection, item); - - internal override TCollection CreateObject(Json json, JsonElement element) - { - if (element.ValueKind == JsonValueKind.Null) - { - return default!; - } - - TCollection collection = CreateCollection(element); - foreach (JsonElement item in element.EnumerateArray()) - { - AddItem(collection, json.Bind(item)); - } - - return collection; - } -} diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/Json/JsonPropertyBagDeserializer.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/Json/JsonPropertyBagDeserializer.cs deleted file mode 100644 index 08e5e8c4c9..0000000000 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/Json/JsonPropertyBagDeserializer.cs +++ /dev/null @@ -1,14 +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.Text.Json; - -namespace Microsoft.Testing.Platform.ServerMode.Json; - -internal sealed class JsonPropertyCollectionDeserializer(Func, T> creator) : JsonDeserializer -{ - private readonly Func, T> _creator = creator; - - internal T CreateObject(Json json, IEnumerable properties) - => _creator(json, properties); -} diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/ServerMode/JsonTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/ServerMode/JsonTests.cs index cfa9e68ac5..e7afcf77ec 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/ServerMode/JsonTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/ServerMode/JsonTests.cs @@ -125,43 +125,14 @@ public void DeserializePerson() [typeof(Person)] = new JsonElementDeserializer((json, jsonElement) => new Person { Name = json.Bind(jsonElement, "name"), - Children = json.Bind>(jsonElement, "children"), }), - - [typeof(List)] = new JsonCollectionDeserializer, Person>(_ => [], (c, i) => c.Add(i)), }); // Act - Person actual = json.Deserialize(new("""{"name":"Thomas","children":[{"name":"Ruth","children":null}]}""".ToCharArray())); + Person actual = json.Deserialize(new("""{"name":"Thomas"}""".ToCharArray())); // Assert Assert.AreEqual("Thomas", actual.Name); - Assert.AreEqual(1, actual.Children!.Count); - Assert.AreEqual("Ruth", actual.Children![0].Name); - Assert.IsNull(actual.Children![0].Children); - } - - [TestMethod] - public void DeserializePersonList() - { - // Arrange - Json json = new(null, new Dictionary - { - [typeof(Person)] = new JsonElementDeserializer((json, jsonElement) => new Person - { - Name = json.Bind(jsonElement, "name"), - Children = json.Bind>(jsonElement, "children"), - }), - - [typeof(List)] = new JsonCollectionDeserializer, Person>(_ => [], (c, i) => c.Add(i)), - }); - - // Act - List actual = json.Deserialize>(new("""[{"name":"Thomas","children":[{"name":"Ruth","children":null}]}]""".ToCharArray())); - - // Assert - Assert.AreEqual(1, actual.Count); - Assert.AreEqual("Thomas", actual[0].Name); } private sealed class Person From 9f043c6725409d3acc9871983460cbf8a669c6c9 Mon Sep 17 00:00:00 2001 From: Copilot <198982749+Copilot@users.noreply.github.com> Date: Tue, 20 May 2025 09:35:33 +0000 Subject: [PATCH 012/541] Fix MSTEST0004 analyzer to recognize TestClass-derived attributes (#5600) Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: Youssef1313 <31348972+Youssef1313@users.noreply.github.com> Co-authored-by: Youssef Victor --- .../PublicTypeShouldBeTestClassAnalyzer.cs | 2 +- ...ublicTypeShouldBeTestClassAnalyzerTests.cs | 36 +++++++++++++++++++ 2 files changed, 37 insertions(+), 1 deletion(-) diff --git a/src/Analyzers/MSTest.Analyzers/PublicTypeShouldBeTestClassAnalyzer.cs b/src/Analyzers/MSTest.Analyzers/PublicTypeShouldBeTestClassAnalyzer.cs index ae2e53ad40..4fc74ef968 100644 --- a/src/Analyzers/MSTest.Analyzers/PublicTypeShouldBeTestClassAnalyzer.cs +++ b/src/Analyzers/MSTest.Analyzers/PublicTypeShouldBeTestClassAnalyzer.cs @@ -63,7 +63,7 @@ private static void AnalyzeSymbol(SymbolAnalysisContext context, INamedTypeSymbo } // The type is public, ensure this is a test class. - if (!namedTypeSymbol.GetAttributes().Any(attr => SymbolEqualityComparer.Default.Equals(attr.AttributeClass, testClassAttributeSymbol))) + if (!namedTypeSymbol.GetAttributes().Any(attr => attr.AttributeClass.Inherits(testClassAttributeSymbol))) { context.ReportDiagnostic(namedTypeSymbol.CreateDiagnostic(Rule, namedTypeSymbol.Name)); } diff --git a/test/UnitTests/MSTest.Analyzers.UnitTests/PublicTypeShouldBeTestClassAnalyzerTests.cs b/test/UnitTests/MSTest.Analyzers.UnitTests/PublicTypeShouldBeTestClassAnalyzerTests.cs index b2438a3742..6bcbaaf960 100644 --- a/test/UnitTests/MSTest.Analyzers.UnitTests/PublicTypeShouldBeTestClassAnalyzerTests.cs +++ b/test/UnitTests/MSTest.Analyzers.UnitTests/PublicTypeShouldBeTestClassAnalyzerTests.cs @@ -62,6 +62,42 @@ await VerifyCS.VerifyCodeFixAsync( fixedCode); } + [TestMethod] + public async Task WhenClassIsPublicAndHasSTATestClassAttribute_NoDiagnostic() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [STATestClass] + public class MyTestClass + { + } + """; + + await VerifyCS.VerifyCodeFixAsync( + code, + code); + } + + [TestMethod] + public async Task WhenClassIsPublicAndHasDerivedTestClassAttribute_NoDiagnostic() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + internal sealed class MyTestClassAttribute : TestClassAttribute; + + [MyTestClass] + public class MyTestClass + { + } + """; + + await VerifyCS.VerifyCodeFixAsync( + code, + code); + } + [TestMethod] public async Task WhenClassIsPublicAndNotClass_NoDiagnostic() { From b6024f2d9bd5bea923854439674c98de1b83d81c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Jare=C5=A1?= Date: Tue, 20 May 2025 12:16:11 +0200 Subject: [PATCH 013/541] Update versions in samples (#5603) --- samples/public/Directory.Build.props | 10 +++++----- samples/public/global.json | 2 +- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/samples/public/Directory.Build.props b/samples/public/Directory.Build.props index 0cee8689b5..9f5290fd47 100644 --- a/samples/public/Directory.Build.props +++ b/samples/public/Directory.Build.props @@ -2,12 +2,12 @@ 9.0.0 - 17.13.1 - 3.8.3 - 1.0.0-alpha.25167.5 + 17.14.2 + 3.9.0 + 1.0.0-alpha.25256.6 1.50.0 - 1.6.3 - 17.13.0 + 1.7.0 + 17.14.0 diff --git a/samples/public/global.json b/samples/public/global.json index 11074d3c4b..ccda54a3fa 100644 --- a/samples/public/global.json +++ b/samples/public/global.json @@ -1,5 +1,5 @@ { "msbuild-sdks": { - "MSTest.Sdk": "3.8.1" + "MSTest.Sdk": "3.9.0" } } From 06fcf131a45db8f43a009c166b754c85de90feaa Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Tue, 20 May 2025 12:25:28 +0200 Subject: [PATCH 014/541] Update SDK to 10.0.100-preview.5.25269.23 (#5602) --- global.json | 4 ++-- .../RoslynAnalyzerHelpers/IOperationExtensions.cs | 1 + 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/global.json b/global.json index 1814242c89..73d10b19cb 100644 --- a/global.json +++ b/global.json @@ -1,6 +1,6 @@ { "tools": { - "dotnet": "10.0.100-preview.4.25206.7", + "dotnet": "10.0.100-preview.5.25269.23", "runtimes": { "dotnet": [ "3.1.32", @@ -23,7 +23,7 @@ } }, "sdk": { - "version": "10.0.100-preview.4.25206.7", + "version": "10.0.100-preview.5.25269.23", "allowPrerelease": true, "rollForward": "latestFeature" }, diff --git a/src/Analyzers/MSTest.Analyzers/RoslynAnalyzerHelpers/IOperationExtensions.cs b/src/Analyzers/MSTest.Analyzers/RoslynAnalyzerHelpers/IOperationExtensions.cs index b4f48fb09f..e3ec94bd4c 100644 --- a/src/Analyzers/MSTest.Analyzers/RoslynAnalyzerHelpers/IOperationExtensions.cs +++ b/src/Analyzers/MSTest.Analyzers/RoslynAnalyzerHelpers/IOperationExtensions.cs @@ -5,6 +5,7 @@ using Microsoft.CodeAnalysis.Operations; namespace MSTest.Analyzers.RoslynAnalyzerHelpers; + internal static class IOperationExtensions { public static ISymbol? GetReferencedMemberOrLocalOrParameter(this IOperation? operation) => operation switch From c4cba5b494f111eddeabbede34cbbf99bbe8ac8e Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Tue, 20 May 2025 22:37:17 +1000 Subject: [PATCH 015/541] use char based APIs in TryUnescape (#5608) --- src/Platform/Microsoft.Testing.Platform/CommandLine/Parser.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Platform/CommandLine/Parser.cs b/src/Platform/Microsoft.Testing.Platform/CommandLine/Parser.cs index 61551e2c83..0e95742763 100644 --- a/src/Platform/Microsoft.Testing.Platform/CommandLine/Parser.cs +++ b/src/Platform/Microsoft.Testing.Platform/CommandLine/Parser.cs @@ -145,7 +145,7 @@ static bool TryUnescape(string input, string? option, IEnvironment environment, // Enclosing characters in single-quotes ( '' ) shall preserve the literal value of each character within the single-quotes. // A single-quote cannot occur within single-quotes. - if (input.StartsWith(@"'", StringComparison.OrdinalIgnoreCase) && input.EndsWith(@"'", StringComparison.OrdinalIgnoreCase)) + if (input.StartsWith('\'') && input.EndsWith('\'')) { if (input.IndexOf('\'', 1, input.Length - 2) != -1) { @@ -165,7 +165,7 @@ static bool TryUnescape(string input, string? option, IEnvironment environment, // * The shall retain its special meaning introducing parameter expansion. [NOT SUPPORTED] // * The backslash shall retain its special meaning as an escape character only when followed by one of the following characters when considered special: // $ ` " \ - if (input.StartsWith("\"", StringComparison.OrdinalIgnoreCase) && input.EndsWith("\"", StringComparison.OrdinalIgnoreCase)) + if (input.StartsWith('"') && input.EndsWith('"')) { unescapedArg = input[1..^1].Replace(@"\\", "\\") .Replace(@"\""", "\"") From 17ad76666880625321083a0a1d12925a6db2eb41 Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Tue, 20 May 2025 22:40:11 +1000 Subject: [PATCH 016/541] attribute param nullability in TryUnescape (#5609) --- .../Microsoft.Testing.Platform/CommandLine/Parser.cs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Platform/CommandLine/Parser.cs b/src/Platform/Microsoft.Testing.Platform/CommandLine/Parser.cs index 0e95742763..8e4d3e44b1 100644 --- a/src/Platform/Microsoft.Testing.Platform/CommandLine/Parser.cs +++ b/src/Platform/Microsoft.Testing.Platform/CommandLine/Parser.cs @@ -93,11 +93,11 @@ private static CommandLineParseResult Parse(List args, IEnvironment envi { if (TryUnescape(currentArg.Trim(), currentOption, environment, out string? unescapedArg, out string? error)) { - currentOptionArguments.Add(unescapedArg!); + currentOptionArguments.Add(unescapedArg); } else { - errors.Add(error!); + errors.Add(error); } currentArg = null; @@ -114,11 +114,11 @@ private static CommandLineParseResult Parse(List args, IEnvironment envi { if (TryUnescape(currentArg.Trim(), currentOption, environment, out string? unescapedArg, out string? error)) { - currentOptionArguments.Add(unescapedArg!); + currentOptionArguments.Add(unescapedArg); } else { - errors.Add(error!); + errors.Add(error); } } @@ -138,7 +138,7 @@ static void ParseOptionAndSeparators(string arg, out string? currentOption, out currentOption = currentOption.TrimStart('-'); } - static bool TryUnescape(string input, string? option, IEnvironment environment, out string? unescapedArg, out string? error) + static bool TryUnescape(string input, string? option, IEnvironment environment, [NotNullWhen(true)] out string? unescapedArg, [NotNullWhen(false)] out string? error) { unescapedArg = input; error = null; From cc4c21a84bf499e062322ca09392902001bc59d5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Jare=C5=A1?= Date: Tue, 20 May 2025 15:17:07 +0200 Subject: [PATCH 017/541] Don't publish final package builds to feeds (#5599) Co-authored-by: Youssef Victor --- azure-pipelines-official.yml | 25 ++++++++++++++++--------- 1 file changed, 16 insertions(+), 9 deletions(-) diff --git a/azure-pipelines-official.yml b/azure-pipelines-official.yml index 2ead4ae47b..f7f7cdd446 100644 --- a/azure-pipelines-official.yml +++ b/azure-pipelines-official.yml @@ -90,7 +90,8 @@ extends: enablePublishTestResults: true testResultsFormat: 'vstest' enablePublishBuildAssets: true - enablePublishUsingPipelines: true + # For final version build, don't publish to internal feeds. + isAssetlessBuild: ${{ parameters.isRTM }} enableTelemetry: true jobs: - job: Windows @@ -181,13 +182,17 @@ extends: - task: NuGetAuthenticate@1 displayName: 'NuGet Authenticate to test-tools feed' - - task: 1ES.PublishNuget@1 - displayName: 'Publish NuGet packages to test-tools feed' - inputs: - # Do not push symbol packages nor Microsoft.Testing.Platform package - packageParentPath: '$(Build.SourcesDirectory)/artifacts/packages/$(_BuildConfig)' - packagesToPush: '$(Build.SourcesDirectory)/artifacts/packages/$(_BuildConfig)/**/*.nupkg;!$(Build.SourcesDirectory)/artifacts/packages/$(_BuildConfig)/**/*.symbols.nupkg;!$(Build.SourcesDirectory)/artifacts/packages/$(_BuildConfig)/NonShipping/Microsoft.Testing.Platform.*.nupkg' - publishVstsFeed: 'public/test-tools' + # Final builds should not go into test-tools package feed, so we can keep re-building them until we are ready to ship to nuget.org. + # This has to depend on the parameter and not on variable, variables are not defined early enough to be used in templating condition. + # We still need the final builds on test-tools so that internal repos can consume it, so we will publish it manually. + - ${{ if eq(parameters.isRTM, False) }}: + - task: 1ES.PublishNuget@1 + displayName: 'Publish NuGet packages to test-tools feed' + inputs: + # Do not push symbol packages nor Microsoft.Testing.Platform package + packageParentPath: '$(Build.SourcesDirectory)/artifacts/packages/$(_BuildConfig)' + packagesToPush: '$(Build.SourcesDirectory)/artifacts/packages/$(_BuildConfig)/**/*.nupkg;!$(Build.SourcesDirectory)/artifacts/packages/$(_BuildConfig)/**/*.symbols.nupkg;!$(Build.SourcesDirectory)/artifacts/packages/$(_BuildConfig)/NonShipping/Microsoft.Testing.Platform.*.nupkg' + publishVstsFeed: 'public/test-tools' - job: Linux timeoutInMinutes: 90 @@ -232,4 +237,6 @@ extends: LclSource: lclFilesfromPackage LclPackageId: 'LCL-JUNO-PROD-TESTFX' - - template: eng\common\templates-official\post-build\post-build.yml@self + # For stable versions avoid publishing them to internal feeds. + - ${{ if eq(parameters.isRTM, False) }}: + - template: eng\common\templates-official\post-build\post-build.yml@self From 34051e907f3d69f9cfa5db8881fefbe392945d8f Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Tue, 20 May 2025 21:01:10 +0200 Subject: [PATCH 018/541] Delete unused ClientTestingCapabilities (#5617) --- .../ServerMode/JsonRpc/RpcMessages.cs | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/RpcMessages.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/RpcMessages.cs index ae0efe1c4d..e975f8f469 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/RpcMessages.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/RpcMessages.cs @@ -63,8 +63,6 @@ internal sealed record ClientInfo(string Name, string Version); internal sealed record ClientCapabilities(bool DebuggerProvider); -internal sealed record ClientTestingCapabilities(bool DebuggerProvider); - internal sealed record ServerInfo(string Name, string Version); internal sealed record ServerCapabilities(ServerTestingCapabilities TestingCapabilities); From 174eccf23138523cf9cd2ce90bb1afb8fb69fb00 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Tue, 20 May 2025 21:02:17 +0200 Subject: [PATCH 019/541] Cleanup unneeded count variable in `SerializeAsync` (#5616) --- .../Microsoft.Testing.Platform/ServerMode/JsonRpc/Json/Json.cs | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/Json/Json.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/Json/Json.cs index cac6d8afaa..8c0e7fde9f 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/Json/Json.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/Json/Json.cs @@ -726,12 +726,10 @@ private async Task SerializeAsync(object? obj, Utf8JsonWriter writer) (string Key, object? Value)[]? properties = objectConverter.Properties(obj); if (properties is not null) { - int count = 1; foreach ((string property, object? value) in properties) { writer.WritePropertyName(property); await SerializeAsync(value, writer); - count++; } } From ce77f199bc3f388f9526eec9b4ae19c8b99c568a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Jare=C5=A1?= Date: Tue, 20 May 2025 21:02:45 +0200 Subject: [PATCH 020/541] Fix changelog date (#5585) --- docs/Changelog-Platform.md | 32 ++-- docs/Changelog.md | 146 +++++++++--------- docs/README.md | 2 +- ...DataSource-Attribute-VS-ITestDataSource.md | 2 +- 4 files changed, 91 insertions(+), 91 deletions(-) diff --git a/docs/Changelog-Platform.md b/docs/Changelog-Platform.md index 2b7c67ebba..8a03893f3a 100644 --- a/docs/Changelog-Platform.md +++ b/docs/Changelog-Platform.md @@ -4,9 +4,9 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) -## [1.7.0] - 2025-03-17 +## [1.7.0] - 2025-05-20 -See full log [here](https://github.com/microsoft/testfx/compare/v3.8.3...v3.9.0) +See full log [of v3.8.3...v3.9.0](https://github.com/microsoft/testfx/compare/v3.8.3...v3.9.0) ### Added @@ -90,7 +90,7 @@ See full log [here](https://github.com/microsoft/testfx/compare/v3.8.3...v3.9.0) ## [1.6.3] - 2025-03-17 -See full log [here](https://github.com/microsoft/testfx/compare/v3.8.2...v3.8.3) +See full log [of v3.8.2...v3.8.3](https://github.com/microsoft/testfx/compare/v3.8.2...v3.8.3) ### Fixed @@ -119,7 +119,7 @@ See full log [here](https://github.com/microsoft/testfx/compare/v3.8.2...v3.8.3) ## [1.6.2] - 2025-02-19 -See full log [here](https://github.com/microsoft/testfx/compare/v3.8.1...v3.8.2) +See full log [of v3.8.1...v3.8.2](https://github.com/microsoft/testfx/compare/v3.8.1...v3.8.2) ### Fixed @@ -140,7 +140,7 @@ See full log [here](https://github.com/microsoft/testfx/compare/v3.8.1...v3.8.2) ## [1.6.1] - 2025-02-18 -See full log [here](https://github.com/microsoft/testfx/compare/v3.8.0...v3.8.1) +See full log [of 3.8.0...v3.8.1](https://github.com/microsoft/testfx/compare/v3.8.0...v3.8.1) ### Fixed @@ -163,7 +163,7 @@ See full log [here](https://github.com/microsoft/testfx/compare/v3.8.0...v3.8.1) ## [1.6.0] - 2025-02-12 -See full log [here](https://github.com/microsoft/testfx/compare/v3.7.3...v3.8.0) +See full log [of v3.7.3...v3.8.0](https://github.com/microsoft/testfx/compare/v3.7.3...v3.8.0) ### Added @@ -201,7 +201,7 @@ See full log [here](https://github.com/microsoft/testfx/compare/v3.7.3...v3.8.0) ## [1.5.3] - 2025-01-27 -See full log [here](https://github.com/microsoft/testfx/compare/v3.7.2...v3.7.3) +See full log [of v3.7.2...v3.7.3](https://github.com/microsoft/testfx/compare/v3.7.2...v3.7.3) ### Fixed @@ -222,7 +222,7 @@ See full log [here](https://github.com/microsoft/testfx/compare/v3.7.2...v3.7.3) ## [1.5.2] - 2025-01-21 -See full log [here](https://github.com/microsoft/testfx/compare/v3.7.1...v3.7.2) +See full log [of v3.7.1...v3.7.2](https://github.com/microsoft/testfx/compare/v3.7.1...v3.7.2) ### Fixed @@ -243,7 +243,7 @@ See full log [here](https://github.com/microsoft/testfx/compare/v3.7.1...v3.7.2) ## [1.5.1] - 2025-01-13 -See full log [here](https://github.com/microsoft/testfx/compare/v3.7.0...v3.7.1) +See full log [of v3.7.0...v3.7.1](https://github.com/microsoft/testfx/compare/v3.7.0...v3.7.1) ### Fixed @@ -265,7 +265,7 @@ See full log [here](https://github.com/microsoft/testfx/compare/v3.7.0...v3.7.1) ## [1.5.0] - 2024-12-20 -See full log [here](https://github.com/microsoft/testfx/compare/v1.4.3...v1.5.0) +See full log [of v1.4.3...v1.5.0](https://github.com/microsoft/testfx/compare/v1.4.3...v1.5.0) ### Added @@ -320,7 +320,7 @@ See full log [here](https://github.com/microsoft/testfx/compare/v1.4.3...v1.5.0) ## [1.4.3] - 2024-11-12 -See full log [here](https://github.com/microsoft/testanywhere/compare/v1.4.2...v1.4.3) +See full log [of v1.4.2...v1.4.3](https://github.com/microsoft/testanywhere/compare/v1.4.2...v1.4.3) ### Fixed @@ -343,7 +343,7 @@ See full log [here](https://github.com/microsoft/testanywhere/compare/v1.4.2...v ## [1.4.2] - 2024-10-31 -See full log [here](https://github.com/microsoft/testanywhere/compare/v1.4.1...v1.4.2) +See full log [of v1.4.1...v1.4.2](https://github.com/microsoft/testanywhere/compare/v1.4.1...v1.4.2) ### Fixed @@ -366,7 +366,7 @@ See full log [here](https://github.com/microsoft/testanywhere/compare/v1.4.1...v ## [1.4.1] - 2024-10-03 -See full log [here](https://github.com/microsoft/testanywhere/compare/v1.4.0...v1.4.1) +See full log [of v1.4.0...v1.4.1](https://github.com/microsoft/testanywhere/compare/v1.4.0...v1.4.1) ### Fixed @@ -389,7 +389,7 @@ See full log [here](https://github.com/microsoft/testanywhere/compare/v1.4.0...v ## [1.4.0] - 2024-09-11 -See full log [here](https://github.com/microsoft/testanywhere/compare/v1.3.2...v1.4.0) +See full log [of v1.3.2...v1.4.0](https://github.com/microsoft/testanywhere/compare/v1.3.2...v1.4.0) ### Added @@ -461,7 +461,7 @@ See full log [here](https://github.com/microsoft/testanywhere/compare/v1.3.2...v ## [1.3.2] - 2024-08-05 -See full log [here](https://github.com/microsoft/testanywhere/compare/v1.3.1...v1.3.2) +See full log [of v1.3.1...v1.3.2](https://github.com/microsoft/testanywhere/compare/v1.3.1...v1.3.2) ### Fixed @@ -485,7 +485,7 @@ See full log [here](https://github.com/microsoft/testanywhere/compare/v1.3.1...v ## [1.3.1] - 2024-07-15 -See full log [here](https://github.com/microsoft/testanywhere/compare/v1.2.1...v1.3.1) +See full log [of v1.2.1...v1.3.1](https://github.com/microsoft/testanywhere/compare/v1.2.1...v1.3.1) ### Added diff --git a/docs/Changelog.md b/docs/Changelog.md index 4e38beb338..204a1d9946 100644 --- a/docs/Changelog.md +++ b/docs/Changelog.md @@ -4,9 +4,9 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) -## [3.9.0] - 2025-05-07 +## [3.9.0] - 2025-05-20 -See full log [here](https://github.com/microsoft/testfx/compare/v3.8.3...v3.9.0) +See full log [of v3.8.3...v3.9.0](https://github.com/microsoft/testfx/compare/v3.8.3...v3.9.0) ### Added @@ -80,7 +80,7 @@ See full log [here](https://github.com/microsoft/testfx/compare/v3.8.3...v3.9.0) ## [3.8.3] - 2025-03-17 -See full log [here](https://github.com/microsoft/testfx/compare/v3.8.2...v3.8.3) +See full log [of v3.8.2...v3.8.3](https://github.com/microsoft/testfx/compare/v3.8.2...v3.8.3) ### Fixed @@ -107,7 +107,7 @@ See full log [here](https://github.com/microsoft/testfx/compare/v3.8.2...v3.8.3) ## [3.8.2] - 2025-02-19 -See full log [here](https://github.com/microsoft/testfx/compare/v3.8.1...v3.8.2) +See full log [of v3.8.1...v3.8.2](https://github.com/microsoft/testfx/compare/v3.8.1...v3.8.2) ### Fixed @@ -130,7 +130,7 @@ See full log [here](https://github.com/microsoft/testfx/compare/v3.8.1...v3.8.2) ## [3.8.1] - 2025-02-18 -See full log [here](https://github.com/microsoft/testfx/compare/v3.8.0...v3.8.1) +See full log [of v3.8.0...v3.8.1](https://github.com/microsoft/testfx/compare/v3.8.0...v3.8.1) ### Fixed @@ -157,7 +157,7 @@ See full log [here](https://github.com/microsoft/testfx/compare/v3.8.0...v3.8.1) ## [3.8.0] - 2025-02-12 -See full log [here](https://github.com/microsoft/testfx/compare/v3.7.3...v3.8.0) +See full log [of v3.7.3...v3.8.0](https://github.com/microsoft/testfx/compare/v3.7.3...v3.8.0) ### Added @@ -268,7 +268,7 @@ See full log [here](https://github.com/microsoft/testfx/compare/v3.7.3...v3.8.0) ## [3.7.3] - 2025-01-27 -See full log [here](https://github.com/microsoft/testfx/compare/v3.7.2...v3.7.3) +See full log [of v3.7.2...v3.7.3](https://github.com/microsoft/testfx/compare/v3.7.2...v3.7.3) ### Fixed @@ -289,7 +289,7 @@ See full log [here](https://github.com/microsoft/testfx/compare/v3.7.2...v3.7.3) ## [3.7.2] - 2025-01-21 -See full log [here](https://github.com/microsoft/testfx/compare/v3.7.1...v3.7.2) +See full log [of v3.7.1...v3.7.2](https://github.com/microsoft/testfx/compare/v3.7.1...v3.7.2) ### Fixed @@ -311,7 +311,7 @@ See full log [here](https://github.com/microsoft/testfx/compare/v3.7.1...v3.7.2) ## [3.7.1] - 2024-01-13 -See full log [here](https://github.com/microsoft/testfx/compare/v3.7.0...v3.7.1) +See full log [of v3.7.0...v3.7.1](https://github.com/microsoft/testfx/compare/v3.7.0...v3.7.1) ### Fixed @@ -340,7 +340,7 @@ See full log [here](https://github.com/microsoft/testfx/compare/v3.7.0...v3.7.1) ## [3.7.0] - 2024-12-20 -See full log [here](https://github.com/microsoft/testfx/compare/v3.6.4...v3.7.0) +See full log [of v3.6.4...v3.7.0](https://github.com/microsoft/testfx/compare/v3.6.4...v3.7.0) ### Added @@ -470,7 +470,7 @@ See full log [here](https://github.com/microsoft/testfx/compare/v3.6.4...v3.7.0) ## [3.6.4] - 2024-12-03 -See full log [here](https://github.com/microsoft/testfx/compare/v3.6.3...v3.6.4) +See full log [of v3.6.3...v3.6.4](https://github.com/microsoft/testfx/compare/v3.6.3...v3.6.4) ### Fixed @@ -492,7 +492,7 @@ See full log [here](https://github.com/microsoft/testfx/compare/v3.6.3...v3.6.4) ## [3.6.3] - 2024-11-12 -See full log [here](https://github.com/microsoft/testfx/compare/v3.6.2...v3.6.3) +See full log [of v3.6.2...v3.6.3](https://github.com/microsoft/testfx/compare/v3.6.2...v3.6.3) ### Fixed @@ -513,7 +513,7 @@ See full log [here](https://github.com/microsoft/testfx/compare/v3.6.2...v3.6.3) ## [3.6.2] - 2024-10-31 -See full log [here](https://github.com/microsoft/testfx/compare/v3.6.1...v3.6.2) +See full log [of v3.6.1...v3.6.2](https://github.com/microsoft/testfx/compare/v3.6.1...v3.6.2) ### Fixed @@ -539,7 +539,7 @@ See full log [here](https://github.com/microsoft/testfx/compare/v3.6.1...v3.6.2) ## [3.6.1] - 2024-10-03 -See full log [here](https://github.com/microsoft/testfx/compare/v3.6.0...v3.6.1) +See full log [of v3.6.0...v3.6.1](https://github.com/microsoft/testfx/compare/v3.6.0...v3.6.1) ### Fixed @@ -566,7 +566,7 @@ See full log [here](https://github.com/microsoft/testfx/compare/v3.6.0...v3.6.1) ## [3.6.0] - 2024-09-11 -See full log [here](https://github.com/microsoft/testfx/compare/v3.5.2...v3.6.0) +See full log [of v3.5.2...v3.6.0](https://github.com/microsoft/testfx/compare/v3.5.2...v3.6.0) ### Added @@ -650,7 +650,7 @@ See full log [here](https://github.com/microsoft/testfx/compare/v3.5.2...v3.6.0) ## [3.5.2] - 2024-08-13 -See full log [here](https://github.com/microsoft/testfx/compare/v3.5.1...v3.5.2) +See full log [of v3.5.1...v3.5.2](https://github.com/microsoft/testfx/compare/v3.5.1...v3.5.2) ### Fixed @@ -671,7 +671,7 @@ See full log [here](https://github.com/microsoft/testfx/compare/v3.5.1...v3.5.2) ## [3.5.1] - 2024-08-05 -See full log [here](https://github.com/microsoft/testfx/compare/v3.5.0...v3.5.1) +See full log [of v3.5.0...v3.5.1](https://github.com/microsoft/testfx/compare/v3.5.0...v3.5.1) ### Fixed @@ -694,7 +694,7 @@ See full log [here](https://github.com/microsoft/testfx/compare/v3.5.0...v3.5.1) ## [3.5.0] - 2024-07-15 -See full log [here](https://github.com/microsoft/testfx/compare/v3.4.3...v3.5.0) +See full log [of v3.4.3...v3.5.0](https://github.com/microsoft/testfx/compare/v3.4.3...v3.5.0) ### Added @@ -798,7 +798,7 @@ See full log [here](https://github.com/microsoft/testfx/compare/v3.4.3...v3.5.0) ## [3.4.3] - 2024-05-30 -See full log [here](https://github.com/microsoft/testfx/compare/v3.4.2...v3.4.3) +See full log [of v3.4.2...v3.4.3](https://github.com/microsoft/testfx/compare/v3.4.2...v3.4.3) ### Fixed @@ -819,7 +819,7 @@ See full log [here](https://github.com/microsoft/testfx/compare/v3.4.2...v3.4.3) ## [3.4.2] - 2024-05-30 -See full log [here](https://github.com/microsoft/testfx/compare/v3.4.1...v3.4.2) +See full log [of v3.4.1...v3.4.2](https://github.com/microsoft/testfx/compare/v3.4.1...v3.4.2) ### Fixed @@ -842,7 +842,7 @@ See full log [here](https://github.com/microsoft/testfx/compare/v3.4.1...v3.4.2) ## [3.4.1] - 2024-05-27 -See full log [here](https://github.com/microsoft/testfx/compare/v3.4.0...v3.4.1) +See full log [of v3.4.0...v3.4.1](https://github.com/microsoft/testfx/compare/v3.4.0...v3.4.1) ### Fixed @@ -863,7 +863,7 @@ See full log [here](https://github.com/microsoft/testfx/compare/v3.4.0...v3.4.1) ## [3.4.0] - 2024-05-23 -See full log [here](https://github.com/microsoft/testfx/compare/v3.3.1...v3.4.0) +See full log [of v3.3.1...v3.4.0](https://github.com/microsoft/testfx/compare/v3.3.1...v3.4.0) ### Added @@ -958,7 +958,7 @@ See full log [here](https://github.com/microsoft/testfx/compare/v3.3.1...v3.4.0) ## [3.3.1] - 2024-04-04 -See full log [here](https://github.com/microsoft/testfx/compare/v3.3.0...v3.3.1) +See full log [of v3.3.0...v3.3.1](https://github.com/microsoft/testfx/compare/v3.3.0...v3.3.1) ### Fixed @@ -979,7 +979,7 @@ See full log [here](https://github.com/microsoft/testfx/compare/v3.3.0...v3.3.1) ## [3.3.0] - 2024-04-03 -See full log [here](https://github.com/microsoft/testfx/compare/v3.2.2...v3.3.0) +See full log [of v3.2.2...v3.3.0](https://github.com/microsoft/testfx/compare/v3.2.2...v3.3.0) ### Added @@ -1052,7 +1052,7 @@ See full log [here](https://github.com/microsoft/testfx/compare/v3.2.2...v3.3.0) ## [3.2.2] - 2024-02-22 -See full log [here](https://github.com/microsoft/testfx/compare/v3.2.1...v3.2.2) +See full log [of v3.2.1...v3.2.2](https://github.com/microsoft/testfx/compare/v3.2.1...v3.2.2) ### Fixed @@ -1076,7 +1076,7 @@ See full log [here](https://github.com/microsoft/testfx/compare/v3.2.1...v3.2.2) ## [3.2.1] - 2024-02-13 -See full log [here](https://github.com/microsoft/testfx/compare/v3.2.0...v.3.2.1) +See full log [of v3.2.0...v.3.2.1](https://github.com/microsoft/testfx/compare/v3.2.0...v.3.2.1) ### Fixed @@ -1106,7 +1106,7 @@ See full log [here](https://github.com/microsoft/testfx/compare/v3.2.0...v.3.2.1 ## [3.2.0] - 2024-01-24 -See full log [here](https://github.com/microsoft/testfx/compare/v3.1.1...v.3.2.0) +See full log [of v3.1.1...v.3.2.0](https://github.com/microsoft/testfx/compare/v3.1.1...v.3.2.0) ### Added @@ -1187,7 +1187,7 @@ See full log [here](https://github.com/microsoft/testfx/compare/v3.1.1...v.3.2.0 ## [3.2.0-preview.24069.3] - 2024-01-19 -See full log [here](https://github.com/microsoft/testfx/compare/v3.2.0-preview.23623.1...v3.2.0-preview.24069.3) +See full log [of v3.2.0-preview.23623.1...v3.2.0-preview.24069.3](https://github.com/microsoft/testfx/compare/v3.2.0-preview.23623.1...v3.2.0-preview.24069.3) ### Added @@ -1240,7 +1240,7 @@ See full log [here](https://github.com/microsoft/testfx/compare/v3.2.0-preview.2 ## [3.2.0-preview.23623.1] - 2023-12-23 -See full log [here](https://github.com/Microsoft/testfx/compare/v3.2.0-preview.23622.1...3.2.0-preview.23623.1) +See full log [of v3.2.0-preview.23622.1...3.2.0-preview.23623.1](https://github.com/microsoft/testfx/compare/v3.2.0-preview.23622.1...3.2.0-preview.23623.1) ### Fixed @@ -1255,7 +1255,7 @@ See full log [here](https://github.com/Microsoft/testfx/compare/v3.2.0-preview.2 ## [3.2.0-preview.23622.1] - 2023-12-22 -See full log [here](https://github.com/Microsoft/testfx/compare/v3.1.1...v3.2.0-preview.23622.1) +See full log [of v3.1.1...v3.2.0-preview.23622.1](https://github.com/microsoft/testfx/compare/v3.1.1...v3.2.0-preview.23622.1) ### Added @@ -1307,7 +1307,7 @@ See full log [here](https://github.com/Microsoft/testfx/compare/v3.1.1...v3.2.0- * Artifact `3.1.0` was corrupted during pipeline and for security reasons we cannot regenerate it. -See full log [here](https://github.com/Microsoft/testfx/compare/v3.1.0...v3.1.1) +See full log [of v3.1.0...v3.1.1](https://github.com/microsoft/testfx/compare/v3.1.0...v3.1.1) ### Artifacts @@ -1317,7 +1317,7 @@ See full log [here](https://github.com/Microsoft/testfx/compare/v3.1.0...v3.1.1) ## [3.1.0] - 2023-07-14 -See full log [here](https://github.com/Microsoft/testfx/compare/v3.0.4...v3.1.0) +See full log [of v3.0.4...v3.1.0](https://github.com/microsoft/testfx/compare/v3.0.4...v3.1.0) ### Added @@ -1363,7 +1363,7 @@ See full log [here](https://github.com/Microsoft/testfx/compare/v3.0.4...v3.1.0) ## [3.0.4] - 2023-06-01 -See full log [here](https://github.com/microsoft/testfx/compare/v3.0.3...v3.0.4) +See full log [of v3.0.3...v3.0.4](https://github.com/microsoft/testfx/compare/v3.0.3...v3.0.4) ### Fixed @@ -1378,7 +1378,7 @@ See full log [here](https://github.com/microsoft/testfx/compare/v3.0.3...v3.0.4) ## [3.0.3] - 2023-05-24 -See full log [here](https://github.com/Microsoft/testfx/compare/v3.0.2...v3.0.3) +See full log [of v3.0.2...v3.0.3](https://github.com/microsoft/testfx/compare/v3.0.2...v3.0.3) ### Changed @@ -1399,7 +1399,7 @@ See full log [here](https://github.com/Microsoft/testfx/compare/v3.0.2...v3.0.3) ## [3.0.2] - 2022-12-27 -See full log [here](https://github.com/microsoft/testfx/compare/v3.0.1...v3.0.2) +See full log [of v3.0.1...v3.0.2](https://github.com/microsoft/testfx/compare/v3.0.1...v3.0.2) ### Fixed @@ -1413,7 +1413,7 @@ See full log [here](https://github.com/microsoft/testfx/compare/v3.0.1...v3.0.2) ## [3.0.1] - 2022-12-20 -See full log [here](https://github.com/microsoft/testfx/compare/v3.0.0...v3.0.1) +See full log [of v3.0.0...v3.0.1](https://github.com/microsoft/testfx/compare/v3.0.0...v3.0.1) ### Fixed @@ -1436,7 +1436,7 @@ See full log [here](https://github.com/microsoft/testfx/compare/v3.0.0...v3.0.1) ## [3.0.0] - 2022-12-06 -See full log [here](https://github.com/microsoft/testfx/compare/v2.2.10...v3.0.0) +See full log [of v2.2.10...v3.0.0](https://github.com/microsoft/testfx/compare/v2.2.10...v3.0.0) Breaking changes announcements [#1274](https://github.com/microsoft/testfx/issues/1274) @@ -1493,7 +1493,7 @@ Breaking changes announcements [#1274](https://github.com/microsoft/testfx/issue ## [3.0.0-preview-20221122-01] - 2022-11-23 -See full log [here](https://github.com/microsoft/testfx/compare/v3.0.0-preview-20221110-04...v3.0.0-preview-20221122-01) +See full log [of v3.0.0-preview-20221110-04...v3.0.0-preview-20221122-01](https://github.com/microsoft/testfx/compare/v3.0.0-preview-20221110-04...v3.0.0-preview-20221122-01) ### Added @@ -1537,7 +1537,7 @@ See full log [here](https://github.com/microsoft/testfx/compare/v3.0.0-preview-2 ## [3.0.0-preview-20221110-04] - 2022-11-11 -See full log [here](https://github.com/microsoft/testfx/compare/v2.3.0-preview-20220810-02...v3.0.0-preview-20221110-04) +See full log [of v2.3.0-preview-20220810-02...v3.0.0-preview-20221110-04](https://github.com/microsoft/testfx/compare/v2.3.0-preview-20220810-02...v3.0.0-preview-20221110-04) ### Added @@ -1670,7 +1670,7 @@ See full log [here](https://github.com/microsoft/testfx/compare/v2.3.0-preview-2 ## [2.3.0-preview-20220810-02] 2022-08-10 -A list of changes since last release are available [here](https://github.com/microsoft/testfx/compare/v2.2.10...v2.3.0-preview-20220810-02) +A list of changes since last release are available [of v2.2.10...v2.3.0-preview-20220810-02](https://github.com/microsoft/testfx/compare/v2.2.10...v2.3.0-preview-20220810-02) ### Added @@ -1703,7 +1703,7 @@ A list of changes since last release are available [here](https://github.com/mic ## [2.2.10] - 2022-04-26 -A list of changes since last release are available [here](https://github.com/microsoft/testfx/compare/v2.2.10-preview-20220414-01...v2.2.10) +A list of changes since last release are available [of v2.2.10-preview-20220414-01...v2.2.10](https://github.com/microsoft/testfx/compare/v2.2.10-preview-20220414-01...v2.2.10) ### Added @@ -1743,7 +1743,7 @@ A list of changes since last release are available [here](https://github.com/mic ## [2.2.9] 2022-04-08 -A list of changes since last release are available [here](https://github.com/microsoft/testfx/compare/v2.2.8...v2.2.9) +A list of changes since last release are available [of v2.2.8...v2.2.9](https://github.com/microsoft/testfx/compare/v2.2.8...v2.2.9) ### Parallel output @@ -1777,7 +1777,7 @@ Due to the way that class and assembly initialize, and cleanup are invoked, thei ## [2.2.8] - 2021-11-23 -A list of changes since last release are available [here](https://github.com/microsoft/testfx/compare/v2.2.7...v2.2.8) +A list of changes since last release are available [of v2.2.7...v2.2.8](https://github.com/microsoft/testfx/compare/v2.2.7...v2.2.8) ### Added @@ -1809,7 +1809,7 @@ A list of changes since last release are available [here](https://github.com/mic ## [2.2.7] - 2021-09-03 -A list of changes since last release are available [here](https://github.com/microsoft/testfx/compare/v2.2.6...v2.2.7) +A list of changes since last release are available [of v2.2.6...v2.2.7](https://github.com/microsoft/testfx/compare/v2.2.6...v2.2.7) ### Changed @@ -1826,7 +1826,7 @@ A list of changes since last release are available [here](https://github.com/mic ## [2.2.6] - 2021-08-25 -A list of changes since last release are available [here](https://github.com/microsoft/testfx/compare/v2.2.5...v2.2.6) +A list of changes since last release are available [of v2.2.5...v2.2.6](https://github.com/microsoft/testfx/compare/v2.2.5...v2.2.6) ### Changed @@ -1844,7 +1844,7 @@ A list of changes since last release are available [here](https://github.com/mic ## [2.2.5] - 2021-06-28 -A list of changes since last release are available [here](https://github.com/microsoft/testfx/compare/v2.2.4...v2.2.5) +A list of changes since last release are available [of v2.2.4...v2.2.5](https://github.com/microsoft/testfx/compare/v2.2.4...v2.2.5) ### Added @@ -1869,7 +1869,7 @@ A list of changes since last release are available [here](https://github.com/mic ## [2.2.4] - 2021-05-25 -A list of changes since last release are available [here](https://github.com/microsoft/testfx/compare/0b95a26282eae17f896d732381e5c77b9a603382...v2.2.4) +A list of changes since last release are available [of 0b95a26282eae17f896d732381e5c77b9a603382...v2.2.4](https://github.com/microsoft/testfx/compare/0b95a26282eae17f896d732381e5c77b9a603382...v2.2.4) ### Artifacts @@ -1878,7 +1878,7 @@ A list of changes since last release are available [here](https://github.com/mic ## [2.2.4-preview-20210331-02] - 2021-04-02 -A list of changes since last release are available [here](https://github.com/microsoft/testfx/compare/v2.2.3...v2.2.4-preview-20210331-02) +A list of changes since last release are available [of v2.2.3...v2.2.4-preview-20210331-02](https://github.com/microsoft/testfx/compare/v2.2.3...v2.2.4-preview-20210331-02) ### Added @@ -1900,7 +1900,7 @@ A list of changes since last release are available [here](https://github.com/mic ## [2.2.3] - 2021-03-16 -A list of changes since last release are available [here](https://github.com/microsoft/testfx/compare/v2.2.2...v2.2.3) +A list of changes since last release are available [of v2.2.2...v2.2.3](https://github.com/microsoft/testfx/compare/v2.2.2...v2.2.3) ### Added @@ -1913,7 +1913,7 @@ A list of changes since last release are available [here](https://github.com/mic ## [2.2.2] - 2021-03-15 -A list of changes since last release are available [here](https://github.com/microsoft/testfx/compare/v2.2.1...v2.2.2) +A list of changes since last release are available [of v2.2.1...v2.2.2](https://github.com/microsoft/testfx/compare/v2.2.1...v2.2.2) ### Added @@ -1932,7 +1932,7 @@ A list of changes since last release are available [here](https://github.com/mic ## [2.2.1] - 2021-03-01 -A list of changes since last release are available [here](https://github.com/microsoft/testfx/compare/v2.2.0-preview-20210115-03...v2.2.1) +A list of changes since last release are available [of v2.2.0-preview-20210115-03...v2.2.1](https://github.com/microsoft/testfx/compare/v2.2.0-preview-20210115-03...v2.2.1) ### Added @@ -1961,7 +1961,7 @@ A list of changes since last release are available [here](https://github.com/mic ## [2.2.0-preview-20210115-03] - 2021-01-20 -A list of changes since last release are available [here](https://github.com/microsoft/testfx/compare/v2.2.0-preview-20201126-03...v2.2.0-preview-20210115-03) +A list of changes since last release are available [of v2.2.0-preview-20201126-03...v2.2.0-preview-20210115-03](https://github.com/microsoft/testfx/compare/v2.2.0-preview-20201126-03...v2.2.0-preview-20210115-03) ### Changed @@ -1988,7 +1988,7 @@ A list of changes since last release are available [here](https://github.com/mic ## [2.2.0-preview-20201126-03] - 2020-11-26 -A list of changes since last release are available [here](https://github.com/microsoft/testfx/compare/v2.1.2...v2.2.0-preview-20201126-03) +A list of changes since last release are available [of v2.1.2...v2.2.0-preview-20201126-03](https://github.com/microsoft/testfx/compare/v2.1.2...v2.2.0-preview-20201126-03) ### Added @@ -2018,7 +2018,7 @@ A list of changes since last release are available [here](https://github.com/mic ## [2.1.2] - 2020-06-08 -A list of changes since last release are available [here](https://github.com/microsoft/testfx/compare/v2.1.1...v2.1.2) +A list of changes since last release are available [of v2.1.1...v2.1.2](https://github.com/microsoft/testfx/compare/v2.1.1...v2.1.2) ### Changed @@ -2039,7 +2039,7 @@ A list of changes since last release are available [here](https://github.com/mic ## [2.1.1] - 2020-04-01 -A list of changes since last release are available [here](https://github.com/microsoft/testfx/compare/v2.1.0...v2.1.1) +A list of changes since last release are available [of v2.1.0...v2.1.1](https://github.com/microsoft/testfx/compare/v2.1.0...v2.1.1) ### Added @@ -2066,7 +2066,7 @@ A list of changes since last release are available [here](https://github.com/mic ## [2.1.0] - 2020-02-03 -A list of changes since last release are available [here](https://github.com/microsoft/testfx/compare/v2.1.0-beta2...v2.1.0) +A list of changes since last release are available [of v2.1.0-beta2...v2.1.0](https://github.com/microsoft/testfx/compare/v2.1.0-beta2...v2.1.0) ### Changed @@ -2084,7 +2084,7 @@ A list of changes since last release are available [here](https://github.com/mic ## [2.1.0-beta2] - 2019-12-18 -A list of changes since last release are available [here](https://github.com/Microsoft/testfx/compare/v2.1.0-beta...v2.1.0-beta2) +A list of changes since last release are available [of v2.1.0-beta...v2.1.0-beta2](https://github.com/microsoft/testfx/compare/v2.1.0-beta...v2.1.0-beta2) ### Changed @@ -2097,7 +2097,7 @@ A list of changes since last release are available [here](https://github.com/Mic ## [2.1.0-beta] - 2019-11-28 -A list of changes since last release are available [here](https://github.com/Microsoft/testfx/compare/v2.0.0...v2.1.0-beta) +A list of changes since last release are available [of v2.0.0...v2.1.0-beta](https://github.com/microsoft/testfx/compare/v2.0.0...v2.1.0-beta) ### Fixed @@ -2111,7 +2111,7 @@ A list of changes since last release are available [here](https://github.com/Mic ## [2.0.0] 2019-09-03 -A list of changes since last release are available [here](https://github.com/Microsoft/testfx/compare/v2.0.0-beta4...v2.0.0) +A list of changes since last release are available [of v2.0.0-beta4...v2.0.0](https://github.com/microsoft/testfx/compare/v2.0.0-beta4...v2.0.0) ### Added @@ -2135,7 +2135,7 @@ A list of changes since last release are available [here](https://github.com/Mic ## [2.0.0-beta4] - 2019-04-10 -A list of changes since last release are available [here](https://github.com/Microsoft/testfx/compare/2.0.0-beta2...v2.0.0-beta4) +A list of changes since last release are available [of 2.0.0-beta2...v2.0.0-beta4](https://github.com/microsoft/testfx/compare/2.0.0-beta2...v2.0.0-beta4) ### Changed @@ -2150,7 +2150,7 @@ A list of changes since last release are available [here](https://github.com/Mic ## [2.0.0-beta2] - 2019-02-15 -A list of changes since last release are available [here](https://github.com/Microsoft/testfx/compare/1.4.0...2.0.0-beta2) +A list of changes since last release are available [of 1.4.0...2.0.0-beta2](https://github.com/microsoft/testfx/compare/1.4.0...2.0.0-beta2) ### Changed @@ -2165,7 +2165,7 @@ A list of changes since last release are available [here](https://github.com/Mic ## [1.4.0] - 2018-11-26 -A list of changes since last release are available [here](https://github.com/Microsoft/testfx/compare/1.4.0-beta...1.4.0) +A list of changes since last release are available [of 1.4.0-beta...1.4.0](https://github.com/microsoft/testfx/compare/1.4.0-beta...1.4.0) ### Added @@ -2187,7 +2187,7 @@ A list of changes since last release are available [here](https://github.com/Mic ## [1.4.0-beta] 2018-10-17 -A list of changes since last release are available [here](https://github.com/Microsoft/testfx/compare/1.3.2...1.4.0-beta) +A list of changes since last release are available [of 1.3.2...1.4.0-beta](https://github.com/microsoft/testfx/compare/1.3.2...1.4.0-beta) ### Added @@ -2205,7 +2205,7 @@ A list of changes since last release are available [here](https://github.com/Mic ## [1.3.2] - 2018-06-06 -A list of changes since last release are available [here](https://github.com/Microsoft/testfx/compare/v1.3.1...v1.3.2) +A list of changes since last release are available [of v1.3.1...v1.3.2](https://github.com/microsoft/testfx/compare/v1.3.1...v1.3.2) ### Changed @@ -2218,7 +2218,7 @@ A list of changes since last release are available [here](https://github.com/Mic ## [1.3.1] - 2018-05-25 -A list of changes since last release are available [here](https://github.com/Microsoft/testfx/compare/v1.3.0...v1.3.1) +A list of changes since last release are available [of v1.3.0...v1.3.1](https://github.com/microsoft/testfx/compare/v1.3.0...v1.3.1) ### Changed @@ -2232,7 +2232,7 @@ A list of changes since last release are available [here](https://github.com/Mic ## [1.3.0] - 2018-05-11 -A list of changes since last release are available [here](https://github.com/Microsoft/testfx/compare/v1.2.1...v1.3.0) +A list of changes since last release are available [of v1.2.1...v1.3.0](https://github.com/microsoft/testfx/compare/v1.2.1...v1.3.0) ### Changed @@ -2254,7 +2254,7 @@ A list of changes since last release are available [here](https://github.com/Mic ## [1.3.0-beta2] - 2018-01-15 -A list of changes since last release are available [here](https://github.com/Microsoft/testfx/compare/v1.2.0...v1.3.0-beta2) +A list of changes since last release are available [of v1.2.0...v1.3.0-beta2](https://github.com/microsoft/testfx/compare/v1.2.0...v1.3.0-beta2) ### Added @@ -2297,7 +2297,7 @@ A list of changes since last release are available [here](https://github.com/Mic ## [1.2.0] - 2017-10-11 -A list of changes since last release are available [here](https://github.com/Microsoft/testfx/compare/v1.2.0-beta3...v1.2.0) +A list of changes since last release are available [of v1.2.0-beta3...v1.2.0](https://github.com/microsoft/testfx/compare/v1.2.0-beta3...v1.2.0) ### Added @@ -2317,7 +2317,7 @@ A list of changes since last release are available [here](https://github.com/Mic ## [1.2.0-beta3] - 2017-08-09 -A list of changes since last release are available [here](https://github.com/Microsoft/testfx/compare/v1.2.0-beta...v1.2.0-beta3) +A list of changes since last release are available [of v1.2.0-beta...v1.2.0-beta3](https://github.com/microsoft/testfx/compare/v1.2.0-beta...v1.2.0-beta3) ### Added @@ -2337,7 +2337,7 @@ A list of changes since last release are available [here](https://github.com/Mic ## [1.2.0-beta] - 2017-06-29 -A list of changes since last release are available [here](https://github.com/Microsoft/testfx/compare/v1.1.18...v1.2.0-beta) +A list of changes since last release are available [of v1.1.18...v1.2.0-beta](https://github.com/microsoft/testfx/compare/v1.1.18...v1.2.0-beta) ### Changed @@ -2352,7 +2352,7 @@ A list of changes since last release are available [here](https://github.com/Mic ## [1.1.18] - 2017-06-01 -A list of changes since last release are available [here](https://github.com/Microsoft/testfx/compare/v1.1.17...v1.1.18) +A list of changes since last release are available [of v1.1.17...v1.1.18](https://github.com/microsoft/testfx/compare/v1.1.17...v1.1.18) ### Changed @@ -2370,7 +2370,7 @@ A list of changes since last release are available [here](https://github.com/Mic ## [1.1.17] - 2017-04-21 -A list of changes since last release are available [here](https://github.com/Microsoft/testfx/compare/v1.1.14...v1.1.17) +A list of changes since last release are available [of v1.1.14...v1.1.17](https://github.com/microsoft/testfx/compare/v1.1.14...v1.1.17) ### Changed @@ -2388,7 +2388,7 @@ A list of changes since last release are available [here](https://github.com/Mic ## [1.1.14] - 2017-03-31 -A list of changes since last release are available [here](https://github.com/Microsoft/testfx/compare/v1.1.13...v1.1.14) +A list of changes since last release are available [of v1.1.13...v1.1.14](https://github.com/microsoft/testfx/compare/v1.1.13...v1.1.14) ### Changed diff --git a/docs/README.md b/docs/README.md index 5096491634..f476da5c8e 100644 --- a/docs/README.md +++ b/docs/README.md @@ -4,7 +4,7 @@ The following official [learn.microsoft.com website](https://learn.microsoft.com This [blog post](https://devblogs.microsoft.com/devops/mstest-v2-now-and-ahead/) announces the vision for MSTest V2. -For API documentation refer [here](https://docs.microsoft.com/dotnet/api/microsoft.visualstudio.testtools.unittesting). +For API documentation refer [to Microsoft Documentation](https://docs.microsoft.com/dotnet/api/microsoft.visualstudio.testtools.unittesting). ## Contributing diff --git a/docs/RFCs/007-DataSource-Attribute-VS-ITestDataSource.md b/docs/RFCs/007-DataSource-Attribute-VS-ITestDataSource.md index c5e08d9f65..e40cc02454 100644 --- a/docs/RFCs/007-DataSource-Attribute-VS-ITestDataSource.md +++ b/docs/RFCs/007-DataSource-Attribute-VS-ITestDataSource.md @@ -7,7 +7,7 @@ ## Summary -This details the MSTest V2 framework attribute "DataSource" for data driven tests where test data can be present in an excel file, xml file, sql database or OleDb. You can refer documentation [here](https://docs.microsoft.com/dotnet/api/microsoft.visualstudio.testtools.unittesting.datasourceattribute) for more details. +This details the MSTest V2 framework attribute "DataSource" for data driven tests where test data can be present in an excel file, xml file, sql database or OleDb. You can refer to documentation [of datasourceattribute here](https://docs.microsoft.com/dotnet/api/microsoft.visualstudio.testtools.unittesting.datasourceattribute) for more details. ## Motivation From 93497b76adc08debe6638ab329b8be922387696f Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Tue, 20 May 2025 21:26:07 +0200 Subject: [PATCH 021/541] Cleanup TestApplicationResult (#5615) --- .../Services/TestApplicationResult.cs | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Platform/Services/TestApplicationResult.cs b/src/Platform/Microsoft.Testing.Platform/Services/TestApplicationResult.cs index 6539fae697..fd7ee1e415 100644 --- a/src/Platform/Microsoft.Testing.Platform/Services/TestApplicationResult.cs +++ b/src/Platform/Microsoft.Testing.Platform/Services/TestApplicationResult.cs @@ -17,7 +17,8 @@ internal sealed class TestApplicationResult : ITestApplicationProcessExitCode, I private readonly ICommandLineOptions _commandLineOptions; private readonly IEnvironment _environment; private readonly IStopPoliciesService _policiesService; - private readonly List _failedTests = []; + private readonly bool _isDiscovery; + private int _failedTestsCount; private int _totalRanTests; private bool _testAdapterTestSessionFailure; @@ -31,6 +32,7 @@ public TestApplicationResult( _commandLineOptions = commandLineOptions; _environment = environment; _policiesService = policiesService; + _isDiscovery = _commandLineOptions.IsOptionSet(PlatformCommandLineProvider.DiscoverTestsOptionKey); } /// @@ -68,10 +70,10 @@ public Task ConsumeAsync(IDataProducer dataProducer, IData value, CancellationTo if (Array.IndexOf(TestNodePropertiesCategories.WellKnownTestNodeTestRunOutcomeFailedProperties, executionState.GetType()) != -1) { - _failedTests.Add(message.TestNode); + _failedTestsCount++; } - if (_commandLineOptions.IsOptionSet(PlatformCommandLineProvider.DiscoverTestsOptionKey) + if (_isDiscovery && Array.IndexOf(TestNodePropertiesCategories.WellKnownTestNodeDiscoveredProperties, executionState.GetType()) != -1) { _totalRanTests++; @@ -89,7 +91,7 @@ public int GetProcessExitCode() int exitCode = ExitCodes.Success; exitCode = exitCode == ExitCodes.Success && _policiesService.IsMaxFailedTestsTriggered ? ExitCodes.TestExecutionStoppedForMaxFailedTests : exitCode; exitCode = exitCode == ExitCodes.Success && _testAdapterTestSessionFailure ? ExitCodes.TestAdapterTestSessionFailure : exitCode; - exitCode = exitCode == ExitCodes.Success && _failedTests.Count > 0 ? ExitCodes.AtLeastOneTestFailed : exitCode; + exitCode = exitCode == ExitCodes.Success && _failedTestsCount > 0 ? ExitCodes.AtLeastOneTestFailed : exitCode; exitCode = exitCode == ExitCodes.Success && _policiesService.IsAbortTriggered ? ExitCodes.TestSessionAborted : exitCode; exitCode = exitCode == ExitCodes.Success && _totalRanTests == 0 ? ExitCodes.ZeroTests : exitCode; @@ -127,5 +129,5 @@ public async Task SetTestAdapterTestSessionFailureAsync(string errorMessage) } public Statistics GetStatistics() - => new() { TotalRanTests = _totalRanTests, TotalFailedTests = _failedTests.Count }; + => new() { TotalRanTests = _totalRanTests, TotalFailedTests = _failedTestsCount }; } From 7518ef3c31767a95d32be46f806d0a36ec971f8d Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Tue, 20 May 2025 21:29:02 +0200 Subject: [PATCH 022/541] Inherit OwnerAttribute and PriorityAttribute from TestPropertyAttribute (#5591) --- .../Discovery/TypeEnumerator.cs | 17 +-------- .../Helpers/ReflectHelper.cs | 35 ------------------- .../UseAttributeOnTestMethodAnalyzer.cs | 3 ++ .../Attributes/TestMethod/OwnerAttribute.cs | 9 +++-- .../TestMethod/PriorityAttribute.cs | 5 +-- .../ReflectionUtilityTests.cs | 4 +-- 6 files changed, 15 insertions(+), 58 deletions(-) diff --git a/src/Adapter/MSTest.TestAdapter/Discovery/TypeEnumerator.cs b/src/Adapter/MSTest.TestAdapter/Discovery/TypeEnumerator.cs index c2db89fa3d..ee0678ba2e 100644 --- a/src/Adapter/MSTest.TestAdapter/Discovery/TypeEnumerator.cs +++ b/src/Adapter/MSTest.TestAdapter/Discovery/TypeEnumerator.cs @@ -153,24 +153,9 @@ internal UnitTestElement GetTestFromMethod(MethodInfo method, bool isDeclaredInT DoNotParallelize = _reflectHelper.IsDoNotParallelizeSet(method, _type), Priority = _reflectHelper.GetPriority(method), DeploymentItems = PlatformServiceProvider.Instance.TestDeployment.GetDeploymentItems(method, _type, warnings), + Traits = _reflectHelper.GetTestPropertiesAsTraits(method).ToArray(), }; - var traits = _reflectHelper.GetTestPropertiesAsTraits(method).ToList(); - - TestPlatform.ObjectModel.Trait? ownerTrait = _reflectHelper.GetTestOwnerAsTraits(method); - if (ownerTrait != null) - { - traits.Add(ownerTrait); - } - - TestPlatform.ObjectModel.Trait? priorityTrait = _reflectHelper.GetTestPriorityAsTraits(testElement.Priority); - if (priorityTrait != null) - { - traits.Add(priorityTrait); - } - - testElement.Traits = traits.ToArray(); - Attribute[] attributes = _reflectHelper.GetCustomAttributesCached(method, inherit: true); TestMethodAttribute? testMethodAttribute = null; diff --git a/src/Adapter/MSTest.TestAdapter/Helpers/ReflectHelper.cs b/src/Adapter/MSTest.TestAdapter/Helpers/ReflectHelper.cs index 3d3cd4e937..43a84a0d99 100644 --- a/src/Adapter/MSTest.TestAdapter/Helpers/ReflectHelper.cs +++ b/src/Adapter/MSTest.TestAdapter/Helpers/ReflectHelper.cs @@ -258,29 +258,6 @@ internal static bool IsDoNotParallelizeSet(Assembly assembly) .OfType() .FirstOrDefault(); - /// - /// KeyValue pairs that are provided by TestOwnerAttribute of the given test method. - /// - /// The member to inspect. - /// The owner trait. - internal virtual Trait? GetTestOwnerAsTraits(MemberInfo ownerAttributeProvider) - { - string? owner = GetOwner(ownerAttributeProvider); - - return StringEx.IsNullOrEmpty(owner) - ? null - : new Trait("Owner", owner); - } - - /// - /// KeyValue pairs that are provided by TestPriorityAttributes of the given test method. - /// - /// The priority. - /// The corresponding trait. - internal virtual Trait? GetTestPriorityAsTraits(int? testPriority) => testPriority == null - ? null - : new Trait("Priority", ((int)testPriority).ToString(CultureInfo.InvariantCulture)); - /// /// Priority if any set for test method. Will return priority if attribute is applied to TestMethod /// else null. @@ -361,18 +338,6 @@ internal virtual IEnumerable GetTestPropertiesAsTraits(MemberInfo testPro } } - /// - /// Returns owner if attribute is applied to TestMethod, else null. - /// - /// The member to inspect. - /// owner if attribute is applied to TestMethod, else null. - private string? GetOwner(MemberInfo ownerAttributeProvider) - { - OwnerAttribute? ownerAttribute = GetFirstDerivedAttributeOrDefault(ownerAttributeProvider, inherit: true); - - return ownerAttribute?.Owner; - } - /// /// Gets and caches the attributes for the given type, or method. /// diff --git a/src/Analyzers/MSTest.Analyzers/UseAttributeOnTestMethodAnalyzer.cs b/src/Analyzers/MSTest.Analyzers/UseAttributeOnTestMethodAnalyzer.cs index 63c73fd004..f26f04834e 100644 --- a/src/Analyzers/MSTest.Analyzers/UseAttributeOnTestMethodAnalyzer.cs +++ b/src/Analyzers/MSTest.Analyzers/UseAttributeOnTestMethodAnalyzer.cs @@ -127,6 +127,8 @@ public sealed class UseAttributeOnTestMethodAnalyzer : DiagnosticAnalyzer isEnabledByDefault: true); // IMPORTANT: Remember to add any new rule to the rule tuple. + // IMPORTANT: The order is important. For example, Owner is also TestProperty. We report the first violation and then bail-out. + // It may be a better idea to consolidate OwnerRule, PriorityRule, and TestPropertyRule into a single rule. private static readonly List<(string AttributeFullyQualifiedName, DiagnosticDescriptor Rule)> RuleTuples = [ (WellKnownTypeNames.MicrosoftVisualStudioTestToolsUnitTestingOwnerAttribute, OwnerRule), @@ -214,6 +216,7 @@ private static void AnalyzeSymbol( if (methodAttribute.AttributeClass.Inherits(attributeSymbol)) { attributes.Add((methodAttribute, rule)); + break; } } } diff --git a/src/TestFramework/TestFramework/Attributes/TestMethod/OwnerAttribute.cs b/src/TestFramework/TestFramework/Attributes/TestMethod/OwnerAttribute.cs index 5f33b2ed23..72526ac379 100644 --- a/src/TestFramework/TestFramework/Attributes/TestMethod/OwnerAttribute.cs +++ b/src/TestFramework/TestFramework/Attributes/TestMethod/OwnerAttribute.cs @@ -7,7 +7,7 @@ namespace Microsoft.VisualStudio.TestTools.UnitTesting; /// Test Owner. /// [AttributeUsage(AttributeTargets.Method)] -public sealed class OwnerAttribute : Attribute +public sealed class OwnerAttribute : TestPropertyAttribute { /// /// Initializes a new instance of the class. @@ -15,10 +15,13 @@ public sealed class OwnerAttribute : Attribute /// /// The owner. /// - public OwnerAttribute(string? owner) => Owner = owner; + public OwnerAttribute(string? owner) + : base("Owner", owner ?? string.Empty) + { + } /// /// Gets the owner. /// - public string? Owner { get; } + public string? Owner => Value; } diff --git a/src/TestFramework/TestFramework/Attributes/TestMethod/PriorityAttribute.cs b/src/TestFramework/TestFramework/Attributes/TestMethod/PriorityAttribute.cs index eaf0ae7532..ab0da4cddf 100644 --- a/src/TestFramework/TestFramework/Attributes/TestMethod/PriorityAttribute.cs +++ b/src/TestFramework/TestFramework/Attributes/TestMethod/PriorityAttribute.cs @@ -7,7 +7,7 @@ namespace Microsoft.VisualStudio.TestTools.UnitTesting; /// Priority attribute; used to specify the priority of a unit test. /// [AttributeUsage(AttributeTargets.Method)] -public sealed class PriorityAttribute : Attribute +public sealed class PriorityAttribute : TestPropertyAttribute { /// /// Initializes a new instance of the class. @@ -15,7 +15,8 @@ public sealed class PriorityAttribute : Attribute /// /// The priority. /// - public PriorityAttribute(int priority) => Priority = priority; + public PriorityAttribute(int priority) + : base("Priority", priority.ToString(CultureInfo.InvariantCulture)) => Priority = priority; /// /// Gets the priority. diff --git a/test/IntegrationTests/PlatformServices.Desktop.IntegrationTests/ReflectionUtilityTests.cs b/test/IntegrationTests/PlatformServices.Desktop.IntegrationTests/ReflectionUtilityTests.cs index 7c91950519..4e2ee52753 100644 --- a/test/IntegrationTests/PlatformServices.Desktop.IntegrationTests/ReflectionUtilityTests.cs +++ b/test/IntegrationTests/PlatformServices.Desktop.IntegrationTests/ReflectionUtilityTests.cs @@ -174,9 +174,9 @@ public void GetSpecificCustomAttributesShouldReturnAllAttributesIncludingUserDef IReadOnlyList attributes = ReflectionUtility.GetCustomAttributes(methodInfo, typeof(TestPropertyAttribute), true); attributes.Should().NotBeNull(); - attributes.Should().HaveCount(1); + attributes.Should().HaveCount(2); - string[] expectedAttributes = ["Duration : superfast"]; + string[] expectedAttributes = ["Duration : superfast", "Owner : base"]; GetAttributeValuePairs(attributes).Should().Equal(expectedAttributes); } From d1c37802e3d5fef0eae72bf26d9ae302e4bb4962 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Tue, 20 May 2025 21:29:36 +0200 Subject: [PATCH 023/541] Add open-code.cmd (#5592) --- eng/build.ps1 | 18 +++++++++++++++--- open-code.cmd | 2 ++ 2 files changed, 17 insertions(+), 3 deletions(-) create mode 100644 open-code.cmd diff --git a/eng/build.ps1 b/eng/build.ps1 index ea65bad4fc..330a5c2309 100644 --- a/eng/build.ps1 +++ b/eng/build.ps1 @@ -29,11 +29,12 @@ Param( [switch] $nativeToolsOnMachine, [switch] $help, [switch] $vs, + [switch] $vscode, [switch] $installWindowsSdk, [Parameter(ValueFromRemainingArguments=$true)][String[]]$properties ) -if ($vs) { +if ($vs -or $vscode) { . $PSScriptRoot\common\tools.ps1 # This tells .NET Core to use the bootstrapped runtime @@ -54,8 +55,19 @@ if ($vs) { # Enables the logginc of Json RPC messages if diagnostic logging for Test Explorer is enabled in Visual Studio. $env:_TestingPlatformDiagnostics_=1; - # Launch Visual Studio with the locally defined environment variables - & "$PSScriptRoot\..\TestFx.sln" + if ($vs) { + # Launch Visual Studio with the locally defined environment variables + & "$PSScriptRoot\..\TestFx.sln" + } else { + if (Get-Command code -ErrorAction Ignore) { + & code "$PSScriptRoot\.." + } elseif (Get-Command code-insiders -ErrorAction Ignore) { + & code-insiders "$PSScriptRoot\.." + } else { + Write-Error "VS Code not found. Please install it from https://code.visualstudio.com/" + return + } + } return } diff --git a/open-code.cmd b/open-code.cmd new file mode 100644 index 0000000000..82dda1d310 --- /dev/null +++ b/open-code.cmd @@ -0,0 +1,2 @@ +@echo off +powershell -ExecutionPolicy ByPass -NoProfile -command "& """%~dp0eng\build.ps1""" -vscode %*" \ No newline at end of file From efb5da0be8e0f961d298d506a467aa20bc260f10 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Wed, 21 May 2025 16:59:31 +0200 Subject: [PATCH 024/541] Cleanup always-true #if NETCOREAPP (#5626) --- .../ServerMode/JsonRpc/Json/Json.cs | 4 ---- 1 file changed, 4 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/Json/Json.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/Json/Json.cs index 8c0e7fde9f..43bf9d41bd 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/Json/Json.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/Json/Json.cs @@ -621,11 +621,7 @@ public async Task SerializeAsync(object obj) await using Utf8JsonWriter writer = new(stream); await SerializeAsync(obj, writer); await writer.FlushAsync(); -#if NETCOREAPP return Encoding.UTF8.GetString(stream.GetBuffer().AsMemory().Span[..(int)stream.Position]); -#else - return Encoding.UTF8.GetString(stream.ToArray()); -#endif } finally { From d37f75d8953c51523b91bf47e894bdfc2087cc60 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Thu, 22 May 2025 12:02:23 +0200 Subject: [PATCH 025/541] Update Polyfill to 7.32.0 (#5631) --- Directory.Packages.props | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Directory.Packages.props b/Directory.Packages.props index b12c03a835..33fe166766 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -54,7 +54,7 @@ - + From b44fb4efda993bcee8c3af9d161845bcb63bf6d3 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Thu, 22 May 2025 12:02:56 +0200 Subject: [PATCH 026/541] Add missing overload for Assert.Throws (#5619) --- .../Assertions/Assert.ThrowsException.cs | 12 ++++++++++++ .../TestFramework/PublicAPI/PublicAPI.Unshipped.txt | 2 ++ .../Assertions/AssertTests.ThrowsExceptionTests.cs | 12 ++++++++++++ 3 files changed, 26 insertions(+) diff --git a/src/TestFramework/TestFramework/Assertions/Assert.ThrowsException.cs b/src/TestFramework/TestFramework/Assertions/Assert.ThrowsException.cs index d57d2c31c9..3ae76b2c63 100644 --- a/src/TestFramework/TestFramework/Assertions/Assert.ThrowsException.cs +++ b/src/TestFramework/TestFramework/Assertions/Assert.ThrowsException.cs @@ -31,6 +31,11 @@ public AssertNonStrictThrowsInterpolatedStringHandler(int literalLength, int for } } + public AssertNonStrictThrowsInterpolatedStringHandler(int literalLength, int formattedCount, Func action, out bool shouldAppend) + : this(literalLength, formattedCount, (Action)(() => _ = action()), out shouldAppend) + { + } + internal TException ComputeAssertion() { if (_state.FailAction is not null) @@ -218,6 +223,13 @@ public static TException Throws(Action action, [InterpolatedStringHa where TException : Exception => message.ComputeAssertion(); + /// +#pragma warning disable IDE0060 // Remove unused parameter - https://github.com/dotnet/roslyn/issues/76578 + public static TException Throws(Func action, [InterpolatedStringHandlerArgument(nameof(action))] ref AssertNonStrictThrowsInterpolatedStringHandler message) +#pragma warning restore IDE0060 // Remove unused parameter + where TException : Exception + => message.ComputeAssertion(); + /// /// Asserts that the delegate throws an exception of type /// (and not of derived type) and throws AssertFailedException if code does not throws exception or throws diff --git a/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Unshipped.txt b/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Unshipped.txt index 758e4cf563..112144eb52 100644 --- a/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Unshipped.txt +++ b/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Unshipped.txt @@ -1,2 +1,4 @@ #nullable enable +Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AssertNonStrictThrowsInterpolatedStringHandler.AssertNonStrictThrowsInterpolatedStringHandler(int literalLength, int formattedCount, System.Func! action, out bool shouldAppend) -> void Microsoft.VisualStudio.TestTools.UnitTesting.ConditionBaseAttribute.Mode.get -> Microsoft.VisualStudio.TestTools.UnitTesting.ConditionMode +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.Throws(System.Func! action, ref Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AssertNonStrictThrowsInterpolatedStringHandler message) -> TException! diff --git a/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.ThrowsExceptionTests.cs b/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.ThrowsExceptionTests.cs index 52b1fd9620..e409bae51c 100644 --- a/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.ThrowsExceptionTests.cs +++ b/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.ThrowsExceptionTests.cs @@ -202,6 +202,18 @@ public void Throws_WhenExceptionIsNotExpectedType_ShouldThrow() Verify(ex is AssertFailedException); } + public void Throws_WithInterpolation() + { + static string GetString() => throw new Exception(); + +#pragma warning disable IDE0200 // Remove unnecessary lambda expression - intentionally testing overload resolution for this case. + Exception ex = Assert.Throws(() => GetString(), $"Hello {GetString()}"); +#pragma warning restore IDE0200 // Remove unnecessary lambda expression + Exception ex2 = Assert.Throws(GetString, $"Hello {GetString()}"); + Verify(ex is not null); + Verify(ex2 is not null); + } + public void ThrowsExactly_WhenExceptionIsDerivedFromExpectedType_ShouldThrow() { static void Action() => Assert.ThrowsExactly(() => throw new ArgumentNullException()); From 491500a8e51e143dc29f8bb8a874b113220f521c Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Mon, 26 May 2025 09:56:12 +0200 Subject: [PATCH 027/541] Simplify ReadHeadersAsync to not read unused Content-Type (#5638) --- .../JsonRpc/StreamMessageHandler.cs | 26 ++++++------------- 1 file changed, 8 insertions(+), 18 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/StreamMessageHandler.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/StreamMessageHandler.cs index c93aabf846..56e18acf10 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/StreamMessageHandler.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/StreamMessageHandler.cs @@ -47,8 +47,7 @@ public StreamMessageHandler( // [content]\r\n while (true) { - // Content type is not mandatory, and we don't use it. - (int commandSize, string _) = await ReadHeadersAsync(cancellationToken); + int commandSize = await ReadHeadersAsync(cancellationToken); // Most probably connection lost if (commandSize is -1) @@ -76,10 +75,9 @@ public StreamMessageHandler( } } - private async Task<(int ContentSize, string ContentType)> ReadHeadersAsync(CancellationToken cancellationToken) + private async Task ReadHeadersAsync(CancellationToken cancellationToken) { int contentSize = -1; - string contentType = string.Empty; while (true) { @@ -95,27 +93,19 @@ public StreamMessageHandler( break; } - string contentSizeStr = "Content-Length:"; - string contentTypeStr = "Content-Type:"; - if (line.StartsWith(contentSizeStr, StringComparison.OrdinalIgnoreCase)) - { -#if NETCOREAPP - _ = int.TryParse(line.AsSpan()[contentSizeStr.Length..].Trim(), out contentSize); -#else - _ = int.TryParse(line[contentSizeStr.Length..].Trim(), out contentSize); -#endif - } - else if (line.StartsWith(contentTypeStr, StringComparison.OrdinalIgnoreCase)) + const string ContentLengthHeaderName = "Content-Length:"; + // Content type is not mandatory, and we don't use it. + if (line.StartsWith(ContentLengthHeaderName, StringComparison.OrdinalIgnoreCase)) { #if NETCOREAPP - contentType = new(line.AsSpan()[contentTypeStr.Length..].Trim()); + _ = int.TryParse(line.AsSpan()[ContentLengthHeaderName.Length..].Trim(), out contentSize); #else - contentType = line[contentTypeStr.Length..].Trim(); + _ = int.TryParse(line[ContentLengthHeaderName.Length..].Trim(), out contentSize); #endif } } - return (contentSize, contentType); + return contentSize; } public async Task WriteRequestAsync(RpcMessage message, CancellationToken cancellationToken) From 983886c585ec245287b59e9821ad3e6f16657c3c Mon Sep 17 00:00:00 2001 From: Copilot <198982749+Copilot@users.noreply.github.com> Date: Mon, 26 May 2025 10:52:06 +0200 Subject: [PATCH 028/541] Fix MSTEST0005 false positive when using null-checking with TestContext constructor parameter (#5601) Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: Youssef1313 <31348972+Youssef1313@users.noreply.github.com> --- .../TestContextShouldBeValidAnalyzer.cs | 41 +++++++++++++---- .../TestContextShouldBeValidAnalyzerTests.cs | 46 +++++++++++++++++++ 2 files changed, 79 insertions(+), 8 deletions(-) diff --git a/src/Analyzers/MSTest.Analyzers/TestContextShouldBeValidAnalyzer.cs b/src/Analyzers/MSTest.Analyzers/TestContextShouldBeValidAnalyzer.cs index 4297c944d7..10bb626e00 100644 --- a/src/Analyzers/MSTest.Analyzers/TestContextShouldBeValidAnalyzer.cs +++ b/src/Analyzers/MSTest.Analyzers/TestContextShouldBeValidAnalyzer.cs @@ -92,11 +92,26 @@ private static bool AssignsParameterToMember(IParameterSymbol parameter, ISymbol operation = expressionStatementOperation.Operation; } - return operation is ISimpleAssignmentOperation assignmentOperation && + if (operation is ISimpleAssignmentOperation assignmentOperation && assignmentOperation.Target is IMemberReferenceOperation targetMemberReference && - SymbolEqualityComparer.Default.Equals(targetMemberReference.Member, member) && - assignmentOperation.Value is IParameterReferenceOperation parameterReference && - SymbolEqualityComparer.Default.Equals(parameterReference.Parameter, parameter); + SymbolEqualityComparer.Default.Equals(targetMemberReference.Member, member)) + { + // Extract parameter reference from the value, unwrapping from coalesce operation if necessary + IOperation effectiveValue = assignmentOperation.Value; + if (effectiveValue is ICoalesceOperation coalesceOperation) + { + effectiveValue = coalesceOperation.Value; + } + + // Check if the effective value is a parameter reference to our target parameter + if (effectiveValue is IParameterReferenceOperation parameterReference && + SymbolEqualityComparer.Default.Equals(parameterReference.Parameter, parameter)) + { + return true; + } + } + + return false; } private static void CollectTestContextFieldsAssignedInConstructor( @@ -125,11 +140,21 @@ private static void CollectTestContextFieldsAssignedInConstructor( } if (operation is ISimpleAssignmentOperation assignmentOperation && - assignmentOperation.Target is IMemberReferenceOperation { Member: IFieldSymbol { } candidateField } && - assignmentOperation.Value is IParameterReferenceOperation parameterReference && - SymbolEqualityComparer.Default.Equals(parameterReference.Parameter, testContextParameter)) + assignmentOperation.Target is IMemberReferenceOperation { Member: IFieldSymbol { } candidateField }) { - fieldsAssignedInConstructor.Add(candidateField); + // Extract parameter reference from the value, unwrapping from coalesce operation if necessary + IOperation effectiveValue = assignmentOperation.Value; + if (effectiveValue is ICoalesceOperation coalesceOperation) + { + effectiveValue = coalesceOperation.Value; + } + + // Check if the effective value is a parameter reference to our target parameter + if (effectiveValue is IParameterReferenceOperation parameterReference && + SymbolEqualityComparer.Default.Equals(parameterReference.Parameter, testContextParameter)) + { + fieldsAssignedInConstructor.Add(candidateField); + } } } diff --git a/test/UnitTests/MSTest.Analyzers.UnitTests/TestContextShouldBeValidAnalyzerTests.cs b/test/UnitTests/MSTest.Analyzers.UnitTests/TestContextShouldBeValidAnalyzerTests.cs index efd9c1c560..ad6598ca1a 100644 --- a/test/UnitTests/MSTest.Analyzers.UnitTests/TestContextShouldBeValidAnalyzerTests.cs +++ b/test/UnitTests/MSTest.Analyzers.UnitTests/TestContextShouldBeValidAnalyzerTests.cs @@ -472,4 +472,50 @@ public class MyTestClass await VerifyCS.VerifyCodeFixAsync(code, code); } + + [TestMethod] + public async Task WhenTestContextAssignedInConstructorWithNullCheck_NoDiagnostic() + { + string code = """ + using System; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + private readonly TestContext _testContext; + + public MyTestClass(TestContext testContext) + { + _testContext = testContext ?? throw new ArgumentNullException(nameof(testContext)); + } + + public TestContext TestContext => _testContext; + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, code); + } + + [TestMethod] + public async Task WhenTestContextPropertyAssignedInConstructorWithNullCheck_NoDiagnostic() + { + string code = """ + using System; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + public MyTestClass(TestContext testContext) + { + TestContext = testContext ?? throw new ArgumentNullException(nameof(testContext)); + } + + public TestContext TestContext { get; } + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, code); + } } From d1e8a8d50a8ff5389c15494be1699d27d852c6af Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Mon, 26 May 2025 19:53:03 +1000 Subject: [PATCH 029/541] remove redundant fields (#5610) --- .../AppInsightTelemetryClient.cs | 7 +++---- .../EnvironmentVariablesConfigurationProvider.cs | 4 +--- .../ServerMode/JsonRpc/StreamMessageHandler.cs | 8 ++------ .../Configuration/ConfigurationManagerTests.cs | 8 -------- 4 files changed, 6 insertions(+), 21 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Extensions.Telemetry/AppInsightTelemetryClient.cs b/src/Platform/Microsoft.Testing.Extensions.Telemetry/AppInsightTelemetryClient.cs index fe27fd2eb2..33d9a0ba3c 100644 --- a/src/Platform/Microsoft.Testing.Extensions.Telemetry/AppInsightTelemetryClient.cs +++ b/src/Platform/Microsoft.Testing.Extensions.Telemetry/AppInsightTelemetryClient.cs @@ -12,14 +12,13 @@ internal sealed class AppInsightTelemetryClient : ITelemetryClient private const string InstrumentationKey = "74cc1c9e-3e6e-4d05-b3fc-dde9101d0254"; private const string TelemetryServiceEndpoint = "https://dc.services.visualstudio.com/"; - private readonly TelemetryConfiguration _config; private readonly TelemetryClient _telemetryClient; public AppInsightTelemetryClient(string? currentSessionId, string osVersion) { - _config = TelemetryConfiguration.CreateDefault(); - _config.ConnectionString = $"InstrumentationKey={InstrumentationKey};IngestionEndpoint={TelemetryServiceEndpoint}"; - _telemetryClient = new TelemetryClient(_config); + var config = TelemetryConfiguration.CreateDefault(); + config.ConnectionString = $"InstrumentationKey={InstrumentationKey};IngestionEndpoint={TelemetryServiceEndpoint}"; + _telemetryClient = new TelemetryClient(config); _telemetryClient.Context.Session.Id = currentSessionId; _telemetryClient.Context.Device.OperatingSystem = osVersion; } diff --git a/src/Platform/Microsoft.Testing.Platform/Configurations/EnvironmentVariablesConfigurationProvider.cs b/src/Platform/Microsoft.Testing.Platform/Configurations/EnvironmentVariablesConfigurationProvider.cs index 1807b234dc..c5f4046058 100644 --- a/src/Platform/Microsoft.Testing.Platform/Configurations/EnvironmentVariablesConfigurationProvider.cs +++ b/src/Platform/Microsoft.Testing.Platform/Configurations/EnvironmentVariablesConfigurationProvider.cs @@ -15,7 +15,6 @@ internal sealed class EnvironmentVariablesConfigurationProvider : IConfiguration private const string SqlServerPrefix = "SQLCONNSTR_"; private const string CustomConnectionStringPrefix = "CUSTOMCONNSTR_"; - private readonly string _prefix; private readonly string _normalizedPrefix; private readonly Dictionary _data = new(StringComparer.OrdinalIgnoreCase); @@ -29,8 +28,7 @@ public EnvironmentVariablesConfigurationProvider(IEnvironment environmentVariabl public EnvironmentVariablesConfigurationProvider(IEnvironment environmentVariables, string prefix) { - _prefix = prefix; - _normalizedPrefix = Normalize(_prefix); + _normalizedPrefix = Normalize(prefix); _environmentVariables = environmentVariables; } diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/StreamMessageHandler.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/StreamMessageHandler.cs index 56e18acf10..474d8c1eb9 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/StreamMessageHandler.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/StreamMessageHandler.cs @@ -11,8 +11,6 @@ namespace Microsoft.Testing.Platform.ServerMode; internal class StreamMessageHandler : IMessageHandler, IDisposable { - private readonly Stream _clientToServerStream; - private readonly Stream _serverToClientStream; private readonly StreamReader _reader; private readonly StreamWriter _writer; private readonly IMessageFormatter _formatter; @@ -23,10 +21,8 @@ public StreamMessageHandler( Stream serverToClientStream, IMessageFormatter formatter) { - _clientToServerStream = clientToServerStream; - _serverToClientStream = serverToClientStream; - _reader = new StreamReader(_clientToServerStream); - _writer = new StreamWriter(_serverToClientStream) + _reader = new StreamReader(clientToServerStream); + _writer = new StreamWriter(serverToClientStream) { // We need to force the NewLine because in Windows and nix different char sequence are used // https://learn.microsoft.com/dotnet/api/system.io.textwriter.newline?view=net-7.0 diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Configuration/ConfigurationManagerTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Configuration/ConfigurationManagerTests.cs index e1b6c394d2..aaf9b02821 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Configuration/ConfigurationManagerTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Configuration/ConfigurationManagerTests.cs @@ -18,14 +18,6 @@ namespace Microsoft.Testing.Platform.UnitTests; [TestClass] public sealed class ConfigurationManagerTests { - private readonly ServiceProvider _serviceProvider; - - public ConfigurationManagerTests() - { - _serviceProvider = new(); - _serviceProvider.AddService(new SystemFileSystem()); - } - [TestMethod] [DynamicData(nameof(GetConfigurationValueFromJsonData))] public async ValueTask GetConfigurationValueFromJson(string jsonFileConfig, string key, string? result) From 6b4546fcad19ff7681f9533aef5b8eb5e8186213 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Mon, 26 May 2025 13:18:45 +0200 Subject: [PATCH 030/541] Remove unused DynamicDataType.DataSourceAttribute enum value and update tests (#5588) --- .../ObjectModel/DynamicDataType.cs | 7 +------ .../ObjectModel/UnitTestElementTests.cs | 13 ++++++++----- 2 files changed, 9 insertions(+), 11 deletions(-) diff --git a/src/Adapter/MSTest.TestAdapter/ObjectModel/DynamicDataType.cs b/src/Adapter/MSTest.TestAdapter/ObjectModel/DynamicDataType.cs index 572a628955..6046f3dfd8 100644 --- a/src/Adapter/MSTest.TestAdapter/ObjectModel/DynamicDataType.cs +++ b/src/Adapter/MSTest.TestAdapter/ObjectModel/DynamicDataType.cs @@ -13,13 +13,8 @@ internal enum DynamicDataType : int /// None = 0, - /// - /// Dynamic data from . - /// - DataSourceAttribute = 1, - /// /// Dynamic data from . /// - ITestDataSource = 2, + ITestDataSource = 1, } diff --git a/test/UnitTests/MSTestAdapter.UnitTests/ObjectModel/UnitTestElementTests.cs b/test/UnitTests/MSTestAdapter.UnitTests/ObjectModel/UnitTestElementTests.cs index 2985183fb9..cc4c0ed328 100644 --- a/test/UnitTests/MSTestAdapter.UnitTests/ObjectModel/UnitTestElementTests.cs +++ b/test/UnitTests/MSTestAdapter.UnitTests/ObjectModel/UnitTestElementTests.cs @@ -240,7 +240,7 @@ public void ToTestCase_WhenStrategyIsDisplayName_ExamplesOfTestCaseIdUniqueness( new UnitTestElement( new("MyMethod", "MyProduct.MyNamespace.MyClass", "MyAssembly", null, testIdStrategy) { - DataType = DynamicDataType.DataSourceAttribute, + DataType = DynamicDataType.ITestDataSource, }) { DisplayName = "SomeDisplayName", @@ -269,20 +269,20 @@ public void ToTestCase_WhenStrategyIsDisplayName_ExamplesOfTestCaseIdCollision() new UnitTestElement( new("MyMethod", "MyProduct.MyNamespace.MyClass", "MyAssembly", null, testIdStrategy) { - DataType = DynamicDataType.DataSourceAttribute, + DataType = DynamicDataType.None, }) .ToTestCase(), new UnitTestElement( new("MyMethod", "MyProduct.MyNamespace.MyClass", "MyAssembly", null, testIdStrategy) { - DataType = DynamicDataType.DataSourceAttribute, + DataType = DynamicDataType.None, SerializedData = ["1"], }) .ToTestCase(), new UnitTestElement( new("MyMethod", "MyProduct.MyNamespace.MyClass", "MyAssembly", null, testIdStrategy) { - DataType = DynamicDataType.DataSourceAttribute, + DataType = DynamicDataType.None, SerializedData = ["2"], }) .ToTestCase(), @@ -302,7 +302,10 @@ public void ToTestCase_WhenStrategyIsDisplayName_ExamplesOfTestCaseIdCollision() .ToTestCase() ]; - Verify(testCases.Select(tc => tc.Id.ToString()).Distinct().Count() == 1); + // All the test cases with DynamicDataType.None will have the same Id (showing collisions). + // All the test cases with DynamicDataType.ITestDataSource will have the same Id, but different one (showing collisions). + // So for the 5 test cases, we have 2 distinct Ids. + Verify(testCases.Select(tc => tc.Id.ToString()).Distinct().Count() == 2); } public void ToTestCase_WhenStrategyIsFullyQualifiedTest_ExamplesOfTestCaseIdUniqueness() From 310d17acfcbae625a4de5d1103d0de6e96d13492 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Mon, 26 May 2025 16:18:35 +0200 Subject: [PATCH 031/541] Run the whole ExecuteInternal logic under the right execution context (#5636) --- .../Execution/TestMethodInfo.cs | 177 +++++++++++------- .../GenericTestMethodTests.cs | 4 - .../TestContextTests.cs | 35 +++- 3 files changed, 136 insertions(+), 80 deletions(-) diff --git a/src/Adapter/MSTest.TestAdapter/Execution/TestMethodInfo.cs b/src/Adapter/MSTest.TestAdapter/Execution/TestMethodInfo.cs index 6caf17ce4e..0d69c53bec 100644 --- a/src/Adapter/MSTest.TestAdapter/Execution/TestMethodInfo.cs +++ b/src/Adapter/MSTest.TestAdapter/Execution/TestMethodInfo.cs @@ -157,30 +157,34 @@ public virtual async Task InvokeAsync(object?[]? arguments) ExecutionContext? executionContext = Parent.ExecutionContext ?? Parent.Parent.ExecutionContext; - try + var tcs = new TaskCompletionSource(); + +#pragma warning disable VSTHRD101 // Avoid unsupported async delegates + ExecutionContextHelpers.RunOnContext(executionContext, async () => { - ExecutionContextHelpers.RunOnContext(executionContext, () => + try { ThreadSafeStringWriter.CleanState(); listener = new LogMessageListener(MSTestSettings.CurrentSettings.CaptureDebugTraces); - executionContext = ExecutionContext.Capture(); - }); - - result = IsTimeoutSet - ? await ExecuteInternalWithTimeoutAsync(arguments, executionContext) - : await ExecuteInternalAsync(arguments, executionContext, null); - } - finally - { - // Handle logs & debug traces. - watch.Stop(); - if (result != null) + result = IsTimeoutSet + ? await ExecuteInternalWithTimeoutAsync(arguments) + : await ExecuteInternalAsync(arguments, null); + tcs.SetResult(null); + } + catch (Exception e) + { + tcs.SetException(e); + } + finally { - result.Duration = watch.Elapsed; - if (listener is not null) + // Handle logs & debug traces. + watch.Stop(); + + if (result != null) { - ExecutionContextHelpers.RunOnContext(executionContext, () => + result.Duration = watch.Elapsed; + if (listener is not null) { result.DebugTrace = listener.GetAndClearDebugTrace(); result.LogOutput = listener.GetAndClearStandardOutput(); @@ -188,12 +192,14 @@ public virtual async Task InvokeAsync(object?[]? arguments) result.TestContextMessages = TestContext?.GetAndClearDiagnosticMessages(); result.ResultFiles = TestContext?.GetResultFiles(); listener.Dispose(); - }); + } } } - } + }); +#pragma warning restore VSTHRD101 // Avoid unsupported async delegates - return result; + await tcs.Task; + return result!; } internal void SetArguments(object?[]? arguments) => Arguments = arguments == null ? null : ResolveArguments(arguments); @@ -394,26 +400,22 @@ private void ThrowMultipleAttributesException(string attributeName) /// Execute test without timeout. /// /// Arguments to be passed to the method. - /// The execution context to execute the test method on. /// The timeout token source. /// The result of the execution. [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Requirement is to handle all kinds of user exceptions and message appropriately.")] - private async Task ExecuteInternalAsync(object?[]? arguments, ExecutionContext? executionContext, CancellationTokenSource? timeoutTokenSource) + private async Task ExecuteInternalAsync(object?[]? arguments, CancellationTokenSource? timeoutTokenSource) { DebugEx.Assert(TestMethod != null, "UnitTestExecuter.DefaultTestMethodInvoke: testMethod = null."); var result = new TestResult(); // TODO remove dry violation with TestMethodRunner - ExecutionContextHelpers.RunOnContext(executionContext, () => - { - _classInstance = CreateTestClassInstance(result); - executionContext = ExecutionContext.Capture(); - }); + _classInstance = CreateTestClassInstance(result); bool isExceptionThrown = false; bool hasTestInitializePassed = false; Exception? testRunnerException = null; _isTestCleanupInvoked = false; + ExecutionContext? executionContext = null; try { @@ -427,33 +429,57 @@ private async Task ExecuteInternalAsync(object?[]? arguments, Execut if (RunTestInitializeMethod(_classInstance, result, ref executionContext, timeoutTokenSource)) { hasTestInitializePassed = true; - var tcs = new TaskCompletionSource(); -#pragma warning disable VSTHRD101 // Avoid unsupported async delegates - ExecutionContextHelpers.RunOnContext(executionContext, async () => + + if (executionContext is null) { - try + object? invokeResult = TestMethod.GetInvokeResult(_classInstance, arguments); + if (invokeResult is Task task) { - object? invokeResult = TestMethod.GetInvokeResult(_classInstance, arguments); - if (invokeResult is Task task) + await task; + } + else if (invokeResult is ValueTask valueTask) + { + await valueTask; + } + } + else + { + var tcs = new TaskCompletionSource(); + ExecutionContext? updatedExecutionContext = executionContext; +#pragma warning disable VSTHRD101 // Avoid unsupported async delegates + ExecutionContextHelpers.RunOnContext(executionContext, async () => + { + try { - await task; + object? invokeResult = TestMethod.GetInvokeResult(_classInstance, arguments); + if (invokeResult is Task task) + { + await task; + } + else if (invokeResult is ValueTask valueTask) + { + await valueTask; + } } - else if (invokeResult is ValueTask valueTask) + catch (Exception e) { - await valueTask; + tcs.SetException(e); } + finally + { + updatedExecutionContext = ExecutionContext.Capture(); + tcs.TrySetResult(null); + } + }); +#pragma warning restore VSTHRD101 // Avoid unsupported async delegates - executionContext = ExecutionContext.Capture(); - tcs.SetResult(null); - } - catch (Exception ex) + await tcs.Task; + + if (updatedExecutionContext is not null) { - tcs.SetException(ex); + executionContext = updatedExecutionContext; } - }); -#pragma warning restore VSTHRD101 // Avoid unsupported async delegates - - await tcs.Task; + } result.Outcome = UTF.UnitTestOutcome.Passed; } @@ -677,7 +703,7 @@ private static TestFailedException HandleMethodException(Exception ex, Exception /// Runs TestCleanup methods of parent TestClass and base classes. /// /// Instance of TestResult. - /// The execution context to execute the test cleanup on. + /// The execution context to run on. /// The timeout token source. [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Requirement is to handle all kinds of user exceptions and message appropriately.")] private void RunTestCleanupMethod(TestResult result, ExecutionContext? executionContext, CancellationTokenSource? timeoutTokenSource) @@ -723,20 +749,12 @@ private void RunTestCleanupMethod(TestResult result, ExecutionContext? execution if (_classInstance is IAsyncDisposable classInstanceAsAsyncDisposable) { // If you implement IAsyncDisposable without calling the DisposeAsync this would result a resource leak. - ExecutionContextHelpers.RunOnContext(executionContext, () => - { - classInstanceAsAsyncDisposable.DisposeAsync().AsTask().Wait(); - executionContext = ExecutionContext.Capture(); - }); + classInstanceAsAsyncDisposable.DisposeAsync().AsTask().Wait(); } #endif if (_classInstance is IDisposable classInstanceAsDisposable) { - ExecutionContextHelpers.RunOnContext(executionContext, () => - { - classInstanceAsDisposable.Dispose(); - executionContext = ExecutionContext.Capture(); - }); + classInstanceAsDisposable.Dispose(); } } } @@ -775,7 +793,7 @@ private void RunTestCleanupMethod(TestResult result, ExecutionContext? execution /// /// Instance of TestClass. /// Instance of TestResult. - /// The execution context to execute the test initialize on. + /// The execution context to run on. /// The timeout token source. /// True if the TestInitialize method(s) did not throw an exception. [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Requirement is to handle all kinds of user exceptions and message appropriately.")] @@ -865,15 +883,18 @@ private bool RunTestInitializeMethod(object classInstance, TestResult result, re timeout = localTimeout; } - ExecutionContext? updatedExecutionContext = executionContext; - + int originalThreadId = Environment.CurrentManagedThreadId; + ExecutionContext? updatedExecutionContext = null; TestFailedException? result = FixtureMethodRunner.RunWithTimeoutAndCancellation( () => { methodInfo.InvokeAsSynchronousTask(classInstance, null); - // **After** we have executed the current test initialize (it could be from the current class or from base class), we save the current context. - // This context will contain async locals set by the test initialize method. - updatedExecutionContext = ExecutionContext.Capture(); + if (originalThreadId != Environment.CurrentManagedThreadId) + { + // We ended up running on a different thread, because of use of non-cooperative timeout. + // Re-capture the execution context. + updatedExecutionContext = ExecutionContext.Capture(); + } }, TestContext!.Context.CancellationTokenSource, timeout, @@ -885,7 +906,11 @@ timeoutTokenSource is null ? null : (timeoutTokenSource, TimeoutInfo.Timeout)); - executionContext = updatedExecutionContext; + if (updatedExecutionContext != null) + { + executionContext = updatedExecutionContext; + } + return result; } @@ -897,14 +922,18 @@ timeoutTokenSource is null timeout = localTimeout; } - ExecutionContext? updatedExecutionContext = executionContext; + int originalThreadId = Environment.CurrentManagedThreadId; + ExecutionContext? updatedExecutionContext = null; TestFailedException? result = FixtureMethodRunner.RunWithTimeoutAndCancellation( () => { methodInfo.InvokeAsSynchronousTask(classInstance, null); - // **After** we have executed the current test cleanup (it could be from the current class or from base class), we save the current context. - // This context will contain async locals set by the test cleanup method. - updatedExecutionContext = ExecutionContext.Capture(); + if (originalThreadId != Environment.CurrentManagedThreadId) + { + // We ended up running on a different thread, because of use of non-cooperative timeout. + // Re-capture the execution context. + updatedExecutionContext = ExecutionContext.Capture(); + } }, TestContext!.Context.CancellationTokenSource, timeout, @@ -916,7 +945,11 @@ timeoutTokenSource is null ? null : (timeoutTokenSource, TimeoutInfo.Timeout)); - executionContext = updatedExecutionContext; + if (updatedExecutionContext != null) + { + executionContext = updatedExecutionContext; + } + return result; } @@ -1031,10 +1064,9 @@ private bool SetTestContext(object classInstance, TestResult result) /// Execute test with a timeout. /// /// The arguments to be passed. - /// The execution context to execute the test method on. /// The result of execution. [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Requirement is to handle all kinds of user exceptions and message appropriately.")] - private async Task ExecuteInternalWithTimeoutAsync(object?[]? arguments, ExecutionContext? executionContext) + private async Task ExecuteInternalWithTimeoutAsync(object?[]? arguments) { DebugEx.Assert(IsTimeoutSet, "Timeout should be set"); @@ -1058,7 +1090,7 @@ private async Task ExecuteInternalWithTimeoutAsync(object?[]? argume try { - return await ExecuteInternalAsync(arguments, executionContext, timeoutTokenSource); + return await ExecuteInternalAsync(arguments, timeoutTokenSource); } catch (OperationCanceledException) { @@ -1084,6 +1116,7 @@ private async Task ExecuteInternalWithTimeoutAsync(object?[]? argume TestResult? result = null; Exception? failure = null; + ExecutionContext? executionContext = null; if (PlatformServiceProvider.Instance.ThreadOperations.Execute(ExecuteAsyncAction, TimeoutInfo.Timeout, TestContext!.Context.CancellationTokenSource.Token)) { @@ -1135,7 +1168,7 @@ void ExecuteAsyncAction() // dispatched back to the SynchronizationContext which offloads the work to the UI thread. // However, the GetAwaiter().GetResult() here will block the current thread which is also the UI thread. // So, the continuations will not be able, thus this task never completes. - result = ExecuteInternalAsync(arguments, executionContext, null).GetAwaiter().GetResult(); + result = ExecuteInternalAsync(arguments, null).GetAwaiter().GetResult(); } catch (Exception ex) { diff --git a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/GenericTestMethodTests.cs b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/GenericTestMethodTests.cs index c298349c7a..341830621f 100644 --- a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/GenericTestMethodTests.cs +++ b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/GenericTestMethodTests.cs @@ -38,22 +38,18 @@ public async Task TestDifferentGenericMethodTestCases() failed ParameterizedMethodSimple \(null\) \(\d+ms\) Test method TestClass\.ParameterizedMethodSimple threw exception: System\.InvalidOperationException: The type of the generic parameter 'T' could not be inferred\. - .+? failed ParameterizedMethodTwoGenericParametersAndFourMethodParameters \(1,"Hello world",2,3\) \(\d+ms\) Test method TestClass\.ParameterizedMethodTwoGenericParametersAndFourMethodParameters threw exception: System\.InvalidOperationException: Found two conflicting types for generic parameter 'T2'\. The conflicting types are 'System\.Byte' and 'System\.Int32'\. - .+? failed ParameterizedMethodTwoGenericParametersAndFourMethodParameters \(null,"Hello world","Hello again",3\) \(\d+ms\) Assert\.Fail failed\. Test method 'ParameterizedMethodTwoGenericParametersAndFourMethodParameters' did run with parameters '', 'Hello world', 'Hello again', '3' and generic types 'System\.Int32', 'System\.String'\. .+? failed ParameterizedMethodTwoGenericParametersAndFourMethodParameters \("Hello hello","Hello world",null,null\) \(\d+ms\) Test method TestClass\.ParameterizedMethodTwoGenericParametersAndFourMethodParameters threw exception: System\.InvalidOperationException: The type of the generic parameter 'T1' could not be inferred\. - .+? failed ParameterizedMethodTwoGenericParametersAndFourMethodParameters \(null,null,null,null\) \(\d+ms\) Test method TestClass\.ParameterizedMethodTwoGenericParametersAndFourMethodParameters threw exception: System\.InvalidOperationException: The type of the generic parameter 'T1' could not be inferred\. - .+? failed ParameterizedMethodSimpleParams \(1\) \(\d+ms\) Cannot create an instance of T\[] because Type\.ContainsGenericParameters is true\. .+? diff --git a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/TestContextTests.cs b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/TestContextTests.cs index 7b86cfbcb4..06b1624ef7 100644 --- a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/TestContextTests.cs +++ b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/TestContextTests.cs @@ -10,9 +10,10 @@ namespace MSTest.Acceptance.IntegrationTests; public sealed class TestContextTests : AcceptanceTestBase { [TestMethod] - public async Task TestContextsAreCorrectlySet() + [DynamicData(nameof(TargetFrameworks.AllForDynamicData), typeof(TargetFrameworks))] + public async Task TestContextsAreCorrectlySet(string tfm) { - var testHost = TestHost.LocateFrom(AssetFixture.ProjectPath, TestAssetFixture.ProjectName, TargetFrameworks.NetCurrent); + var testHost = TestHost.LocateFrom(AssetFixture.ProjectPath, TestAssetFixture.ProjectName, tfm); TestHostResult testHostResult = await testHost.ExecuteAsync("--filter ClassName~TestContextCtor"); // Assert @@ -76,7 +77,7 @@ public sealed class TestAssetFixture() : TestAssetFixtureBase(AcceptanceFixture. { yield return (ProjectName, ProjectName, SourceCode - .PatchTargetFrameworks(TargetFrameworks.NetCurrent) + .PatchTargetFrameworks(TargetFrameworks.All) .PatchCodeWithReplace("$MSTestVersion$", MSTestVersion)); } @@ -88,6 +89,7 @@ public sealed class TestAssetFixture() : TestAssetFixtureBase(AcceptanceFixture. Exe true $TargetFrameworks$ + preview diff --git a/src/Package/MSTest.Sdk/Sdk/Sdk.props.template b/src/Package/MSTest.Sdk/Sdk/Sdk.props.template index 2c6fe5ca7d..73530c9e0d 100644 --- a/src/Package/MSTest.Sdk/Sdk/Sdk.props.template +++ b/src/Package/MSTest.Sdk/Sdk/Sdk.props.template @@ -12,6 +12,8 @@ + + false true From 77c0915dfca9d2f0e9acdbced9be391d4f7f1dd9 Mon Sep 17 00:00:00 2001 From: Copilot <198982749+Copilot@users.noreply.github.com> Date: Tue, 27 May 2025 16:02:46 +0200 Subject: [PATCH 034/541] Fix async void analyzer to detect StringAssert and CollectionAssert (#5650) Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: Youssef1313 <31348972+Youssef1313@users.noreply.github.com> Co-authored-by: Youssef Victor --- ...dUsingAssertsInAsyncVoidContextAnalyzer.cs | 27 +++-- ...gAssertsInAsyncVoidContextAnalyzerTests.cs | 98 +++++++++++++++++++ 2 files changed, 119 insertions(+), 6 deletions(-) diff --git a/src/Analyzers/MSTest.Analyzers/AvoidUsingAssertsInAsyncVoidContextAnalyzer.cs b/src/Analyzers/MSTest.Analyzers/AvoidUsingAssertsInAsyncVoidContextAnalyzer.cs index 4a6c6e1a7a..76ecac2e37 100644 --- a/src/Analyzers/MSTest.Analyzers/AvoidUsingAssertsInAsyncVoidContextAnalyzer.cs +++ b/src/Analyzers/MSTest.Analyzers/AvoidUsingAssertsInAsyncVoidContextAnalyzer.cs @@ -46,23 +46,38 @@ public override void Initialize(AnalysisContext context) { Compilation compilation = context.Compilation; INamedTypeSymbol? assertSymbol = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.MicrosoftVisualStudioTestToolsUnitTestingAssert); - if (assertSymbol is not null) + INamedTypeSymbol? stringAssertSymbol = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.MicrosoftVisualStudioTestToolsUnitTestingStringAssert); + INamedTypeSymbol? collectionAssertSymbol = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.MicrosoftVisualStudioTestToolsUnitTestingCollectionAssert); + + if (assertSymbol is not null || stringAssertSymbol is not null || collectionAssertSymbol is not null) { - context.RegisterOperationAction(context => AnalyzeOperation(context, assertSymbol), OperationKind.Invocation); + context.RegisterOperationAction(context => AnalyzeOperation(context, assertSymbol, stringAssertSymbol, collectionAssertSymbol), OperationKind.Invocation); } }); } - private static void AnalyzeOperation(OperationAnalysisContext context, INamedTypeSymbol assertSymbol) + private static void AnalyzeOperation( + OperationAnalysisContext context, + INamedTypeSymbol? assertSymbol, + INamedTypeSymbol? stringAssertSymbol, + INamedTypeSymbol? collectionAssertSymbol) { var operation = (IInvocationOperation)context.Operation; - if (!IsAsyncVoidContext(operation, context.ContainingSymbol) || - !assertSymbol.Equals(operation.TargetMethod.ContainingType, SymbolEqualityComparer.Default)) + if (!IsAsyncVoidContext(operation, context.ContainingSymbol)) { return; } - context.ReportDiagnostic(operation.CreateDiagnostic(Rule)); + INamedTypeSymbol targetType = operation.TargetMethod.ContainingType; + bool isAssertType = + targetType.Equals(assertSymbol, SymbolEqualityComparer.Default) || + targetType.Equals(stringAssertSymbol, SymbolEqualityComparer.Default) || + targetType.Equals(collectionAssertSymbol, SymbolEqualityComparer.Default); + + if (isAssertType) + { + context.ReportDiagnostic(operation.CreateDiagnostic(Rule)); + } } private static bool IsAsyncVoidContext(IInvocationOperation invocationOperation, ISymbol containingSymbol) diff --git a/test/UnitTests/MSTest.Analyzers.UnitTests/AvoidUsingAssertsInAsyncVoidContextAnalyzerTests.cs b/test/UnitTests/MSTest.Analyzers.UnitTests/AvoidUsingAssertsInAsyncVoidContextAnalyzerTests.cs index 378eb183f4..d30fa650da 100644 --- a/test/UnitTests/MSTest.Analyzers.UnitTests/AvoidUsingAssertsInAsyncVoidContextAnalyzerTests.cs +++ b/test/UnitTests/MSTest.Analyzers.UnitTests/AvoidUsingAssertsInAsyncVoidContextAnalyzerTests.cs @@ -131,4 +131,102 @@ async void d() await VerifyCS.VerifyCodeFixAsync(code, code); } + + [TestMethod] + public async Task UseStringAssertMethodInAsyncVoidMethod_Diagnostic() + { + string code = """ + using System.Threading.Tasks; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public async void TestMethod() + { + await Task.Delay(1); + [|StringAssert.Contains("abc", "a")|]; + } + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, code); + } + + [TestMethod] + public async Task UseCollectionAssertMethodInAsyncVoidMethod_Diagnostic() + { + string code = """ + using System.Collections; + using System.Threading.Tasks; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public async void TestMethod() + { + await Task.Delay(1); + [|CollectionAssert.AreEqual(new[] { 1 }, new[] { 1 })|]; + } + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, code); + } + + [TestMethod] + public async Task UseStringAssertMethodInAsyncVoidLocalFunction_Diagnostic() + { + string code = """ + using System.Threading.Tasks; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void TestMethod() + { + async void d() + { + await Task.Delay(1); + [|StringAssert.Contains("abc", "a")|]; + }; + } + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, code); + } + + [TestMethod] + public async Task UseCollectionAssertMethodInAsyncVoidDelegate_Diagnostic() + { + string code = """ + using System.Collections; + using System.Threading.Tasks; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + internal delegate void MyDelegate(); + + [TestMethod] + public void TestMethod() + { + MyDelegate d = async () => + { + await Task.Delay(1); + [|CollectionAssert.AreEqual(new[] { 1 }, new[] { 1 })|]; + }; + } + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, code); + } } From 98b920a80fcc85d41c42ebe976fbdaf9d501f4e6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Jare=C5=A1?= Date: Tue, 27 May 2025 16:13:32 +0200 Subject: [PATCH 035/541] Fix changelog date (#5586) --- docs/Changelog-Platform.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/Changelog-Platform.md b/docs/Changelog-Platform.md index 8a03893f3a..adeb954a97 100644 --- a/docs/Changelog-Platform.md +++ b/docs/Changelog-Platform.md @@ -140,7 +140,7 @@ See full log [of v3.8.1...v3.8.2](https://github.com/microsoft/testfx/compare/v3 ## [1.6.1] - 2025-02-18 -See full log [of 3.8.0...v3.8.1](https://github.com/microsoft/testfx/compare/v3.8.0...v3.8.1) +See full log [of v3.8.0...v3.8.1](https://github.com/microsoft/testfx/compare/v3.8.0...v3.8.1) ### Fixed From cd2feab15426bddfc7039337154c87f21cedc009 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Wed, 28 May 2025 09:34:08 +0200 Subject: [PATCH 036/541] Use IVT from csproj (#5657) --- src/Adapter/MSTest.TestAdapter/Friends.cs | 8 -------- .../MSTest.TestAdapter/MSTest.TestAdapter.csproj | 7 +++++++ src/Adapter/MSTestAdapter.PlatformServices/Friends.cs | 11 ----------- .../MSTestAdapter.PlatformServices.csproj | 4 ++++ src/TestFramework/TestFramework.Extensions/Friends.cs | 10 ---------- .../TestFramework.Extensions.csproj | 2 ++ src/TestFramework/TestFramework/Friends.cs | 8 -------- src/TestFramework/TestFramework/TestFramework.csproj | 8 ++++++-- 8 files changed, 19 insertions(+), 39 deletions(-) delete mode 100644 src/Adapter/MSTest.TestAdapter/Friends.cs delete mode 100644 src/Adapter/MSTestAdapter.PlatformServices/Friends.cs delete mode 100644 src/TestFramework/TestFramework.Extensions/Friends.cs delete mode 100644 src/TestFramework/TestFramework/Friends.cs diff --git a/src/Adapter/MSTest.TestAdapter/Friends.cs b/src/Adapter/MSTest.TestAdapter/Friends.cs deleted file mode 100644 index bdfd4316bd..0000000000 --- a/src/Adapter/MSTest.TestAdapter/Friends.cs +++ /dev/null @@ -1,8 +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. - -// Friend assemblies -[assembly: InternalsVisibleTo(assemblyName: "Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests, PublicKey=002400000480000094000000060200000024000052534131000400000100010007d1fa57c4aed9f0a32e84aa0faefd0de9e8fd6aec8f87fb03766c834c99921eb23be79ad9d5dcc1dd9ad236132102900b723cf980957fc4e177108fc607774f29e8320e92ea05ece4e821c0a5efe8f1645c4c0c93c1ab99285d622caa652c1dfad63d745d6f2de5f17e5eaf0fc4963d261c8a12436518206dc093344d5ad293")] -[assembly: InternalsVisibleTo(assemblyName: "DynamicProxyGenAssembly2, PublicKey=0024000004800000940000000602000000240000525341310004000001000100c547cac37abd99c8db225ef2f6c8a3602f3b3606cc9891605d02baa56104f4cfc0734aa39b93bf7852f7d9266654753cc297e7d2edfe0bac1cdcf9f717241550e0a7b191195b7667bb4f64bcb8e2121380fd1d9d46ad2d92d2d15605093924cceaf74c4861eff62abf69b9291ed0a340e113be11e6a7d3113e92484cf7045cc7")] -[assembly: InternalsVisibleTo(assemblyName: "MSTest.VstestConsoleWrapper.IntegrationTests, PublicKey=002400000480000094000000060200000024000052534131000400000100010007d1fa57c4aed9f0a32e84aa0faefd0de9e8fd6aec8f87fb03766c834c99921eb23be79ad9d5dcc1dd9ad236132102900b723cf980957fc4e177108fc607774f29e8320e92ea05ece4e821c0a5efe8f1645c4c0c93c1ab99285d622caa652c1dfad63d745d6f2de5f17e5eaf0fc4963d261c8a12436518206dc093344d5ad293")] -[assembly: InternalsVisibleTo(assemblyName: "MSTest.IntegrationTests, PublicKey=002400000480000094000000060200000024000052534131000400000100010007d1fa57c4aed9f0a32e84aa0faefd0de9e8fd6aec8f87fb03766c834c99921eb23be79ad9d5dcc1dd9ad236132102900b723cf980957fc4e177108fc607774f29e8320e92ea05ece4e821c0a5efe8f1645c4c0c93c1ab99285d622caa652c1dfad63d745d6f2de5f17e5eaf0fc4963d261c8a12436518206dc093344d5ad293")] diff --git a/src/Adapter/MSTest.TestAdapter/MSTest.TestAdapter.csproj b/src/Adapter/MSTest.TestAdapter/MSTest.TestAdapter.csproj index 9574cbfe6e..14ab40b3f2 100644 --- a/src/Adapter/MSTest.TestAdapter/MSTest.TestAdapter.csproj +++ b/src/Adapter/MSTest.TestAdapter/MSTest.TestAdapter.csproj @@ -137,6 +137,13 @@ + + + + + + + diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Friends.cs b/src/Adapter/MSTestAdapter.PlatformServices/Friends.cs deleted file mode 100644 index ca53146909..0000000000 --- a/src/Adapter/MSTestAdapter.PlatformServices/Friends.cs +++ /dev/null @@ -1,11 +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. - -// Friend assemblies -[assembly: InternalsVisibleTo("Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter, PublicKey=002400000480000094000000060200000024000052534131000400000100010007d1fa57c4aed9f0a32e84aa0faefd0de9e8fd6aec8f87fb03766c834c99921eb23be79ad9d5dcc1dd9ad236132102900b723cf980957fc4e177108fc607774f29e8320e92ea05ece4e821c0a5efe8f1645c4c0c93c1ab99285d622caa652c1dfad63d745d6f2de5f17e5eaf0fc4963d261c8a12436518206dc093344d5ad293")] -[assembly: InternalsVisibleTo("Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.UWP.UnitTests, PublicKey=002400000480000094000000060200000024000052534131000400000100010007d1fa57c4aed9f0a32e84aa0faefd0de9e8fd6aec8f87fb03766c834c99921eb23be79ad9d5dcc1dd9ad236132102900b723cf980957fc4e177108fc607774f29e8320e92ea05ece4e821c0a5efe8f1645c4c0c93c1ab99285d622caa652c1dfad63d745d6f2de5f17e5eaf0fc4963d261c8a12436518206dc093344d5ad293")] -[assembly: InternalsVisibleTo("Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.WinUI.UnitTests, PublicKey=002400000480000094000000060200000024000052534131000400000100010007d1fa57c4aed9f0a32e84aa0faefd0de9e8fd6aec8f87fb03766c834c99921eb23be79ad9d5dcc1dd9ad236132102900b723cf980957fc4e177108fc607774f29e8320e92ea05ece4e821c0a5efe8f1645c4c0c93c1ab99285d622caa652c1dfad63d745d6f2de5f17e5eaf0fc4963d261c8a12436518206dc093344d5ad293")] -[assembly: InternalsVisibleTo("MSTestAdapter.PlatformServices.UnitTests, PublicKey=002400000480000094000000060200000024000052534131000400000100010007d1fa57c4aed9f0a32e84aa0faefd0de9e8fd6aec8f87fb03766c834c99921eb23be79ad9d5dcc1dd9ad236132102900b723cf980957fc4e177108fc607774f29e8320e92ea05ece4e821c0a5efe8f1645c4c0c93c1ab99285d622caa652c1dfad63d745d6f2de5f17e5eaf0fc4963d261c8a12436518206dc093344d5ad293")] -[assembly: InternalsVisibleTo("PlatformServices.Desktop.IntegrationTests, PublicKey=002400000480000094000000060200000024000052534131000400000100010007d1fa57c4aed9f0a32e84aa0faefd0de9e8fd6aec8f87fb03766c834c99921eb23be79ad9d5dcc1dd9ad236132102900b723cf980957fc4e177108fc607774f29e8320e92ea05ece4e821c0a5efe8f1645c4c0c93c1ab99285d622caa652c1dfad63d745d6f2de5f17e5eaf0fc4963d261c8a12436518206dc093344d5ad293")] -[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2, PublicKey=0024000004800000940000000602000000240000525341310004000001000100c547cac37abd99c8db225ef2f6c8a3602f3b3606cc9891605d02baa56104f4cfc0734aa39b93bf7852f7d9266654753cc297e7d2edfe0bac1cdcf9f717241550e0a7b191195b7667bb4f64bcb8e2121380fd1d9d46ad2d92d2d15605093924cceaf74c4861eff62abf69b9291ed0a340e113be11e6a7d3113e92484cf7045cc7")] -[assembly: InternalsVisibleTo("MSTest.TestAnywhereAdapter, PublicKey=002400000480000094000000060200000024000052534131000400000100010007d1fa57c4aed9f0a32e84aa0faefd0de9e8fd6aec8f87fb03766c834c99921eb23be79ad9d5dcc1dd9ad236132102900b723cf980957fc4e177108fc607774f29e8320e92ea05ece4e821c0a5efe8f1645c4c0c93c1ab99285d622caa652c1dfad63d745d6f2de5f17e5eaf0fc4963d261c8a12436518206dc093344d5ad293")] diff --git a/src/Adapter/MSTestAdapter.PlatformServices/MSTestAdapter.PlatformServices.csproj b/src/Adapter/MSTestAdapter.PlatformServices/MSTestAdapter.PlatformServices.csproj index 15b5a1ee54..bc76142b55 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/MSTestAdapter.PlatformServices.csproj +++ b/src/Adapter/MSTestAdapter.PlatformServices/MSTestAdapter.PlatformServices.csproj @@ -48,7 +48,11 @@ + + + + diff --git a/src/TestFramework/TestFramework.Extensions/Friends.cs b/src/TestFramework/TestFramework.Extensions/Friends.cs deleted file mode 100644 index 57566ec3fd..0000000000 --- a/src/TestFramework/TestFramework.Extensions/Friends.cs +++ /dev/null @@ -1,10 +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. - -// Friend assemblies -[assembly: InternalsVisibleTo("Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices, PublicKey=002400000480000094000000060200000024000052534131000400000100010007d1fa57c4aed9f0a32e84aa0faefd0de9e8fd6aec8f87fb03766c834c99921eb23be79ad9d5dcc1dd9ad236132102900b723cf980957fc4e177108fc607774f29e8320e92ea05ece4e821c0a5efe8f1645c4c0c93c1ab99285d622caa652c1dfad63d745d6f2de5f17e5eaf0fc4963d261c8a12436518206dc093344d5ad293")] -[assembly: InternalsVisibleTo("MSTestAdapter.PlatformServices.UnitTests, PublicKey=002400000480000094000000060200000024000052534131000400000100010007d1fa57c4aed9f0a32e84aa0faefd0de9e8fd6aec8f87fb03766c834c99921eb23be79ad9d5dcc1dd9ad236132102900b723cf980957fc4e177108fc607774f29e8320e92ea05ece4e821c0a5efe8f1645c4c0c93c1ab99285d622caa652c1dfad63d745d6f2de5f17e5eaf0fc4963d261c8a12436518206dc093344d5ad293")] - -#if WINDOWS_UWP || WIN_UI -[assembly: InternalsVisibleTo("Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices, PublicKey=002400000480000094000000060200000024000052534131000400000100010007d1fa57c4aed9f0a32e84aa0faefd0de9e8fd6aec8f87fb03766c834c99921eb23be79ad9d5dcc1dd9ad236132102900b723cf980957fc4e177108fc607774f29e8320e92ea05ece4e821c0a5efe8f1645c4c0c93c1ab99285d622caa652c1dfad63d745d6f2de5f17e5eaf0fc4963d261c8a12436518206dc093344d5ad293")] -#endif diff --git a/src/TestFramework/TestFramework.Extensions/TestFramework.Extensions.csproj b/src/TestFramework/TestFramework.Extensions/TestFramework.Extensions.csproj index 134b272c10..94c011302c 100644 --- a/src/TestFramework/TestFramework.Extensions/TestFramework.Extensions.csproj +++ b/src/TestFramework/TestFramework.Extensions/TestFramework.Extensions.csproj @@ -92,6 +92,8 @@ + + diff --git a/src/TestFramework/TestFramework/Friends.cs b/src/TestFramework/TestFramework/Friends.cs deleted file mode 100644 index ebbc3313b8..0000000000 --- a/src/TestFramework/TestFramework/Friends.cs +++ /dev/null @@ -1,8 +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. - -[assembly: InternalsVisibleTo("Microsoft.VisualStudio.TestPlatform.TestFramework.UnitTests, PublicKey=002400000480000094000000060200000024000052534131000400000100010007d1fa57c4aed9f0a32e84aa0faefd0de9e8fd6aec8f87fb03766c834c99921eb23be79ad9d5dcc1dd9ad236132102900b723cf980957fc4e177108fc607774f29e8320e92ea05ece4e821c0a5efe8f1645c4c0c93c1ab99285d622caa652c1dfad63d745d6f2de5f17e5eaf0fc4963d261c8a12436518206dc093344d5ad293")] -[assembly: InternalsVisibleTo("Microsoft.VisualStudio.TestPlatform.TestFramework.Extensions, PublicKey=002400000480000094000000060200000024000052534131000400000100010007d1fa57c4aed9f0a32e84aa0faefd0de9e8fd6aec8f87fb03766c834c99921eb23be79ad9d5dcc1dd9ad236132102900b723cf980957fc4e177108fc607774f29e8320e92ea05ece4e821c0a5efe8f1645c4c0c93c1ab99285d622caa652c1dfad63d745d6f2de5f17e5eaf0fc4963d261c8a12436518206dc093344d5ad293")] -[assembly: InternalsVisibleTo("Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter, PublicKey=002400000480000094000000060200000024000052534131000400000100010007d1fa57c4aed9f0a32e84aa0faefd0de9e8fd6aec8f87fb03766c834c99921eb23be79ad9d5dcc1dd9ad236132102900b723cf980957fc4e177108fc607774f29e8320e92ea05ece4e821c0a5efe8f1645c4c0c93c1ab99285d622caa652c1dfad63d745d6f2de5f17e5eaf0fc4963d261c8a12436518206dc093344d5ad293")] -[assembly: InternalsVisibleTo("Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices, PublicKey=002400000480000094000000060200000024000052534131000400000100010007d1fa57c4aed9f0a32e84aa0faefd0de9e8fd6aec8f87fb03766c834c99921eb23be79ad9d5dcc1dd9ad236132102900b723cf980957fc4e177108fc607774f29e8320e92ea05ece4e821c0a5efe8f1645c4c0c93c1ab99285d622caa652c1dfad63d745d6f2de5f17e5eaf0fc4963d261c8a12436518206dc093344d5ad293")] -[assembly: InternalsVisibleTo("MSTest.TestAnywhereAdapter, PublicKey=002400000480000094000000060200000024000052534131000400000100010007d1fa57c4aed9f0a32e84aa0faefd0de9e8fd6aec8f87fb03766c834c99921eb23be79ad9d5dcc1dd9ad236132102900b723cf980957fc4e177108fc607774f29e8320e92ea05ece4e821c0a5efe8f1645c4c0c93c1ab99285d622caa652c1dfad63d745d6f2de5f17e5eaf0fc4963d261c8a12436518206dc093344d5ad293")] diff --git a/src/TestFramework/TestFramework/TestFramework.csproj b/src/TestFramework/TestFramework/TestFramework.csproj index a48363f7b4..5aa402300c 100644 --- a/src/TestFramework/TestFramework/TestFramework.csproj +++ b/src/TestFramework/TestFramework/TestFramework.csproj @@ -33,9 +33,13 @@ - - + + + + + + From 892bce4ecb01a5d72168b6f153133551d7e1654b Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Wed, 28 May 2025 10:08:06 +0200 Subject: [PATCH 037/541] VSTestBridge: Handle TestPropertyAttributes.Trait instead of special casing specific properties (#5644) --- .../ObjectModel/ObjectModelConverters.cs | 46 ++++++++----------- .../ObjectModel/ObjectModelConvertersTests.cs | 8 +++- 2 files changed, 26 insertions(+), 28 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/ObjectModelConverters.cs b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/ObjectModelConverters.cs index 4a801d1c4d..43cecb9491 100644 --- a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/ObjectModelConverters.cs +++ b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/ObjectModelConverters.cs @@ -34,18 +34,6 @@ internal static class ObjectModelConverters valueType: typeof(string), owner: typeof(TestCase)); - private static readonly TestProperty TestCategoryProperty = TestProperty.Register( - id: "MSTestDiscoverer.TestCategory", - label: "TestCategory", - valueType: typeof(string[]), - owner: typeof(TestCase)); - - private static readonly TestProperty TraitsProperty = TestProperty.Register( - id: "TestObject.Traits", - label: "Traits", - valueType: typeof(KeyValuePair[]), - owner: typeof(TestObject)); - /// /// Converts a VSTest to a Microsoft Testing Platform . /// @@ -82,27 +70,33 @@ public static TestNode ToTestNode(this TestCase testCase, bool isTrxEnabled, INa private static void CopyCategoryAndTraits(TestObject testCaseOrResult, TestNode testNode, bool isTrxEnabled) { - // TPv2 is doing some special handling for MSTest... we should probably do the same. - // See https://github.com/microsoft/vstest/blob/main/src/Microsoft.TestPlatform.Extensions.TrxLogger/Utility/Converter.cs#L66-L70 - if (testCaseOrResult.GetPropertyValue(TestCategoryProperty, defaultValue: null) is string[] mstestCategories) + foreach (KeyValuePair property in testCaseOrResult.GetProperties()) { - if (isTrxEnabled) +#pragma warning disable CS0618 // Type or member is obsolete + if ((property.Key.Attributes & TestPropertyAttributes.Trait) == 0) +#pragma warning restore CS0618 // Type or member is obsolete { - testNode.Properties.Add(new TrxCategoriesProperty(mstestCategories)); + continue; } - foreach (string category in mstestCategories) + if (property.Value is string[] categories) { - testNode.Properties.Add(new TestMetadataProperty(category, string.Empty)); - } - } + if (isTrxEnabled) + { + testNode.Properties.Add(new TrxCategoriesProperty(categories)); + } - if (testCaseOrResult.GetPropertyValue[]>(TraitsProperty, defaultValue: null) is KeyValuePair[] traits && - traits.Length > 0) - { - foreach (KeyValuePair trait in traits) + foreach (string category in categories) + { + testNode.Properties.Add(new TestMetadataProperty(category, string.Empty)); + } + } + else if (property.Value is KeyValuePair[] traits) { - testNode.Properties.Add(new TestMetadataProperty(trait.Key, trait.Value)); + foreach (KeyValuePair trait in traits) + { + testNode.Properties.Add(new TestMetadataProperty(trait.Key, trait.Value)); + } } } } diff --git a/test/UnitTests/Microsoft.Testing.Extensions.VSTestBridge.UnitTests/ObjectModel/ObjectModelConvertersTests.cs b/test/UnitTests/Microsoft.Testing.Extensions.VSTestBridge.UnitTests/ObjectModel/ObjectModelConvertersTests.cs index 09809de7f8..14d64e2688 100644 --- a/test/UnitTests/Microsoft.Testing.Extensions.VSTestBridge.UnitTests/ObjectModel/ObjectModelConvertersTests.cs +++ b/test/UnitTests/Microsoft.Testing.Extensions.VSTestBridge.UnitTests/ObjectModel/ObjectModelConvertersTests.cs @@ -76,7 +76,9 @@ public void ToTestNode_WhenTestResultOutcomeIsFailed_TestNodePropertiesContainFa public void ToTestNode_WhenTestResultHasMSTestDiscovererTestCategoryTestProperty_TestNodePropertiesContainTheCategoryInTraits() { TestResult testResult = new(new TestCase("SomeFqn", new("executor://uri", UriKind.Absolute), "source.cs")); - var testCategoryProperty = TestProperty.Register("MSTestDiscoverer.TestCategory", "Label", typeof(string[]), TestPropertyAttributes.None, typeof(TestCase)); +#pragma warning disable CS0618 // Type or member is obsolete + var testCategoryProperty = TestProperty.Register("MSTestDiscoverer.TestCategory", "Label", typeof(string[]), TestPropertyAttributes.Trait, typeof(TestCase)); +#pragma warning restore CS0618 // Type or member is obsolete testResult.SetPropertyValue(testCategoryProperty, ["category1"]); var testNode = testResult.ToTestNode(false, new NamedFeatureCapabilityWithVSTestProvider(), new ServerModeCommandLineOptions(), ClientInfo); @@ -91,7 +93,9 @@ public void ToTestNode_WhenTestResultHasMSTestDiscovererTestCategoryTestProperty public void ToTestNode_WhenTestResultHasMSTestDiscovererTestCategoryTestPropertyWithTrxEnabled_TestNodePropertiesContainTrxCategoriesProperty() { TestResult testResult = new(new TestCase("assembly.class.SomeFqn", new("executor://uri", UriKind.Absolute), "source.cs")); - var testCategoryProperty = TestProperty.Register("MSTestDiscoverer.TestCategory", "Label", typeof(string[]), TestPropertyAttributes.None, typeof(TestCase)); +#pragma warning disable CS0618 // Type or member is obsolete + var testCategoryProperty = TestProperty.Register("MSTestDiscoverer.TestCategory", "Label", typeof(string[]), TestPropertyAttributes.Trait, typeof(TestCase)); +#pragma warning restore CS0618 // Type or member is obsolete testResult.SetPropertyValue(testCategoryProperty, ["category1"]); var testNode = testResult.ToTestNode(true, new NamedFeatureCapabilityWithVSTestProvider(), new ServerModeCommandLineOptions(), ClientInfo); From 9de320e234009dce7283d76ef9669b8c884d877f Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Thu, 29 May 2025 11:02:27 +0200 Subject: [PATCH 038/541] Cleanup dead code in MTP (#5660) --- .../Builder/TestApplicationBuilder.cs | 3 -- .../Hosts/ITestHostBuilder.cs | 3 -- .../Hosts/TestHostBuilder.cs | 6 +-- .../Resources/PlatformResources.resx | 6 --- .../Resources/xlf/PlatformResources.cs.xlf | 10 ----- .../Resources/xlf/PlatformResources.de.xlf | 10 ----- .../Resources/xlf/PlatformResources.es.xlf | 10 ----- .../Resources/xlf/PlatformResources.fr.xlf | 10 ----- .../Resources/xlf/PlatformResources.it.xlf | 10 ----- .../Resources/xlf/PlatformResources.ja.xlf | 10 ----- .../Resources/xlf/PlatformResources.ko.xlf | 10 ----- .../Resources/xlf/PlatformResources.pl.xlf | 10 ----- .../Resources/xlf/PlatformResources.pt-BR.xlf | 10 ----- .../Resources/xlf/PlatformResources.ru.xlf | 10 ----- .../Resources/xlf/PlatformResources.tr.xlf | 10 ----- .../xlf/PlatformResources.zh-Hans.xlf | 10 ----- .../xlf/PlatformResources.zh-Hant.xlf | 10 ----- .../ServerMode/JsonRpc/IServerModeManager.cs | 6 --- .../JsonRpc/JsonRpcTcpServerToSingleClient.cs | 20 --------- .../JsonRpc/MessageHandlerFactory.cs | 41 +++---------------- .../ServerMode/JsonRpc/ServerModeManager.cs | 32 ++------------- 21 files changed, 10 insertions(+), 237 deletions(-) delete mode 100644 src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/IServerModeManager.cs delete mode 100644 src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/JsonRpcTcpServerToSingleClient.cs diff --git a/src/Platform/Microsoft.Testing.Platform/Builder/TestApplicationBuilder.cs b/src/Platform/Microsoft.Testing.Platform/Builder/TestApplicationBuilder.cs index ee07ce0ba1..4147baebc8 100644 --- a/src/Platform/Microsoft.Testing.Platform/Builder/TestApplicationBuilder.cs +++ b/src/Platform/Microsoft.Testing.Platform/Builder/TestApplicationBuilder.cs @@ -11,7 +11,6 @@ using Microsoft.Testing.Platform.Hosts; using Microsoft.Testing.Platform.Logging; using Microsoft.Testing.Platform.Resources; -using Microsoft.Testing.Platform.ServerMode; using Microsoft.Testing.Platform.Services; using Microsoft.Testing.Platform.Telemetry; using Microsoft.Testing.Platform.TestHost; @@ -53,8 +52,6 @@ internal TestApplicationBuilder( public ICommandLineManager CommandLine => _testHostBuilder.CommandLine; - internal IServerModeManager ServerMode => _testHostBuilder.ServerMode; - internal ITestHostOrchestratorManager TestHostOrchestrator => _testHostBuilder.TestHostOrchestratorManager; [Obsolete("Remove in v2. Avoid breaking change with the rename of the property. See https://github.com/microsoft/testfx/issues/5015", error: true)] diff --git a/src/Platform/Microsoft.Testing.Platform/Hosts/ITestHostBuilder.cs b/src/Platform/Microsoft.Testing.Platform/Hosts/ITestHostBuilder.cs index dfe44cd17b..38803debf2 100644 --- a/src/Platform/Microsoft.Testing.Platform/Hosts/ITestHostBuilder.cs +++ b/src/Platform/Microsoft.Testing.Platform/Hosts/ITestHostBuilder.cs @@ -8,7 +8,6 @@ using Microsoft.Testing.Platform.Extensions.TestHostOrchestrator; using Microsoft.Testing.Platform.Helpers; using Microsoft.Testing.Platform.Logging; -using Microsoft.Testing.Platform.ServerMode; using Microsoft.Testing.Platform.Telemetry; using Microsoft.Testing.Platform.TestHost; using Microsoft.Testing.Platform.TestHostControllers; @@ -34,8 +33,6 @@ internal interface ITestHostBuilder ITelemetryManager Telemetry { get; } - IServerModeManager ServerMode { get; } - IToolsManager Tools { get; } Task BuildAsync(ApplicationLoggingState loggingState, TestApplicationOptions testApplicationOptions, IUnhandledExceptionsHandler unhandledExceptionsHandler, DateTimeOffset createBuilderStart); diff --git a/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostBuilder.cs b/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostBuilder.cs index 4f11f189c8..3f7f116f16 100644 --- a/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostBuilder.cs +++ b/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostBuilder.cs @@ -46,8 +46,6 @@ internal sealed class TestHostBuilder(IFileSystem fileSystem, IRuntimeFeature ru public ITelemetryManager Telemetry { get; } = new TelemetryManager(); - public IServerModeManager ServerMode { get; } = new ServerModeManager(); - public ITestHostControllersManager TestHostControllers { get; } = new TestHostControllersManager(); public IToolsManager Tools { get; } = new ToolsManager(); @@ -380,7 +378,7 @@ await LogTestHostCreatedAsync( if (hasServerFlag && isJsonRpcProtocol) { // Build the IMessageHandlerFactory for the PassiveNode - IMessageHandlerFactory messageHandlerFactory = ((ServerModeManager)ServerMode).Build(serviceProvider); + IMessageHandlerFactory messageHandlerFactory = ServerModeManager.Build(serviceProvider); passiveNode = new PassiveNode( messageHandlerFactory, testApplicationCancellationTokenSource, @@ -445,7 +443,7 @@ await LogTestHostCreatedAsync( if (hasServerFlag && isJsonRpcProtocol) { // Build the server mode with the user preferences - IMessageHandlerFactory messageHandlerFactory = ((ServerModeManager)ServerMode).Build(serviceProvider); + IMessageHandlerFactory messageHandlerFactory = ServerModeManager.Build(serviceProvider); // Build the test host // note that we pass the BuildTestFrameworkAsync as callback because server mode will call it per-request diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/PlatformResources.resx b/src/Platform/Microsoft.Testing.Platform/Resources/PlatformResources.resx index b894e8fe79..51ec6ea19f 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/PlatformResources.resx +++ b/src/Platform/Microsoft.Testing.Platform/Resources/PlatformResources.resx @@ -444,12 +444,6 @@ The default is TestResults in the directory that contains the test application.< JsonRpc server to client handshake, implementation based on the test platform protocol specification. - - Starting server. Listening on port '{0}' - - - The communication protocol '{0}' is not supported - Telemetry --------- diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.cs.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.cs.xlf index 850364800b..bf97e9b009 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.cs.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.cs.xlf @@ -733,11 +733,6 @@ Může mít jenom jeden argument jako řetězec ve formátu <value>[h|m|s] Standardní výstup - - Starting server. Listening on port '{0}' - Spouští se server. Naslouchání na portu {0} - - Starting test session. Spouští se testovací relace. @@ -952,11 +947,6 @@ Platné hodnoty jsou Normal a Detailed. Výchozí hodnota je Normal. Neočekávaný stav v souboru {0} na řádku {1} - - The communication protocol '{0}' is not supported - Komunikační protokol {0} není podporován. - - [ServerTestHost.OnTaskSchedulerUnobservedTaskException] Unhandled exception: {0} [ServerTestHost.OnTaskSchedulerUnobservedTaskException] Neošetřená výjimka: {0} diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.de.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.de.xlf index f945fff2db..d657755538 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.de.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.de.xlf @@ -733,11 +733,6 @@ Nimmt ein Argument als Zeichenfolge im Format <value>[h|m|s], wobei "value Standardausgabe - - Starting server. Listening on port '{0}' - Server wird gestartet. An Port "{0}" lauschen - - Starting test session. Die Testsitzung wird gestartet. @@ -952,11 +947,6 @@ Gültige Werte sind „Normal“, „Detailed“. Der Standardwert ist „Normal Unerwarteter Status in Datei "{0}" in Zeile "{1}" - - The communication protocol '{0}' is not supported - Das Kommunikationsprotokoll "{0}" wird nicht unterstützt - - [ServerTestHost.OnTaskSchedulerUnobservedTaskException] Unhandled exception: {0} [ServerTestHost.OnTaskSchedulerUnobservedTaskException] Ausnahmefehler: {0} diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.es.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.es.xlf index a264892a13..493fe65d2a 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.es.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.es.xlf @@ -733,11 +733,6 @@ Toma un argumento como cadena con el formato <value>[h|m|s] donde 'value' Salida estándar - - Starting server. Listening on port '{0}' - Iniciando el servidor. Escuchando en el puerto '{0}' - - Starting test session. Iniciando sesión de prueba. @@ -952,11 +947,6 @@ Los valores válidos son 'Normal', 'Detallado'. El valor predeterminado es 'Norm Estado inesperado en el archivo “{0}” en la línea “{1}” - - The communication protocol '{0}' is not supported - No se admite el protocolo de comunicación '{0}' - - [ServerTestHost.OnTaskSchedulerUnobservedTaskException] Unhandled exception: {0} [ServerTestHost.OnTaskSchedulerUnobservedTaskException] excepción no controlada: {0} diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.fr.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.fr.xlf index 6c08b3f8dc..f82ac26b64 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.fr.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.fr.xlf @@ -733,11 +733,6 @@ Prend un argument sous forme de chaîne au format <value>[h|m|s] où « v Sortie standard - - Starting server. Listening on port '{0}' - Démarrage du serveur. Écoute sur le port « {0} » - - Starting test session. Démarrage de la session de test. @@ -952,11 +947,6 @@ Les valeurs valides sont « Normal » et « Détaillé ». La valeur par dé État inattendu dans le fichier « {0} » à la ligne « {1} » - - The communication protocol '{0}' is not supported - Le protocole de communication « {0} » n’est pas pris en charge - - [ServerTestHost.OnTaskSchedulerUnobservedTaskException] Unhandled exception: {0} [ServerTestHost.OnTaskSchedulerUnobservedTaskException] exception non prise en charge : {0} diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.it.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.it.xlf index bb1706795d..0f9e8cf771 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.it.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.it.xlf @@ -733,11 +733,6 @@ Acquisisce un argomento come stringa nel formato <value>[h|m|s] dove 'valu Output standard - - Starting server. Listening on port '{0}' - Avvio del server. In ascolto sulla porta '{0}' - - Starting test session. Avvio della sessione di test. @@ -952,11 +947,6 @@ I valori validi sono 'Normal', 'Detailed'. L'impostazione predefinita è 'Normal Stato imprevisto nel file '{0}' alla riga '{1}' - - The communication protocol '{0}' is not supported - Il protocollo di comunicazione '{0}' non è supportato - - [ServerTestHost.OnTaskSchedulerUnobservedTaskException] Unhandled exception: {0} [ServerTestHost.OnTaskSchedulerUnobservedTaskException] eccezione non gestita: {0} diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ja.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ja.xlf index 825b4cc593..52d494a080 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ja.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ja.xlf @@ -734,11 +734,6 @@ Takes one argument as string in the format <value>[h|m|s] where 'value' is 標準出力 - - Starting server. Listening on port '{0}' - サーバーを起動しています。ポート '{0}' で聞いています - - Starting test session. テスト セッションを開始しています。 @@ -953,11 +948,6 @@ Valid values are 'Normal', 'Detailed'. Default is 'Normal'. ファイル '{0}' の行 '{1}' の予期しない状態 - - The communication protocol '{0}' is not supported - 通信プロトコル '{0}' はサポートされていません - - [ServerTestHost.OnTaskSchedulerUnobservedTaskException] Unhandled exception: {0} ハンドルされない例外 [ServerTestHost.OnTaskSchedulerUnobservedTaskException]: {0} diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ko.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ko.xlf index 5b3fd3add9..2bddcfd54c 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ko.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ko.xlf @@ -733,11 +733,6 @@ Takes one argument as string in the format <value>[h|m|s] where 'value' is 표준 출력 - - Starting server. Listening on port '{0}' - 서버를 시작하는 중입니다. 포트 '{0}'에서 수신 대기 중 - - Starting test session. 테스트 세션을 시작하는 중입니다. @@ -952,11 +947,6 @@ Valid values are 'Normal', 'Detailed'. Default is 'Normal'. '{1}' 줄의 '{0}' 파일에 예기치 않은 상태가 있습니다. - - The communication protocol '{0}' is not supported - 통신 프로토콜 '{0}'은(는) 지원되지 않습니다. - - [ServerTestHost.OnTaskSchedulerUnobservedTaskException] Unhandled exception: {0} 처리되지 않은 예외 [ServerTestHost.OnTaskSchedulerUnobservedTaskException]: {0} diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pl.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pl.xlf index 4f723bdd74..9fa4232e0d 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pl.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pl.xlf @@ -733,11 +733,6 @@ Pobiera jeden argument jako ciąg w formacie <value>[h|m|s], gdzie element Standardowe dane wyjściowe - - Starting server. Listening on port '{0}' - Uruchamianie serwera. Nasłuchiwanie na porcie „{0}” - - Starting test session. Rozpoczynanie sesji testowej. @@ -952,11 +947,6 @@ Prawidłowe wartości to „Normalne”, „Szczegółowe”. Wartość domyśln Nieoczekiwany stan w pliku „{0}” w wierszu „{1}” - - The communication protocol '{0}' is not supported - Protokół komunikacyjny „{0}” nie jest obsługiwany - - [ServerTestHost.OnTaskSchedulerUnobservedTaskException] Unhandled exception: {0} [ServerTestHost.OnTaskSchedulerUnobservedTaskException] Nieobsługiwany wyjątek: {0} diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pt-BR.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pt-BR.xlf index df330a27f2..c24d1413ab 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pt-BR.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pt-BR.xlf @@ -733,11 +733,6 @@ Recebe um argumento como cadeia de caracteres no formato <valor>[h|m|s] em Saída padrão - - Starting server. Listening on port '{0}' - Iniciando servidor. Escutando na porta “{0}” - - Starting test session. Iniciando sessão de teste. @@ -952,11 +947,6 @@ Os valores válidos são “Normal”, “Detalhado”. O padrão é “Normal Estado inesperado no arquivo '{0}' na linha '{1}' - - The communication protocol '{0}' is not supported - O protocolo de comunicação “{0}” não tem suporte - - [ServerTestHost.OnTaskSchedulerUnobservedTaskException] Unhandled exception: {0} [ServerTestHost.OnTaskSchedulerUnobservedTaskException] exceção sem tratamento: {0} diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ru.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ru.xlf index 85478d870f..089434cc81 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ru.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ru.xlf @@ -733,11 +733,6 @@ Takes one argument as string in the format <value>[h|m|s] where 'value' is Стандартный вывод - - Starting server. Listening on port '{0}' - Выполняется запуск сервера. Прослушивание порта "{0}" - - Starting test session. Запуск тестового сеанса. @@ -952,11 +947,6 @@ Valid values are 'Normal', 'Detailed'. Default is 'Normal'. Непредвиденное состояние в файле "{0}" в строке "{1}" - - The communication protocol '{0}' is not supported - Протокол коммуникации "{0}" не поддерживается - - [ServerTestHost.OnTaskSchedulerUnobservedTaskException] Unhandled exception: {0} [ServerTestHost.OnTaskSchedulerUnobservedTaskException] необработанное исключение: {0} diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.tr.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.tr.xlf index 4c7c2fbd6c..67ff90a823 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.tr.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.tr.xlf @@ -733,11 +733,6 @@ Bir bağımsız değişkeni, 'value' değerinin kayan olduğu <value>[h|m| Standart çıkış - - Starting server. Listening on port '{0}' - Sunucu başlatılıyor. '{0}' bağlantı noktasında dinleme işlemi yapılıyor - - Starting test session. Test oturumu başlatılıyor. @@ -952,11 +947,6 @@ Geçerli değerler: ‘Normal’, ‘Ayrıntılı’. Varsayılan değer: ‘Nor '{0}' dosyasında '{1}' satırındaki durum beklenmiyordu - - The communication protocol '{0}' is not supported - '{0}' iletişim protokolü desteklenmiyor - - [ServerTestHost.OnTaskSchedulerUnobservedTaskException] Unhandled exception: {0} [ServerTestHost.OnTaskSchedulerUnobservedTaskException] özel durum: {0} diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hans.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hans.xlf index 15741f97e4..5e2dfad71d 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hans.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hans.xlf @@ -733,11 +733,6 @@ Takes one argument as string in the format <value>[h|m|s] where 'value' is 标准输出 - - Starting server. Listening on port '{0}' - 正在启动服务器。正在侦听端口“{0}” - - Starting test session. 正在启动测试会话。 @@ -952,11 +947,6 @@ Valid values are 'Normal', 'Detailed'. Default is 'Normal'. 文件“{0}”中第“{1}”行出现意外状态 - - The communication protocol '{0}' is not supported - 不支持通信协议“{0}” - - [ServerTestHost.OnTaskSchedulerUnobservedTaskException] Unhandled exception: {0} [ServerTestHost.OnTaskSchedulerUnobservedTaskException] 未经处理的异常: {0} diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hant.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hant.xlf index a788e45f92..8bf8789838 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hant.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hant.xlf @@ -733,11 +733,6 @@ Takes one argument as string in the format <value>[h|m|s] where 'value' is 標準輸出 - - Starting server. Listening on port '{0}' - 正在啟動伺服器。正在連接埠 '{0}' 上聆聽 - - Starting test session. 正在啟動測試會話。 @@ -952,11 +947,6 @@ Valid values are 'Normal', 'Detailed'. Default is 'Normal'. 檔案 '{0}' 的第 '{1}' 行出現未預期的狀態 - - The communication protocol '{0}' is not supported - 通訊協定 '{0}' 不受支援 - - [ServerTestHost.OnTaskSchedulerUnobservedTaskException] Unhandled exception: {0} [ServerTestHost.OnTaskSchedulerUnobservedTaskException] 未處理的例外狀況: {0} diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/IServerModeManager.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/IServerModeManager.cs deleted file mode 100644 index dde41a1521..0000000000 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/IServerModeManager.cs +++ /dev/null @@ -1,6 +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. - -namespace Microsoft.Testing.Platform.ServerMode; - -internal interface IServerModeManager; diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/JsonRpcTcpServerToSingleClient.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/JsonRpcTcpServerToSingleClient.cs deleted file mode 100644 index 93865858e6..0000000000 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/JsonRpcTcpServerToSingleClient.cs +++ /dev/null @@ -1,20 +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 Microsoft.Testing.Platform.Helpers; -using Microsoft.Testing.Platform.Resources; - -namespace Microsoft.Testing.Platform.ServerMode; - -internal sealed class JsonRpcTcpServerToSingleClient(string clientHostName, int clientPort) : ICommunicationProtocol -{ - public string ClientHostName { get; } = clientHostName; - - public int ClientPort { get; } = clientPort; - - public string Name => nameof(JsonRpcTcpServerToSingleClient); - - public string Version => AppVersion.DefaultSemVer; - - public string Description => PlatformResources.JsonRpcTcpServerToSingleClientDescription; -} diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/MessageHandlerFactory.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/MessageHandlerFactory.cs index 6c578c2197..060a2a7562 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/MessageHandlerFactory.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/MessageHandlerFactory.cs @@ -15,7 +15,7 @@ internal sealed partial class ServerModeManager { internal sealed class MessageHandlerFactory : IMessageHandlerFactory, IOutputDeviceDataProducer { - private readonly string? _host; + private readonly string _host; private readonly int _port; private readonly IOutputDevice _outputDevice; @@ -39,52 +39,21 @@ public MessageHandlerFactory( public string Description => nameof(MessageHandlerFactory); - public Task CreateMessageHandlerAsync(CancellationToken cancellationToken) - => _host is not null - ? ConnectToTestPlatformClientAsync(_host, _port, cancellationToken) - : StartTestPlatformServerAsync(port: _port, cancellationToken); - #pragma warning disable CA1416 // Validate platform compatibility - private async Task ConnectToTestPlatformClientAsync(string clientHost, int clientPort, CancellationToken cancellationToken) + public async Task CreateMessageHandlerAsync(CancellationToken cancellationToken) { - await _outputDevice.DisplayAsync(this, new TextOutputDeviceData(string.Format(CultureInfo.InvariantCulture, PlatformResources.ConnectingToClientHost, clientHost, clientPort))); + await _outputDevice.DisplayAsync(this, new TextOutputDeviceData(string.Format(CultureInfo.InvariantCulture, PlatformResources.ConnectingToClientHost, _host, _port))); TcpClient client = new(); #if NETCOREAPP - await client.ConnectAsync(host: clientHost, port: clientPort, cancellationToken); + await client.ConnectAsync(host: _host, port: _port, cancellationToken); #else - await client.ConnectAsync(host: clientHost, port: clientPort).WithCancellationAsync(cancellationToken, observeException: true); + await client.ConnectAsync(host: _host, port: _port).WithCancellationAsync(cancellationToken, observeException: true); #endif NetworkStream stream = client.GetStream(); return new TcpMessageHandler(client, clientToServerStream: stream, serverToClientStream: stream, FormatterUtilities.CreateFormatter()); } - - private async Task StartTestPlatformServerAsync(int? port, CancellationToken cancellationToken) - { - port ??= 0; - IPEndPoint endPoint = new(IPAddress.Loopback, port.Value); - TcpListener listener = new(endPoint); - - listener.Start(); - try - { - await _outputDevice.DisplayAsync(this, new TextOutputDeviceData(string.Format(CultureInfo.InvariantCulture, PlatformResources.StartingServer, ((IPEndPoint)listener.LocalEndpoint).Port))); - -#if NETCOREAPP - TcpClient client = await listener.AcceptTcpClientAsync(cancellationToken); -#else - TcpClient client = await listener.AcceptTcpClientAsync().WithCancellationAsync(cancellationToken); -#endif - NetworkStream stream = client.GetStream(); - return new TcpMessageHandler(client, clientToServerStream: stream, serverToClientStream: stream, FormatterUtilities.CreateFormatter()); - } - catch (OperationCanceledException oc) when (oc.CancellationToken == cancellationToken) - { - listener.Stop(); - throw; - } - } #pragma warning restore CA1416 public Task IsEnabledAsync() => Task.FromResult(false); diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/ServerModeManager.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/ServerModeManager.cs index c0bc80727b..b9ee389873 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/ServerModeManager.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/ServerModeManager.cs @@ -7,11 +7,9 @@ namespace Microsoft.Testing.Platform.ServerMode; -internal sealed partial class ServerModeManager : IServerModeManager +internal sealed partial class ServerModeManager { - internal ICommunicationProtocol? CommunicationProtocol { get; set; } - - internal IMessageHandlerFactory Build(IServiceProvider serviceProvider) + internal static IMessageHandlerFactory Build(IServiceProvider serviceProvider) { ICommandLineOptions commandLineService = serviceProvider.GetCommandLineOptions(); @@ -20,34 +18,10 @@ internal IMessageHandlerFactory Build(IServiceProvider serviceProvider) ? int.Parse(clientPortArgs[0], CultureInfo.InvariantCulture) : throw new InvalidOperationException(PlatformResources.MissingClientPortFoJsonRpc); - string? clientHostName; - clientHostName = commandLineService.TryGetOptionArgumentList(PlatformCommandLineProvider.ClientHostOptionKey, out string[]? clientHostArgs) + string clientHostName = commandLineService.TryGetOptionArgumentList(PlatformCommandLineProvider.ClientHostOptionKey, out string[]? clientHostArgs) ? clientHostArgs[0] : "localhost"; - if (CommunicationProtocol is not null) - { - switch (CommunicationProtocol) - { - case JsonRpcTcpServerToSingleClient tcpServerToSingleClientCommunicationProtocol: - { - clientPort ??= tcpServerToSingleClientCommunicationProtocol.ClientPort; - - if (RoslynString.IsNullOrEmpty(clientHostName)) - { - clientHostName = tcpServerToSingleClientCommunicationProtocol.ClientHostName; - } - - break; - } - - default: - { - throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, PlatformResources.UnknownCommunicationProtocolErrorMessage, CommunicationProtocol.GetType())); - } - } - } - return new MessageHandlerFactory(clientHostName, clientPort.Value, serviceProvider.GetOutputDevice()); } } From cbcbc3157f6fff6ca8f0d69884904274dc65a1c4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Jare=C5=A1?= Date: Thu, 29 May 2025 13:28:13 +0200 Subject: [PATCH 039/541] Add changelogs for 3.9.1 (#5663) --- docs/Changelog-Platform.md | 24 ++++++++++++++++++++++++ docs/Changelog.md | 27 +++++++++++++++++++++++++++ 2 files changed, 51 insertions(+) diff --git a/docs/Changelog-Platform.md b/docs/Changelog-Platform.md index adeb954a97..f965061f16 100644 --- a/docs/Changelog-Platform.md +++ b/docs/Changelog-Platform.md @@ -4,6 +4,30 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) +## [1.7.1] - 2025-05-27 + +See full log [of v3.9.0...v3.9.1](https://github.com/microsoft/testfx/compare/v3.9.0...v3.9.1) + +### Fixed + +* VSTestBridge: Handle TestPropertyAttributes.Trait instead of special casing specific properties by @Youssef1313 in [#5644](https://github.com/microsoft/testfx/pull/5644) + +### Artifacts + +* MSTest: [3.9.1](https://www.nuget.org/packages/MSTest/3.9.1) +* MSTest.TestFramework: [3.9.1](https://www.nuget.org/packages/MSTest.TestFramework/3.9.1) +* MSTest.TestAdapter: [3.9.1](https://www.nuget.org/packages/MSTest.TestAdapter/3.9.1) +* MSTest.Analyzers: [3.9.1](https://www.nuget.org/packages/MSTest.Analyzers/3.9.1) +* MSTest.Sdk: [3.9.1](https://www.nuget.org/packages/MSTest.Sdk/3.9.1) +* Microsoft.Testing.Extensions.CrashDump: [1.7.1](https://www.nuget.org/packages/Microsoft.Testing.Extensions.CrashDump/1.7.1) +* Microsoft.Testing.Extensions.HangDump: [1.7.1](https://www.nuget.org/packages/Microsoft.Testing.Extensions.HangDump/1.7.1) +* Microsoft.Testing.Extensions.HotReload: [1.7.1](https://www.nuget.org/packages/Microsoft.Testing.Extensions.HotReload/1.7.1) +* Microsoft.Testing.Extensions.Retry: [1.7.1](https://www.nuget.org/packages/Microsoft.Testing.Extensions.Retry/1.7.1) +* Microsoft.Testing.Extensions.TrxReport: [1.7.1](https://www.nuget.org/packages/Microsoft.Testing.Extensions.TrxReport/1.7.1) +* Microsoft.Testing.Extensions.AzureDevOpsReport [1.0.0-alpha.25277.3](https://www.nuget.org/packages/Microsoft.Testing.Extensions.AzureDevOpsReport/1.0.0-alpha.25277.3) +* MSTest.SourceGeneration: [1.0.0-alpha.25277.3](https://www.nuget.org/packages/MSTest.SourceGeneration/1.0.0-alpha.25277.3) +* MSTest.Engine: [1.0.0-alpha.25277.3](https://www.nuget.org/packages/MSTest.Engine/1.0.0-alpha.25277.3) + ## [1.7.0] - 2025-05-20 See full log [of v3.8.3...v3.9.0](https://github.com/microsoft/testfx/compare/v3.8.3...v3.9.0) diff --git a/docs/Changelog.md b/docs/Changelog.md index 204a1d9946..06bd4a8ed2 100644 --- a/docs/Changelog.md +++ b/docs/Changelog.md @@ -4,6 +4,33 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) +## [3.9.1] - 2025-05-27 + +See full log [of v3.9.0...v3.9.1](https://github.com/microsoft/testfx/compare/v3.9.0...v3.9.1) + +### Fixed + +* Make ConditionBaseAttribute.Mode public by @Youssef1313 in [#5581](https://github.com/microsoft/testfx/pull/5581) +* Add missing overload for Assert.Throws by @Youssef1313 in [#5619](https://github.com/microsoft/testfx/pull/5619) +* Fix System.MissingMethodException for KeyValuePair Deconstruction by @Youssef1313 in [#5633](https://github.com/microsoft/testfx/pull/5633) +* Run the whole ExecuteInternal logic under the right execution context by @Youssef1313 in [#5636](https://github.com/microsoft/testfx/pull/5636) + +### Artifacts + +* MSTest: [3.9.1](https://www.nuget.org/packages/MSTest/3.9.1) +* MSTest.TestFramework: [3.9.1](https://www.nuget.org/packages/MSTest.TestFramework/3.9.1) +* MSTest.TestAdapter: [3.9.1](https://www.nuget.org/packages/MSTest.TestAdapter/3.9.1) +* MSTest.Analyzers: [3.9.1](https://www.nuget.org/packages/MSTest.Analyzers/3.9.1) +* MSTest.Sdk: [3.9.1](https://www.nuget.org/packages/MSTest.Sdk/3.9.1) +* Microsoft.Testing.Extensions.CrashDump: [1.7.1](https://www.nuget.org/packages/Microsoft.Testing.Extensions.CrashDump/1.7.1) +* Microsoft.Testing.Extensions.HangDump: [1.7.1](https://www.nuget.org/packages/Microsoft.Testing.Extensions.HangDump/1.7.1) +* Microsoft.Testing.Extensions.HotReload: [1.7.1](https://www.nuget.org/packages/Microsoft.Testing.Extensions.HotReload/1.7.1) +* Microsoft.Testing.Extensions.Retry: [1.7.1](https://www.nuget.org/packages/Microsoft.Testing.Extensions.Retry/1.7.1) +* Microsoft.Testing.Extensions.TrxReport: [1.7.1](https://www.nuget.org/packages/Microsoft.Testing.Extensions.TrxReport/1.7.1) +* Microsoft.Testing.Extensions.AzureDevOpsReport [1.0.0-alpha.25277.3](https://www.nuget.org/packages/Microsoft.Testing.Extensions.AzureDevOpsReport/1.0.0-alpha.25277.3) +* MSTest.SourceGeneration: [1.0.0-alpha.25277.3](https://www.nuget.org/packages/MSTest.SourceGeneration/1.0.0-alpha.25277.3) +* MSTest.Engine: [1.0.0-alpha.25277.3](https://www.nuget.org/packages/MSTest.Engine/1.0.0-alpha.25277.3) + ## [3.9.0] - 2025-05-20 See full log [of v3.8.3...v3.9.0](https://github.com/microsoft/testfx/compare/v3.8.3...v3.9.0) From a0b04458f81dcd5efcff3fd216f7252f4ea3b0b0 Mon Sep 17 00:00:00 2001 From: Copilot <198982749+Copilot@users.noreply.github.com> Date: Thu, 29 May 2025 18:10:11 +0200 Subject: [PATCH 040/541] Update backport workflow to include original PR author in backport PR title (#5666) Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: Youssef1313 <31348972+Youssef1313@users.noreply.github.com> Co-authored-by: nohwnd <5735905+nohwnd@users.noreply.github.com> --- .github/workflows/backport-base.yml | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/.github/workflows/backport-base.yml b/.github/workflows/backport-base.yml index 5941ec39fb..f53a7c1cec 100644 --- a/.github/workflows/backport-base.yml +++ b/.github/workflows/backport-base.yml @@ -2,10 +2,10 @@ on: workflow_call: inputs: pr_title_template: - description: 'The template used for the PR title. Special placeholder tokens that will be replaced with a value: %target_branch%, %source_pr_title%, %source_pr_number%, %cc_users%.' + description: 'The template used for the PR title. Special placeholder tokens that will be replaced with a value: %target_branch%, %source_pr_title%, %source_pr_number%, %source_pr_author%, %cc_users%.' required: false type: string - default: '[%target_branch%] %source_pr_title%' + default: '%source_pr_title% by @%source_pr_author% in #%source_pr_number% (backport to %target_branch%)' pr_description_template: description: 'The template used for the PR description. Special placeholder tokens that will be replaced with a value: %target_branch%, %source_pr_title%, %source_pr_number%, %cc_users%.' required: false @@ -116,6 +116,7 @@ jobs: .replace(/%target_branch%/g, target_branch) .replace(/%source_pr_title%/g, context.payload.issue.title) .replace(/%source_pr_number%/g, context.payload.issue.number) + .replace(/%source_pr_author%/g, context.payload.issue.user.login) return backport_pr_title; From 3ad345b8c799f4bea89e534acdf2cd70b3055e2d Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Thu, 29 May 2025 20:08:36 +0000 Subject: [PATCH 041/541] [main] Update dependencies from dotnet/arcade (#5669) [main] Update dependencies from dotnet/arcade --- eng/Version.Details.xml | 12 +- eng/Versions.props | 2 +- eng/common/build.ps1 | 2 +- eng/common/build.sh | 6 +- .../core-templates/jobs/source-build.yml | 2 +- .../core-templates/post-build/post-build.yml | 3 - .../steps/install-microbuild.yml | 35 --- .../core-templates/steps/source-build.yml | 66 +----- eng/common/darc-init.sh | 2 +- eng/common/templates/steps/vmr-sync.yml | 207 ++++++++++++++++++ eng/common/templates/vmr-build-pr.yml | 33 +++ eng/common/tools.ps1 | 4 +- eng/common/tools.sh | 8 +- eng/common/vmr-sync.ps1 | 138 ++++++++++++ eng/common/vmr-sync.sh | 205 +++++++++++++++++ global.json | 2 +- 16 files changed, 611 insertions(+), 116 deletions(-) create mode 100644 eng/common/templates/steps/vmr-sync.yml create mode 100644 eng/common/templates/vmr-build-pr.yml create mode 100644 eng/common/vmr-sync.ps1 create mode 100644 eng/common/vmr-sync.sh diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index 9372be8c7c..d466e73a3f 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -1,17 +1,17 @@ - + https://github.com/dotnet/arcade - e46d1266547513110e67a3e4709fe8ecdfb20849 + 12d3a9f5d6138e22270694574e73e4c58a815795 - + https://github.com/dotnet/arcade - e46d1266547513110e67a3e4709fe8ecdfb20849 + 12d3a9f5d6138e22270694574e73e4c58a815795 - + https://github.com/dotnet/arcade - e46d1266547513110e67a3e4709fe8ecdfb20849 + 12d3a9f5d6138e22270694574e73e4c58a815795 https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage diff --git a/eng/Versions.props b/eng/Versions.props index 5c2268ba95..f6c861d192 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -7,7 +7,7 @@ preview - 10.0.0-beta.25229.4 + 10.0.0-beta.25271.2 17.15.0-preview.25229.5 diff --git a/eng/common/build.ps1 b/eng/common/build.ps1 index 6b3be1916f..ae2309e312 100644 --- a/eng/common/build.ps1 +++ b/eng/common/build.ps1 @@ -127,7 +127,7 @@ function Build { /p:Deploy=$deploy ` /p:Test=$test ` /p:Pack=$pack ` - /p:DotNetBuildRepo=$productBuild ` + /p:DotNetBuild=$productBuild ` /p:IntegrationTest=$integrationTest ` /p:PerformanceTest=$performanceTest ` /p:Sign=$sign ` diff --git a/eng/common/build.sh b/eng/common/build.sh index 36fba82a37..da906da202 100755 --- a/eng/common/build.sh +++ b/eng/common/build.sh @@ -129,14 +129,14 @@ while [[ $# > 0 ]]; do -pack) pack=true ;; - -sourcebuild|-sb) + -sourcebuild|-source-build|-sb) build=true source_build=true product_build=true restore=true pack=true ;; - -productBuild|-pb) + -productbuild|-product-build|-pb) build=true product_build=true restore=true @@ -241,7 +241,7 @@ function Build { /p:RepoRoot="$repo_root" \ /p:Restore=$restore \ /p:Build=$build \ - /p:DotNetBuildRepo=$product_build \ + /p:DotNetBuild=$product_build \ /p:DotNetBuildSourceOnly=$source_build \ /p:Rebuild=$rebuild \ /p:Test=$test \ diff --git a/eng/common/core-templates/jobs/source-build.yml b/eng/common/core-templates/jobs/source-build.yml index a10ccfbee6..df24c948ba 100644 --- a/eng/common/core-templates/jobs/source-build.yml +++ b/eng/common/core-templates/jobs/source-build.yml @@ -14,7 +14,7 @@ parameters: # This is the default platform provided by Arcade, intended for use by a managed-only repo. defaultManagedPlatform: name: 'Managed' - container: 'mcr.microsoft.com/dotnet-buildtools/prereqs:centos-stream9' + container: 'mcr.microsoft.com/dotnet-buildtools/prereqs:centos-stream-10-amd64' # Defines the platforms on which to run build jobs. One job is created for each platform, and the # object in this array is sent to the job template as 'platform'. If no platforms are specified, diff --git a/eng/common/core-templates/post-build/post-build.yml b/eng/common/core-templates/post-build/post-build.yml index 5757915edb..a151fd811e 100644 --- a/eng/common/core-templates/post-build/post-build.yml +++ b/eng/common/core-templates/post-build/post-build.yml @@ -193,9 +193,6 @@ stages: buildId: $(AzDOBuildId) artifactName: PackageArtifacts checkDownloadedFiles: true - itemPattern: | - ** - !**/Microsoft.SourceBuild.Intermediate.*.nupkg # This is necessary whenever we want to publish/restore to an AzDO private feed # Since sdk-task.ps1 tries to restore packages we need to do this authentication here diff --git a/eng/common/core-templates/steps/install-microbuild.yml b/eng/common/core-templates/steps/install-microbuild.yml index 2bcf974ee1..a3540ba00c 100644 --- a/eng/common/core-templates/steps/install-microbuild.yml +++ b/eng/common/core-templates/steps/install-microbuild.yml @@ -48,38 +48,3 @@ steps: eq(variables['_SignType'], 'real') ) )) - - # Workaround for ESRP CLI on Linux - https://github.com/dotnet/source-build/issues/4964 - - ${{ if eq(parameters.enableMicrobuildForMacAndLinux, 'true') }}: - - task: UseDotNet@2 - displayName: Install .NET 9.0 SDK for ESRP CLI Workaround - inputs: - packageType: sdk - version: 9.0.x - installationPath: ${{ parameters.microBuildOutputFolder }}/.dotnet - workingDirectory: ${{ parameters.microBuildOutputFolder }} - condition: and(succeeded(), eq(variables['Agent.OS'], 'Linux')) - - - task: PowerShell@2 - displayName: Workaround for ESRP CLI on Linux - inputs: - targetType: 'inline' - script: | - Write-Host "Copying Linux Path" - $MBSIGN_APPFOLDER = '$(MBSIGN_APPFOLDER)' - $MBSIGN_APPFOLDER = ($MBSIGN_APPFOLDER -replace '/build', '') - - $versionRegex = '\d+\.\d+\.\d+' - $package = Get-ChildItem -Path $MBSIGN_APPFOLDER -Directory | - Where-Object { $_.Name -match $versionRegex } - - if ($package.Count -ne 1) { - Write-Host "There should be exactly one matching subfolder, but found $($package.Count)." - exit 1 - } - - $MBSIGN_APPFOLDER = $package[0].FullName + '/build' - $MBSIGN_APPFOLDER | Write-Host - $SignConfigPath = $MBSIGN_APPFOLDER + '/signconfig.xml' - Copy-Item -Path "$(MBSIGN_APPFOLDER)/signconfig.xml" -Destination $SignConfigPath -Force - condition: and(succeeded(), eq(variables['Agent.OS'], 'Linux')) diff --git a/eng/common/core-templates/steps/source-build.yml b/eng/common/core-templates/steps/source-build.yml index c6b9ef51ac..0dde553c3e 100644 --- a/eng/common/core-templates/steps/source-build.yml +++ b/eng/common/core-templates/steps/source-build.yml @@ -19,19 +19,6 @@ steps: set -x df -h - # If file changes are detected, set CopyWipIntoInnerSourceBuildRepo to copy the WIP changes into the inner source build repo. - internalRestoreArgs= - if ! git diff --quiet; then - internalRestoreArgs='/p:CopyWipIntoInnerSourceBuildRepo=true' - # The 'Copy WIP' feature of source build uses git stash to apply changes from the original repo. - # This only works if there is a username/email configured, which won't be the case in most CI runs. - git config --get user.email - if [ $? -ne 0 ]; then - git config user.email dn-bot@microsoft.com - git config user.name dn-bot - fi - fi - # If building on the internal project, the internal storage variable may be available (usually only if needed) # In that case, add variables to allow the download of internal runtimes if the specified versions are not found # in the default public locations. @@ -46,34 +33,14 @@ steps: buildConfig='$(_BuildConfig)' fi - officialBuildArgs= - if [ '${{ and(ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest')) }}' = 'True' ]; then - officialBuildArgs='/p:DotNetPublishUsingPipelines=true /p:OfficialBuildId=$(BUILD.BUILDNUMBER)' - fi - targetRidArgs= if [ '${{ parameters.platform.targetRID }}' != '' ]; then targetRidArgs='/p:TargetRid=${{ parameters.platform.targetRID }}' fi - runtimeOsArgs= - if [ '${{ parameters.platform.runtimeOS }}' != '' ]; then - runtimeOsArgs='/p:RuntimeOS=${{ parameters.platform.runtimeOS }}' - fi - - baseOsArgs= - if [ '${{ parameters.platform.baseOS }}' != '' ]; then - baseOsArgs='/p:BaseOS=${{ parameters.platform.baseOS }}' - fi - - publishArgs= - if [ '${{ parameters.platform.skipPublishValidation }}' != 'true' ]; then - publishArgs='--publish' - fi - - assetManifestFileName=SourceBuild_RidSpecific.xml - if [ '${{ parameters.platform.name }}' != '' ]; then - assetManifestFileName=SourceBuild_${{ parameters.platform.name }}.xml + baseRidArgs= + if [ '${{ parameters.platform.baseRID }}' != '' ]; then + baseRidArgs='/p:BaseRid=${{ parameters.platform.baseRID }}' fi portableBuildArgs= @@ -83,40 +50,21 @@ steps: ${{ coalesce(parameters.platform.buildScript, './build.sh') }} --ci \ --configuration $buildConfig \ - --restore --build --pack $publishArgs -bl \ + --restore --build --pack -bl \ + --source-build \ ${{ parameters.platform.buildArguments }} \ - $officialBuildArgs \ $internalRuntimeDownloadArgs \ - $internalRestoreArgs \ $targetRidArgs \ - $runtimeOsArgs \ - $baseOsArgs \ + $baseRidArgs \ $portableBuildArgs \ - /p:DotNetBuildSourceOnly=true \ - /p:DotNetBuildRepo=true \ - /p:AssetManifestFileName=$assetManifestFileName displayName: Build -# Upload build logs for diagnosis. -- task: CopyFiles@2 - displayName: Prepare BuildLogs staging directory - inputs: - SourceFolder: '$(Build.SourcesDirectory)' - Contents: | - **/*.log - **/*.binlog - artifacts/sb/prebuilt-report/** - TargetFolder: '$(Build.StagingDirectory)/BuildLogs' - CleanTargetFolder: true - continueOnError: true - condition: succeededOrFailed() - - template: /eng/common/core-templates/steps/publish-pipeline-artifacts.yml parameters: is1ESPipeline: ${{ parameters.is1ESPipeline }} args: displayName: Publish BuildLogs - targetPath: '$(Build.StagingDirectory)/BuildLogs' + targetPath: artifacts/log/${{ coalesce(variables._BuildConfig, 'Release') }} artifactName: BuildLogs_SourceBuild_${{ parameters.platform.name }}_Attempt$(System.JobAttempt) continueOnError: true condition: succeededOrFailed() diff --git a/eng/common/darc-init.sh b/eng/common/darc-init.sh index 36dbd45e1c..e889f439b8 100644 --- a/eng/common/darc-init.sh +++ b/eng/common/darc-init.sh @@ -68,7 +68,7 @@ function InstallDarcCli { fi fi - local arcadeServicesSource="https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-tools/nuget/v3/index.json" + local arcadeServicesSource="https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-eng/nuget/v3/index.json" echo "Installing Darc CLI version $darcVersion..." echo "You may need to restart your command shell if this is the first dotnet tool you have installed." diff --git a/eng/common/templates/steps/vmr-sync.yml b/eng/common/templates/steps/vmr-sync.yml new file mode 100644 index 0000000000..599afb6186 --- /dev/null +++ b/eng/common/templates/steps/vmr-sync.yml @@ -0,0 +1,207 @@ +### These steps synchronize new code from product repositories into the VMR (https://github.com/dotnet/dotnet). +### They initialize the darc CLI and pull the new updates. +### Changes are applied locally onto the already cloned VMR (located in $vmrPath). + +parameters: +- name: targetRef + displayName: Target revision in dotnet/ to synchronize + type: string + default: $(Build.SourceVersion) + +- name: vmrPath + displayName: Path where the dotnet/dotnet is checked out to + type: string + default: $(Agent.BuildDirectory)/vmr + +- name: additionalSyncs + displayName: Optional list of package names whose repo's source will also be synchronized in the local VMR, e.g. NuGet.Protocol + type: object + default: [] + +steps: +- checkout: vmr + displayName: Clone dotnet/dotnet + path: vmr + clean: true + +- checkout: self + displayName: Clone $(Build.Repository.Name) + path: repo + fetchDepth: 0 + +# This step is needed so that when we get a detached HEAD / shallow clone, +# we still pull the commit into the temporary repo clone to use it during the sync. +# Also unshallow the clone so that forwardflow command would work. +- script: | + git branch repo-head + git rev-parse HEAD + displayName: Label PR commit + workingDirectory: $(Agent.BuildDirectory)/repo + +- script: | + vmr_sha=$(grep -oP '(?<=Sha=")[^"]*' $(Agent.BuildDirectory)/repo/eng/Version.Details.xml) + echo "##vso[task.setvariable variable=vmr_sha]$vmr_sha" + displayName: Obtain the vmr sha from Version.Details.xml (Unix) + condition: ne(variables['Agent.OS'], 'Windows_NT') + workingDirectory: $(Agent.BuildDirectory)/repo + +- powershell: | + [xml]$xml = Get-Content -Path $(Agent.BuildDirectory)/repo/eng/Version.Details.xml + $vmr_sha = $xml.SelectSingleNode("//Source").Sha + Write-Output "##vso[task.setvariable variable=vmr_sha]$vmr_sha" + displayName: Obtain the vmr sha from Version.Details.xml (Windows) + condition: eq(variables['Agent.OS'], 'Windows_NT') + workingDirectory: $(Agent.BuildDirectory)/repo + +- script: | + git fetch --all + git checkout $(vmr_sha) + displayName: Checkout VMR at correct sha for repo flow + workingDirectory: ${{ parameters.vmrPath }} + +- script: | + git config --global user.name "dotnet-maestro[bot]" + git config --global user.email "dotnet-maestro[bot]@users.noreply.github.com" + displayName: Set git author to dotnet-maestro[bot] + workingDirectory: ${{ parameters.vmrPath }} + +- script: | + ./eng/common/vmr-sync.sh \ + --vmr ${{ parameters.vmrPath }} \ + --tmp $(Agent.TempDirectory) \ + --azdev-pat '$(dn-bot-all-orgs-code-r)' \ + --ci \ + --debug + + if [ "$?" -ne 0 ]; then + echo "##vso[task.logissue type=error]Failed to synchronize the VMR" + exit 1 + fi + displayName: Sync repo into VMR (Unix) + condition: ne(variables['Agent.OS'], 'Windows_NT') + workingDirectory: $(Agent.BuildDirectory)/repo + +- script: | + git config --global diff.astextplain.textconv echo + git config --system core.longpaths true + displayName: Configure Windows git (longpaths, astextplain) + condition: eq(variables['Agent.OS'], 'Windows_NT') + +- powershell: | + ./eng/common/vmr-sync.ps1 ` + -vmr ${{ parameters.vmrPath }} ` + -tmp $(Agent.TempDirectory) ` + -azdevPat '$(dn-bot-all-orgs-code-r)' ` + -ci ` + -debugOutput + + if ($LASTEXITCODE -ne 0) { + echo "##vso[task.logissue type=error]Failed to synchronize the VMR" + exit 1 + } + displayName: Sync repo into VMR (Windows) + condition: eq(variables['Agent.OS'], 'Windows_NT') + workingDirectory: $(Agent.BuildDirectory)/repo + +- ${{ if eq(variables['Build.Reason'], 'PullRequest') }}: + - task: CopyFiles@2 + displayName: Collect failed patches + condition: failed() + inputs: + SourceFolder: '$(Agent.TempDirectory)' + Contents: '*.patch' + TargetFolder: '$(Build.ArtifactStagingDirectory)/FailedPatches' + + - publish: '$(Build.ArtifactStagingDirectory)/FailedPatches' + artifact: $(System.JobDisplayName)_FailedPatches + displayName: Upload failed patches + condition: failed() + +- ${{ each assetName in parameters.additionalSyncs }}: + # The vmr-sync script ends up staging files in the local VMR so we have to commit those + - script: + git commit --allow-empty -am "Forward-flow $(Build.Repository.Name)" + displayName: Commit local VMR changes + workingDirectory: ${{ parameters.vmrPath }} + + - script: | + set -ex + + echo "Searching for details of asset ${{ assetName }}..." + + # Use darc to get dependencies information + dependencies=$(./.dotnet/dotnet darc get-dependencies --name '${{ assetName }}' --ci) + + # Extract repository URL and commit hash + repository=$(echo "$dependencies" | grep 'Repo:' | sed 's/Repo:[[:space:]]*//' | head -1) + + if [ -z "$repository" ]; then + echo "##vso[task.logissue type=error]Asset ${{ assetName }} not found in the dependency list" + exit 1 + fi + + commit=$(echo "$dependencies" | grep 'Commit:' | sed 's/Commit:[[:space:]]*//' | head -1) + + echo "Updating the VMR from $repository / $commit..." + cd .. + git clone $repository ${{ assetName }} + cd ${{ assetName }} + git checkout $commit + git branch "sync/$commit" + + ./eng/common/vmr-sync.sh \ + --vmr ${{ parameters.vmrPath }} \ + --tmp $(Agent.TempDirectory) \ + --azdev-pat '$(dn-bot-all-orgs-code-r)' \ + --ci \ + --debug + + if [ "$?" -ne 0 ]; then + echo "##vso[task.logissue type=error]Failed to synchronize the VMR" + exit 1 + fi + displayName: Sync ${{ assetName }} into (Unix) + condition: ne(variables['Agent.OS'], 'Windows_NT') + workingDirectory: $(Agent.BuildDirectory)/repo + + - powershell: | + $ErrorActionPreference = 'Stop' + + Write-Host "Searching for details of asset ${{ assetName }}..." + + $dependencies = .\.dotnet\dotnet darc get-dependencies --name '${{ assetName }}' --ci + + $repository = $dependencies | Select-String -Pattern 'Repo:\s+([^\s]+)' | Select-Object -First 1 + $repository -match 'Repo:\s+([^\s]+)' | Out-Null + $repository = $matches[1] + + if ($repository -eq $null) { + Write-Error "Asset ${{ assetName }} not found in the dependency list" + exit 1 + } + + $commit = $dependencies | Select-String -Pattern 'Commit:\s+([^\s]+)' | Select-Object -First 1 + $commit -match 'Commit:\s+([^\s]+)' | Out-Null + $commit = $matches[1] + + Write-Host "Updating the VMR from $repository / $commit..." + cd .. + git clone $repository ${{ assetName }} + cd ${{ assetName }} + git checkout $commit + git branch "sync/$commit" + + .\eng\common\vmr-sync.ps1 ` + -vmr ${{ parameters.vmrPath }} ` + -tmp $(Agent.TempDirectory) ` + -azdevPat '$(dn-bot-all-orgs-code-r)' ` + -ci ` + -debugOutput + + if ($LASTEXITCODE -ne 0) { + echo "##vso[task.logissue type=error]Failed to synchronize the VMR" + exit 1 + } + displayName: Sync ${{ assetName }} into (Windows) + condition: ne(variables['Agent.OS'], 'Windows_NT') + workingDirectory: $(Agent.BuildDirectory)/repo diff --git a/eng/common/templates/vmr-build-pr.yml b/eng/common/templates/vmr-build-pr.yml new file mode 100644 index 0000000000..670cf32c3b --- /dev/null +++ b/eng/common/templates/vmr-build-pr.yml @@ -0,0 +1,33 @@ +trigger: none +pr: + branches: + include: + - main + - release/* + paths: + exclude: + - documentation/* + - README.md + - CODEOWNERS + +variables: +- template: /eng/common/templates/variables/pool-providers.yml@self + +- name: skipComponentGovernanceDetection # we run CG on internal builds only + value: true + +- name: Codeql.Enabled # we run CodeQL on internal builds only + value: false + +resources: + repositories: + - repository: vmr + type: github + name: dotnet/dotnet + endpoint: dotnet + +stages: +- template: /eng/pipelines/templates/stages/vmr-build.yml@vmr + parameters: + isBuiltFromVmr: false + scope: lite diff --git a/eng/common/tools.ps1 b/eng/common/tools.ps1 index 7373e53054..5f40a3f823 100644 --- a/eng/common/tools.ps1 +++ b/eng/common/tools.ps1 @@ -68,8 +68,6 @@ $ErrorActionPreference = 'Stop' # True if the build is a product build [bool]$productBuild = if (Test-Path variable:productBuild) { $productBuild } else { $false } -[String[]]$properties = if (Test-Path variable:properties) { $properties } else { @() } - function Create-Directory ([string[]] $path) { New-Item -Path $path -Force -ItemType 'Directory' | Out-Null } @@ -853,7 +851,7 @@ function MSBuild-Core() { # When running on Azure Pipelines, override the returned exit code to avoid double logging. # Skip this when the build is a child of the VMR orchestrator build. - if ($ci -and $env:SYSTEM_TEAMPROJECT -ne $null -and !$productBuild -and -not($properties -like "*DotNetBuildRepo=true*")) { + if ($ci -and $env:SYSTEM_TEAMPROJECT -ne $null -and !$productBuild) { Write-PipelineSetResult -Result "Failed" -Message "msbuild execution failed." # Exiting with an exit code causes the azure pipelines task to log yet another "noise" error # The above Write-PipelineSetResult will cause the task to be marked as failure without adding yet another error diff --git a/eng/common/tools.sh b/eng/common/tools.sh index d51f300c77..25f5932eee 100644 --- a/eng/common/tools.sh +++ b/eng/common/tools.sh @@ -5,6 +5,9 @@ # CI mode - set to true on CI server for PR validation build or official build. ci=${ci:-false} +# Build mode +source_build=${source_build:-false} + # Set to true to use the pipelines logger which will enable Azure logging output. # https://github.com/Microsoft/azure-pipelines-tasks/blob/master/docs/authoring/commands.md # This flag is meant as a temporary opt-opt for the feature while validate it across @@ -58,7 +61,8 @@ use_installed_dotnet_cli=${use_installed_dotnet_cli:-true} dotnetInstallScriptVersion=${dotnetInstallScriptVersion:-'v1'} # True to use global NuGet cache instead of restoring packages to repository-local directory. -if [[ "$ci" == true ]]; then +# Keep in sync with NuGetPackageroot in Arcade SDK's RepositoryLayout.props. +if [[ "$ci" == true || "$source_build" == true ]]; then use_global_nuget_cache=${use_global_nuget_cache:-false} else use_global_nuget_cache=${use_global_nuget_cache:-true} @@ -503,7 +507,7 @@ function MSBuild-Core { # When running on Azure Pipelines, override the returned exit code to avoid double logging. # Skip this when the build is a child of the VMR orchestrator build. - if [[ "$ci" == true && -n ${SYSTEM_TEAMPROJECT:-} && "$product_build" != true && "$properties" != *"DotNetBuildRepo=true"* ]]; then + if [[ "$ci" == true && -n ${SYSTEM_TEAMPROJECT:-} && "$product_build" != true ]]; then Write-PipelineSetResult -result "Failed" -message "msbuild execution failed." # Exiting with an exit code causes the azure pipelines task to log yet another "noise" error # The above Write-PipelineSetResult will cause the task to be marked as failure without adding yet another error diff --git a/eng/common/vmr-sync.ps1 b/eng/common/vmr-sync.ps1 new file mode 100644 index 0000000000..8c3c91ce8d --- /dev/null +++ b/eng/common/vmr-sync.ps1 @@ -0,0 +1,138 @@ +<# +.SYNOPSIS + +This script is used for synchronizing the current repository into a local VMR. +It pulls the current repository's code into the specified VMR directory for local testing or +Source-Build validation. + +.DESCRIPTION + +The tooling used for synchronization will clone the VMR repository into a temporary folder if +it does not already exist. These clones can be reused in future synchronizations, so it is +recommended to dedicate a folder for this to speed up re-runs. + +.EXAMPLE + Synchronize current repository into a local VMR: + ./vmr-sync.ps1 -vmrDir "$HOME/repos/dotnet" -tmpDir "$HOME/repos/tmp" + +.PARAMETER tmpDir +Required. Path to the temporary folder where repositories will be cloned + +.PARAMETER vmrBranch +Optional. Branch of the 'dotnet/dotnet' repo to synchronize. The VMR will be checked out to this branch + +.PARAMETER azdevPat +Optional. Azure DevOps PAT to use for cloning private repositories. + +.PARAMETER vmrDir +Optional. Path to the dotnet/dotnet repository. When null, gets cloned to the temporary folder + +.PARAMETER debugOutput +Optional. Enables debug logging in the darc vmr command. + +.PARAMETER ci +Optional. Denotes that the script is running in a CI environment. +#> +param ( + [Parameter(Mandatory=$true, HelpMessage="Path to the temporary folder where repositories will be cloned")] + [string][Alias('t', 'tmp')]$tmpDir, + [string][Alias('b', 'branch')]$vmrBranch, + [string]$remote, + [string]$azdevPat, + [string][Alias('v', 'vmr')]$vmrDir, + [switch]$ci, + [switch]$debugOutput +) + +function Fail { + Write-Host "> $($args[0])" -ForegroundColor 'Red' +} + +function Highlight { + Write-Host "> $($args[0])" -ForegroundColor 'Cyan' +} + +$verbosity = 'verbose' +if ($debugOutput) { + $verbosity = 'debug' +} +# Validation + +if (-not $tmpDir) { + Fail "Missing -tmpDir argument. Please specify the path to the temporary folder where the repositories will be cloned" + exit 1 +} + +# Sanitize the input + +if (-not $vmrDir) { + $vmrDir = Join-Path $tmpDir 'dotnet' +} + +if (-not (Test-Path -Path $tmpDir -PathType Container)) { + New-Item -ItemType Directory -Path $tmpDir | Out-Null +} + +# Prepare the VMR + +if (-not (Test-Path -Path $vmrDir -PathType Container)) { + Highlight "Cloning 'dotnet/dotnet' into $vmrDir.." + git clone https://github.com/dotnet/dotnet $vmrDir + + if ($vmrBranch) { + git -C $vmrDir switch -c $vmrBranch + } +} +else { + if ((git -C $vmrDir diff --quiet) -eq $false) { + Fail "There are changes in the working tree of $vmrDir. Please commit or stash your changes" + exit 1 + } + + if ($vmrBranch) { + Highlight "Preparing $vmrDir" + git -C $vmrDir checkout $vmrBranch + git -C $vmrDir pull + } +} + +Set-StrictMode -Version Latest + +# Prepare darc + +Highlight 'Installing .NET, preparing the tooling..' +. .\eng\common\tools.ps1 +$dotnetRoot = InitializeDotNetCli -install:$true +$dotnet = "$dotnetRoot\dotnet.exe" +& "$dotnet" tool restore + +Highlight "Starting the synchronization of VMR.." + +# Synchronize the VMR +$darcArgs = ( + "darc", "vmr", "forwardflow", + "--tmp", $tmpDir, + "--$verbosity", + $vmrDir +) + +if ($ci) { + $darcArgs += ("--ci") +} + +if ($azdevPat) { + $darcArgs += ("--azdev-pat", $azdevPat) +} + +& "$dotnet" $darcArgs + +if ($LASTEXITCODE -eq 0) { + Highlight "Synchronization succeeded" +} +else { + Fail "Synchronization of repo to VMR failed!" + Fail "'$vmrDir' is left in its last state (re-run of this script will reset it)." + Fail "Please inspect the logs which contain path to the failing patch file (use -debugOutput to get all the details)." + Fail "Once you make changes to the conflicting VMR patch, commit it locally and re-run this script." + exit 1 +} diff --git a/eng/common/vmr-sync.sh b/eng/common/vmr-sync.sh new file mode 100644 index 0000000000..86d77ccf5b --- /dev/null +++ b/eng/common/vmr-sync.sh @@ -0,0 +1,205 @@ +#!/bin/bash + +### This script is used for synchronizing the current repository into a local VMR. +### It pulls the current repository's code into the specified VMR directory for local testing or +### Source-Build validation. +### +### The tooling used for synchronization will clone the VMR repository into a temporary folder if +### it does not already exist. These clones can be reused in future synchronizations, so it is +### recommended to dedicate a folder for this to speed up re-runs. +### +### USAGE: +### Synchronize current repository into a local VMR: +### ./vmr-sync.sh --tmp "$HOME/repos/tmp" "$HOME/repos/dotnet" +### +### Options: +### -t, --tmp, --tmp-dir PATH +### Required. Path to the temporary folder where repositories will be cloned +### +### -b, --branch, --vmr-branch BRANCH_NAME +### Optional. Branch of the 'dotnet/dotnet' repo to synchronize. The VMR will be checked out to this branch +### +### --debug +### Optional. Turns on the most verbose logging for the VMR tooling +### +### --remote name:URI +### Optional. Additional remote to use during the synchronization +### This can be used to synchronize to a commit from a fork of the repository +### Example: 'runtime:https://github.com/yourfork/runtime' +### +### --azdev-pat +### Optional. Azure DevOps PAT to use for cloning private repositories. +### +### -v, --vmr, --vmr-dir PATH +### Optional. Path to the dotnet/dotnet repository. When null, gets cloned to the temporary folder + +source="${BASH_SOURCE[0]}" + +# resolve $source until the file is no longer a symlink +while [[ -h "$source" ]]; do + scriptroot="$( cd -P "$( dirname "$source" )" && pwd )" + source="$(readlink "$source")" + # if $source was a relative symlink, we need to resolve it relative to the path where the + # symlink file was located + [[ $source != /* ]] && source="$scriptroot/$source" +done +scriptroot="$( cd -P "$( dirname "$source" )" && pwd )" + +function print_help () { + sed -n '/^### /,/^$/p' "$source" | cut -b 5- +} + +COLOR_RED=$(tput setaf 1 2>/dev/null || true) +COLOR_CYAN=$(tput setaf 6 2>/dev/null || true) +COLOR_CLEAR=$(tput sgr0 2>/dev/null || true) +COLOR_RESET=uniquesearchablestring +FAILURE_PREFIX='> ' + +function fail () { + echo "${COLOR_RED}$FAILURE_PREFIX${1//${COLOR_RESET}/${COLOR_RED}}${COLOR_CLEAR}" >&2 +} + +function highlight () { + echo "${COLOR_CYAN}$FAILURE_PREFIX${1//${COLOR_RESET}/${COLOR_CYAN}}${COLOR_CLEAR}" +} + +tmp_dir='' +vmr_dir='' +vmr_branch='' +additional_remotes='' +verbosity=verbose +azdev_pat='' +ci=false + +while [[ $# -gt 0 ]]; do + opt="$(echo "$1" | tr "[:upper:]" "[:lower:]")" + case "$opt" in + -t|--tmp|--tmp-dir) + tmp_dir=$2 + shift + ;; + -v|--vmr|--vmr-dir) + vmr_dir=$2 + shift + ;; + -b|--branch|--vmr-branch) + vmr_branch=$2 + shift + ;; + --remote) + additional_remotes="$additional_remotes $2" + shift + ;; + --azdev-pat) + azdev_pat=$2 + shift + ;; + --ci) + ci=true + ;; + -d|--debug) + verbosity=debug + ;; + -h|--help) + print_help + exit 0 + ;; + *) + fail "Invalid argument: $1" + print_help + exit 1 + ;; + esac + + shift +done + +# Validation + +if [[ -z "$tmp_dir" ]]; then + fail "Missing --tmp-dir argument. Please specify the path to the temporary folder where the repositories will be cloned" + exit 1 +fi + +# Sanitize the input + +if [[ -z "$vmr_dir" ]]; then + vmr_dir="$tmp_dir/dotnet" +fi + +if [[ ! -d "$tmp_dir" ]]; then + mkdir -p "$tmp_dir" +fi + +if [[ "$verbosity" == "debug" ]]; then + set -x +fi + +# Prepare the VMR + +if [[ ! -d "$vmr_dir" ]]; then + highlight "Cloning 'dotnet/dotnet' into $vmr_dir.." + git clone https://github.com/dotnet/dotnet "$vmr_dir" + + if [[ -n "$vmr_branch" ]]; then + git -C "$vmr_dir" switch -c "$vmr_branch" + fi +else + if ! git -C "$vmr_dir" diff --quiet; then + fail "There are changes in the working tree of $vmr_dir. Please commit or stash your changes" + exit 1 + fi + + if [[ -n "$vmr_branch" ]]; then + highlight "Preparing $vmr_dir" + git -C "$vmr_dir" checkout "$vmr_branch" + git -C "$vmr_dir" pull + fi +fi + +set -e + +# Prepare darc + +highlight 'Installing .NET, preparing the tooling..' +source "./eng/common/tools.sh" +InitializeDotNetCli true +dotnetDir=$( cd ./.dotnet/; pwd -P ) +dotnet=$dotnetDir/dotnet +"$dotnet" tool restore + +highlight "Starting the synchronization of VMR.." +set +e + +if [[ -n "$additional_remotes" ]]; then + additional_remotes="--additional-remotes $additional_remotes" +fi + +if [[ -n "$azdev_pat" ]]; then + azdev_pat="--azdev-pat $azdev_pat" +fi + +ci_arg='' +if [[ "$ci" == "true" ]]; then + ci_arg="--ci" +fi + +# Synchronize the VMR + +"$dotnet" darc vmr forwardflow \ + --tmp "$tmp_dir" \ + $azdev_pat \ + --$verbosity \ + $ci_arg \ + $additional_remotes \ + "$vmr_dir" + +if [[ $? == 0 ]]; then + highlight "Synchronization succeeded" +else + fail "Synchronization of repo to VMR failed!" + fail "'$vmr_dir' is left in its last state (re-run of this script will reset it)." + fail "Please inspect the logs which contain path to the failing patch file (use --debug to get all the details)." + fail "Once you make changes to the conflicting VMR patch, commit it locally and re-run this script." + exit 1 +fi diff --git a/global.json b/global.json index 73d10b19cb..91a8faa1f6 100644 --- a/global.json +++ b/global.json @@ -28,7 +28,7 @@ "rollForward": "latestFeature" }, "msbuild-sdks": { - "Microsoft.DotNet.Arcade.Sdk": "10.0.0-beta.25229.4", + "Microsoft.DotNet.Arcade.Sdk": "10.0.0-beta.25271.2", "MSBuild.Sdk.Extras": "3.0.44" } } From 718e38b4558d39afde8bd4a9e6b3566336867c67 Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Fri, 30 May 2025 06:20:17 +0000 Subject: [PATCH 042/541] [main] Update dependencies from devdiv/DevDiv/vs-code-coverage (#5670) [main] Update dependencies from devdiv/DevDiv/vs-code-coverage --- eng/Version.Details.xml | 4 ++-- eng/Versions.props | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index d466e73a3f..52f4c40047 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -13,9 +13,9 @@ https://github.com/dotnet/arcade 12d3a9f5d6138e22270694574e73e4c58a815795 - + https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage - 22fe23c5579dfe54e9ab651eb4d3b002d9d18d73 + b37c73cef7bbebb497a391cab93a2de4897e6671 diff --git a/eng/Versions.props b/eng/Versions.props index f6c861d192..a18ff9cfef 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -8,6 +8,6 @@ 10.0.0-beta.25271.2 - 17.15.0-preview.25229.5 + 17.15.0-preview.25278.2 From d02a7c77160d916925dbeb198d612f688ccba232 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Fri, 30 May 2025 16:42:32 +0200 Subject: [PATCH 043/541] Simplify reflection (#4702) --- .../Discovery/AssemblyEnumerator.cs | 2 +- .../Discovery/TestMethodValidator.cs | 2 +- .../Discovery/TypeEnumerator.cs | 2 +- .../Discovery/TypeValidator.cs | 2 +- .../Execution/TestClassInfo.cs | 4 +- .../Execution/TestMethodInfo.cs | 12 +- .../Execution/TestMethodRunner.cs | 4 +- .../MSTest.TestAdapter/Execution/TypeCache.cs | 22 +-- .../Extensions/MethodInfoExtensions.cs | 2 +- .../Helpers/AttributeComparer.cs | 14 -- .../Helpers/AttributeHelpers.cs | 2 +- .../Helpers/ReflectHelper.cs | 90 ++------- .../Discovery/TestMethodValidatorTests.cs | 8 +- .../Discovery/TypeValidatorTests.cs | 8 +- .../Execution/TypeCacheTests.cs | 174 +++++++++--------- .../Execution/UnitTestRunnerTests.cs | 2 +- .../Helpers/ReflectHelperTests.cs | 22 +-- 17 files changed, 152 insertions(+), 220 deletions(-) delete mode 100644 src/Adapter/MSTest.TestAdapter/Helpers/AttributeComparer.cs diff --git a/src/Adapter/MSTest.TestAdapter/Discovery/AssemblyEnumerator.cs b/src/Adapter/MSTest.TestAdapter/Discovery/AssemblyEnumerator.cs index 6cd0f3970b..6dfe08c60b 100644 --- a/src/Adapter/MSTest.TestAdapter/Discovery/AssemblyEnumerator.cs +++ b/src/Adapter/MSTest.TestAdapter/Discovery/AssemblyEnumerator.cs @@ -347,7 +347,7 @@ private static bool TryUnfoldITestDataSources(UnitTestElement test, DiscoveryTes // We don't have a special method to filter attributes that are not derived from Attribute, so we take all // attributes and filter them. We don't have to care if there is one, because this method is only entered when // there is at least one (we determine this in TypeEnumerator.GetTestFromMethod. - IEnumerable testDataSources = ReflectHelper.Instance.GetDerivedAttributes(testMethodInfo.MethodInfo, inherit: false).OfType(); + IEnumerable testDataSources = ReflectHelper.Instance.GetAttributes(testMethodInfo.MethodInfo, inherit: false).OfType(); // We need to use a temporary list to avoid adding tests to the main list if we fail to expand any data source. List tempListOfTests = new(); diff --git a/src/Adapter/MSTest.TestAdapter/Discovery/TestMethodValidator.cs b/src/Adapter/MSTest.TestAdapter/Discovery/TestMethodValidator.cs index c9099700e3..04ca9f18ba 100644 --- a/src/Adapter/MSTest.TestAdapter/Discovery/TestMethodValidator.cs +++ b/src/Adapter/MSTest.TestAdapter/Discovery/TestMethodValidator.cs @@ -44,7 +44,7 @@ internal virtual bool IsValidTestMethod(MethodInfo testMethodInfo, Type type, IC // but the difference is quite small, and we don't expect a huge amount of non-test methods in the assembly. // // Also skip all methods coming from object, because they cannot be tests. - if (testMethodInfo.DeclaringType == typeof(object) || !_reflectHelper.IsDerivedAttributeDefined(testMethodInfo, inherit: false)) + if (testMethodInfo.DeclaringType == typeof(object) || !_reflectHelper.IsAttributeDefined(testMethodInfo, inherit: false)) { return false; } diff --git a/src/Adapter/MSTest.TestAdapter/Discovery/TypeEnumerator.cs b/src/Adapter/MSTest.TestAdapter/Discovery/TypeEnumerator.cs index ee0678ba2e..52c8becccc 100644 --- a/src/Adapter/MSTest.TestAdapter/Discovery/TypeEnumerator.cs +++ b/src/Adapter/MSTest.TestAdapter/Discovery/TypeEnumerator.cs @@ -159,7 +159,7 @@ internal UnitTestElement GetTestFromMethod(MethodInfo method, bool isDeclaredInT Attribute[] attributes = _reflectHelper.GetCustomAttributesCached(method, inherit: true); TestMethodAttribute? testMethodAttribute = null; - // Backward looping for backcompat. This used to be calls to _reflectHelper.GetFirstDerivedAttributeOrDefault + // Backward looping for backcompat. This used to be calls to _reflectHelper.GetFirstAttributeOrDefault // So, to make sure the first attribute always wins, we loop from end to start. for (int i = attributes.Length - 1; i >= 0; i--) { diff --git a/src/Adapter/MSTest.TestAdapter/Discovery/TypeValidator.cs b/src/Adapter/MSTest.TestAdapter/Discovery/TypeValidator.cs index 9e8e1c98d6..b82623ca7c 100644 --- a/src/Adapter/MSTest.TestAdapter/Discovery/TypeValidator.cs +++ b/src/Adapter/MSTest.TestAdapter/Discovery/TypeValidator.cs @@ -52,7 +52,7 @@ internal virtual bool IsValidTestClass(Type type, List warnings) // gives us a better performance. // It would be possible to use non-caching reflection here if we knew that we are only doing discovery that won't be followed by run, // but the difference is quite small, and we don't expect a huge amount of non-test classes in the assembly. - if (!type.IsClass || !_reflectHelper.IsDerivedAttributeDefined(type, inherit: false)) + if (!type.IsClass || !_reflectHelper.IsAttributeDefined(type, inherit: false)) { return false; } diff --git a/src/Adapter/MSTest.TestAdapter/Execution/TestClassInfo.cs b/src/Adapter/MSTest.TestAdapter/Execution/TestClassInfo.cs index 8d7b2cda24..dc4ae10a17 100644 --- a/src/Adapter/MSTest.TestAdapter/Execution/TestClassInfo.cs +++ b/src/Adapter/MSTest.TestAdapter/Execution/TestClassInfo.cs @@ -399,7 +399,7 @@ internal TestResult GetResultOrRunClassInitialize(ITestContext testContext, stri DebugEx.Assert(!IsClassInitializeExecuted, "If class initialize was executed, we should have been in the previous if were we have a result available."); - bool isSTATestClass = AttributeComparer.IsDerived(ClassAttribute); + bool isSTATestClass = ClassAttribute is STATestClassAttribute; bool isWindowsOS = RuntimeInformation.IsOSPlatform(OSPlatform.Windows); if (isSTATestClass && isWindowsOS @@ -741,7 +741,7 @@ internal void RunClassCleanup(ITestContext testContext, ClassCleanupManager clas return; } - bool isSTATestClass = AttributeComparer.IsDerived(ClassAttribute); + bool isSTATestClass = ClassAttribute is STATestClassAttribute; bool isWindowsOS = RuntimeInformation.IsOSPlatform(OSPlatform.Windows); if (isSTATestClass && isWindowsOS diff --git a/src/Adapter/MSTest.TestAdapter/Execution/TestMethodInfo.cs b/src/Adapter/MSTest.TestAdapter/Execution/TestMethodInfo.cs index 0d69c53bec..b736e57bd9 100644 --- a/src/Adapter/MSTest.TestAdapter/Execution/TestMethodInfo.cs +++ b/src/Adapter/MSTest.TestAdapter/Execution/TestMethodInfo.cs @@ -121,7 +121,7 @@ internal TestMethodInfo( /// Whether or not getting the attributes that are inherited. /// An array of the attributes. public Attribute[]? GetAllAttributes(bool inherit) - => ReflectHelper.Instance.GetDerivedAttributes(TestMethod, inherit).ToArray(); + => ReflectHelper.Instance.GetAttributes(TestMethod, inherit).ToArray(); /// /// Gets all attributes of the test method. @@ -131,7 +131,7 @@ internal TestMethodInfo( /// An array of the attributes. public TAttributeType[] GetAttributes(bool inherit) where TAttributeType : Attribute - => ReflectHelper.Instance.GetDerivedAttributes(TestMethod, inherit).ToArray(); + => ReflectHelper.Instance.GetAttributes(TestMethod, inherit).ToArray(); /// public virtual TestResult Invoke(object?[]? arguments) @@ -286,7 +286,7 @@ public virtual async Task InvokeAsync(object?[]? arguments) private TimeoutInfo GetTestTimeout() { DebugEx.Assert(TestMethod != null, "TestMethod should be non-null"); - TimeoutAttribute? timeoutAttribute = ReflectHelper.Instance.GetFirstNonDerivedAttributeOrDefault(TestMethod, inherit: false); + TimeoutAttribute? timeoutAttribute = ReflectHelper.Instance.GetFirstAttributeOrDefault(TestMethod, inherit: false); if (timeoutAttribute is null) { return TimeoutInfo.FromTestTimeoutSettings(); @@ -309,7 +309,7 @@ private TestMethodAttribute GetTestMethodAttribute() { // Get the derived TestMethod attribute from reflection. // It should be non-null as it was already validated by IsValidTestMethod. - TestMethodAttribute testMethodAttribute = ReflectHelper.Instance.GetFirstDerivedAttributeOrDefault(TestMethod, inherit: false)!; + TestMethodAttribute testMethodAttribute = ReflectHelper.Instance.GetFirstAttributeOrDefault(TestMethod, inherit: false)!; // Get the derived TestMethod attribute from Extended TestClass Attribute // If the extended TestClass Attribute doesn't have extended TestMethod attribute then base class returns back the original testMethod Attribute @@ -329,7 +329,7 @@ private TestMethodAttribute GetTestMethodAttribute() try { - expectedExceptions = ReflectHelper.Instance.GetDerivedAttributes(TestMethod, inherit: true); + expectedExceptions = ReflectHelper.Instance.GetAttributes(TestMethod, inherit: true); } catch (Exception ex) { @@ -365,7 +365,7 @@ private TestMethodAttribute GetTestMethodAttribute() /// private RetryBaseAttribute? GetRetryAttribute() { - IEnumerable attributes = ReflectHelper.Instance.GetDerivedAttributes(TestMethod, inherit: true); + IEnumerable attributes = ReflectHelper.Instance.GetAttributes(TestMethod, inherit: true); using IEnumerator enumerator = attributes.GetEnumerator(); if (!enumerator.MoveNext()) { diff --git a/src/Adapter/MSTest.TestAdapter/Execution/TestMethodRunner.cs b/src/Adapter/MSTest.TestAdapter/Execution/TestMethodRunner.cs index 078d97c4cb..15240f0c41 100644 --- a/src/Adapter/MSTest.TestAdapter/Execution/TestMethodRunner.cs +++ b/src/Adapter/MSTest.TestAdapter/Execution/TestMethodRunner.cs @@ -64,8 +64,8 @@ public TestMethodRunner(TestMethodInfo testMethodInfo, TestMethod testMethod, IT internal async Task ExecuteAsync(string initializationLogs, string initializationErrorLogs, string initializationTrace, string initializationTestContextMessages) { _testContext.Context.TestRunCount++; - bool isSTATestClass = AttributeComparer.IsDerived(_testMethodInfo.Parent.ClassAttribute); - bool isSTATestMethod = AttributeComparer.IsDerived(_testMethodInfo.Executor); + bool isSTATestClass = _testMethodInfo.Parent.ClassAttribute is STATestClassAttribute; + bool isSTATestMethod = _testMethodInfo.Executor is STATestMethodAttribute; bool isSTARequested = isSTATestClass || isSTATestMethod; bool isWindowsOS = RuntimeInformation.IsOSPlatform(OSPlatform.Windows); if (isSTARequested && isWindowsOS && Thread.CurrentThread.GetApartmentState() != ApartmentState.STA) diff --git a/src/Adapter/MSTest.TestAdapter/Execution/TypeCache.cs b/src/Adapter/MSTest.TestAdapter/Execution/TypeCache.cs index 55f1cc63c6..bf6100502f 100644 --- a/src/Adapter/MSTest.TestAdapter/Execution/TypeCache.cs +++ b/src/Adapter/MSTest.TestAdapter/Execution/TypeCache.cs @@ -302,7 +302,7 @@ private TestClassInfo CreateClassInfo(Type classType) TestAssemblyInfo assemblyInfo = GetAssemblyInfo(classType.Assembly); - TestClassAttribute? testClassAttribute = ReflectHelper.Instance.GetFirstDerivedAttributeOrDefault(classType, inherit: false); + TestClassAttribute? testClassAttribute = ReflectHelper.Instance.GetFirstAttributeOrDefault(classType, inherit: false); DebugEx.Assert(testClassAttribute is not null, "testClassAttribute is null"); var classInfo = new TestClassInfo(classType, constructor, isParameterLessConstructor, testClassAttribute, assemblyInfo); @@ -354,7 +354,7 @@ private TestClassInfo CreateClassInfo(Type classType) private TimeoutInfo? TryGetTimeoutInfo(MethodInfo methodInfo, FixtureKind fixtureKind) { - TimeoutAttribute? timeoutAttribute = _reflectionHelper.GetFirstNonDerivedAttributeOrDefault(methodInfo, inherit: false); + TimeoutAttribute? timeoutAttribute = _reflectionHelper.GetFirstAttributeOrDefault(methodInfo, inherit: false); if (timeoutAttribute != null) { if (!timeoutAttribute.HasCorrectTimeout) @@ -391,7 +391,7 @@ private TestAssemblyInfo GetAssemblyInfo(Assembly assembly) try { // Only examine classes which are TestClass or derives from TestClass attribute - if (!@this._reflectionHelper.IsDerivedAttributeDefined(t, inherit: false)) + if (!@this._reflectionHelper.IsAttributeDefined(t, inherit: false)) { continue; } @@ -440,7 +440,7 @@ private bool IsAssemblyOrClassInitializeMethod(MethodInfo // { // return false; // } - if (!_reflectionHelper.IsNonDerivedAttributeDefined(methodInfo, false)) + if (!_reflectionHelper.IsAttributeDefined(methodInfo, false)) { return false; } @@ -468,7 +468,7 @@ private bool IsAssemblyOrClassCleanupMethod(MethodInfo method // { // return false; // } - if (!_reflectionHelper.IsNonDerivedAttributeDefined(methodInfo, false)) + if (!_reflectionHelper.IsAttributeDefined(methodInfo, false)) { return false; } @@ -550,7 +550,7 @@ private void UpdateInfoIfClassInitializeOrCleanupMethod( if (isBase) { - if (_reflectionHelper.GetFirstDerivedAttributeOrDefault(methodInfo, inherit: true)? + if (_reflectionHelper.GetFirstAttributeOrDefault(methodInfo, inherit: true)? .InheritanceBehavior == InheritanceBehavior.BeforeEachDerivedClass) { initAndCleanupMethods[0] = methodInfo; @@ -572,7 +572,7 @@ private void UpdateInfoIfClassInitializeOrCleanupMethod( if (isBase) { - if (_reflectionHelper.GetFirstDerivedAttributeOrDefault(methodInfo, inherit: true)? + if (_reflectionHelper.GetFirstAttributeOrDefault(methodInfo, inherit: true)? .InheritanceBehavior == InheritanceBehavior.BeforeEachDerivedClass) { initAndCleanupMethods[1] = methodInfo; @@ -599,8 +599,8 @@ private void UpdateInfoIfTestInitializeOrCleanupMethod( bool isBase, Dictionary instanceMethods) { - bool hasTestInitialize = _reflectionHelper.IsNonDerivedAttributeDefined(methodInfo, inherit: false); - bool hasTestCleanup = _reflectionHelper.IsNonDerivedAttributeDefined(methodInfo, inherit: false); + bool hasTestInitialize = _reflectionHelper.IsAttributeDefined(methodInfo, inherit: false); + bool hasTestCleanup = _reflectionHelper.IsAttributeDefined(methodInfo, inherit: false); if (!hasTestCleanup && !hasTestInitialize) { @@ -778,10 +778,10 @@ private void SetCustomProperties(TestMethodInfo testMethodInfo, ITestContext tes DebugEx.Assert(testMethodInfo != null, "testMethodInfo is Null"); DebugEx.Assert(testMethodInfo.TestMethod != null, "testMethodInfo.TestMethod is Null"); - IEnumerable attributes = _reflectionHelper.GetDerivedAttributes(testMethodInfo.TestMethod, inherit: true); + IEnumerable attributes = _reflectionHelper.GetAttributes(testMethodInfo.TestMethod, inherit: true); DebugEx.Assert(attributes != null, "attributes is null"); - attributes = attributes.Concat(_reflectionHelper.GetDerivedAttributes(testMethodInfo.Parent.ClassType, inherit: true)); + attributes = attributes.Concat(_reflectionHelper.GetAttributes(testMethodInfo.Parent.ClassType, inherit: true)); foreach (TestPropertyAttribute attribute in attributes) { diff --git a/src/Adapter/MSTest.TestAdapter/Extensions/MethodInfoExtensions.cs b/src/Adapter/MSTest.TestAdapter/Extensions/MethodInfoExtensions.cs index 87be62dd88..940f96fb55 100644 --- a/src/Adapter/MSTest.TestAdapter/Extensions/MethodInfoExtensions.cs +++ b/src/Adapter/MSTest.TestAdapter/Extensions/MethodInfoExtensions.cs @@ -103,7 +103,7 @@ internal static bool IsValidReturnType(this MethodInfo method, ReflectHelper? re /// Compiler generated type name for given async test method.. internal static string? GetAsyncTypeName(this MethodInfo method, ReflectHelper? reflectHelper = null) { - AsyncStateMachineAttribute? asyncStateMachineAttribute = (reflectHelper ?? ReflectHelper.Instance).GetFirstNonDerivedAttributeOrDefault(method, inherit: false); + AsyncStateMachineAttribute? asyncStateMachineAttribute = (reflectHelper ?? ReflectHelper.Instance).GetFirstAttributeOrDefault(method, inherit: false); return asyncStateMachineAttribute?.StateMachineType?.FullName; } diff --git a/src/Adapter/MSTest.TestAdapter/Helpers/AttributeComparer.cs b/src/Adapter/MSTest.TestAdapter/Helpers/AttributeComparer.cs deleted file mode 100644 index c82f46d996..0000000000 --- a/src/Adapter/MSTest.TestAdapter/Helpers/AttributeComparer.cs +++ /dev/null @@ -1,14 +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. - -namespace Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Helpers; - -internal static class AttributeComparer -{ - public static bool IsNonDerived(Attribute attribute) => - // We are explicitly checking the given type *exactly*. We don't want to consider inheritance. - // So, this should NOT be refactored to 'attribute is TAttribute'. - attribute.GetType() == typeof(TAttribute); - - public static bool IsDerived(Attribute attribute) => attribute is TAttribute; -} diff --git a/src/Adapter/MSTest.TestAdapter/Helpers/AttributeHelpers.cs b/src/Adapter/MSTest.TestAdapter/Helpers/AttributeHelpers.cs index 673fbfb4fd..b112d05c87 100644 --- a/src/Adapter/MSTest.TestAdapter/Helpers/AttributeHelpers.cs +++ b/src/Adapter/MSTest.TestAdapter/Helpers/AttributeHelpers.cs @@ -9,7 +9,7 @@ internal static class AttributeExtensions { public static bool IsIgnored(this ICustomAttributeProvider type, out string? ignoreMessage) { - IEnumerable attributes = ReflectHelper.Instance.GetDerivedAttributes(type, inherit: false); + IEnumerable attributes = ReflectHelper.Instance.GetAttributes(type, inherit: false); IEnumerable> groups = attributes.GroupBy(attr => attr.GroupName); foreach (IGrouping? group in groups) { diff --git a/src/Adapter/MSTest.TestAdapter/Helpers/ReflectHelper.cs b/src/Adapter/MSTest.TestAdapter/Helpers/ReflectHelper.cs index 43a84a0d99..7eff98c5ff 100644 --- a/src/Adapter/MSTest.TestAdapter/Helpers/ReflectHelper.cs +++ b/src/Adapter/MSTest.TestAdapter/Helpers/ReflectHelper.cs @@ -24,35 +24,6 @@ internal class ReflectHelper : MarshalByRefObject public static ReflectHelper Instance => InstanceValue.Value; - /// - /// Checks to see if a member or type is decorated with the given attribute. The type is checked exactly. If attribute is derived (inherits from) a class, e.g. [MyTestClass] from [TestClass] it won't match if you look for [TestClass]. The inherit parameter does not impact this checking. - /// - /// - /// Note that because derived attribute types are not considered, should be sealed. - /// - /// Attribute to search for by fully qualified name. - /// Member/Type to test. - /// Inspect inheritance chain of the member or class. E.g. if parent class has this attribute defined. - /// True if the attribute of the specified type is defined on this member or a class. - public virtual bool IsNonDerivedAttributeDefined(MemberInfo memberInfo, bool inherit) - where TAttribute : Attribute - { - Guard.NotNull(memberInfo); - - // Get attributes defined on the member from the cache. - Attribute[] attributes = GetCustomAttributesCached(memberInfo, inherit); - - foreach (Attribute attribute in attributes) - { - if (AttributeComparer.IsNonDerived(attribute)) - { - return true; - } - } - - return false; - } - /// /// Checks to see if a member or type is decorated with the given attribute, or an attribute that derives from it. e.g. [MyTestClass] from [TestClass] will match if you look for [TestClass]. The inherit parameter does not impact this checking. /// @@ -60,7 +31,7 @@ public virtual bool IsNonDerivedAttributeDefined(MemberInfo memberIn /// Member to inspect for attributes. /// Inspect inheritance chain of the member or class. E.g. if parent class has this attribute defined. /// True if the attribute of the specified type is defined on this member or a class. - public virtual /* for testing */ bool IsDerivedAttributeDefined(MemberInfo memberInfo, bool inherit) + public virtual /* for testing */ bool IsAttributeDefined(MemberInfo memberInfo, bool inherit) where TAttribute : Attribute { Guard.NotNull(memberInfo); @@ -73,7 +44,7 @@ public virtual bool IsNonDerivedAttributeDefined(MemberInfo memberIn { DebugEx.Assert(attribute != null, $"{nameof(ReflectHelper)}.{nameof(GetCustomAttributesCached)}: internal error: wrong value in the attributes dictionary."); - if (AttributeComparer.IsDerived(attribute)) + if (attribute is TAttribute) { return true; } @@ -94,31 +65,6 @@ public virtual bool IsNonDerivedAttributeDefined(MemberInfo memberIn #endif public override object InitializeLifetimeService() => null!; - /// - /// Gets first attribute that matches the type (but is not derived from it). Use this together with attribute that is both sealed and does not allow multiple. - /// In such case there cannot be more attributes, and this will avoid the cost of - /// checking for more than one attribute. - /// - /// Type of the attribute to find. - /// The type, assembly or method. - /// If we should inspect parents of this type. - /// The attribute that is found or null. - public virtual /* for tests, for moq */ TAttribute? GetFirstNonDerivedAttributeOrDefault(ICustomAttributeProvider attributeProvider, bool inherit) - where TAttribute : Attribute - { - Attribute[] cachedAttributes = GetCustomAttributesCached(attributeProvider, inherit); - - foreach (Attribute cachedAttribute in cachedAttributes) - { - if (AttributeComparer.IsNonDerived(cachedAttribute)) - { - return (TAttribute)cachedAttribute; - } - } - - return null; - } - /// /// Gets first attribute that matches the type or is derived from it. /// Use this together with attribute that does not allow multiple. In such case there cannot be more attributes, and this will avoid the cost of @@ -129,16 +75,16 @@ public virtual bool IsNonDerivedAttributeDefined(MemberInfo memberIn /// If we should inspect parents of this type. /// The attribute that is found or null. /// Throws when multiple attributes are found (the attribute must allow multiple). - public virtual /* for tests, for moq */ TAttribute? GetFirstDerivedAttributeOrDefault(ICustomAttributeProvider attributeProvider, bool inherit) + public virtual /* for tests, for moq */ TAttribute? GetFirstAttributeOrDefault(ICustomAttributeProvider attributeProvider, bool inherit) where TAttribute : Attribute { Attribute[] cachedAttributes = GetCustomAttributesCached(attributeProvider, inherit); foreach (Attribute cachedAttribute in cachedAttributes) { - if (AttributeComparer.IsDerived(cachedAttribute)) + if (cachedAttribute is TAttribute cachedAttributeAsTAttribute) { - return (TAttribute)cachedAttribute; + return cachedAttributeAsTAttribute; } } @@ -175,9 +121,9 @@ internal virtual bool IsMethodDeclaredInSameAssemblyAsType(MethodInfo method, Ty /// Categories defined. internal virtual /* for tests, we are mocking this */ string[] GetTestCategories(MemberInfo categoryAttributeProvider, Type owningType) { - IEnumerable methodCategories = GetDerivedAttributes(categoryAttributeProvider, inherit: true); - IEnumerable typeCategories = GetDerivedAttributes(owningType, inherit: true); - IEnumerable assemblyCategories = GetDerivedAttributes(owningType.Assembly, inherit: true); + IEnumerable methodCategories = GetAttributes(categoryAttributeProvider, inherit: true); + IEnumerable typeCategories = GetAttributes(owningType, inherit: true); + IEnumerable assemblyCategories = GetAttributes(owningType.Assembly, inherit: true); return methodCategories.Concat(typeCategories).Concat(assemblyCategories).SelectMany(c => c.TestCategories).ToArray(); } @@ -236,8 +182,8 @@ internal static TestIdGenerationStrategy GetTestIdGenerationStrategy(Assembly as /// The type that owns . /// True if test method should not run in parallel. internal bool IsDoNotParallelizeSet(MemberInfo testMethod, Type owningType) - => IsDerivedAttributeDefined(testMethod, inherit: true) - || IsDerivedAttributeDefined(owningType, inherit: true); + => IsAttributeDefined(testMethod, inherit: true) + || IsAttributeDefined(owningType, inherit: true); /// /// Get the parallelization behavior for a test assembly. @@ -265,7 +211,7 @@ internal static bool IsDoNotParallelizeSet(Assembly assembly) /// The member to inspect. /// Priority value if defined. Null otherwise. internal virtual int? GetPriority(MemberInfo priorityAttributeProvider) => - GetFirstDerivedAttributeOrDefault(priorityAttributeProvider, inherit: true)?.Priority; + GetFirstAttributeOrDefault(priorityAttributeProvider, inherit: true)?.Priority; /// /// Gets the class cleanup lifecycle for the class, if set. @@ -283,9 +229,9 @@ internal static bool IsDoNotParallelizeSet(Assembly assembly) var cleanupBehaviors = new HashSet( classInfo.BaseClassCleanupMethods - .Select(x => GetFirstDerivedAttributeOrDefault(x, inherit: true)?.CleanupBehavior)) + .Select(x => GetFirstAttributeOrDefault(x, inherit: true)?.CleanupBehavior)) { - classInfo.ClassCleanupMethod == null ? null : GetFirstDerivedAttributeOrDefault(classInfo.ClassCleanupMethod, inherit: true)?.CleanupBehavior, + classInfo.ClassCleanupMethod == null ? null : GetFirstAttributeOrDefault(classInfo.ClassCleanupMethod, inherit: true)?.CleanupBehavior, }; return cleanupBehaviors.Contains(ClassCleanupBehavior.EndOfClass) @@ -300,11 +246,11 @@ internal static bool IsDoNotParallelizeSet(Assembly assembly) /// List of traits. internal virtual IEnumerable GetTestPropertiesAsTraits(MemberInfo testPropertyProvider) { - IEnumerable testPropertyAttributes = GetDerivedAttributes(testPropertyProvider, inherit: true); + IEnumerable testPropertyAttributes = GetAttributes(testPropertyProvider, inherit: true); if (testPropertyProvider.DeclaringType is { } testClass) { - testPropertyAttributes = testPropertyAttributes.Concat(GetDerivedAttributes(testClass, inherit: true)); + testPropertyAttributes = testPropertyAttributes.Concat(GetAttributes(testClass, inherit: true)); } foreach (TestPropertyAttribute testProperty in testPropertyAttributes) @@ -321,7 +267,7 @@ internal virtual IEnumerable GetTestPropertiesAsTraits(MemberInfo testPro /// The member to inspect. /// Look at inheritance chain. /// An instance of the attribute. - internal virtual /* for tests, for moq */ IEnumerable GetDerivedAttributes(ICustomAttributeProvider attributeProvider, bool inherit) + internal virtual /* for tests, for moq */ IEnumerable GetAttributes(ICustomAttributeProvider attributeProvider, bool inherit) where TAttributeType : Attribute { Attribute[] attributes = GetCustomAttributesCached(attributeProvider, inherit); @@ -331,9 +277,9 @@ internal virtual IEnumerable GetTestPropertiesAsTraits(MemberInfo testPro { DebugEx.Assert(attribute != null, "ReflectHelper.DefinesAttributeDerivedFrom: internal error: wrong value in the attributes dictionary."); - if (AttributeComparer.IsDerived(attribute)) + if (attribute is TAttributeType attributeAsAttributeType) { - yield return (TAttributeType)attribute; + yield return attributeAsAttributeType; } } } diff --git a/test/UnitTests/MSTestAdapter.UnitTests/Discovery/TestMethodValidatorTests.cs b/test/UnitTests/MSTestAdapter.UnitTests/Discovery/TestMethodValidatorTests.cs index 10067ed9da..e660a7a115 100644 --- a/test/UnitTests/MSTestAdapter.UnitTests/Discovery/TestMethodValidatorTests.cs +++ b/test/UnitTests/MSTestAdapter.UnitTests/Discovery/TestMethodValidatorTests.cs @@ -34,7 +34,7 @@ public TestMethodValidatorTests() public void IsValidTestMethodShouldReturnFalseForMethodsWithoutATestMethodAttributeOrItsDerivedAttributes() { _mockReflectHelper.Setup( - rh => rh.IsDerivedAttributeDefined(It.IsAny(), false)).Returns(false); + rh => rh.IsAttributeDefined(It.IsAny(), false)).Returns(false); Verify(!_testMethodValidator.IsValidTestMethod(_mockMethodInfo.Object, _type, _warnings)); } @@ -57,7 +57,7 @@ public void IsValidTestMethodShouldNotReportWarningsForGenericTestMethodDefiniti SetupTestMethod(); _mockReflectHelper - .Setup(x => x.GetFirstNonDerivedAttributeOrDefault(_mockMethodInfo.Object, false)) + .Setup(x => x.GetFirstAttributeOrDefault(_mockMethodInfo.Object, false)) .Returns(default(AsyncStateMachineAttribute?)); _mockMethodInfo.Setup(mi => mi.IsGenericMethodDefinition).Returns(true); @@ -114,7 +114,7 @@ public void IsValidTestMethodShouldReturnFalseForAsyncMethodsWithNonTaskReturnTy MethodInfo methodInfo = typeof(DummyTestClass).GetMethod( "AsyncMethodWithVoidReturnType", BindingFlags.Instance | BindingFlags.Public)!; - _mockReflectHelper.Setup(_mockReflectHelper => _mockReflectHelper.GetFirstNonDerivedAttributeOrDefault(methodInfo, false)) + _mockReflectHelper.Setup(_mockReflectHelper => _mockReflectHelper.GetFirstAttributeOrDefault(methodInfo, false)) .CallBase(); Verify(!_testMethodValidator.IsValidTestMethod(methodInfo, typeof(DummyTestClass), _warnings)); @@ -190,7 +190,7 @@ public void WhenDiscoveryOfInternalsIsEnabledIsValidTestMethodShouldReturnFalseF private void SetupTestMethod() => _mockReflectHelper.Setup( - rh => rh.IsDerivedAttributeDefined(It.IsAny(), false)).Returns(true); + rh => rh.IsAttributeDefined(It.IsAny(), false)).Returns(true); } #region Dummy types diff --git a/test/UnitTests/MSTestAdapter.UnitTests/Discovery/TypeValidatorTests.cs b/test/UnitTests/MSTestAdapter.UnitTests/Discovery/TypeValidatorTests.cs index 1fedee983c..8c4de47c06 100644 --- a/test/UnitTests/MSTestAdapter.UnitTests/Discovery/TypeValidatorTests.cs +++ b/test/UnitTests/MSTestAdapter.UnitTests/Discovery/TypeValidatorTests.cs @@ -41,15 +41,15 @@ public TypeValidatorTests() public void IsValidTestClassShouldReturnFalseForClassesNotHavingTestClassAttributeOrDerivedAttributeTypes() { - _mockReflectHelper.Setup(rh => rh.IsNonDerivedAttributeDefined(It.IsAny(), false)).Returns(false); + _mockReflectHelper.Setup(rh => rh.IsAttributeDefined(It.IsAny(), false)).Returns(false); Verify(!_typeValidator.IsValidTestClass(typeof(TypeValidatorTests), _warnings)); } public void IsValidTestClassShouldReturnTrueForClassesMarkedByAnAttributeDerivedFromTestClass() { - _mockReflectHelper.Setup(rh => rh.IsNonDerivedAttributeDefined(It.IsAny(), false)).Returns(false); + _mockReflectHelper.Setup(rh => rh.IsAttributeDefined(It.IsAny(), false)).Returns(false); _mockReflectHelper.Setup( - rh => rh.IsDerivedAttributeDefined(It.IsAny(), false)).Returns(true); + rh => rh.IsAttributeDefined(It.IsAny(), false)).Returns(true); Verify(_typeValidator.IsValidTestClass(typeof(TypeValidatorTests), _warnings)); } @@ -393,7 +393,7 @@ private static Type[] GetAllTestTypes() #region private methods - private void SetupTestClass() => _mockReflectHelper.Setup(rh => rh.IsDerivedAttributeDefined(It.IsAny(), false)).Returns(true); + private void SetupTestClass() => _mockReflectHelper.Setup(rh => rh.IsAttributeDefined(It.IsAny(), false)).Returns(true); #endregion } diff --git a/test/UnitTests/MSTestAdapter.UnitTests/Execution/TypeCacheTests.cs b/test/UnitTests/MSTestAdapter.UnitTests/Execution/TypeCacheTests.cs index a1348ff357..2136801507 100644 --- a/test/UnitTests/MSTestAdapter.UnitTests/Execution/TypeCacheTests.cs +++ b/test/UnitTests/MSTestAdapter.UnitTests/Execution/TypeCacheTests.cs @@ -152,7 +152,7 @@ public void GetTestMethodInfoShouldSetTestContextIfPresent() var testMethod = new TestMethod(methodInfo.Name, type.FullName!, "A", isAsync: false); _mockReflectHelper.Setup( - rh => rh.IsNonDerivedAttributeDefined(type, true)).Returns(true); + rh => rh.IsAttributeDefined(type, true)).Returns(true); TestMethodInfo? testMethodInfo = _typeCache.GetTestMethodInfo( testMethod, @@ -169,7 +169,7 @@ public void GetTestMethodInfoShouldSetTestContextToNullIfNotPresent() var testMethod = new TestMethod(methodInfo.Name, type.FullName!, "A", isAsync: false); _mockReflectHelper.Setup( - rh => rh.IsNonDerivedAttributeDefined(type, true)).Returns(true); + rh => rh.IsAttributeDefined(type, true)).Returns(true); TestMethodInfo? testMethodInfo = _typeCache.GetTestMethodInfo( testMethod, @@ -188,7 +188,7 @@ public void GetTestMethodInfoShouldAddAssemblyInfoToTheCache() var testMethod = new TestMethod(methodInfo.Name, type.FullName!, "A", isAsync: false); _mockReflectHelper.Setup( - rh => rh.IsNonDerivedAttributeDefined(type, true)).Returns(true); + rh => rh.IsAttributeDefined(type, true)).Returns(true); _typeCache.GetTestMethodInfo( testMethod, @@ -204,10 +204,10 @@ public void GetTestMethodInfoShouldNotThrowIfWeFailToDiscoverTypeFromAnAssembly( var testMethod = new TestMethod(methodInfo.Name, type.FullName!, "A", isAsync: false); _mockReflectHelper.Setup( - rh => rh.IsNonDerivedAttributeDefined(It.IsAny(), true)).Throws(new Exception()); + rh => rh.IsAttributeDefined(It.IsAny(), true)).Throws(new Exception()); _mockReflectHelper.Setup( - rh => rh.IsNonDerivedAttributeDefined(typeof(DummyTestClassWithTestMethods), true)).Returns(true); + rh => rh.IsAttributeDefined(typeof(DummyTestClassWithTestMethods), true)).Returns(true); _typeCache.GetTestMethodInfo( testMethod, @@ -222,10 +222,10 @@ public void GetTestMethodInfoShouldCacheAssemblyInitializeAttribute() var testMethod = new TestMethod("TestInit", type.FullName!, "A", isAsync: false); _mockReflectHelper.Setup( - rh => rh.IsDerivedAttributeDefined(type, false)).Returns(true); + rh => rh.IsAttributeDefined(type, false)).Returns(true); _mockReflectHelper.Setup( - rh => rh.IsNonDerivedAttributeDefined(type.GetMethod("AssemblyInit")!, false)).Returns(true); + rh => rh.IsAttributeDefined(type.GetMethod("AssemblyInit")!, false)).Returns(true); _typeCache.GetTestMethodInfo( testMethod, @@ -241,10 +241,10 @@ public void GetTestMethodInfoShouldCacheAssemblyCleanupAttribute() var testMethod = new TestMethod("TestCleanup", type.FullName!, "A", isAsync: false); _mockReflectHelper.Setup( - rh => rh.IsDerivedAttributeDefined(type, false)).Returns(true); + rh => rh.IsAttributeDefined(type, false)).Returns(true); _mockReflectHelper.Setup( - rh => rh.IsNonDerivedAttributeDefined(type.GetMethod("AssemblyCleanup")!, false)).Returns(true); + rh => rh.IsAttributeDefined(type.GetMethod("AssemblyCleanup")!, false)).Returns(true); _typeCache.GetTestMethodInfo( testMethod, @@ -260,12 +260,12 @@ public void GetTestMethodInfoShouldCacheAssemblyInitAndCleanupAttribute() var testMethod = new TestMethod("TestInitOrCleanup", type.FullName!, "A", isAsync: false); _mockReflectHelper.Setup( - rh => rh.IsDerivedAttributeDefined(type, false)).Returns(true); + rh => rh.IsAttributeDefined(type, false)).Returns(true); _mockReflectHelper.Setup( - rh => rh.IsNonDerivedAttributeDefined(type.GetMethod("AssemblyInit")!, false)).Returns(true); + rh => rh.IsAttributeDefined(type.GetMethod("AssemblyInit")!, false)).Returns(true); _mockReflectHelper.Setup( - rh => rh.IsNonDerivedAttributeDefined(type.GetMethod("AssemblyCleanup")!, false)).Returns(true); + rh => rh.IsAttributeDefined(type.GetMethod("AssemblyCleanup")!, false)).Returns(true); _typeCache.GetTestMethodInfo( testMethod, @@ -282,10 +282,10 @@ public void GetTestMethodInfoShouldThrowIfAssemblyInitHasIncorrectSignature() var testMethod = new TestMethod("M", type.FullName!, "A", isAsync: false); _mockReflectHelper.Setup( - rh => rh.IsDerivedAttributeDefined(type, false)).Returns(true); + rh => rh.IsAttributeDefined(type, false)).Returns(true); _mockReflectHelper.Setup( - rh => rh.IsNonDerivedAttributeDefined(type.GetMethod("AssemblyInit")!, false)).Returns(true); + rh => rh.IsAttributeDefined(type.GetMethod("AssemblyInit")!, false)).Returns(true); void A() => _typeCache.GetTestMethodInfo( @@ -311,10 +311,10 @@ public void GetTestMethodInfoShouldThrowIfAssemblyCleanupHasIncorrectSignature() var testMethod = new TestMethod("M", type.FullName!, "A", isAsync: false); _mockReflectHelper.Setup( - rh => rh.IsDerivedAttributeDefined(type, false)).Returns(true); + rh => rh.IsAttributeDefined(type, false)).Returns(true); _mockReflectHelper.Setup( - rh => rh.IsNonDerivedAttributeDefined(type.GetMethod("AssemblyCleanup")!, false)).Returns(true); + rh => rh.IsAttributeDefined(type.GetMethod("AssemblyCleanup")!, false)).Returns(true); void A() => _typeCache.GetTestMethodInfo( @@ -341,7 +341,7 @@ public void GetTestMethodInfoShouldCacheAssemblyInfoInstanceAndReuseTheCache() var testMethod = new TestMethod(methodInfo.Name, type.FullName!, "A", isAsync: false); _mockReflectHelper.Setup( - rh => rh.IsDerivedAttributeDefined(type, false)).Returns(true); + rh => rh.IsAttributeDefined(type, false)).Returns(true); _typeCache.GetTestMethodInfo( testMethod, @@ -351,7 +351,7 @@ public void GetTestMethodInfoShouldCacheAssemblyInfoInstanceAndReuseTheCache() testMethod, new TestContextImplementation(testMethod, new ThreadSafeStringWriter(null!, "test"), new Dictionary())); - _mockReflectHelper.Verify(rh => rh.IsDerivedAttributeDefined(type, false), Times.Once); + _mockReflectHelper.Verify(rh => rh.IsAttributeDefined(type, false), Times.Once); Verify(_typeCache.AssemblyInfoCache.Count == 1); } @@ -366,7 +366,7 @@ public void GetTestMethodInfoShouldAddClassInfoToTheCache() var testMethod = new TestMethod(methodInfo.Name, type.FullName!, "A", isAsync: false); _mockReflectHelper.Setup( - rh => rh.IsNonDerivedAttributeDefined(type, true)).Returns(true); + rh => rh.IsAttributeDefined(type, true)).Returns(true); _typeCache.GetTestMethodInfo( testMethod, @@ -383,10 +383,10 @@ public void GetTestMethodInfoShouldCacheClassInitializeAttribute() var testMethod = new TestMethod("TestInit", type.FullName!, "A", isAsync: false); _mockReflectHelper.Setup( - rh => rh.IsNonDerivedAttributeDefined(type, true)).Returns(true); + rh => rh.IsAttributeDefined(type, true)).Returns(true); _mockReflectHelper.Setup( - rh => rh.IsNonDerivedAttributeDefined(type.GetMethod("AssemblyInit")!, false)).Returns(true); + rh => rh.IsAttributeDefined(type.GetMethod("AssemblyInit")!, false)).Returns(true); _typeCache.GetTestMethodInfo( testMethod, @@ -405,16 +405,16 @@ public void GetTestMethodInfoShouldCacheBaseClassInitializeAttributes() var testMethod = new TestMethod("TestMethod", type.FullName!, "A", false); _mockReflectHelper.Setup( - rh => rh.IsDerivedAttributeDefined(type, false)).Returns(true); + rh => rh.IsAttributeDefined(type, false)).Returns(true); _mockReflectHelper.Setup( - rh => rh.IsNonDerivedAttributeDefined(baseType.GetMethod("AssemblyInit")!, false)).Returns(true); + rh => rh.IsAttributeDefined(baseType.GetMethod("AssemblyInit")!, false)).Returns(true); _mockReflectHelper.Setup( - rh => rh.GetFirstDerivedAttributeOrDefault(baseType.GetMethod("AssemblyInit")!, true)) + rh => rh.GetFirstAttributeOrDefault(baseType.GetMethod("AssemblyInit")!, true)) .Returns(new ClassInitializeAttribute(InheritanceBehavior.BeforeEachDerivedClass)); _mockReflectHelper.Setup( - rh => rh.IsNonDerivedAttributeDefined(type.GetMethod("ClassInit")!, false)).Returns(true); + rh => rh.IsAttributeDefined(type.GetMethod("ClassInit")!, false)).Returns(true); _typeCache.GetTestMethodInfo( testMethod, @@ -431,10 +431,10 @@ public void GetTestMethodInfoShouldCacheClassCleanupAttribute() var testMethod = new TestMethod("TestCleanup", type.FullName!, "A", isAsync: false); _mockReflectHelper.Setup( - rh => rh.IsNonDerivedAttributeDefined(type, true)).Returns(true); + rh => rh.IsAttributeDefined(type, true)).Returns(true); _mockReflectHelper.Setup( - rh => rh.IsNonDerivedAttributeDefined(type.GetMethod("AssemblyCleanup")!, false)).Returns(true); + rh => rh.IsAttributeDefined(type.GetMethod("AssemblyCleanup")!, false)).Returns(true); _typeCache.GetTestMethodInfo( testMethod, @@ -452,11 +452,11 @@ public void GetTestMethodInfoShouldCacheBaseClassCleanupAttributes() var testMethod = new TestMethod("TestMethod", type.FullName!, "A", false); _mockReflectHelper.Setup( - rh => rh.IsDerivedAttributeDefined(type, false)).Returns(true); + rh => rh.IsAttributeDefined(type, false)).Returns(true); _mockReflectHelper.Setup( - rh => rh.IsNonDerivedAttributeDefined(baseType.GetMethod("AssemblyCleanup")!, false)).Returns(true); + rh => rh.IsAttributeDefined(baseType.GetMethod("AssemblyCleanup")!, false)).Returns(true); _mockReflectHelper.Setup( - rh => rh.GetFirstDerivedAttributeOrDefault(baseType.GetMethod("AssemblyCleanup")!, true)) + rh => rh.GetFirstAttributeOrDefault(baseType.GetMethod("AssemblyCleanup")!, true)) .Returns(new ClassCleanupAttribute(InheritanceBehavior.BeforeEachDerivedClass)); _typeCache.GetTestMethodInfo( @@ -474,11 +474,11 @@ public void GetTestMethodInfoShouldCacheClassInitAndCleanupAttribute() var testMethod = new TestMethod("TestInitOrCleanup", type.FullName!, "A", isAsync: false); _mockReflectHelper.Setup( - rh => rh.IsNonDerivedAttributeDefined(type, true)).Returns(true); + rh => rh.IsAttributeDefined(type, true)).Returns(true); _mockReflectHelper.Setup( - rh => rh.IsNonDerivedAttributeDefined(type.GetMethod("AssemblyInit")!, false)).Returns(true); + rh => rh.IsAttributeDefined(type.GetMethod("AssemblyInit")!, false)).Returns(true); _mockReflectHelper.Setup( - rh => rh.IsNonDerivedAttributeDefined(type.GetMethod("AssemblyCleanup")!, false)).Returns(true); + rh => rh.IsAttributeDefined(type.GetMethod("AssemblyCleanup")!, false)).Returns(true); _typeCache.GetTestMethodInfo( testMethod, @@ -499,23 +499,23 @@ public void GetTestMethodInfoShouldCacheBaseClassInitAndCleanupAttributes() MethodInfo baseCleanupMethod = baseType.GetMethod("ClassCleanup")!; _mockReflectHelper.Setup( - rh => rh.IsDerivedAttributeDefined(type, false)).Returns(true); + rh => rh.IsAttributeDefined(type, false)).Returns(true); _mockReflectHelper.Setup( - rh => rh.IsNonDerivedAttributeDefined(baseInitializeMethod, false)).Returns(true); + rh => rh.IsAttributeDefined(baseInitializeMethod, false)).Returns(true); _mockReflectHelper.Setup( - rh => rh.GetFirstDerivedAttributeOrDefault(baseInitializeMethod, true)) + rh => rh.GetFirstAttributeOrDefault(baseInitializeMethod, true)) .Returns(new ClassInitializeAttribute(InheritanceBehavior.BeforeEachDerivedClass)); _mockReflectHelper.Setup( - rh => rh.IsNonDerivedAttributeDefined(baseCleanupMethod, false)).Returns(true); + rh => rh.IsAttributeDefined(baseCleanupMethod, false)).Returns(true); _mockReflectHelper.Setup( - rh => rh.GetFirstDerivedAttributeOrDefault(baseCleanupMethod, true)) + rh => rh.GetFirstAttributeOrDefault(baseCleanupMethod, true)) .Returns(new ClassCleanupAttribute(InheritanceBehavior.BeforeEachDerivedClass)); _mockReflectHelper.Setup( - rh => rh.IsNonDerivedAttributeDefined(type.GetMethod("AssemblyInit")!, false)).Returns(true); + rh => rh.IsAttributeDefined(type.GetMethod("AssemblyInit")!, false)).Returns(true); _mockReflectHelper.Setup( - rh => rh.IsNonDerivedAttributeDefined(type.GetMethod("AssemblyCleanup")!, false)).Returns(true); + rh => rh.IsAttributeDefined(type.GetMethod("AssemblyCleanup")!, false)).Returns(true); _typeCache.GetTestMethodInfo( testMethod, @@ -541,35 +541,35 @@ public void GetTestMethodInfoShouldCacheParentAndGrandparentClassInitAndCleanupA MethodInfo parentCleanupMethod = parentType.GetMethod("ChildClassCleanup")!; _mockReflectHelper - .Setup(rh => rh.IsNonDerivedAttributeDefined(type, true)) + .Setup(rh => rh.IsAttributeDefined(type, true)) .Returns(true); // Setup grandparent class init/cleanup methods _mockReflectHelper - .Setup(rh => rh.IsNonDerivedAttributeDefined(grandparentInitMethod, false)) + .Setup(rh => rh.IsAttributeDefined(grandparentInitMethod, false)) .Returns(true); _mockReflectHelper - .Setup(rh => rh.GetFirstDerivedAttributeOrDefault(grandparentInitMethod, true)) + .Setup(rh => rh.GetFirstAttributeOrDefault(grandparentInitMethod, true)) .Returns(new ClassInitializeAttribute(InheritanceBehavior.BeforeEachDerivedClass)); _mockReflectHelper - .Setup(rh => rh.IsNonDerivedAttributeDefined(grandparentCleanupMethod, false)) + .Setup(rh => rh.IsAttributeDefined(grandparentCleanupMethod, false)) .Returns(true); _mockReflectHelper - .Setup(rh => rh.GetFirstDerivedAttributeOrDefault(grandparentCleanupMethod, true)) + .Setup(rh => rh.GetFirstAttributeOrDefault(grandparentCleanupMethod, true)) .Returns(new ClassCleanupAttribute(InheritanceBehavior.BeforeEachDerivedClass)); // Setup parent class init/cleanup methods _mockReflectHelper - .Setup(rh => rh.IsNonDerivedAttributeDefined(parentInitMethod, false)) + .Setup(rh => rh.IsAttributeDefined(parentInitMethod, false)) .Returns(true); _mockReflectHelper - .Setup(rh => rh.GetFirstDerivedAttributeOrDefault(parentInitMethod, true)) + .Setup(rh => rh.GetFirstAttributeOrDefault(parentInitMethod, true)) .Returns(new ClassInitializeAttribute(InheritanceBehavior.BeforeEachDerivedClass)); _mockReflectHelper - .Setup(rh => rh.IsNonDerivedAttributeDefined(parentCleanupMethod, false)) + .Setup(rh => rh.IsAttributeDefined(parentCleanupMethod, false)) .Returns(true); _mockReflectHelper - .Setup(rh => rh.GetFirstDerivedAttributeOrDefault(parentCleanupMethod, true)) + .Setup(rh => rh.GetFirstAttributeOrDefault(parentCleanupMethod, true)) .Returns(new ClassCleanupAttribute(InheritanceBehavior.BeforeEachDerivedClass)); var testMethod = new TestMethod("TestMethod", type.FullName!, "A", isAsync: false); @@ -597,10 +597,10 @@ public void GetTestMethodInfoShouldThrowIfClassInitHasIncorrectSignature() var testMethod = new TestMethod("M", type.FullName!, "A", isAsync: false); _mockReflectHelper.Setup( - rh => rh.IsDerivedAttributeDefined(type, false)).Returns(true); + rh => rh.IsAttributeDefined(type, false)).Returns(true); _mockReflectHelper.Setup( - rh => rh.IsNonDerivedAttributeDefined(type.GetMethod("AssemblyInit")!, false)).Returns(true); + rh => rh.IsAttributeDefined(type.GetMethod("AssemblyInit")!, false)).Returns(true); void A() => _typeCache.GetTestMethodInfo( @@ -626,10 +626,10 @@ public void GetTestMethodInfoShouldThrowIfClassCleanupHasIncorrectSignature() var testMethod = new TestMethod("M", type.FullName!, "A", isAsync: false); _mockReflectHelper.Setup( - rh => rh.IsDerivedAttributeDefined(type, false)).Returns(true); + rh => rh.IsAttributeDefined(type, false)).Returns(true); _mockReflectHelper.Setup( - rh => rh.IsNonDerivedAttributeDefined(type.GetMethod("AssemblyCleanup")!, false)).Returns(true); + rh => rh.IsAttributeDefined(type.GetMethod("AssemblyCleanup")!, false)).Returns(true); void A() => _typeCache.GetTestMethodInfo( @@ -655,10 +655,10 @@ public void GetTestMethodInfoShouldCacheTestInitializeAttribute() var testMethod = new TestMethod("TestInit", type.FullName!, "A", isAsync: false); _mockReflectHelper.Setup( - rh => rh.IsNonDerivedAttributeDefined(type, true)).Returns(true); + rh => rh.IsAttributeDefined(type, true)).Returns(true); _mockReflectHelper.Setup( - rh => rh.IsNonDerivedAttributeDefined(type.GetMethod("TestInit")!, false)).Returns(true); + rh => rh.IsAttributeDefined(type.GetMethod("TestInit")!, false)).Returns(true); _typeCache.GetTestMethodInfo( testMethod, @@ -674,10 +674,10 @@ public void GetTestMethodInfoShouldCacheTestCleanupAttribute() var testMethod = new TestMethod("TestCleanup", type.FullName!, "A", isAsync: false); _mockReflectHelper.Setup( - rh => rh.IsNonDerivedAttributeDefined(type, true)).Returns(true); + rh => rh.IsAttributeDefined(type, true)).Returns(true); _mockReflectHelper.Setup( - rh => rh.IsNonDerivedAttributeDefined(type.GetMethod("TestCleanup")!, false)).Returns(true); + rh => rh.IsAttributeDefined(type.GetMethod("TestCleanup")!, false)).Returns(true); _typeCache.GetTestMethodInfo( testMethod, @@ -693,10 +693,10 @@ public void GetTestMethodInfoShouldThrowIfTestInitOrCleanupHasIncorrectSignature var testMethod = new TestMethod("M", type.FullName!, "A", isAsync: false); _mockReflectHelper.Setup( - rh => rh.IsDerivedAttributeDefined(type, false)).Returns(true); + rh => rh.IsAttributeDefined(type, false)).Returns(true); _mockReflectHelper.Setup( - rh => rh.IsNonDerivedAttributeDefined(type.GetMethod("TestInit")!, false)).Returns(true); + rh => rh.IsAttributeDefined(type.GetMethod("TestInit")!, false)).Returns(true); void A() => _typeCache.GetTestMethodInfo( @@ -723,10 +723,10 @@ public void GetTestMethodInfoShouldCacheTestInitializeAttributeDefinedInBaseClas var testMethod = new TestMethod("TestMethod", type.FullName!, "A", isAsync: false); _mockReflectHelper.Setup( - rh => rh.IsNonDerivedAttributeDefined(type, true)).Returns(true); + rh => rh.IsAttributeDefined(type, true)).Returns(true); _mockReflectHelper.Setup( - rh => rh.IsNonDerivedAttributeDefined(baseType.GetMethod("TestInit")!, false)).Returns(true); + rh => rh.IsAttributeDefined(baseType.GetMethod("TestInit")!, false)).Returns(true); _typeCache.GetTestMethodInfo( testMethod, @@ -743,10 +743,10 @@ public void GetTestMethodInfoShouldCacheTestCleanupAttributeDefinedInBaseClass() var testMethod = new TestMethod("TestMethod", type.FullName!, "A", isAsync: false); _mockReflectHelper.Setup( - rh => rh.IsNonDerivedAttributeDefined(type, true)).Returns(true); + rh => rh.IsAttributeDefined(type, true)).Returns(true); _mockReflectHelper.Setup( - rh => rh.IsNonDerivedAttributeDefined(baseType.GetMethod("TestCleanup")!, false)).Returns(true); + rh => rh.IsAttributeDefined(baseType.GetMethod("TestCleanup")!, false)).Returns(true); _typeCache.GetTestMethodInfo( testMethod, @@ -763,7 +763,7 @@ public void GetTestMethodInfoShouldCacheClassInfoInstanceAndReuseFromCache() var testMethod = new TestMethod(methodInfo.Name, type.FullName!, "A", isAsync: false); _mockReflectHelper.Setup( - rh => rh.IsNonDerivedAttributeDefined(type, true)).Returns(true); + rh => rh.IsAttributeDefined(type, true)).Returns(true); _typeCache.GetTestMethodInfo( testMethod, @@ -809,7 +809,7 @@ public void GetTestMethodInfoShouldReturnTestMethodInfo() MethodInfo methodInfo = type.GetMethod("TestMethod")!; var testMethod = new TestMethod(methodInfo.Name, type.FullName!, "A", isAsync: false); - _mockReflectHelper.Setup(rh => rh.GetFirstDerivedAttributeOrDefault(It.IsAny(), false)).CallBase(); + _mockReflectHelper.Setup(rh => rh.GetFirstAttributeOrDefault(It.IsAny(), false)).CallBase(); TestMethodInfo? testMethodInfo = _typeCache.GetTestMethodInfo( testMethod, new TestContextImplementation(testMethod, new ThreadSafeStringWriter(null!, "test"), new Dictionary())); @@ -826,10 +826,10 @@ public void GetTestMethodInfoShouldReturnTestMethodInfoWithTimeout() MethodInfo methodInfo = type.GetMethod("TestMethodWithTimeout")!; var testMethod = new TestMethod(methodInfo.Name, type.FullName!, "A", isAsync: false); - _mockReflectHelper.Setup(rh => rh.IsNonDerivedAttributeDefined(methodInfo, false)) + _mockReflectHelper.Setup(rh => rh.IsAttributeDefined(methodInfo, false)) .Returns(true); - _mockReflectHelper.Setup(rh => rh.GetFirstDerivedAttributeOrDefault(It.IsAny(), false)).CallBase(); - _mockReflectHelper.Setup(rh => rh.GetFirstNonDerivedAttributeOrDefault(methodInfo, false)).CallBase(); + _mockReflectHelper.Setup(rh => rh.GetFirstAttributeOrDefault(It.IsAny(), false)).CallBase(); + _mockReflectHelper.Setup(rh => rh.GetFirstAttributeOrDefault(methodInfo, false)).CallBase(); TestMethodInfo? testMethodInfo = _typeCache.GetTestMethodInfo( testMethod, new TestContextImplementation(testMethod, new ThreadSafeStringWriter(null!, "test"), new Dictionary())); @@ -846,9 +846,9 @@ public void GetTestMethodInfoShouldThrowWhenTimeoutIsNegative() MethodInfo methodInfo = type.GetMethod("TestMethodWithNegativeTimeout")!; var testMethod = new TestMethod(methodInfo.Name, type.FullName!, "A", isAsync: false); - _mockReflectHelper.Setup(rh => rh.IsNonDerivedAttributeDefined(methodInfo, false)) + _mockReflectHelper.Setup(rh => rh.IsAttributeDefined(methodInfo, false)) .Returns(true); - _mockReflectHelper.Setup(ReflectHelper => ReflectHelper.GetFirstNonDerivedAttributeOrDefault(methodInfo, false)) + _mockReflectHelper.Setup(ReflectHelper => ReflectHelper.GetFirstAttributeOrDefault(methodInfo, false)) .CallBase(); void A() => _typeCache.GetTestMethodInfo( @@ -873,9 +873,9 @@ public void GetTestMethodInfoShouldThrowWhenTimeoutIsZero() MethodInfo methodInfo = type.GetMethod("TestMethodWithTimeoutOfZero")!; var testMethod = new TestMethod(methodInfo.Name, type.FullName!, "A", isAsync: false); - _mockReflectHelper.Setup(rh => rh.IsNonDerivedAttributeDefined(methodInfo, false)) + _mockReflectHelper.Setup(rh => rh.IsAttributeDefined(methodInfo, false)) .Returns(true); - _mockReflectHelper.Setup(ReflectHelper => ReflectHelper.GetFirstNonDerivedAttributeOrDefault(methodInfo, false)) + _mockReflectHelper.Setup(ReflectHelper => ReflectHelper.GetFirstAttributeOrDefault(methodInfo, false)) .CallBase(); void A() => _typeCache.GetTestMethodInfo( @@ -935,9 +935,9 @@ public void GetTestMethodInfoWhenTimeoutAttributeSetShouldReturnTimeoutBasedOnAt MethodInfo methodInfo = type.GetMethod("TestMethodWithTimeout")!; var testMethod = new TestMethod(methodInfo.Name, type.FullName!, "A", isAsync: false); - _mockReflectHelper.Setup(rh => rh.IsNonDerivedAttributeDefined(methodInfo, false)) + _mockReflectHelper.Setup(rh => rh.IsAttributeDefined(methodInfo, false)) .Returns(true); - _mockReflectHelper.Setup(ReflectHelper => ReflectHelper.GetFirstNonDerivedAttributeOrDefault(methodInfo, false)) + _mockReflectHelper.Setup(ReflectHelper => ReflectHelper.GetFirstAttributeOrDefault(methodInfo, false)) .CallBase(); TestMethodInfo? testMethodInfo = _typeCache.GetTestMethodInfo( @@ -977,7 +977,7 @@ public void GetTestMethodInfoShouldReturnTestMethodInfoForMethodsAdornedWithADer MethodInfo methodInfo = type.GetMethod("TestMethodWithDerivedTestMethodAttribute")!; var testMethod = new TestMethod(methodInfo.Name, type.FullName!, "A", isAsync: false); - _mockReflectHelper.Setup(rh => rh.GetFirstDerivedAttributeOrDefault(It.IsAny(), false)).CallBase(); + _mockReflectHelper.Setup(rh => rh.GetFirstAttributeOrDefault(It.IsAny(), false)).CallBase(); TestMethodInfo? testMethodInfo = _typeCache.GetTestMethodInfo( testMethod, new TestContextImplementation(testMethod, new ThreadSafeStringWriter(null!, "test"), new Dictionary())); @@ -1110,7 +1110,7 @@ public void GetTestMethodInfoShouldReturnTestMethodInfoForDerivedTestClasses() MethodInfo methodInfo = type.GetRuntimeMethod("DummyTestMethod", [])!; var testMethod = new TestMethod(methodInfo.Name, type.FullName!, "A", isAsync: false); - _mockReflectHelper.Setup(rh => rh.GetFirstDerivedAttributeOrDefault(It.IsAny(), false)).CallBase(); + _mockReflectHelper.Setup(rh => rh.GetFirstAttributeOrDefault(It.IsAny(), false)).CallBase(); TestMethodInfo? testMethodInfo = _typeCache.GetTestMethodInfo( testMethod, new TestContextImplementation(testMethod, new ThreadSafeStringWriter(null!, "test"), new Dictionary())); @@ -1127,7 +1127,7 @@ public void GetTestMethodInfoShouldReturnTestMethodInfoForDerivedClassMethodOver MethodInfo methodInfo = type.GetRuntimeMethod("OverloadedTestMethod", [])!; var testMethod = new TestMethod(methodInfo.Name, type.FullName!, "A", isAsync: false); - _mockReflectHelper.Setup(rh => rh.GetFirstDerivedAttributeOrDefault(It.IsAny(), false)).CallBase(); + _mockReflectHelper.Setup(rh => rh.GetFirstAttributeOrDefault(It.IsAny(), false)).CallBase(); TestMethodInfo? testMethodInfo = _typeCache.GetTestMethodInfo( testMethod, new TestContextImplementation(testMethod, new ThreadSafeStringWriter(null!, "test"), new Dictionary())); @@ -1148,7 +1148,7 @@ public void GetTestMethodInfoShouldReturnTestMethodInfoForDeclaringTypeMethodOve DeclaringClassFullName = baseType.FullName!, }; - _mockReflectHelper.Setup(rh => rh.GetFirstDerivedAttributeOrDefault(It.IsAny(), false)).CallBase(); + _mockReflectHelper.Setup(rh => rh.GetFirstAttributeOrDefault(It.IsAny(), false)).CallBase(); TestMethodInfo? testMethodInfo = _typeCache.GetTestMethodInfo( testMethod, new TestContextImplementation(testMethod, new ThreadSafeStringWriter(null!, "test"), new Dictionary())); @@ -1181,10 +1181,10 @@ public void ClassInfoListWithExecutableCleanupMethodsShouldReturnEmptyListWhenCl var testMethod = new TestMethod(methodInfo.Name, type.FullName!, "A", isAsync: false); _mockReflectHelper.Setup( - rh => rh.IsNonDerivedAttributeDefined(type, true)).Returns(true); + rh => rh.IsAttributeDefined(type, true)).Returns(true); _mockReflectHelper.Setup( - rh => rh.IsNonDerivedAttributeDefined(type.GetMethod("TestCleanup")!, false)).Returns(false); + rh => rh.IsAttributeDefined(type.GetMethod("TestCleanup")!, false)).Returns(false); _typeCache.GetTestMethodInfo( testMethod, @@ -1202,10 +1202,10 @@ public void ClassInfoListWithExecutableCleanupMethodsShouldReturnClassInfosWithE var testMethod = new TestMethod(methodInfo.Name, type.FullName!, "A", isAsync: false); _mockReflectHelper.Setup( - rh => rh.IsNonDerivedAttributeDefined(type, true)).Returns(true); + rh => rh.IsAttributeDefined(type, true)).Returns(true); _mockReflectHelper.Setup( - rh => rh.IsNonDerivedAttributeDefined(type.GetMethod("AssemblyCleanup")!, false)).Returns(true); + rh => rh.IsAttributeDefined(type.GetMethod("AssemblyCleanup")!, false)).Returns(true); _typeCache.GetTestMethodInfo( testMethod, @@ -1235,10 +1235,10 @@ public void AssemblyInfoListWithExecutableCleanupMethodsShouldReturnEmptyListWhe var testMethod = new TestMethod(methodInfo.Name, type.FullName!, "A", isAsync: false); _mockReflectHelper.Setup( - rh => rh.IsDerivedAttributeDefined(type, false)).Returns(true); + rh => rh.IsAttributeDefined(type, false)).Returns(true); _mockReflectHelper.Setup( - rh => rh.IsNonDerivedAttributeDefined(type.GetMethod("AssemblyCleanup")!, false)).Returns(false); + rh => rh.IsAttributeDefined(type.GetMethod("AssemblyCleanup")!, false)).Returns(false); _typeCache.GetTestMethodInfo( testMethod, @@ -1256,10 +1256,10 @@ public void AssemblyInfoListWithExecutableCleanupMethodsShouldReturnAssemblyInfo var testMethod = new TestMethod(methodInfo.Name, type.FullName!, "A", isAsync: false); _mockReflectHelper.Setup( - rh => rh.IsDerivedAttributeDefined(type, false)).Returns(true); + rh => rh.IsAttributeDefined(type, false)).Returns(true); _mockReflectHelper.Setup( - rh => rh.IsNonDerivedAttributeDefined(type.GetMethod("AssemblyCleanup")!, false)).Returns(true); + rh => rh.IsAttributeDefined(type.GetMethod("AssemblyCleanup")!, false)).Returns(true); _typeCache.GetTestMethodInfo( testMethod, @@ -1281,7 +1281,7 @@ public void ResolveExpectedExceptionHelperShouldThrowIfMultipleExpectedException MethodInfo methodInfo = type.GetMethod("TestMethodWithMultipleExpectedException")!; var testMethod = new TestMethod(methodInfo.Name, type.FullName!, "A", isAsync: false); - _mockReflectHelper.Setup(rh => rh.IsNonDerivedAttributeDefined(methodInfo, false)) + _mockReflectHelper.Setup(rh => rh.IsAttributeDefined(methodInfo, false)) .Returns(true); try diff --git a/test/UnitTests/MSTestAdapter.UnitTests/Execution/UnitTestRunnerTests.cs b/test/UnitTests/MSTestAdapter.UnitTests/Execution/UnitTestRunnerTests.cs index 380c69c3fd..142ff3dffc 100644 --- a/test/UnitTests/MSTestAdapter.UnitTests/Execution/UnitTestRunnerTests.cs +++ b/test/UnitTests/MSTestAdapter.UnitTests/Execution/UnitTestRunnerTests.cs @@ -292,7 +292,7 @@ public async Task RunSingleTestShouldCallAssemblyInitializeAndClassInitializeMet _testablePlatformServiceProvider.MockFileOperations.Setup(fo => fo.LoadAssembly("A", It.IsAny())) .Returns(Assembly.GetExecutingAssembly()); mockReflectHelper.Setup( - rh => rh.IsNonDerivedAttributeDefined(type.GetMethod("AssemblyInitialize")!, It.IsAny())) + rh => rh.IsAttributeDefined(type.GetMethod("AssemblyInitialize")!, It.IsAny())) .Returns(true); int validator = 1; diff --git a/test/UnitTests/MSTestAdapter.UnitTests/Helpers/ReflectHelperTests.cs b/test/UnitTests/MSTestAdapter.UnitTests/Helpers/ReflectHelperTests.cs index f6856b60ba..16cde8c2bb 100644 --- a/test/UnitTests/MSTestAdapter.UnitTests/Helpers/ReflectHelperTests.cs +++ b/test/UnitTests/MSTestAdapter.UnitTests/Helpers/ReflectHelperTests.cs @@ -150,7 +150,7 @@ public void IsAttributeDefinedShouldReturnTrueIfSpecifiedAttributeIsDefinedOnAMe Setup(ro => ro.GetCustomAttributes(mockMemberInfo.Object, true)). Returns(attributes); - Verify(rh.IsNonDerivedAttributeDefined(mockMemberInfo.Object, true)); + Verify(rh.IsAttributeDefined(mockMemberInfo.Object, true)); } public void IsAttributeDefinedShouldReturnFalseIfSpecifiedAttributeIsNotDefinedOnAMember() @@ -163,7 +163,7 @@ public void IsAttributeDefinedShouldReturnFalseIfSpecifiedAttributeIsNotDefinedO Setup(ro => ro.GetCustomAttributes(mockMemberInfo.Object, true)). Returns(attributes); - Verify(!rh.IsNonDerivedAttributeDefined(mockMemberInfo.Object, true)); + Verify(!rh.IsAttributeDefined(mockMemberInfo.Object, true)); } public void IsAttributeDefinedShouldReturnFromCache() @@ -180,10 +180,10 @@ public void IsAttributeDefinedShouldReturnFromCache() Setup(ro => ro.GetCustomAttributes(memberInfo, true)). Returns(attributes); - Verify(rh.IsNonDerivedAttributeDefined(memberInfo, true)); + Verify(rh.IsAttributeDefined(memberInfo, true)); // Validate that reflection APIs are not called again. - Verify(rh.IsNonDerivedAttributeDefined(memberInfo, true)); + Verify(rh.IsAttributeDefined(memberInfo, true)); _testablePlatformServiceProvider.MockReflectionOperations.Verify(ro => ro.GetCustomAttributes(memberInfo, true), Times.Once); // Also validate that reflection APIs for an individual type is not called since the cache gives us what we need already. @@ -200,7 +200,7 @@ public void HasAttributeDerivedFromShouldReturnTrueIfSpecifiedAttributeIsDefined Setup(ro => ro.GetCustomAttributes(mockMemberInfo.Object, true)). Returns(attributes); - Verify(rh.IsDerivedAttributeDefined(mockMemberInfo.Object, true)); + Verify(rh.IsAttributeDefined(mockMemberInfo.Object, true)); } public void HasAttributeDerivedFromShouldReturnFalseIfSpecifiedAttributeIsNotDefinedOnAMember() @@ -213,7 +213,7 @@ public void HasAttributeDerivedFromShouldReturnFalseIfSpecifiedAttributeIsNotDef Setup(ro => ro.GetCustomAttributes(mockMemberInfo.Object, true)). Returns(attributes); - Verify(!rh.IsNonDerivedAttributeDefined(mockMemberInfo.Object, true)); + Verify(!rh.IsAttributeDefined(mockMemberInfo.Object, true)); } public void HasAttributeDerivedFromShouldReturnFromCache() @@ -230,10 +230,10 @@ public void HasAttributeDerivedFromShouldReturnFromCache() Setup(ro => ro.GetCustomAttributes(memberInfo, true)). Returns(attributes); - Verify(rh.IsDerivedAttributeDefined(memberInfo, true)); + Verify(rh.IsAttributeDefined(memberInfo, true)); // Validate that reflection APIs are not called again. - Verify(rh.IsDerivedAttributeDefined(memberInfo, true)); + Verify(rh.IsAttributeDefined(memberInfo, true)); _testablePlatformServiceProvider.MockReflectionOperations.Verify(ro => ro.GetCustomAttributes(memberInfo, true), Times.Once); // Also validate that reflection APIs for an individual type is not called since the cache gives us what we need already. @@ -254,7 +254,7 @@ public void HasAttributeDerivedFromShouldReturnFalseQueryingProvidedAttributesEx Setup(ro => ro.GetCustomAttributes(mockMemberInfo.Object, typeof(TestMethodAttribute), true)). Returns(attributes); - Verify(!rh.IsNonDerivedAttributeDefined(mockMemberInfo.Object, true)); + Verify(!rh.IsAttributeDefined(mockMemberInfo.Object, true)); } public void GettingAttributesShouldNotReturnInheritedAttributesWhenAskingForNonInheritedAttributes() @@ -274,8 +274,8 @@ public void GettingAttributesShouldNotReturnInheritedAttributesWhenAskingForNonI Setup(ro => ro.GetCustomAttributes(It.IsAny(), /* inherit */ false)). Returns([new TestClassAttribute()]); - TestClassAttribute[] inheritedAttributes = rh.GetDerivedAttributes(typeof(object), inherit: true).ToArray(); - TestClassAttribute[] nonInheritedAttributes = rh.GetDerivedAttributes(typeof(object), inherit: false).ToArray(); + TestClassAttribute[] inheritedAttributes = rh.GetAttributes(typeof(object), inherit: true).ToArray(); + TestClassAttribute[] nonInheritedAttributes = rh.GetAttributes(typeof(object), inherit: false).ToArray(); Verify(inheritedAttributes.Length == 2); Verify(nonInheritedAttributes.Length == 1); From 35ac25e5c53ed8313e1eb17954714a168cd5d972 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Fri, 30 May 2025 16:52:57 +0200 Subject: [PATCH 044/541] Cleaning packaging of MSTest.TestFramework (#5672) --- .../MSTest.TestFramework.NonWindows.nuspec | 8 ++++---- .../TestFramework.Extensions/MSTest.TestFramework.nuspec | 8 ++++---- .../TestFramework.Extensions.csproj | 6 ------ .../MSTest.TestFramework.targets | 0 4 files changed, 8 insertions(+), 14 deletions(-) rename src/TestFramework/TestFramework.Extensions/buildTransitive/{winui+uwp => net6.0AndLater}/MSTest.TestFramework.targets (100%) diff --git a/src/TestFramework/TestFramework.Extensions/MSTest.TestFramework.NonWindows.nuspec b/src/TestFramework/TestFramework.Extensions/MSTest.TestFramework.NonWindows.nuspec index af5c322364..6191d8cbb4 100644 --- a/src/TestFramework/TestFramework.Extensions/MSTest.TestFramework.NonWindows.nuspec +++ b/src/TestFramework/TestFramework.Extensions/MSTest.TestFramework.NonWindows.nuspec @@ -48,7 +48,7 @@ - + @@ -57,7 +57,7 @@ - + @@ -66,7 +66,7 @@ - + @@ -75,7 +75,7 @@ - + diff --git a/src/TestFramework/TestFramework.Extensions/MSTest.TestFramework.nuspec b/src/TestFramework/TestFramework.Extensions/MSTest.TestFramework.nuspec index 67a4e010a2..bfa19db5e8 100644 --- a/src/TestFramework/TestFramework.Extensions/MSTest.TestFramework.nuspec +++ b/src/TestFramework/TestFramework.Extensions/MSTest.TestFramework.nuspec @@ -75,7 +75,7 @@ - + @@ -86,7 +86,7 @@ - + @@ -95,7 +95,7 @@ - + @@ -104,7 +104,7 @@ - + diff --git a/src/TestFramework/TestFramework.Extensions/TestFramework.Extensions.csproj b/src/TestFramework/TestFramework.Extensions/TestFramework.Extensions.csproj index 94c011302c..85515dfec2 100644 --- a/src/TestFramework/TestFramework.Extensions/TestFramework.Extensions.csproj +++ b/src/TestFramework/TestFramework.Extensions/TestFramework.Extensions.csproj @@ -96,12 +96,6 @@ - - - PreserveNewest - - - diff --git a/src/TestFramework/TestFramework.Extensions/buildTransitive/winui+uwp/MSTest.TestFramework.targets b/src/TestFramework/TestFramework.Extensions/buildTransitive/net6.0AndLater/MSTest.TestFramework.targets similarity index 100% rename from src/TestFramework/TestFramework.Extensions/buildTransitive/winui+uwp/MSTest.TestFramework.targets rename to src/TestFramework/TestFramework.Extensions/buildTransitive/net6.0AndLater/MSTest.TestFramework.targets From 803e1d6faff4c14dd092f5dafc756e99886f60fe Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Mon, 2 Jun 2025 09:34:00 +0200 Subject: [PATCH 045/541] Add implicit using even when not using MSTest.Sdk (#5589) --- eng/verify-nupkgs.ps1 | 2 +- src/Package/MSTest.Sdk/Sdk/Runner/Common.targets | 9 --------- .../MSTest.TestFramework.NonWindows.nuspec | 4 ++++ .../MSTest.TestFramework.nuspec | 8 ++++++++ .../build/net462/MSTest.TestFramework.targets | 3 +++ .../build/netcoreapp3.1/MSTest.TestFramework.targets | 3 +++ .../build/netstandard2.0/MSTest.TestFramework.targets | 3 +++ .../build/uap10.0/MSTest.TestFramework.targets | 3 +++ .../net6.0AndLater/MSTest.TestFramework.targets | 8 ++++++++ .../others/MSTest.TestFramework.targets | 11 +++++++++++ 10 files changed, 44 insertions(+), 10 deletions(-) create mode 100644 src/TestFramework/TestFramework.Extensions/build/net462/MSTest.TestFramework.targets create mode 100644 src/TestFramework/TestFramework.Extensions/build/netcoreapp3.1/MSTest.TestFramework.targets create mode 100644 src/TestFramework/TestFramework.Extensions/build/netstandard2.0/MSTest.TestFramework.targets create mode 100644 src/TestFramework/TestFramework.Extensions/build/uap10.0/MSTest.TestFramework.targets create mode 100644 src/TestFramework/TestFramework.Extensions/buildTransitive/others/MSTest.TestFramework.targets diff --git a/eng/verify-nupkgs.ps1 b/eng/verify-nupkgs.ps1 index cd18465fe1..26e97d3fd1 100644 --- a/eng/verify-nupkgs.ps1 +++ b/eng/verify-nupkgs.ps1 @@ -20,7 +20,7 @@ function Confirm-NugetPackages { Write-Verbose "Starting Confirm-NugetPackages." $expectedNumOfFiles = @{ "MSTest.Sdk" = 15 - "MSTest.TestFramework" = 154 + "MSTest.TestFramework" = 162 "MSTest.TestAdapter" = 93 "MSTest" = 14 "MSTest.Analyzers" = 56 diff --git a/src/Package/MSTest.Sdk/Sdk/Runner/Common.targets b/src/Package/MSTest.Sdk/Sdk/Runner/Common.targets index af047cbf0c..78d6d93755 100644 --- a/src/Package/MSTest.Sdk/Sdk/Runner/Common.targets +++ b/src/Package/MSTest.Sdk/Sdk/Runner/Common.targets @@ -33,13 +33,4 @@ - - - - - diff --git a/src/TestFramework/TestFramework.Extensions/MSTest.TestFramework.NonWindows.nuspec b/src/TestFramework/TestFramework.Extensions/MSTest.TestFramework.NonWindows.nuspec index 6191d8cbb4..d214368c74 100644 --- a/src/TestFramework/TestFramework.Extensions/MSTest.TestFramework.NonWindows.nuspec +++ b/src/TestFramework/TestFramework.Extensions/MSTest.TestFramework.NonWindows.nuspec @@ -34,18 +34,22 @@ $CommonFileElements$ + + + + diff --git a/src/TestFramework/TestFramework.Extensions/MSTest.TestFramework.nuspec b/src/TestFramework/TestFramework.Extensions/MSTest.TestFramework.nuspec index bfa19db5e8..deeb4715bd 100644 --- a/src/TestFramework/TestFramework.Extensions/MSTest.TestFramework.nuspec +++ b/src/TestFramework/TestFramework.Extensions/MSTest.TestFramework.nuspec @@ -47,32 +47,40 @@ $CommonFileElements$ + + + + + + + + diff --git a/src/TestFramework/TestFramework.Extensions/build/net462/MSTest.TestFramework.targets b/src/TestFramework/TestFramework.Extensions/build/net462/MSTest.TestFramework.targets new file mode 100644 index 0000000000..f80fd5bb22 --- /dev/null +++ b/src/TestFramework/TestFramework.Extensions/build/net462/MSTest.TestFramework.targets @@ -0,0 +1,3 @@ + + + diff --git a/src/TestFramework/TestFramework.Extensions/build/netcoreapp3.1/MSTest.TestFramework.targets b/src/TestFramework/TestFramework.Extensions/build/netcoreapp3.1/MSTest.TestFramework.targets new file mode 100644 index 0000000000..a9e20a1c40 --- /dev/null +++ b/src/TestFramework/TestFramework.Extensions/build/netcoreapp3.1/MSTest.TestFramework.targets @@ -0,0 +1,3 @@ + + + diff --git a/src/TestFramework/TestFramework.Extensions/build/netstandard2.0/MSTest.TestFramework.targets b/src/TestFramework/TestFramework.Extensions/build/netstandard2.0/MSTest.TestFramework.targets new file mode 100644 index 0000000000..d4afeaee4a --- /dev/null +++ b/src/TestFramework/TestFramework.Extensions/build/netstandard2.0/MSTest.TestFramework.targets @@ -0,0 +1,3 @@ + + + diff --git a/src/TestFramework/TestFramework.Extensions/build/uap10.0/MSTest.TestFramework.targets b/src/TestFramework/TestFramework.Extensions/build/uap10.0/MSTest.TestFramework.targets new file mode 100644 index 0000000000..9b248fe99e --- /dev/null +++ b/src/TestFramework/TestFramework.Extensions/build/uap10.0/MSTest.TestFramework.targets @@ -0,0 +1,3 @@ + + + diff --git a/src/TestFramework/TestFramework.Extensions/buildTransitive/net6.0AndLater/MSTest.TestFramework.targets b/src/TestFramework/TestFramework.Extensions/buildTransitive/net6.0AndLater/MSTest.TestFramework.targets index 4fa711c2c7..5d2ec50262 100644 --- a/src/TestFramework/TestFramework.Extensions/buildTransitive/net6.0AndLater/MSTest.TestFramework.targets +++ b/src/TestFramework/TestFramework.Extensions/buildTransitive/net6.0AndLater/MSTest.TestFramework.targets @@ -20,4 +20,12 @@ + + + + diff --git a/src/TestFramework/TestFramework.Extensions/buildTransitive/others/MSTest.TestFramework.targets b/src/TestFramework/TestFramework.Extensions/buildTransitive/others/MSTest.TestFramework.targets new file mode 100644 index 0000000000..7ab2dd1dd4 --- /dev/null +++ b/src/TestFramework/TestFramework.Extensions/buildTransitive/others/MSTest.TestFramework.targets @@ -0,0 +1,11 @@ + + + + + + + From 88183f462bb30773a84f61ef968c1fc471e50658 Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Mon, 2 Jun 2025 19:48:21 +1000 Subject: [PATCH 046/541] remove redudnant cast to IReadOnlyList and add a not null ckeck in AssemblyEnumeratorTests (#5402) --- .../Discovery/AssemblyEnumeratorTests.cs | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/test/UnitTests/MSTestAdapter.UnitTests/Discovery/AssemblyEnumeratorTests.cs b/test/UnitTests/MSTestAdapter.UnitTests/Discovery/AssemblyEnumeratorTests.cs index 4a34f4c0bb..239be62d6b 100644 --- a/test/UnitTests/MSTestAdapter.UnitTests/Discovery/AssemblyEnumeratorTests.cs +++ b/test/UnitTests/MSTestAdapter.UnitTests/Discovery/AssemblyEnumeratorTests.cs @@ -94,7 +94,7 @@ public void GetTypesShouldReturnSetOfDefinedTypes() // Setup mocks mockAssembly.Setup(a => a.GetTypes()).Returns(expectedTypes); - IReadOnlyList types = AssemblyEnumerator.GetTypes(mockAssembly.Object, string.Empty, _warnings); + Type[] types = AssemblyEnumerator.GetTypes(mockAssembly.Object, string.Empty, _warnings); Verify(expectedTypes.SequenceEqual(types)); } @@ -116,7 +116,7 @@ public void GetTypesShouldReturnReflectionTypeLoadExceptionTypesOnException() // Setup mocks mockAssembly.Setup(a => a.GetTypes()).Throws(new ReflectionTypeLoadException(reflectedTypes, null)); - IReadOnlyList types = AssemblyEnumerator.GetTypes(mockAssembly.Object, string.Empty, _warnings); + Type[] types = AssemblyEnumerator.GetTypes(mockAssembly.Object, string.Empty, _warnings); Verify(types is not null); Verify(reflectedTypes.Equals(types)); @@ -131,7 +131,10 @@ public void GetTypesShouldLogWarningsWhenReflectionFailsWithLoaderExceptions() mockAssembly.Setup(a => a.GetTypes()).Throws(new ReflectionTypeLoadException(null, exceptions)); mockAssembly.Setup(a => a.GetTypes()).Throws(new ReflectionTypeLoadException(null, exceptions)); - IReadOnlyList types = AssemblyEnumerator.GetTypes(mockAssembly.Object, "DummyAssembly", _warnings); + Type[] types = AssemblyEnumerator.GetTypes(mockAssembly.Object, "DummyAssembly", _warnings); + + // Depending on the TFM, .NET either gives us null or empty array. + Verify(types is null || types.Length == 0); Verify(_warnings.Count == 1); Verify(_warnings.ToList().Contains( From 43d1d16ac9dcc0c2fd945e529a272f159aa0927d Mon Sep 17 00:00:00 2001 From: Tom Longhurst <30480171+thomhurst@users.noreply.github.com> Date: Mon, 2 Jun 2025 12:11:08 +0100 Subject: [PATCH 047/541] Enable filtering with `TestMetadataProperty` in the treenode filter (#5679) --- .../Messages/TestNodeProperties.cs | 3 +++ .../Requests/TreeNodeFilter/TreeNodeFilter.cs | 12 +++++++++++- .../Messages/TestNodePropertiesTests.cs | 1 + .../Requests/TreeNodeFilterTests.cs | 9 +++++++++ 4 files changed, 24 insertions(+), 1 deletion(-) diff --git a/src/Platform/Microsoft.Testing.Platform/Messages/TestNodeProperties.cs b/src/Platform/Microsoft.Testing.Platform/Messages/TestNodeProperties.cs index 858f1b53a0..0a0de9b2b3 100644 --- a/src/Platform/Microsoft.Testing.Platform/Messages/TestNodeProperties.cs +++ b/src/Platform/Microsoft.Testing.Platform/Messages/TestNodeProperties.cs @@ -13,6 +13,7 @@ public interface IProperty; /// /// Key name. /// Key value. +[Obsolete("Use TestMetadataProperty instead. This will be removed in a future version.")] public record KeyValuePairStringProperty(string Key, string Value) : IProperty; /// @@ -415,4 +416,6 @@ public record StandardErrorProperty(string StandardError) : IProperty; /// The description. public record FileArtifactProperty(FileInfo FileInfo, string DisplayName, string? Description = null) : IProperty; +#pragma warning disable CS0618 // Type or member is obsolete internal sealed record SerializableKeyValuePairStringProperty(string Key, string Value) : KeyValuePairStringProperty(Key, Value); +#pragma warning restore CS0618 // Type or member is obsolete diff --git a/src/Platform/Microsoft.Testing.Platform/Requests/TreeNodeFilter/TreeNodeFilter.cs b/src/Platform/Microsoft.Testing.Platform/Requests/TreeNodeFilter/TreeNodeFilter.cs index 7cb4ff2a9e..f20620f964 100644 --- a/src/Platform/Microsoft.Testing.Platform/Requests/TreeNodeFilter/TreeNodeFilter.cs +++ b/src/Platform/Microsoft.Testing.Platform/Requests/TreeNodeFilter/TreeNodeFilter.cs @@ -550,7 +550,7 @@ private static bool MatchProperties( => propertyExpr switch { PropertyExpression { PropertyName: var propExpr, Value: var valueExpr } - => properties.AsEnumerable().Any(prop => prop is KeyValuePairStringProperty kvpProperty && propExpr.Regex.IsMatch(kvpProperty.Key) && valueExpr.Regex.IsMatch(kvpProperty.Value)), + => properties.AsEnumerable().Any(prop => IsMatchingProperty(prop, propExpr, valueExpr)), OperatorExpression { Op: FilterOperator.Or, SubExpressions: var subExprs } => subExprs.Any(expr => MatchProperties(expr, properties)), OperatorExpression { Op: FilterOperator.And, SubExpressions: var subExprs } @@ -559,4 +559,14 @@ private static bool MatchProperties( => !MatchProperties(subExprs.Single(), properties), _ => throw ApplicationStateGuard.Unreachable(), }; + + private static bool IsMatchingProperty(IProperty prop, ValueExpression propExpr, ValueExpression valueExpr) => + prop switch + { +#pragma warning disable CS0618 // Type or member is obsolete + KeyValuePairStringProperty kvpProperty => propExpr.Regex.IsMatch(kvpProperty.Key) && valueExpr.Regex.IsMatch(kvpProperty.Value), +#pragma warning restore CS0618 // Type or member is obsolete + TestMetadataProperty testMetadataProperty => propExpr.Regex.IsMatch(testMetadataProperty.Key) && valueExpr.Regex.IsMatch(testMetadataProperty.Value), + _ => false, + }; } diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Messages/TestNodePropertiesTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Messages/TestNodePropertiesTests.cs index 849b57375f..2a91a44c32 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Messages/TestNodePropertiesTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Messages/TestNodePropertiesTests.cs @@ -1,6 +1,7 @@ // 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 CS0618 // Type or member is obsolete namespace Microsoft.Testing.Platform.Extensions.Messages.UnitTests; [TestClass] diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Requests/TreeNodeFilterTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Requests/TreeNodeFilterTests.cs index f587f02457..5f9e229e99 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Requests/TreeNodeFilterTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Requests/TreeNodeFilterTests.cs @@ -3,6 +3,7 @@ using Microsoft.Testing.Platform.Extensions.Messages; using Microsoft.Testing.Platform.Requests; +#pragma warning disable CS0618 // Type or member is obsolete #pragma warning disable TPEXP // Type is for evaluation purposes only and is subject to change or removal in future updates. Suppress this diagnostic to proceed. namespace Microsoft.Testing.Platform.UnitTests; @@ -220,6 +221,14 @@ public void MatchAllFilterSubpathWithPropertyExpression() Assert.IsFalse(filter.MatchesFilter("/B/A/C/D", new PropertyBag(new KeyValuePairStringProperty("A", "B")))); } + [TestMethod] + public void MatchAllFilterSubpathWithPropertyExpression_WithTestMetadataProperty() + { + TreeNodeFilter filter = new("/A/**[A=B]"); + Assert.IsTrue(filter.MatchesFilter("/A/B/C/D", new PropertyBag(new TestMetadataProperty("A", "B")))); + Assert.IsFalse(filter.MatchesFilter("/B/A/C/D", new PropertyBag(new TestMetadataProperty("A", "B")))); + } + [TestMethod] public void MatchAllFilterWithPropertyExpression_DoNotAllowInMiddleOfFilter() => Assert.ThrowsException(() => _ = new TreeNodeFilter("/**/Path[A=B]")); } From 721ac3244ba48d1f400e830517059a0acf96cb8a Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Tue, 3 Jun 2025 00:09:03 +1000 Subject: [PATCH 048/541] use more collection expressions and mark as error for Rider and R# in editorconfig (#5377) --- .editorconfig | 4 +- samples/Playground/Program.cs | 6 +- .../ServerMode/TestNodeUpdateCollector.cs | 2 +- .../v1.0.0/TestingPlatformClient.cs | 6 +- .../Engine/BFSTestNodeVisitor.cs | 8 +- .../Engine/TestArgumentsManager.cs | 8 +- .../Engine/TestFixtureManager.cs | 8 +- .../Engine/TestFrameworkEngine.cs | 9 +- .../Engine/ThreadPoolTestNodeRunner.cs | 2 +- src/Adapter/MSTest.Engine/Helpers/Result.cs | 2 +- .../TestFramework/TestFramework.cs | 4 +- .../TestFrameworkCapabilities.cs | 2 +- .../TestNodes/FactoryTestNodesBuilder.cs | 3 +- .../TestNodes/FrameworkTestNodeProperties.cs | 2 +- .../MSTest.Engine/TestNodes/TestNode.cs | 4 +- .../Discovery/AssemblyEnumerator.cs | 4 +- .../Discovery/AssemblyEnumeratorWrapper.cs | 2 +- .../Discovery/TypeEnumerator.cs | 9 +- .../Execution/TestCaseDiscoverySink.cs | 2 +- .../Execution/TestClassInfo.cs | 12 +- .../Execution/TestExecutionManager.cs | 4 +- .../Execution/TestMethodInfo.cs | 4 +- .../Execution/TestMethodRunner.cs | 4 +- .../Execution/TestRunCancellationToken.cs | 2 +- .../MSTest.TestAdapter/Execution/TypeCache.cs | 2 +- .../Extensions/MethodInfoExtensions.cs | 4 +- .../Extensions/TestCaseExtensions.cs | 2 +- .../Helpers/ReflectHelper.cs | 4 +- .../Helpers/TestDataSourceHelpers.cs | 4 +- .../ObjectModel/UnitTestElement.cs | 2 +- .../AssemblyResolver.cs | 2 +- .../Data/TestDataConnectionSql.cs | 2 +- .../Deployment/AssemblyLoadWorker.cs | 2 +- .../Services/ReflectionOperations.cs | 4 +- .../Services/TestSource.cs | 12 +- .../Services/ThreadSafeStringWriter.cs | 2 +- .../Utilities/DeploymentItemUtility.cs | 6 +- .../Utilities/DeploymentUtilityBase.cs | 2 +- .../Utilities/ReflectionUtility.cs | 6 +- ...referConstructorOverTestInitializeFixer.cs | 2 +- .../PreferDisposeOverTestCleanupFixer.cs | 2 +- ...referTestInitializeOverConstructorFixer.cs | 2 +- .../TestContextShouldBeValidFixer.cs | 10 +- .../DataRowShouldBeValidAnalyzer.cs | 4 +- .../DoNotUseShadowingAnalyzer.cs | 6 +- .../Helpers/DiagnosticDescriptorHelper.cs | 2 +- .../DiagnosticExtensions.cs | 2 +- .../TestContextShouldBeValidAnalyzer.cs | 2 +- .../GlobalConfigBuilder.cs | 2 +- .../Generators/TestNodesGenerator.cs | 9 +- .../Helpers/SystemPolyfills.cs | 4 +- .../DataRowTestMethodArgumentsInfo.cs | 2 +- .../ObjectModels/TestMethodInfo.cs | 8 +- .../ObjectModels/TestNamespaceInfo.cs | 3 +- .../ObjectModels/TestTypeInfo.cs | 2 +- .../AzureDevOpsReporter.cs | 2 +- .../HangDumpActivityIndicator.cs | 2 +- .../Serializers/GetInProgressTestsResponse.cs | 2 +- .../RetryCommandLineOptionsProvider.cs | 9 +- .../RetryDataConsumer.cs | 2 +- .../RetryExecutionFilterFactory.cs | 3 +- .../RetryFailedTestsPipeServer.cs | 2 +- .../RetryOrchestrator.cs | 10 +- .../AppInsightsProvider.cs | 2 +- .../CIEnvironmentDetectorForTelemetry.cs | 6 +- .../TrxCompareTool.cs | 13 +- .../TrxDataConsumer.cs | 4 +- .../TrxProcessLifetimeHandler.cs | 4 +- .../ObjectModel/Condition.cs | 2 +- .../ObjectModel/FastFilter.cs | 2 +- .../ObjectModel/FilterExpression.cs | 2 +- .../ObjectModel/ObjectModelConverters.cs | 5 +- .../ObjectModel/RunSettingsPatcher.cs | 2 +- ...ngleSessionVSTestAndTestAnywhereAdapter.cs | 2 +- .../Tasks/InvokeTestingPlatformTask.cs | 2 +- ...TestingPlatformAutoRegisteredExtensions.cs | 2 +- .../Builder/TestApplication.cs | 4 +- .../CommandLine/CommandLineHandler.cs | 9 +- .../CommandLine/ParseResult.cs | 2 +- .../CommandLine/Parser.cs | 4 +- .../PlatformCommandLineProvider.cs | 2 +- .../CommandLine/ResponseFileHelper.cs | 2 +- .../Configurations/ConfigurationManager.cs | 2 +- .../Hosts/ServerTestHost.cs | 2 +- .../Hosts/TestHostBuilder.cs | 2 +- .../Hosts/TestHostControllersTestHost.cs | 2 +- .../Logging/LoggerFactory.cs | 2 +- .../Logging/LoggingManager.cs | 2 +- .../Messages/PropertyBag.Property.cs | 2 +- .../Messages/PropertyBag.cs | 4 +- .../OutputDevice/Terminal/AnsiDetector.cs | 6 +- .../OutputDevice/Terminal/AnsiTerminal.cs | 8 +- .../Terminal/AnsiTerminalTestProgressFrame.cs | 4 +- .../Terminal/ExceptionFlattener.cs | 9 +- .../Terminal/TerminalTestReporter.cs | 4 +- .../Terminal/TestNodeResultsState.cs | 2 +- .../Terminal/TestProgressState.cs | 4 +- .../OutputDevice/TerminalOutputDevice.cs | 2 +- .../DotnetTest/DotnetTestConnection.cs | 4 +- .../DotnetTest/IPC/DotnetTestDataConsumer.cs | 66 +++---- .../Serializers/HandshakeMessageSerializer.cs | 2 +- .../TestResultMessagesSerializer.cs | 2 +- .../ServerMode/JsonRpc/FormatterUtilities.cs | 6 +- .../ServerMode/JsonRpc/Json/Json.cs | 173 ++++++++---------- .../JsonRpc/ServerModePerCallOutputDevice.cs | 4 +- .../JsonRpc/TestNodeStateChangeAggregator.cs | 2 +- .../Services/StopPoliciesService.cs | 2 +- .../TestHost/TestHostManager.cs | 6 +- .../TestHostControllersManager.cs | 6 +- .../TestHostOrchestratorManager.cs | 2 +- .../DataSource/DynamicDataOperations.cs | 4 +- .../Attributes/TestMethod/RetryResult.cs | 2 +- .../SdkTests.cs | 2 +- .../ServerModeTests.cs | 8 +- .../DataExtensibilityTests.cs | 2 +- .../Utilities/CLITestBase.discovery.cs | 6 +- .../Utilities/TestCaseFilterFactory.cs | 2 +- .../TimeoutTests.cs | 2 +- .../ExitOnProcessExitTests.cs | 2 +- .../Helpers/AcceptanceTestBase.cs | 5 +- .../RetryFailedTestsTests.cs | 4 +- .../ServerLoggingTests.cs | 2 +- .../ServerMode/TestNodeUpdateCollector.cs | 2 +- .../v1.0.0/TestingPlatformClient.cs | 9 +- .../ReflectionUtilityTests.cs | 2 +- .../DataRowTests_OverriddenGetDisplayName.cs | 2 +- .../DataRowTests_Regular.cs | 8 +- .../DisableExpansionTests.cs | 8 +- .../DynamicDataTests.cs | 8 +- .../CustomTestExTests.cs | 2 +- .../MSTest.Performance.Runner/Context.cs | 4 +- .../PipelinesRunner.cs | 2 +- .../Steps/PlainProcess.cs | 2 +- ...eReferenceNotInitializedSuppressorTests.cs | 2 +- ...cSuffixTestFixtureMethodSuppressorTests.cs | 2 +- ...UseAsyncSuffixTestMethodSuppressorTests.cs | 2 +- .../UseAttributeOnTestMethodAnalyzerTests.cs | 10 +- .../Adapter_ExecuteRequestAsyncTests.cs | 10 +- .../BFSTestNodeVisitorTests.cs | 44 ++--- .../DynamicDataNameProviderTests.cs | 4 +- .../DynamicDataTests.cs | 60 +++--- .../Generators/TestNodesGeneratorTests.cs | 86 +++++---- .../Helpers/MinimalTestRunner.cs | 7 +- .../TestUtilities/GeneratorTester.cs | 16 +- .../TestUtilities/TestingFrameworkVerifier.cs | 2 +- .../AssemblyResolverTests.cs | 8 +- .../Services/DesktopTestDeploymentTests.cs | 2 +- .../Services/ReflectionOperationsTests.cs | 6 +- .../Services/TestDeploymentTests.cs | 2 +- .../Utilities/DeploymentUtilityTests.cs | 2 +- .../DesktopReflectionUtilityTests.cs | 2 +- .../Utilities/ns10FileUtilityTests.cs | 16 +- .../ns13DeploymentItemUtilityTests.cs | 2 +- .../Discovery/AssemblyEnumeratorTests.cs | 7 +- .../AssemblyEnumeratorWrapperTests.cs | 2 +- .../Discovery/TypeEnumeratorTests.cs | 2 +- .../Discovery/TypeValidatorTests.cs | 26 +-- .../DynamicDataAttributeTests.cs | 2 +- .../Execution/ClassCleanupManagerTests.cs | 8 +- .../Execution/TestExecutionManagerTests.cs | 2 +- .../Execution/TestMethodInfoTests.cs | 10 +- .../Execution/TestMethodRunnerTests.cs | 4 +- .../Execution/TestPropertyAttributeTests.cs | 6 +- .../Execution/UnitTestRunnerTests.cs | 6 +- .../Extensions/TestResultExtensionsTests.cs | 4 +- .../Helpers/ReflectHelperTests.cs | 20 +- .../AppInsightsProviderTests.cs | 2 +- .../TrxTests.cs | 2 +- .../ObjectModel/ObjectModelConvertersTests.cs | 24 +-- .../ObjectModel/RunSettingsPatcherTests.cs | 4 +- .../MSBuildTests.cs | 14 +- .../ConfigurationManagerTests.cs | 14 +- .../Helpers/SystemAsyncMonitorTests.cs | 2 +- .../IPC/IPCTests.cs | 11 +- .../IPC/ProtocolTests.cs | 2 +- .../Logging/LogTestHelpers.cs | 4 +- .../Messages/AsynchronousMessageBusTests.cs | 3 +- .../Messages/PropertyBagTests.cs | 2 +- .../ServerMode/FormatterUtilitiesTests.cs | 2 +- .../ServerMode/JsonTests.cs | 6 +- .../ServerMode/JsoniteTests.cs | 2 +- .../Services/TestApplicationResultTests.cs | 8 +- .../TestApplicationBuilderTests.cs | 4 +- .../Assertions/CollectionAssertTests.cs | 10 +- .../CommandLine.cs | 4 +- .../DotnetCli.cs | 2 +- .../ProjectSystem.cs | 2 +- .../TargetFrameworks.cs | 2 +- .../TempDirectory.cs | 2 +- .../TestHost.cs | 2 +- .../TestFrameworkEngine.cs | 7 +- 191 files changed, 611 insertions(+), 666 deletions(-) diff --git a/.editorconfig b/.editorconfig index 430647d9df..dfbcbe5b01 100644 --- a/.editorconfig +++ b/.editorconfig @@ -689,8 +689,8 @@ resharper_empty_constructor_highlighting = warning # Redundant empty argument list on object creation expression resharper_redundant_empty_object_creation_argument_list_highlighting = warning -# IDE0300: Simplify collection initialization -dotnet_style_prefer_collection_expression = false +# IDE0300-IDE0306: Simplify collection initialization +dotnet_style_prefer_collection_expression = true # IDE0065: using directive placement csharp_using_directive_placement = outside_namespace:warning diff --git a/samples/Playground/Program.cs b/samples/Playground/Program.cs index 205088910d..c5c842a040 100644 --- a/samples/Playground/Program.cs +++ b/samples/Playground/Program.cs @@ -57,7 +57,7 @@ public static async Task Main(string[] args) using TestingPlatformClient client = await TestingPlatformClientFactory.StartAsServerAndConnectToTheClientAsync(Environment.ProcessPath!); await client.InitializeAsync(); - List testNodeUpdates = new(); + List testNodeUpdates = []; ResponseListener discoveryResponse = await client.DiscoverTestsAsync(Guid.NewGuid(), node => { testNodeUpdates.AddRange(node); @@ -65,7 +65,7 @@ public static async Task Main(string[] args) }); await discoveryResponse.WaitCompletionAsync(); - ResponseListener runRequest = await client.RunTestsAsync(Guid.NewGuid(), testNodeUpdates.Select(x => x.Node).ToArray(), _ => Task.CompletedTask); + ResponseListener runRequest = await client.RunTestsAsync(Guid.NewGuid(), [.. testNodeUpdates.Select(x => x.Node)], _ => Task.CompletedTask); await runRequest.WaitCompletionAsync(); await client.ExitAsync(); @@ -86,7 +86,7 @@ internal sealed class DummyAdapter : ITestFramework, IDataProducer public string Description => string.Empty; - public Type[] DataTypesProduced => new[] { typeof(TestNodeUpdateMessage) }; + public Type[] DataTypesProduced => [typeof(TestNodeUpdateMessage)]; public Task CloseTestSessionAsync(CloseTestSessionContext context) => Task.FromResult(new CloseTestSessionResult { IsSuccess = true }); diff --git a/samples/Playground/ServerMode/TestNodeUpdateCollector.cs b/samples/Playground/ServerMode/TestNodeUpdateCollector.cs index 067a4f4410..799aab6ab5 100644 --- a/samples/Playground/ServerMode/TestNodeUpdateCollector.cs +++ b/samples/Playground/ServerMode/TestNodeUpdateCollector.cs @@ -10,7 +10,7 @@ public class TestNodeUpdateCollector private readonly TaskCompletionSource _taskCompletionSource = new(); private readonly Func? _completeCollector; - public ConcurrentBag TestNodeUpdates { get; } = new(); + public ConcurrentBag TestNodeUpdates { get; } = []; public TestNodeUpdateCollector(Func? completeCollectorWhen = null) => _completeCollector = completeCollectorWhen; diff --git a/samples/Playground/ServerMode/v1.0.0/TestingPlatformClient.cs b/samples/Playground/ServerMode/v1.0.0/TestingPlatformClient.cs index 3b40c4d341..5d1a5b917c 100644 --- a/samples/Playground/ServerMode/v1.0.0/TestingPlatformClient.cs +++ b/samples/Playground/ServerMode/v1.0.0/TestingPlatformClient.cs @@ -171,11 +171,9 @@ private sealed class TargetHandler private readonly ConcurrentDictionary _listeners = new(); - private readonly ConcurrentBag _logListeners - = new(); + private readonly ConcurrentBag _logListeners = []; - private readonly ConcurrentBag _telemetryPayloads - = new(); + private readonly ConcurrentBag _telemetryPayloads = []; public void RegisterTelemetryListener(TelemetryCollector listener) => _telemetryPayloads.Add(listener); diff --git a/src/Adapter/MSTest.Engine/Engine/BFSTestNodeVisitor.cs b/src/Adapter/MSTest.Engine/Engine/BFSTestNodeVisitor.cs index 9d3cf88a38..0b83379dc2 100644 --- a/src/Adapter/MSTest.Engine/Engine/BFSTestNodeVisitor.cs +++ b/src/Adapter/MSTest.Engine/Engine/BFSTestNodeVisitor.cs @@ -29,12 +29,12 @@ public BFSTestNodeVisitor(IEnumerable rootTestNodes, ITestExecutionFil _testArgumentsManager = testArgumentsManager; } - internal KeyValuePair>[] DuplicatedNodes { get; private set; } = Array.Empty>>(); + internal KeyValuePair>[] DuplicatedNodes { get; private set; } = []; public async Task VisitAsync(Func onIncludedTestNodeAsync) { // This is case sensitive, and culture insensitive, to keep UIDs unique, and comparable between different system. - Dictionary> testNodesByUid = new(); + Dictionary> testNodesByUid = []; Queue<(TestNode CurrentNode, TestNodeUid? ParentNodeUid, StringBuilder NodeFullPath)> queue = new(); foreach (TestNode node in _rootTestNodes) { @@ -47,7 +47,7 @@ public async Task VisitAsync(Func onIncludedTestNo if (!testNodesByUid.TryGetValue(currentNode.StableUid, out List? testNodes)) { - testNodes = new(); + testNodes = []; testNodesByUid.Add(currentNode.StableUid, testNodes); } @@ -94,7 +94,7 @@ public async Task VisitAsync(Func onIncludedTestNo } } - DuplicatedNodes = testNodesByUid.Where(x => x.Value.Count > 1).ToArray(); + DuplicatedNodes = [.. testNodesByUid.Where(x => x.Value.Count > 1)]; } private static PropertyBag CreatePropertyBagForFilter(IProperty[] properties) diff --git a/src/Adapter/MSTest.Engine/Engine/TestArgumentsManager.cs b/src/Adapter/MSTest.Engine/Engine/TestArgumentsManager.cs index 1003fe27ef..095208b484 100644 --- a/src/Adapter/MSTest.Engine/Engine/TestArgumentsManager.cs +++ b/src/Adapter/MSTest.Engine/Engine/TestArgumentsManager.cs @@ -7,7 +7,7 @@ namespace Microsoft.Testing.Framework; internal sealed class TestArgumentsManager : ITestArgumentsManager { - private readonly Dictionary> _testArgumentsEntryProviders = new(); + private readonly Dictionary> _testArgumentsEntryProviders = []; private bool _isRegistrationFrozen; public void RegisterTestArgumentsEntryProvider( @@ -53,8 +53,8 @@ internal async Task ExpandTestNodeAsync(TestNode currentNode) }; } - HashSet expandedTestNodeUids = new(); - List expandedTestNodes = new(currentNode.Tests); + HashSet expandedTestNodeUids = []; + List expandedTestNodes = [.. currentNode.Tests]; switch (currentNode) { case IParameterizedTestNode parameterizedTestNode: @@ -98,7 +98,7 @@ internal async Task ExpandTestNodeAsync(TestNode currentNode) DisplayName = currentNode.DisplayName, OverriddenEdgeName = currentNode.OverriddenEdgeName, Properties = currentNode.Properties, - Tests = expandedTestNodes.ToArray(), + Tests = [.. expandedTestNodes], }; return expandedNode; diff --git a/src/Adapter/MSTest.Engine/Engine/TestFixtureManager.cs b/src/Adapter/MSTest.Engine/Engine/TestFixtureManager.cs index 4c26895bc4..3553ebc4ef 100644 --- a/src/Adapter/MSTest.Engine/Engine/TestFixtureManager.cs +++ b/src/Adapter/MSTest.Engine/Engine/TestFixtureManager.cs @@ -10,13 +10,13 @@ namespace Microsoft.Testing.Framework; internal sealed class TestFixtureManager : ITestFixtureManager { - private readonly Dictionary>> _fixtureInstancesByFixtureId = new(); - private readonly Dictionary _fixtureIdsUsedByTestNode = new(); + private readonly Dictionary>> _fixtureInstancesByFixtureId = []; + private readonly Dictionary _fixtureIdsUsedByTestNode = []; // We could improve this by doing some optimistic lock but we expect a rather low contention on this. // We use a dictionary as performance improvement because we know that when the registration is complete // we will only read the collection (so no need for concurrency handling). - private readonly Dictionary _fixtureUses = new(); + private readonly Dictionary _fixtureUses = []; private readonly CancellationToken _cancellationToken; private bool _isRegistrationFrozen; private bool _isUsageRegistrationFrozen; @@ -79,7 +79,7 @@ internal void RegisterFixtureUsage(TestNode testNode, string[] fixtureIds) return; } - _fixtureIdsUsedByTestNode.Add(testNode, fixtureIds.Select(x => new FixtureId(x)).ToArray()); + _fixtureIdsUsedByTestNode.Add(testNode, [.. fixtureIds.Select(x => new FixtureId(x))]); foreach (string fixtureId in fixtureIds) { if (!_fixtureUses.TryGetValue(fixtureId, out CountHolder? uses)) diff --git a/src/Adapter/MSTest.Engine/Engine/TestFrameworkEngine.cs b/src/Adapter/MSTest.Engine/Engine/TestFrameworkEngine.cs index f78f930f7a..0855e884df 100644 --- a/src/Adapter/MSTest.Engine/Engine/TestFrameworkEngine.cs +++ b/src/Adapter/MSTest.Engine/Engine/TestFrameworkEngine.cs @@ -38,8 +38,7 @@ public TestFrameworkEngine(TestFrameworkConfiguration testFrameworkConfiguration _configuration = new(configuration); } - public Type[] DataTypesProduced { get; } - = new Type[1] { typeof(TestNodeUpdateMessage) }; + public Type[] DataTypesProduced { get; } = [typeof(TestNodeUpdateMessage)]; public string Uid => _extension.Uid; @@ -62,7 +61,7 @@ public async Task ExecuteRequestAsync(TestExecutionRequest testExecution private async Task ExecuteTestNodeRunAsync(RunTestExecutionRequest request, IMessageBus messageBus, CancellationToken cancellationToken) { - List allRootTestNodes = new(); + List allRootTestNodes = []; TestFixtureManager fixtureManager = new(cancellationToken); TestArgumentsManager argumentsManager = new(); TestSessionContext testSessionContext = new(_configuration, fixtureManager, argumentsManager, request.Session.SessionUid, @@ -96,7 +95,7 @@ await testNodesVisitor.VisitAsync((testNode, parentTestNodeUid) => .OfType() .SingleOrDefault() .UsedFixtureIds - ?? Array.Empty(); + ?? []; fixtureManager.RegisterFixtureUsage(testNode, fixtureIds); return Task.CompletedTask; @@ -142,7 +141,7 @@ Task PublishDataAsync(IData data) private async Task ExecuteTestNodeDiscoveryAsync(DiscoverTestExecutionRequest request, IMessageBus messageBus, CancellationToken cancellationToken) { - List allRootTestNodes = new(); + List allRootTestNodes = []; TestFixtureManager fixtureManager = new(cancellationToken); TestArgumentsManager argumentsManager = new(); TestSessionContext testSessionContext = new(_configuration, fixtureManager, argumentsManager, request.Session.SessionUid, diff --git a/src/Adapter/MSTest.Engine/Engine/ThreadPoolTestNodeRunner.cs b/src/Adapter/MSTest.Engine/Engine/ThreadPoolTestNodeRunner.cs index 3ef4aa070f..f8d32269cc 100644 --- a/src/Adapter/MSTest.Engine/Engine/ThreadPoolTestNodeRunner.cs +++ b/src/Adapter/MSTest.Engine/Engine/ThreadPoolTestNodeRunner.cs @@ -16,7 +16,7 @@ namespace Microsoft.Testing.Framework; internal sealed class ThreadPoolTestNodeRunner : IDisposable { private readonly SemaphoreSlim? _maxParallelTests; - private readonly ConcurrentBag> _runningTests = new(); + private readonly ConcurrentBag> _runningTests = []; private readonly ConcurrentDictionary _runningTestNodeUids = new(); private readonly CountdownEvent _ensureTaskQueuedCountdownEvent = new(1); private readonly Func _publishDataAsync; diff --git a/src/Adapter/MSTest.Engine/Helpers/Result.cs b/src/Adapter/MSTest.Engine/Helpers/Result.cs index 6f6a70af1d..881c9fa4d1 100644 --- a/src/Adapter/MSTest.Engine/Helpers/Result.cs +++ b/src/Adapter/MSTest.Engine/Helpers/Result.cs @@ -5,7 +5,7 @@ namespace Microsoft.Testing.Framework; internal sealed class Result { - private readonly List _reasons = new(); + private readonly List _reasons = []; private Result() { diff --git a/src/Adapter/MSTest.Engine/TestFramework/TestFramework.cs b/src/Adapter/MSTest.Engine/TestFramework/TestFramework.cs index 1fb61c5f9d..e43320b5bd 100644 --- a/src/Adapter/MSTest.Engine/TestFramework/TestFramework.cs +++ b/src/Adapter/MSTest.Engine/TestFramework/TestFramework.cs @@ -23,8 +23,8 @@ internal sealed class TestFramework : IDisposable, ITestFramework private readonly TestingFrameworkExtension _extension; private readonly CountdownEvent _incomingRequestCounter = new(1); private readonly TestFrameworkEngine _engine; - private readonly List _sessionWarningMessages = new(); - private readonly List _sessionErrorMessages = new(); + private readonly List _sessionWarningMessages = []; + private readonly List _sessionErrorMessages = []; private SessionUid? _sessionId; public TestFramework(TestFrameworkConfiguration testFrameworkConfiguration, ITestNodesBuilder[] testNodesBuilders, TestingFrameworkExtension extension, diff --git a/src/Adapter/MSTest.Engine/TestFramework/TestFrameworkCapabilities.cs b/src/Adapter/MSTest.Engine/TestFramework/TestFrameworkCapabilities.cs index 868a1e63db..434251ea82 100644 --- a/src/Adapter/MSTest.Engine/TestFramework/TestFrameworkCapabilities.cs +++ b/src/Adapter/MSTest.Engine/TestFramework/TestFrameworkCapabilities.cs @@ -18,7 +18,7 @@ public TestFrameworkCapabilities(ITestNodesBuilder[] testNodesBuilders, IBannerM } public IReadOnlyCollection Capabilities - => new[] { new TestFrameworkCapabilitiesSet(_testNodesBuilders), _bannerMessageOwnerCapability }; + => [new TestFrameworkCapabilitiesSet(_testNodesBuilders), _bannerMessageOwnerCapability]; } internal sealed class TestFrameworkCapabilitiesSet : diff --git a/src/Adapter/MSTest.Engine/TestNodes/FactoryTestNodesBuilder.cs b/src/Adapter/MSTest.Engine/TestNodes/FactoryTestNodesBuilder.cs index 8f2b9bc3b6..eaad6454de 100644 --- a/src/Adapter/MSTest.Engine/TestNodes/FactoryTestNodesBuilder.cs +++ b/src/Adapter/MSTest.Engine/TestNodes/FactoryTestNodesBuilder.cs @@ -15,8 +15,7 @@ public FactoryTestNodesBuilder(Func testNodesFactory) public bool IsSupportingTrxProperties { get; } - IReadOnlyCollection ICapabilities.Capabilities - => Array.Empty(); + IReadOnlyCollection ICapabilities.Capabilities => []; public Task BuildAsync(ITestSessionContext _) => Task.FromResult(_testNodesFactory()); } diff --git a/src/Adapter/MSTest.Engine/TestNodes/FrameworkTestNodeProperties.cs b/src/Adapter/MSTest.Engine/TestNodes/FrameworkTestNodeProperties.cs index 718e6b8b40..3c61f91f6c 100644 --- a/src/Adapter/MSTest.Engine/TestNodes/FrameworkTestNodeProperties.cs +++ b/src/Adapter/MSTest.Engine/TestNodes/FrameworkTestNodeProperties.cs @@ -9,5 +9,5 @@ internal readonly struct FrameworkEngineMetadataProperty() : IProperty { public bool PreventArgumentsExpansion { get; init; } - public string[] UsedFixtureIds { get; init; } = Array.Empty(); + public string[] UsedFixtureIds { get; init; } = []; } diff --git a/src/Adapter/MSTest.Engine/TestNodes/TestNode.cs b/src/Adapter/MSTest.Engine/TestNodes/TestNode.cs index 58f015c055..8119973fde 100644 --- a/src/Adapter/MSTest.Engine/TestNodes/TestNode.cs +++ b/src/Adapter/MSTest.Engine/TestNodes/TestNode.cs @@ -17,7 +17,7 @@ public class TestNode /// public string? OverriddenEdgeName { get; init; } - public IProperty[] Properties { get; init; } = Array.Empty(); + public IProperty[] Properties { get; init; } = []; - public TestNode[] Tests { get; init; } = Array.Empty(); + public TestNode[] Tests { get; init; } = []; } diff --git a/src/Adapter/MSTest.TestAdapter/Discovery/AssemblyEnumerator.cs b/src/Adapter/MSTest.TestAdapter/Discovery/AssemblyEnumerator.cs index 6dfe08c60b..34c6e1b21a 100644 --- a/src/Adapter/MSTest.TestAdapter/Discovery/AssemblyEnumerator.cs +++ b/src/Adapter/MSTest.TestAdapter/Discovery/AssemblyEnumerator.cs @@ -65,7 +65,7 @@ public AssemblyEnumerator(MSTestSettings settings) => /// A collection of Test Elements. internal AssemblyEnumerationResult EnumerateAssembly(string assemblyFileName) { - List warnings = new(); + List warnings = []; DebugEx.Assert(!StringEx.IsNullOrWhiteSpace(assemblyFileName), "Invalid assembly file name."); var tests = new List(); // Contains list of assembly/class names for which we have already added fixture tests. @@ -350,7 +350,7 @@ private static bool TryUnfoldITestDataSources(UnitTestElement test, DiscoveryTes IEnumerable testDataSources = ReflectHelper.Instance.GetAttributes(testMethodInfo.MethodInfo, inherit: false).OfType(); // We need to use a temporary list to avoid adding tests to the main list if we fail to expand any data source. - List tempListOfTests = new(); + List tempListOfTests = []; try { diff --git a/src/Adapter/MSTest.TestAdapter/Discovery/AssemblyEnumeratorWrapper.cs b/src/Adapter/MSTest.TestAdapter/Discovery/AssemblyEnumeratorWrapper.cs index 7e14d56e6b..5633389cbd 100644 --- a/src/Adapter/MSTest.TestAdapter/Discovery/AssemblyEnumeratorWrapper.cs +++ b/src/Adapter/MSTest.TestAdapter/Discovery/AssemblyEnumeratorWrapper.cs @@ -26,7 +26,7 @@ internal sealed class AssemblyEnumeratorWrapper /// A collection of test elements. internal ICollection? GetTests(string? assemblyFileName, IRunSettings? runSettings, out List warnings) { - warnings = new List(); + warnings = []; if (StringEx.IsNullOrEmpty(assemblyFileName)) { diff --git a/src/Adapter/MSTest.TestAdapter/Discovery/TypeEnumerator.cs b/src/Adapter/MSTest.TestAdapter/Discovery/TypeEnumerator.cs index 52c8becccc..78342edf83 100644 --- a/src/Adapter/MSTest.TestAdapter/Discovery/TypeEnumerator.cs +++ b/src/Adapter/MSTest.TestAdapter/Discovery/TypeEnumerator.cs @@ -110,11 +110,10 @@ internal List GetTests(List warnings) currentType = currentType.BaseType; } - return tests.GroupBy( + return [.. tests.GroupBy( t => t.TestMethod.Name, (_, elements) => - elements.OrderBy(t => inheritanceDepths[t.TestMethod.DeclaringClassFullName ?? t.TestMethod.FullClassName]).First()) - .ToList(); + elements.OrderBy(t => inheritanceDepths[t.TestMethod.DeclaringClassFullName ?? t.TestMethod.FullClassName]).First())]; } /// @@ -153,7 +152,7 @@ internal UnitTestElement GetTestFromMethod(MethodInfo method, bool isDeclaredInT DoNotParallelize = _reflectHelper.IsDoNotParallelizeSet(method, _type), Priority = _reflectHelper.GetPriority(method), DeploymentItems = PlatformServiceProvider.Instance.TestDeployment.GetDeploymentItems(method, _type, warnings), - Traits = _reflectHelper.GetTestPropertiesAsTraits(method).ToArray(), + Traits = [.. _reflectHelper.GetTestPropertiesAsTraits(method)], }; Attribute[] attributes = _reflectHelper.GetCustomAttributesCached(method, inherit: true); @@ -184,7 +183,7 @@ internal UnitTestElement GetTestFromMethod(MethodInfo method, bool isDeclaredInT IEnumerable workItemAttributes = attributes.OfType(); if (workItemAttributes.Any()) { - testElement.WorkItemIds = workItemAttributes.Select(x => x.Id.ToString(CultureInfo.InvariantCulture)).ToArray(); + testElement.WorkItemIds = [.. workItemAttributes.Select(x => x.Id.ToString(CultureInfo.InvariantCulture))]; } // In production, we always have a TestMethod attribute because GetTestFromMethod is called under IsValidTestMethod diff --git a/src/Adapter/MSTest.TestAdapter/Execution/TestCaseDiscoverySink.cs b/src/Adapter/MSTest.TestAdapter/Execution/TestCaseDiscoverySink.cs index 2315b67113..8ae3f43e28 100644 --- a/src/Adapter/MSTest.TestAdapter/Execution/TestCaseDiscoverySink.cs +++ b/src/Adapter/MSTest.TestAdapter/Execution/TestCaseDiscoverySink.cs @@ -14,7 +14,7 @@ internal sealed class TestCaseDiscoverySink : ITestCaseDiscoverySink /// /// Gets the tests. /// - public ICollection Tests { get; } = new List(); + public ICollection Tests { get; } = []; /// /// Sends the test case. diff --git a/src/Adapter/MSTest.TestAdapter/Execution/TestClassInfo.cs b/src/Adapter/MSTest.TestAdapter/Execution/TestClassInfo.cs index dc4ae10a17..ba55a398c4 100644 --- a/src/Adapter/MSTest.TestAdapter/Execution/TestClassInfo.cs +++ b/src/Adapter/MSTest.TestAdapter/Execution/TestClassInfo.cs @@ -102,25 +102,25 @@ internal set /// Gets the timeout for the class initialize methods. /// We can use a dictionary because the MethodInfo is unique in an inheritance hierarchy. /// - internal Dictionary ClassInitializeMethodTimeoutMilliseconds { get; } = new(); + internal Dictionary ClassInitializeMethodTimeoutMilliseconds { get; } = []; /// /// Gets the timeout for the class cleanup methods. /// We can use a dictionary because the MethodInfo is unique in an inheritance hierarchy. /// - internal Dictionary ClassCleanupMethodTimeoutMilliseconds { get; } = new(); + internal Dictionary ClassCleanupMethodTimeoutMilliseconds { get; } = []; /// /// Gets the timeout for the test initialize methods. /// We can use a dictionary because the MethodInfo is unique in an inheritance hierarchy. /// - internal Dictionary TestInitializeMethodTimeoutMilliseconds { get; } = new(); + internal Dictionary TestInitializeMethodTimeoutMilliseconds { get; } = []; /// /// Gets the timeout for the test cleanup methods. /// We can use a dictionary because the MethodInfo is unique in an inheritance hierarchy. /// - internal Dictionary TestCleanupMethodTimeoutMilliseconds { get; } = new(); + internal Dictionary TestCleanupMethodTimeoutMilliseconds { get; } = []; /// /// Gets a value indicating whether class initialize has executed. @@ -138,9 +138,9 @@ internal set [Obsolete("API will be dropped in v4")] public Stack BaseClassCleanupMethodsStack { get; } = new(); - internal List BaseClassInitMethods { get; } = new(); + internal List BaseClassInitMethods { get; } = []; - internal List BaseClassCleanupMethods { get; } = new(); + internal List BaseClassCleanupMethods { get; } = []; /// /// Gets the exception thrown during method invocation. diff --git a/src/Adapter/MSTest.TestAdapter/Execution/TestExecutionManager.cs b/src/Adapter/MSTest.TestAdapter/Execution/TestExecutionManager.cs index bd5dde9130..5fe5f07078 100644 --- a/src/Adapter/MSTest.TestAdapter/Execution/TestExecutionManager.cs +++ b/src/Adapter/MSTest.TestAdapter/Execution/TestExecutionManager.cs @@ -389,8 +389,8 @@ private async Task ExecuteTestsInSourceAsync(IEnumerable tests, IRunCo int parallelWorkers = sourceSettings.Workers; ExecutionScope parallelScope = sourceSettings.Scope; - TestCase[] testsToRun = tests.Where(t => MatchTestFilter(filterExpression, t, _testMethodFilter)).ToArray(); - UnitTestElement[] unitTestElements = testsToRun.Select(e => e.ToUnitTestElement(source)).ToArray(); + TestCase[] testsToRun = [.. tests.Where(t => MatchTestFilter(filterExpression, t, _testMethodFilter))]; + UnitTestElement[] unitTestElements = [.. testsToRun.Select(e => e.ToUnitTestElement(source))]; // Create an instance of a type defined in adapter so that adapter gets loaded in the child app domain var testRunner = (UnitTestRunner)isolationHost.CreateInstanceForType( typeof(UnitTestRunner), diff --git a/src/Adapter/MSTest.TestAdapter/Execution/TestMethodInfo.cs b/src/Adapter/MSTest.TestAdapter/Execution/TestMethodInfo.cs index b736e57bd9..7429314707 100644 --- a/src/Adapter/MSTest.TestAdapter/Execution/TestMethodInfo.cs +++ b/src/Adapter/MSTest.TestAdapter/Execution/TestMethodInfo.cs @@ -121,7 +121,7 @@ internal TestMethodInfo( /// Whether or not getting the attributes that are inherited. /// An array of the attributes. public Attribute[]? GetAllAttributes(bool inherit) - => ReflectHelper.Instance.GetAttributes(TestMethod, inherit).ToArray(); + => [.. ReflectHelper.Instance.GetAttributes(TestMethod, inherit)]; /// /// Gets all attributes of the test method. @@ -131,7 +131,7 @@ internal TestMethodInfo( /// An array of the attributes. public TAttributeType[] GetAttributes(bool inherit) where TAttributeType : Attribute - => ReflectHelper.Instance.GetAttributes(TestMethod, inherit).ToArray(); + => [.. ReflectHelper.Instance.GetAttributes(TestMethod, inherit)]; /// public virtual TestResult Invoke(object?[]? arguments) diff --git a/src/Adapter/MSTest.TestAdapter/Execution/TestMethodRunner.cs b/src/Adapter/MSTest.TestAdapter/Execution/TestMethodRunner.cs index 15240f0c41..1d04d00e3f 100644 --- a/src/Adapter/MSTest.TestAdapter/Execution/TestMethodRunner.cs +++ b/src/Adapter/MSTest.TestAdapter/Execution/TestMethodRunner.cs @@ -93,7 +93,7 @@ internal async Task ExecuteAsync(string initializationLogs, string PlatformServiceProvider.Instance.AdapterTraceLogger.LogError(ex.ToString()); } - return results ?? Array.Empty(); + return results ?? []; } else { @@ -245,7 +245,7 @@ internal async Task RunTestMethodAsync() results.Add(emptyResult); } - return results.ToArray(); + return [.. results]; } private async Task TryExecuteDataSourceBasedTestsAsync(List results) diff --git a/src/Adapter/MSTest.TestAdapter/Execution/TestRunCancellationToken.cs b/src/Adapter/MSTest.TestAdapter/Execution/TestRunCancellationToken.cs index fbd7b24255..51516465c7 100644 --- a/src/Adapter/MSTest.TestAdapter/Execution/TestRunCancellationToken.cs +++ b/src/Adapter/MSTest.TestAdapter/Execution/TestRunCancellationToken.cs @@ -17,7 +17,7 @@ public class TestRunCancellationToken /// Callbacks to be invoked when canceled. /// Needs to be a concurrent collection, see https://github.com/microsoft/testfx/issues/3953. /// - private readonly ConcurrentBag<(Action, object?)> _registeredCallbacks = new(); + private readonly ConcurrentBag<(Action, object?)> _registeredCallbacks = []; /// /// Gets a value indicating whether the test run is canceled. diff --git a/src/Adapter/MSTest.TestAdapter/Execution/TypeCache.cs b/src/Adapter/MSTest.TestAdapter/Execution/TypeCache.cs index bf6100502f..bf00aec70e 100644 --- a/src/Adapter/MSTest.TestAdapter/Execution/TypeCache.cs +++ b/src/Adapter/MSTest.TestAdapter/Execution/TypeCache.cs @@ -736,7 +736,7 @@ private MethodInfo GetMethodInfoForTestMethod(TestMethod testMethod, TestClassIn } else if (methodBase != null) { - Type[] parameters = methodBase.GetParameters().Select(i => i.ParameterType).ToArray(); + Type[] parameters = [.. methodBase.GetParameters().Select(i => i.ParameterType)]; // TODO: Should we pass true for includeNonPublic? testMethodInfo = PlatformServiceProvider.Instance.ReflectionOperations.GetRuntimeMethod(methodBase.DeclaringType!, methodBase.Name, parameters, includeNonPublic: false); } diff --git a/src/Adapter/MSTest.TestAdapter/Extensions/MethodInfoExtensions.cs b/src/Adapter/MSTest.TestAdapter/Extensions/MethodInfoExtensions.cs index 940f96fb55..69b9818219 100644 --- a/src/Adapter/MSTest.TestAdapter/Extensions/MethodInfoExtensions.cs +++ b/src/Adapter/MSTest.TestAdapter/Extensions/MethodInfoExtensions.cs @@ -166,9 +166,9 @@ internal static bool IsValidReturnType(this MethodInfo method, ReflectHelper? re methodInfo.DeclaringType!.FullName, methodInfo.Name, methodParametersLengthOrZero, - string.Join(", ", methodParameters?.Select(p => p.ParameterType.Name) ?? Array.Empty()), + string.Join(", ", methodParameters?.Select(p => p.ParameterType.Name) ?? []), argumentsLengthOrZero, - string.Join(", ", arguments?.Select(a => a?.GetType().Name ?? "null") ?? Array.Empty())), ex); + string.Join(", ", arguments?.Select(a => a?.GetType().Name ?? "null") ?? [])), ex); } } diff --git a/src/Adapter/MSTest.TestAdapter/Extensions/TestCaseExtensions.cs b/src/Adapter/MSTest.TestAdapter/Extensions/TestCaseExtensions.cs index 35f2d18207..44a8247390 100644 --- a/src/Adapter/MSTest.TestAdapter/Extensions/TestCaseExtensions.cs +++ b/src/Adapter/MSTest.TestAdapter/Extensions/TestCaseExtensions.cs @@ -102,7 +102,7 @@ internal static UnitTestElement ToUnitTestElement(this TestCase testCase, string if (testCase.Traits.Any()) { - testElement.Traits = testCase.Traits.ToArray(); + testElement.Traits = [.. testCase.Traits]; } string? cssIteration = testCase.GetPropertyValue(Constants.CssIterationProperty, null); diff --git a/src/Adapter/MSTest.TestAdapter/Helpers/ReflectHelper.cs b/src/Adapter/MSTest.TestAdapter/Helpers/ReflectHelper.cs index 7eff98c5ff..40f114585f 100644 --- a/src/Adapter/MSTest.TestAdapter/Helpers/ReflectHelper.cs +++ b/src/Adapter/MSTest.TestAdapter/Helpers/ReflectHelper.cs @@ -125,7 +125,7 @@ internal virtual bool IsMethodDeclaredInSameAssemblyAsType(MethodInfo method, Ty IEnumerable typeCategories = GetAttributes(owningType, inherit: true); IEnumerable assemblyCategories = GetAttributes(owningType.Assembly, inherit: true); - return methodCategories.Concat(typeCategories).Concat(assemblyCategories).SelectMany(c => c.TestCategories).ToArray(); + return [.. methodCategories.Concat(typeCategories).Concat(assemblyCategories).SelectMany(c => c.TestCategories)]; } /// @@ -311,7 +311,7 @@ static Attribute[] GetAttributes(ICustomAttributeProvider attributeProvider, boo try { object[]? attributes = NotCachedReflectionAccessor.GetCustomAttributesNotCached(attributeProvider, inherit); - return attributes is null ? [] : attributes as Attribute[] ?? attributes.Cast().ToArray(); + return attributes is null ? [] : attributes as Attribute[] ?? [.. attributes.Cast()]; } catch (Exception ex) { diff --git a/src/Adapter/MSTest.TestAdapter/Helpers/TestDataSourceHelpers.cs b/src/Adapter/MSTest.TestAdapter/Helpers/TestDataSourceHelpers.cs index ddac9f6ded..db7144303b 100644 --- a/src/Adapter/MSTest.TestAdapter/Helpers/TestDataSourceHelpers.cs +++ b/src/Adapter/MSTest.TestAdapter/Helpers/TestDataSourceHelpers.cs @@ -44,7 +44,7 @@ public static bool TryHandleTupleDataSource(object? data, ParameterInfo[] testMe if (testMethodParameters.Length == 1 && data?.GetType().IsAssignableTo(testMethodParameters[0].ParameterType) == true) { - array = Array.Empty(); + array = []; return false; } @@ -103,7 +103,7 @@ static void ProcessTuple(object data, object?[] array, int startingIndex) } #endif - array = Array.Empty(); + array = []; return false; } diff --git a/src/Adapter/MSTest.TestAdapter/ObjectModel/UnitTestElement.cs b/src/Adapter/MSTest.TestAdapter/ObjectModel/UnitTestElement.cs index 54bcc8fb98..5d5055f537 100644 --- a/src/Adapter/MSTest.TestAdapter/ObjectModel/UnitTestElement.cs +++ b/src/Adapter/MSTest.TestAdapter/ObjectModel/UnitTestElement.cs @@ -126,7 +126,7 @@ internal TestCase ToTestCase() IReadOnlyCollection hierarchy = TestMethod.Hierarchy; if (hierarchy is { Count: > 0 }) { - testCase.SetHierarchy(hierarchy.ToArray()); + testCase.SetHierarchy([.. hierarchy]); } // Set declaring type if present so the correct method info can be retrieved diff --git a/src/Adapter/MSTestAdapter.PlatformServices/AssemblyResolver.cs b/src/Adapter/MSTestAdapter.PlatformServices/AssemblyResolver.cs index 1ac452a754..39ee56ac55 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/AssemblyResolver.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/AssemblyResolver.cs @@ -408,7 +408,7 @@ protected virtual return null; } - s_currentlyLoading ??= new List(); + s_currentlyLoading ??= []; s_currentlyLoading.Add(assemblyPath); // Push isPushed = true; } diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Data/TestDataConnectionSql.cs b/src/Adapter/MSTestAdapter.PlatformServices/Data/TestDataConnectionSql.cs index f2af39ca11..90c377b952 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Data/TestDataConnectionSql.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Data/TestDataConnectionSql.cs @@ -282,7 +282,7 @@ public string PrepareNameForSql(string tableName) return null; } - return parts.ToArray(); + return [.. parts]; } } diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Deployment/AssemblyLoadWorker.cs b/src/Adapter/MSTestAdapter.PlatformServices/Deployment/AssemblyLoadWorker.cs index 323487a79f..ac9d21964f 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Deployment/AssemblyLoadWorker.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Deployment/AssemblyLoadWorker.cs @@ -41,7 +41,7 @@ public IReadOnlyCollection GetFullPathToDependentAssemblies(string assem { DebugEx.Assert(!StringEx.IsNullOrEmpty(assemblyPath), "assemblyPath"); - warnings = new List(); + warnings = []; Assembly? assembly; try { diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Services/ReflectionOperations.cs b/src/Adapter/MSTestAdapter.PlatformServices/Services/ReflectionOperations.cs index 2e37b5afba..b1bf6dcfbb 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Services/ReflectionOperations.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Services/ReflectionOperations.cs @@ -27,7 +27,7 @@ public class ReflectionOperations : IReflectionOperations [return: NotNullIfNotNull(nameof(memberInfo))] public object[]? GetCustomAttributes(MemberInfo memberInfo, bool inherit) #if NETFRAMEWORK - => ReflectionUtility.GetCustomAttributes(memberInfo, inherit).ToArray(); + => [.. ReflectionUtility.GetCustomAttributes(memberInfo, inherit)]; #else { object[] attributes = memberInfo.GetCustomAttributes(typeof(Attribute), inherit); @@ -51,7 +51,7 @@ public class ReflectionOperations : IReflectionOperations [return: NotNullIfNotNull(nameof(memberInfo))] public object[]? GetCustomAttributes(MemberInfo memberInfo, Type type, bool inherit) => #if NETFRAMEWORK - ReflectionUtility.GetCustomAttributes(memberInfo, type, inherit).ToArray(); + [.. ReflectionUtility.GetCustomAttributes(memberInfo, type, inherit)]; #else memberInfo.GetCustomAttributes(type, inherit); #endif diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Services/TestSource.cs b/src/Adapter/MSTestAdapter.PlatformServices/Services/TestSource.cs index c0cbeab9cd..de06dce3fb 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Services/TestSource.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Services/TestSource.cs @@ -33,16 +33,16 @@ public class TestSource : ITestSource // Constants.DllExtension }; - private static readonly HashSet SystemAssemblies = new(new string[] - { + private static readonly HashSet SystemAssemblies = + [ "MICROSOFT.CSHARP.DLL", "MICROSOFT.VISUALBASIC.DLL", "CLRCOMPRESSION.DLL", - }); + ]; // Well known platform assemblies. - private static readonly HashSet PlatformAssemblies = new(new string[] - { + private static readonly HashSet PlatformAssemblies = + [ "MICROSOFT.VISUALSTUDIO.TESTPLATFORM.TESTFRAMEWORK.DLL", "MICROSOFT.VISUALSTUDIO.TESTPLATFORM.TESTFRAMEWORK.EXTENSIONS.CORE.DLL", "MICROSOFT.VISUALSTUDIO.TESTPLATFORM.CORE.DLL", @@ -54,7 +54,7 @@ public class TestSource : ITestSource "VSTEST_EXECUTIONENGINE_PLATFORMBRIDGE.DLL", "VSTEST_EXECUTIONENGINE_PLATFORMBRIDGE.WINMD", "VSTEST.EXECUTIONENGINE.WINDOWSPHONE.DLL", - }); + ]; #endif /// diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Services/ThreadSafeStringWriter.cs b/src/Adapter/MSTestAdapter.PlatformServices/Services/ThreadSafeStringWriter.cs index 821e25829d..95a4de695d 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Services/ThreadSafeStringWriter.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Services/ThreadSafeStringWriter.cs @@ -183,7 +183,7 @@ internal static void CleanState() { lock (StaticLockObject) { - State.Value = new(); + State.Value = []; } } diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Utilities/DeploymentItemUtility.cs b/src/Adapter/MSTestAdapter.PlatformServices/Utilities/DeploymentItemUtility.cs index bd8c0d78e6..e274bbf7c3 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Utilities/DeploymentItemUtility.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Utilities/DeploymentItemUtility.cs @@ -212,7 +212,7 @@ private static List GetDeploymentItems(IEnumerable deploymentIte return deploymentItemList1; } - IList result = new List(deploymentItemList1); + IList result = [.. deploymentItemList1]; foreach (DeploymentItem item in deploymentItemList2) { @@ -247,7 +247,7 @@ private static List GetDeploymentItems(IEnumerable deploymentIte } } - return result.ToArray(); + return [.. result]; } private static IList? FromKeyValuePairs(KeyValuePair[] deploymentItemsData) @@ -257,7 +257,7 @@ private static List GetDeploymentItems(IEnumerable deploymentIte return null; } - IList result = new List(); + IList result = []; foreach ((string? key, string? value) in deploymentItemsData) { diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Utilities/DeploymentUtilityBase.cs b/src/Adapter/MSTestAdapter.PlatformServices/Utilities/DeploymentUtilityBase.cs index 21de3f1a79..7b2f77a9a6 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Utilities/DeploymentUtilityBase.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Utilities/DeploymentUtilityBase.cs @@ -407,7 +407,7 @@ private bool Deploy(string source, IRunContext? runContext, ITestExecutionRecord // Do the deployment. EqtTrace.InfoIf(EqtTrace.IsInfoEnabled, "MSTestExecutor: Using deployment directory {0} for source {1}.", runDirectories.OutDirectory, source); - IEnumerable warnings = Deploy(new List(deploymentItems), source, runDirectories.OutDirectory, GetTestResultsDirectory(runContext)); + IEnumerable warnings = Deploy([.. deploymentItems], source, runDirectories.OutDirectory, GetTestResultsDirectory(runContext)); // Log warnings LogWarnings(testExecutionRecorder, warnings); diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Utilities/ReflectionUtility.cs b/src/Adapter/MSTestAdapter.PlatformServices/Utilities/ReflectionUtility.cs index b9fe555b32..1ef57c713c 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Utilities/ReflectionUtility.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Utilities/ReflectionUtility.cs @@ -126,7 +126,7 @@ internal static List GetCustomAttributes(Assembly assembly, Type type { if (!assembly.ReflectionOnly) { - return assembly.GetCustomAttributes(type).ToList(); + return [.. assembly.GetCustomAttributes(type)]; } List customAttributes = [.. CustomAttributeData.GetCustomAttributes(assembly)]; @@ -195,8 +195,8 @@ internal static List GetCustomAttributes(Assembly assembly, Type type constructorArguments.Add(list.ToArray(parameterType.GetElementType())); } - ConstructorInfo constructor = attributeType.GetConstructor(constructorParameters.ToArray()); - attribute = constructor.Invoke(constructorArguments.ToArray()); + ConstructorInfo constructor = attributeType.GetConstructor([.. constructorParameters]); + attribute = constructor.Invoke([.. constructorArguments]); foreach (CustomAttributeNamedArgument namedArgument in attributeData.NamedArguments) { diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/PreferConstructorOverTestInitializeFixer.cs b/src/Analyzers/MSTest.Analyzers.CodeFixes/PreferConstructorOverTestInitializeFixer.cs index efeecd6dbd..b2005cc8c6 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/PreferConstructorOverTestInitializeFixer.cs +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/PreferConstructorOverTestInitializeFixer.cs @@ -81,7 +81,7 @@ private static async Task ReplaceTestInitializeWithConstructorAsync(Do // If a constructor already exists, append the body of the TestInitialize method to it if (existingConstructor.Body != null) { - BlockSyntax newConstructorBody = existingConstructor.Body.AddStatements(testInitializeStatements ?? Array.Empty()); + BlockSyntax newConstructorBody = existingConstructor.Body.AddStatements(testInitializeStatements ?? []); newConstructor = existingConstructor.WithBody(newConstructorBody); } else diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/PreferDisposeOverTestCleanupFixer.cs b/src/Analyzers/MSTest.Analyzers.CodeFixes/PreferDisposeOverTestCleanupFixer.cs index 9911ee7287..0f47efc748 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/PreferDisposeOverTestCleanupFixer.cs +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/PreferDisposeOverTestCleanupFixer.cs @@ -98,7 +98,7 @@ private static async Task AddDisposeAndBaseClassAsync( MethodDeclarationSyntax newDisposeMethod; if (existingDisposeMethod.Body != null) { - BlockSyntax newDisposeBody = existingDisposeMethod.Body.AddStatements(cleanupStatements ?? Array.Empty()); + BlockSyntax newDisposeBody = existingDisposeMethod.Body.AddStatements(cleanupStatements ?? []); newDisposeMethod = existingDisposeMethod.WithBody(newDisposeBody); } else diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/PreferTestInitializeOverConstructorFixer.cs b/src/Analyzers/MSTest.Analyzers.CodeFixes/PreferTestInitializeOverConstructorFixer.cs index 9ea85da311..5961aa1747 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/PreferTestInitializeOverConstructorFixer.cs +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/PreferTestInitializeOverConstructorFixer.cs @@ -86,7 +86,7 @@ private static async Task ReplaceConstructorWithTestInitializeAsync(Do MethodDeclarationSyntax newTestInitialize; if (existingTestInitialize.Body != null) { - BlockSyntax newTestInitializeBody = existingTestInitialize.Body.AddStatements(constructorStatements ?? Array.Empty()); + BlockSyntax newTestInitializeBody = existingTestInitialize.Body.AddStatements(constructorStatements ?? []); newTestInitialize = existingTestInitialize.WithBody(newTestInitializeBody); } else diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/TestContextShouldBeValidFixer.cs b/src/Analyzers/MSTest.Analyzers.CodeFixes/TestContextShouldBeValidFixer.cs index c15765fa46..a504d42fb0 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/TestContextShouldBeValidFixer.cs +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/TestContextShouldBeValidFixer.cs @@ -103,7 +103,7 @@ private static async Task FixMemberDeclarationAsync(Document document, AccessorDeclarationSyntax setAccessor = accessors.FirstOrDefault(a => a.Kind() == SyntaxKind.SetAccessorDeclaration) ?? SyntaxFactory.AccessorDeclaration(SyntaxKind.SetAccessorDeclaration).WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)); - newMemberDeclaration = propertyDeclaration.WithAccessorList(SyntaxFactory.AccessorList(SyntaxFactory.List(new[] { getAccessor, setAccessor }))); + newMemberDeclaration = propertyDeclaration.WithAccessorList(SyntaxFactory.AccessorList(SyntaxFactory.List([getAccessor, setAccessor]))); } // Create a new member declaration with the updated modifiers. @@ -121,13 +121,13 @@ private static PropertyDeclarationSyntax ConvertFieldToProperty(FieldDeclaration PropertyDeclarationSyntax propertyDeclaration = SyntaxFactory.PropertyDeclaration(type, TestContextShouldBeValidAnalyzer.TestContextPropertyName) .WithModifiers(SyntaxFactory.TokenList(fieldDeclaration.Modifiers)) .WithAccessorList(SyntaxFactory.AccessorList( - SyntaxFactory.List(new[] - { + SyntaxFactory.List( + [ SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration) .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)), SyntaxFactory.AccessorDeclaration(SyntaxKind.SetAccessorDeclaration) - .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)), - }))); + .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)) + ]))); return propertyDeclaration; } diff --git a/src/Analyzers/MSTest.Analyzers/DataRowShouldBeValidAnalyzer.cs b/src/Analyzers/MSTest.Analyzers/DataRowShouldBeValidAnalyzer.cs index 1742bf29c9..4e903b6a2b 100644 --- a/src/Analyzers/MSTest.Analyzers/DataRowShouldBeValidAnalyzer.cs +++ b/src/Analyzers/MSTest.Analyzers/DataRowShouldBeValidAnalyzer.cs @@ -91,7 +91,7 @@ private static void AnalyzeSymbol( var methodSymbol = (IMethodSymbol)context.Symbol; bool isTestMethod = false; - List dataRowAttributes = new(); + List dataRowAttributes = []; foreach (AttributeData methodAttribute in methodSymbol.GetAttributes()) { // Current method should be a test method or should inherit from the TestMethod attribute. @@ -184,7 +184,7 @@ private static void AnalyzeAttribute(SymbolAnalysisContext context, AttributeDat AnalyzeGenericMethod(context, dataRowSyntax, methodSymbol, constructorArguments); // Check constructor argument types match method parameter types. - List<(int ConstructorArgumentIndex, int MethodParameterIndex)> typeMismatchIndices = new(); + List<(int ConstructorArgumentIndex, int MethodParameterIndex)> typeMismatchIndices = []; for (int currentArgumentIndex = 0; currentArgumentIndex < constructorArguments.Length; currentArgumentIndex++) { // Null is considered as default for non-nullable types. diff --git a/src/Analyzers/MSTest.Analyzers/DoNotUseShadowingAnalyzer.cs b/src/Analyzers/MSTest.Analyzers/DoNotUseShadowingAnalyzer.cs index e326e9cff5..99f2fca090 100644 --- a/src/Analyzers/MSTest.Analyzers/DoNotUseShadowingAnalyzer.cs +++ b/src/Analyzers/MSTest.Analyzers/DoNotUseShadowingAnalyzer.cs @@ -64,7 +64,7 @@ private static void AnalyzeSymbol(SymbolAnalysisContext context, INamedTypeSymbo Dictionary> membersByName = GetBaseMembers(namedTypeSymbol); foreach (ISymbol member in namedTypeSymbol.GetMembers()) { - foreach (ISymbol baseMember in membersByName.GetValueOrDefault(member.Name, new List())) + foreach (ISymbol baseMember in membersByName.GetValueOrDefault(member.Name, [])) { // Check if the member is shadowing a base class member if (IsMemberShadowing(member, baseMember)) @@ -77,7 +77,7 @@ private static void AnalyzeSymbol(SymbolAnalysisContext context, INamedTypeSymbo private static Dictionary> GetBaseMembers(INamedTypeSymbol namedTypeSymbol) { - Dictionary> membersByName = new(); + Dictionary> membersByName = []; INamedTypeSymbol? currentType = namedTypeSymbol.BaseType; while (currentType is not null) { @@ -91,7 +91,7 @@ private static Dictionary> GetBaseMembers(INamedTypeSymbol if (!membersByName.TryGetValue(member.Name, out List? members)) { - members = new List(); + members = []; membersByName[member.Name] = members; } diff --git a/src/Analyzers/MSTest.Analyzers/Helpers/DiagnosticDescriptorHelper.cs b/src/Analyzers/MSTest.Analyzers/Helpers/DiagnosticDescriptorHelper.cs index c719ef7aae..9e09a07c97 100644 --- a/src/Analyzers/MSTest.Analyzers/Helpers/DiagnosticDescriptorHelper.cs +++ b/src/Analyzers/MSTest.Analyzers/Helpers/DiagnosticDescriptorHelper.cs @@ -31,7 +31,7 @@ public static DiagnosticDescriptor Create( public static DiagnosticDescriptor WithMessage(this DiagnosticDescriptor diagnosticDescriptor, LocalizableResourceString messageFormat) => new(diagnosticDescriptor.Id, diagnosticDescriptor.Title, messageFormat, diagnosticDescriptor.Category, diagnosticDescriptor.DefaultSeverity, - diagnosticDescriptor.IsEnabledByDefault, diagnosticDescriptor.Description, diagnosticDescriptor.HelpLinkUri, diagnosticDescriptor.CustomTags.ToArray()); + diagnosticDescriptor.IsEnabledByDefault, diagnosticDescriptor.Description, diagnosticDescriptor.HelpLinkUri, [.. diagnosticDescriptor.CustomTags]); private static string[] CreateCustomTags(bool isReportedAtCompilationEnd, bool escalateToErrorInRecommended, bool disableInAllMode, string[] customTags) { diff --git a/src/Analyzers/MSTest.Analyzers/RoslynAnalyzerHelpers/DiagnosticExtensions.cs b/src/Analyzers/MSTest.Analyzers/RoslynAnalyzerHelpers/DiagnosticExtensions.cs index 7316c3ebb5..dbed1d2ae6 100644 --- a/src/Analyzers/MSTest.Analyzers/RoslynAnalyzerHelpers/DiagnosticExtensions.cs +++ b/src/Analyzers/MSTest.Analyzers/RoslynAnalyzerHelpers/DiagnosticExtensions.cs @@ -169,7 +169,7 @@ public static void ReportNoLocationDiagnostic( { #pragma warning disable RS0030 // The symbol 'DiagnosticDescriptor.DiagnosticDescriptor.#ctor' is banned in this project: Use 'DiagnosticDescriptorHelper.Create' instead rule = new DiagnosticDescriptor(rule.Id, rule.Title, rule.MessageFormat, rule.Category, - effectiveSeverity.Value, rule.IsEnabledByDefault, rule.Description, rule.HelpLinkUri, rule.CustomTags.ToArray()); + effectiveSeverity.Value, rule.IsEnabledByDefault, rule.Description, rule.HelpLinkUri, [.. rule.CustomTags]); #pragma warning restore RS0030 } diff --git a/src/Analyzers/MSTest.Analyzers/TestContextShouldBeValidAnalyzer.cs b/src/Analyzers/MSTest.Analyzers/TestContextShouldBeValidAnalyzer.cs index 10bb626e00..6838d3bbc7 100644 --- a/src/Analyzers/MSTest.Analyzers/TestContextShouldBeValidAnalyzer.cs +++ b/src/Analyzers/MSTest.Analyzers/TestContextShouldBeValidAnalyzer.cs @@ -212,7 +212,7 @@ public override void Initialize(AnalysisContext context) return; } - fieldsAssignedInConstructor = new(); + fieldsAssignedInConstructor = []; context.RegisterOperationBlockAction(context => { diff --git a/src/Analyzers/MSTest.GlobalConfigsGenerator/GlobalConfigBuilder.cs b/src/Analyzers/MSTest.GlobalConfigsGenerator/GlobalConfigBuilder.cs index d0940b34f5..9eb780c850 100644 --- a/src/Analyzers/MSTest.GlobalConfigsGenerator/GlobalConfigBuilder.cs +++ b/src/Analyzers/MSTest.GlobalConfigsGenerator/GlobalConfigBuilder.cs @@ -6,7 +6,7 @@ internal sealed class GlobalConfigBuilder { private readonly StringBuilder _builder = new(); - private readonly Dictionary _severityDictionary = new(); + private readonly Dictionary _severityDictionary = []; public GlobalConfigBuilder(MSTestAnalysisMode mode) { diff --git a/src/Analyzers/MSTest.SourceGeneration/Generators/TestNodesGenerator.cs b/src/Analyzers/MSTest.SourceGeneration/Generators/TestNodesGenerator.cs index c841f5d90d..aa42fbb24a 100644 --- a/src/Analyzers/MSTest.SourceGeneration/Generators/TestNodesGenerator.cs +++ b/src/Analyzers/MSTest.SourceGeneration/Generators/TestNodesGenerator.cs @@ -50,10 +50,9 @@ private static void AddAssemblyTestNode(SourceProductionContext context, (string sourceStringBuilder.AppendAutoGeneratedHeader(); sourceStringBuilder.AppendLine(); - TestNamespaceInfo[] uniqueUsedNamespaces = testClasses + TestNamespaceInfo[] uniqueUsedNamespaces = [.. testClasses .Select(x => x.ContainingNamespace) - .Distinct() - .ToArray(); + .Distinct()]; string? safeAssemblyName = null; IDisposable? namespaceBlock = null; @@ -148,7 +147,7 @@ private static void AddAssemblyTestNode(SourceProductionContext context, (string private static void AppendAssemblyTestNodeBuilderContent(IndentedStringBuilder sourceStringBuilder, string assemblyName, ImmutableArray testClasses) { - Dictionary rootVariablesPerNamespace = new(); + Dictionary rootVariablesPerNamespace = []; int variableIndex = 1; IEnumerable> classesPerNamespaces = testClasses.GroupBy(x => x.ContainingNamespace); foreach (IGrouping namespaceClasses in classesPerNamespaces) @@ -169,7 +168,7 @@ private static void AppendAssemblyTestNodeBuilderContent(IndentedStringBuilder s sourceStringBuilder.Append("MSTF::TestNode root = "); - using (sourceStringBuilder.AppendTestNode(assemblyName, assemblyName, Array.Empty(), ';')) + using (sourceStringBuilder.AppendTestNode(assemblyName, assemblyName, [], ';')) { foreach (IGrouping group in classesPerNamespaces) { diff --git a/src/Analyzers/MSTest.SourceGeneration/Helpers/SystemPolyfills.cs b/src/Analyzers/MSTest.SourceGeneration/Helpers/SystemPolyfills.cs index 7a3645233e..f3e2817245 100644 --- a/src/Analyzers/MSTest.SourceGeneration/Helpers/SystemPolyfills.cs +++ b/src/Analyzers/MSTest.SourceGeneration/Helpers/SystemPolyfills.cs @@ -81,7 +81,7 @@ internal sealed class MemberNotNullAttribute : Attribute /// /// The field or property member that is promised to be not-null. /// - public MemberNotNullAttribute(string member) => Members = new[] { member }; + public MemberNotNullAttribute(string member) => Members = [member]; /// Initializes the attribute with the list of field and property members. /// @@ -107,7 +107,7 @@ internal sealed class MemberNotNullWhenAttribute : Attribute public MemberNotNullWhenAttribute(bool returnValue, string member) { ReturnValue = returnValue; - Members = new[] { member }; + Members = [member]; } /// Initializes the attribute with the specified return value condition and list of field and property members. diff --git a/src/Analyzers/MSTest.SourceGeneration/ObjectModels/DataRowTestMethodArgumentsInfo.cs b/src/Analyzers/MSTest.SourceGeneration/ObjectModels/DataRowTestMethodArgumentsInfo.cs index 5380802d1d..b085453536 100644 --- a/src/Analyzers/MSTest.SourceGeneration/ObjectModels/DataRowTestMethodArgumentsInfo.cs +++ b/src/Analyzers/MSTest.SourceGeneration/ObjectModels/DataRowTestMethodArgumentsInfo.cs @@ -43,7 +43,7 @@ public void AppendArguments(IndentedStringBuilder nodeBuilder) string argumentsEntry = arguments.Length > 1 ? "(" + string.Join(", ", arguments) + ")" : arguments[0]; - string argumentsUid = GetArgumentsUid(_parametersInfo.Parameters.Select(x => x.Name).ToArray(), arguments); + string argumentsUid = GetArgumentsUid([.. _parametersInfo.Parameters.Select(x => x.Name)], arguments); nodeBuilder.AppendLine($"new {TestMethodInfo.TestArgumentsEntryTypeName}<{_parametersInfo.ParametersTuple}>({argumentsEntry}, \"{argumentsUid}\"),"); } } diff --git a/src/Analyzers/MSTest.SourceGeneration/ObjectModels/TestMethodInfo.cs b/src/Analyzers/MSTest.SourceGeneration/ObjectModels/TestMethodInfo.cs index 4cad071a97..708dce9b17 100644 --- a/src/Analyzers/MSTest.SourceGeneration/ObjectModels/TestMethodInfo.cs +++ b/src/Analyzers/MSTest.SourceGeneration/ObjectModels/TestMethodInfo.cs @@ -89,10 +89,10 @@ private TestMethodInfo(IMethodSymbol methodSymbol, INamedTypeSymbol typeUsingMet return null; } - List dataRowAttributes = new(); - List dynamicDataAttributes = new(); - List testPropertyAttributes = new(); - List<(string RuleId, string Description)> pragmas = new(); + List dataRowAttributes = []; + List dynamicDataAttributes = []; + List testPropertyAttributes = []; + List<(string RuleId, string Description)> pragmas = []; TimeSpan? testExecutionTimeout = null; foreach (AttributeData attribute in attributes) { diff --git a/src/Analyzers/MSTest.SourceGeneration/ObjectModels/TestNamespaceInfo.cs b/src/Analyzers/MSTest.SourceGeneration/ObjectModels/TestNamespaceInfo.cs index a17a31fc11..308a04ebea 100644 --- a/src/Analyzers/MSTest.SourceGeneration/ObjectModels/TestNamespaceInfo.cs +++ b/src/Analyzers/MSTest.SourceGeneration/ObjectModels/TestNamespaceInfo.cs @@ -30,8 +30,7 @@ public TestNamespaceInfo(INamespaceSymbol namespaceSymbol) public void AppendNamespaceTestNode(IndentedStringBuilder nodeStringBuilder, string testsVariableName) { - using (nodeStringBuilder.AppendTestNode(_containingAssembly + "." + _nameOrGlobalNamespace, _nameOrGlobalNamespace, - Array.Empty(), testsVariableName)) + using (nodeStringBuilder.AppendTestNode(_containingAssembly + "." + _nameOrGlobalNamespace, _nameOrGlobalNamespace, [], testsVariableName)) { } } diff --git a/src/Analyzers/MSTest.SourceGeneration/ObjectModels/TestTypeInfo.cs b/src/Analyzers/MSTest.SourceGeneration/ObjectModels/TestTypeInfo.cs index 60d46150ed..c1ec3a610e 100644 --- a/src/Analyzers/MSTest.SourceGeneration/ObjectModels/TestTypeInfo.cs +++ b/src/Analyzers/MSTest.SourceGeneration/ObjectModels/TestTypeInfo.cs @@ -156,7 +156,7 @@ public void AppendTestNode(IndentedStringBuilder sourceStringBuilder) private void AppendTestNodeCreation(IndentedStringBuilder sourceStringBuilder) { - List properties = new(); + List properties = []; foreach ((string filePath, int startLine, int endLine) in _declarationReferences) { properties.Add($"new Msg::TestFileLocationProperty(@\"{filePath}\", new(new({startLine}, -1), new({endLine}, -1))),"); diff --git a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/AzureDevOpsReporter.cs b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/AzureDevOpsReporter.cs index 9e7093ba63..580002941d 100644 --- a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/AzureDevOpsReporter.cs +++ b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/AzureDevOpsReporter.cs @@ -23,7 +23,7 @@ internal sealed class AzureDevOpsReporter : private readonly IOutputDevice _outputDisplay; private readonly ILogger _logger; - private static readonly char[] NewlineCharacters = new char[] { '\r', '\n' }; + private static readonly char[] NewlineCharacters = ['\r', '\n']; private readonly ICommandLineOptions _commandLine; private readonly IEnvironment _environment; private readonly IFileSystem _fileSystem; diff --git a/src/Platform/Microsoft.Testing.Extensions.HangDump/HangDumpActivityIndicator.cs b/src/Platform/Microsoft.Testing.Extensions.HangDump/HangDumpActivityIndicator.cs index 9469725e51..7ca615581c 100644 --- a/src/Platform/Microsoft.Testing.Extensions.HangDump/HangDumpActivityIndicator.cs +++ b/src/Platform/Microsoft.Testing.Extensions.HangDump/HangDumpActivityIndicator.cs @@ -140,7 +140,7 @@ private async Task CallbackAsync(IRequest request) if (request is GetInProgressTestsRequest) { await _logger.LogDebugAsync($"Received '{nameof(GetInProgressTestsRequest)}'"); - return new GetInProgressTestsResponse(_testsCurrentExecutionState.Select(x => (x.Value.Name, (int)_clock.UtcNow.Subtract(x.Value.StartTime).TotalSeconds)).ToArray()); + return new GetInProgressTestsResponse([.. _testsCurrentExecutionState.Select(x => (x.Value.Name, (int)_clock.UtcNow.Subtract(x.Value.StartTime).TotalSeconds))]); } else if (request is ExitSignalActivityIndicatorTaskRequest) { diff --git a/src/Platform/Microsoft.Testing.Extensions.HangDump/Serializers/GetInProgressTestsResponse.cs b/src/Platform/Microsoft.Testing.Extensions.HangDump/Serializers/GetInProgressTestsResponse.cs index da92375d71..04344f941c 100644 --- a/src/Platform/Microsoft.Testing.Extensions.HangDump/Serializers/GetInProgressTestsResponse.cs +++ b/src/Platform/Microsoft.Testing.Extensions.HangDump/Serializers/GetInProgressTestsResponse.cs @@ -26,7 +26,7 @@ public object Deserialize(Stream stream) tests.Add((testName, unixTimeSeconds)); } - return new GetInProgressTestsResponse(tests.ToArray()); + return new GetInProgressTestsResponse([.. tests]); } public void Serialize(object objectToSerialize, Stream stream) diff --git a/src/Platform/Microsoft.Testing.Extensions.Retry/RetryCommandLineOptionsProvider.cs b/src/Platform/Microsoft.Testing.Extensions.Retry/RetryCommandLineOptionsProvider.cs index 954fb4dfe9..5a5e521ca2 100644 --- a/src/Platform/Microsoft.Testing.Extensions.Retry/RetryCommandLineOptionsProvider.cs +++ b/src/Platform/Microsoft.Testing.Extensions.Retry/RetryCommandLineOptionsProvider.cs @@ -24,9 +24,8 @@ internal sealed class RetryCommandLineOptionsProvider : ICommandLineOptionsProvi public string Description => ExtensionResources.RetryFailedTestsExtensionDescription; - public IReadOnlyCollection GetCommandLineOptions() - => new CommandLineOption[] - { + public IReadOnlyCollection GetCommandLineOptions() => + [ // Hide the extension for now, we will add tests and we will re-enable when will be good. // We'd like to have some iteration in prod with our dogfooders before. new(RetryFailedTestsOptionName, ExtensionResources.RetryFailedTestsOptionDescription, ArgumentArity.ExactlyOne, false, isBuiltIn: true), @@ -34,8 +33,8 @@ public IReadOnlyCollection GetCommandLineOptions() new(RetryFailedTestsMaxTestsOptionName, ExtensionResources.RetryFailedTestsMaxTestsOptionDescription, ArgumentArity.ExactlyOne, false, isBuiltIn: true), // Hidden internal args - new(RetryFailedTestsPipeNameOptionName, "Communication between the test host and the retry infra.", ArgumentArity.ExactlyOne, isHidden: true, isBuiltIn: true), - }; + new(RetryFailedTestsPipeNameOptionName, "Communication between the test host and the retry infra.", ArgumentArity.ExactlyOne, isHidden: true, isBuiltIn: true) + ]; public Task IsEnabledAsync() => Task.FromResult(true); diff --git a/src/Platform/Microsoft.Testing.Extensions.Retry/RetryDataConsumer.cs b/src/Platform/Microsoft.Testing.Extensions.Retry/RetryDataConsumer.cs index 8b92f00072..d81ebe0fb0 100644 --- a/src/Platform/Microsoft.Testing.Extensions.Retry/RetryDataConsumer.cs +++ b/src/Platform/Microsoft.Testing.Extensions.Retry/RetryDataConsumer.cs @@ -28,7 +28,7 @@ public RetryDataConsumer(IServiceProvider serviceProvider) _commandLineOptions = _serviceProvider.GetCommandLineOptions(); } - public Type[] DataTypesConsumed => new[] { typeof(TestNodeUpdateMessage) }; + public Type[] DataTypesConsumed => [typeof(TestNodeUpdateMessage)]; public string Uid => nameof(RetryDataConsumer); diff --git a/src/Platform/Microsoft.Testing.Extensions.Retry/RetryExecutionFilterFactory.cs b/src/Platform/Microsoft.Testing.Extensions.Retry/RetryExecutionFilterFactory.cs index 1beb0961e0..0c28e544c0 100644 --- a/src/Platform/Microsoft.Testing.Extensions.Retry/RetryExecutionFilterFactory.cs +++ b/src/Platform/Microsoft.Testing.Extensions.Retry/RetryExecutionFilterFactory.cs @@ -38,8 +38,7 @@ public Task IsEnabledAsync() _retryFailedTestsLifecycleCallbacks = _serviceProvider.GetRequiredService(); if (_retryFailedTestsLifecycleCallbacks.FailedTestsIDToRetry?.Length > 0) { - return (true, new TestNodeUidListFilter(_retryFailedTestsLifecycleCallbacks.FailedTestsIDToRetry - .Select(x => new TestNodeUid(x)).ToArray())); + return (true, new TestNodeUidListFilter([.. _retryFailedTestsLifecycleCallbacks.FailedTestsIDToRetry.Select(x => new TestNodeUid(x))])); } else { diff --git a/src/Platform/Microsoft.Testing.Extensions.Retry/RetryFailedTestsPipeServer.cs b/src/Platform/Microsoft.Testing.Extensions.Retry/RetryFailedTestsPipeServer.cs index 21032e0497..b516672563 100644 --- a/src/Platform/Microsoft.Testing.Extensions.Retry/RetryFailedTestsPipeServer.cs +++ b/src/Platform/Microsoft.Testing.Extensions.Retry/RetryFailedTestsPipeServer.cs @@ -54,7 +54,7 @@ private Task CallbackAsync(IRequest request) { if (request is FailedTestRequest failed) { - FailedUID ??= new(); + FailedUID ??= []; FailedUID.Add(failed.Uid); return Task.FromResult((IResponse)VoidResponse.CachedInstance); } diff --git a/src/Platform/Microsoft.Testing.Extensions.Retry/RetryOrchestrator.cs b/src/Platform/Microsoft.Testing.Extensions.Retry/RetryOrchestrator.cs index 59df6004f2..94bc289dd5 100644 --- a/src/Platform/Microsoft.Testing.Extensions.Retry/RetryOrchestrator.cs +++ b/src/Platform/Microsoft.Testing.Extensions.Retry/RetryOrchestrator.cs @@ -93,8 +93,8 @@ public async Task OrchestrateTestHostExecutionAsync() int userMaxRetryCount = int.Parse(cmdRetries[0], CultureInfo.InvariantCulture); // Find out the retry args index inside the arguments to after cleanup the command line when we restart - List indexToCleanup = new(); - string[] executableArguments = executableInfo.Arguments.ToArray(); + List indexToCleanup = []; + string[] executableArguments = [.. executableInfo.Arguments]; int argIndex = GetOptionArgumentIndex(RetryCommandLineOptionsProvider.RetryFailedTestsOptionName, executableArguments); if (argIndex < 0) { @@ -128,12 +128,12 @@ public async Task OrchestrateTestHostExecutionAsync() // Override the result directory with the attempt one string resultDirectory = configuration.GetTestResultDirectory(); - List exitCodes = new(); + List exitCodes = []; IOutputDevice outputDevice = _serviceProvider.GetOutputDevice(); IFileSystem fileSystem = _serviceProvider.GetFileSystem(); int attemptCount = 0; - List finalArguments = new(); + List finalArguments = []; string[]? lastListOfFailedId = null; string? currentTryResultFolder = null; bool thresholdPolicyKickedIn = false; @@ -160,7 +160,7 @@ public async Task OrchestrateTestHostExecutionAsync() finalArguments.Add(currentTryResultFolder); // Prepare the pipeserver - using RetryFailedTestsPipeServer retryFailedTestsPipeServer = new(_serviceProvider, lastListOfFailedId ?? Array.Empty(), logger); + using RetryFailedTestsPipeServer retryFailedTestsPipeServer = new(_serviceProvider, lastListOfFailedId ?? [], logger); finalArguments.Add($"--{RetryCommandLineOptionsProvider.RetryFailedTestsPipeNameOptionName}"); finalArguments.Add(retryFailedTestsPipeServer.PipeName); diff --git a/src/Platform/Microsoft.Testing.Extensions.Telemetry/AppInsightsProvider.cs b/src/Platform/Microsoft.Testing.Extensions.Telemetry/AppInsightsProvider.cs index 959180a64a..070495036b 100644 --- a/src/Platform/Microsoft.Testing.Extensions.Telemetry/AppInsightsProvider.cs +++ b/src/Platform/Microsoft.Testing.Extensions.Telemetry/AppInsightsProvider.cs @@ -108,7 +108,7 @@ public AppInsightsProvider( #else // Keep the custom thread to avoid to waste one from thread pool. // We have some await but we should stay on the custom thread if not for special cases like trace log or exception. - _payloads = new(); + _payloads = []; _telemetryTask = _task.RunLongRunning(IngestLoopAsync, "Telemetry AppInsightsProvider", _testApplicationCancellationTokenSource.CancellationToken); #endif diff --git a/src/Platform/Microsoft.Testing.Extensions.Telemetry/CIEnvironmentDetectorForTelemetry.cs b/src/Platform/Microsoft.Testing.Extensions.Telemetry/CIEnvironmentDetectorForTelemetry.cs index b90059537b..0ac25bde4a 100644 --- a/src/Platform/Microsoft.Testing.Extensions.Telemetry/CIEnvironmentDetectorForTelemetry.cs +++ b/src/Platform/Microsoft.Testing.Extensions.Telemetry/CIEnvironmentDetectorForTelemetry.cs @@ -33,8 +33,8 @@ internal sealed class CIEnvironmentDetectorForTelemetry ]; // Systems where every variable must be present and not-null before returning true - private static readonly string[][] AllNotNullVariables = new string[][] - { + private static readonly string[][] AllNotNullVariables = + [ // AWS CodeBuild - https://docs.aws.amazon.com/codebuild/latest/userguide/build-env-ref-env-vars.html ["CODEBUILD_BUILD_ID", "AWS_REGION"], @@ -43,7 +43,7 @@ internal sealed class CIEnvironmentDetectorForTelemetry // Google Cloud Build - https://cloud.google.com/build/docs/configuring-builds/substitute-variable-values#using_default_substitutions ["BUILD_ID", "PROJECT_ID"], - }; + ]; // Systems where the variable must be present and not-null private static readonly string[] IfNonNullVariables = diff --git a/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxCompareTool.cs b/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxCompareTool.cs index c79cb5c062..2373e481b5 100644 --- a/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxCompareTool.cs +++ b/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxCompareTool.cs @@ -55,10 +55,10 @@ public async Task RunAsync() XNamespace trxNamespace = "http://microsoft.com/schemas/VisualStudio/TeamTest/2010"; - List<(string TestName, string Outcome, string Storage)> baseLineResults = new(); - List baseLineIssues = new(); - List<(string TestName, string Outcome, string Storage)> comparedResults = new(); - List comparedIssues = new(); + List<(string TestName, string Outcome, string Storage)> baseLineResults = []; + List baseLineIssues = []; + List<(string TestName, string Outcome, string Storage)> comparedResults = []; + List comparedIssues = []; await _task.WhenAll( _task.Run(() => CollectEntriesAndErrors(baselineFilePaths[0], trxNamespace, baseLineResults, baseLineIssues)), _task.Run(() => CollectEntriesAndErrors(comparedFilePaths[0], trxNamespace, comparedResults, comparedIssues))); @@ -202,11 +202,10 @@ private static void CollectEntriesAndErrors(string trxFile, XNamespace ns, List< continue; } - XElement[] matchingUnitTestDefinitions = trxTestRun + XElement[] matchingUnitTestDefinitions = [.. trxTestRun .Elements(ns + "TestDefinitions") .Elements(ns + "UnitTest") - .Where(x => x.Attribute("id")?.Value == testId) - .ToArray(); + .Where(x => x.Attribute("id")?.Value == testId)]; if (matchingUnitTestDefinitions.Length > 1) { issues.Add($"Found more than one entry in 'TestDefinitions.UnitTest' matching the test ID '{testId}'."); diff --git a/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxDataConsumer.cs b/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxDataConsumer.cs index 7999b00d47..6157ecc217 100644 --- a/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxDataConsumer.cs +++ b/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxDataConsumer.cs @@ -40,7 +40,7 @@ internal sealed class TrxReportGenerator : private readonly TrxTestApplicationLifecycleCallbacks? _trxTestApplicationLifecycleCallbacks; private readonly ILogger _logger; private readonly List _tests = []; - private readonly Dictionary> _artifactsByExtension = new(); + private readonly Dictionary> _artifactsByExtension = []; private readonly bool _isEnabled; private DateTimeOffset? _testStartTime; @@ -227,7 +227,7 @@ public async Task OnTestSessionFinishingAsync(SessionUid sessionUid, Cancellatio int exitCode = _testApplicationProcessExitCode.GetProcessExitCode(); TrxReportEngine trxReportGeneratorEngine = new(_testApplicationModuleInfo, _environment, _commandLineOptionsService, _configuration, - _clock, _tests.ToArray(), _failedTestsCount, _passedTestsCount, _notExecutedTestsCount, _timeoutTestsCount, _artifactsByExtension, + _clock, [.. _tests], _failedTestsCount, _passedTestsCount, _notExecutedTestsCount, _timeoutTestsCount, _artifactsByExtension, _adapterSupportTrxCapability, _testFramework, _testStartTime.Value, exitCode, cancellationToken); (string reportFileName, string? warning) = await trxReportGeneratorEngine.GenerateReportAsync(); if (warning is not null) diff --git a/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxProcessLifetimeHandler.cs b/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxProcessLifetimeHandler.cs index 903579a21a..9277a8b3ef 100644 --- a/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxProcessLifetimeHandler.cs +++ b/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxProcessLifetimeHandler.cs @@ -44,7 +44,7 @@ internal sealed class TrxProcessLifetimeHandler : private readonly IOutputDevice _outputDevice; private readonly ILogger _logger; private readonly PipeNameDescription _pipeNameDescription; - private readonly Dictionary> _fileArtifacts = new(); + private readonly Dictionary> _fileArtifacts = []; private readonly DateTimeOffset _startTime; private NamedPipeServer? _singleConnectionNamedPipeServer; @@ -144,7 +144,7 @@ public async Task OnTestHostProcessExitedAsync(ITestHostProcessInformation testH return; } - Dictionary> artifacts = new(); + Dictionary> artifacts = []; foreach (KeyValuePair> prodArtifacts in _fileArtifacts) { diff --git a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/Condition.cs b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/Condition.cs index 90d9101af0..e5b628d9b4 100644 --- a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/Condition.cs +++ b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/Condition.cs @@ -164,7 +164,7 @@ internal static Condition Parse(string? conditionString) ThrownFormatExceptionForInvalidCondition(conditionString); } - string[] parts = TokenizeFilterConditionString(conditionString).ToArray(); + string[] parts = [.. TokenizeFilterConditionString(conditionString)]; if (parts.Length == 1) { // If only parameter values is passed, create condition with default property name, diff --git a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/FastFilter.cs b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/FastFilter.cs index 456384b72c..aab3a4cf06 100644 --- a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/FastFilter.cs +++ b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/FastFilter.cs @@ -37,7 +37,7 @@ internal FastFilter(ImmutableDictionary> filterProperties, ? null : FilterProperties.Keys.All(name => properties.Contains(name)) ? null - : FilterProperties.Keys.Where(name => !properties.Contains(name)).ToArray(); + : [.. FilterProperties.Keys.Where(name => !properties.Contains(name))]; internal bool Evaluate(Func propertyValueProvider) { diff --git a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/FilterExpression.cs b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/FilterExpression.cs index 4f771bfc0f..be6f23da2b 100644 --- a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/FilterExpression.cs +++ b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/FilterExpression.cs @@ -136,7 +136,7 @@ private static void ProcessOperator(Stack filterStack, Operato } else if (invalidRight != null) { - invalidProperties = invalidProperties.Concat(invalidRight).ToArray(); + invalidProperties = [.. invalidProperties, .. invalidRight]; } return invalidProperties; diff --git a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/ObjectModelConverters.cs b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/ObjectModelConverters.cs index 43cecb9491..85fc64ea49 100644 --- a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/ObjectModelConverters.cs +++ b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/ObjectModelConverters.cs @@ -150,7 +150,7 @@ public static TestNode ToTestNode(this TestResult testResult, bool isTrxEnabled, throw new InvalidOperationException("Unable to parse fully qualified type name from test case: " + testResult.TestCase.FullyQualifiedName); } - testNode.Properties.Add(new TrxMessagesProperty(testResult.Messages + testNode.Properties.Add(new TrxMessagesProperty([.. testResult.Messages .Select(msg => msg.Category switch { @@ -158,8 +158,7 @@ public static TestNode ToTestNode(this TestResult testResult, bool isTrxEnabled, string x when x == TestResultMessage.StandardOutCategory => new StandardOutputTrxMessage(msg.Text), string x when x == TestResultMessage.DebugTraceCategory => new DebugOrTraceTrxMessage(msg.Text), _ => new TrxMessage(msg.Text), - }) - .ToArray())); + })])); } testNode.Properties.Add(new TimingProperty(new(testResult.StartTime, testResult.EndTime, testResult.Duration), [])); diff --git a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/RunSettingsPatcher.cs b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/RunSettingsPatcher.cs index 85cc81e2e2..97fa572220 100644 --- a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/RunSettingsPatcher.cs +++ b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/RunSettingsPatcher.cs @@ -107,7 +107,7 @@ private static void PatchTestRunParameters(XDocument runSettingsDocument, IComma runSettingsElement.Add(testRunParametersElement); } - XElement[] testRunParametersNodes = testRunParametersElement.Nodes().OfType().ToArray(); + XElement[] testRunParametersNodes = [.. testRunParametersElement.Nodes().OfType()]; foreach (string testRunParameter in testRunParameters) { string[] parts = testRunParameter.Split(TestRunParameterSeparator, 2); diff --git a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/SynchronizedSingleSessionVSTestAndTestAnywhereAdapter.cs b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/SynchronizedSingleSessionVSTestAndTestAnywhereAdapter.cs index 57ae617299..a9f70fbcdf 100644 --- a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/SynchronizedSingleSessionVSTestAndTestAnywhereAdapter.cs +++ b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/SynchronizedSingleSessionVSTestAndTestAnywhereAdapter.cs @@ -150,7 +150,7 @@ protected sealed override Task ExecuteRequestAsync(TestExecutionRequest request, => ExecuteRequestWithRequestCountGuardAsync(async () => { #pragma warning disable IL3000 // Avoid accessing Assembly file path when publishing as a single file - string[] testAssemblyPaths = _getTestAssemblies().Select(x => x.Location).ToArray(); + string[] testAssemblyPaths = [.. _getTestAssemblies().Select(x => x.Location)]; #pragma warning restore IL3000 // Avoid accessing Assembly file path when publishing as a single file switch (request) { diff --git a/src/Platform/Microsoft.Testing.Platform.MSBuild/Tasks/InvokeTestingPlatformTask.cs b/src/Platform/Microsoft.Testing.Platform.MSBuild/Tasks/InvokeTestingPlatformTask.cs index ed0cbe17ec..fd765fce0b 100644 --- a/src/Platform/Microsoft.Testing.Platform.MSBuild/Tasks/InvokeTestingPlatformTask.cs +++ b/src/Platform/Microsoft.Testing.Platform.MSBuild/Tasks/InvokeTestingPlatformTask.cs @@ -32,7 +32,7 @@ public class InvokeTestingPlatformTask : Build.Utilities.ToolTask, IDisposable private readonly IFileSystem _fileSystem; private readonly PipeNameDescription _pipeNameDescription; private readonly CancellationTokenSource _waitForConnections = new(); - private readonly List _connections = new(); + private readonly List _connections = []; private readonly StringBuilder _output = new(); private readonly Lock _initLock = new(); private readonly Architecture _currentProcessArchitecture = RuntimeInformation.ProcessArchitecture; diff --git a/src/Platform/Microsoft.Testing.Platform.MSBuild/Tasks/TestingPlatformAutoRegisteredExtensions.cs b/src/Platform/Microsoft.Testing.Platform.MSBuild/Tasks/TestingPlatformAutoRegisteredExtensions.cs index 818749ffad..f1d1018d35 100644 --- a/src/Platform/Microsoft.Testing.Platform.MSBuild/Tasks/TestingPlatformAutoRegisteredExtensions.cs +++ b/src/Platform/Microsoft.Testing.Platform.MSBuild/Tasks/TestingPlatformAutoRegisteredExtensions.cs @@ -156,7 +156,7 @@ private static ITaskItem[] Reorder(ITaskItem[] items) result.Add(items[wellKnownBuilderHook_MicrosoftTestingPlatformExtensions_index]); } - return result.ToArray(); + return [.. result]; } private static void GenerateCode(string language, string? rootNamespace, ITaskItem[] taskItems, ITaskItem testingPlatformEntryPointSourcePath, IFileSystem fileSystem, TaskLoggingHelper taskLoggingHelper) diff --git a/src/Platform/Microsoft.Testing.Platform/Builder/TestApplication.cs b/src/Platform/Microsoft.Testing.Platform/Builder/TestApplication.cs index b1cd776b62..b5f7d81720 100644 --- a/src/Platform/Microsoft.Testing.Platform/Builder/TestApplication.cs +++ b/src/Platform/Microsoft.Testing.Platform/Builder/TestApplication.cs @@ -47,10 +47,10 @@ public static Task CreateServerModeBuilderAsync(string[ if (args.Contains($"--{PlatformCommandLineProvider.ServerOptionKey}") || args.Contains($"-{PlatformCommandLineProvider.ServerOptionKey}")) { // Remove the --server option from the args so that the builder can be created. - args = args.Where(arg => arg.Trim('-') != PlatformCommandLineProvider.ServerOptionKey).ToArray(); + args = [.. args.Where(arg => arg.Trim('-') != PlatformCommandLineProvider.ServerOptionKey)]; } - return CreateBuilderAsync(args.Append($"--{PlatformCommandLineProvider.ServerOptionKey}").ToArray(), testApplicationOptions); + return CreateBuilderAsync([.. args, $"--{PlatformCommandLineProvider.ServerOptionKey}"], testApplicationOptions); } /// diff --git a/src/Platform/Microsoft.Testing.Platform/CommandLine/CommandLineHandler.cs b/src/Platform/Microsoft.Testing.Platform/CommandLine/CommandLineHandler.cs index 1f6a1e0365..ac42242e50 100644 --- a/src/Platform/Microsoft.Testing.Platform/CommandLine/CommandLineHandler.cs +++ b/src/Platform/Microsoft.Testing.Platform/CommandLine/CommandLineHandler.cs @@ -248,11 +248,10 @@ static string GetApplicationName(ITestApplicationModuleInfo testApplicationModul async Task PrintOptionsAsync(IEnumerable optionProviders, bool builtInOnly = false) { CommandLineOption[] options = - optionProviders + [.. optionProviders .SelectMany(provider => provider.GetCommandLineOptions()) .Where(option => !option.IsHidden && option.IsBuiltIn == builtInOnly) - .OrderBy(option => option.Name) - .ToArray(); + .OrderBy(option => option.Name)]; if (options.Length == 0) { @@ -281,9 +280,7 @@ async Task PrintApplicationUsageAsync(string applicationName) "System command line options should not have any tool option registered."); await outputDevice.DisplayAsync(this, new TextOutputDeviceData(PlatformResources.HelpOptions)); ICommandLineOptionsProvider[] nonToolsExtensionProviders = - ExtensionsCommandLineOptionsProviders - .Where(provider => provider is not IToolCommandLineOptionsProvider) - .ToArray(); + [.. ExtensionsCommandLineOptionsProviders.Where(provider => provider is not IToolCommandLineOptionsProvider)]; // By default, only system options are built-in but some extensions (e.g. retry) are considered as built-in too, // so we need to union the 2 collections before printing the options. await PrintOptionsAsync(SystemCommandLineOptionsProviders.Union(nonToolsExtensionProviders), builtInOnly: true); diff --git a/src/Platform/Microsoft.Testing.Platform/CommandLine/ParseResult.cs b/src/Platform/Microsoft.Testing.Platform/CommandLine/ParseResult.cs index 6e3de38051..1a39282dc7 100644 --- a/src/Platform/Microsoft.Testing.Platform/CommandLine/ParseResult.cs +++ b/src/Platform/Microsoft.Testing.Platform/CommandLine/ParseResult.cs @@ -129,7 +129,7 @@ public bool TryGetOptionArgumentList(string optionName, [NotNullWhen(true)] out IEnumerable result = Options.Where(x => x.Name == optionName); if (result.Any()) { - arguments = result.SelectMany(x => x.Arguments).ToArray(); + arguments = [.. result.SelectMany(x => x.Arguments)]; return true; } diff --git a/src/Platform/Microsoft.Testing.Platform/CommandLine/Parser.cs b/src/Platform/Microsoft.Testing.Platform/CommandLine/Parser.cs index 8e4d3e44b1..f8f6306d22 100644 --- a/src/Platform/Microsoft.Testing.Platform/CommandLine/Parser.cs +++ b/src/Platform/Microsoft.Testing.Platform/CommandLine/Parser.cs @@ -72,7 +72,7 @@ private static CommandLineParseResult Parse(List args, IEnvironment envi } else { - options.Add(new(currentOption, currentOptionArguments.ToArray())); + options.Add(new(currentOption, [.. currentOptionArguments])); currentOptionArguments.Clear(); ParseOptionAndSeparators(args[i], out currentOption, out currentArg); argumentHandled = true; @@ -122,7 +122,7 @@ private static CommandLineParseResult Parse(List args, IEnvironment envi } } - options.Add(new(currentOption, currentOptionArguments.ToArray())); + options.Add(new(currentOption, [.. currentOptionArguments])); } return new CommandLineParseResult(toolName, options, errors); diff --git a/src/Platform/Microsoft.Testing.Platform/CommandLine/PlatformCommandLineProvider.cs b/src/Platform/Microsoft.Testing.Platform/CommandLine/PlatformCommandLineProvider.cs index c448fa0bf4..d744fdd77b 100644 --- a/src/Platform/Microsoft.Testing.Platform/CommandLine/PlatformCommandLineProvider.cs +++ b/src/Platform/Microsoft.Testing.Platform/CommandLine/PlatformCommandLineProvider.cs @@ -143,7 +143,7 @@ public Task ValidateOptionArgumentsAsync(CommandLineOption com public static int GetMinimumExpectedTests(ICommandLineOptions commandLineOptions) { bool hasMinimumExpectedTestsOptionKey = commandLineOptions.TryGetOptionArgumentList(MinimumExpectedTestsOptionKey, out string[]? minimumExpectedTests); - if (!hasMinimumExpectedTestsOptionKey || !IsMinimumExpectedTestsOptionValidAsync(MinimumExpectedTests, minimumExpectedTests ?? Array.Empty()).Result.IsValid) + if (!hasMinimumExpectedTestsOptionKey || !IsMinimumExpectedTestsOptionValidAsync(MinimumExpectedTests, minimumExpectedTests ?? []).Result.IsValid) { return 0; } diff --git a/src/Platform/Microsoft.Testing.Platform/CommandLine/ResponseFileHelper.cs b/src/Platform/Microsoft.Testing.Platform/CommandLine/ResponseFileHelper.cs index 1b9d4c057b..a0d5965447 100644 --- a/src/Platform/Microsoft.Testing.Platform/CommandLine/ResponseFileHelper.cs +++ b/src/Platform/Microsoft.Testing.Platform/CommandLine/ResponseFileHelper.cs @@ -12,7 +12,7 @@ internal static bool TryReadResponseFile(string rspFilePath, ICollection { try { - newArguments = ExpandResponseFile(rspFilePath).ToArray(); + newArguments = [.. ExpandResponseFile(rspFilePath)]; return true; } catch (FileNotFoundException) diff --git a/src/Platform/Microsoft.Testing.Platform/Configurations/ConfigurationManager.cs b/src/Platform/Microsoft.Testing.Platform/Configurations/ConfigurationManager.cs index 5a4861b9b0..4336f6c4e8 100644 --- a/src/Platform/Microsoft.Testing.Platform/Configurations/ConfigurationManager.cs +++ b/src/Platform/Microsoft.Testing.Platform/Configurations/ConfigurationManager.cs @@ -58,6 +58,6 @@ internal async Task BuildAsync(IFileLoggerProvider? syncFileLogg return defaultJsonConfiguration is null ? throw new InvalidOperationException(PlatformResources.ConfigurationManagerCannotFindDefaultJsonConfigurationErrorMessage) - : new AggregatedConfiguration(configurationProviders.OrderBy(x => x.Order).Select(x => x.ConfigurationProvider).ToArray(), _testApplicationModuleInfo, _fileSystem, commandLineParseResult); + : new AggregatedConfiguration([.. configurationProviders.OrderBy(x => x.Order).Select(x => x.ConfigurationProvider)], _testApplicationModuleInfo, _fileSystem, commandLineParseResult); } } diff --git a/src/Platform/Microsoft.Testing.Platform/Hosts/ServerTestHost.cs b/src/Platform/Microsoft.Testing.Platform/Hosts/ServerTestHost.cs index be8ff2dd95..1292534fa5 100644 --- a/src/Platform/Microsoft.Testing.Platform/Hosts/ServerTestHost.cs +++ b/src/Platform/Microsoft.Testing.Platform/Hosts/ServerTestHost.cs @@ -556,7 +556,7 @@ await ExecuteRequestAsync( await _telemetryService.LogEventAsync(TelemetryEvents.TestsRunEventName, metadata); return method == JsonRpcMethods.TestingRunTests - ? new RunResponseArgs(testNodeUpdateProcessor.Artifacts.ToArray()) + ? new RunResponseArgs([.. testNodeUpdateProcessor.Artifacts]) : method == JsonRpcMethods.TestingDiscoverTests ? (ResponseArgsBase)new DiscoverResponseArgs() : throw new NotImplementedException($"Request not implemented '{method}'"); diff --git a/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostBuilder.cs b/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostBuilder.cs index 3f7f116f16..ac796585c4 100644 --- a/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostBuilder.cs +++ b/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostBuilder.cs @@ -727,7 +727,7 @@ private static async Task BuildTestFrameworkAsync(TestFrameworkB dataConsumersBuilder.Add(abortForMaxFailedTestsExtension); } - IDataConsumer[] dataConsumerServices = dataConsumersBuilder.ToArray(); + IDataConsumer[] dataConsumerServices = [.. dataConsumersBuilder]; AsynchronousMessageBus concreteMessageBusService = new( dataConsumerServices, diff --git a/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostControllersTestHost.cs b/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostControllersTestHost.cs index 601ea403d2..5fb3719f64 100644 --- a/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostControllersTestHost.cs +++ b/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostControllersTestHost.cs @@ -157,7 +157,7 @@ protected override async Task InternalRunAsync() } AsynchronousMessageBus concreteMessageBusService = new( - dataConsumersBuilder.ToArray(), + [.. dataConsumersBuilder], ServiceProvider.GetTestApplicationCancellationTokenSource(), ServiceProvider.GetTask(), ServiceProvider.GetLoggerFactory(), diff --git a/src/Platform/Microsoft.Testing.Platform/Logging/LoggerFactory.cs b/src/Platform/Microsoft.Testing.Platform/Logging/LoggerFactory.cs index 951e264d23..796f009c74 100644 --- a/src/Platform/Microsoft.Testing.Platform/Logging/LoggerFactory.cs +++ b/src/Platform/Microsoft.Testing.Platform/Logging/LoggerFactory.cs @@ -41,7 +41,7 @@ private ILogger[] CreateLoggers(string categoryName) loggers.Add(loggerProvider.CreateLogger(categoryName)); } - return loggers.ToArray(); + return [.. loggers]; } public void Dispose() diff --git a/src/Platform/Microsoft.Testing.Platform/Logging/LoggingManager.cs b/src/Platform/Microsoft.Testing.Platform/Logging/LoggingManager.cs index 5ce732043a..43c32ecbb2 100644 --- a/src/Platform/Microsoft.Testing.Platform/Logging/LoggingManager.cs +++ b/src/Platform/Microsoft.Testing.Platform/Logging/LoggingManager.cs @@ -33,6 +33,6 @@ internal async Task BuildAsync(IServiceProvider serviceProvider, loggerProviders.Add(serviceInstance); } - return new LoggerFactory(loggerProviders.ToArray(), logLevel, monitor); + return new LoggerFactory([.. loggerProviders], logLevel, monitor); } } diff --git a/src/Platform/Microsoft.Testing.Platform/Messages/PropertyBag.Property.cs b/src/Platform/Microsoft.Testing.Platform/Messages/PropertyBag.Property.cs index 0594ffa307..c0401e55a1 100644 --- a/src/Platform/Microsoft.Testing.Platform/Messages/PropertyBag.Property.cs +++ b/src/Platform/Microsoft.Testing.Platform/Messages/PropertyBag.Property.cs @@ -147,6 +147,6 @@ public PropertyDebugView(Property property) } [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] - public IProperty[] Items => _property.AsEnumerable().ToArray(); + public IProperty[] Items => [.. _property.AsEnumerable()]; } } diff --git a/src/Platform/Microsoft.Testing.Platform/Messages/PropertyBag.cs b/src/Platform/Microsoft.Testing.Platform/Messages/PropertyBag.cs index c3d1e03d24..b8c0905ce1 100644 --- a/src/Platform/Microsoft.Testing.Platform/Messages/PropertyBag.cs +++ b/src/Platform/Microsoft.Testing.Platform/Messages/PropertyBag.cs @@ -230,7 +230,7 @@ public TProperty Single() throw new InvalidOperationException($"Could not find a property of type '{typeof(TProperty)}'."); } - IEnumerable matchingValues = _property is null ? Array.Empty() : _property.OfType(); + IEnumerable matchingValues = _property is null ? [] : _property.OfType(); return !matchingValues.Any() ? throw new InvalidOperationException($"Could not find a property of type '{typeof(TProperty)}'.") @@ -255,7 +255,7 @@ public TProperty[] OfType() // We don't want to allocate an array if we know that we're looking for a TestNodeStateProperty return typeof(TestNodeStateProperty).IsAssignableFrom(typeof(TProperty)) ? [] - : _property is null ? [] : _property.OfType().ToArray(); + : _property is null ? [] : [.. _property.OfType()]; } /// diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/AnsiDetector.cs b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/AnsiDetector.cs index 5dd4b3e884..9c1b06e283 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/AnsiDetector.cs +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/AnsiDetector.cs @@ -13,7 +13,7 @@ namespace Microsoft.Testing.Platform.OutputDevice.Terminal; internal static class AnsiDetector { private static readonly Regex[] TerminalsRegexes = - { + [ new("^xterm"), // xterm, PuTTY, Mintty new("^rxvt"), // RXVT new("^(?!eterm-color).*eterm.*"), // Accepts eterm, but not eterm-color, which does not support moving the cursor, see #9950. @@ -30,8 +30,8 @@ internal static class AnsiDetector new("konsole"), // Konsole new("bvterm"), // Bitvise SSH Client new("^st-256color"), // Suckless Simple Terminal, st - new("alacritty"), // Alacritty - }; + new("alacritty") // Alacritty + ]; public static bool IsAnsiSupported(string? termType) => !RoslynString.IsNullOrEmpty(termType) && TerminalsRegexes.Any(regex => regex.IsMatch(termType)); diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/AnsiTerminal.cs b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/AnsiTerminal.cs index 4e8e511e22..abc28c3ea2 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/AnsiTerminal.cs +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/AnsiTerminal.cs @@ -16,8 +16,8 @@ internal sealed class AnsiTerminal : ITerminal /// File extensions that we will link to directly, all other files /// are linked to their directory, to avoid opening dlls, or executables. /// - private static readonly string[] KnownFileExtensions = new string[] - { + private static readonly string[] KnownFileExtensions = + [ // code files ".cs", ".vb", @@ -33,8 +33,8 @@ internal sealed class AnsiTerminal : ITerminal ".nunit", ".trx", ".xml", - ".xunit", - }; + ".xunit" + ]; private readonly IConsole _console; private readonly string? _baseDirectory; diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/AnsiTerminalTestProgressFrame.cs b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/AnsiTerminalTestProgressFrame.cs index 6489512a6b..71649d1dea 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/AnsiTerminalTestProgressFrame.cs +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/AnsiTerminalTestProgressFrame.cs @@ -308,7 +308,7 @@ private List GenerateLinesToRender(TestProgressState?[] progress) // Note: We want to render the list of active tests, but this can easily fill up the full screen. // As such, we should balance the number of active tests shown per project. // We do this by distributing the remaining lines for each projects. - TestProgressState[] progressItems = progress.OfType().ToArray(); + TestProgressState[] progressItems = [.. progress.OfType()]; int linesToDistribute = (int)(Height * 0.7) - 1 - progressItems.Length; var detailItems = new IEnumerable[progressItems.Length]; IEnumerable sortedItemsIndices = Enumerable.Range(0, progressItems.Length).OrderBy(i => progressItems[i].TestNodeResultsState?.Count ?? 0); @@ -317,7 +317,7 @@ private List GenerateLinesToRender(TestProgressState?[] progress) { detailItems[sortedItemIndex] = progressItems[sortedItemIndex].TestNodeResultsState?.GetRunningTasks( linesToDistribute / progressItems.Length) - ?? Array.Empty(); + ?? []; } for (int progressI = 0; progressI < progressItems.Length; progressI++) diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/ExceptionFlattener.cs b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/ExceptionFlattener.cs index 5e0a406ab8..929a2d6ed4 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/ExceptionFlattener.cs +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/ExceptionFlattener.cs @@ -9,7 +9,7 @@ internal static FlatException[] Flatten(string? errorMessage, Exception? excepti { if (errorMessage is null && exception is null) { - return Array.Empty(); + return []; } string? message = !RoslynString.IsNullOrWhiteSpace(errorMessage) ? errorMessage : exception?.Message; @@ -17,10 +17,7 @@ internal static FlatException[] Flatten(string? errorMessage, Exception? excepti string? stackTrace = exception?.StackTrace; var flatException = new FlatException(message, type, stackTrace); - List flatExceptions = new() - { - flatException, - }; + List flatExceptions = [flatException]; // Add all inner exceptions. This will flatten top level AggregateExceptions, // and all AggregateExceptions that are directly in AggregateExceptions, but won't expand @@ -45,7 +42,7 @@ internal static FlatException[] Flatten(string? errorMessage, Exception? excepti } } - return flatExceptions.ToArray(); + return [.. flatExceptions]; } } diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporter.cs b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporter.cs index 905fc50137..834156bbef 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporter.cs +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporter.cs @@ -15,7 +15,7 @@ internal sealed partial class TerminalTestReporter : IDisposable /// /// The two directory separator characters to be passed to methods like . /// - private static readonly string[] NewLineStrings = { "\r\n", "\n" }; + private static readonly string[] NewLineStrings = ["\r\n", "\n"]; internal const string SingleIndentation = " "; @@ -37,7 +37,7 @@ internal event EventHandler OnProgressStopUpdate private readonly ConcurrentDictionary _assemblies = new(); - private readonly List _artifacts = new(); + private readonly List _artifacts = []; private readonly TerminalTestReporterOptions _options; diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TestNodeResultsState.cs b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TestNodeResultsState.cs index db574dfa97..f14fecc7aa 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TestNodeResultsState.cs +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TestNodeResultsState.cs @@ -45,7 +45,7 @@ public IEnumerable GetRunningTasks(int maxCount) ? string.Format(CultureInfo.CurrentCulture, PlatformResources.ActiveTestsRunning_FullTestsCount, sortedDetails.Count) // If itemsToTake is larger, then we show the project summary, active tests, and the number of active tests that are not shown. : $"... {string.Format(CultureInfo.CurrentCulture, PlatformResources.ActiveTestsRunning_MoreTestsCount, sortedDetails.Count - itemsToTake)}"; - sortedDetails = sortedDetails.Take(itemsToTake).ToList(); + sortedDetails = [.. sortedDetails.Take(itemsToTake)]; } foreach (TestDetailState? detail in sortedDetails) diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TestProgressState.cs b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TestProgressState.cs index afc5d8d7cf..73a8aff848 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TestProgressState.cs +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TestProgressState.cs @@ -27,7 +27,7 @@ public TestProgressState(long id, string assembly, string? targetFramework, stri public IStopwatch Stopwatch { get; } - public List Messages { get; } = new(); + public List Messages { get; } = []; public int FailedTests { get; internal set; } @@ -45,7 +45,7 @@ public TestProgressState(long id, string assembly, string? targetFramework, stri public long Version { get; internal set; } - public List<(string? DisplayName, string? UID)> DiscoveredTests { get; internal set; } = new(); + public List<(string? DisplayName, string? UID)> DiscoveredTests { get; internal set; } = []; internal void AddError(string text) => Messages.Add(new ErrorMessage(text)); diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/TerminalOutputDevice.cs b/src/Platform/Microsoft.Testing.Platform/OutputDevice/TerminalOutputDevice.cs index ac46b81654..30da68d0ef 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/TerminalOutputDevice.cs +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/TerminalOutputDevice.cs @@ -51,7 +51,7 @@ internal sealed partial class TerminalOutputDevice : IHotReloadPlatformOutputDev // The targeted framework, .NET 8 when application specifies net8.0 private readonly string? _targetFramework; private readonly string _assemblyName; - private readonly char[] _dash = new char[] { '-' }; + private readonly char[] _dash = ['-']; private TerminalTestReporter? _terminalTestReporter; private bool _firstCallTo_OnSessionStartingAsync = true; diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/DotnetTestConnection.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/DotnetTestConnection.cs index 8b1d908167..b6cba24fa5 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/DotnetTestConnection.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/DotnetTestConnection.cs @@ -69,7 +69,7 @@ public async Task HelpInvokedAsync() { RoslynDebug.Assert(_dotnetTestPipeClient is not null); - List commandLineHelpOptions = new(); + List commandLineHelpOptions = []; foreach (ICommandLineOptionsProvider commandLineOptionProvider in _commandLineHandler.CommandLineOptionsProviders) { if (commandLineOptionProvider is IToolCommandLineOptionsProvider) @@ -87,7 +87,7 @@ public async Task HelpInvokedAsync() } } - await _dotnetTestPipeClient.RequestReplyAsync(new CommandLineOptionMessages(_testApplicationModuleInfo.GetCurrentTestApplicationFullPath(), commandLineHelpOptions.OrderBy(option => option.Name).ToArray()), _cancellationTokenSource.CancellationToken); + await _dotnetTestPipeClient.RequestReplyAsync(new CommandLineOptionMessages(_testApplicationModuleInfo.GetCurrentTestApplicationFullPath(), [.. commandLineHelpOptions.OrderBy(option => option.Name)]), _cancellationTokenSource.CancellationToken); } public async Task IsCompatibleProtocolAsync(string hostType) diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/DotnetTestDataConsumer.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/DotnetTestDataConsumer.cs index 702a3bd9be..1c23eb623e 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/DotnetTestDataConsumer.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/DotnetTestDataConsumer.cs @@ -21,13 +21,13 @@ public DotnetTestDataConsumer(DotnetTestConnection dotnetTestConnection, IEnviro _environment = environment; } - public Type[] DataTypesConsumed => new[] - { + public Type[] DataTypesConsumed => + [ typeof(TestNodeUpdateMessage), typeof(SessionFileArtifact), typeof(FileArtifact), - typeof(TestRequestExecutionTimeInfo), - }; + typeof(TestRequestExecutionTimeInfo) + ]; public string Uid => nameof(DotnetTestDataConsumer); @@ -59,12 +59,11 @@ public async Task ConsumeAsync(IDataProducer dataProducer, IData value, Cancella DiscoveredTestMessages discoveredTestMessages = new( ExecutionId, DotnetTestConnection.InstanceId, - new[] - { + [ new DiscoveredTestMessage( testNodeUpdateMessage.TestNode.Uid.Value, - testNodeUpdateMessage.TestNode.DisplayName), - }); + testNodeUpdateMessage.TestNode.DisplayName) + ]); await _dotnetTestConnection.SendMessageAsync(discoveredTestMessages); break; @@ -74,8 +73,7 @@ public async Task ConsumeAsync(IDataProducer dataProducer, IData value, Cancella TestResultMessages testResultMessages = new( ExecutionId, DotnetTestConnection.InstanceId, - new[] - { + [ new SuccessfulTestResultMessage( testNodeUpdateMessage.TestNode.Uid.Value, testNodeUpdateMessage.TestNode.DisplayName, @@ -84,9 +82,9 @@ public async Task ConsumeAsync(IDataProducer dataProducer, IData value, Cancella testNodeDetails.Reason ?? string.Empty, testNodeDetails.StandardOutput ?? string.Empty, testNodeDetails.StandardError ?? string.Empty, - testNodeUpdateMessage.SessionUid.Value), - }, - Array.Empty()); + testNodeUpdateMessage.SessionUid.Value) + ], + []); await _dotnetTestConnection.SendMessageAsync(testResultMessages); break; @@ -98,9 +96,8 @@ public async Task ConsumeAsync(IDataProducer dataProducer, IData value, Cancella testResultMessages = new( ExecutionId, DotnetTestConnection.InstanceId, - Array.Empty(), - new[] - { + [], + [ new FailedTestResultMessage( testNodeUpdateMessage.TestNode.Uid.Value, testNodeUpdateMessage.TestNode.DisplayName, @@ -110,8 +107,8 @@ public async Task ConsumeAsync(IDataProducer dataProducer, IData value, Cancella testNodeDetails.Exceptions, testNodeDetails.StandardOutput ?? string.Empty, testNodeDetails.StandardError ?? string.Empty, - testNodeUpdateMessage.SessionUid.Value), - }); + testNodeUpdateMessage.SessionUid.Value) + ]); await _dotnetTestConnection.SendMessageAsync(testResultMessages); break; @@ -122,16 +119,15 @@ public async Task ConsumeAsync(IDataProducer dataProducer, IData value, Cancella FileArtifactMessages testFileArtifactMessages = new( ExecutionId, DotnetTestConnection.InstanceId, - new[] - { - new FileArtifactMessage( - artifact.FileInfo.FullName, - artifact.DisplayName, - artifact.Description ?? string.Empty, - testNodeUpdateMessage.TestNode.Uid.Value, - testNodeUpdateMessage.TestNode.DisplayName, - testNodeUpdateMessage.SessionUid.Value), - }); + [ + new FileArtifactMessage( + artifact.FileInfo.FullName, + artifact.DisplayName, + artifact.Description ?? string.Empty, + testNodeUpdateMessage.TestNode.Uid.Value, + testNodeUpdateMessage.TestNode.DisplayName, + testNodeUpdateMessage.SessionUid.Value) + ]); await _dotnetTestConnection.SendMessageAsync(testFileArtifactMessages); } @@ -142,16 +138,15 @@ public async Task ConsumeAsync(IDataProducer dataProducer, IData value, Cancella var fileArtifactMessages = new FileArtifactMessages( ExecutionId, DotnetTestConnection.InstanceId, - new[] - { + [ new FileArtifactMessage( sessionFileArtifact.FileInfo.FullName, sessionFileArtifact.DisplayName, sessionFileArtifact.Description ?? string.Empty, string.Empty, string.Empty, - sessionFileArtifact.SessionUid.Value), - }); + sessionFileArtifact.SessionUid.Value) + ]); await _dotnetTestConnection.SendMessageAsync(fileArtifactMessages); break; @@ -160,16 +155,15 @@ public async Task ConsumeAsync(IDataProducer dataProducer, IData value, Cancella fileArtifactMessages = new( ExecutionId, DotnetTestConnection.InstanceId, - new[] - { + [ new FileArtifactMessage( fileArtifact.FileInfo.FullName, fileArtifact.DisplayName, fileArtifact.Description ?? string.Empty, string.Empty, string.Empty, - string.Empty), - }); + string.Empty) + ]); await _dotnetTestConnection.SendMessageAsync(fileArtifactMessages); break; diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Serializers/HandshakeMessageSerializer.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Serializers/HandshakeMessageSerializer.cs index 9940477af9..9571f8f7a4 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Serializers/HandshakeMessageSerializer.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Serializers/HandshakeMessageSerializer.cs @@ -11,7 +11,7 @@ internal sealed class HandshakeMessageSerializer : BaseSerializer, INamedPipeSer public object Deserialize(Stream stream) { - Dictionary properties = new(); + Dictionary properties = []; ushort fieldCount = ReadShort(stream); diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Serializers/TestResultMessagesSerializer.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Serializers/TestResultMessagesSerializer.cs index 4472ddbaea..3bc7cc8965 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Serializers/TestResultMessagesSerializer.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Serializers/TestResultMessagesSerializer.cs @@ -323,7 +323,7 @@ private static ExceptionMessage[] ReadExceptionMessagesPayload(Stream stream) exceptionMessages.Add(new ExceptionMessage(errorMessage, errorType, stackTrace)); } - return exceptionMessages.ToArray(); + return [.. exceptionMessages]; } public void Serialize(object objectToSerialize, Stream stream) diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/FormatterUtilities.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/FormatterUtilities.cs index 0e540ef32e..f5a40ec03f 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/FormatterUtilities.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/FormatterUtilities.cs @@ -34,13 +34,13 @@ internal sealed class MessageFormatter : IMessageFormatter public MessageFormatter() { - Dictionary serializers = new(); - Dictionary deserializers = new(); + Dictionary serializers = []; + Dictionary deserializers = []; foreach (Type serializableType in SerializerUtilities.SerializerTypes) { serializers[serializableType] = new JsonObjectSerializer( - o => SerializerUtilities.Serialize(serializableType, o).Select(kvp => (kvp.Key, kvp.Value)).ToArray()); + o => [.. SerializerUtilities.Serialize(serializableType, o).Select(kvp => (kvp.Key, kvp.Value))]); } foreach (Type deserializableType in SerializerUtilities.DeserializerTypes) diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/Json/Json.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/Json/Json.cs index 43bf9d41bd..c6a35fe518 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/Json/Json.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/Json/Json.cs @@ -19,28 +19,27 @@ public Json(Dictionary? serializers = null, Dictionary(request => new[] - { - (JsonRpcStrings.JsonRpc, "2.0"), + _serializers[typeof(RequestMessage)] = new JsonObjectSerializer(request => + [ + (JsonRpcStrings.JsonRpc, "2.0"), (JsonRpcStrings.Id, request.Id), (JsonRpcStrings.Method, request.Method), - (JsonRpcStrings.Params, request.Params), - }); + (JsonRpcStrings.Params, request.Params) + ]); - _serializers[typeof(ResponseMessage)] = new JsonObjectSerializer(response => new[] - { - (JsonRpcStrings.JsonRpc, "2.0"), + _serializers[typeof(ResponseMessage)] = new JsonObjectSerializer(response => + [ + (JsonRpcStrings.JsonRpc, "2.0"), (JsonRpcStrings.Id, response.Id), - (JsonRpcStrings.Result, response.Result), - }); + (JsonRpcStrings.Result, response.Result) + ]); _serializers[typeof(NotificationMessage)] = new JsonObjectSerializer(notification => - new[] - { - (JsonRpcStrings.JsonRpc, "2.0"), + [ + (JsonRpcStrings.JsonRpc, "2.0"), (JsonRpcStrings.Method, notification.Method), - (JsonRpcStrings.Params, notification.Params), - }); + (JsonRpcStrings.Params, notification.Params) + ]); _serializers[typeof(ErrorMessage)] = new JsonObjectSerializer(error => { @@ -51,76 +50,69 @@ public Json(Dictionary? serializers = null, Dictionary(response => - new (string, object?)[] - { - (JsonRpcStrings.ProcessId, response.ProcessId), + [ + (JsonRpcStrings.ProcessId, response.ProcessId), (JsonRpcStrings.ServerInfo, response.ServerInfo), - (JsonRpcStrings.Capabilities, response.Capabilities), - }); + (JsonRpcStrings.Capabilities, response.Capabilities) + ]); - _serializers[typeof(ServerInfo)] = new JsonObjectSerializer(info => new (string, object?)[] - { - (JsonRpcStrings.Name, info.Name), - (JsonRpcStrings.Version, info.Version), - }); + _serializers[typeof(ServerInfo)] = new JsonObjectSerializer(info => + [ + (JsonRpcStrings.Name, info.Name), + (JsonRpcStrings.Version, info.Version) + ]); _serializers[typeof(ServerCapabilities)] = new JsonObjectSerializer(capabilities => - new (string, object?)[] - { - (JsonRpcStrings.Testing, capabilities.TestingCapabilities), - }); + [ + (JsonRpcStrings.Testing, capabilities.TestingCapabilities) + ]); _serializers[typeof(ServerTestingCapabilities)] = new JsonObjectSerializer(capabilities => - new (string, object?)[] - { - (JsonRpcStrings.SupportsDiscovery, capabilities.SupportsDiscovery), + [ + (JsonRpcStrings.SupportsDiscovery, capabilities.SupportsDiscovery), (JsonRpcStrings.MultiRequestSupport, capabilities.MultiRequestSupport), (JsonRpcStrings.VSTestProviderSupport, capabilities.VSTestProviderSupport), (JsonRpcStrings.AttachmentsSupport, capabilities.SupportsAttachments), - (JsonRpcStrings.MultiConnectionProvider, capabilities.MultiConnectionProvider), - }); + (JsonRpcStrings.MultiConnectionProvider, capabilities.MultiConnectionProvider) + ]); _serializers[typeof(Artifact)] = new JsonObjectSerializer(artifact => - new (string, object?)[] - { - (JsonRpcStrings.Uri, artifact.Uri), + [ + (JsonRpcStrings.Uri, artifact.Uri), (JsonRpcStrings.Producer, artifact.Producer), (JsonRpcStrings.Type, artifact.Type), (JsonRpcStrings.DisplayName, artifact.DisplayName), - (JsonRpcStrings.Description, artifact.Description), - }); + (JsonRpcStrings.Description, artifact.Description) + ]); _serializers[typeof(DiscoverResponseArgs)] = new JsonObjectSerializer(response => []); _serializers[typeof(RunResponseArgs)] = new JsonObjectSerializer(response => - new (string, object?)[] - { - (JsonRpcStrings.Attachments, response.Artifacts), - }); + [ + (JsonRpcStrings.Attachments, response.Artifacts) + ]); _serializers[typeof(TestNodeUpdateMessage)] = new JsonObjectSerializer(message => - new (string, object?)[] - { - (JsonRpcStrings.Node, message.TestNode), - (JsonRpcStrings.Parent, message.ParentTestNodeUid?.Value), - }); + [ + (JsonRpcStrings.Node, message.TestNode), + (JsonRpcStrings.Parent, message.ParentTestNodeUid?.Value) + ]); _serializers[typeof(TestNodeStateChangedEventArgs)] = new JsonObjectSerializer(message => - new (string, object?)[] - { - (JsonRpcStrings.RunId, message.RunId), - (JsonRpcStrings.Changes, message.Changes), - }); + [ + (JsonRpcStrings.RunId, message.RunId), + (JsonRpcStrings.Changes, message.Changes) + ]); _serializers[typeof(TestNode)] = new JsonObjectSerializer(message => { @@ -299,59 +291,52 @@ public Json(Dictionary? serializers = null, Dictionary(message => - new (string, object?)[] - { - (JsonRpcStrings.Level, message.LogMessage.Level.ToString()), - (JsonRpcStrings.Message, message.LogMessage.Message), - }); + [ + (JsonRpcStrings.Level, message.LogMessage.Level.ToString()), + (JsonRpcStrings.Message, message.LogMessage.Message) + ]); _serializers[typeof(CancelRequestArgs)] = new JsonObjectSerializer(request => - new (string, object?)[] - { - (JsonRpcStrings.Id, request.CancelRequestId), - }); + [ + (JsonRpcStrings.Id, request.CancelRequestId) + ]); _serializers[typeof(TelemetryEventArgs)] = new JsonObjectSerializer(ev => - new (string, object?)[] - { - (JsonRpcStrings.EventName, ev.EventName), - (JsonRpcStrings.Metrics, ev.Metrics), - }); + [ + (JsonRpcStrings.EventName, ev.EventName), + (JsonRpcStrings.Metrics, ev.Metrics) + ]); _serializers[typeof(ProcessInfoArgs)] = new JsonObjectSerializer(info => - new (string, object?)[] - { - (JsonRpcStrings.Program, info.Program), + [ + (JsonRpcStrings.Program, info.Program), (JsonRpcStrings.Args, info.Args), (JsonRpcStrings.WorkingDirectory, info.WorkingDirectory), - (JsonRpcStrings.EnvironmentVariables, info.EnvironmentVariables), - }); + (JsonRpcStrings.EnvironmentVariables, info.EnvironmentVariables) + ]); _serializers[typeof(AttachDebuggerInfoArgs)] = new JsonObjectSerializer(info => - new (string, object?)[] - { - (JsonRpcStrings.ProcessId, info.ProcessId), - }); + [ + (JsonRpcStrings.ProcessId, info.ProcessId) + ]); _serializers[typeof(TestsAttachments)] = new JsonObjectSerializer(info => - new (string, object?)[] - { - (JsonRpcStrings.Attachments, info.Attachments), - }); + [ + (JsonRpcStrings.Attachments, info.Attachments) + ]); _serializers[typeof(RunTestAttachment)] = new JsonObjectSerializer(info => - new (string, object?)[] - { - (JsonRpcStrings.Uri, info.Uri), + [ + (JsonRpcStrings.Uri, info.Uri), (JsonRpcStrings.Producer, info.Producer), (JsonRpcStrings.Type, info.Type), (JsonRpcStrings.DisplayName, info.DisplayName), - (JsonRpcStrings.Description, info.Description), - }); + (JsonRpcStrings.Description, info.Description) + ]); // Serializers _serializers[typeof(string)] = new JsonValueSerializer((w, v) => w.WriteStringValue(v)); @@ -368,7 +353,7 @@ public Json(Dictionary? serializers = null, Dictionary((w, v) => w.WriteStringValue(v.ToString())); // Remove for now _serializers[typeof((string, object?)[])] = new JsonObjectSerializer<(string, object?)[]>(n => n); - _serializers[typeof(Dictionary)] = new JsonObjectSerializer>(d => d.Select(kvp => (kvp.Key, (object?)kvp.Value)).ToArray()); + _serializers[typeof(Dictionary)] = new JsonObjectSerializer>(d => [.. d.Select(kvp => (kvp.Key, (object?)kvp.Value))]); // Deserializers _deserializers[typeof(string)] = new JsonElementDeserializer((json, jsonDocument) => jsonDocument.GetString()!); @@ -379,7 +364,7 @@ public Json(Dictionary? serializers = null, Dictionary)] = new JsonElementDeserializer>((json, jsonDocument) => { - Dictionary items = new(); + Dictionary items = []; foreach (JsonProperty kvp in jsonDocument.EnumerateObject()) { switch (kvp.Value.ValueKind) @@ -672,7 +657,7 @@ internal bool TryArrayBind(JsonElement element, out T[]? value, string? prope return false; } - value = element.EnumerateArray().Select(Deserialize).ToArray(); + value = [.. element.EnumerateArray().Select(Deserialize)]; return true; } diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/ServerModePerCallOutputDevice.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/ServerModePerCallOutputDevice.cs index 1ae054fcbd..d15e47b46f 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/ServerModePerCallOutputDevice.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/ServerModePerCallOutputDevice.cs @@ -15,11 +15,11 @@ internal sealed class ServerModePerCallOutputDevice : IPlatformOutputDevice, IOu { private readonly FileLoggerProvider? _fileLoggerProvider; private readonly IStopPoliciesService _policiesService; - private readonly ConcurrentBag _messages = new(); + private readonly ConcurrentBag _messages = []; private IServerTestHost? _serverTestHost; - private static readonly string[] NewLineStrings = { "\r\n", "\n" }; + private static readonly string[] NewLineStrings = ["\r\n", "\n"]; public ServerModePerCallOutputDevice(FileLoggerProvider? fileLoggerProvider, IStopPoliciesService policiesService) { diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/TestNodeStateChangeAggregator.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/TestNodeStateChangeAggregator.cs index 0c26a1c096..91a23ad4f7 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/TestNodeStateChangeAggregator.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/TestNodeStateChangeAggregator.cs @@ -29,6 +29,6 @@ public void OnStateChange(TestNodeUpdateMessage stateChangedMessage) => _stateChanges.Add(stateChangedMessage); public TestNodeStateChangedEventArgs BuildAggregatedChange() - => new(RunId, _stateChanges.ToArray()); + => new(RunId, [.. _stateChanges]); } } diff --git a/src/Platform/Microsoft.Testing.Platform/Services/StopPoliciesService.cs b/src/Platform/Microsoft.Testing.Platform/Services/StopPoliciesService.cs index c69e617b8a..79a71c1489 100644 --- a/src/Platform/Microsoft.Testing.Platform/Services/StopPoliciesService.cs +++ b/src/Platform/Microsoft.Testing.Platform/Services/StopPoliciesService.cs @@ -31,7 +31,7 @@ public StopPoliciesService(ITestApplicationCancellationTokenSource testApplicati private static void RegisterCallback(ref BlockingCollection? callbacks, T callback) #pragma warning disable CA1416 // Validate platform compatibility - => (callbacks ??= new()).Add(callback); + => (callbacks ??= []).Add(callback); #pragma warning restore CA1416 public async Task ExecuteMaxFailedTestsCallbacksAsync(int maxFailedTests, CancellationToken cancellationToken) diff --git a/src/Platform/Microsoft.Testing.Platform/TestHost/TestHostManager.cs b/src/Platform/Microsoft.Testing.Platform/TestHost/TestHostManager.cs index 684e3cfeec..a9a6f7ce61 100644 --- a/src/Platform/Microsoft.Testing.Platform/TestHost/TestHostManager.cs +++ b/src/Platform/Microsoft.Testing.Platform/TestHost/TestHostManager.cs @@ -118,7 +118,7 @@ internal async Task BuildTestApplicationLi } } - return testApplicationLifecycleCallbacks.ToArray(); + return [.. testApplicationLifecycleCallbacks]; } public void AddDataConsumer(Func dataConsumerFactory) @@ -212,7 +212,7 @@ public void AddDataConsumer(CompositeExtensionFactory compositeServiceFact } } - return dataConsumers.ToArray(); + return [.. dataConsumers]; } public void AddTestSessionLifetimeHandle(Func testSessionLifetimeHandleFactory) @@ -307,6 +307,6 @@ public void AddTestSessionLifetimeHandle(CompositeExtensionFactory composi } } - return testSessionLifetimeHandlers.ToArray(); + return [.. testSessionLifetimeHandlers]; } } diff --git a/src/Platform/Microsoft.Testing.Platform/TestHostControllers/TestHostControllersManager.cs b/src/Platform/Microsoft.Testing.Platform/TestHostControllers/TestHostControllersManager.cs index f04985b9db..3422551b69 100644 --- a/src/Platform/Microsoft.Testing.Platform/TestHostControllers/TestHostControllersManager.cs +++ b/src/Platform/Microsoft.Testing.Platform/TestHostControllers/TestHostControllersManager.cs @@ -286,9 +286,9 @@ internal async Task BuildAsync(ServiceProvider bool requireProcessRestart = environmentVariableProviders.Count > 0 || lifetimeHandlers.Count > 0 || dataConsumers.Count > 0; return new TestHostControllerConfiguration( - environmentVariableProviders.OrderBy(x => x.RegistrationOrder).Select(x => x.TestHostEnvironmentVariableProvider).ToArray(), - lifetimeHandlers.OrderBy(x => x.RegistrationOrder).Select(x => x.TestHostProcessLifetimeHandler).ToArray(), - dataConsumers.OrderBy(x => x.RegistrationOrder).Select(x => x.Consumer).ToArray(), + [.. environmentVariableProviders.OrderBy(x => x.RegistrationOrder).Select(x => x.TestHostEnvironmentVariableProvider)], + [.. lifetimeHandlers.OrderBy(x => x.RegistrationOrder).Select(x => x.TestHostProcessLifetimeHandler)], + [.. dataConsumers.OrderBy(x => x.RegistrationOrder).Select(x => x.Consumer)], requireProcessRestart); } } diff --git a/src/Platform/Microsoft.Testing.Platform/TestHostOrcherstrator/TestHostOrchestratorManager.cs b/src/Platform/Microsoft.Testing.Platform/TestHostOrcherstrator/TestHostOrchestratorManager.cs index d6f7a628bf..a4015025af 100644 --- a/src/Platform/Microsoft.Testing.Platform/TestHostOrcherstrator/TestHostOrchestratorManager.cs +++ b/src/Platform/Microsoft.Testing.Platform/TestHostOrcherstrator/TestHostOrchestratorManager.cs @@ -46,6 +46,6 @@ public async Task BuildAsync(ServiceProvider } } - return new TestHostOrchestratorConfiguration(orchestrators.ToArray()); + return new TestHostOrchestratorConfiguration([.. orchestrators]); } } diff --git a/src/TestFramework/TestFramework/Attributes/DataSource/DynamicDataOperations.cs b/src/TestFramework/TestFramework/Attributes/DataSource/DynamicDataOperations.cs index 1c91754b59..664e9bad37 100644 --- a/src/TestFramework/TestFramework/Attributes/DataSource/DynamicDataOperations.cs +++ b/src/TestFramework/TestFramework/Attributes/DataSource/DynamicDataOperations.cs @@ -115,7 +115,7 @@ private static bool TryGetData(object dataSource, [NotNullWhen(true)] out IEnume if (dataSource is IEnumerable enumerable and not string) { - List objects = new(); + List objects = []; foreach (object? entry in enumerable) { if (entry is null) @@ -124,7 +124,7 @@ private static bool TryGetData(object dataSource, [NotNullWhen(true)] out IEnume return false; } - objects.Add(new[] { entry }); + objects.Add([entry]); } data = objects; diff --git a/src/TestFramework/TestFramework/Attributes/TestMethod/RetryResult.cs b/src/TestFramework/TestFramework/Attributes/TestMethod/RetryResult.cs index 60dc976cf9..855893fc95 100644 --- a/src/TestFramework/TestFramework/Attributes/TestMethod/RetryResult.cs +++ b/src/TestFramework/TestFramework/Attributes/TestMethod/RetryResult.cs @@ -9,7 +9,7 @@ namespace Microsoft.VisualStudio.TestTools.UnitTesting; [Experimental("MSTESTEXP", UrlFormat = "https://aka.ms/mstest/diagnostics#{0}")] public sealed class RetryResult { - private readonly List _testResults = new(); + private readonly List _testResults = []; /// /// Adds a set of test results to the retry result. diff --git a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/SdkTests.cs b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/SdkTests.cs index 3260b69c61..4d6885fd96 100644 --- a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/SdkTests.cs +++ b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/SdkTests.cs @@ -428,7 +428,7 @@ public async Task SettingIsTestApplicationToFalseReducesAddedExtensionsAndMakesP SL.Build binLog = SL.Serialization.Read(compilationResult.BinlogPath!); SL.Task cscTask = binLog.FindChildrenRecursive(task => task.Name == "Csc").Single(); - SL.Item[] references = cscTask.FindChildrenRecursive(p => p.Name == "References").Single().Children.OfType().ToArray(); + SL.Item[] references = [.. cscTask.FindChildrenRecursive(p => p.Name == "References").Single().Children.OfType()]; // Ensure that MSTest.Framework is referenced Assert.IsTrue(references.Any(r => r.Text.EndsWith("Microsoft.VisualStudio.TestPlatform.TestFramework.dll", StringComparison.OrdinalIgnoreCase))); diff --git a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/ServerModeTests.cs b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/ServerModeTests.cs index b79c30d152..1405d7ad71 100644 --- a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/ServerModeTests.cs +++ b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/ServerModeTests.cs @@ -16,9 +16,9 @@ public sealed class ServerModeTests : ServerModeTestsBase testResults = await RunTestsAsync(testCases); // Assert - VerifyE2E.ContainsTestsFailed(testResults, new string[] { null! }); + VerifyE2E.ContainsTestsFailed(testResults, [null!]); } public async Task AssertExtensibilityTests() diff --git a/test/IntegrationTests/MSTest.IntegrationTests/Utilities/CLITestBase.discovery.cs b/test/IntegrationTests/MSTest.IntegrationTests/Utilities/CLITestBase.discovery.cs index 7cf6b875ab..4b9b678643 100644 --- a/test/IntegrationTests/MSTest.IntegrationTests/Utilities/CLITestBase.discovery.cs +++ b/test/IntegrationTests/MSTest.IntegrationTests/Utilities/CLITestBase.discovery.cs @@ -54,7 +54,7 @@ private sealed class InternalSink : ITestCaseDiscoverySink { private readonly List _testCases = []; - public ImmutableArray DiscoveredTests => _testCases.ToImmutableArray(); + public ImmutableArray DiscoveredTests => [.. _testCases]; public void SendTestCase(TestCase discoveredTest) => _testCases.Add(discoveredTest); } @@ -92,11 +92,11 @@ private sealed class InternalFrameworkHandle : IFrameworkHandle private readonly List _messageList = []; private readonly ConcurrentDictionary> _testResults = new(); - private ConcurrentBag _activeResults = new(); + private ConcurrentBag _activeResults = []; public bool EnableShutdownAfterTestRun { get; set; } - public void RecordStart(TestCase testCase) => _activeResults = _testResults.GetOrAdd(testCase, _ => new()); + public void RecordStart(TestCase testCase) => _activeResults = _testResults.GetOrAdd(testCase, _ => []); public void RecordEnd(TestCase testCase, TestOutcome outcome) => _activeResults = _testResults[testCase]; diff --git a/test/IntegrationTests/MSTest.IntegrationTests/Utilities/TestCaseFilterFactory.cs b/test/IntegrationTests/MSTest.IntegrationTests/Utilities/TestCaseFilterFactory.cs index ef809a9bb7..8c4d4f96dd 100644 --- a/test/IntegrationTests/MSTest.IntegrationTests/Utilities/TestCaseFilterFactory.cs +++ b/test/IntegrationTests/MSTest.IntegrationTests/Utilities/TestCaseFilterFactory.cs @@ -288,7 +288,7 @@ private static bool ContainsComparer(string[] values, string value) { Guard.NotNull(conditionString); - string[] condition = TokenizeCondition(conditionString).ToArray(); + string[] condition = [.. TokenizeCondition(conditionString)]; Expression parameterName, expectedValue, parameterValueProvider, expression; string op; diff --git a/test/IntegrationTests/MSTest.VstestConsoleWrapper.IntegrationTests/TimeoutTests.cs b/test/IntegrationTests/MSTest.VstestConsoleWrapper.IntegrationTests/TimeoutTests.cs index b7e513c82b..d48e07480c 100644 --- a/test/IntegrationTests/MSTest.VstestConsoleWrapper.IntegrationTests/TimeoutTests.cs +++ b/test/IntegrationTests/MSTest.VstestConsoleWrapper.IntegrationTests/TimeoutTests.cs @@ -34,7 +34,7 @@ private void ValidateTimeoutTests(string targetFramework) failedTests.Add("TimeoutTestProject.TimeoutTestClass.TimeoutTest_WhenUserCallsThreadAbort_AbortTest"); } - ValidateFailedTestsContain(false, failedTests.ToArray()); + ValidateFailedTestsContain(false, [.. failedTests]); // We should find the /TimeoutTestOutput.txt file, as it's our way to validate // that when the timeout expires it cancels the test context token. diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/ExitOnProcessExitTests.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/ExitOnProcessExitTests.cs index 8e7ae8bb7f..060a342a1a 100644 --- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/ExitOnProcessExitTests.cs +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/ExitOnProcessExitTests.cs @@ -25,7 +25,7 @@ public void ExitOnProcessExit_Succeed(string tfm) Thread.Sleep(500); // Look for the pid file created by the test host. - string[] pidFile = Directory.GetFiles(Path.GetDirectoryName(testHost.FullName)!, "PID").ToArray(); + string[] pidFile = [.. Directory.GetFiles(Path.GetDirectoryName(testHost.FullName)!, "PID")]; if (pidFile.Length > 0) { string pid = File.ReadAllText(pidFile[0]); diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/Helpers/AcceptanceTestBase.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/Helpers/AcceptanceTestBase.cs index 2c3afc4387..ee62060cb3 100644 --- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/Helpers/AcceptanceTestBase.cs +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/Helpers/AcceptanceTestBase.cs @@ -180,14 +180,13 @@ private static string ExtractVersionFromPackage(string rootFolder, string packag // Microsoft.Testing.Platform.Extensions.1.0.0.nupkg // So we need to find a package that contains a number after the prefix. // Ideally, we would want to do a full validation to check this is a nuget version number, but that's too much work for now. - matches = matches + matches = [.. matches // (full path, file name without prefix) .Select(path => (path, fileName: Path.GetFileName(path)[packagePrefixName.Length..])) // check if first character of file name without prefix is number .Where(tuple => int.TryParse(tuple.fileName[0].ToString(), CultureInfo.InvariantCulture, out _)) // take the full path - .Select(tuple => tuple.path) - .ToArray(); + .Select(tuple => tuple.path)]; } if (matches.Length != 1) diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/RetryFailedTestsTests.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/RetryFailedTestsTests.cs index d971231e9b..c4f229af9d 100644 --- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/RetryFailedTestsTests.cs +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/RetryFailedTestsTests.cs @@ -158,9 +158,7 @@ await RetryHelper.RetryAsync( testHostResult.AssertExitCodeIs(ExitCodes.TestHostProcessExitedNonGracefully); - string[] entries = Directory.GetFiles(resultDirectory, "*.*", SearchOption.AllDirectories) - .Where(x => !x.Contains("Retries", StringComparison.OrdinalIgnoreCase)) - .ToArray(); + string[] entries = [.. Directory.GetFiles(resultDirectory, "*.*", SearchOption.AllDirectories).Where(x => !x.Contains("Retries", StringComparison.OrdinalIgnoreCase))]; // 1 trx file Assert.AreEqual(1, entries.Count(x => x.EndsWith("trx", StringComparison.OrdinalIgnoreCase))); diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/ServerLoggingTests.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/ServerLoggingTests.cs index 3bfd65e5ea..16c19ea78a 100644 --- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/ServerLoggingTests.cs +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/ServerLoggingTests.cs @@ -17,7 +17,7 @@ public async Task RunningInServerJsonRpcModeShouldHaveOutputDeviceLogsPushedToTe string resultDirectory = Path.Combine(AssetFixture.TargetAssetPath, Guid.NewGuid().ToString("N"), tfm); var testHost = TestInfrastructure.TestHost.LocateFrom(AssetFixture.TargetAssetPath, "ServerLoggingTests", tfm); using TestingPlatformClient jsonClient = await StartAsServerAndConnectToTheClientAsync(testHost); - LogsCollector logs = new(); + LogsCollector logs = []; jsonClient.RegisterLogListener(logs); InitializeResponse initializeResponseArgs = await jsonClient.Initialize(); diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/ServerMode/TestNodeUpdateCollector.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/ServerMode/TestNodeUpdateCollector.cs index 4df559bc05..18efef8eae 100644 --- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/ServerMode/TestNodeUpdateCollector.cs +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/ServerMode/TestNodeUpdateCollector.cs @@ -10,7 +10,7 @@ public class TestNodeUpdateCollector private readonly TaskCompletionSource _taskCompletionSource = new(); private readonly Func? _completeCollector; - public ConcurrentBag TestNodeUpdates { get; } = new(); + public ConcurrentBag TestNodeUpdates { get; } = []; public TestNodeUpdateCollector(Func? completeCollectorWhen = null) => _completeCollector = completeCollectorWhen; diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/ServerMode/v1.0.0/TestingPlatformClient.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/ServerMode/v1.0.0/TestingPlatformClient.cs index 6dda46477f..e1abd7b78a 100644 --- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/ServerMode/v1.0.0/TestingPlatformClient.cs +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/ServerMode/v1.0.0/TestingPlatformClient.cs @@ -157,14 +157,11 @@ public record Log(LogLevel LogLevel, string Message); private sealed class TargetHandler { - private readonly ConcurrentDictionary _listeners - = new(); + private readonly ConcurrentDictionary _listeners = new(); - private readonly ConcurrentBag _logListeners - = new(); + private readonly ConcurrentBag _logListeners = []; - private readonly ConcurrentBag _telemetryPayloads - = new(); + private readonly ConcurrentBag _telemetryPayloads = []; public void RegisterTelemetryListener(TelemetryCollector listener) => _telemetryPayloads.Add(listener); diff --git a/test/IntegrationTests/PlatformServices.Desktop.IntegrationTests/ReflectionUtilityTests.cs b/test/IntegrationTests/PlatformServices.Desktop.IntegrationTests/ReflectionUtilityTests.cs index 4e2ee52753..bb1425fb6d 100644 --- a/test/IntegrationTests/PlatformServices.Desktop.IntegrationTests/ReflectionUtilityTests.cs +++ b/test/IntegrationTests/PlatformServices.Desktop.IntegrationTests/ReflectionUtilityTests.cs @@ -275,6 +275,6 @@ private static string[] GetAttributeValuePairs(IEnumerable attributes) } } - return attributeValuePairs.ToArray(); + return [.. attributeValuePairs]; } } diff --git a/test/IntegrationTests/TestAssets/DataRowTestProject/DataRowTests_OverriddenGetDisplayName.cs b/test/IntegrationTests/TestAssets/DataRowTestProject/DataRowTests_OverriddenGetDisplayName.cs index b8c2e49da3..bcd6a6bffc 100644 --- a/test/IntegrationTests/TestAssets/DataRowTestProject/DataRowTests_OverriddenGetDisplayName.cs +++ b/test/IntegrationTests/TestAssets/DataRowTestProject/DataRowTests_OverriddenGetDisplayName.cs @@ -34,7 +34,7 @@ public static IEnumerable Data { get { - yield return new object[] { "SomeData" }; + yield return ["SomeData"]; } } } diff --git a/test/IntegrationTests/TestAssets/DataRowTestProject/DataRowTests_Regular.cs b/test/IntegrationTests/TestAssets/DataRowTestProject/DataRowTests_Regular.cs index 6f6e1ae3ef..cf397b5972 100644 --- a/test/IntegrationTests/TestAssets/DataRowTestProject/DataRowTests_Regular.cs +++ b/test/IntegrationTests/TestAssets/DataRowTestProject/DataRowTests_Regular.cs @@ -68,7 +68,9 @@ public void NullValueInData(string email, string password, string returnUrl) public void NullValue(object o) => Assert.IsNull(o); [TestMethod] - [DataRow(new string[] { "" })] +#pragma warning disable SA1122 // Use string.Empty for empty strings + [DataRow([""])] +#pragma warning restore SA1122 // Use string.Empty for empty strings public void OneStringArray(string[] lines) => Assert.AreEqual(1, lines.Length); [TestMethod] @@ -80,7 +82,9 @@ public void TwoStringArrays(string[] input1, string[] input2) } [TestMethod] - [DataRow(new object[] { "", 1 })] +#pragma warning disable SA1122 // Use string.Empty for empty strings + [DataRow(["", 1])] +#pragma warning restore SA1122 // Use string.Empty for empty strings public void OneObjectArray(object[] objects) => Assert.AreEqual(2, objects.Length); [TestMethod] diff --git a/test/IntegrationTests/TestAssets/DynamicDataTestProject/DisableExpansionTests.cs b/test/IntegrationTests/TestAssets/DynamicDataTestProject/DisableExpansionTests.cs index c22a047e3f..97f8dc09f4 100644 --- a/test/IntegrationTests/TestAssets/DynamicDataTestProject/DisableExpansionTests.cs +++ b/test/IntegrationTests/TestAssets/DynamicDataTestProject/DisableExpansionTests.cs @@ -50,8 +50,8 @@ public void TestPropertyWithTwoSourcesAndSecondDisablesExpansion(int a, string s private static IEnumerable MethodSource() { - yield return new object[] { 1, "a" }; - yield return new object[] { 2, "b" }; + yield return [1, "a"]; + yield return [2, "b"]; } } @@ -61,7 +61,7 @@ public class DataSourceHelper public static IEnumerable MethodSource() { - yield return new object[] { 3, "c" }; - yield return new object[] { 4, "d" }; + yield return [3, "c"]; + yield return [4, "d"]; } } diff --git a/test/IntegrationTests/TestAssets/DynamicDataTestProject/DynamicDataTests.cs b/test/IntegrationTests/TestAssets/DynamicDataTestProject/DynamicDataTests.cs index 8fdeb44f88..5e0149815c 100644 --- a/test/IntegrationTests/TestAssets/DynamicDataTestProject/DynamicDataTests.cs +++ b/test/IntegrationTests/TestAssets/DynamicDataTestProject/DynamicDataTests.cs @@ -253,14 +253,14 @@ public class ExampleTestCase private static IEnumerable StringAndInt32() { - yield return new object[] { "1", 1 }; - yield return new object[] { "2", 1 }; + yield return ["1", 1]; + yield return ["2", 1]; } private static IEnumerable Int32AndString() { - yield return new object[] { 1, "0" }; - yield return new object[] { 2, "2" }; + yield return [1, "0"]; + yield return [2, "2"]; } private static IEnumerable SimpleCollection diff --git a/test/IntegrationTests/TestAssets/FxExtensibilityTestProject/CustomTestExTests.cs b/test/IntegrationTests/TestAssets/FxExtensibilityTestProject/CustomTestExTests.cs index fe39499599..48d882ece8 100644 --- a/test/IntegrationTests/TestAssets/FxExtensibilityTestProject/CustomTestExTests.cs +++ b/test/IntegrationTests/TestAssets/FxExtensibilityTestProject/CustomTestExTests.cs @@ -53,7 +53,7 @@ public override TestResult[] Execute(ITestMethod testMethod) results.AddRange(testResults); } - return results.ToArray(); + return [.. results]; } } diff --git a/test/Performance/MSTest.Performance.Runner/Context.cs b/test/Performance/MSTest.Performance.Runner/Context.cs index a3bd69a829..ab4a7a76d3 100644 --- a/test/Performance/MSTest.Performance.Runner/Context.cs +++ b/test/Performance/MSTest.Performance.Runner/Context.cs @@ -5,13 +5,13 @@ namespace MSTest.Performance.Runner; internal class Context : IContext, IDisposable { - private List _disposables = new(); + private List _disposables = []; public IDictionary Properties { get; private set; } = new Dictionary(); public void Init(IDictionary properties) { - _disposables = new(); + _disposables = []; Properties = properties; } diff --git a/test/Performance/MSTest.Performance.Runner/PipelinesRunner.cs b/test/Performance/MSTest.Performance.Runner/PipelinesRunner.cs index bcc2153539..ad75d304d4 100644 --- a/test/Performance/MSTest.Performance.Runner/PipelinesRunner.cs +++ b/test/Performance/MSTest.Performance.Runner/PipelinesRunner.cs @@ -7,7 +7,7 @@ namespace MSTest.Performance.Runner; internal class PipelinesRunner { - private readonly List _pipelines = new(); + private readonly List _pipelines = []; public void AddPipeline(string groupName, string pipelineName, OSPlatform[] oSPlatform, Action> func, Action>? updatePropertyBag = null, string[]? traits = null) => _pipelines.Add(new PipelineInfo(groupName, pipelineName, oSPlatform, func, updatePropertyBag, traits)); diff --git a/test/Performance/MSTest.Performance.Runner/Steps/PlainProcess.cs b/test/Performance/MSTest.Performance.Runner/Steps/PlainProcess.cs index b1f1af50d9..691ffb6a74 100644 --- a/test/Performance/MSTest.Performance.Runner/Steps/PlainProcess.cs +++ b/test/Performance/MSTest.Performance.Runner/Steps/PlainProcess.cs @@ -36,7 +36,7 @@ public async Task ExecuteAsync(BuildArtifact payload, IContext context) Console.WriteLine($"Process command: '{processStartInfo.FileName} {processStartInfo.Arguments.Trim()}' for {_numberOfRun} times"); - List results = new(); + List results = []; for (int i = 0; i < _numberOfRun; i++) { using Process process = Process.Start(processStartInfo)!; diff --git a/test/UnitTests/MSTest.Analyzers.UnitTests/NonNullableReferenceNotInitializedSuppressorTests.cs b/test/UnitTests/MSTest.Analyzers.UnitTests/NonNullableReferenceNotInitializedSuppressorTests.cs index 23d263569a..7f553df797 100644 --- a/test/UnitTests/MSTest.Analyzers.UnitTests/NonNullableReferenceNotInitializedSuppressorTests.cs +++ b/test/UnitTests/MSTest.Analyzers.UnitTests/NonNullableReferenceNotInitializedSuppressorTests.cs @@ -79,7 +79,7 @@ public class DoNothingAnalyzer : DiagnosticAnalyzer [SuppressMessage("MicrosoftCodeAnalysisDesign", "RS1017:DiagnosticId for analyzers must be a non-null constant.", Justification = "For suppression test only.")] public static readonly DiagnosticDescriptor Rule = new(NonNullableReferenceNotInitializedSuppressor.Rule.SuppressedDiagnosticId, "Title", "Message", "Category", DiagnosticSeverity.Warning, isEnabledByDefault: true); - public override ImmutableArray SupportedDiagnostics => ImmutableArray.Create(Rule); + public override ImmutableArray SupportedDiagnostics => [Rule]; public override void Initialize(AnalysisContext context) { diff --git a/test/UnitTests/MSTest.Analyzers.UnitTests/UseAsyncSuffixTestFixtureMethodSuppressorTests.cs b/test/UnitTests/MSTest.Analyzers.UnitTests/UseAsyncSuffixTestFixtureMethodSuppressorTests.cs index 069d599c3e..b75ac12800 100644 --- a/test/UnitTests/MSTest.Analyzers.UnitTests/UseAsyncSuffixTestFixtureMethodSuppressorTests.cs +++ b/test/UnitTests/MSTest.Analyzers.UnitTests/UseAsyncSuffixTestFixtureMethodSuppressorTests.cs @@ -104,7 +104,7 @@ public class WarnForMissingAsyncSuffix : DiagnosticAnalyzer [SuppressMessage("MicrosoftCodeAnalysisDesign", "RS1017:DiagnosticId for analyzers must be a non-null constant.", Justification = "For suppression test only.")] public static readonly DiagnosticDescriptor Rule = new(UseAsyncSuffixTestFixtureMethodSuppressor.Rule.SuppressedDiagnosticId, "Title", "Message", "Category", DiagnosticSeverity.Warning, isEnabledByDefault: true); - public override ImmutableArray SupportedDiagnostics => ImmutableArray.Create(Rule); + public override ImmutableArray SupportedDiagnostics => [Rule]; public override void Initialize(AnalysisContext context) { diff --git a/test/UnitTests/MSTest.Analyzers.UnitTests/UseAsyncSuffixTestMethodSuppressorTests.cs b/test/UnitTests/MSTest.Analyzers.UnitTests/UseAsyncSuffixTestMethodSuppressorTests.cs index ba566c293c..1bd51439f4 100644 --- a/test/UnitTests/MSTest.Analyzers.UnitTests/UseAsyncSuffixTestMethodSuppressorTests.cs +++ b/test/UnitTests/MSTest.Analyzers.UnitTests/UseAsyncSuffixTestMethodSuppressorTests.cs @@ -107,7 +107,7 @@ public class WarnForMissingAsyncSuffix : DiagnosticAnalyzer [SuppressMessage("MicrosoftCodeAnalysisDesign", "RS1017:DiagnosticId for analyzers must be a non-null constant.", Justification = "For suppression test only.")] public static readonly DiagnosticDescriptor Rule = new(UseAsyncSuffixTestMethodSuppressor.Rule.SuppressedDiagnosticId, "Title", "Message", "Category", DiagnosticSeverity.Warning, isEnabledByDefault: true); - public override ImmutableArray SupportedDiagnostics => ImmutableArray.Create(Rule); + public override ImmutableArray SupportedDiagnostics => [Rule]; public override void Initialize(AnalysisContext context) { diff --git a/test/UnitTests/MSTest.Analyzers.UnitTests/UseAttributeOnTestMethodAnalyzerTests.cs b/test/UnitTests/MSTest.Analyzers.UnitTests/UseAttributeOnTestMethodAnalyzerTests.cs index f7353183ad..8ddb170745 100644 --- a/test/UnitTests/MSTest.Analyzers.UnitTests/UseAttributeOnTestMethodAnalyzerTests.cs +++ b/test/UnitTests/MSTest.Analyzers.UnitTests/UseAttributeOnTestMethodAnalyzerTests.cs @@ -91,7 +91,7 @@ public void TestMethod() string fixedCode = $$""" using Microsoft.VisualStudio.TestTools.UnitTesting; - + {{MyExpectedExceptionAttributeDeclaration}} [TestClass] @@ -118,7 +118,7 @@ public async Task WhenMethodIsMarkedWithMultipleTestAttributesButNotWithTestMeth { string code = $$""" using Microsoft.VisualStudio.TestTools.UnitTesting; - + {{MyExpectedExceptionAttributeDeclaration}} [TestClass] @@ -134,7 +134,7 @@ public void TestMethod() string fixedCode = $$""" using Microsoft.VisualStudio.TestTools.UnitTesting; - + {{MyExpectedExceptionAttributeDeclaration}} [TestClass] @@ -149,7 +149,7 @@ public void TestMethod() } """; - await VerifyCS.VerifyCodeFixAsync(code, new[] { VerifyCS.Diagnostic(rule1).WithLocation(0), VerifyCS.Diagnostic(rule2).WithLocation(1) }, fixedCode); + await VerifyCS.VerifyCodeFixAsync(code, [VerifyCS.Diagnostic(rule1).WithLocation(0), VerifyCS.Diagnostic(rule2).WithLocation(1)], fixedCode); } [DynamicData(nameof(GetAttributeUsageExamples), DynamicDataSourceType.Method)] @@ -159,7 +159,7 @@ public async Task WhenMethodIsMarkedWithTestAttributeAndCustomTestMethod_NoDiagn string code = $$""" using System; using Microsoft.VisualStudio.TestTools.UnitTesting; - + {{MyExpectedExceptionAttributeDeclaration}} [TestClass] diff --git a/test/UnitTests/MSTest.Engine.UnitTests/Adapter_ExecuteRequestAsyncTests.cs b/test/UnitTests/MSTest.Engine.UnitTests/Adapter_ExecuteRequestAsyncTests.cs index 5100e968e7..5b7e1a422b 100644 --- a/test/UnitTests/MSTest.Engine.UnitTests/Adapter_ExecuteRequestAsyncTests.cs +++ b/test/UnitTests/MSTest.Engine.UnitTests/Adapter_ExecuteRequestAsyncTests.cs @@ -27,7 +27,7 @@ public async Task ExecutableNode_ThatDoesNotThrow_ShouldReportPassed() }; var services = new Services(); - var adapter = new TestFramework(new(), new[] { new FactoryTestNodesBuilder(() => new[] { testNode }) }, new(), + var adapter = new TestFramework(new(), [new FactoryTestNodesBuilder(() => [testNode])], new(), services.ServiceProvider.GetSystemClock(), services.ServiceProvider.GetTask(), services.ServiceProvider.GetConfiguration(), new Platform.Capabilities.TestFramework.TestFrameworkCapabilities()); CancellationToken cancellationToken = CancellationToken.None; @@ -62,7 +62,7 @@ public async Task ExecutableNode_ThatThrows_ShouldReportError() var services = new Services(); var fakeClock = (FakeClock)services.ServiceProvider.GetService(typeof(FakeClock))!; - var adapter = new TestFramework(new(), new[] { new FactoryTestNodesBuilder(() => new[] { testNode }) }, new(), + var adapter = new TestFramework(new(), [new FactoryTestNodesBuilder(() => [testNode])], new(), services.ServiceProvider.GetSystemClock(), services.ServiceProvider.GetTask(), services.ServiceProvider.GetConfiguration(), new Platform.Capabilities.TestFramework.TestFrameworkCapabilities()); CancellationToken cancellationToken = CancellationToken.None; @@ -93,7 +93,7 @@ await adapter.ExecuteRequestAsync(new( private sealed class FakeClock : IClock { - public List UsedTimes { get; } = new(); + public List UsedTimes { get; } = []; public DateTimeOffset UtcNow { @@ -116,7 +116,7 @@ public Services() ServiceProvider.AddService(new FakeClock()); ServiceProvider.AddService(new SystemTask()); #pragma warning disable TPEXP // Type is for evaluation purposes only and is subject to change or removal in future updates. Suppress this diagnostic to proceed. - ServiceProvider.AddService(new AggregatedConfiguration(Array.Empty(), new CurrentTestApplicationModuleInfo(new SystemEnvironment(), new SystemProcessHandler()), new SystemFileSystem(), new(null, [], []))); + ServiceProvider.AddService(new AggregatedConfiguration([], new CurrentTestApplicationModuleInfo(new SystemEnvironment(), new SystemProcessHandler()), new SystemFileSystem(), new(null, [], []))); #pragma warning restore TPEXP // Type is for evaluation purposes only and is subject to change or removal in future updates. Suppress this diagnostic to proceed. } @@ -127,7 +127,7 @@ public Services() private sealed class MessageBus : IMessageBus { - public List Messages { get; } = new(); + public List Messages { get; } = []; public Task PublishAsync(IDataProducer dataProducer, IData data) { diff --git a/test/UnitTests/MSTest.Engine.UnitTests/BFSTestNodeVisitorTests.cs b/test/UnitTests/MSTest.Engine.UnitTests/BFSTestNodeVisitorTests.cs index 847ecdf276..6ff2840b2a 100644 --- a/test/UnitTests/MSTest.Engine.UnitTests/BFSTestNodeVisitorTests.cs +++ b/test/UnitTests/MSTest.Engine.UnitTests/BFSTestNodeVisitorTests.cs @@ -18,21 +18,21 @@ public async Task Visit_WhenFilterDoesNotUseEncodedSlash_NodeIsNotIncluded() { StableUid = "ID1", DisplayName = "A", - Tests = new[] - { + Tests = + [ new TestNode { StableUid = "ID2", DisplayName = "B/C", }, - }, + ], }; var filter = new TreeNodeFilter("/A/B/C"); var visitor = new BFSTestNodeVisitor(new[] { rootNode }, filter, null!); // Act - List includedTestNodes = new(); + List includedTestNodes = []; await visitor.VisitAsync((testNode, _) => { includedTestNodes.Add(testNode); @@ -55,21 +55,21 @@ public async Task Visit_WhenFilterUsesEncodedEntry_NodeIsIncluded(string nodeSpe { StableUid = "ID1", DisplayName = "A", - Tests = new[] - { + Tests = + [ new TestNode { StableUid = "ID2", DisplayName = "B" + nodeSpecialString + "C", }, - }, + ], }; var filter = new TreeNodeFilter("/A/B" + filterEncodedSpecialString + "C"); var visitor = new BFSTestNodeVisitor(new[] { rootNode }, filter, null!); // Act - List includedTestNodes = new(); + List includedTestNodes = []; await visitor.VisitAsync((testNode, _) => { includedTestNodes.Add(testNode); @@ -107,7 +107,7 @@ public async Task Visit_WhenNodeIsNotParameterizedNode_DoesNotExpand(string nonP var visitor = new BFSTestNodeVisitor(new[] { rootNode }, new NopFilter(), null!); // Act - List includedTestNodes = new(); + List includedTestNodes = []; await visitor.VisitAsync((testNode, _) => { includedTestNodes.Add(testNode); @@ -129,7 +129,7 @@ public async Task Visit_WhenNodeIsParameterizedNodeAndPropertyIsAbsentOrTrue_Exp var visitor = new BFSTestNodeVisitor(new[] { rootNode }, new NopFilter(), new TestArgumentsManager()); // Act - List<(TestNode Node, TestNodeUid? ParentNodeUid)> includedTestNodes = new(); + List<(TestNode Node, TestNodeUid? ParentNodeUid)> includedTestNodes = []; await visitor.VisitAsync((testNode, parentNodeUid) => { includedTestNodes.Add((testNode, parentNodeUid)); @@ -158,7 +158,7 @@ public async Task Visit_WhenNodeIsParameterizedNodeAndDoesNotAllowExpansion_Does var visitor = new BFSTestNodeVisitor(new[] { rootNode }, new NopFilter(), new TestArgumentsManager()); // Act - List<(TestNode Node, TestNodeUid? ParentNodeUid)> includedTestNodes = new(); + List<(TestNode Node, TestNodeUid? ParentNodeUid)> includedTestNodes = []; await visitor.VisitAsync((testNode, parentNodeUid) => { includedTestNodes.Add((testNode, parentNodeUid)); @@ -177,14 +177,14 @@ public async Task Visit_WithModuleNamespaceClassMethodLevelAndExpansion_Discover { StableUid = "MyModule", DisplayName = "MyModule", - Tests = new[] - { + Tests = + [ new TestNode { StableUid = "MyNamespace", DisplayName = "MyNamespace", - Tests = new[] - { + Tests = + [ new TestNode { StableUid = "MyType", @@ -200,14 +200,14 @@ public async Task Visit_WithModuleNamespaceClassMethodLevelAndExpansion_Discover }, }, }, - }, + ], }, - }, + ], }; var visitor = new BFSTestNodeVisitor(new[] { rootNode }, new NopFilter(), new TestArgumentsManager()); // Act - List<(TestNode Node, TestNodeUid? ParentNodeUid)> includedTestNodes = new(); + List<(TestNode Node, TestNodeUid? ParentNodeUid)> includedTestNodes = []; await visitor.VisitAsync((testNode, parentNodeUid) => { includedTestNodes.Add((testNode, parentNodeUid)); @@ -267,13 +267,13 @@ private static TestNode CreateParameterizedTestNode(string parameterizedTestNode static IEnumerable GetArguments() => new byte[] { 0, 1 }; static IProperty[] GetProperties(bool? hasExpansionProperty) => hasExpansionProperty.HasValue - ? new IProperty[1] - { + ? + [ new FrameworkEngineMetadataProperty { PreventArgumentsExpansion = hasExpansionProperty.Value, }, - } - : Array.Empty(); + ] + : []; } } diff --git a/test/UnitTests/MSTest.Engine.UnitTests/DynamicDataNameProviderTests.cs b/test/UnitTests/MSTest.Engine.UnitTests/DynamicDataNameProviderTests.cs index f511c2ff51..d7d29cca7a 100644 --- a/test/UnitTests/MSTest.Engine.UnitTests/DynamicDataNameProviderTests.cs +++ b/test/UnitTests/MSTest.Engine.UnitTests/DynamicDataNameProviderTests.cs @@ -15,7 +15,7 @@ public void NullTranslatesToNullString() // you will get empty string while with the call you will get "null,a". // // check that this is still true: - string fragment = DynamicDataNameProvider.GetUidFragment(["parameter1", "parameter2"], new object?[] { null, "a" }, 0); + string fragment = DynamicDataNameProvider.GetUidFragment(["parameter1", "parameter2"], [null, "a"], 0); Assert.AreEqual("(parameter1: null, parameter2: a)[0]", fragment); } @@ -28,7 +28,7 @@ public void ParameterMismatchShowsDataInMessage() // you will get empty string while with the call you will get "null,a". // // check that this is still true: - ArgumentException exception = Assert.ThrowsException(() => DynamicDataNameProvider.GetUidFragment(["parameter1"], new object?[] { null, "a" }, 0)); + ArgumentException exception = Assert.ThrowsException(() => DynamicDataNameProvider.GetUidFragment(["parameter1"], [null, "a"], 0)); Assert.AreEqual("Parameter count mismatch. The provided data (null, a) have 2 items, but there are 1 parameters.", exception.Message); } } diff --git a/test/UnitTests/MSTest.Engine.UnitTests/DynamicDataTests.cs b/test/UnitTests/MSTest.Engine.UnitTests/DynamicDataTests.cs index ea608a39d3..1fa1ce4990 100644 --- a/test/UnitTests/MSTest.Engine.UnitTests/DynamicDataTests.cs +++ b/test/UnitTests/MSTest.Engine.UnitTests/DynamicDataTests.cs @@ -10,11 +10,11 @@ namespace Microsoft.Testing.Framework.UnitTests; public class DynamicDataTests { public static IEnumerable IntDataProperty - => new[] - { - new object[] { 1, 2 }, - new object[] { 2, 3 }, - }; + => + [ + [1, 2], + [2, 3] + ]; [DynamicData(nameof(IntDataProperty))] [TestMethod] @@ -37,11 +37,11 @@ public void DynamicDataWithIntMethodAndExplicitSourceType(int expected, int actu => Assert.AreEqual(expected, actualPlus1 - 1); public static IEnumerable IntDataMethod() - => new[] - { - new object[] { 1, 2 }, - new object[] { 2, 3 }, - }; + => + [ + [1, 2], + [2, 3] + ]; [DynamicData(nameof(IntDataProperty), typeof(DataClass))] [TestMethod] @@ -60,11 +60,11 @@ public void DynamicDataWithUserProperty(User _, User _2) } public static IEnumerable UserDataProperty - => new[] - { - new object[] { new User("Jakub"), new User("Amaury") }, - new object[] { new User("Marco"), new User("Pavel") }, - }; + => + [ + [new User("Jakub"), new User("Amaury")], + [new User("Marco"), new User("Pavel")] + ]; [DynamicData(nameof(UserDataMethod), DynamicDataSourceType.Method)] [TestMethod] @@ -73,28 +73,28 @@ public void DynamicDataWithUserMethod(User _, User _2) } public static IEnumerable UserDataMethod() - => new[] - { - new object[] { new User("Jakub"), new User("Amaury") }, - new object[] { new User("Marco"), new User("Pavel") }, - }; + => + [ + [new User("Jakub"), new User("Amaury")], + [new User("Marco"), new User("Pavel")] + ]; } public class DataClass { public static IEnumerable IntDataProperty - => new[] - { - new object[] { 1, 3 }, - new object[] { 2, 4 }, - }; + => + [ + [1, 3], + [2, 4] + ]; public static IEnumerable IntDataMethod() - => new[] - { - new object[] { 1, 3 }, - new object[] { 2, 4 }, - }; + => + [ + [1, 3], + [2, 4] + ]; } public class User diff --git a/test/UnitTests/MSTest.SourceGeneration.UnitTests/Generators/TestNodesGeneratorTests.cs b/test/UnitTests/MSTest.SourceGeneration.UnitTests/Generators/TestNodesGeneratorTests.cs index 7695466e03..7d3c831a9b 100644 --- a/test/UnitTests/MSTest.SourceGeneration.UnitTests/Generators/TestNodesGeneratorTests.cs +++ b/test/UnitTests/MSTest.SourceGeneration.UnitTests/Generators/TestNodesGeneratorTests.cs @@ -626,25 +626,24 @@ public Task TestMethod() public async Task When_MultipleClassesFromSameNamespace_ItGeneratesASingleNamespaceTestNode() { GeneratorCompilationResult generatorResult = await GeneratorTester.TestGraph.CompileAndExecuteAsync( - new[] - { - $$""" - using System.Threading.Tasks; - using Microsoft.VisualStudio.TestTools.UnitTesting; - - namespace MyNamespace - { - [TestClass] - public class MyType1 - { - [TestMethod] - public Task TestMethod() - { - return Task.CompletedTask; - } - } - } - """, + [ + $$""" + using System.Threading.Tasks; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + namespace MyNamespace + { + [TestClass] + public class MyType1 + { + [TestMethod] + public Task TestMethod() + { + return Task.CompletedTask; + } + } + } + """, $$""" using System.Threading.Tasks; using Microsoft.VisualStudio.TestTools.UnitTesting; @@ -661,8 +660,8 @@ public Task TestMethod() } } } - """, - }, CancellationToken.None); + """ + ], CancellationToken.None); generatorResult.AssertSuccessfulGeneration(); generatorResult.GeneratedTrees.Should().HaveCount(4); @@ -1154,27 +1153,26 @@ public void GenerateValidNamespaceName_WithGivenAssemblyName_ReturnsExpectedName public async Task When_APartialTypeIsMarkedWithTestClass_ItGeneratesAGraphWithAssemblyNamespaceTypeAndMethods() { GeneratorCompilationResult generatorResult = await GeneratorTester.TestGraph.CompileAndExecuteAsync( - new string[] - { - $$""" - using System.Threading.Tasks; - using Microsoft.VisualStudio.TestTools.UnitTesting; - - namespace MyNamespace - { - [TestClass] - public partial class MyType - { - public MyType(int a) { } - - [TestMethod] - public Task TestMethod1() - { - return Task.CompletedTask; - } - } - } - """, + [ + $$""" + using System.Threading.Tasks; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + namespace MyNamespace + { + [TestClass] + public partial class MyType + { + public MyType(int a) { } + + [TestMethod] + public Task TestMethod1() + { + return Task.CompletedTask; + } + } + } + """, $$""" using System.Threading.Tasks; using Microsoft.VisualStudio.TestTools.UnitTesting; @@ -1196,8 +1194,8 @@ public Task TestMethod2() } } } - """, - }, CancellationToken.None); + """ + ], CancellationToken.None); generatorResult.AssertSuccessfulGeneration(); generatorResult.GeneratedTrees.Should().HaveCount(3); diff --git a/test/UnitTests/MSTest.SourceGeneration.UnitTests/Helpers/MinimalTestRunner.cs b/test/UnitTests/MSTest.SourceGeneration.UnitTests/Helpers/MinimalTestRunner.cs index e00e391545..5537de1ad2 100644 --- a/test/UnitTests/MSTest.SourceGeneration.UnitTests/Helpers/MinimalTestRunner.cs +++ b/test/UnitTests/MSTest.SourceGeneration.UnitTests/Helpers/MinimalTestRunner.cs @@ -11,7 +11,7 @@ public static async Task RunAllAsync(string? testNameContainsFilter = null) #pragma warning disable IL2026 // Members annotated with 'RequiresUnreferencedCodeAttribute' require dynamic access otherwise can break functionality when trimming application code IEnumerable classes = Assembly.GetExecutingAssembly().GetTypes().Where(c => c.IsPublic); #pragma warning restore IL2026 // Members annotated with 'RequiresUnreferencedCodeAttribute' require dynamic access otherwise can break functionality when trimming application code - object[][] emptyRow = new[] { Array.Empty() }; + object[][] emptyRow = [[]]; int total = 0; int failed = 0; @@ -63,7 +63,7 @@ public static async Task RunAllAsync(string? testNameContainsFilter = null) object?[][]? rows = null; if (methodAttributes.Any(a => a.AttributeType == typeof(DataRowAttribute))) { - rows = methodAttributes + rows = [.. methodAttributes .Where(a => a.AttributeType == typeof(DataRowAttribute)) .SelectMany(a => a.ConstructorArguments.Select(arg => { @@ -79,8 +79,7 @@ public static async Task RunAllAsync(string? testNameContainsFilter = null) return [arg.Value]; } #pragma warning restore IDE0046 // Convert to conditional expression - })) - .ToArray(); + }))]; } foreach (object?[]? row in rows ?? emptyRow) diff --git a/test/UnitTests/MSTest.SourceGeneration.UnitTests/TestUtilities/GeneratorTester.cs b/test/UnitTests/MSTest.SourceGeneration.UnitTests/TestUtilities/GeneratorTester.cs index 83f1290dcc..1bbd56f15a 100644 --- a/test/UnitTests/MSTest.SourceGeneration.UnitTests/TestUtilities/GeneratorTester.cs +++ b/test/UnitTests/MSTest.SourceGeneration.UnitTests/TestUtilities/GeneratorTester.cs @@ -30,8 +30,7 @@ public GeneratorTester(Func incrementalGeneratorFactory, public static GeneratorTester TestGraph { get; } = new( () => new TestNodesGenerator(), - new[] - { + [ // Microsoft.Testing.Platform dll Assembly.GetAssembly(typeof(IProperty))!.Location, @@ -45,13 +44,13 @@ public GeneratorTester(Func incrementalGeneratorFactory, Assembly.GetAssembly(typeof(TrxExceptionProperty))!.Location, // MSTest.TestFramework dll - Assembly.GetAssembly(typeof(TestClassAttribute))!.Location, - }); + Assembly.GetAssembly(typeof(TestClassAttribute))!.Location + ]); public static ImmutableArray? Net60MetadataReferences { get; set; } public async Task CompileAndExecuteAsync(string source, CancellationToken cancellationToken) - => await CompileAndExecuteAsync(new[] { source }, cancellationToken); + => await CompileAndExecuteAsync([source], cancellationToken); public async Task CompileAndExecuteAsync(string[] sources, CancellationToken cancellationToken) { @@ -79,10 +78,7 @@ public async Task CompileAndExecuteAsync(string[] so } } - MetadataReference[] metadataReferences = - Net60MetadataReferences.Value - .Concat(_additionalReferences.Select(loc => MetadataReference.CreateFromFile(loc))) - .ToArray(); + MetadataReference[] metadataReferences = [.. Net60MetadataReferences.Value, .. _additionalReferences.Select(loc => MetadataReference.CreateFromFile(loc))]; var compilation = CSharpCompilation.Create( "TestAssembly", @@ -92,7 +88,7 @@ public async Task CompileAndExecuteAsync(string[] so ISourceGenerator generator = _incrementalGeneratorFactory().AsSourceGenerator(); GeneratorDriver driver = CSharpGeneratorDriver.Create( - generators: new ISourceGenerator[] { generator }); + generators: [generator]); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out Compilation? outputCompilation, out ImmutableArray diagnostics, cancellationToken); diff --git a/test/UnitTests/MSTest.SourceGeneration.UnitTests/TestUtilities/TestingFrameworkVerifier.cs b/test/UnitTests/MSTest.SourceGeneration.UnitTests/TestUtilities/TestingFrameworkVerifier.cs index c870abcfe3..39c3e026ba 100644 --- a/test/UnitTests/MSTest.SourceGeneration.UnitTests/TestUtilities/TestingFrameworkVerifier.cs +++ b/test/UnitTests/MSTest.SourceGeneration.UnitTests/TestUtilities/TestingFrameworkVerifier.cs @@ -11,7 +11,7 @@ namespace Microsoft.Testing.Framework.SourceGeneration.UnitTests.TestUtilities; internal sealed class TestingFrameworkVerifier : IVerifier { public TestingFrameworkVerifier() - : this(ImmutableStack.Empty) + : this([]) { } diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/AssemblyResolverTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/AssemblyResolverTests.cs index 4e5035c30c..3af7639fa0 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/AssemblyResolverTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/AssemblyResolverTests.cs @@ -24,7 +24,7 @@ public void AddSubDirectoriesShouldReturnSubDirectoriesInDfsOrder() @"C:\unitTesting\b", ]; - TestableAssemblyResolver assemblyResolver = new(new List { @"c:\dummy" }) + TestableAssemblyResolver assemblyResolver = new([@"c:\dummy"]) { DoesDirectoryExistSetter = (str) => true, GetDirectoriesSetter = (str) => @@ -42,7 +42,7 @@ public void AddSubDirectoriesShouldReturnSubDirectoriesInDfsOrder() return [@"C:\unitTesting\a\c\d"]; } - return new List().ToArray(); + return []; }, }; @@ -88,7 +88,7 @@ public void OnResolveShouldAddSearchDirectoryListOnANeedToBasis() return [@"C:\FunctionalTesting\c"]; } - return new List().ToArray(); + return []; }; assemblyResolver.SearchAssemblySetter = @@ -147,7 +147,7 @@ public void ReflectionOnlyOnResolveShouldNotReturnACachedDefaultLoadedAssembly() { Assembly currentAssembly = typeof(AssemblyResolverTests).Assembly; string currentAssemblyPath = Path.GetDirectoryName(currentAssembly.Location); - var assemblyResolver = new TestableAssemblyResolver(new List { currentAssemblyPath }); + var assemblyResolver = new TestableAssemblyResolver([currentAssemblyPath]); bool isAssemblyLoaded = false; bool isAssemblyReflectionOnlyLoaded = false; diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/DesktopTestDeploymentTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/DesktopTestDeploymentTests.cs index f7f7883ca2..d436619ee5 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/DesktopTestDeploymentTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/DesktopTestDeploymentTests.cs @@ -32,7 +32,7 @@ public DesktopTestDeploymentTests() { _mockReflectionUtility = new Mock(); _mockFileUtility = new Mock(); - _warnings = new List(); + _warnings = []; // Reset adapter settings. MSTestSettingsProvider.Reset(); diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/ReflectionOperationsTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/ReflectionOperationsTests.cs index dfd8626b64..97159226f6 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/ReflectionOperationsTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/ReflectionOperationsTests.cs @@ -67,9 +67,7 @@ public void GetCustomAttributesOnTypeShouldReturnAllAttributes() } private object[] GetMemberAttributes(Type type, bool inherit) - => _reflectionOperations.GetCustomAttributes(type, inherit) - .Where(x => x.GetType().FullName != "System.Runtime.CompilerServices.NullableContextAttribute") - .ToArray(); + => [.. _reflectionOperations.GetCustomAttributes(type, inherit).Where(x => x.GetType().FullName != "System.Runtime.CompilerServices.NullableContextAttribute")]; public void GetCustomAttributesOnTypeShouldReturnAllAttributesIgnoringBaseInheritance() { @@ -203,7 +201,7 @@ private static string[] GetAttributeValuePairs(object[] attributes) } } - return attribValuePairs.ToArray(); + return [.. attribValuePairs]; } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Assembly, AllowMultiple = true)] diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/TestDeploymentTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/TestDeploymentTests.cs index 49b2bf0e66..37cf9f5605 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/TestDeploymentTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/TestDeploymentTests.cs @@ -33,7 +33,7 @@ public TestDeploymentTests() { _mockReflectionUtility = new Mock(); _mockFileUtility = new Mock(); - _warnings = new List(); + _warnings = []; // Reset adapter settings. MSTestSettingsProvider.Reset(); diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Utilities/DeploymentUtilityTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Utilities/DeploymentUtilityTests.cs index 673c1159d9..928a13ca44 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Utilities/DeploymentUtilityTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Utilities/DeploymentUtilityTests.cs @@ -42,7 +42,7 @@ public DeploymentUtilityTests() _mockReflectionUtility = new Mock(); _mockFileUtility = new Mock(); _mockAssemblyUtility = new Mock(); - _warnings = new List(); + _warnings = []; _deploymentUtility = new DeploymentUtility( new DeploymentItemUtility(_mockReflectionUtility.Object), diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Utilities/DesktopReflectionUtilityTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Utilities/DesktopReflectionUtilityTests.cs index 2e7348f8e9..80b9663729 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Utilities/DesktopReflectionUtilityTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Utilities/DesktopReflectionUtilityTests.cs @@ -40,7 +40,7 @@ internal static string[] GetAttributeValuePairs(IEnumerable attributes) } } - return attribValuePairs.ToArray(); + return [.. attribValuePairs]; } [DummyA("ba")] diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Utilities/ns10FileUtilityTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Utilities/ns10FileUtilityTests.cs index adea291520..5f83427888 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Utilities/ns10FileUtilityTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Utilities/ns10FileUtilityTests.cs @@ -105,10 +105,10 @@ public void AddFilesWithIgnoreDirectory() _fileUtility.Setup(fu => fu.GetDirectoriesInADirectory(It.IsAny())).Returns(directory => { IEnumerable directories = allFiles.Where(file => IsFileUnderDirectory(directory, file)).Select(file => Path.GetDirectoryName(file)!).Distinct(); - return directories.ToArray(); + return [.. directories]; }); - _fileUtility.Setup(fu => fu.GetFilesInADirectory(It.IsAny())).Returns(directory => allFiles.Where(file => Path.GetDirectoryName(file)!.Equals(directory, StringComparison.OrdinalIgnoreCase)).Distinct().ToArray()); + _fileUtility.Setup(fu => fu.GetFilesInADirectory(It.IsAny())).Returns(directory => [.. allFiles.Where(file => Path.GetDirectoryName(file)!.Equals(directory, StringComparison.OrdinalIgnoreCase)).Distinct()]); // Act List files = _fileUtility.Object.AddFilesFromDirectory("C:\\MainClock", directory => directory.Contains("Results"), false); @@ -145,10 +145,10 @@ public void AddFilesWithNoIgnoreDirectory() _fileUtility.Setup(fu => fu.GetDirectoriesInADirectory(It.IsAny())).Returns(directory => { IEnumerable directories = allFiles.Where(file => IsFileUnderDirectory(directory, file)).Select(file => Path.GetDirectoryName(file)!).Distinct(); - return directories.ToArray(); + return [.. directories]; }); - _fileUtility.Setup(fu => fu.GetFilesInADirectory(It.IsAny())).Returns(directory => allFiles.Where(file => Path.GetDirectoryName(file)!.Equals(directory, StringComparison.OrdinalIgnoreCase)).Distinct().ToArray()); + _fileUtility.Setup(fu => fu.GetFilesInADirectory(It.IsAny())).Returns(directory => [.. allFiles.Where(file => Path.GetDirectoryName(file)!.Equals(directory, StringComparison.OrdinalIgnoreCase)).Distinct()]); // Act List files = _fileUtility.Object.AddFilesFromDirectory("C:\\MainClock", false); @@ -171,9 +171,8 @@ private void SetupMockFileAPIs(string[] files) { _fileUtility.Setup(fu => fu.GetFilesInADirectory(It.IsAny())).Returns((string dp) => #pragma warning disable CA1865 // Use char overload - files.Where(f => f.Contains(dp) && f.LastIndexOf('\\') == (f.IndexOf(dp, StringComparison.Ordinal) + dp.Length) && !f.EndsWith("\\", StringComparison.Ordinal)) - .ToArray()); - _fileUtility.Setup(fu => fu.GetDirectoriesInADirectory(It.IsAny())).Returns((string dp) => files.Where(f => f.Contains(dp) && f.LastIndexOf('\\') > (f.IndexOf(dp, StringComparison.Ordinal) + dp.Length)) + [.. files.Where(f => f.Contains(dp) && f.LastIndexOf('\\') == (f.IndexOf(dp, StringComparison.Ordinal) + dp.Length) && !f.EndsWith("\\", StringComparison.Ordinal))]); + _fileUtility.Setup(fu => fu.GetDirectoriesInADirectory(It.IsAny())).Returns((string dp) => [.. files.Where(f => f.Contains(dp) && f.LastIndexOf('\\') > (f.IndexOf(dp, StringComparison.Ordinal) + dp.Length)) .Select(f => { #pragma warning disable IDE0057 // Use range operator @@ -183,8 +182,7 @@ private void SetupMockFileAPIs(string[] files) return f.Substring(0, dp.Length + 1 + val.IndexOf('\\')); #pragma warning restore IDE0057 // Use range operator }) - .Distinct() - .ToArray()); + .Distinct()]); } #endregion diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Utilities/ns13DeploymentItemUtilityTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Utilities/ns13DeploymentItemUtilityTests.cs index 06ee4478ee..0cdb0d537d 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Utilities/ns13DeploymentItemUtilityTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Utilities/ns13DeploymentItemUtilityTests.cs @@ -34,7 +34,7 @@ public DeploymentItemUtilityTests() { _mockReflectionUtility = new Mock(); _deploymentItemUtility = new DeploymentItemUtility(_mockReflectionUtility.Object); - _warnings = new List(); + _warnings = []; } #region GetClassLevelDeploymentItems tests diff --git a/test/UnitTests/MSTestAdapter.UnitTests/Discovery/AssemblyEnumeratorTests.cs b/test/UnitTests/MSTestAdapter.UnitTests/Discovery/AssemblyEnumeratorTests.cs index 239be62d6b..afb9c13dde 100644 --- a/test/UnitTests/MSTestAdapter.UnitTests/Discovery/AssemblyEnumeratorTests.cs +++ b/test/UnitTests/MSTestAdapter.UnitTests/Discovery/AssemblyEnumeratorTests.cs @@ -26,7 +26,7 @@ public class AssemblyEnumeratorTests : TestContainer public AssemblyEnumeratorTests() { _assemblyEnumerator = new AssemblyEnumerator(); - _warnings = new List(); + _warnings = []; _testablePlatformServiceProvider = new TestablePlatformServiceProvider(); PlatformServiceProvider.Instance = _testablePlatformServiceProvider; @@ -259,7 +259,7 @@ public void EnumerateAssemblyShouldReturnTestElementsForAType() _testablePlatformServiceProvider.MockFileOperations.Setup(fo => fo.LoadAssembly("DummyAssembly", false)) .Returns(mockAssembly.Object); testableAssemblyEnumerator.MockTypeEnumerator.Setup(te => te.Enumerate(_warnings)) - .Returns(new List { unitTestElement }); + .Returns([unitTestElement]); AssemblyEnumerationResult result = testableAssemblyEnumerator.EnumerateAssembly("DummyAssembly"); _warnings.AddRange(result.Warnings); @@ -392,6 +392,9 @@ private static Mock CreateMockTestableAssembly() // The mock must be configured with a return value for GetCustomAttributes for this attribute type, but the // actual return value is irrelevant for these tests. + // NOTE: Don't convert Array.Empty() to [] as it will cause an InvalidCastException. + // [] will produce `object[]`, then it will fail to cast here: + // https://github.com/dotnet/runtime/blob/4252c8d09b2ec537928f34dad269f02f167c8ce5/src/coreclr/System.Private.CoreLib/src/System/Attribute.CoreCLR.cs#L710 mockAssembly .Setup(a => a.GetCustomAttributes( typeof(DiscoverInternalsAttribute), diff --git a/test/UnitTests/MSTestAdapter.UnitTests/Discovery/AssemblyEnumeratorWrapperTests.cs b/test/UnitTests/MSTestAdapter.UnitTests/Discovery/AssemblyEnumeratorWrapperTests.cs index e652995ef1..95d6da8f50 100644 --- a/test/UnitTests/MSTestAdapter.UnitTests/Discovery/AssemblyEnumeratorWrapperTests.cs +++ b/test/UnitTests/MSTestAdapter.UnitTests/Discovery/AssemblyEnumeratorWrapperTests.cs @@ -23,7 +23,7 @@ public class AssemblyEnumeratorWrapperTests : TestContainer public AssemblyEnumeratorWrapperTests() { _testableAssemblyEnumeratorWrapper = new AssemblyEnumeratorWrapper(); - _warnings = new List(); + _warnings = []; _testablePlatformServiceProvider = new TestablePlatformServiceProvider(); PlatformServiceProvider.Instance = _testablePlatformServiceProvider; diff --git a/test/UnitTests/MSTestAdapter.UnitTests/Discovery/TypeEnumeratorTests.cs b/test/UnitTests/MSTestAdapter.UnitTests/Discovery/TypeEnumeratorTests.cs index 43d39526a2..a6f584291e 100644 --- a/test/UnitTests/MSTestAdapter.UnitTests/Discovery/TypeEnumeratorTests.cs +++ b/test/UnitTests/MSTestAdapter.UnitTests/Discovery/TypeEnumeratorTests.cs @@ -33,7 +33,7 @@ public TypeEnumeratorTests() _mockTypeValidator = new Mock(MockBehavior.Default, _mockReflectHelper.Object); _mockTestMethodValidator = new Mock(MockBehavior.Default, _mockReflectHelper.Object, false); - _warnings = new List(); + _warnings = []; _mockMessageLogger = new Mock(); _testablePlatformServiceProvider = new TestablePlatformServiceProvider(); diff --git a/test/UnitTests/MSTestAdapter.UnitTests/Discovery/TypeValidatorTests.cs b/test/UnitTests/MSTestAdapter.UnitTests/Discovery/TypeValidatorTests.cs index 8c4de47c06..3e15bc8c09 100644 --- a/test/UnitTests/MSTestAdapter.UnitTests/Discovery/TypeValidatorTests.cs +++ b/test/UnitTests/MSTestAdapter.UnitTests/Discovery/TypeValidatorTests.cs @@ -240,8 +240,8 @@ public void AllTypesContainAllPrivateClasses() { // The names of private types are not accessible by nameof or typeof, ensure that we have them in the // list of our test types, to avoid bugs caused by typos. - string[] allTypes = GetAllTestTypes().Select(t => t.Name).ToArray(); - string[] privateTypes = typeof(PrivateClassNames).GetProperties().Select(n => n.Name).ToArray(); + string[] allTypes = [.. GetAllTestTypes().Select(t => t.Name)]; + string[] privateTypes = [.. typeof(PrivateClassNames).GetProperties().Select(n => n.Name)]; Verify(privateTypes.Length >= 1); foreach (string type in privateTypes) @@ -264,9 +264,9 @@ public void TypeHasValidAccessibilityShouldReturnTrueForAllPublicTypesIncludingN ]; bool discoverInternal = false; - string[] actualDiscoveredTypes = allTypes + string[] actualDiscoveredTypes = [.. allTypes .Where(t => TypeValidator.TypeHasValidAccessibility(t, discoverInternal)) - .Select(t => t.Name).ToArray(); + .Select(t => t.Name)]; Array.Sort(actualDiscoveredTypes); Array.Sort(expectedDiscoveredTypes); @@ -307,9 +307,9 @@ public void TypeHasValidAccessibilityShouldReturnFalseForAllTypesThatAreNotPubli ]; bool discoverInternal = false; - string[] actualDiscoveredTypes = allTypes + string[] actualDiscoveredTypes = [.. allTypes .Where(t => !TypeValidator.TypeHasValidAccessibility(t, discoverInternal)) - .Select(t => t.Name).ToArray(); + .Select(t => t.Name)]; Array.Sort(actualDiscoveredTypes); Array.Sort(expectedNonDiscoveredTypes); @@ -342,9 +342,9 @@ public void TypeHasValidAccessibilityShouldReturnTrueForAllPublicAndInternalType ]; bool discoverInternal = true; - string[] actualDiscoveredTypes = allTypes + string[] actualDiscoveredTypes = [.. allTypes .Where(t => TypeValidator.TypeHasValidAccessibility(t, discoverInternal)) - .Select(t => t.Name).ToArray(); + .Select(t => t.Name)]; Array.Sort(actualDiscoveredTypes); Array.Sort(expectedDiscoveredTypes); @@ -372,9 +372,9 @@ public void TypeHasValidAccessibilityShouldReturnFalseForAllTypesThatAreNotPubli ]; bool discoverInternal = true; - string[] actualDiscoveredTypes = allTypes + string[] actualDiscoveredTypes = [.. allTypes .Where(t => !TypeValidator.TypeHasValidAccessibility(t, discoverInternal)) - .Select(t => t.Name).ToArray(); + .Select(t => t.Name)]; Array.Sort(actualDiscoveredTypes); Array.Sort(expectedNonDiscoveredTypes); @@ -384,9 +384,9 @@ public void TypeHasValidAccessibilityShouldReturnFalseForAllTypesThatAreNotPubli private static Type[] GetAllTestTypes() { Type[] types = [typeof(PublicClass2), typeof(PublicClass3), typeof(InternalClass), typeof(InternalClass2)]; - Type[] nestedTypes = types.SelectMany(t => t.GetNestedTypes(BindingFlags.Public | BindingFlags.NonPublic)).ToArray(); - Type[] nestedNestedTypes = nestedTypes.SelectMany(t => t.GetNestedTypes(BindingFlags.Public | BindingFlags.NonPublic)).ToArray(); - Type[] allTypes = new[] { types, nestedTypes, nestedNestedTypes }.SelectMany(t => t).ToArray(); + Type[] nestedTypes = [.. types.SelectMany(t => t.GetNestedTypes(BindingFlags.Public | BindingFlags.NonPublic))]; + Type[] nestedNestedTypes = [.. nestedTypes.SelectMany(t => t.GetNestedTypes(BindingFlags.Public | BindingFlags.NonPublic))]; + Type[] allTypes = [.. new[] { types, nestedTypes, nestedNestedTypes }.SelectMany(t => t)]; return allTypes; } #endregion diff --git a/test/UnitTests/MSTestAdapter.UnitTests/DynamicDataAttributeTests.cs b/test/UnitTests/MSTestAdapter.UnitTests/DynamicDataAttributeTests.cs index dce014fc52..8bc201d4ec 100644 --- a/test/UnitTests/MSTestAdapter.UnitTests/DynamicDataAttributeTests.cs +++ b/test/UnitTests/MSTestAdapter.UnitTests/DynamicDataAttributeTests.cs @@ -285,7 +285,7 @@ internal class DummyTestClass /// /// Gets the empty test data property. /// - public static IEnumerable EmptyProperty => Array.Empty(); + public static IEnumerable EmptyProperty => []; /// /// Gets the wrong test data property i.e. Property returning something other than diff --git a/test/UnitTests/MSTestAdapter.UnitTests/Execution/ClassCleanupManagerTests.cs b/test/UnitTests/MSTestAdapter.UnitTests/Execution/ClassCleanupManagerTests.cs index 50d3f59707..055e52f37c 100644 --- a/test/UnitTests/MSTestAdapter.UnitTests/Execution/ClassCleanupManagerTests.cs +++ b/test/UnitTests/MSTestAdapter.UnitTests/Execution/ClassCleanupManagerTests.cs @@ -24,11 +24,11 @@ public void AssemblyCleanupRunsAfterAllTestsFinishEvenIfWeScheduleTheSameTestMul // Setting 2 of the same test to run, we should run assembly cleanup after both these tests // finish, not after the first one finishes. - List testsToRun = new() - { - new(testMethod), + List testsToRun = + [ new(testMethod), - }; + new(testMethod) + ]; var classCleanupManager = new ClassCleanupManager(testsToRun, ClassCleanupBehavior.EndOfClass, ClassCleanupBehavior.EndOfClass, reflectHelper); diff --git a/test/UnitTests/MSTestAdapter.UnitTests/Execution/TestExecutionManagerTests.cs b/test/UnitTests/MSTestAdapter.UnitTests/Execution/TestExecutionManagerTests.cs index cea2718a3b..2f1fe65132 100644 --- a/test/UnitTests/MSTestAdapter.UnitTests/Execution/TestExecutionManagerTests.cs +++ b/test/UnitTests/MSTestAdapter.UnitTests/Execution/TestExecutionManagerTests.cs @@ -48,7 +48,7 @@ public class TestExecutionManagerTests : TestContainer ]; private TestableRunContextTestExecutionTests _runContext; - private List _callers = new(); + private List _callers = []; private int _enqueuedParallelTestsCount; public TestExecutionManagerTests() diff --git a/test/UnitTests/MSTestAdapter.UnitTests/Execution/TestMethodInfoTests.cs b/test/UnitTests/MSTestAdapter.UnitTests/Execution/TestMethodInfoTests.cs index b935c23c3b..b91c041b66 100644 --- a/test/UnitTests/MSTestAdapter.UnitTests/Execution/TestMethodInfoTests.cs +++ b/test/UnitTests/MSTestAdapter.UnitTests/Execution/TestMethodInfoTests.cs @@ -344,7 +344,7 @@ public void TestMethodInfoInvokeShouldSetStackTraceInformationIfTestClassConstru public void TestMethodInfoInvokeShouldSetResultFilesIfTestContextHasAttachments() { Mock testContext = new(); - testContext.Setup(tc => tc.GetResultFiles()).Returns(new List { "C:\\temp.txt" }); + testContext.Setup(tc => tc.GetResultFiles()).Returns(["C:\\temp.txt"]); var mockInnerContext = new Mock(); testContext.SetupGet(tc => tc.Context).Returns(mockInnerContext.Object); mockInnerContext.SetupGet(tc => tc.CancellationTokenSource).Returns(new CancellationTokenSource()); @@ -1398,7 +1398,7 @@ public void ResolveExpectedExceptionShouldThrowWhenAttributeIsDefinedTwice_Diffe MethodInfo testMethodInfo = typeof(DummyTestClassForExpectedException).GetMethod(nameof(DummyTestClassForExpectedException.DummyTestMethod1))!; TestClassInfo classInfo = new( typeof(DummyTestClassForExpectedException), - typeof(DummyTestClassForExpectedException).GetConstructor(Array.Empty())!, + typeof(DummyTestClassForExpectedException).GetConstructor([])!, isParameterlessConstructor: true, new UTF.TestClassAttribute(), new TestAssemblyInfo(typeof(DummyTestClassForExpectedException).Assembly)); @@ -1416,7 +1416,7 @@ public void ResolveExpectedExceptionShouldThrowWhenAttributeIsDefinedTwice_SameC MethodInfo testMethodInfo = typeof(DummyTestClassForExpectedException).GetMethod(nameof(DummyTestClassForExpectedException.DummyTestMethod1))!; TestClassInfo classInfo = new( typeof(DummyTestClassForExpectedException), - typeof(DummyTestClassForExpectedException).GetConstructor(Array.Empty())!, + typeof(DummyTestClassForExpectedException).GetConstructor([])!, isParameterlessConstructor: true, new UTF.TestClassAttribute(), new TestAssemblyInfo(typeof(DummyTestClassForExpectedException).Assembly)); @@ -1435,7 +1435,7 @@ public void ResolveExpectedExceptionHelperShouldReturnExpectedExceptionAttribute MethodInfo methodInfo = type.GetMethod(nameof(DummyTestClassForExpectedException.TestMethodWithExpectedException))!; TestClassInfo classInfo = new( typeof(DummyTestClassForExpectedException), - typeof(DummyTestClassForExpectedException).GetConstructor(Array.Empty())!, + typeof(DummyTestClassForExpectedException).GetConstructor([])!, isParameterlessConstructor: true, new UTF.TestClassAttribute(), new TestAssemblyInfo(typeof(DummyTestClassForExpectedException).Assembly)); @@ -1456,7 +1456,7 @@ public void ResolveExpectedExceptionHelperShouldReturnNullIfExpectedExceptionAtt MethodInfo methodInfo = type.GetMethod(nameof(DummyTestClassForExpectedException.TestMethodWithoutExpectedException))!; TestClassInfo classInfo = new( typeof(DummyTestClassForExpectedException), - typeof(DummyTestClassForExpectedException).GetConstructor(Array.Empty())!, + typeof(DummyTestClassForExpectedException).GetConstructor([])!, isParameterlessConstructor: true, new UTF.TestClassAttribute(), new TestAssemblyInfo(typeof(DummyTestClassForExpectedException).Assembly)); diff --git a/test/UnitTests/MSTestAdapter.UnitTests/Execution/TestMethodRunnerTests.cs b/test/UnitTests/MSTestAdapter.UnitTests/Execution/TestMethodRunnerTests.cs index edb63ea7ab..4c9f11f909 100644 --- a/test/UnitTests/MSTestAdapter.UnitTests/Execution/TestMethodRunnerTests.cs +++ b/test/UnitTests/MSTestAdapter.UnitTests/Execution/TestMethodRunnerTests.cs @@ -359,7 +359,7 @@ public async Task RunTestMethodShouldSetResultFilesIfPresentForDataDrivenTests() { TestResult testResult = new() { - ResultFiles = new List { "C:\\temp.txt" }, + ResultFiles = ["C:\\temp.txt"], }; int dummyIntData1 = 1; @@ -537,7 +537,7 @@ public class DummyTestClassWithTestContextWithoutSetter public class DummyTestClassEmptyDataSource { - public static IEnumerable EmptyProperty => Array.Empty(); + public static IEnumerable EmptyProperty => []; [DynamicData("EmptyProperty")] public void TestMethod(int x) diff --git a/test/UnitTests/MSTestAdapter.UnitTests/Execution/TestPropertyAttributeTests.cs b/test/UnitTests/MSTestAdapter.UnitTests/Execution/TestPropertyAttributeTests.cs index a61975dfb5..a2c6b1aafe 100644 --- a/test/UnitTests/MSTestAdapter.UnitTests/Execution/TestPropertyAttributeTests.cs +++ b/test/UnitTests/MSTestAdapter.UnitTests/Execution/TestPropertyAttributeTests.cs @@ -60,7 +60,7 @@ public void GetTestMethodInfoShouldAddPropertiesFromContainingClassCorrectly() Assert.IsTrue(testContext.TryGetPropertyValue("DummyTestClassBaseKey2", out object? value3)); Assert.AreEqual("DummyTestClassBaseValue2", value3); - TestPlatform.ObjectModel.Trait[] traits = ReflectHelper.Instance.GetTestPropertiesAsTraits(typeof(DummyTestClassBase).GetMethod(nameof(DummyTestClassBase.VirtualTestMethodInBaseAndDerived))!).ToArray(); + TestPlatform.ObjectModel.Trait[] traits = [.. ReflectHelper.Instance.GetTestPropertiesAsTraits(typeof(DummyTestClassBase).GetMethod(nameof(DummyTestClassBase.VirtualTestMethodInBaseAndDerived))!)]; Assert.AreEqual(3, traits.Length); Assert.AreEqual("TestMethodKeyFromBase", traits[0].Name); Assert.AreEqual("TestMethodValueFromBase", traits[0].Value); @@ -99,7 +99,7 @@ public void GetTestMethodInfoShouldAddPropertiesFromContainingClassAndBaseClasse Assert.IsTrue(testContext.TryGetPropertyValue("DummyTestClassBaseKey2", out object? value6)); Assert.AreEqual("DummyTestClassBaseValue2", value6); - TestPlatform.ObjectModel.Trait[] traits = ReflectHelper.Instance.GetTestPropertiesAsTraits(typeof(DummyTestClassDerived).GetMethod(nameof(DummyTestClassDerived.VirtualTestMethodInBaseAndDerived))!).ToArray(); + TestPlatform.ObjectModel.Trait[] traits = [.. ReflectHelper.Instance.GetTestPropertiesAsTraits(typeof(DummyTestClassDerived).GetMethod(nameof(DummyTestClassDerived.VirtualTestMethodInBaseAndDerived))!)]; Assert.AreEqual(6, traits.Length); Assert.AreEqual("DerivedMethod1Key", traits[0].Name); Assert.AreEqual("DerivedMethod1Value", traits[0].Value); @@ -144,7 +144,7 @@ public void GetTestMethodInfoShouldAddPropertiesFromContainingClassAndBaseClasse Assert.IsTrue(testContext.TryGetPropertyValue("DummyTestClassBaseKey2", out object? value6)); Assert.AreEqual("DummyTestClassBaseValue2", value6); - TestPlatform.ObjectModel.Trait[] traits = ReflectHelper.Instance.GetTestPropertiesAsTraits(typeof(DummyTestClassDerived).GetMethod(nameof(DummyTestClassDerived.VirtualTestMethodInDerivedButNotTestMethodInBase))!).ToArray(); + TestPlatform.ObjectModel.Trait[] traits = [.. ReflectHelper.Instance.GetTestPropertiesAsTraits(typeof(DummyTestClassDerived).GetMethod(nameof(DummyTestClassDerived.VirtualTestMethodInDerivedButNotTestMethodInBase))!)]; Assert.AreEqual(6, traits.Length); Assert.AreEqual("DerivedMethod2Key", traits[0].Name); Assert.AreEqual("DerivedMethod2Value", traits[0].Value); diff --git a/test/UnitTests/MSTestAdapter.UnitTests/Execution/UnitTestRunnerTests.cs b/test/UnitTests/MSTestAdapter.UnitTests/Execution/UnitTestRunnerTests.cs index 142ff3dffc..fec3b90852 100644 --- a/test/UnitTests/MSTestAdapter.UnitTests/Execution/UnitTestRunnerTests.cs +++ b/test/UnitTests/MSTestAdapter.UnitTests/Execution/UnitTestRunnerTests.cs @@ -31,7 +31,7 @@ public UnitTestRunnerTests() _mockMessageLogger = new Mock(); PlatformServiceProvider.Instance = _testablePlatformServiceProvider; - _unitTestRunner = new UnitTestRunner(GetSettingsWithDebugTrace(false)!, Array.Empty(), null); + _unitTestRunner = new UnitTestRunner(GetSettingsWithDebugTrace(false)!, [], null); } protected override void Dispose(bool disposing) @@ -65,7 +65,7 @@ public void ConstructorShouldPopulateSettings() }); MSTestSettings adapterSettings = MSTestSettings.GetSettings(runSettingsXml, MSTestSettings.SettingsName, _mockMessageLogger.Object)!; - var assemblyEnumerator = new UnitTestRunner(adapterSettings, Array.Empty(), null); + var assemblyEnumerator = new UnitTestRunner(adapterSettings, [], null); Verify(MSTestSettings.CurrentSettings.ForcedLegacyMode); Verify(MSTestSettings.CurrentSettings.TestSettingsFile == "DummyPath\\TestSettings1.testsettings"); @@ -283,7 +283,7 @@ public async Task RunSingleTestShouldSetTestsAsInProgressInTestContext() public async Task RunSingleTestShouldCallAssemblyInitializeAndClassInitializeMethodsInOrder() { var mockReflectHelper = new Mock(); - _unitTestRunner = new UnitTestRunner(new MSTestSettings(), Array.Empty(), null, mockReflectHelper.Object); + _unitTestRunner = new UnitTestRunner(new MSTestSettings(), [], null, mockReflectHelper.Object); Type type = typeof(DummyTestClassWithInitializeMethods); MethodInfo methodInfo = type.GetMethod("TestMethod")!; diff --git a/test/UnitTests/MSTestAdapter.UnitTests/Extensions/TestResultExtensionsTests.cs b/test/UnitTests/MSTestAdapter.UnitTests/Extensions/TestResultExtensionsTests.cs index 0b116fc5a8..0f9877ebca 100644 --- a/test/UnitTests/MSTestAdapter.UnitTests/Extensions/TestResultExtensionsTests.cs +++ b/test/UnitTests/MSTestAdapter.UnitTests/Extensions/TestResultExtensionsTests.cs @@ -43,7 +43,7 @@ public void ToUnitTestResultsForTestResultShouldSetLoggingDataForConvertedUnitTe }; var convertedResult = result.ToTestResult(new() { DisplayName = result.DisplayName }, default, default, string.Empty, new()); - VSTestTestResultMessage[] stdOutMessages = convertedResult.Messages.Where(m => m.Category == VSTestTestResultMessage.StandardOutCategory).ToArray(); + VSTestTestResultMessage[] stdOutMessages = [.. convertedResult.Messages.Where(m => m.Category == VSTestTestResultMessage.StandardOutCategory)]; Verify(stdOutMessages[0].Text == "logOutput"); Verify(convertedResult.Messages.Single(m => m.Category == VSTestTestResultMessage.StandardErrorCategory).Text == "logError"); Verify(convertedResult.DisplayName == "displayName (Data Row 1)"); @@ -177,7 +177,7 @@ public void ToUnitTestResultsShouldHaveResultsFileProvidedToTestResult() // Otherwise, ToTestResult will crash because it calls new Uri on the result file. string resultFile = Path.GetFullPath("DummyFile.txt"); - var result = new TestResult { ResultFiles = new List() { resultFile } }; + var result = new TestResult { ResultFiles = [resultFile] }; var convertedResult = result.ToTestResult(new(), default, default, string.Empty, new()); Verify(convertedResult.Attachments[0].Attachments[0].Description == resultFile); } diff --git a/test/UnitTests/MSTestAdapter.UnitTests/Helpers/ReflectHelperTests.cs b/test/UnitTests/MSTestAdapter.UnitTests/Helpers/ReflectHelperTests.cs index 16cde8c2bb..f77540b6f9 100644 --- a/test/UnitTests/MSTestAdapter.UnitTests/Helpers/ReflectHelperTests.cs +++ b/test/UnitTests/MSTestAdapter.UnitTests/Helpers/ReflectHelperTests.cs @@ -49,7 +49,7 @@ public void GetTestCategoryAttributeShouldIncludeTestCategoriesAtClassLevel() _attributeMockingHelper.SetCustomAttribute(typeof(TestCategoryBaseAttribute), [new TestCategoryAttribute("ClassLevel")], MemberTypes.TypeInfo); string[] expected = ["ClassLevel"]; - string[] actual = _reflectHelper.GetTestCategories(_method.Object, typeof(ReflectHelperTests)).ToArray(); + string[] actual = [.. _reflectHelper.GetTestCategories(_method.Object, typeof(ReflectHelperTests))]; Verify(expected.SequenceEqual(actual)); } @@ -64,7 +64,7 @@ public void GetTestCategoryAttributeShouldIncludeTestCategoriesAtAllLevels() _attributeMockingHelper.SetCustomAttribute(typeof(TestCategoryBaseAttribute), [new TestCategoryAttribute("ClassLevel")], MemberTypes.TypeInfo); _attributeMockingHelper.SetCustomAttribute(typeof(TestCategoryBaseAttribute), [new TestCategoryAttribute("MethodLevel")], MemberTypes.Method); - string[] actual = _reflectHelper.GetTestCategories(_method.Object, typeof(ReflectHelperTests)).ToArray(); + string[] actual = [.. _reflectHelper.GetTestCategories(_method.Object, typeof(ReflectHelperTests))]; string[] expected = ["MethodLevel", "ClassLevel", "AsmLevel1", "AsmLevel2", "AsmLevel3"]; Verify(expected.SequenceEqual(actual)); @@ -82,7 +82,7 @@ public void GetTestCategoryAttributeShouldConcatCustomAttributeOfSameType() _attributeMockingHelper.SetCustomAttribute(typeof(TestCategoryBaseAttribute), [new TestCategoryAttribute("MethodLevel1")], MemberTypes.Method); _attributeMockingHelper.SetCustomAttribute(typeof(TestCategoryBaseAttribute), [new TestCategoryAttribute("MethodLevel2")], MemberTypes.Method); - string[] actual = _reflectHelper.GetTestCategories(_method.Object, typeof(ReflectHelperTests)).ToArray(); + string[] actual = [.. _reflectHelper.GetTestCategories(_method.Object, typeof(ReflectHelperTests))]; string[] expected = ["MethodLevel1", "MethodLevel2", "ClassLevel1", "ClassLevel2", "AsmLevel1", "AsmLevel2"]; Verify(expected.SequenceEqual(actual)); @@ -97,7 +97,7 @@ public void GetTestCategoryAttributeShouldIncludeTestCategoriesAtAssemblyLevel() string[] expected = ["AsmLevel"]; - string[] actual = _reflectHelper.GetTestCategories(_method.Object, typeof(ReflectHelperTests)).ToArray(); + string[] actual = [.. _reflectHelper.GetTestCategories(_method.Object, typeof(ReflectHelperTests))]; Verify(expected.SequenceEqual(actual)); } @@ -110,7 +110,7 @@ public void GetTestCategoryAttributeShouldIncludeMultipleTestCategoriesAtClassLe _attributeMockingHelper.SetCustomAttribute(typeof(TestCategoryBaseAttribute), [new TestCategoryAttribute("ClassLevel"), new TestCategoryAttribute("ClassLevel1")], MemberTypes.TypeInfo); string[] expected = ["ClassLevel", "ClassLevel1"]; - string[] actual = _reflectHelper.GetTestCategories(_method.Object, typeof(ReflectHelperTests)).ToArray(); + string[] actual = [.. _reflectHelper.GetTestCategories(_method.Object, typeof(ReflectHelperTests))]; Verify(expected.SequenceEqual(actual)); } @@ -123,7 +123,7 @@ public void GetTestCategoryAttributeShouldIncludeMultipleTestCategoriesAtAssembl _attributeMockingHelper.SetCustomAttribute(typeof(TestCategoryBaseAttribute), [new TestCategoryAttribute("AsmLevel"), new TestCategoryAttribute("AsmLevel1")], MemberTypes.All); string[] expected = ["AsmLevel", "AsmLevel1"]; - string[] actual = _reflectHelper.GetTestCategories(_method.Object, typeof(ReflectHelperTests)).ToArray(); + string[] actual = [.. _reflectHelper.GetTestCategories(_method.Object, typeof(ReflectHelperTests))]; Verify(expected.SequenceEqual(actual)); } @@ -135,7 +135,7 @@ public void GetTestCategoryAttributeShouldIncludeTestCategoriesAtMethodLevel() _attributeMockingHelper.SetCustomAttribute(typeof(TestCategoryBaseAttribute), [new TestCategoryAttribute("MethodLevel")], MemberTypes.Method); string[] expected = ["MethodLevel"]; - string[] actual = _reflectHelper.GetTestCategories(_method.Object, typeof(ReflectHelperTests)).ToArray(); + string[] actual = [.. _reflectHelper.GetTestCategories(_method.Object, typeof(ReflectHelperTests))]; Verify(expected.SequenceEqual(actual)); } @@ -274,8 +274,8 @@ public void GettingAttributesShouldNotReturnInheritedAttributesWhenAskingForNonI Setup(ro => ro.GetCustomAttributes(It.IsAny(), /* inherit */ false)). Returns([new TestClassAttribute()]); - TestClassAttribute[] inheritedAttributes = rh.GetAttributes(typeof(object), inherit: true).ToArray(); - TestClassAttribute[] nonInheritedAttributes = rh.GetAttributes(typeof(object), inherit: false).ToArray(); + TestClassAttribute[] inheritedAttributes = [.. rh.GetAttributes(typeof(object), inherit: true)]; + TestClassAttribute[] nonInheritedAttributes = [.. rh.GetAttributes(typeof(object), inherit: false)]; Verify(inheritedAttributes.Length == 2); Verify(nonInheritedAttributes.Length == 1); @@ -291,7 +291,7 @@ internal class AttributeMockingHelper /// MemberTypes.TypeInfo for class level /// MemberTypes.Method for method level. /// - private readonly List<(Type Type, Attribute Attribute, MemberTypes MemberType)> _data = new(); + private readonly List<(Type Type, Attribute Attribute, MemberTypes MemberType)> _data = []; private readonly Mock _mockReflectionOperations; public void SetCustomAttribute(Type type, Attribute[] values, MemberTypes memberTypes) diff --git a/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/AppInsightsProviderTests.cs b/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/AppInsightsProviderTests.cs index 95068374c5..c281ef4a14 100644 --- a/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/AppInsightsProviderTests.cs +++ b/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/AppInsightsProviderTests.cs @@ -32,7 +32,7 @@ public void Platform_CancellationToken_Cancellation_Should_Exit_Gracefully() Mock testApplicationCancellationTokenSource = new(); testApplicationCancellationTokenSource.Setup(x => x.CancellationToken).Returns(cancellationTokenSource.Token); - List events = new(); + List events = []; Mock testTelemetryClient = new(); testTelemetryClient.Setup(x => x.TrackEvent(It.IsAny(), It.IsAny>(), It.IsAny>())) .Callback((string eventName, Dictionary properties, Dictionary metrics) => diff --git a/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/TrxTests.cs b/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/TrxTests.cs index 0f1a96c59d..6e94f8fe07 100644 --- a/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/TrxTests.cs +++ b/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/TrxTests.cs @@ -27,7 +27,7 @@ public class TrxTests private readonly Mock _testFrameworkMock = new(); private readonly Mock _testApplicationModuleInfoMock = new(); private readonly Mock _fileSystem = new(); - private readonly Dictionary> _artifactsByExtension = new(); + private readonly Dictionary> _artifactsByExtension = []; [TestMethod] public async Task TrxReportEngine_GenerateReportAsyncWithNullAdapterSupportTrxCapability_TrxDoesNotContainClassName() diff --git a/test/UnitTests/Microsoft.Testing.Extensions.VSTestBridge.UnitTests/ObjectModel/ObjectModelConvertersTests.cs b/test/UnitTests/Microsoft.Testing.Extensions.VSTestBridge.UnitTests/ObjectModel/ObjectModelConvertersTests.cs index 14d64e2688..d5971e5cb8 100644 --- a/test/UnitTests/Microsoft.Testing.Extensions.VSTestBridge.UnitTests/ObjectModel/ObjectModelConvertersTests.cs +++ b/test/UnitTests/Microsoft.Testing.Extensions.VSTestBridge.UnitTests/ObjectModel/ObjectModelConvertersTests.cs @@ -65,7 +65,7 @@ public void ToTestNode_WhenTestResultOutcomeIsFailed_TestNodePropertiesContainFa }; var testNode = testResult.ToTestNode(false, null, new ConsoleCommandLineOptions(), ClientInfo); - FailedTestNodeStateProperty[] failedTestNodeStateProperties = testNode.Properties.OfType().ToArray(); + FailedTestNodeStateProperty[] failedTestNodeStateProperties = [.. testNode.Properties.OfType()]; Assert.AreEqual(1, failedTestNodeStateProperties.Length); Assert.IsTrue(failedTestNodeStateProperties[0].Exception is VSTestException); Assert.AreEqual(testResult.ErrorStackTrace, failedTestNodeStateProperties[0].Exception!.StackTrace); @@ -83,7 +83,7 @@ public void ToTestNode_WhenTestResultHasMSTestDiscovererTestCategoryTestProperty var testNode = testResult.ToTestNode(false, new NamedFeatureCapabilityWithVSTestProvider(), new ServerModeCommandLineOptions(), ClientInfo); - TestMetadataProperty[] testMetadatas = testNode.Properties.OfType().ToArray(); + TestMetadataProperty[] testMetadatas = [.. testNode.Properties.OfType()]; Assert.AreEqual(1, testMetadatas.Length); Assert.AreEqual("category1", testMetadatas[0].Key); Assert.AreEqual(string.Empty, testMetadatas[0].Value); @@ -100,7 +100,7 @@ public void ToTestNode_WhenTestResultHasMSTestDiscovererTestCategoryTestProperty var testNode = testResult.ToTestNode(true, new NamedFeatureCapabilityWithVSTestProvider(), new ServerModeCommandLineOptions(), ClientInfo); - TrxCategoriesProperty[] trxCategoriesProperty = testNode.Properties.OfType().ToArray(); + TrxCategoriesProperty[] trxCategoriesProperty = [.. testNode.Properties.OfType()]; Assert.AreEqual(1, trxCategoriesProperty.Length); Assert.AreEqual(1, trxCategoriesProperty[0].Categories.Length); Assert.AreEqual("category1", trxCategoriesProperty[0].Categories[0]); @@ -117,7 +117,7 @@ public void ToTestNode_WhenTestCaseHasOriginalExecutorUriProperty_TestNodeProper var testNode = testCase.ToTestNode(false, new NamedFeatureCapabilityWithVSTestProvider(), new ServerModeCommandLineOptions(), ClientInfo); - SerializableKeyValuePairStringProperty[] serializableKeyValuePairStringProperty = testNode.Properties.OfType().ToArray(); + SerializableKeyValuePairStringProperty[] serializableKeyValuePairStringProperty = [.. testNode.Properties.OfType()]; Assert.AreEqual(3, serializableKeyValuePairStringProperty.Length); Assert.AreEqual(VSTestTestNodeProperties.OriginalExecutorUriPropertyName, serializableKeyValuePairStringProperty[0].Key); Assert.AreEqual("https://vs.com/", serializableKeyValuePairStringProperty[0].Value); @@ -173,7 +173,7 @@ public void ToTestNode_WhenTestResultOutcomeIsNotFoundWithoutSetErrorMessage_Tes }; var testNode = testResult.ToTestNode(false, null, new ConsoleCommandLineOptions(), ClientInfo); - ErrorTestNodeStateProperty[] errorTestNodeStateProperties = testNode.Properties.OfType().ToArray(); + ErrorTestNodeStateProperty[] errorTestNodeStateProperties = [.. testNode.Properties.OfType()]; Assert.AreEqual(1, errorTestNodeStateProperties.Length); Assert.IsTrue(errorTestNodeStateProperties[0].Exception is VSTestException); Assert.AreEqual(testResult.ErrorStackTrace, errorTestNodeStateProperties[0].Exception!.StackTrace); @@ -189,7 +189,7 @@ public void ToTestNode_WhenTestResultOutcomeIsSkipped_TestNodePropertiesContainS }; var testNode = testResult.ToTestNode(false, null, new ConsoleCommandLineOptions(), ClientInfo); - SkippedTestNodeStateProperty[] skipTestNodeStateProperties = testNode.Properties.OfType().ToArray(); + SkippedTestNodeStateProperty[] skipTestNodeStateProperties = [.. testNode.Properties.OfType()]; Assert.AreEqual(1, skipTestNodeStateProperties.Length); } @@ -202,7 +202,7 @@ public void ToTestNode_WhenTestResultOutcomeIsNone_TestNodePropertiesContainSkip }; var testNode = testResult.ToTestNode(false, null, new ConsoleCommandLineOptions(), ClientInfo); - SkippedTestNodeStateProperty[] skipTestNodeStateProperties = testNode.Properties.OfType().ToArray(); + SkippedTestNodeStateProperty[] skipTestNodeStateProperties = [.. testNode.Properties.OfType()]; Assert.AreEqual(1, skipTestNodeStateProperties.Length); } @@ -215,7 +215,7 @@ public void ToTestNode_WhenTestResultOutcomeIsPassed_TestNodePropertiesContainPa }; var testNode = testResult.ToTestNode(false, null, new ConsoleCommandLineOptions(), ClientInfo); - PassedTestNodeStateProperty[] passedTestNodeStateProperties = testNode.Properties.OfType().ToArray(); + PassedTestNodeStateProperty[] passedTestNodeStateProperties = [.. testNode.Properties.OfType()]; Assert.AreEqual(1, passedTestNodeStateProperties.Length); } @@ -226,7 +226,7 @@ public void ToTestNode_WhenTestCaseHasUidAndDisplayNameWithWellKnownClient_TestN var testNode = testCase.ToTestNode(false, new NamedFeatureCapabilityWithVSTestProvider(), new ServerModeCommandLineOptions(), ClientInfo); - SerializableKeyValuePairStringProperty[] errorTestNodeStateProperties = testNode.Properties.OfType().ToArray(); + SerializableKeyValuePairStringProperty[] errorTestNodeStateProperties = [.. testNode.Properties.OfType()]; Assert.AreEqual(2, errorTestNodeStateProperties.Length, "Expected 2 SerializableKeyValuePairStringProperty"); Assert.AreEqual("vstest.TestCase.FullyQualifiedName", errorTestNodeStateProperties[0].Key); Assert.AreEqual("SomeFqn", errorTestNodeStateProperties[0].Value); @@ -244,7 +244,7 @@ public void ToTestNode_WhenTestResultHasTraits_TestNodePropertiesContainIt() var testNode = testResult.ToTestNode(false, new NamedFeatureCapabilityWithVSTestProvider(), new ServerModeCommandLineOptions(), ClientInfo); - TestMetadataProperty[] testMetadatas = testNode.Properties.OfType().ToArray(); + TestMetadataProperty[] testMetadatas = [.. testNode.Properties.OfType()]; Assert.AreEqual(1, testMetadatas.Length); Assert.AreEqual("key", testMetadatas[0].Key); Assert.AreEqual("value", testMetadatas[0].Value); @@ -265,7 +265,7 @@ public void ToTestNode_WhenTestResultHasMultipleStandardOutputMessages_TestNodeP var testNode = testResult.ToTestNode(false, new NamedFeatureCapabilityWithVSTestProvider(), new ServerModeCommandLineOptions(), ClientInfo); - StandardOutputProperty[] standardOutputProperties = testNode.Properties.OfType().ToArray(); + StandardOutputProperty[] standardOutputProperties = [.. testNode.Properties.OfType()]; Assert.IsTrue(standardOutputProperties.Length == 1); Assert.AreEqual($"message1{Environment.NewLine}message2", standardOutputProperties[0].StandardOutput); } @@ -285,7 +285,7 @@ public void ToTestNode_WhenTestResultHasMultipleStandardErrorMessages_TestNodePr var testNode = testResult.ToTestNode(false, new NamedFeatureCapabilityWithVSTestProvider(), new ServerModeCommandLineOptions(), ClientInfo); - StandardErrorProperty[] standardErrorProperties = testNode.Properties.OfType().ToArray(); + StandardErrorProperty[] standardErrorProperties = [.. testNode.Properties.OfType()]; Assert.IsTrue(standardErrorProperties.Length == 1); Assert.AreEqual($"message1{Environment.NewLine}message2", standardErrorProperties[0].StandardError); } diff --git a/test/UnitTests/Microsoft.Testing.Extensions.VSTestBridge.UnitTests/ObjectModel/RunSettingsPatcherTests.cs b/test/UnitTests/Microsoft.Testing.Extensions.VSTestBridge.UnitTests/ObjectModel/RunSettingsPatcherTests.cs index 92c52dbde1..262f7bc9ae 100644 --- a/test/UnitTests/Microsoft.Testing.Extensions.VSTestBridge.UnitTests/ObjectModel/RunSettingsPatcherTests.cs +++ b/test/UnitTests/Microsoft.Testing.Extensions.VSTestBridge.UnitTests/ObjectModel/RunSettingsPatcherTests.cs @@ -94,7 +94,7 @@ public void Patch_WhenRunSettingsExists_MergesParameters() XDocument runSettingsDocument = RunSettingsPatcher.Patch(runSettings, _configuration.Object, new ClientInfoService(string.Empty, string.Empty), _commandLineOptions.Object); - XElement[] testRunParameters = runSettingsDocument.XPathSelectElements("RunSettings/TestRunParameters/Parameter").ToArray(); + XElement[] testRunParameters = [.. runSettingsDocument.XPathSelectElements("RunSettings/TestRunParameters/Parameter")]; Assert.AreEqual("key1", testRunParameters[0].Attribute("name")!.Value); Assert.AreEqual("value1", testRunParameters[0].Attribute("value")!.Value); Assert.AreEqual("key2", testRunParameters[1].Attribute("name")!.Value); @@ -118,7 +118,7 @@ public void Patch_WhenRunSettingsDoesNotExist_AddParameters() XDocument runSettingsDocument = RunSettingsPatcher.Patch(null, _configuration.Object, new ClientInfoService(string.Empty, string.Empty), _commandLineOptions.Object); - XElement[] testRunParameters = runSettingsDocument.XPathSelectElements("RunSettings/TestRunParameters/Parameter").ToArray(); + XElement[] testRunParameters = [.. runSettingsDocument.XPathSelectElements("RunSettings/TestRunParameters/Parameter")]; Assert.AreEqual("key1", testRunParameters[0].Attribute("name")!.Value); Assert.AreEqual("value1", testRunParameters[0].Attribute("value")!.Value); Assert.AreEqual("key2", testRunParameters[1].Attribute("name")!.Value); diff --git a/test/UnitTests/Microsoft.Testing.Platform.MSBuild.UnitTests/MSBuildTests.cs b/test/UnitTests/Microsoft.Testing.Platform.MSBuild.UnitTests/MSBuildTests.cs index ad5f780f08..e9762332bd 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.MSBuild.UnitTests/MSBuildTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.MSBuild.UnitTests/MSBuildTests.cs @@ -10,15 +10,11 @@ namespace Microsoft.Testing.Platform.MSBuild.UnitTests; [TestClass] public sealed class MSBuildTests { - private readonly Mock _buildEngine; - private readonly List _errors; + private readonly Mock _buildEngine = new(); + private readonly List _errors = []; - public MSBuildTests() - { - _buildEngine = new Mock(); - _errors = new List(); + public MSBuildTests() => _buildEngine.Setup(x => x.LogErrorEvent(It.IsAny())).Callback(e => _errors.Add(e)); - } [TestMethod] public void Verify_Correct_Registration_Order_For_WellKnown_Extensions() @@ -65,7 +61,7 @@ internal sealed class MicrosoftTestingPlatformEntryPoint private sealed class InMemoryFileSystem : IFileSystem { - public Dictionary Files { get; } = new(); + public Dictionary Files { get; } = []; public void CopyFile(string source, string destination) => throw new NotImplementedException(); @@ -80,7 +76,7 @@ private sealed class InMemoryFileSystem : IFileSystem private sealed class CustomTaskItem : ITaskItem { - private readonly Dictionary _keyValuePairs = new(); + private readonly Dictionary _keyValuePairs = []; public CustomTaskItem(string itemSpec) => ItemSpec = itemSpec; diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Configuration/ConfigurationManagerTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Configuration/ConfigurationManagerTests.cs index aaf9b02821..2465f64839 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Configuration/ConfigurationManagerTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Configuration/ConfigurationManagerTests.cs @@ -29,7 +29,7 @@ public async ValueTask GetConfigurationValueFromJson(string jsonFileConfig, stri CurrentTestApplicationModuleInfo testApplicationModuleInfo = new(new SystemEnvironment(), new SystemProcessHandler()); ConfigurationManager configurationManager = new(fileSystem.Object, testApplicationModuleInfo); configurationManager.AddConfigurationSource(() => new JsonConfigurationSource(testApplicationModuleInfo, fileSystem.Object, null)); - IConfiguration configuration = await configurationManager.BuildAsync(null, new CommandLineParseResult(null, new List(), Array.Empty())); + IConfiguration configuration = await configurationManager.BuildAsync(null, new CommandLineParseResult(null, new List(), [])); Assert.AreEqual(result, configuration[key], $"Expected '{result}' found '{configuration[key]}'"); } @@ -63,9 +63,9 @@ public async ValueTask InvalidJson_Fail() // The behavior difference is System.Text.Json vs Jsonite #if NETFRAMEWORK - await Assert.ThrowsAsync(() => configurationManager.BuildAsync(null, new CommandLineParseResult(null, new List(), Array.Empty())), ex => ex?.ToString() ?? "No exception was thrown"); + await Assert.ThrowsAsync(() => configurationManager.BuildAsync(null, new CommandLineParseResult(null, new List(), [])), ex => ex?.ToString() ?? "No exception was thrown"); #else - await Assert.ThrowsAsync(() => configurationManager.BuildAsync(null, new CommandLineParseResult(null, new List(), Array.Empty())), ex => ex?.ToString() ?? "No exception was thrown"); + await Assert.ThrowsAsync(() => configurationManager.BuildAsync(null, new CommandLineParseResult(null, new List(), [])), ex => ex?.ToString() ?? "No exception was thrown"); #endif } @@ -91,7 +91,7 @@ public async ValueTask GetConfigurationValueFromJsonWithFileLoggerProvider(strin configurationManager.AddConfigurationSource(() => new JsonConfigurationSource(testApplicationModuleInfo, fileSystem.Object, null)); - IConfiguration configuration = await configurationManager.BuildAsync(loggerProviderMock.Object, new CommandLineParseResult(null, new List(), Array.Empty())); + IConfiguration configuration = await configurationManager.BuildAsync(loggerProviderMock.Object, new CommandLineParseResult(null, new List(), [])); Assert.AreEqual(result, configuration[key], $"Expected '{result}' found '{configuration[key]}'"); loggerMock.Verify(x => x.LogAsync(LogLevel.Trace, It.IsAny(), null, LoggingExtensions.Formatter), Times.Once); @@ -102,7 +102,7 @@ public async ValueTask BuildAsync_EmptyConfigurationSources_ThrowsException() { CurrentTestApplicationModuleInfo testApplicationModuleInfo = new(new SystemEnvironment(), new SystemProcessHandler()); ConfigurationManager configurationManager = new(new SystemFileSystem(), testApplicationModuleInfo); - await Assert.ThrowsAsync(() => configurationManager.BuildAsync(null, new CommandLineParseResult(null, new List(), Array.Empty()))); + await Assert.ThrowsAsync(() => configurationManager.BuildAsync(null, new CommandLineParseResult(null, new List(), []))); } [TestMethod] @@ -115,7 +115,7 @@ public async ValueTask BuildAsync_ConfigurationSourcesNotEnabledAsync_ThrowsExce ConfigurationManager configurationManager = new(new SystemFileSystem(), testApplicationModuleInfo); configurationManager.AddConfigurationSource(() => mockConfigurationSource.Object); - await Assert.ThrowsAsync(() => configurationManager.BuildAsync(null, new CommandLineParseResult(null, new List(), Array.Empty()))); + await Assert.ThrowsAsync(() => configurationManager.BuildAsync(null, new CommandLineParseResult(null, new List(), []))); mockConfigurationSource.Verify(x => x.IsEnabledAsync(), Times.Once); } @@ -135,7 +135,7 @@ public async ValueTask BuildAsync_ConfigurationSourceIsAsyncInitializableExtensi ConfigurationManager configurationManager = new(new SystemFileSystem(), testApplicationModuleInfo); configurationManager.AddConfigurationSource(() => fakeConfigurationSource); - await Assert.ThrowsAsync(() => configurationManager.BuildAsync(null, new CommandLineParseResult(null, new List(), Array.Empty()))); + await Assert.ThrowsAsync(() => configurationManager.BuildAsync(null, new CommandLineParseResult(null, new List(), []))); } private class FakeConfigurationSource : IConfigurationSource, IAsyncInitializableExtension diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Helpers/SystemAsyncMonitorTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Helpers/SystemAsyncMonitorTests.cs index d6d0daaa03..aaf9ec1547 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Helpers/SystemAsyncMonitorTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Helpers/SystemAsyncMonitorTests.cs @@ -20,7 +20,7 @@ public async Task AsyncMonitor_ShouldCorrectlyLock() tasks.Add(Task.Run(TestLock)); } - await Task.WhenAll(tasks.ToArray()); + await Task.WhenAll([.. tasks]); // Give more time to be above 3s Thread.Sleep(500); diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/IPCTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/IPCTests.cs index 78beb1d004..e36d719839 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/IPCTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/IPCTests.cs @@ -172,7 +172,7 @@ public async Task ConnectionNamedPipeServer_MultipleConnection_Succeeds() { PipeNameDescription pipeNameDescription = NamedPipeServer.GetPipeName(Guid.NewGuid().ToString("N")); - List pipes = new(); + List pipes = []; for (int i = 0; i < 3; i++) { pipes.Add(new( @@ -196,7 +196,7 @@ public async Task ConnectionNamedPipeServer_MultipleConnection_Succeeds() _testContext.CancellationTokenSource.Token)); StringAssert.Contains(exception.Message, "All pipe instances are busy."); - List waitConnectionTask = new(); + List waitConnectionTask = []; int connectionCompleted = 0; foreach (NamedPipeServer namedPipeServer in pipes) { @@ -207,7 +207,7 @@ public async Task ConnectionNamedPipeServer_MultipleConnection_Succeeds() })); } - List connectedClients = new(); + List connectedClients = []; for (int i = 0; i < waitConnectionTask.Count; i++) { NamedPipeClient namedPipeClient = new(pipeNameDescription.Name); @@ -215,7 +215,7 @@ public async Task ConnectionNamedPipeServer_MultipleConnection_Succeeds() await namedPipeClient.ConnectAsync(_testContext.CancellationTokenSource.Token); } - await Task.WhenAll(waitConnectionTask.ToArray()); + await Task.WhenAll([.. waitConnectionTask]); Assert.AreEqual(3, connectionCompleted); @@ -235,8 +235,7 @@ public async Task ConnectionNamedPipeServer_MultipleConnection_Succeeds() private static string RandomString(int length, Random random) { const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; - return new string(Enumerable.Repeat(chars, length) - .Select(s => s[random.Next(s.Length)]).ToArray()); + return new string([.. Enumerable.Repeat(chars, length).Select(s => s[random.Next(s.Length)])]); } private abstract record BaseMessage : IRequest; diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/ProtocolTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/ProtocolTests.cs index 019aa5219a..73f4309e2f 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/ProtocolTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/ProtocolTests.cs @@ -14,7 +14,7 @@ public void TestResultMessagesSerializeDeserialize() { var success = new SuccessfulTestResultMessage("uid", "displayName", 1, 100, "reason", "standardOutput", "errorOutput", "sessionUid"); var fail = new FailedTestResultMessage("uid", "displayName", 2, 200, "reason", [new ExceptionMessage("errorMessage", "errorType", "stackTrace")], "standardOutput", "errorOutput", "sessionUid"); - var message = new TestResultMessages("executionId", "instanceId", new[] { success }, new[] { fail }); + var message = new TestResultMessages("executionId", "instanceId", [success], [fail]); var stream = new MemoryStream(); new TestResultMessagesSerializer().Serialize(message, stream); diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Logging/LogTestHelpers.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Logging/LogTestHelpers.cs index 571f312dff..cc3883e67b 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Logging/LogTestHelpers.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Logging/LogTestHelpers.cs @@ -21,8 +21,8 @@ public static IEnumerable GetLogLevelsForDynamicData() public static IEnumerable<(LogLevel DefaultLevel, LogLevel CurrentLevel)> GetLogLevelCombinations() { - List<(LogLevel, LogLevel)> logLevelCombinations = new(); - LogLevel[] logLevels = GetLogLevels().ToArray(); + List<(LogLevel, LogLevel)> logLevelCombinations = []; + LogLevel[] logLevels = [.. GetLogLevels()]; for (int i = 0; i < logLevels.Length; i++) { diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Messages/AsynchronousMessageBusTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Messages/AsynchronousMessageBusTests.cs index 2d6ba5076e..af1b5c2ab0 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Messages/AsynchronousMessageBusTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Messages/AsynchronousMessageBusTests.cs @@ -120,8 +120,7 @@ public async Task Consumers_ConsumeData_ShouldNotMissAnyPayload() proxy.SetBuiltMessageBus(asynchronousMessageBus); DummyConsumer.DummyProducer producer = new(); - await Task.WhenAll(Enumerable.Range(1, totalPayloads) - .Select(i => Task.Run(async () => await proxy.PublishAsync(producer, new DummyConsumer.DummyData { Data = i }))).ToArray()); + await Task.WhenAll([.. Enumerable.Range(1, totalPayloads).Select(i => Task.Run(async () => await proxy.PublishAsync(producer, new DummyConsumer.DummyData { Data = i })))]); await proxy.DrainDataAsync(); diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Messages/PropertyBagTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Messages/PropertyBagTests.cs index 12f4ad6b23..43805d2171 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Messages/PropertyBagTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Messages/PropertyBagTests.cs @@ -143,7 +143,7 @@ public void AsEnumerable_Should_Return_CorrectItems() Assert.AreEqual(0, list.Count); - list = property.AsEnumerable().ToList(); + list = [.. property.AsEnumerable()]; foreach (IProperty prop in property) { list.Remove(prop); diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/ServerMode/FormatterUtilitiesTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/ServerMode/FormatterUtilitiesTests.cs index 75b6c6ee89..b400dcd61a 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/ServerMode/FormatterUtilitiesTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/ServerMode/FormatterUtilitiesTests.cs @@ -363,7 +363,7 @@ private static object CreateInstance(Type type) if (type == typeof(TestsAttachments)) { - return new TestsAttachments(new RunTestAttachment[] { new("Uri", "Producer", "Type", "DisplayName", "Description") }); + return new TestsAttachments([new("Uri", "Producer", "Type", "DisplayName", "Description")]); } if (type == typeof(RunTestAttachment)) diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/ServerMode/JsonTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/ServerMode/JsonTests.cs index e7afcf77ec..f3e0ffd468 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/ServerMode/JsonTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/ServerMode/JsonTests.cs @@ -16,13 +16,13 @@ public sealed class JsonTests public JsonTests() { - Dictionary serializers = new(); - Dictionary deserializers = new(); + Dictionary serializers = []; + Dictionary deserializers = []; foreach (Type serializableType in SerializerUtilities.SerializerTypes) { serializers[serializableType] = new JsonObjectSerializer( - o => SerializerUtilities.Serialize(serializableType, o).Select(kvp => (kvp.Key, kvp.Value)).ToArray()); + o => [.. SerializerUtilities.Serialize(serializableType, o).Select(kvp => (kvp.Key, kvp.Value))]); } foreach (Type deserializableType in SerializerUtilities.DeserializerTypes) diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/ServerMode/JsoniteTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/ServerMode/JsoniteTests.cs index d2aa862511..ebc6fac83b 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/ServerMode/JsoniteTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/ServerMode/JsoniteTests.cs @@ -22,7 +22,7 @@ public void Serialize_SpecialCharacters() { // This test is testing if we can serialize the range 0x0000 - 0x001FF correctly, this range contains special characters like NUL. // This is a fix for Jsonite, which throws when such characters are found in a string (but does not fail when we provide them as character). - List errors = new(); + List errors = []; // This could be converted to Data source, but this way we have more control about where in the result message the // special characters will be (hopefully nowhere) so in case of failure, we can still serialize the message to IDE diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Services/TestApplicationResultTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Services/TestApplicationResultTests.cs index 580fd28310..1d74be935a 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Services/TestApplicationResultTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Services/TestApplicationResultTests.cs @@ -214,10 +214,10 @@ public void GetProcessExitCodeAsync_IgnoreExitCodes(string? argument, int expect internal static IEnumerable FailedState() { - yield return new[] { new FailedTestNodeStateProperty() }; - yield return new[] { new ErrorTestNodeStateProperty() }; - yield return new[] { new CancelledTestNodeStateProperty() }; - yield return new[] { new TimeoutTestNodeStateProperty() }; + yield return [new FailedTestNodeStateProperty()]; + yield return [new ErrorTestNodeStateProperty()]; + yield return [new CancelledTestNodeStateProperty()]; + yield return [new TimeoutTestNodeStateProperty()]; } private sealed class CommandLineOption : ICommandLineOptions diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/TestApplicationBuilderTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/TestApplicationBuilderTests.cs index d35d3d8e62..152e35d6e3 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/TestApplicationBuilderTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/TestApplicationBuilderTests.cs @@ -91,8 +91,8 @@ public async Task TestHost_ComposeFactory_ShouldSucceed(bool withParameter) testHostManager.AddTestSessionLifetimeHandle(compositeExtensionFactory); testHostManager.AddDataConsumer(compositeExtensionFactory); List compositeExtensions = []; - IDataConsumer[] consumers = (await testHostManager.BuildDataConsumersAsync(_serviceProvider, compositeExtensions)).Select(x => (IDataConsumer)x.Consumer).ToArray(); - ITestSessionLifetimeHandler[] sessionLifetimeHandle = (await testHostManager.BuildTestSessionLifetimeHandleAsync(_serviceProvider, compositeExtensions)).Select(x => (ITestSessionLifetimeHandler)x.TestSessionLifetimeHandler).ToArray(); + IDataConsumer[] consumers = [.. (await testHostManager.BuildDataConsumersAsync(_serviceProvider, compositeExtensions)).Select(x => (IDataConsumer)x.Consumer)]; + ITestSessionLifetimeHandler[] sessionLifetimeHandle = [.. (await testHostManager.BuildTestSessionLifetimeHandleAsync(_serviceProvider, compositeExtensions)).Select(x => (ITestSessionLifetimeHandler)x.TestSessionLifetimeHandler)]; Assert.AreEqual(1, consumers.Length); Assert.AreEqual(1, sessionLifetimeHandle.Length); Assert.AreEqual(compositeExtensions[0].GetInstance(), consumers[0]); diff --git a/test/UnitTests/TestFramework.UnitTests/Assertions/CollectionAssertTests.cs b/test/UnitTests/TestFramework.UnitTests/Assertions/CollectionAssertTests.cs index 877e51b57a..4c32ca18af 100644 --- a/test/UnitTests/TestFramework.UnitTests/Assertions/CollectionAssertTests.cs +++ b/test/UnitTests/TestFramework.UnitTests/Assertions/CollectionAssertTests.cs @@ -488,7 +488,7 @@ private static List GenerateDeeplyNestedCollection(int depth) { if (depth == 0) { - return new List { new ReadOnlyCollection(Enumerable.Range(1, 10).ToList()) }; + return [new ReadOnlyCollection([.. Enumerable.Range(1, 10)])]; } var nestedCollection = new List(); @@ -528,14 +528,14 @@ private static List GenerateDeeplyNestedCollection(int depth) private ICollection? GetNonICollectionInnerCollection() => new List> { - new(new List { 1, 2 }), - new(new List { 3, 4 }), + new([1, 2]), + new([3, 4]), }; private ICollection? GetNotMatchingGetNonICollectionInnerCollection() => new List> { - new(new List { 6, 5 }), - new(new List { 3, 4 }), + new([6, 5]), + new([3, 4]), }; private Type? GetStringType() => typeof(string); diff --git a/test/Utilities/Microsoft.Testing.TestInfrastructure/CommandLine.cs b/test/Utilities/Microsoft.Testing.TestInfrastructure/CommandLine.cs index 3fd02adb5b..883e1f367d 100644 --- a/test/Utilities/Microsoft.Testing.TestInfrastructure/CommandLine.cs +++ b/test/Utilities/Microsoft.Testing.TestInfrastructure/CommandLine.cs @@ -14,8 +14,8 @@ public sealed class CommandLine : IDisposable public static int TotalProcessesAttempt => s_totalProcessesAttempt; - private readonly List _errorOutputLines = new(); - private readonly List _standardOutputLines = new(); + private readonly List _errorOutputLines = []; + private readonly List _standardOutputLines = []; private IProcessHandle? _process; public ReadOnlyCollection StandardOutputLines => _standardOutputLines.AsReadOnly(); diff --git a/test/Utilities/Microsoft.Testing.TestInfrastructure/DotnetCli.cs b/test/Utilities/Microsoft.Testing.TestInfrastructure/DotnetCli.cs index 0d7c7413a0..03ec18f867 100644 --- a/test/Utilities/Microsoft.Testing.TestInfrastructure/DotnetCli.cs +++ b/test/Utilities/Microsoft.Testing.TestInfrastructure/DotnetCli.cs @@ -64,7 +64,7 @@ public static async Task RunAsync( await s_maxOutstandingCommands_semaphore.WaitAsync(); try { - environmentVariables ??= new Dictionary(); + environmentVariables ??= []; foreach (DictionaryEntry entry in Environment.GetEnvironmentVariables()) { // Skip all unwanted environment variables. diff --git a/test/Utilities/Microsoft.Testing.TestInfrastructure/ProjectSystem.cs b/test/Utilities/Microsoft.Testing.TestInfrastructure/ProjectSystem.cs index 91deff4f72..f19bde0388 100644 --- a/test/Utilities/Microsoft.Testing.TestInfrastructure/ProjectSystem.cs +++ b/test/Utilities/Microsoft.Testing.TestInfrastructure/ProjectSystem.cs @@ -46,7 +46,7 @@ public VSSolution(string? solutionFolder, string? solutionName) AddOrUpdateFileContent(_solutionFileName, MergeSolutionContent()); } - public ICollection Projects { get; } = new List(); + public ICollection Projects { get; } = []; public string SolutionFile { get; private set; } diff --git a/test/Utilities/Microsoft.Testing.TestInfrastructure/TargetFrameworks.cs b/test/Utilities/Microsoft.Testing.TestInfrastructure/TargetFrameworks.cs index 3d4b2ffb33..6a8e91de1f 100644 --- a/test/Utilities/Microsoft.Testing.TestInfrastructure/TargetFrameworks.cs +++ b/test/Utilities/Microsoft.Testing.TestInfrastructure/TargetFrameworks.cs @@ -24,7 +24,7 @@ public static class TargetFrameworks public static string[] All { get; } = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) - ? Net.Concat(NetFramework).ToArray() + ? [.. Net, .. NetFramework] : Net; public static IEnumerable AllForDynamicData { get; } = diff --git a/test/Utilities/Microsoft.Testing.TestInfrastructure/TempDirectory.cs b/test/Utilities/Microsoft.Testing.TestInfrastructure/TempDirectory.cs index 76dcfca4b6..285a53fe3a 100644 --- a/test/Utilities/Microsoft.Testing.TestInfrastructure/TempDirectory.cs +++ b/test/Utilities/Microsoft.Testing.TestInfrastructure/TempDirectory.cs @@ -131,7 +131,7 @@ public string[] CopyFile(params string[] filePaths) paths.Add(destination); } - return paths.ToArray(); + return [.. paths]; } /// diff --git a/test/Utilities/Microsoft.Testing.TestInfrastructure/TestHost.cs b/test/Utilities/Microsoft.Testing.TestInfrastructure/TestHost.cs index 32352b750b..44c7a12894 100644 --- a/test/Utilities/Microsoft.Testing.TestInfrastructure/TestHost.cs +++ b/test/Utilities/Microsoft.Testing.TestInfrastructure/TestHost.cs @@ -51,7 +51,7 @@ public async Task ExecuteAsync( throw new InvalidOperationException($"Command should not start with module name '{_testHostModuleName}'."); } - environmentVariables ??= new Dictionary(); + environmentVariables ??= []; if (disableTelemetry) { diff --git a/test/Utilities/TestFramework.ForTestingMSTest/TestFrameworkEngine.cs b/test/Utilities/TestFramework.ForTestingMSTest/TestFrameworkEngine.cs index 0f26913c36..922dd103ac 100644 --- a/test/Utilities/TestFramework.ForTestingMSTest/TestFrameworkEngine.cs +++ b/test/Utilities/TestFramework.ForTestingMSTest/TestFrameworkEngine.cs @@ -20,8 +20,7 @@ public TestFrameworkEngine(TestFrameworkExtension extension, ILoggerFactory logg _logger = loggerFactory.CreateLogger("InternalTestFrameworkEngine"); } - public Type[] DataTypesProduced { get; } - = new Type[1] { typeof(TestNodeUpdateMessage) }; + public Type[] DataTypesProduced { get; } = [typeof(TestNodeUpdateMessage)]; public string Uid => _extension.Uid; @@ -99,7 +98,7 @@ private async Task ExecuteTestNodeRunAsync(RunTestExecutionRequest request, IMes testContainerType.Name, publicMethod.Name, publicMethod.GetGenericArguments().Length, - publicMethod.GetParameters().Select(x => x.ParameterType.FullName!).ToArray(), + [.. publicMethod.GetParameters().Select(x => x.ParameterType.FullName!)], publicMethod.ReturnType.FullName!)); testNode.Properties.Add(new TrxFullyQualifiedTypeNameProperty(testContainerType.FullName!)); @@ -176,7 +175,7 @@ private async Task ExecuteTestNodeDiscoveryAsync(DiscoverTestExecutionRequest re testContainerType.Name, publicMethod.Name, publicMethod.GetGenericArguments().Length, - publicMethod.GetParameters().Select(x => x.ParameterType.FullName!).ToArray(), + [.. publicMethod.GetParameters().Select(x => x.ParameterType.FullName!)], publicMethod.ReturnType.FullName!)); await messageBus.PublishAsync(this, new TestNodeUpdateMessage(request.Session.SessionUid, testNode)); From ffa7287ceef96e4dbdb7e02a7a1deeae377441e3 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Mon, 2 Jun 2025 17:12:11 +0200 Subject: [PATCH 049/541] Add quotes around MSBuild property when performing comparison (#5678) --- .../Microsoft.Testing.Platform.MSBuild.targets | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Platform/Microsoft.Testing.Platform.MSBuild/buildMultiTargeting/Microsoft.Testing.Platform.MSBuild.targets b/src/Platform/Microsoft.Testing.Platform.MSBuild/buildMultiTargeting/Microsoft.Testing.Platform.MSBuild.targets index 882b0396c6..04b28bc764 100644 --- a/src/Platform/Microsoft.Testing.Platform.MSBuild/buildMultiTargeting/Microsoft.Testing.Platform.MSBuild.targets +++ b/src/Platform/Microsoft.Testing.Platform.MSBuild/buildMultiTargeting/Microsoft.Testing.Platform.MSBuild.targets @@ -4,7 +4,7 @@ - $(MSBuildThisFileDirectory)..\_MSBuildTasks\netstandard2.0\ + $(MSBuildThisFileDirectory)..\_MSBuildTasks\netstandard2.0\ From 6f11fa52de4374676a6576189c38c4e4781a0b6f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Jare=C5=A1?= Date: Mon, 2 Jun 2025 18:04:54 +0200 Subject: [PATCH 050/541] Show colors in AzDo and GH actions (#5535) --- .../RetryOrchestrator.cs | 2 +- .../Terminal/AnsiTerminalTestProgressFrame.cs | 6 +- .../OutputDevice/Terminal/NonAnsiTerminal.cs | 241 ++--------------- .../Terminal/SimpleAnsiTerminal.cs | 66 +++++ .../Terminal/SimpleTerminalBase.cs | 223 ++++++++++++++++ .../Terminal/TerminalTestReporter.cs | 52 ++-- .../Terminal/TerminalTestReporterOptions.cs | 6 + .../OutputDevice/TerminalOutputDevice.cs | 4 + .../ConsoleTests.cs | 2 +- .../ExitOnProcessExitTests.cs | 9 +- .../Terminal/TerminalTestReporterTests.cs | 243 ++++++++++++++++-- .../TestHost.cs | 4 +- 12 files changed, 586 insertions(+), 272 deletions(-) create mode 100644 src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/SimpleAnsiTerminal.cs create mode 100644 src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/SimpleTerminalBase.cs diff --git a/src/Platform/Microsoft.Testing.Extensions.Retry/RetryOrchestrator.cs b/src/Platform/Microsoft.Testing.Extensions.Retry/RetryOrchestrator.cs index 94bc289dd5..03cabcb6d7 100644 --- a/src/Platform/Microsoft.Testing.Extensions.Retry/RetryOrchestrator.cs +++ b/src/Platform/Microsoft.Testing.Extensions.Retry/RetryOrchestrator.cs @@ -292,7 +292,7 @@ public async Task OrchestrateTestHostExecutionAsync() } else { - await outputDevice.DisplayAsync(this, new FormattedTextOutputDeviceData(string.Format(CultureInfo.InvariantCulture, ExtensionResources.TestSuiteCompletedSuccessfully, attemptCount)) { ForegroundColor = new SystemConsoleColor { ConsoleColor = ConsoleColor.Green } }); + await outputDevice.DisplayAsync(this, new FormattedTextOutputDeviceData(string.Format(CultureInfo.InvariantCulture, ExtensionResources.TestSuiteCompletedSuccessfully, attemptCount)) { ForegroundColor = new SystemConsoleColor { ConsoleColor = ConsoleColor.DarkGreen } }); } } diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/AnsiTerminalTestProgressFrame.cs b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/AnsiTerminalTestProgressFrame.cs index 71649d1dea..272e73c412 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/AnsiTerminalTestProgressFrame.cs +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/AnsiTerminalTestProgressFrame.cs @@ -37,7 +37,7 @@ public void AppendTestWorkerProgress(TestProgressState progress, RenderedProgres terminal.Append('['); charsTaken++; - terminal.SetColor(TerminalColor.Green); + terminal.SetColor(TerminalColor.DarkGreen); terminal.Append('✓'); charsTaken++; string passedText = passed.ToString(CultureInfo.CurrentCulture); @@ -48,7 +48,7 @@ public void AppendTestWorkerProgress(TestProgressState progress, RenderedProgres terminal.Append('/'); charsTaken++; - terminal.SetColor(TerminalColor.Red); + terminal.SetColor(TerminalColor.DarkRed); terminal.Append('x'); charsTaken++; string failedText = failed.ToString(CultureInfo.CurrentCulture); @@ -59,7 +59,7 @@ public void AppendTestWorkerProgress(TestProgressState progress, RenderedProgres terminal.Append('/'); charsTaken++; - terminal.SetColor(TerminalColor.Yellow); + terminal.SetColor(TerminalColor.DarkYellow); terminal.Append('↓'); charsTaken++; string skippedText = skipped.ToString(CultureInfo.CurrentCulture); diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/NonAnsiTerminal.cs b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/NonAnsiTerminal.cs index 11af53dc1e..78b26ac13d 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/NonAnsiTerminal.cs +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/NonAnsiTerminal.cs @@ -2,7 +2,6 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.Testing.Platform.Helpers; -using Microsoft.Testing.Platform.Resources; namespace Microsoft.Testing.Platform.OutputDevice.Terminal; @@ -10,143 +9,48 @@ namespace Microsoft.Testing.Platform.OutputDevice.Terminal; /// Non-ANSI terminal that writes text using the standard Console.Foreground color capabilities to stay compatible with /// standard Windows command line, and other command lines that are not capable of ANSI, or when output is redirected. /// -internal sealed class NonAnsiTerminal : ITerminal +internal sealed class NonAnsiTerminal : SimpleTerminal { - private readonly IConsole _console; private readonly ConsoleColor _defaultForegroundColor; - private bool _isBatching; - private object? _batchingLock; + private bool? _colorNotSupported; public NonAnsiTerminal(IConsole console) - { - _console = console; - _defaultForegroundColor = IsForegroundColorNotSupported() ? ConsoleColor.Black : _console.GetForegroundColor(); - } - -#pragma warning disable CA1416 // Validate platform compatibility - public int Width => _console.IsOutputRedirected ? int.MaxValue : _console.BufferWidth; - - public int Height => _console.IsOutputRedirected ? int.MaxValue : _console.BufferHeight; -#pragma warning restore CA1416 // Validate platform compatibility - - public void Append(char value) - => _console.Write(value); - - public void Append(string value) - => _console.Write(value); - - public void AppendLine() - => _console.WriteLine(); - - public void AppendLine(string value) - => _console.WriteLine(value); - - public void AppendLink(string path, int? lineNumber) - { - Append(path); - if (lineNumber.HasValue) - { - Append($":{lineNumber}"); - } - } + : base(console) + => _defaultForegroundColor = IsForegroundColorNotSupported() ? ConsoleColor.Black : console.GetForegroundColor(); - public void SetColor(TerminalColor color) + public override void SetColor(TerminalColor color) { if (IsForegroundColorNotSupported()) { return; } - _console.SetForegroundColor(ToConsoleColor(color)); + Console.SetForegroundColor(ToConsoleColor(color)); } - public void ResetColor() + public override void ResetColor() { if (IsForegroundColorNotSupported()) { return; } - _console.SetForegroundColor(_defaultForegroundColor); - } - - public void ShowCursor() - { - // nop + Console.SetForegroundColor(_defaultForegroundColor); } - public void HideCursor() - { - // nop - } - - // TODO: Refactor NonAnsiTerminal and AnsiTerminal such that we don't need StartUpdate/StopUpdate. - // It's much better if we use lock C# keyword instead of manually calling Monitor.Enter/Exit - // Using lock also ensures we don't accidentally have `await`s in between that could cause Exit to be on a different thread. - public void StartUpdate() + [SupportedOSPlatformGuard("android")] + [SupportedOSPlatformGuard("ios")] + [SupportedOSPlatformGuard("tvos")] + [SupportedOSPlatformGuard("browser")] + private bool IsForegroundColorNotSupported() { - if (_isBatching) - { - throw new InvalidOperationException(PlatformResources.ConsoleIsAlreadyInBatchingMode); - } - - bool lockTaken = false; - - // We store Console.Out in a field to make sure we will be doing - // the Monitor.Exit call on the same instance. - _batchingLock = Console.Out; - - // Note that we need to lock on System.Out for batching to work correctly. - // Consider the following scenario: - // 1. We call StartUpdate - // 2. We call a Write("A") - // 3. User calls Console.Write("B") from another thread. - // 4. We call a Write("C"). - // 5. We call StopUpdate. - // The expectation is that we see either ACB, or BAC, but not ABC. - // Basically, when doing batching, we want to ensure that everything we write is - // written continuously, without anything in-between. - // One option (and we used to do it), is that we append to a StringBuilder while batching - // Then at StopUpdate, we write the whole string at once. - // This works to some extent, but we cannot get it to work when SetColor kicks in. - // Console methods will internally lock on Console.Out, so we are locking on the same thing. - // This locking is the easiest way to get coloring to work correctly while preventing - // interleaving with user's calls to Console.Write methods. - // One extra note: - // It's very important to lock on Console.Out (the current Console.Out). - // Consider the following scenario: - // 1. SystemConsole captures the original Console.Out set by runtime. - // 2. Framework author sets his own Console.Out which wraps the original Console.Out. - // 3. Two threads are writing concurrently: - // - One thread is writing using Console.Write* APIs, which will use the Console.Out set by framework author. - // - The other thread is writing using NonAnsiTerminal. - // 4. **If** we lock the original Console.Out. The following may happen (subject to race) [NOT THE CURRENT CASE - imaginary situation if we lock on the original Console.Out]: - // - First thread enters the Console.Write, which will acquire the lock for the current Console.Out (set by framework author). - // - Second thread executes StartUpdate, and acquires the lock for the original Console.Out. - // - First thread continues in the Write implementation of the framework author, which tries to run Console.Write on the original Console.Out. - // - First thread can't make any progress, because the second thread is holding the lock already. - // - Second thread continues execution, and reaches into runtime code (ConsolePal.WriteFromConsoleStream - on Unix) which tries to acquire the lock for the current Console.Out (set by framework author). - // - (see https://github.com/dotnet/runtime/blob/8a9d492444f06df20fcc5dfdcf7a6395af18361f/src/libraries/System.Console/src/System/ConsolePal.Unix.cs#L963) - // - No thread can progress. - // - Basically, what happened is that the first thread acquires the lock for current Console.Out, then for the original Console.Out. - // - while the second thread acquires the lock for the original Console.Out, then for the current Console.Out. - // - That's a typical deadlock where two threads are acquiring two locks in reverse order. - // 5. By locking the *current* Console.Out, we avoid the situation described in 4. - Monitor.Enter(_batchingLock, ref lockTaken); - if (!lockTaken) - { - // Can this happen? :/ - throw new InvalidOperationException(); - } - - _isBatching = true; - } + _colorNotSupported ??= RuntimeInformation.IsOSPlatform(OSPlatform.Create("ANDROID")) || + RuntimeInformation.IsOSPlatform(OSPlatform.Create("IOS")) || + RuntimeInformation.IsOSPlatform(OSPlatform.Create("TVOS")) || + RuntimeInformation.IsOSPlatform(OSPlatform.Create("WASI")) || + RuntimeInformation.IsOSPlatform(OSPlatform.Create("BROWSER")); - public void StopUpdate() - { - Monitor.Exit(_batchingLock!); - _batchingLock = null; - _isBatching = false; + return _colorNotSupported.Value; } private ConsoleColor ToConsoleColor(TerminalColor color) => color switch @@ -170,111 +74,4 @@ public void StopUpdate() TerminalColor.White => ConsoleColor.White, _ => _defaultForegroundColor, }; - - public void EraseProgress() - { - // nop - } - - public void RenderProgress(TestProgressState?[] progress) - { - int count = 0; - foreach (TestProgressState? p in progress) - { - if (p == null) - { - continue; - } - - count++; - - string durationString = HumanReadableDurationFormatter.Render(p.Stopwatch.Elapsed); - - int passed = p.PassedTests; - int failed = p.FailedTests; - int skipped = p.SkippedTests; - - // Use just ascii here, so we don't put too many restrictions on fonts needing to - // properly show unicode, or logs being saved in particular encoding. - Append('['); - SetColor(TerminalColor.DarkGreen); - Append('+'); - Append(passed.ToString(CultureInfo.CurrentCulture)); - ResetColor(); - - Append('/'); - - SetColor(TerminalColor.DarkRed); - Append('x'); - Append(failed.ToString(CultureInfo.CurrentCulture)); - ResetColor(); - - Append('/'); - - SetColor(TerminalColor.DarkYellow); - Append('?'); - Append(skipped.ToString(CultureInfo.CurrentCulture)); - ResetColor(); - Append(']'); - - Append(' '); - Append(p.AssemblyName); - - if (p.TargetFramework != null || p.Architecture != null) - { - Append(" ("); - if (p.TargetFramework != null) - { - Append(p.TargetFramework); - Append('|'); - } - - if (p.Architecture != null) - { - Append(p.Architecture); - } - - Append(')'); - } - - TestDetailState? activeTest = p.TestNodeResultsState?.GetRunningTasks(1).FirstOrDefault(); - if (!RoslynString.IsNullOrWhiteSpace(activeTest?.Text)) - { - Append(" - "); - Append(activeTest.Text); - Append(' '); - } - - Append(durationString); - - AppendLine(); - } - - // Do not render empty lines when there is nothing to show. - if (count > 0) - { - AppendLine(); - } - } - - public void StartBusyIndicator() - { - // nop - } - - public void StopBusyIndicator() - { - // nop - } - - [SupportedOSPlatformGuard("android")] - [SupportedOSPlatformGuard("ios")] - [SupportedOSPlatformGuard("tvos")] - [SupportedOSPlatformGuard("browser")] - private static bool IsForegroundColorNotSupported() - => RuntimeInformation.IsOSPlatform(OSPlatform.Create("ANDROID")) || - RuntimeInformation.IsOSPlatform(OSPlatform.Create("IOS")) || - RuntimeInformation.IsOSPlatform(OSPlatform.Create("TVOS")) || - RuntimeInformation.IsOSPlatform(OSPlatform.Create("WASI")) || - RuntimeInformation.IsOSPlatform(OSPlatform.Create("BROWSER")); } diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/SimpleAnsiTerminal.cs b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/SimpleAnsiTerminal.cs new file mode 100644 index 0000000000..12b4f4eee0 --- /dev/null +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/SimpleAnsiTerminal.cs @@ -0,0 +1,66 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using Microsoft.Testing.Platform.Helpers; + +namespace Microsoft.Testing.Platform.OutputDevice.Terminal; + +/// +/// Simple terminal that uses 4-bit ANSI for colors but does not move cursor and does not do other fancy stuff to stay compatible with CI systems like AzDO. +/// The colors are set on start of every line to properly color multiline strings in AzDO output. +/// +internal sealed class SimpleAnsiTerminal : SimpleTerminal +{ + private string? _foregroundColor; + private bool _prependColor; + + public SimpleAnsiTerminal(IConsole console) + : base(console) + { + } + + public override void Append(string value) + { + // Previous write appended line, so we need to prepend color. + if (_prependColor) + { + Console.Write(_foregroundColor); + // This line is not adding new line at the end, so we don't need to prepend color on next line. + _prependColor = false; + } + + Console.Write(SetColorPerLine(value)); + } + + public override void AppendLine(string value) + { + // Previous write appended line, so we need to prepend color. + if (_prependColor) + { + Console.Write(_foregroundColor); + } + + Console.WriteLine(SetColorPerLine(value)); + // This call appended new line so the next write to console needs to prepend color. + _prependColor = true; + } + + public override void SetColor(TerminalColor color) + { + string setColor = $"{AnsiCodes.CSI}{(int)color}{AnsiCodes.SetColor}"; + _foregroundColor = setColor; + Console.Write(setColor); + // This call set the color for current line, no need to prepend on next write. + _prependColor = false; + } + + public override void ResetColor() + { + _foregroundColor = null; + _prependColor = false; + Console.Write(AnsiCodes.SetDefaultColor); + } + + private string? SetColorPerLine(string value) + => _foregroundColor == null ? value : value.Replace("\n", $"\n{_foregroundColor}"); +} diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/SimpleTerminalBase.cs b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/SimpleTerminalBase.cs new file mode 100644 index 0000000000..aefad9bc28 --- /dev/null +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/SimpleTerminalBase.cs @@ -0,0 +1,223 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using Microsoft.Testing.Platform.Helpers; +using Microsoft.Testing.Platform.Resources; + +namespace Microsoft.Testing.Platform.OutputDevice.Terminal; + +internal abstract class SimpleTerminal : ITerminal +{ + private object? _batchingLock; + private bool _isBatching; + + public SimpleTerminal(IConsole console) + => Console = console; + +#pragma warning disable CA1416 // Validate platform compatibility + public int Width => Console.IsOutputRedirected ? int.MaxValue : Console.BufferWidth; + + public int Height => Console.IsOutputRedirected ? int.MaxValue : Console.BufferHeight; + + protected IConsole Console { get; } + + public void Append(char value) + => Console.Write(value); + + public virtual void Append(string value) + => Console.Write(value); + + public void AppendLine() + => Console.WriteLine(); + + public virtual void AppendLine(string value) + => Console.WriteLine(value); + + public void AppendLink(string path, int? lineNumber) + { + Append(path); + if (lineNumber.HasValue) + { + Append($":{lineNumber}"); + } + } + + public void EraseProgress() + { + // nop + } + + public void HideCursor() + { + // nop + } + + public void RenderProgress(TestProgressState?[] progress) + { + int count = 0; + foreach (TestProgressState? p in progress) + { + if (p == null) + { + continue; + } + + count++; + + string durationString = HumanReadableDurationFormatter.Render(p.Stopwatch.Elapsed); + + int passed = p.PassedTests; + int failed = p.FailedTests; + int skipped = p.SkippedTests; + + // Use just ascii here, so we don't put too many restrictions on fonts needing to + // properly show unicode, or logs being saved in particular encoding. + Append('['); + SetColor(TerminalColor.DarkGreen); + Append('+'); + Append(passed.ToString(CultureInfo.CurrentCulture)); + ResetColor(); + + Append('/'); + + SetColor(TerminalColor.DarkRed); + Append('x'); + Append(failed.ToString(CultureInfo.CurrentCulture)); + ResetColor(); + + Append('/'); + + SetColor(TerminalColor.DarkYellow); + Append('?'); + Append(skipped.ToString(CultureInfo.CurrentCulture)); + ResetColor(); + Append(']'); + + Append(' '); + Append(p.AssemblyName); + + if (p.TargetFramework != null || p.Architecture != null) + { + Append(" ("); + if (p.TargetFramework != null) + { + Append(p.TargetFramework); + Append('|'); + } + + if (p.Architecture != null) + { + Append(p.Architecture); + } + + Append(')'); + } + + TestDetailState? activeTest = p.TestNodeResultsState?.GetRunningTasks(1).FirstOrDefault(); + if (!RoslynString.IsNullOrWhiteSpace(activeTest?.Text)) + { + Append(" - "); + Append(activeTest.Text); + Append(' '); + } + + Append(durationString); + + AppendLine(); + } + + // Do not render empty lines when there is nothing to show. + if (count > 0) + { + AppendLine(); + } + } + + public void ShowCursor() + { + // nop + } + + public void StartBusyIndicator() + { + // nop + } + + // TODO: Refactor NonAnsiTerminal and AnsiTerminal such that we don't need StartUpdate/StopUpdate. + // It's much better if we use lock C# keyword instead of manually calling Monitor.Enter/Exit + // Using lock also ensures we don't accidentally have `await`s in between that could cause Exit to be on a different thread. + public void StartUpdate() + { + if (_isBatching) + { + throw new InvalidOperationException(PlatformResources.ConsoleIsAlreadyInBatchingMode); + } + + bool lockTaken = false; + + // We store Console.Out in a field to make sure we will be doing + // the Monitor.Exit call on the same instance. + _batchingLock = System.Console.Out; + + // Note that we need to lock on System.Out for batching to work correctly. + // Consider the following scenario: + // 1. We call StartUpdate + // 2. We call a Write("A") + // 3. User calls Console.Write("B") from another thread. + // 4. We call a Write("C"). + // 5. We call StopUpdate. + // The expectation is that we see either ACB, or BAC, but not ABC. + // Basically, when doing batching, we want to ensure that everything we write is + // written continuously, without anything in-between. + // One option (and we used to do it), is that we append to a StringBuilder while batching + // Then at StopUpdate, we write the whole string at once. + // This works to some extent, but we cannot get it to work when SetColor kicks in. + // Console methods will internally lock on Console.Out, so we are locking on the same thing. + // This locking is the easiest way to get coloring to work correctly while preventing + // interleaving with user's calls to Console.Write methods. + // One extra note: + // It's very important to lock on Console.Out (the current Console.Out). + // Consider the following scenario: + // 1. SystemConsole captures the original Console.Out set by runtime. + // 2. Framework author sets his own Console.Out which wraps the original Console.Out. + // 3. Two threads are writing concurrently: + // - One thread is writing using Console.Write* APIs, which will use the Console.Out set by framework author. + // - The other thread is writing using NonAnsiTerminal. + // 4. **If** we lock the original Console.Out. The following may happen (subject to race) [NOT THE CURRENT CASE - imaginary situation if we lock on the original Console.Out]: + // - First thread enters the Console.Write, which will acquire the lock for the current Console.Out (set by framework author). + // - Second thread executes StartUpdate, and acquires the lock for the original Console.Out. + // - First thread continues in the Write implementation of the framework author, which tries to run Console.Write on the original Console.Out. + // - First thread can't make any progress, because the second thread is holding the lock already. + // - Second thread continues execution, and reaches into runtime code (ConsolePal.WriteFromConsoleStream - on Unix) which tries to acquire the lock for the current Console.Out (set by framework author). + // - (see https://github.com/dotnet/runtime/blob/8a9d492444f06df20fcc5dfdcf7a6395af18361f/src/libraries/System.Console/src/System/ConsolePal.Unix.cs#L963) + // - No thread can progress. + // - Basically, what happened is that the first thread acquires the lock for current Console.Out, then for the original Console.Out. + // - while the second thread acquires the lock for the original Console.Out, then for the current Console.Out. + // - That's a typical deadlock where two threads are acquiring two locks in reverse order. + // 5. By locking the *current* Console.Out, we avoid the situation described in 4. + Monitor.Enter(_batchingLock, ref lockTaken); + if (!lockTaken) + { + // Can this happen? :/ + throw new InvalidOperationException(); + } + + _isBatching = true; + } + + public void StopBusyIndicator() + { + // nop + } + + public void StopUpdate() + { + Monitor.Exit(_batchingLock!); + _batchingLock = null; + _isBatching = false; + } + + public abstract void SetColor(TerminalColor color); + + public abstract void ResetColor(); +} diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporter.cs b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporter.cs index 834156bbef..9582462fda 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporter.cs +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporter.cs @@ -77,12 +77,20 @@ public TerminalTestReporter(IConsole console, TerminalTestReporterOptions option } else { - // Autodetect. - (bool consoleAcceptsAnsiCodes, bool _, uint? originalConsoleMode) = NativeMethods.QueryIsScreenAndTryEnableAnsiColorCodes(); - _originalConsoleMode = originalConsoleMode; - terminalWithProgress = consoleAcceptsAnsiCodes || _options.ForceAnsi is true - ? new TestProgressStateAwareTerminal(new AnsiTerminal(console, _options.BaseDirectory), showProgress, writeProgressImmediatelyAfterOutput: true, updateEvery: ansiUpdateCadenceInMs) - : new TestProgressStateAwareTerminal(new NonAnsiTerminal(console), showProgress, writeProgressImmediatelyAfterOutput: false, updateEvery: nonAnsiUpdateCadenceInMs); + if (_options.UseCIAnsi) + { + // We are told externally that we are in CI, use simplified ANSI mode. + terminalWithProgress = new TestProgressStateAwareTerminal(new SimpleAnsiTerminal(console), showProgress, writeProgressImmediatelyAfterOutput: true, updateEvery: nonAnsiUpdateCadenceInMs); + } + else + { + // We are not in CI, or in CI non-compatible with simple ANSI, autodetect terminal capabilities + (bool consoleAcceptsAnsiCodes, bool _, uint? originalConsoleMode) = NativeMethods.QueryIsScreenAndTryEnableAnsiColorCodes(); + _originalConsoleMode = originalConsoleMode; + terminalWithProgress = consoleAcceptsAnsiCodes || _options.ForceAnsi is true + ? new TestProgressStateAwareTerminal(new AnsiTerminal(console, _options.BaseDirectory), showProgress, writeProgressImmediatelyAfterOutput: true, updateEvery: ansiUpdateCadenceInMs) + : new TestProgressStateAwareTerminal(new NonAnsiTerminal(console), showProgress, writeProgressImmediatelyAfterOutput: false, updateEvery: nonAnsiUpdateCadenceInMs); + } } _terminalWithProgress = terminalWithProgress; @@ -179,7 +187,7 @@ private void AppendTestRunSummary(ITerminal terminal) bool allTestsWereSkipped = totalTests == 0 || totalTests == totalSkippedTests; bool anyTestFailed = totalFailedTests > 0; bool runFailed = anyTestFailed || notEnoughTests || allTestsWereSkipped || _wasCancelled; - terminal.SetColor(runFailed ? TerminalColor.Red : TerminalColor.Green); + terminal.SetColor(runFailed ? TerminalColor.DarkRed : TerminalColor.DarkGreen); terminal.Append(PlatformResources.TestRunSummary); terminal.Append(' '); @@ -248,7 +256,7 @@ private void AppendTestRunSummary(ITerminal terminal) terminal.AppendLine(totalText); if (colorizeFailed) { - terminal.SetColor(TerminalColor.Red); + terminal.SetColor(TerminalColor.DarkRed); } terminal.AppendLine(failedText); @@ -260,7 +268,7 @@ private void AppendTestRunSummary(ITerminal terminal) if (colorizePassed) { - terminal.SetColor(TerminalColor.Green); + terminal.SetColor(TerminalColor.DarkGreen); } terminal.AppendLine(passedText); @@ -272,7 +280,7 @@ private void AppendTestRunSummary(ITerminal terminal) if (colorizeSkipped) { - terminal.SetColor(TerminalColor.Yellow); + terminal.SetColor(TerminalColor.DarkYellow); } terminal.AppendLine(skippedText); @@ -294,7 +302,7 @@ private static void AppendAssemblyResult(ITerminal terminal, bool succeeded, int { if (!succeeded) { - terminal.SetColor(TerminalColor.Red); + terminal.SetColor(TerminalColor.DarkRed); // If the build failed, we print one of three red strings. string text = (countErrors > 0, countWarnings > 0) switch { @@ -308,13 +316,13 @@ private static void AppendAssemblyResult(ITerminal terminal, bool succeeded, int } else if (countWarnings > 0) { - terminal.SetColor(TerminalColor.Yellow); + terminal.SetColor(TerminalColor.DarkYellow); terminal.Append($"succeeded with {countWarnings} warning(s)"); terminal.ResetColor(); } else { - terminal.SetColor(TerminalColor.Green); + terminal.SetColor(TerminalColor.DarkGreen); terminal.Append(PlatformResources.PassedLowercase); terminal.ResetColor(); } @@ -442,9 +450,9 @@ private void RenderTestCompleted( TerminalColor color = outcome switch { - TestOutcome.Error or TestOutcome.Fail or TestOutcome.Canceled or TestOutcome.Timeout => TerminalColor.Red, - TestOutcome.Skipped => TerminalColor.Yellow, - TestOutcome.Passed => TerminalColor.Green, + TestOutcome.Error or TestOutcome.Fail or TestOutcome.Canceled or TestOutcome.Timeout => TerminalColor.DarkRed, + TestOutcome.Skipped => TerminalColor.DarkYellow, + TestOutcome.Passed => TerminalColor.DarkGreen, _ => throw new NotSupportedException(), }; string outcomeText = outcome switch @@ -492,7 +500,7 @@ private static void FormatInnerExceptions(ITerminal terminal, FlatException[] ex for (int i = 1; i < exceptions.Length; i++) { - terminal.SetColor(TerminalColor.Red); + terminal.SetColor(TerminalColor.DarkRed); terminal.Append(SingleIndentation); terminal.Append("--->"); FormatErrorMessage(terminal, exceptions, TestOutcome.Error, i); @@ -510,7 +518,7 @@ private static void FormatErrorMessage(ITerminal terminal, FlatException[] excep return; } - terminal.SetColor(TerminalColor.Red); + terminal.SetColor(TerminalColor.DarkRed); if (firstStackTrace is null) { @@ -539,7 +547,7 @@ private static void FormatExpectedAndActual(ITerminal terminal, string? expected return; } - terminal.SetColor(TerminalColor.Red); + terminal.SetColor(TerminalColor.DarkRed); terminal.Append(SingleIndentation); terminal.AppendLine(PlatformResources.Expected); AppendIndentedLine(terminal, expected, DoubleIndentation); @@ -781,7 +789,7 @@ internal void WriteErrorMessage(string assembly, string? targetFramework, string _terminalWithProgress.WriteToTerminal(terminal => { - terminal.SetColor(TerminalColor.Red); + terminal.SetColor(TerminalColor.DarkRed); if (padding == null) { terminal.AppendLine(text); @@ -801,7 +809,7 @@ internal void WriteWarningMessage(string assembly, string? targetFramework, stri asm.AddWarning(text); _terminalWithProgress.WriteToTerminal(terminal => { - terminal.SetColor(TerminalColor.Yellow); + terminal.SetColor(TerminalColor.DarkYellow); if (padding == null) { terminal.AppendLine(text); @@ -906,7 +914,7 @@ public void AppendTestDiscoverySummary(ITerminal terminal) terminal.AppendLine(); } - terminal.SetColor(runFailed ? TerminalColor.Red : TerminalColor.Green); + terminal.SetColor(runFailed ? TerminalColor.DarkRed : TerminalColor.DarkGreen); if (assemblies.Count <= 1) { terminal.Append(string.Format(CultureInfo.CurrentCulture, PlatformResources.TestDiscoverySummarySingular, totalTests)); diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporterOptions.cs b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporterOptions.cs index 478453758d..bb610c1026 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporterOptions.cs +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporterOptions.cs @@ -47,6 +47,12 @@ internal sealed class TerminalTestReporterOptions /// public bool UseAnsi { get; init; } + /// + /// Gets a value indicating whether we are running in compatible CI, and should use simplified ANSI renderer, which colors output, but does not move cursor. + /// Setting to false will disable this option. + /// + public bool UseCIAnsi { get; init; } + /// /// Gets a value indicating whether we should force ANSI escape codes. When true the ANSI is used without auto-detecting capabilities of the console. This is needed only for testing. /// diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/TerminalOutputDevice.cs b/src/Platform/Microsoft.Testing.Platform/OutputDevice/TerminalOutputDevice.cs index 30da68d0ef..cfe454e7de 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/TerminalOutputDevice.cs +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/TerminalOutputDevice.cs @@ -118,6 +118,9 @@ await _policiesService.RegisterOnAbortCallbackAsync( _isListTests = _commandLineOptions.IsOptionSet(PlatformCommandLineProvider.DiscoverTestsOptionKey); _isServerMode = _commandLineOptions.IsOptionSet(PlatformCommandLineProvider.ServerOptionKey); bool noAnsi = _commandLineOptions.IsOptionSet(TerminalTestReporterCommandLineOptionsProvider.NoAnsiOption); + + // TODO: Replace this with proper CI detection that we already have in telemetry. https://github.com/microsoft/testfx/issues/5533#issuecomment-2838893327 + bool inCI = string.Equals(_environment.GetEnvironmentVariable("TF_BUILD"), "true", StringComparison.OrdinalIgnoreCase) || string.Equals(_environment.GetEnvironmentVariable("GITHUB_ACTIONS"), "true", StringComparison.OrdinalIgnoreCase); bool noProgress = _commandLineOptions.IsOptionSet(TerminalTestReporterCommandLineOptionsProvider.NoProgressOption); // _runtimeFeature.IsHotReloadEnabled is not set to true here, even if the session will be HotReload, @@ -155,6 +158,7 @@ await _policiesService.RegisterOnAbortCallbackAsync( ShowPassedTests = showPassed, MinimumExpectedTests = PlatformCommandLineProvider.GetMinimumExpectedTests(_commandLineOptions), UseAnsi = !noAnsi, + UseCIAnsi = inCI, ShowActiveTests = true, ShowProgress = shouldShowProgress, }); diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/ConsoleTests.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/ConsoleTests.cs index 31f4b9b9b4..e035572d0f 100644 --- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/ConsoleTests.cs +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/ConsoleTests.cs @@ -43,7 +43,7 @@ private async Task ConsoleTestsCoreAsync(string tfm, string? environmentVariable }; } - TestHostResult testHostResult = await testHost.ExecuteAsync("--no-ansi --ignore-exit-code 8", environmentVariables); + TestHostResult testHostResult = await testHost.ExecuteAsync("--ignore-exit-code 8", environmentVariables); testHostResult.AssertExitCodeIs(ExitCodes.Success); testHostResult.AssertOutputContains("ABCDEF123"); } diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/ExitOnProcessExitTests.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/ExitOnProcessExitTests.cs index 060a342a1a..ad3137f788 100644 --- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/ExitOnProcessExitTests.cs +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/ExitOnProcessExitTests.cs @@ -37,7 +37,7 @@ public void ExitOnProcessExit_Succeed(string tfm) } } - if (startTime.Elapsed.TotalSeconds > 55) + if (startTime.Elapsed.TotalSeconds > 60) { throw new Exception("Process PID not found in 60 seconds"); } @@ -48,7 +48,8 @@ public void ExitOnProcessExit_Succeed(string tfm) startTime = Stopwatch.StartNew(); while (!process.HasExited) { - if (startTime.Elapsed.TotalSeconds > 55) + Thread.Sleep(1000); + if (startTime.Elapsed.TotalSeconds > 60) { throw new Exception("Process did not exit in 60 seconds"); } @@ -83,7 +84,7 @@ public sealed class TestAssetFixture() : TestAssetFixtureBase(AcceptanceFixture. using Microsoft.Testing.Platform.Extensions.Messages; using Microsoft.Testing.Platform.Extensions.TestFramework; -if (args.Length == 0) +if (!args.Contains("--exit-on-process-exit")) { int currentPid = Process.GetCurrentProcess().Id; var currentEntryPoint = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly()!.Location)!, Path.GetFileNameWithoutExtension(Assembly.GetEntryAssembly()!.Location) @@ -93,7 +94,7 @@ public sealed class TestAssetFixture() : TestAssetFixtureBase(AcceptanceFixture. Environment.SetEnvironmentVariable("WaitTestHost", mutexName); ProcessStartInfo processStartInfo = new(); processStartInfo.FileName = currentEntryPoint; - processStartInfo.Arguments = $"--exit-on-process-exit {currentPid}"; + processStartInfo.Arguments = $"--exit-on-process-exit {currentPid} --no-progress --no-ansi"; processStartInfo.UseShellExecute = false; var process = Process.Start(processStartInfo); while (!Mutex.TryOpenExisting(mutexName, out Mutex? _)) diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/OutputDevice/Terminal/TerminalTestReporterTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/OutputDevice/Terminal/TerminalTestReporterTests.cs index 0e3467d86c..1cce4e85cc 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/OutputDevice/Terminal/TerminalTestReporterTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/OutputDevice/Terminal/TerminalTestReporterTests.cs @@ -29,6 +29,8 @@ public void AppendStackFrameFormatsStackTraceLineCorrectly() #if NETCOREAPP StringAssert.Contains(terminal.Output, " at Microsoft.Testing.Platform.UnitTests.TerminalTestReporterTests.AppendStackFrameFormatsStackTraceLineCorrectly() in "); #else + // This is caused by us using portable symbols, and .NET Framework 4.6.2, once we update to .NET Framework 4.7.2 the path to file will be included in the stacktrace and this won't be necessary. + // See first point here: https://learn.microsoft.com/en-us/dotnet/core/diagnostics/symbols#support-for-portable-pdbs StringAssert.Contains(terminal.Output, " at Microsoft.Testing.Platform.UnitTests.TerminalTestReporterTests.AppendStackFrameFormatsStackTraceLineCorrectly()"); #endif // Line number without the respective file @@ -64,13 +66,216 @@ public void StackTraceRegexCapturesLines(string stackTraceLine, string expected) } [TestMethod] - public void OutputFormattingIsCorrect() + public void NonAnsiTerminal_OutputFormattingIsCorrect() { var stringBuilderConsole = new StringBuilderConsole(); var terminalReporter = new TerminalTestReporter(stringBuilderConsole, new TerminalTestReporterOptions { ShowPassedTests = () => true, + + // Like --no-ansi in commandline, should disable ANSI altogether. + UseAnsi = false, + + ShowAssembly = false, + ShowAssemblyStartAndComplete = false, + ShowProgress = () => false, + }); + + DateTimeOffset startTime = DateTimeOffset.MinValue; + DateTimeOffset endTime = DateTimeOffset.MaxValue; + terminalReporter.TestExecutionStarted(startTime, 1, isDiscovery: false); + + string targetFramework = "net8.0"; + string architecture = "x64"; + string assembly = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? @"C:\work\assembly.dll" : "/mnt/work/assembly.dll"; + string folder = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? @"C:\work\" : "/mnt/work/"; + string folderNoSlash = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? @"C:\work" : "/mnt/work"; + string folderLink = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? @"C:/work/" : "mnt/work/"; + string folderLinkNoSlash = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? @"C:/work" : "mnt/work"; + + terminalReporter.AssemblyRunStarted(assembly, targetFramework, architecture); + string standardOutput = "Hello!"; + string errorOutput = "Oh no!"; + + terminalReporter.TestCompleted(assembly, targetFramework, architecture, testNodeUid: "PassedTest1", "PassedTest1", TestOutcome.Passed, TimeSpan.FromSeconds(10), + informativeMessage: null, errorMessage: null, exception: null, expected: null, actual: null, standardOutput, errorOutput); + terminalReporter.TestCompleted(assembly, targetFramework, architecture, testNodeUid: "SkippedTest1", "SkippedTest1", TestOutcome.Skipped, TimeSpan.FromSeconds(10), + informativeMessage: null, errorMessage: null, exception: null, expected: null, actual: null, standardOutput, errorOutput); + // timed out + canceled + failed should all report as failed in summary + terminalReporter.TestCompleted(assembly, targetFramework, architecture, testNodeUid: "TimedoutTest1", "TimedoutTest1", TestOutcome.Timeout, TimeSpan.FromSeconds(10), + informativeMessage: null, errorMessage: null, exception: null, expected: null, actual: null, standardOutput, errorOutput); + terminalReporter.TestCompleted(assembly, targetFramework, architecture, testNodeUid: "CanceledTest1", "CanceledTest1", TestOutcome.Canceled, TimeSpan.FromSeconds(10), + informativeMessage: null, errorMessage: null, exception: null, expected: null, actual: null, standardOutput, errorOutput); + terminalReporter.TestCompleted(assembly, targetFramework, architecture, testNodeUid: "FailedTest1", "FailedTest1", TestOutcome.Fail, TimeSpan.FromSeconds(10), + informativeMessage: null, errorMessage: "Tests failed", exception: new StackTraceException(@$" at FailingTest() in {folder}codefile.cs:line 10"), expected: "ABC", actual: "DEF", standardOutput, errorOutput); + terminalReporter.ArtifactAdded(outOfProcess: true, assembly, targetFramework, architecture, testName: null, @$"{folder}artifact1.txt"); + terminalReporter.ArtifactAdded(outOfProcess: false, assembly, targetFramework, architecture, testName: null, @$"{folder}artifact2.txt"); + terminalReporter.AssemblyRunCompleted(assembly, targetFramework, architecture, exitCode: null, outputData: null, errorData: null); + terminalReporter.TestExecutionCompleted(endTime); + + string output = stringBuilderConsole.Output; + + string expected = $""" + passed PassedTest1 (10s 000ms) + Standard output + Hello! + Error output + Oh no! + skipped SkippedTest1 (10s 000ms) + Standard output + Hello! + Error output + Oh no! + failed (canceled) TimedoutTest1 (10s 000ms) + Standard output + Hello! + Error output + Oh no! + failed (canceled) CanceledTest1 (10s 000ms) + Standard output + Hello! + Error output + Oh no! + failed FailedTest1 (10s 000ms) + Tests failed + Expected + ABC + Actual + DEF + at FailingTest() in {folder}codefile.cs:10 + Standard output + Hello! + Error output + Oh no! + + Out of process file artifacts produced: + - {folder}artifact1.txt + In process file artifacts produced: + - {folder}artifact2.txt + + Test run summary: Failed! - {assembly} (net8.0|x64) + total: 5 + failed: 3 + succeeded: 1 + skipped: 1 + duration: 3652058d 23h 59m 59s 999ms + + """; + + Assert.AreEqual(expected, ShowEscape(output)); + } + + [TestMethod] + public void SimpleAnsiTerminal_OutputFormattingIsCorrect() + { + var stringBuilderConsole = new StringBuilderConsole(); + var terminalReporter = new TerminalTestReporter(stringBuilderConsole, new TerminalTestReporterOptions + { + ShowPassedTests = () => true, + // Like if we autodetect that we are in CI (e.g. by looking at TF_BUILD, and we don't disable ANSI. + UseAnsi = true, + UseCIAnsi = true, + ForceAnsi = true, + + ShowAssembly = false, + ShowAssemblyStartAndComplete = false, + ShowProgress = () => false, + }); + + DateTimeOffset startTime = DateTimeOffset.MinValue; + DateTimeOffset endTime = DateTimeOffset.MaxValue; + terminalReporter.TestExecutionStarted(startTime, 1, isDiscovery: false); + + string targetFramework = "net8.0"; + string architecture = "x64"; + string assembly = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? @"C:\work\assembly.dll" : "/mnt/work/assembly.dll"; + string folder = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? @"C:\work\" : "/mnt/work/"; + string folderNoSlash = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? @"C:\work" : "/mnt/work"; + string folderLink = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? @"C:/work/" : "mnt/work/"; + string folderLinkNoSlash = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? @"C:/work" : "mnt/work"; + + terminalReporter.AssemblyRunStarted(assembly, targetFramework, architecture); + string standardOutput = "Hello!"; + string errorOutput = "Oh no!"; + + terminalReporter.TestCompleted(assembly, targetFramework, architecture, testNodeUid: "PassedTest1", "PassedTest1", TestOutcome.Passed, TimeSpan.FromSeconds(10), + informativeMessage: null, errorMessage: null, exception: null, expected: null, actual: null, standardOutput, errorOutput); + terminalReporter.TestCompleted(assembly, targetFramework, architecture, testNodeUid: "SkippedTest1", "SkippedTest1", TestOutcome.Skipped, TimeSpan.FromSeconds(10), + informativeMessage: null, errorMessage: null, exception: null, expected: null, actual: null, standardOutput, errorOutput); + // timed out + canceled + failed should all report as failed in summary + terminalReporter.TestCompleted(assembly, targetFramework, architecture, testNodeUid: "TimedoutTest1", "TimedoutTest1", TestOutcome.Timeout, TimeSpan.FromSeconds(10), + informativeMessage: null, errorMessage: null, exception: null, expected: null, actual: null, standardOutput, errorOutput); + terminalReporter.TestCompleted(assembly, targetFramework, architecture, testNodeUid: "CanceledTest1", "CanceledTest1", TestOutcome.Canceled, TimeSpan.FromSeconds(10), + informativeMessage: null, errorMessage: null, exception: null, expected: null, actual: null, standardOutput, errorOutput); + terminalReporter.TestCompleted(assembly, targetFramework, architecture, testNodeUid: "FailedTest1", "FailedTest1", TestOutcome.Fail, TimeSpan.FromSeconds(10), + informativeMessage: null, errorMessage: "Tests failed", exception: new StackTraceException(@$" at FailingTest() in {folder}codefile.cs:line 10"), expected: "ABC", actual: "DEF", standardOutput, errorOutput); + terminalReporter.ArtifactAdded(outOfProcess: true, assembly, targetFramework, architecture, testName: null, @$"{folder}artifact1.txt"); + terminalReporter.ArtifactAdded(outOfProcess: false, assembly, targetFramework, architecture, testName: null, @$"{folder}artifact2.txt"); + terminalReporter.AssemblyRunCompleted(assembly, targetFramework, architecture, exitCode: null, outputData: null, errorData: null); + terminalReporter.TestExecutionCompleted(endTime); + + string output = stringBuilderConsole.Output; + + string expected = $""" + ␛[32mpassed␛[m PassedTest1␛[90m ␛[90m(10s 000ms)␛[m + ␛[90m Standard output + ␛[90m Hello! + ␛[90m Error output + ␛[90m Oh no! + ␛[m␛[33mskipped␛[m SkippedTest1␛[90m ␛[90m(10s 000ms)␛[m + ␛[90m Standard output + ␛[90m Hello! + ␛[90m Error output + ␛[90m Oh no! + ␛[m␛[31mfailed (canceled)␛[m TimedoutTest1␛[90m ␛[90m(10s 000ms)␛[m + ␛[90m Standard output + ␛[90m Hello! + ␛[90m Error output + ␛[90m Oh no! + ␛[m␛[31mfailed (canceled)␛[m CanceledTest1␛[90m ␛[90m(10s 000ms)␛[m + ␛[90m Standard output + ␛[90m Hello! + ␛[90m Error output + ␛[90m Oh no! + ␛[m␛[31mfailed␛[m FailedTest1␛[90m ␛[90m(10s 000ms)␛[m + ␛[31m Tests failed + ␛[m␛[31m Expected + ␛[31m ABC + ␛[31m Actual + ␛[31m DEF + ␛[m␛[90m at FailingTest() in {folder}codefile.cs:10␛[90m + ␛[m␛[90m Standard output + ␛[90m Hello! + ␛[90m Error output + ␛[90m Oh no! + ␛[m + Out of process file artifacts produced: + - {folder}artifact1.txt + In process file artifacts produced: + - {folder}artifact2.txt + + ␛[31mTest run summary: Failed!␛[90m - ␛[m{folder}assembly.dll (net8.0|x64) + ␛[m total: 5 + ␛[31m failed: 3 + ␛[m succeeded: 1 + skipped: 1 + duration: 3652058d 23h 59m 59s 999ms + + """; + + Assert.AreEqual(expected, ShowEscape(output)); + } + + [TestMethod] + public void AnsiTerminal_OutputFormattingIsCorrect() + { + var stringBuilderConsole = new StringBuilderConsole(); + var terminalReporter = new TerminalTestReporter(stringBuilderConsole, new TerminalTestReporterOptions + { + ShowPassedTests = () => true, + // Like if we autodetect that we are in ANSI capable terminal. UseAnsi = true, + UseCIAnsi = false, ForceAnsi = true, ShowAssembly = false, @@ -113,29 +318,29 @@ public void OutputFormattingIsCorrect() string output = stringBuilderConsole.Output; string expected = $""" - ␛[92mpassed␛[m PassedTest1␛[90m ␛[90m(10s 000ms)␛[m + ␛[32mpassed␛[m PassedTest1␛[90m ␛[90m(10s 000ms)␛[m ␛[90m Standard output Hello! Error output Oh no! - ␛[m␛[93mskipped␛[m SkippedTest1␛[90m ␛[90m(10s 000ms)␛[m + ␛[m␛[33mskipped␛[m SkippedTest1␛[90m ␛[90m(10s 000ms)␛[m ␛[90m Standard output Hello! Error output Oh no! - ␛[m␛[91mfailed (canceled)␛[m TimedoutTest1␛[90m ␛[90m(10s 000ms)␛[m + ␛[m␛[31mfailed (canceled)␛[m TimedoutTest1␛[90m ␛[90m(10s 000ms)␛[m ␛[90m Standard output Hello! Error output Oh no! - ␛[m␛[91mfailed (canceled)␛[m CanceledTest1␛[90m ␛[90m(10s 000ms)␛[m + ␛[m␛[31mfailed (canceled)␛[m CanceledTest1␛[90m ␛[90m(10s 000ms)␛[m ␛[90m Standard output Hello! Error output Oh no! - ␛[m␛[91mfailed␛[m FailedTest1␛[90m ␛[90m(10s 000ms)␛[m - ␛[91m Tests failed - ␛[m␛[91m Expected + ␛[m␛[31mfailed␛[m FailedTest1␛[90m ␛[90m(10s 000ms)␛[m + ␛[31m Tests failed + ␛[m␛[31m Expected ABC Actual DEF @@ -149,28 +354,30 @@ Oh no! - ␛[90m␛]8;;file:///{folderLink}artifact1.txt␛\{folder}artifact1.txt␛]8;;␛\␛[m In process file artifacts produced: - ␛[90m␛]8;;file:///{folderLink}artifact2.txt␛\{folder}artifact2.txt␛]8;;␛\␛[m - - ␛[91mTest run summary: Failed!␛[90m - ␛[m␛[90m␛]8;;file:///{folderLinkNoSlash}␛\{folder}assembly.dll␛]8;;␛\␛[m (net8.0|x64) + + ␛[31mTest run summary: Failed!␛[90m - ␛[m␛[90m␛]8;;file:///{folderLinkNoSlash}␛\{folder}assembly.dll␛]8;;␛\␛[m (net8.0|x64) ␛[m total: 5 - ␛[91m failed: 3 + ␛[31m failed: 3 ␛[m succeeded: 1 skipped: 1 duration: 3652058d 23h 59m 59s 999ms - + """; Assert.AreEqual(expected, ShowEscape(output)); } [TestMethod] - public void OutputProgressFrameIsCorrect() + public void AnsiTerminal_OutputProgressFrameIsCorrect() { var stringBuilderConsole = new StringBuilderConsole(); var stopwatchFactory = new StopwatchFactory(); var terminalReporter = new TerminalTestReporter(stringBuilderConsole, new TerminalTestReporterOptions { ShowPassedTests = () => true, + // Like if we autodetect that we are in ANSI capable terminal. UseAnsi = true, + UseCIAnsi = false, ForceAnsi = true, ShowActiveTests = true, @@ -233,29 +440,29 @@ public void OutputProgressFrameIsCorrect() // Note: The progress is drawn after each completed event. string expected = $""" - {busyIndicatorString}␛[?25l␛[92mpassed␛[m PassedTest1␛[90m ␛[90m(10s 000ms)␛[m + {busyIndicatorString}␛[?25l␛[32mpassed␛[m PassedTest1␛[90m ␛[90m(10s 000ms)␛[m ␛[90m Standard output Hello! Error output Oh no! ␛[m - [␛[92m✓1␛[m/␛[91mx0␛[m/␛[93m↓0␛[m] assembly.dll (net8.0|x64)␛[2147483640G(1m 31s) + [␛[32m✓1␛[m/␛[31mx0␛[m/␛[33m↓0␛[m] assembly.dll (net8.0|x64)␛[2147483640G(1m 31s) SkippedTest1␛[2147483640G(1m 31s) InProgressTest1␛[2147483640G(1m 31s) InProgressTest2␛[2147483643G(31s) InProgressTest3␛[2147483644G(1s) ␛[7F - ␛[J␛[93mskipped␛[m SkippedTest1␛[90m ␛[90m(10s 000ms)␛[m + ␛[J␛[33mskipped␛[m SkippedTest1␛[90m ␛[90m(10s 000ms)␛[m ␛[90m Standard output Hello! Error output Oh no! ␛[m - [␛[92m✓1␛[m/␛[91mx0␛[m/␛[93m↓1␛[m] assembly.dll (net8.0|x64)␛[2147483640G(1m 31s) + [␛[32m✓1␛[m/␛[31mx0␛[m/␛[33m↓1␛[m] assembly.dll (net8.0|x64)␛[2147483640G(1m 31s) InProgressTest1␛[2147483640G(1m 31s) InProgressTest2␛[2147483643G(31s) InProgressTest3␛[2147483644G(1s) - + """; Assert.AreEqual(expected, ShowEscape(output)); diff --git a/test/Utilities/Microsoft.Testing.TestInfrastructure/TestHost.cs b/test/Utilities/Microsoft.Testing.TestInfrastructure/TestHost.cs index 44c7a12894..e81575f584 100644 --- a/test/Utilities/Microsoft.Testing.TestInfrastructure/TestHost.cs +++ b/test/Utilities/Microsoft.Testing.TestInfrastructure/TestHost.cs @@ -87,8 +87,10 @@ public async Task ExecuteAsync( .ExecuteAsync(async () => { CommandLine commandLine = new(); + // Disable ANSI rendering so tests have easier time parsing the output. + // Disable progress so tests don't mix progress with overall progress, and with test process output. int exitCode = await commandLine.RunAsyncAndReturnExitCodeAsync( - $"{FullName} {finalArguments}", + $"{FullName} --no-ansi --no-progress {finalArguments}", environmentVariables: environmentVariables, workingDirectory: null, cleanDefaultEnvironmentVariableIfCustomAreProvided: true, From 39aa07628664da4dc76d3fbec7f69f4cff575a04 Mon Sep 17 00:00:00 2001 From: Copilot <198982749+Copilot@users.noreply.github.com> Date: Tue, 3 Jun 2025 09:15:39 +0200 Subject: [PATCH 051/541] Downgrade VSTestVersion to 17.13.0 to restore net6.0 support in examples (#5613) Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: nohwnd <5735905+nohwnd@users.noreply.github.com> --- samples/public/Directory.Build.props | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/public/Directory.Build.props b/samples/public/Directory.Build.props index 9f5290fd47..803b6a98c5 100644 --- a/samples/public/Directory.Build.props +++ b/samples/public/Directory.Build.props @@ -7,7 +7,7 @@ 1.0.0-alpha.25256.6 1.50.0 1.7.0 - 17.14.0 + 17.13.0 From bb3c852afe2e5a43795b9fdbee6f14b445a6d29e Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Tue, 3 Jun 2025 09:16:53 +0200 Subject: [PATCH 052/541] Allow serialization of DateOnly/TimeOnly for parameterized tests (#5676) --- .../Helpers/DataSerializationHelper.cs | 105 ++++++++++++++++++ .../DataSource/DynamicDataOperations.cs | 8 +- .../Helpers/DataSerializationHelperTests.cs | 24 ++++ .../MSTestAdapter.UnitTests.csproj | 2 +- 4 files changed, 131 insertions(+), 8 deletions(-) diff --git a/src/Adapter/MSTest.TestAdapter/Helpers/DataSerializationHelper.cs b/src/Adapter/MSTest.TestAdapter/Helpers/DataSerializationHelper.cs index efafabaa74..22becc21ab 100644 --- a/src/Adapter/MSTest.TestAdapter/Helpers/DataSerializationHelper.cs +++ b/src/Adapter/MSTest.TestAdapter/Helpers/DataSerializationHelper.cs @@ -1,6 +1,11 @@ // 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 +using System.CodeDom; +using System.Collections.ObjectModel; +#endif +using System.Runtime.Serialization; using System.Runtime.Serialization.Json; namespace Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Helpers; @@ -13,6 +18,10 @@ internal static class DataSerializationHelper UseSimpleDictionaryFormat = true, EmitTypeInformation = System.Runtime.Serialization.EmitTypeInformation.Always, DateTimeFormat = new System.Runtime.Serialization.DateTimeFormat("O", CultureInfo.InvariantCulture), +#if NETFRAMEWORK + DataContractSurrogate = SerializationSurrogateProvider.Instance, +#endif + KnownTypes = [typeof(SurrogatedDateOnly), typeof(SurrogatedTimeOnly)], }; /// @@ -47,6 +56,9 @@ internal static class DataSerializationHelper serializedData[typeIndex] = typeName; DataContractJsonSerializer serializer = GetSerializer(type); +#if NET7_0_OR_GREATER + serializer.SetSerializationSurrogateProvider(SerializationSurrogateProvider.Instance); +#endif using var memoryStream = new MemoryStream(); // This should be safe as long as our generator mentions @@ -93,6 +105,9 @@ internal static class DataSerializationHelper } DataContractJsonSerializer serializer = GetSerializer(assemblyQualifiedName); +#if NET7_0_OR_GREATER + serializer.SetSerializationSurrogateProvider(SerializationSurrogateProvider.Instance); +#endif byte[] serializedDataBytes = Encoding.UTF8.GetBytes(serializedValue); using var memoryStream = new MemoryStream(serializedDataBytes); @@ -104,6 +119,9 @@ internal static class DataSerializationHelper data[i] = serializer.ReadObject(memoryStream); #pragma warning restore IL3050 // IL3050: Avoid calling members annotated with 'RequiresDynamicCodeAttribute' when publishing as Native AOT #pragma warning restore IL2026 // IL2026: Members attributed with RequiresUnreferencedCode may break when trimming + // For some reason, we don't get SerializationSurrogateProvider.GetDeserializedObject to be called by .NET runtime. + // So we manually call it. + data[i] = SerializationSurrogateProvider.GetDeserializedObject(data[i]!); } return data; @@ -130,6 +148,93 @@ private static DataContractJsonSerializer GetSerializer(Type type) #pragma warning disable IL3050 // IL3050: Avoid calling members annotated with 'RequiresDynamicCodeAttribute' when publishing as Native AOT #pragma warning disable IL2026 // IL2026: Members attributed with RequiresUnreferencedCode may break when trimming _ => new DataContractJsonSerializer(type, SerializerSettings)); + + [DataContract] + private sealed class SurrogatedDateOnly + { + [DataMember] + public int DayNumber { get; set; } + } + + [DataContract] + private sealed class SurrogatedTimeOnly + { + [DataMember] + public long Ticks { get; set; } + } + + private sealed class SerializationSurrogateProvider +#if NETFRAMEWORK + : IDataContractSurrogate +#else + : ISerializationSurrogateProvider +#endif + { + public static SerializationSurrogateProvider Instance { get; } = new(); + +#if NETFRAMEWORK + public object GetCustomDataToExport(MemberInfo memberInfo, Type dataContractType) => null!; + + public object GetCustomDataToExport(Type clrType, Type dataContractType) => null!; + + public void GetKnownCustomDataTypes(Collection customDataTypes) + { + } + + public Type GetReferencedTypeOnImport(string typeName, string typeNamespace, object customData) => null!; + + public CodeTypeDeclaration ProcessImportedType(CodeTypeDeclaration typeDeclaration, CodeCompileUnit compileUnit) => typeDeclaration; +#endif + + public object GetDeserializedObject(object obj, Type targetType) + => GetDeserializedObject(obj); + + internal static object GetDeserializedObject(object obj) + { +#if NET6_0_OR_GREATER + if (obj is SurrogatedDateOnly surrogatedDateOnly) + { + return DateOnly.FromDayNumber(surrogatedDateOnly.DayNumber); + } + else if (obj is SurrogatedTimeOnly surrogatedTimeOnly) + { + return new TimeOnly(surrogatedTimeOnly.Ticks); + } +#endif + + return obj; + } + + public object GetObjectToSerialize(object obj, Type targetType) + => obj switch + { +#if NET6_0_OR_GREATER + DateOnly dateOnly => new SurrogatedDateOnly() { DayNumber = dateOnly.DayNumber }, + TimeOnly timeOnly => new SurrogatedTimeOnly() { Ticks = timeOnly.Ticks }, +#endif + _ => obj, + }; + +#if NETFRAMEWORK + public Type GetDataContractType(Type type) +#else + public Type GetSurrogateType(Type type) +#endif + { +#if NET6_0_OR_GREATER + if (type == typeof(DateOnly)) + { + return typeof(SurrogatedDateOnly); + } + else if (type == typeof(TimeOnly)) + { + return typeof(SurrogatedTimeOnly); + } +#endif + + return type; + } + } #pragma warning restore IL3050 // IL3050: Avoid calling members annotated with 'RequiresDynamicCodeAttribute' when publishing as Native AOT #pragma warning restore IL2026 // IL2026: Members attributed with RequiresUnreferencedCode may break when trimming } diff --git a/src/TestFramework/TestFramework/Attributes/DataSource/DynamicDataOperations.cs b/src/TestFramework/TestFramework/Attributes/DataSource/DynamicDataOperations.cs index 664e9bad37..d2d4b3dd2f 100644 --- a/src/TestFramework/TestFramework/Attributes/DataSource/DynamicDataOperations.cs +++ b/src/TestFramework/TestFramework/Attributes/DataSource/DynamicDataOperations.cs @@ -118,13 +118,7 @@ private static bool TryGetData(object dataSource, [NotNullWhen(true)] out IEnume List objects = []; foreach (object? entry in enumerable) { - if (entry is null) - { - data = null; - return false; - } - - objects.Add([entry]); + objects.Add([entry!]); } data = objects; diff --git a/test/UnitTests/MSTestAdapter.UnitTests/Helpers/DataSerializationHelperTests.cs b/test/UnitTests/MSTestAdapter.UnitTests/Helpers/DataSerializationHelperTests.cs index 17f093237a..1b7e4aa18e 100644 --- a/test/UnitTests/MSTestAdapter.UnitTests/Helpers/DataSerializationHelperTests.cs +++ b/test/UnitTests/MSTestAdapter.UnitTests/Helpers/DataSerializationHelperTests.cs @@ -55,4 +55,28 @@ public void DataSerializerShouldRoundTripDateTimeOfKindUtc() Verify(actual[0]!.Equals(source)); Verify(((DateTime)actual[0]!).Kind.Equals(source.Kind)); } + +#if NET7_0_OR_GREATER + public void DataSerializerShouldRoundTripDateOnly() + { + var source = new DateOnly(1999, 11, 3); + + object?[]? actual = DataSerializationHelper.Deserialize(DataSerializationHelper.Serialize([source])); + + Verify(actual!.Length == 1); + Verify(actual[0]!.GetType() == typeof(DateOnly)); + Verify(actual[0]!.Equals(source)); + } + + public void DataSerializerShouldRoundTripTimeOnly() + { + var source = new TimeOnly(hour: 14, minute: 50, second: 13, millisecond: 15); + + object?[]? actual = DataSerializationHelper.Deserialize(DataSerializationHelper.Serialize([source])); + + Verify(actual!.Length == 1); + Verify(actual[0]!.GetType() == typeof(TimeOnly)); + Verify(actual[0]!.Equals(source)); + } +#endif } diff --git a/test/UnitTests/MSTestAdapter.UnitTests/MSTestAdapter.UnitTests.csproj b/test/UnitTests/MSTestAdapter.UnitTests/MSTestAdapter.UnitTests.csproj index 2f3eddd243..80b1c28992 100644 --- a/test/UnitTests/MSTestAdapter.UnitTests/MSTestAdapter.UnitTests.csproj +++ b/test/UnitTests/MSTestAdapter.UnitTests/MSTestAdapter.UnitTests.csproj @@ -2,7 +2,7 @@ net48 - net6.0;net462;$(NetStandardNetFrameworkHolder);netcoreapp3.1 + net6.0;net7.0;net462;$(NetStandardNetFrameworkHolder);netcoreapp3.1 $(TargetFrameworks);$(WinUiMinimum) true Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests From fe4cee5f737f70f11657780ab1bd9c0815617b29 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Tue, 3 Jun 2025 14:30:05 +0200 Subject: [PATCH 053/541] Allow framework authors to use TestCase.FullyQualifiedName as the TestNodeUid (#5658) --- .../ObjectModel/FrameworkHandlerAdapter.cs | 4 +- .../ObjectModel/ObjectModelConverters.cs | 21 ++++++++-- .../TestCaseDiscoverySinkAdapter.cs | 2 +- .../PublicAPI.Unshipped.txt | 1 + .../VSTestBridgedTestFrameworkBase.cs | 6 +++ .../ObjectModel/ObjectModelConvertersTests.cs | 41 ++++++++++--------- 6 files changed, 49 insertions(+), 26 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/FrameworkHandlerAdapter.cs b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/FrameworkHandlerAdapter.cs index 865ba66023..65804c81be 100644 --- a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/FrameworkHandlerAdapter.cs +++ b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/FrameworkHandlerAdapter.cs @@ -140,7 +140,7 @@ public void RecordResult(TestResult testResult) _frameworkHandle?.RecordResult(testResult); // Publish node state change to Microsoft Testing Platform - var testNode = testResult.ToTestNode(_isTrxEnabled, _namedFeatureCapability, _commandLineOptions, _clientInfo); + var testNode = testResult.ToTestNode(_isTrxEnabled, _adapterExtensionBase.UseFullyQualifiedNameAsTestNodeUid, _namedFeatureCapability, _commandLineOptions, _clientInfo); var testNodeChange = new TestNodeUpdateMessage(_session.SessionUid, testNode); _messageBus.PublishAsync(_adapterExtensionBase, testNodeChange).Await(); @@ -159,7 +159,7 @@ public void RecordStart(TestCase testCase) _frameworkHandle?.RecordStart(testCase); // Publish node state change to Microsoft Testing Platform - var testNode = testCase.ToTestNode(_isTrxEnabled, _namedFeatureCapability, _commandLineOptions, _clientInfo); + var testNode = testCase.ToTestNode(_isTrxEnabled, _adapterExtensionBase.UseFullyQualifiedNameAsTestNodeUid, _namedFeatureCapability, _commandLineOptions, _clientInfo); testNode.Properties.Add(InProgressTestNodeStateProperty.CachedInstance); var testNodeChange = new TestNodeUpdateMessage(_session.SessionUid, testNode); diff --git a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/ObjectModelConverters.cs b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/ObjectModelConverters.cs index 85fc64ea49..175dede801 100644 --- a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/ObjectModelConverters.cs +++ b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/ObjectModelConverters.cs @@ -37,9 +37,16 @@ internal static class ObjectModelConverters /// /// Converts a VSTest to a Microsoft Testing Platform . /// - public static TestNode ToTestNode(this TestCase testCase, bool isTrxEnabled, INamedFeatureCapability? namedFeatureCapability, ICommandLineOptions commandLineOptions, IClientInfo clientInfo, string? displayNameFromTestResult = null) + public static TestNode ToTestNode( + this TestCase testCase, + bool isTrxEnabled, + bool useFullyQualifiedNameAsUid, + INamedFeatureCapability? namedFeatureCapability, + ICommandLineOptions commandLineOptions, + IClientInfo clientInfo, + string? displayNameFromTestResult = null) { - string testNodeUid = testCase.Id.ToString(); + string testNodeUid = useFullyQualifiedNameAsUid ? testCase.FullyQualifiedName : testCase.Id.ToString(); TestNode testNode = new() { @@ -129,9 +136,15 @@ private static void CopyVSTestProviderProperties(TestNode testNode, TestCase tes /// /// Converts a VSTest to a Microsoft Testing Platform . /// - public static TestNode ToTestNode(this TestResult testResult, bool isTrxEnabled, INamedFeatureCapability? namedFeatureCapability, ICommandLineOptions commandLineOptions, IClientInfo clientInfo) + public static TestNode ToTestNode( + this TestResult testResult, + bool isTrxEnabled, + bool useFullyQualifiedNameAsUid, + INamedFeatureCapability? namedFeatureCapability, + ICommandLineOptions commandLineOptions, + IClientInfo clientInfo) { - var testNode = testResult.TestCase.ToTestNode(isTrxEnabled, namedFeatureCapability, commandLineOptions, clientInfo, testResult.DisplayName); + var testNode = testResult.TestCase.ToTestNode(isTrxEnabled, useFullyQualifiedNameAsUid, namedFeatureCapability, commandLineOptions, clientInfo, testResult.DisplayName); CopyCategoryAndTraits(testResult, testNode, isTrxEnabled); diff --git a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/TestCaseDiscoverySinkAdapter.cs b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/TestCaseDiscoverySinkAdapter.cs index 2fda4f9620..390b979878 100644 --- a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/TestCaseDiscoverySinkAdapter.cs +++ b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/TestCaseDiscoverySinkAdapter.cs @@ -94,7 +94,7 @@ public void SendTestCase(TestCase discoveredTest) _testCaseDiscoverySink?.SendTestCase(discoveredTest); // Publish node state change to Microsoft Testing Platform - var testNode = discoveredTest.ToTestNode(_isTrxEnabled, _namedFeatureCapability, _commandLineOptions, _clientInfo); + var testNode = discoveredTest.ToTestNode(_isTrxEnabled, _adapterExtension.UseFullyQualifiedNameAsTestNodeUid, _namedFeatureCapability, _commandLineOptions, _clientInfo); testNode.Properties.Add(DiscoveredTestNodeStateProperty.CachedInstance); var testNodeChange = new TestNodeUpdateMessage(_session.SessionUid, testNode); diff --git a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/PublicAPI.Unshipped.txt b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/PublicAPI.Unshipped.txt index 7dc5c58110..a0e14e5ed0 100644 --- a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/PublicAPI.Unshipped.txt +++ b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/PublicAPI.Unshipped.txt @@ -1 +1,2 @@ #nullable enable +virtual Microsoft.Testing.Extensions.VSTestBridge.VSTestBridgedTestFrameworkBase.UseFullyQualifiedNameAsTestNodeUid.get -> bool diff --git a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/VSTestBridgedTestFrameworkBase.cs b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/VSTestBridgedTestFrameworkBase.cs index 28481349d3..516ce0c386 100644 --- a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/VSTestBridgedTestFrameworkBase.cs +++ b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/VSTestBridgedTestFrameworkBase.cs @@ -14,6 +14,7 @@ using Microsoft.Testing.Platform.Messages; using Microsoft.Testing.Platform.Requests; using Microsoft.Testing.Platform.Services; +using Microsoft.VisualStudio.TestPlatform.ObjectModel; namespace Microsoft.Testing.Extensions.VSTestBridge; @@ -58,6 +59,11 @@ protected VSTestBridgedTestFrameworkBase(IServiceProvider serviceProvider, ITest /// protected internal IServiceProvider ServiceProvider { get; } + /// + /// Gets a value indicating whether the should use instead of . + /// + protected internal virtual bool UseFullyQualifiedNameAsTestNodeUid { get; } + /// /// Gets a value indicating whether the TRX report is enabled. /// diff --git a/test/UnitTests/Microsoft.Testing.Extensions.VSTestBridge.UnitTests/ObjectModel/ObjectModelConvertersTests.cs b/test/UnitTests/Microsoft.Testing.Extensions.VSTestBridge.UnitTests/ObjectModel/ObjectModelConvertersTests.cs index d5971e5cb8..999813a0db 100644 --- a/test/UnitTests/Microsoft.Testing.Extensions.VSTestBridge.UnitTests/ObjectModel/ObjectModelConvertersTests.cs +++ b/test/UnitTests/Microsoft.Testing.Extensions.VSTestBridge.UnitTests/ObjectModel/ObjectModelConvertersTests.cs @@ -23,22 +23,25 @@ public sealed class ObjectModelConvertersTests private static readonly IClientInfo ClientInfo = new ClientInfoService(WellKnownClients.VisualStudio, "1.0.0"); [TestMethod] - public void ToTestNode_WhenTestCaseHasDisplayName_TestNodeDisplayNameUsesIt() + [DataRow(true)] + [DataRow(false)] + public void ToTestNode_WhenTestCaseHasDisplayName_TestNodeDisplayNameUsesIt(bool useFullyQualifiedNameAsUid) { TestCase testCase = new("SomeFqn", new("executor://uri", UriKind.Absolute), "source.cs") { DisplayName = "MyDisplayName", }; - var testNode = testCase.ToTestNode(false, null, new ConsoleCommandLineOptions(), ClientInfo); + var testNode = testCase.ToTestNode(isTrxEnabled: false, useFullyQualifiedNameAsUid, null, new ConsoleCommandLineOptions(), ClientInfo); Assert.AreEqual("MyDisplayName", testNode.DisplayName); + Assert.AreEqual(useFullyQualifiedNameAsUid ? "SomeFqn" : testCase.Id.ToString(), testNode.Uid.Value); } [TestMethod] public void ToTestNode_WhenTestCaseHasNoDisplayName_TestNodeDisplayNameUsesIt() { TestCase testCase = new("SomeFqn", new("executor://uri", UriKind.Absolute), "source.cs"); - var testNode = testCase.ToTestNode(false, null, new ConsoleCommandLineOptions(), ClientInfo); + var testNode = testCase.ToTestNode(isTrxEnabled: false, useFullyQualifiedNameAsUid: false, null, new ConsoleCommandLineOptions(), ClientInfo); Assert.AreEqual("SomeFqn", testNode.DisplayName); } @@ -50,7 +53,7 @@ public void ToTestNode_WhenTestResultHasCodeFilePath_SetsTestFileLocationPropert { CodeFilePath = "FilePath", }); - var testNode = testResult.ToTestNode(false, null, new ConsoleCommandLineOptions(), ClientInfo); + var testNode = testResult.ToTestNode(isTrxEnabled: false, useFullyQualifiedNameAsUid: false, null, new ConsoleCommandLineOptions(), ClientInfo); Assert.AreEqual("FilePath", testNode.Properties.Single().FilePath); } @@ -63,7 +66,7 @@ public void ToTestNode_WhenTestResultOutcomeIsFailed_TestNodePropertiesContainFa ErrorMessage = "SomeErrorMessage", ErrorStackTrace = "SomeStackTrace", }; - var testNode = testResult.ToTestNode(false, null, new ConsoleCommandLineOptions(), ClientInfo); + var testNode = testResult.ToTestNode(isTrxEnabled: false, useFullyQualifiedNameAsUid: false, null, new ConsoleCommandLineOptions(), ClientInfo); FailedTestNodeStateProperty[] failedTestNodeStateProperties = [.. testNode.Properties.OfType()]; Assert.AreEqual(1, failedTestNodeStateProperties.Length); @@ -81,7 +84,7 @@ public void ToTestNode_WhenTestResultHasMSTestDiscovererTestCategoryTestProperty #pragma warning restore CS0618 // Type or member is obsolete testResult.SetPropertyValue(testCategoryProperty, ["category1"]); - var testNode = testResult.ToTestNode(false, new NamedFeatureCapabilityWithVSTestProvider(), new ServerModeCommandLineOptions(), ClientInfo); + var testNode = testResult.ToTestNode(isTrxEnabled: false, useFullyQualifiedNameAsUid: false, new NamedFeatureCapabilityWithVSTestProvider(), new ServerModeCommandLineOptions(), ClientInfo); TestMetadataProperty[] testMetadatas = [.. testNode.Properties.OfType()]; Assert.AreEqual(1, testMetadatas.Length); @@ -98,7 +101,7 @@ public void ToTestNode_WhenTestResultHasMSTestDiscovererTestCategoryTestProperty #pragma warning restore CS0618 // Type or member is obsolete testResult.SetPropertyValue(testCategoryProperty, ["category1"]); - var testNode = testResult.ToTestNode(true, new NamedFeatureCapabilityWithVSTestProvider(), new ServerModeCommandLineOptions(), ClientInfo); + var testNode = testResult.ToTestNode(isTrxEnabled: true, useFullyQualifiedNameAsUid: false, new NamedFeatureCapabilityWithVSTestProvider(), new ServerModeCommandLineOptions(), ClientInfo); TrxCategoriesProperty[] trxCategoriesProperty = [.. testNode.Properties.OfType()]; Assert.AreEqual(1, trxCategoriesProperty.Length); @@ -115,7 +118,7 @@ public void ToTestNode_WhenTestCaseHasOriginalExecutorUriProperty_TestNodeProper testCase.SetPropertyValue(originalExecutorUriProperty, new Uri("https://vs.com/")); - var testNode = testCase.ToTestNode(false, new NamedFeatureCapabilityWithVSTestProvider(), new ServerModeCommandLineOptions(), ClientInfo); + var testNode = testCase.ToTestNode(isTrxEnabled: false, useFullyQualifiedNameAsUid: false, new NamedFeatureCapabilityWithVSTestProvider(), new ServerModeCommandLineOptions(), ClientInfo); SerializableKeyValuePairStringProperty[] serializableKeyValuePairStringProperty = [.. testNode.Properties.OfType()]; Assert.AreEqual(3, serializableKeyValuePairStringProperty.Length); @@ -128,7 +131,7 @@ public void ToTestNode_WhenTestResultHasFullyQualifiedTypeAndTrxEnabled_TestNode { TestResult testResult = new(new TestCase("assembly.class.test", new("executor://uri", UriKind.Absolute), "source.cs")); - var testNode = testResult.ToTestNode(true, null, new ConsoleCommandLineOptions(), ClientInfo); + var testNode = testResult.ToTestNode(isTrxEnabled: true, useFullyQualifiedNameAsUid: false, null, new ConsoleCommandLineOptions(), ClientInfo); Assert.AreEqual(1, testNode.Properties.OfType()?.Length); Assert.AreEqual("assembly.class", testNode.Properties.Single().FullyQualifiedTypeName); @@ -139,7 +142,7 @@ public void ToTestNode_WhenTestResultHasNoFullyQualifiedTypeAndTrxEnabled_Throws { TestResult testResult = new(new TestCase("test", new("executor://uri", UriKind.Absolute), "source.cs")); - string errorMessage = Assert.ThrowsException(() => testResult.ToTestNode(true, null, new ConsoleCommandLineOptions(), ClientInfo)).Message; + string errorMessage = Assert.ThrowsException(() => testResult.ToTestNode(isTrxEnabled: true, useFullyQualifiedNameAsUid: false, null, new ConsoleCommandLineOptions(), ClientInfo)).Message; Assert.IsTrue(errorMessage.Contains("Unable to parse fully qualified type name from test case: ")); } @@ -157,7 +160,7 @@ public void ToTestNode_FromTestResult_TestNodePropertiesContainCorrectTimingProp EndTime = endTime, Duration = duration, }; - var testNode = testResult.ToTestNode(false, null, new ConsoleCommandLineOptions(), ClientInfo); + var testNode = testResult.ToTestNode(isTrxEnabled: false, useFullyQualifiedNameAsUid: false, null, new ConsoleCommandLineOptions(), ClientInfo); var testResultTimingProperty = new TimingProperty(new(startTime, endTime, duration), []); Assert.AreEqual(testNode.Properties.OfType()[0], testResultTimingProperty); @@ -171,7 +174,7 @@ public void ToTestNode_WhenTestResultOutcomeIsNotFoundWithoutSetErrorMessage_Tes Outcome = TestOutcome.NotFound, ErrorStackTrace = "SomeStackTrace", }; - var testNode = testResult.ToTestNode(false, null, new ConsoleCommandLineOptions(), ClientInfo); + var testNode = testResult.ToTestNode(isTrxEnabled: false, useFullyQualifiedNameAsUid: false, null, new ConsoleCommandLineOptions(), ClientInfo); ErrorTestNodeStateProperty[] errorTestNodeStateProperties = [.. testNode.Properties.OfType()]; Assert.AreEqual(1, errorTestNodeStateProperties.Length); @@ -187,7 +190,7 @@ public void ToTestNode_WhenTestResultOutcomeIsSkipped_TestNodePropertiesContainS { Outcome = TestOutcome.Skipped, }; - var testNode = testResult.ToTestNode(false, null, new ConsoleCommandLineOptions(), ClientInfo); + var testNode = testResult.ToTestNode(isTrxEnabled: false, useFullyQualifiedNameAsUid: false, null, new ConsoleCommandLineOptions(), ClientInfo); SkippedTestNodeStateProperty[] skipTestNodeStateProperties = [.. testNode.Properties.OfType()]; Assert.AreEqual(1, skipTestNodeStateProperties.Length); @@ -200,7 +203,7 @@ public void ToTestNode_WhenTestResultOutcomeIsNone_TestNodePropertiesContainSkip { Outcome = TestOutcome.None, }; - var testNode = testResult.ToTestNode(false, null, new ConsoleCommandLineOptions(), ClientInfo); + var testNode = testResult.ToTestNode(isTrxEnabled: false, useFullyQualifiedNameAsUid: false, null, new ConsoleCommandLineOptions(), ClientInfo); SkippedTestNodeStateProperty[] skipTestNodeStateProperties = [.. testNode.Properties.OfType()]; Assert.AreEqual(1, skipTestNodeStateProperties.Length); @@ -213,7 +216,7 @@ public void ToTestNode_WhenTestResultOutcomeIsPassed_TestNodePropertiesContainPa { Outcome = TestOutcome.Passed, }; - var testNode = testResult.ToTestNode(false, null, new ConsoleCommandLineOptions(), ClientInfo); + var testNode = testResult.ToTestNode(isTrxEnabled: false, useFullyQualifiedNameAsUid: false, null, new ConsoleCommandLineOptions(), ClientInfo); PassedTestNodeStateProperty[] passedTestNodeStateProperties = [.. testNode.Properties.OfType()]; Assert.AreEqual(1, passedTestNodeStateProperties.Length); @@ -224,7 +227,7 @@ public void ToTestNode_WhenTestCaseHasUidAndDisplayNameWithWellKnownClient_TestN { var testCase = new TestCase("SomeFqn", new("executor://uri", UriKind.Absolute), "source.cs"); - var testNode = testCase.ToTestNode(false, new NamedFeatureCapabilityWithVSTestProvider(), new ServerModeCommandLineOptions(), ClientInfo); + var testNode = testCase.ToTestNode(isTrxEnabled: false, useFullyQualifiedNameAsUid: false, new NamedFeatureCapabilityWithVSTestProvider(), new ServerModeCommandLineOptions(), ClientInfo); SerializableKeyValuePairStringProperty[] errorTestNodeStateProperties = [.. testNode.Properties.OfType()]; Assert.AreEqual(2, errorTestNodeStateProperties.Length, "Expected 2 SerializableKeyValuePairStringProperty"); @@ -242,7 +245,7 @@ public void ToTestNode_WhenTestResultHasTraits_TestNodePropertiesContainIt() Traits = { new Trait("key", "value") }, }; - var testNode = testResult.ToTestNode(false, new NamedFeatureCapabilityWithVSTestProvider(), new ServerModeCommandLineOptions(), ClientInfo); + var testNode = testResult.ToTestNode(isTrxEnabled: false, useFullyQualifiedNameAsUid: false, new NamedFeatureCapabilityWithVSTestProvider(), new ServerModeCommandLineOptions(), ClientInfo); TestMetadataProperty[] testMetadatas = [.. testNode.Properties.OfType()]; Assert.AreEqual(1, testMetadatas.Length); @@ -263,7 +266,7 @@ public void ToTestNode_WhenTestResultHasMultipleStandardOutputMessages_TestNodeP }, }; - var testNode = testResult.ToTestNode(false, new NamedFeatureCapabilityWithVSTestProvider(), new ServerModeCommandLineOptions(), ClientInfo); + var testNode = testResult.ToTestNode(isTrxEnabled: false, useFullyQualifiedNameAsUid: false, new NamedFeatureCapabilityWithVSTestProvider(), new ServerModeCommandLineOptions(), ClientInfo); StandardOutputProperty[] standardOutputProperties = [.. testNode.Properties.OfType()]; Assert.IsTrue(standardOutputProperties.Length == 1); @@ -283,7 +286,7 @@ public void ToTestNode_WhenTestResultHasMultipleStandardErrorMessages_TestNodePr }, }; - var testNode = testResult.ToTestNode(false, new NamedFeatureCapabilityWithVSTestProvider(), new ServerModeCommandLineOptions(), ClientInfo); + var testNode = testResult.ToTestNode(isTrxEnabled: false, useFullyQualifiedNameAsUid: false, new NamedFeatureCapabilityWithVSTestProvider(), new ServerModeCommandLineOptions(), ClientInfo); StandardErrorProperty[] standardErrorProperties = [.. testNode.Properties.OfType()]; Assert.IsTrue(standardErrorProperties.Length == 1); From 7b0d5d1c5049a2a485586b45bce5a98305e3d300 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Tue, 3 Jun 2025 16:39:20 +0200 Subject: [PATCH 054/541] Fix MSTEST0042 (duplicate data row) false positive with Zero/NegativeZero (#5684) --- .../DuplicateDataRowAnalyzer.cs | 16 +++ .../DuplicateDataRowAnalyzerTests.cs | 112 ++++++++++++++++++ 2 files changed, 128 insertions(+) diff --git a/src/Analyzers/MSTest.Analyzers/DuplicateDataRowAnalyzer.cs b/src/Analyzers/MSTest.Analyzers/DuplicateDataRowAnalyzer.cs index b4c2596fe9..6d560c76c1 100644 --- a/src/Analyzers/MSTest.Analyzers/DuplicateDataRowAnalyzer.cs +++ b/src/Analyzers/MSTest.Analyzers/DuplicateDataRowAnalyzer.cs @@ -126,6 +126,22 @@ private static bool AreTypedConstantEquals(TypedConstant typedConstant1, TypedCo return TypedConstantArrayComparer.Instance.Equals(typedConstant1.Values, typedConstant2.Values); } + if (typedConstant1.Kind == TypedConstantKind.Primitive) + { + // object.Equals(float.NegativeZero, 0.0f) will return true. + // But we don't want to consider it as "equal" as the test case can yield different results. + // Behavior difference between zero and negative zero can be observed via BitConverter or ToString. + if (typedConstant1.Value is float float1 && typedConstant2.Value is float float2) + { + // BitConverter.SingleToInt32Bits isn't available on netstandard2.0, so we use BitConverter.GetBytes instead. + return BitConverter.GetBytes(float1).SequenceEqual(BitConverter.GetBytes(float2)); + } + else if (typedConstant1.Value is double double1 && typedConstant2.Value is double double2) + { + return BitConverter.DoubleToInt64Bits(double1) == BitConverter.DoubleToInt64Bits(double2); + } + } + // At this point, the type is matching and the kind is matching and is not array. return object.Equals(typedConstant1.Value, typedConstant2.Value); } diff --git a/test/UnitTests/MSTest.Analyzers.UnitTests/DuplicateDataRowAnalyzerTests.cs b/test/UnitTests/MSTest.Analyzers.UnitTests/DuplicateDataRowAnalyzerTests.cs index 52a788fcb2..49c9de6b33 100644 --- a/test/UnitTests/MSTest.Analyzers.UnitTests/DuplicateDataRowAnalyzerTests.cs +++ b/test/UnitTests/MSTest.Analyzers.UnitTests/DuplicateDataRowAnalyzerTests.cs @@ -177,4 +177,116 @@ public static void TestMethod() await VerifyCS.VerifyAnalyzerAsync(code); } + + [TestMethod] + public async Task WhenZeroAndNegativeZero_NoDiagnostic() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + [DataRow(0.0d)] + [DataRow(-0.0d)] + public static void TestMethod1(double x) + { + } + + [TestMethod] + [DataRow(0.0f)] + [DataRow(-0.0f)] + public static void TestMethod2(float x) + { + } + } + """; + + await VerifyCS.VerifyAnalyzerAsync(code); + } + + [TestMethod] + public async Task WhenZeroIsDuplicated_Diagnostic() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + [DataRow(0.0d)] + [[|DataRow(0d)|]] + public static void TestMethod1(double x) + { + } + + [TestMethod] + [DataRow(0.0d)] + [[|DataRow(0.0d)|]] + public static void TestMethod2(double x) + { + } + + [TestMethod] + [DataRow(0.0f)] + [[|DataRow(0f)|]] + public static void TestMethod3(float x) + { + } + + [TestMethod] + [DataRow(0.0f)] + [[|DataRow(0.0f)|]] + public static void TestMethod4(float x) + { + } + } + """; + + await VerifyCS.VerifyAnalyzerAsync(code); + } + + [TestMethod] + public async Task WhenNegativeZeroIsDuplicated_Diagnostic() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + [DataRow(-0.0d)] + [[|DataRow(-0d)|]] + public static void TestMethod1(double x) + { + } + + [TestMethod] + [DataRow(-0.0d)] + [[|DataRow(-0.0d)|]] + public static void TestMethod2(double x) + { + } + + [TestMethod] + [DataRow(-0.0f)] + [[|DataRow(-0f)|]] + public static void TestMethod3(float x) + { + } + + [TestMethod] + [DataRow(-0.0f)] + [[|DataRow(-0.0f)|]] + public static void TestMethod4(float x) + { + } + } + """; + + await VerifyCS.VerifyAnalyzerAsync(code); + } } From 189406154b25d7f2727bd16e74f0dcbf3431b40b Mon Sep 17 00:00:00 2001 From: Copilot <198982749+Copilot@users.noreply.github.com> Date: Wed, 4 Jun 2025 12:58:50 +0200 Subject: [PATCH 055/541] Rename RegisterTestFramework adapterFactory parameter to frameworkFactory (#5691) Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: Youssef1313 <31348972+Youssef1313@users.noreply.github.com> --- .../Builder/ITestApplicationBuilder.cs | 4 ++-- .../Builder/TestApplicationBuilder.cs | 6 +++--- .../PublicAPI/PublicAPI.Unshipped.txt | 2 ++ 3 files changed, 7 insertions(+), 5 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Platform/Builder/ITestApplicationBuilder.cs b/src/Platform/Microsoft.Testing.Platform/Builder/ITestApplicationBuilder.cs index 7309a14589..d17fca33e1 100644 --- a/src/Platform/Microsoft.Testing.Platform/Builder/ITestApplicationBuilder.cs +++ b/src/Platform/Microsoft.Testing.Platform/Builder/ITestApplicationBuilder.cs @@ -47,11 +47,11 @@ public interface ITestApplicationBuilder /// Registers a test framework with the application builder. /// /// The factory method for creating test framework capabilities. - /// The factory method for creating a test framework adapter. + /// The factory method for creating a test framework adapter. /// The updated test application builder. ITestApplicationBuilder RegisterTestFramework( Func capabilitiesFactory, - Func adapterFactory); + Func frameworkFactory); /// /// Builds the test application asynchronously. diff --git a/src/Platform/Microsoft.Testing.Platform/Builder/TestApplicationBuilder.cs b/src/Platform/Microsoft.Testing.Platform/Builder/TestApplicationBuilder.cs index 4147baebc8..ce13d07d0b 100644 --- a/src/Platform/Microsoft.Testing.Platform/Builder/TestApplicationBuilder.cs +++ b/src/Platform/Microsoft.Testing.Platform/Builder/TestApplicationBuilder.cs @@ -72,9 +72,9 @@ internal TestApplicationBuilder( public ITestApplicationBuilder RegisterTestFramework( Func capabilitiesFactory, - Func adapterFactory) + Func frameworkFactory) { - Guard.NotNull(adapterFactory); + Guard.NotNull(frameworkFactory); Guard.NotNull(capabilitiesFactory); if (_testFrameworkFactory is not null) @@ -82,7 +82,7 @@ public ITestApplicationBuilder RegisterTestFramework( throw new InvalidOperationException(PlatformResources.TestApplicationBuilderFrameworkAdapterFactoryAlreadyRegisteredErrorMessage); } - _testFrameworkFactory = adapterFactory; + _testFrameworkFactory = frameworkFactory; if (_testFrameworkCapabilitiesFactory is not null) { diff --git a/src/Platform/Microsoft.Testing.Platform/PublicAPI/PublicAPI.Unshipped.txt b/src/Platform/Microsoft.Testing.Platform/PublicAPI/PublicAPI.Unshipped.txt index 7dc5c58110..eed1e2d100 100644 --- a/src/Platform/Microsoft.Testing.Platform/PublicAPI/PublicAPI.Unshipped.txt +++ b/src/Platform/Microsoft.Testing.Platform/PublicAPI/PublicAPI.Unshipped.txt @@ -1 +1,3 @@ #nullable enable +Microsoft.Testing.Platform.Builder.ITestApplicationBuilder.RegisterTestFramework(System.Func! capabilitiesFactory, System.Func! frameworkFactory) -> Microsoft.Testing.Platform.Builder.ITestApplicationBuilder! +*REMOVED*Microsoft.Testing.Platform.Builder.ITestApplicationBuilder.RegisterTestFramework(System.Func! capabilitiesFactory, System.Func! adapterFactory) -> Microsoft.Testing.Platform.Builder.ITestApplicationBuilder! From 37692a09d71e05eedc0298d670bc7194fa734d36 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Wed, 4 Jun 2025 13:18:03 +0200 Subject: [PATCH 056/541] Fix fallback path for getting method info if InvalidManagedNameException is thrown (#5692) --- src/Adapter/MSTest.TestAdapter/Execution/TypeCache.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Adapter/MSTest.TestAdapter/Execution/TypeCache.cs b/src/Adapter/MSTest.TestAdapter/Execution/TypeCache.cs index bf00aec70e..2d49d1fe10 100644 --- a/src/Adapter/MSTest.TestAdapter/Execution/TypeCache.cs +++ b/src/Adapter/MSTest.TestAdapter/Execution/TypeCache.cs @@ -738,7 +738,7 @@ private MethodInfo GetMethodInfoForTestMethod(TestMethod testMethod, TestClassIn { Type[] parameters = [.. methodBase.GetParameters().Select(i => i.ParameterType)]; // TODO: Should we pass true for includeNonPublic? - testMethodInfo = PlatformServiceProvider.Instance.ReflectionOperations.GetRuntimeMethod(methodBase.DeclaringType!, methodBase.Name, parameters, includeNonPublic: false); + testMethodInfo = PlatformServiceProvider.Instance.ReflectionOperations.GetRuntimeMethod(methodBase.DeclaringType!, methodBase.Name, parameters, includeNonPublic: true); } return testMethodInfo is null From 8db96837292a8b95b27182e0044c223bd594174e Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Thu, 5 Jun 2025 09:56:15 +0000 Subject: [PATCH 057/541] [main] Update dependencies from devdiv/DevDiv/vs-code-coverage, dotnet/arcade (#5675) [main] Update dependencies from devdiv/DevDiv/vs-code-coverage, dotnet/arcade --- eng/Version.Details.xml | 16 +++--- eng/Versions.props | 4 +- eng/common/build.ps1 | 3 ++ eng/common/build.sh | 14 ++++-- eng/common/core-templates/job/onelocbuild.yml | 5 +- .../job/publish-build-assets.yml | 49 ++++++++++++++++--- eng/common/tools.ps1 | 9 ++-- eng/common/tools.sh | 11 ++--- eng/common/vmr-sync.ps1 | 6 +-- eng/common/vmr-sync.sh | 6 ++- global.json | 2 +- 11 files changed, 84 insertions(+), 41 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index 52f4c40047..b9ecb36f6c 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -1,21 +1,21 @@ - + https://github.com/dotnet/arcade - 12d3a9f5d6138e22270694574e73e4c58a815795 + d3a9e0bf843815be1a2b30895e2060ef73735772 - + https://github.com/dotnet/arcade - 12d3a9f5d6138e22270694574e73e4c58a815795 + d3a9e0bf843815be1a2b30895e2060ef73735772 - + https://github.com/dotnet/arcade - 12d3a9f5d6138e22270694574e73e4c58a815795 + d3a9e0bf843815be1a2b30895e2060ef73735772 - + https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage - b37c73cef7bbebb497a391cab93a2de4897e6671 + 56072d0b01c97c921bf6dcbe81297f0e44551f04 diff --git a/eng/Versions.props b/eng/Versions.props index a18ff9cfef..d3e76836f4 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -7,7 +7,7 @@ preview - 10.0.0-beta.25271.2 - 17.15.0-preview.25278.2 + 10.0.0-beta.25304.5 + 17.15.0-preview.25304.1 diff --git a/eng/common/build.ps1 b/eng/common/build.ps1 index ae2309e312..8cfee107e7 100644 --- a/eng/common/build.ps1 +++ b/eng/common/build.ps1 @@ -21,6 +21,7 @@ Param( [switch] $publish, [switch] $clean, [switch][Alias('pb')]$productBuild, + [switch]$fromVMR, [switch][Alias('bl')]$binaryLog, [switch][Alias('nobl')]$excludeCIBinarylog, [switch] $ci, @@ -74,6 +75,7 @@ function Print-Usage() { Write-Host " -nativeToolsOnMachine Sets the native tools on machine environment variable (indicating that the script should use native tools on machine)" Write-Host " -nodeReuse Sets nodereuse msbuild parameter ('true' or 'false')" Write-Host " -buildCheck Sets /check msbuild parameter" + Write-Host " -fromVMR Set when building from within the VMR" Write-Host "" Write-Host "Command line arguments not listed above are passed thru to msbuild." @@ -128,6 +130,7 @@ function Build { /p:Test=$test ` /p:Pack=$pack ` /p:DotNetBuild=$productBuild ` + /p:DotNetBuildFromVMR=$fromVMR ` /p:IntegrationTest=$integrationTest ` /p:PerformanceTest=$performanceTest ` /p:Sign=$sign ` diff --git a/eng/common/build.sh b/eng/common/build.sh index da906da202..9767bb411a 100755 --- a/eng/common/build.sh +++ b/eng/common/build.sh @@ -43,6 +43,7 @@ usage() echo " --nodeReuse Sets nodereuse msbuild parameter ('true' or 'false')" echo " --warnAsError Sets warnaserror msbuild parameter ('true' or 'false')" echo " --buildCheck Sets /check msbuild parameter" + echo " --fromVMR Set when building from within the VMR" echo "" echo "Command line arguments not listed above are passed thru to msbuild." echo "Arguments can also be passed in with a single hyphen." @@ -64,6 +65,7 @@ restore=false build=false source_build=false product_build=false +from_vmr=false rebuild=false test=false integration_test=false @@ -89,7 +91,7 @@ verbosity='minimal' runtime_source_feed='' runtime_source_feed_key='' -properties='' +properties=() while [[ $# > 0 ]]; do opt="$(echo "${1/#--/-}" | tr "[:upper:]" "[:lower:]")" case "$opt" in @@ -142,6 +144,9 @@ while [[ $# > 0 ]]; do restore=true pack=true ;; + -fromvmr|-from-vmr) + from_vmr=true + ;; -test|-t) test=true ;; @@ -187,7 +192,7 @@ while [[ $# > 0 ]]; do shift ;; *) - properties="$properties $1" + properties+=("$1") ;; esac @@ -221,7 +226,7 @@ function Build { InitializeCustomToolset if [[ ! -z "$projects" ]]; then - properties="$properties /p:Projects=$projects" + properties+=("/p:Projects=$projects") fi local bl="" @@ -243,6 +248,7 @@ function Build { /p:Build=$build \ /p:DotNetBuild=$product_build \ /p:DotNetBuildSourceOnly=$source_build \ + /p:DotNetBuildFromVMR=$from_vmr \ /p:Rebuild=$rebuild \ /p:Test=$test \ /p:Pack=$pack \ @@ -251,7 +257,7 @@ function Build { /p:Sign=$sign \ /p:Publish=$publish \ /p:RestoreStaticGraphEnableBinaryLogger=$binary_log \ - $properties + ${properties[@]+"${properties[@]}"} ExitWithExitCode 0 } diff --git a/eng/common/core-templates/job/onelocbuild.yml b/eng/common/core-templates/job/onelocbuild.yml index 00feec8ebb..8034815f42 100644 --- a/eng/common/core-templates/job/onelocbuild.yml +++ b/eng/common/core-templates/job/onelocbuild.yml @@ -86,8 +86,7 @@ jobs: isAutoCompletePrSelected: ${{ parameters.AutoCompletePr }} ${{ if eq(parameters.CreatePr, true) }}: isUseLfLineEndingsSelected: ${{ parameters.UseLfLineEndings }} - ${{ if eq(parameters.RepoType, 'gitHub') }}: - isShouldReusePrSelected: ${{ parameters.ReusePr }} + isShouldReusePrSelected: ${{ parameters.ReusePr }} packageSourceAuth: patAuth patVariable: ${{ parameters.CeapexPat }} ${{ if eq(parameters.RepoType, 'gitHub') }}: @@ -118,4 +117,4 @@ jobs: pathToPublish: '$(Build.SourcesDirectory)/eng/Localize/' publishLocation: Container artifactName: Loc - condition: ${{ parameters.condition }} \ No newline at end of file + condition: ${{ parameters.condition }} diff --git a/eng/common/core-templates/job/publish-build-assets.yml b/eng/common/core-templates/job/publish-build-assets.yml index 4f1dc42e02..d5303229c9 100644 --- a/eng/common/core-templates/job/publish-build-assets.yml +++ b/eng/common/core-templates/job/publish-build-assets.yml @@ -32,6 +32,12 @@ parameters: # Optional: 🌤️ or not the build has assets it wants to publish to BAR isAssetlessBuild: false + # Optional, publishing version + publishingVersion: 3 + + # Optional: A minimatch pattern for the asset manifests to publish to BAR + assetManifestsPattern: '*/manifests/**/*.xml' + jobs: - job: Asset_Registry_Publish @@ -77,13 +83,31 @@ jobs: clean: true - ${{ if eq(parameters.isAssetlessBuild, 'false') }}: - - task: DownloadPipelineArtifact@2 - displayName: Download Asset Manifests - inputs: - artifactName: AssetManifests - targetPath: '$(Build.StagingDirectory)/AssetManifests' - condition: ${{ parameters.condition }} - continueOnError: ${{ parameters.continueOnError }} + - ${{ if eq(parameters.publishingVersion, 3) }}: + - task: DownloadPipelineArtifact@2 + displayName: Download Asset Manifests + inputs: + artifactName: AssetManifests + targetPath: '$(Build.StagingDirectory)/AssetManifests' + condition: ${{ parameters.condition }} + continueOnError: ${{ parameters.continueOnError }} + - ${{ if eq(parameters.publishingVersion, 4) }}: + - task: DownloadPipelineArtifact@2 + displayName: Download V4 asset manifests + inputs: + itemPattern: '*/manifests/**/*.xml' + targetPath: '$(Build.StagingDirectory)/AllAssetManifests' + condition: ${{ parameters.condition }} + continueOnError: ${{ parameters.continueOnError }} + - task: CopyFiles@2 + displayName: Copy V4 asset manifests to AssetManifests + inputs: + SourceFolder: '$(Build.StagingDirectory)/AllAssetManifests' + Contents: ${{ parameters.assetManifestsPattern }} + TargetFolder: '$(Build.StagingDirectory)/AssetManifests' + flattenFolders: true + condition: ${{ parameters.condition }} + continueOnError: ${{ parameters.continueOnError }} - task: NuGetAuthenticate@1 @@ -120,6 +144,17 @@ jobs: Copy-Item -Path $symbolExclusionfile -Destination "$(Build.StagingDirectory)/ReleaseConfigs" } + - ${{ if eq(parameters.publishingVersion, 4) }}: + - template: /eng/common/core-templates/steps/publish-pipeline-artifacts.yml + parameters: + is1ESPipeline: ${{ parameters.is1ESPipeline }} + args: + targetPath: '$(Build.ArtifactStagingDirectory)/MergedManifest.xml' + artifactName: AssetManifests + displayName: 'Publish Merged Manifest' + retryCountOnTaskFailure: 10 # for any logs being locked + sbomEnabled: false # we don't need SBOM for logs + - template: /eng/common/core-templates/steps/publish-build-artifacts.yml parameters: is1ESPipeline: ${{ parameters.is1ESPipeline }} diff --git a/eng/common/tools.ps1 b/eng/common/tools.ps1 index 5f40a3f823..c9e39595b5 100644 --- a/eng/common/tools.ps1 +++ b/eng/common/tools.ps1 @@ -65,8 +65,8 @@ $ErrorActionPreference = 'Stop' # Base-64 encoded SAS token that has permission to storage container described by $runtimeSourceFeed [string]$runtimeSourceFeedKey = if (Test-Path variable:runtimeSourceFeedKey) { $runtimeSourceFeedKey } else { $null } -# True if the build is a product build -[bool]$productBuild = if (Test-Path variable:productBuild) { $productBuild } else { $false } +# True when the build is running within the VMR. +[bool]$fromVMR = if (Test-Path variable:fromVMR) { $fromVMR } else { $false } function Create-Directory ([string[]] $path) { New-Item -Path $path -Force -ItemType 'Directory' | Out-Null @@ -644,7 +644,6 @@ function GetNuGetPackageCachePath() { $env:NUGET_PACKAGES = Join-Path $env:UserProfile '.nuget\packages\' } else { $env:NUGET_PACKAGES = Join-Path $RepoRoot '.packages\' - $env:RESTORENOHTTPCACHE = $true } } @@ -850,8 +849,8 @@ function MSBuild-Core() { } # When running on Azure Pipelines, override the returned exit code to avoid double logging. - # Skip this when the build is a child of the VMR orchestrator build. - if ($ci -and $env:SYSTEM_TEAMPROJECT -ne $null -and !$productBuild) { + # Skip this when the build is a child of the VMR build. + if ($ci -and $env:SYSTEM_TEAMPROJECT -ne $null -and !$fromVMR) { Write-PipelineSetResult -Result "Failed" -Message "msbuild execution failed." # Exiting with an exit code causes the azure pipelines task to log yet another "noise" error # The above Write-PipelineSetResult will cause the task to be marked as failure without adding yet another error diff --git a/eng/common/tools.sh b/eng/common/tools.sh index 25f5932eee..a7e8493151 100644 --- a/eng/common/tools.sh +++ b/eng/common/tools.sh @@ -72,8 +72,8 @@ fi runtime_source_feed=${runtime_source_feed:-''} runtime_source_feed_key=${runtime_source_feed_key:-''} -# True if the build is a product build -product_build=${product_build:-false} +# True when the build is running within the VMR. +from_vmr=${from_vmr:-false} # Resolve any symlinks in the given path. function ResolvePath { @@ -345,14 +345,12 @@ function InitializeBuildTool { _InitializeBuildToolCommand="msbuild" } -# Set RestoreNoHttpCache as a workaround for https://github.com/NuGet/Home/issues/3116 function GetNuGetPackageCachePath { if [[ -z ${NUGET_PACKAGES:-} ]]; then if [[ "$use_global_nuget_cache" == true ]]; then export NUGET_PACKAGES="$HOME/.nuget/packages/" else export NUGET_PACKAGES="$repo_root/.packages/" - export RESTORENOHTTPCACHE=true fi fi @@ -506,8 +504,8 @@ function MSBuild-Core { echo "Build failed with exit code $exit_code. Check errors above." # When running on Azure Pipelines, override the returned exit code to avoid double logging. - # Skip this when the build is a child of the VMR orchestrator build. - if [[ "$ci" == true && -n ${SYSTEM_TEAMPROJECT:-} && "$product_build" != true ]]; then + # Skip this when the build is a child of the VMR build. + if [[ "$ci" == true && -n ${SYSTEM_TEAMPROJECT:-} && "$from_vmr" != true ]]; then Write-PipelineSetResult -result "Failed" -message "msbuild execution failed." # Exiting with an exit code causes the azure pipelines task to log yet another "noise" error # The above Write-PipelineSetResult will cause the task to be marked as failure without adding yet another error @@ -530,6 +528,7 @@ function GetDarc { fi "$eng_root/common/darc-init.sh" --toolpath "$darc_path" $version + darc_tool="$darc_path/darc" } # Returns a full path to an Arcade SDK task project file. diff --git a/eng/common/vmr-sync.ps1 b/eng/common/vmr-sync.ps1 index 8c3c91ce8d..97302f3205 100644 --- a/eng/common/vmr-sync.ps1 +++ b/eng/common/vmr-sync.ps1 @@ -103,14 +103,14 @@ Set-StrictMode -Version Latest Highlight 'Installing .NET, preparing the tooling..' . .\eng\common\tools.ps1 $dotnetRoot = InitializeDotNetCli -install:$true +$darc = Get-Darc $dotnet = "$dotnetRoot\dotnet.exe" -& "$dotnet" tool restore Highlight "Starting the synchronization of VMR.." # Synchronize the VMR $darcArgs = ( - "darc", "vmr", "forwardflow", + "vmr", "forwardflow", "--tmp", $tmpDir, "--$verbosity", $vmrDir @@ -124,7 +124,7 @@ if ($azdevPat) { $darcArgs += ("--azdev-pat", $azdevPat) } -& "$dotnet" $darcArgs +& "$darc" $darcArgs if ($LASTEXITCODE -eq 0) { Highlight "Synchronization succeeded" diff --git a/eng/common/vmr-sync.sh b/eng/common/vmr-sync.sh index 86d77ccf5b..44239e331c 100644 --- a/eng/common/vmr-sync.sh +++ b/eng/common/vmr-sync.sh @@ -164,9 +164,9 @@ set -e highlight 'Installing .NET, preparing the tooling..' source "./eng/common/tools.sh" InitializeDotNetCli true +GetDarc dotnetDir=$( cd ./.dotnet/; pwd -P ) dotnet=$dotnetDir/dotnet -"$dotnet" tool restore highlight "Starting the synchronization of VMR.." set +e @@ -186,7 +186,9 @@ fi # Synchronize the VMR -"$dotnet" darc vmr forwardflow \ +export DOTNET_ROOT="$dotnetDir" + +"$darc_tool" vmr forwardflow \ --tmp "$tmp_dir" \ $azdev_pat \ --$verbosity \ diff --git a/global.json b/global.json index 91a8faa1f6..867bbcf5e2 100644 --- a/global.json +++ b/global.json @@ -28,7 +28,7 @@ "rollForward": "latestFeature" }, "msbuild-sdks": { - "Microsoft.DotNet.Arcade.Sdk": "10.0.0-beta.25271.2", + "Microsoft.DotNet.Arcade.Sdk": "10.0.0-beta.25304.5", "MSBuild.Sdk.Extras": "3.0.44" } } From a4167587079e565b3f1c18b332e61f789b50acb1 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Thu, 5 Jun 2025 18:08:09 +0200 Subject: [PATCH 058/541] Update MSTestVersion to latest 3.10 preview (#5699) --- Directory.Packages.props | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Directory.Packages.props b/Directory.Packages.props index 33fe166766..01279aa849 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -29,8 +29,8 @@ 1.1.3-beta1.24423.1 - 3.9.0-preview.25229.4 - 1.7.0-preview.25226.1 + 3.10.0-preview.25304.2 + 1.8.0-preview.25304.2 From 37b077229e6e158e3897d575aa55b92a318d4d0e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Jare=C5=A1?= Date: Thu, 5 Jun 2025 18:52:18 +0200 Subject: [PATCH 059/541] Update SDK for colors (#5700) --- global.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/global.json b/global.json index 867bbcf5e2..43aa07af7c 100644 --- a/global.json +++ b/global.json @@ -1,6 +1,6 @@ { "tools": { - "dotnet": "10.0.100-preview.5.25269.23", + "dotnet": "10.0.100-preview.6.25304.106", "runtimes": { "dotnet": [ "3.1.32", @@ -23,7 +23,7 @@ } }, "sdk": { - "version": "10.0.100-preview.5.25269.23", + "version": "10.0.100-preview.6.25304.106", "allowPrerelease": true, "rollForward": "latestFeature" }, From 8cda3e17bbaee224623bfceb65877694f07ddd4a Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Fri, 6 Jun 2025 11:16:39 +0200 Subject: [PATCH 060/541] Ensure TestMethodAttribute.Execute is run on the correct execution context (#5688) --- MSTest.slnf | 1 + TestFx.sln | 7 +++ .../Execution/TestMethodInfo.cs | 57 +++++++------------ .../Execution/TestMethodRunner.cs | 19 ++++++- .../TestMethod/TestMethodAttribute.cs | 1 - .../MSTest.SelfRealExamples.UnitTests.csproj | 29 ++++++++++ .../Program.cs | 19 +++++++ ...tionFromTestMethodAttributeToTestMethod.cs | 30 ++++++++++ 8 files changed, 125 insertions(+), 38 deletions(-) create mode 100644 test/UnitTests/MSTest.SelfRealExamples.UnitTests/MSTest.SelfRealExamples.UnitTests.csproj create mode 100644 test/UnitTests/MSTest.SelfRealExamples.UnitTests/Program.cs create mode 100644 test/UnitTests/MSTest.SelfRealExamples.UnitTests/TestExecutionContextPropagationFromTestMethodAttributeToTestMethod.cs diff --git a/MSTest.slnf b/MSTest.slnf index 111ef185e0..80979689ba 100644 --- a/MSTest.slnf +++ b/MSTest.slnf @@ -50,6 +50,7 @@ "test\\UnitTests\\MSTest.Analyzers.UnitTests\\MSTest.Analyzers.UnitTests.csproj", "test\\UnitTests\\MSTestAdapter.PlatformServices.UnitTests\\MSTestAdapter.PlatformServices.UnitTests.csproj", "test\\UnitTests\\MSTestAdapter.UnitTests\\MSTestAdapter.UnitTests.csproj", + "test\\UnitTests\\MSTest.SelfRealExamples.UnitTests\\MSTest.SelfRealExamples.UnitTests.csproj", "test\\UnitTests\\TestFramework.UnitTests\\TestFramework.UnitTests.csproj", "test\\Utilities\\Automation.CLI\\Automation.CLI.csproj", "test\\Utilities\\Microsoft.Testing.TestInfrastructure\\Microsoft.Testing.TestInfrastructure.csproj", diff --git a/TestFx.sln b/TestFx.sln index ef5738fbb2..55c2fa31d9 100644 --- a/TestFx.sln +++ b/TestFx.sln @@ -224,6 +224,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MSTest.SourceGeneration.Uni EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.Testing.Extensions.AzureDevOpsReport", "src\Platform\Microsoft.Testing.Extensions.AzureDevOpsReport\Microsoft.Testing.Extensions.AzureDevOpsReport.csproj", "{F608D3A3-125B-CD88-1D51-8714ED142029}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MSTest.SelfRealExamples.UnitTests", "test\UnitTests\MSTest.SelfRealExamples.UnitTests\MSTest.SelfRealExamples.UnitTests.csproj", "{E5DE7057-7304-439A-94D7-D1609CC40631}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -530,6 +532,10 @@ Global {F608D3A3-125B-CD88-1D51-8714ED142029}.Debug|Any CPU.Build.0 = Debug|Any CPU {F608D3A3-125B-CD88-1D51-8714ED142029}.Release|Any CPU.ActiveCfg = Release|Any CPU {F608D3A3-125B-CD88-1D51-8714ED142029}.Release|Any CPU.Build.0 = Release|Any CPU + {E5DE7057-7304-439A-94D7-D1609CC40631}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {E5DE7057-7304-439A-94D7-D1609CC40631}.Debug|Any CPU.Build.0 = Debug|Any CPU + {E5DE7057-7304-439A-94D7-D1609CC40631}.Release|Any CPU.ActiveCfg = Release|Any CPU + {E5DE7057-7304-439A-94D7-D1609CC40631}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -622,6 +628,7 @@ Global {2C0DFAC0-5D58-D172-ECE4-CBB78AD03435} = {BB874DF1-44FE-415A-B634-A6B829107890} {E6C0466E-BE8D-C04F-149A-FD98438F1413} = {BB874DF1-44FE-415A-B634-A6B829107890} {F608D3A3-125B-CD88-1D51-8714ED142029} = {6AEE1440-FDF0-4729-8196-B24D0E333550} + {E5DE7057-7304-439A-94D7-D1609CC40631} = {BB874DF1-44FE-415A-B634-A6B829107890} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {31E0F4D5-975A-41CC-933E-545B2201FAF9} diff --git a/src/Adapter/MSTest.TestAdapter/Execution/TestMethodInfo.cs b/src/Adapter/MSTest.TestAdapter/Execution/TestMethodInfo.cs index 7429314707..e7063754f7 100644 --- a/src/Adapter/MSTest.TestAdapter/Execution/TestMethodInfo.cs +++ b/src/Adapter/MSTest.TestAdapter/Execution/TestMethodInfo.cs @@ -155,50 +155,35 @@ public virtual async Task InvokeAsync(object?[]? arguments) LogMessageListener? listener = null; watch.Start(); - ExecutionContext? executionContext = Parent.ExecutionContext ?? Parent.Parent.ExecutionContext; - - var tcs = new TaskCompletionSource(); + try + { + ThreadSafeStringWriter.CleanState(); + listener = new LogMessageListener(MSTestSettings.CurrentSettings.CaptureDebugTraces); -#pragma warning disable VSTHRD101 // Avoid unsupported async delegates - ExecutionContextHelpers.RunOnContext(executionContext, async () => + result = IsTimeoutSet + ? await ExecuteInternalWithTimeoutAsync(arguments) + : await ExecuteInternalAsync(arguments, null); + } + finally { - try - { - ThreadSafeStringWriter.CleanState(); - listener = new LogMessageListener(MSTestSettings.CurrentSettings.CaptureDebugTraces); + // Handle logs & debug traces. + watch.Stop(); - result = IsTimeoutSet - ? await ExecuteInternalWithTimeoutAsync(arguments) - : await ExecuteInternalAsync(arguments, null); - tcs.SetResult(null); - } - catch (Exception e) + if (result != null) { - tcs.SetException(e); - } - finally - { - // Handle logs & debug traces. - watch.Stop(); - - if (result != null) + result.Duration = watch.Elapsed; + if (listener is not null) { - result.Duration = watch.Elapsed; - if (listener is not null) - { - result.DebugTrace = listener.GetAndClearDebugTrace(); - result.LogOutput = listener.GetAndClearStandardOutput(); - result.LogError = listener.GetAndClearStandardError(); - result.TestContextMessages = TestContext?.GetAndClearDiagnosticMessages(); - result.ResultFiles = TestContext?.GetResultFiles(); - listener.Dispose(); - } + result.DebugTrace = listener.GetAndClearDebugTrace(); + result.LogOutput = listener.GetAndClearStandardOutput(); + result.LogError = listener.GetAndClearStandardError(); + result.TestContextMessages = TestContext?.GetAndClearDiagnosticMessages(); + result.ResultFiles = TestContext?.GetResultFiles(); + listener.Dispose(); } } - }); -#pragma warning restore VSTHRD101 // Avoid unsupported async delegates + } - await tcs.Task; return result!; } diff --git a/src/Adapter/MSTest.TestAdapter/Execution/TestMethodRunner.cs b/src/Adapter/MSTest.TestAdapter/Execution/TestMethodRunner.cs index 1d04d00e3f..8d770d8460 100644 --- a/src/Adapter/MSTest.TestAdapter/Execution/TestMethodRunner.cs +++ b/src/Adapter/MSTest.TestAdapter/Execution/TestMethodRunner.cs @@ -458,7 +458,24 @@ private async Task ExecuteTestAsync(TestMethodInfo testMethodInfo) { try { - return await _testMethodInfo.Executor.ExecuteAsync(testMethodInfo); + var tcs = new TaskCompletionSource(); + +#pragma warning disable VSTHRD101 // Avoid unsupported async delegates + ExecutionContextHelpers.RunOnContext( + testMethodInfo.Parent.ExecutionContext ?? testMethodInfo.Parent.Parent.ExecutionContext, + async () => + { + try + { + tcs.SetResult(await _testMethodInfo.Executor.ExecuteAsync(testMethodInfo)); + } + catch (Exception e) + { + tcs.SetException(e); + } + }); +#pragma warning restore VSTHRD101 // Avoid unsupported async delegates + return await tcs.Task; } catch (Exception ex) { diff --git a/src/TestFramework/TestFramework/Attributes/TestMethod/TestMethodAttribute.cs b/src/TestFramework/TestFramework/Attributes/TestMethod/TestMethodAttribute.cs index 75f7455b3b..6baf8e78fa 100644 --- a/src/TestFramework/TestFramework/Attributes/TestMethod/TestMethodAttribute.cs +++ b/src/TestFramework/TestFramework/Attributes/TestMethod/TestMethodAttribute.cs @@ -67,7 +67,6 @@ public TestMethodAttribute(string? displayName) /// The test method to execute. /// An array of TestResult objects that represent the outcome(s) of the test. /// Extensions can override this method to customize running a TestMethod. - // TODO: Double check whether this breaks async local propagation between test init, test, test cleanup internal virtual async Task ExecuteAsync(ITestMethod testMethod) => UseAsync ? [await testMethod.InvokeAsync(null)] diff --git a/test/UnitTests/MSTest.SelfRealExamples.UnitTests/MSTest.SelfRealExamples.UnitTests.csproj b/test/UnitTests/MSTest.SelfRealExamples.UnitTests/MSTest.SelfRealExamples.UnitTests.csproj new file mode 100644 index 0000000000..f8e01b977b --- /dev/null +++ b/test/UnitTests/MSTest.SelfRealExamples.UnitTests/MSTest.SelfRealExamples.UnitTests.csproj @@ -0,0 +1,29 @@ + + + + Exe + net472;net9.0 + enable + Exe + true + + + + + + + + + + + + + + + + + + + + + diff --git a/test/UnitTests/MSTest.SelfRealExamples.UnitTests/Program.cs b/test/UnitTests/MSTest.SelfRealExamples.UnitTests/Program.cs new file mode 100644 index 0000000000..904b1066e1 --- /dev/null +++ b/test/UnitTests/MSTest.SelfRealExamples.UnitTests/Program.cs @@ -0,0 +1,19 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using Microsoft.Testing.Extensions; +using Microsoft.Testing.Platform.Builder; + +using Microsoft.VisualStudio.TestTools.UnitTesting; + +[assembly: Parallelize(Scope = Microsoft.VisualStudio.TestTools.UnitTesting.ExecutionScope.ClassLevel, Workers = 0)] + +ITestApplicationBuilder testApplicationBuilder = await TestApplication.CreateBuilderAsync(args); + +testApplicationBuilder.AddMSTest(() => [Assembly.GetEntryAssembly()!]); +testApplicationBuilder.AddTrxReportProvider(); +testApplicationBuilder.AddAppInsightsTelemetryProvider(); +testApplicationBuilder.AddCodeCoverageProvider(); +testApplicationBuilder.AddAzureDevOpsProvider(); +using ITestApplication testApplication = await testApplicationBuilder.BuildAsync(); +return await testApplication.RunAsync(); diff --git a/test/UnitTests/MSTest.SelfRealExamples.UnitTests/TestExecutionContextPropagationFromTestMethodAttributeToTestMethod.cs b/test/UnitTests/MSTest.SelfRealExamples.UnitTests/TestExecutionContextPropagationFromTestMethodAttributeToTestMethod.cs new file mode 100644 index 0000000000..274c3c5524 --- /dev/null +++ b/test/UnitTests/MSTest.SelfRealExamples.UnitTests/TestExecutionContextPropagationFromTestMethodAttributeToTestMethod.cs @@ -0,0 +1,30 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace MSTest.SelfRealExamples.UnitTests; + +[TestClass] +public sealed class TestExecutionContextPropagationFromTestMethodAttributeToTestMethod +{ + private static readonly AsyncLocal State = new(); + + [ClassInitialize] + public static void ClassInitialize(TestContext testContext) + { + } + + [MyTestMethod] + public void TestAsyncLocalValueIsPreserved() + => Assert.AreEqual("In Execute", State.Value); + + private sealed class MyTestMethodAttribute : TestMethodAttribute + { + public override TestResult[] Execute(ITestMethod testMethod) + { + State.Value = "In Execute"; + return base.Execute(testMethod); + } + } +} From 1421741993d32b68741c65770b47a7295c5dece3 Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Fri, 6 Jun 2025 09:30:38 +0000 Subject: [PATCH 061/541] [main] Update dependencies from dotnet/arcade (#5701) [main] Update dependencies from dotnet/arcade --- eng/Version.Details.xml | 12 ++++++------ eng/Versions.props | 2 +- global.json | 2 +- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index b9ecb36f6c..f7bbf6249c 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -1,17 +1,17 @@ - + https://github.com/dotnet/arcade - d3a9e0bf843815be1a2b30895e2060ef73735772 + aba421eb78276b26d1a24df7772474806b27aa13 - + https://github.com/dotnet/arcade - d3a9e0bf843815be1a2b30895e2060ef73735772 + aba421eb78276b26d1a24df7772474806b27aa13 - + https://github.com/dotnet/arcade - d3a9e0bf843815be1a2b30895e2060ef73735772 + aba421eb78276b26d1a24df7772474806b27aa13 https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage diff --git a/eng/Versions.props b/eng/Versions.props index d3e76836f4..1726ec8930 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -7,7 +7,7 @@ preview - 10.0.0-beta.25304.5 + 10.0.0-beta.25305.3 17.15.0-preview.25304.1 diff --git a/global.json b/global.json index 43aa07af7c..2b3d333208 100644 --- a/global.json +++ b/global.json @@ -28,7 +28,7 @@ "rollForward": "latestFeature" }, "msbuild-sdks": { - "Microsoft.DotNet.Arcade.Sdk": "10.0.0-beta.25304.5", + "Microsoft.DotNet.Arcade.Sdk": "10.0.0-beta.25305.3", "MSBuild.Sdk.Extras": "3.0.44" } } From 45dec3b577fbf56de1a7f390b78d0ad0abf95906 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Mon, 9 Jun 2025 10:23:08 +0200 Subject: [PATCH 062/541] Avoid loading System.Threading.Tasks.Extensions when not needed (#5694) --- .../Execution/TestMethodInfo.cs | 20 +++------ .../Extensions/MethodInfoExtensions.cs | 43 ++++++++++++------- 2 files changed, 34 insertions(+), 29 deletions(-) diff --git a/src/Adapter/MSTest.TestAdapter/Execution/TestMethodInfo.cs b/src/Adapter/MSTest.TestAdapter/Execution/TestMethodInfo.cs index e7063754f7..afb0e28c10 100644 --- a/src/Adapter/MSTest.TestAdapter/Execution/TestMethodInfo.cs +++ b/src/Adapter/MSTest.TestAdapter/Execution/TestMethodInfo.cs @@ -417,14 +417,10 @@ private async Task ExecuteInternalAsync(object?[]? arguments, Cancel if (executionContext is null) { - object? invokeResult = TestMethod.GetInvokeResult(_classInstance, arguments); - if (invokeResult is Task task) + Task? invokeResult = TestMethod.GetInvokeResultAsync(_classInstance, arguments); + if (invokeResult is not null) { - await task; - } - else if (invokeResult is ValueTask valueTask) - { - await valueTask; + await invokeResult; } } else @@ -436,14 +432,10 @@ private async Task ExecuteInternalAsync(object?[]? arguments, Cancel { try { - object? invokeResult = TestMethod.GetInvokeResult(_classInstance, arguments); - if (invokeResult is Task task) - { - await task; - } - else if (invokeResult is ValueTask valueTask) + Task? invokeResult = TestMethod.GetInvokeResultAsync(_classInstance, arguments); + if (invokeResult is not null) { - await valueTask; + await invokeResult; } } catch (Exception e) diff --git a/src/Adapter/MSTest.TestAdapter/Extensions/MethodInfoExtensions.cs b/src/Adapter/MSTest.TestAdapter/Extensions/MethodInfoExtensions.cs index 69b9818219..b34dab9522 100644 --- a/src/Adapter/MSTest.TestAdapter/Extensions/MethodInfoExtensions.cs +++ b/src/Adapter/MSTest.TestAdapter/Extensions/MethodInfoExtensions.cs @@ -91,8 +91,17 @@ internal static bool HasCorrectTestMethodSignature(this MethodInfo method, bool /// True if the method has a void/task return type.. internal static bool IsValidReturnType(this MethodInfo method, ReflectHelper? reflectHelper = null) => ReflectHelper.MatchReturnType(method, typeof(Task)) - || ReflectHelper.MatchReturnType(method, typeof(ValueTask)) - || (ReflectHelper.MatchReturnType(method, typeof(void)) && method.GetAsyncTypeName(reflectHelper) == null); + || (ReflectHelper.MatchReturnType(method, typeof(void)) && method.GetAsyncTypeName(reflectHelper) == null) + // Keep this the last check, as it avoids loading System.Threading.Tasks.Extensions unnecessarily. + || method.IsValueTask(); + + // Avoid loading System.Threading.Tasks.Extensions if not needed. + // Note: .NET runtime will load all types once it's entering the method. + // So, moving this out of the method will load System.Threading.Tasks.Extensions + // Even when invokeResult is null or Task. + [MethodImpl(MethodImplOptions.NoInlining)] + private static bool IsValueTask(this MethodInfo method) + => ReflectHelper.MatchReturnType(method, typeof(ValueTask)); /// /// For async methods compiler generates different type and method. @@ -107,7 +116,7 @@ internal static bool IsValidReturnType(this MethodInfo method, ReflectHelper? re return asyncStateMachineAttribute?.StateMachineType?.FullName; } - internal static object? GetInvokeResult(this MethodInfo methodInfo, object? classInstance, params object?[]? arguments) + internal static Task? GetInvokeResultAsync(this MethodInfo methodInfo, object? classInstance, params object?[]? arguments) { ParameterInfo[]? methodParameters = methodInfo.GetParameters(); @@ -172,9 +181,22 @@ internal static bool IsValidReturnType(this MethodInfo method, ReflectHelper? re } } - return invokeResult; + return invokeResult switch + { + null => null, + Task t => t, + _ => TryGetTaskFromValueTaskAsync(invokeResult), + }; } + // Avoid loading System.Threading.Tasks.Extensions if not needed. + // Note: .NET runtime will load all types once it's entering the method. + // So, moving this out of the method will load System.Threading.Tasks.Extensions + // Even when invokeResult is null or Task. + [MethodImpl(MethodImplOptions.NoInlining)] + private static Task? TryGetTaskFromValueTaskAsync(object invokeResult) + => (invokeResult as ValueTask?)?.AsTask(); + /// /// Invoke a as a synchronous . /// @@ -189,17 +211,8 @@ internal static bool IsValidReturnType(this MethodInfo method, ReflectHelper? re /// internal static void InvokeAsSynchronousTask(this MethodInfo methodInfo, object? classInstance, params object?[]? arguments) { - object? invokeResult = methodInfo.GetInvokeResult(classInstance, arguments); - - // If methodInfo is an async method, wait for returned task - if (invokeResult is Task task) - { - task.GetAwaiter().GetResult(); - } - else if (invokeResult is ValueTask valueTask) - { - valueTask.GetAwaiter().GetResult(); - } + Task? invokeResult = methodInfo.GetInvokeResultAsync(classInstance, arguments); + invokeResult?.GetAwaiter().GetResult(); } private static void InferGenerics(Type parameterType, Type argumentType, List<(Type ParameterType, Type Substitution)> result) From 97ee44f70fc8153317e5405a400592765d89c93e Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Mon, 9 Jun 2025 13:44:43 +0200 Subject: [PATCH 063/541] Delete dead code in ExceptionHelper (#5704) --- .../Execution/ExceptionHelper.cs | 18 ++---------------- .../Extensions/ExceptionExtensions.cs | 2 +- 2 files changed, 3 insertions(+), 17 deletions(-) diff --git a/src/Adapter/MSTest.TestAdapter/Execution/ExceptionHelper.cs b/src/Adapter/MSTest.TestAdapter/Execution/ExceptionHelper.cs index f4820a5be7..eecbd05a4e 100644 --- a/src/Adapter/MSTest.TestAdapter/Execution/ExceptionHelper.cs +++ b/src/Adapter/MSTest.TestAdapter/Execution/ExceptionHelper.cs @@ -83,7 +83,7 @@ internal static class ExceptionHelper first = false; } - return CreateStackTraceInformation(ex, true, result.ToString()); + return CreateStackTraceInformation(result.ToString()); } /// @@ -173,28 +173,14 @@ internal static string GetFormattedExceptionMessage(this Exception ex) /// /// Create stack trace information. /// - /// - /// The exception. - /// - /// - /// Whether the inner exception needs to be checked too. - /// /// /// The stack Trace String. /// /// /// The . /// - internal static StackTraceInformation? CreateStackTraceInformation( - Exception ex, - bool checkInnerExceptions, - string stackTraceString) + internal static StackTraceInformation? CreateStackTraceInformation(string stackTraceString) { - if (checkInnerExceptions && ex.InnerException != null) - { - return CreateStackTraceInformation(ex.InnerException, checkInnerExceptions, stackTraceString); - } - string stackTrace = TrimStackTrace(stackTraceString); return !StringEx.IsNullOrEmpty(stackTrace) ? new StackTraceInformation(stackTrace, null, 0, 0) : null; diff --git a/src/Adapter/MSTest.TestAdapter/Extensions/ExceptionExtensions.cs b/src/Adapter/MSTest.TestAdapter/Extensions/ExceptionExtensions.cs index 648fbc41db..c2a398faeb 100644 --- a/src/Adapter/MSTest.TestAdapter/Extensions/ExceptionExtensions.cs +++ b/src/Adapter/MSTest.TestAdapter/Extensions/ExceptionExtensions.cs @@ -54,7 +54,7 @@ internal static string TryGetMessage(this Exception? exception) /// An instance. /// StackTraceInformation for the exception. internal static StackTraceInformation? TryGetStackTraceInformation(this Exception exception) => !StringEx.IsNullOrEmpty(exception.StackTrace) - ? ExceptionHelper.CreateStackTraceInformation(exception, false, exception.StackTrace) + ? ExceptionHelper.CreateStackTraceInformation(exception.StackTrace) : null; /// From 1f90e42e92aed5277fc264e520d0c32d042a6b29 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Mon, 9 Jun 2025 23:48:41 +0200 Subject: [PATCH 064/541] Remove dead code in TestMethodInfo (#5718) --- src/Adapter/MSTest.TestAdapter/Execution/TestMethodInfo.cs | 4 ---- 1 file changed, 4 deletions(-) diff --git a/src/Adapter/MSTest.TestAdapter/Execution/TestMethodInfo.cs b/src/Adapter/MSTest.TestAdapter/Execution/TestMethodInfo.cs index afb0e28c10..2be31c1b9b 100644 --- a/src/Adapter/MSTest.TestAdapter/Execution/TestMethodInfo.cs +++ b/src/Adapter/MSTest.TestAdapter/Execution/TestMethodInfo.cs @@ -1103,10 +1103,6 @@ private async Task ExecuteInternalWithTimeoutAsync(object?[]? argume } DebugEx.Assert(result is not null, "result is not null"); - - // It's possible that some failures happened and that the cleanup wasn't executed, so we need to run it here. - // The method already checks if the cleanup was already executed. - RunTestCleanupMethod(result, executionContext, null); return result; } From b26a6209079bbb22f6d04be5cc31e285156a9d99 Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Tue, 10 Jun 2025 03:08:46 +0000 Subject: [PATCH 065/541] [main] Update dependencies from dotnet/arcade (#5720) [main] Update dependencies from dotnet/arcade --- eng/Version.Details.xml | 12 ++++++------ eng/Versions.props | 2 +- .../steps/source-index-stage1-publish.yml | 6 +++--- global.json | 2 +- 4 files changed, 11 insertions(+), 11 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index f7bbf6249c..42f087dac4 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -1,17 +1,17 @@ - + https://github.com/dotnet/arcade - aba421eb78276b26d1a24df7772474806b27aa13 + add492db56ebc80df604ba5a30723beef14ed3dd - + https://github.com/dotnet/arcade - aba421eb78276b26d1a24df7772474806b27aa13 + add492db56ebc80df604ba5a30723beef14ed3dd - + https://github.com/dotnet/arcade - aba421eb78276b26d1a24df7772474806b27aa13 + add492db56ebc80df604ba5a30723beef14ed3dd https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage diff --git a/eng/Versions.props b/eng/Versions.props index 1726ec8930..3be3b98ff5 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -7,7 +7,7 @@ preview - 10.0.0-beta.25305.3 + 10.0.0-beta.25309.2 17.15.0-preview.25304.1 diff --git a/eng/common/core-templates/steps/source-index-stage1-publish.yml b/eng/common/core-templates/steps/source-index-stage1-publish.yml index 99c2326fc1..c2917c1efc 100644 --- a/eng/common/core-templates/steps/source-index-stage1-publish.yml +++ b/eng/common/core-templates/steps/source-index-stage1-publish.yml @@ -1,15 +1,15 @@ parameters: sourceIndexUploadPackageVersion: 2.0.0-20250425.2 - sourceIndexProcessBinlogPackageVersion: 1.0.1-20250425.2 + sourceIndexProcessBinlogPackageVersion: 1.0.1-20250515.1 sourceIndexPackageSource: https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-tools/nuget/v3/index.json binlogPath: artifacts/log/Debug/Build.binlog steps: - task: UseDotNet@2 - displayName: "Source Index: Use .NET 8 SDK" + displayName: "Source Index: Use .NET 9 SDK" inputs: packageType: sdk - version: 8.0.x + version: 9.0.x installationPath: $(Agent.TempDirectory)/dotnet workingDirectory: $(Agent.TempDirectory) diff --git a/global.json b/global.json index 2b3d333208..f17cdf892a 100644 --- a/global.json +++ b/global.json @@ -28,7 +28,7 @@ "rollForward": "latestFeature" }, "msbuild-sdks": { - "Microsoft.DotNet.Arcade.Sdk": "10.0.0-beta.25305.3", + "Microsoft.DotNet.Arcade.Sdk": "10.0.0-beta.25309.2", "MSBuild.Sdk.Extras": "3.0.44" } } From 881ccf317588a0d3c81463092dcabe753a6598b4 Mon Sep 17 00:00:00 2001 From: Copilot <198982749+Copilot@users.noreply.github.com> Date: Tue, 10 Jun 2025 09:51:40 +0200 Subject: [PATCH 066/541] Fix UseAsync property in TestMethodAttribute derived classes to use type checks (#5708) Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: Youssef1313 <31348972+Youssef1313@users.noreply.github.com> --- .../Attributes/UWP_UITestMethodAttribute.cs | 2 +- .../Attributes/WinUI_UITestMethodAttribute.cs | 2 +- .../Attributes/DataSource/DataTestMethodAttribute.cs | 2 +- .../Attributes/TestMethod/STATestMethodAttribute.cs | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/TestFramework/TestFramework.Extensions/Attributes/UWP_UITestMethodAttribute.cs b/src/TestFramework/TestFramework.Extensions/Attributes/UWP_UITestMethodAttribute.cs index 6be0c1acea..ab0577b601 100644 --- a/src/TestFramework/TestFramework.Extensions/Attributes/UWP_UITestMethodAttribute.cs +++ b/src/TestFramework/TestFramework.Extensions/Attributes/UWP_UITestMethodAttribute.cs @@ -10,7 +10,7 @@ namespace Microsoft.VisualStudio.TestTools.UnitTesting.AppContainer; /// public class UITestMethodAttribute : TestMethodAttribute { - private protected override bool UseAsync => true; + private protected override bool UseAsync => GetType() == typeof(UITestMethodAttribute); /// public override TestResult[] Execute(ITestMethod testMethod) => base.Execute(testMethod); diff --git a/src/TestFramework/TestFramework.Extensions/Attributes/WinUI_UITestMethodAttribute.cs b/src/TestFramework/TestFramework.Extensions/Attributes/WinUI_UITestMethodAttribute.cs index 37f81c56dc..acec6a45d9 100644 --- a/src/TestFramework/TestFramework.Extensions/Attributes/WinUI_UITestMethodAttribute.cs +++ b/src/TestFramework/TestFramework.Extensions/Attributes/WinUI_UITestMethodAttribute.cs @@ -34,7 +34,7 @@ public UITestMethodAttribute(string displayName) { } - private protected override bool UseAsync => true; + private protected override bool UseAsync => GetType() == typeof(UITestMethodAttribute); /// /// Gets or sets the that should be used to invoke the UITestMethodAttribute. diff --git a/src/TestFramework/TestFramework/Attributes/DataSource/DataTestMethodAttribute.cs b/src/TestFramework/TestFramework/Attributes/DataSource/DataTestMethodAttribute.cs index ed2e10f86f..d93c2161ee 100644 --- a/src/TestFramework/TestFramework/Attributes/DataSource/DataTestMethodAttribute.cs +++ b/src/TestFramework/TestFramework/Attributes/DataSource/DataTestMethodAttribute.cs @@ -13,7 +13,7 @@ namespace Microsoft.VisualStudio.TestTools.UnitTesting; [EditorBrowsable(EditorBrowsableState.Never)] public class DataTestMethodAttribute : TestMethodAttribute { - private protected override bool UseAsync => true; + private protected override bool UseAsync => GetType() == typeof(DataTestMethodAttribute); /// /// Initializes a new instance of the class. diff --git a/src/TestFramework/TestFramework/Attributes/TestMethod/STATestMethodAttribute.cs b/src/TestFramework/TestFramework/Attributes/TestMethod/STATestMethodAttribute.cs index a0cecc24aa..3f317a3eac 100644 --- a/src/TestFramework/TestFramework/Attributes/TestMethod/STATestMethodAttribute.cs +++ b/src/TestFramework/TestFramework/Attributes/TestMethod/STATestMethodAttribute.cs @@ -9,7 +9,7 @@ namespace Microsoft.VisualStudio.TestTools.UnitTesting; [AttributeUsage(AttributeTargets.Method)] public class STATestMethodAttribute : TestMethodAttribute { - private protected override bool UseAsync => true; + private protected override bool UseAsync => GetType() == typeof(STATestMethodAttribute); /// /// Initializes a new instance of the class. From db8f1061830e6420e04caeecb5601ebbb61bcae8 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Tue, 10 Jun 2025 10:32:27 +0200 Subject: [PATCH 067/541] Fix UnitTestRunner leaking some test class instances (#5715) --- .../Execution/UnitTestRunner.cs | 45 +++++++++---------- 1 file changed, 21 insertions(+), 24 deletions(-) diff --git a/src/Adapter/MSTest.TestAdapter/Execution/UnitTestRunner.cs b/src/Adapter/MSTest.TestAdapter/Execution/UnitTestRunner.cs index 873252874d..03093d24b9 100644 --- a/src/Adapter/MSTest.TestAdapter/Execution/UnitTestRunner.cs +++ b/src/Adapter/MSTest.TestAdapter/Execution/UnitTestRunner.cs @@ -22,7 +22,8 @@ namespace Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution; /// internal sealed class UnitTestRunner : MarshalByRefObject { - private readonly ConcurrentDictionary _fixtureTests = new(); + private readonly ConcurrentDictionary _assemblyFixtureTests = new(); + private readonly ConcurrentDictionary _classFixtureTests = new(); private readonly TypeCache _typeCache; private readonly ReflectHelper _reflectHelper; private readonly ClassCleanupManager _classCleanupManager; @@ -92,33 +93,29 @@ internal FixtureTestResult GetFixtureTestResult(TestMethod testMethod, string fi { // For the fixture methods, we need to return the appropriate result. // Get matching testMethodInfo from the cache and return UnitTestOutcome for the fixture test. - if (_fixtureTests.TryGetValue(testMethod.AssemblyName + testMethod.FullClassName, out TestMethodInfo? testMethodInfo)) + if (fixtureType is Constants.ClassInitializeFixtureTrait or Constants.ClassCleanupFixtureTrait && + _classFixtureTests.TryGetValue(testMethod.AssemblyName + testMethod.FullClassName, out TestClassInfo? testClassInfo)) { - if (fixtureType == Constants.ClassInitializeFixtureTrait) + UnitTestOutcome outcome = fixtureType switch { - return testMethodInfo.Parent.IsClassInitializeExecuted - ? new(true, GetOutcome(testMethodInfo.Parent.ClassInitializationException)) - : new(true, UnitTestOutcome.Inconclusive); - } + Constants.ClassInitializeFixtureTrait => testClassInfo.IsClassInitializeExecuted ? GetOutcome(testClassInfo.ClassInitializationException) : UnitTestOutcome.Inconclusive, + Constants.ClassCleanupFixtureTrait => testClassInfo.IsClassCleanupExecuted ? GetOutcome(testClassInfo.ClassCleanupException) : UnitTestOutcome.Inconclusive, + _ => throw ApplicationStateGuard.Unreachable(), + }; - if (fixtureType == Constants.ClassCleanupFixtureTrait) - { - return testMethodInfo.Parent.IsClassInitializeExecuted - ? new(true, GetOutcome(testMethodInfo.Parent.ClassCleanupException)) - : new(true, UnitTestOutcome.Inconclusive); - } + return new FixtureTestResult(true, outcome); } - - if (_fixtureTests.TryGetValue(testMethod.AssemblyName, out testMethodInfo)) + else if (fixtureType is Constants.AssemblyInitializeFixtureTrait or Constants.AssemblyCleanupFixtureTrait && + _assemblyFixtureTests.TryGetValue(testMethod.AssemblyName, out TestAssemblyInfo? testAssemblyInfo)) { - if (fixtureType == Constants.AssemblyInitializeFixtureTrait) + Exception? exception = fixtureType switch { - return new(true, GetOutcome(testMethodInfo.Parent.Parent.AssemblyInitializationException)); - } - else if (fixtureType == Constants.AssemblyCleanupFixtureTrait) - { - return new(true, GetOutcome(testMethodInfo.Parent.Parent.AssemblyCleanupException)); - } + Constants.AssemblyInitializeFixtureTrait => testAssemblyInfo.AssemblyInitializationException, + Constants.AssemblyCleanupFixtureTrait => testAssemblyInfo.AssemblyCleanupException, + _ => throw ApplicationStateGuard.Unreachable(), + }; + + return new(true, GetOutcome(exception)); } return new(false, UnitTestOutcome.Inconclusive); @@ -165,8 +162,8 @@ internal async Task RunSingleTestAsync(TestMethod testMethod, IDic DebugEx.Assert(testMethodInfo is not null, "testMethodInfo should not be null."); // Keep track of all non-runnable methods so that we can return the appropriate result at the end. - _fixtureTests.TryAdd(testMethod.AssemblyName, testMethodInfo); - _fixtureTests.TryAdd(testMethod.AssemblyName + testMethod.FullClassName, testMethodInfo); + _assemblyFixtureTests.TryAdd(testMethod.AssemblyName, testMethodInfo.Parent.Parent); + _classFixtureTests.TryAdd(testMethod.AssemblyName + testMethod.FullClassName, testMethodInfo.Parent); ITestContext testContextForAssemblyInit = PlatformServiceProvider.Instance.GetTestContext(testMethod, writer, properties, messageLogger, testContextForTestExecution.Context.CurrentTestOutcome); From 2497a404f166bc93a06c6f49081396e53be7573c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Jare=C5=A1?= Date: Tue, 10 Jun 2025 15:29:26 +0200 Subject: [PATCH 068/541] Update global.json for colors (#5723) --- global.json | 4 ++-- .../MSTest.TestAdapter/Execution/LogMessageListener.cs | 2 ++ .../Microsoft.Testing.Extensions.TrxReport/TrxReportEngine.cs | 2 +- .../TestFramework/Attributes/TestMethod/RetryAttribute.cs | 2 ++ .../TestFramework/Exceptions/AssertFailedException.cs | 2 +- .../TestFramework/Exceptions/AssertInconclusiveException.cs | 2 +- .../TestFramework/Exceptions/InternalTestFailureException.cs | 2 +- .../TestFramework/Exceptions/UnitTestAssertException.cs | 2 +- src/TestFramework/TestFramework/Internal/DebugEx.cs | 2 ++ src/TestFramework/TestFramework/TestDataRow.cs | 4 +++- 10 files changed, 16 insertions(+), 8 deletions(-) diff --git a/global.json b/global.json index f17cdf892a..08c258fca8 100644 --- a/global.json +++ b/global.json @@ -1,6 +1,6 @@ { "tools": { - "dotnet": "10.0.100-preview.6.25304.106", + "dotnet": "10.0.100-preview.6.25309.101", "runtimes": { "dotnet": [ "3.1.32", @@ -23,7 +23,7 @@ } }, "sdk": { - "version": "10.0.100-preview.6.25304.106", + "version": "10.0.100-preview.6.25309.101", "allowPrerelease": true, "rollForward": "latestFeature" }, diff --git a/src/Adapter/MSTest.TestAdapter/Execution/LogMessageListener.cs b/src/Adapter/MSTest.TestAdapter/Execution/LogMessageListener.cs index a3e3581682..39b3dada59 100644 --- a/src/Adapter/MSTest.TestAdapter/Execution/LogMessageListener.cs +++ b/src/Adapter/MSTest.TestAdapter/Execution/LogMessageListener.cs @@ -169,5 +169,7 @@ public void Dispose() s_listenerCount--; } + + GC.SuppressFinalize(this); } } diff --git a/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxReportEngine.cs b/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxReportEngine.cs index e58b34329c..bed4e9dc84 100644 --- a/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxReportEngine.cs +++ b/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxReportEngine.cs @@ -653,7 +653,7 @@ private static bool IsReservedFileName(string fileName) => // LPT1, LPT2, LPT3, LPT4, LPT5, LPT6, LPT7, LPT8, and LPT9. // Also avoid these names followed by an extension, for example, NUL.tx7. // Windows NT: CLOCK$ is also a reserved device name. - ReservedFileNamesRegex.Match(fileName).Success; + ReservedFileNamesRegex.IsMatch(fileName); private static Guid GuidFromString(string data) { diff --git a/src/TestFramework/TestFramework/Attributes/TestMethod/RetryAttribute.cs b/src/TestFramework/TestFramework/Attributes/TestMethod/RetryAttribute.cs index 0ee55befc5..3cc9868be5 100644 --- a/src/TestFramework/TestFramework/Attributes/TestMethod/RetryAttribute.cs +++ b/src/TestFramework/TestFramework/Attributes/TestMethod/RetryAttribute.cs @@ -15,10 +15,12 @@ public sealed class RetryAttribute : RetryBaseAttribute /// The maximum number of retry attempts. This must be greater than or equal to 1. public RetryAttribute(int maxRetryAttempts) { +#pragma warning disable CA1512 // Use ArgumentOutOfRangeException throw helper if (maxRetryAttempts < 1) { throw new ArgumentOutOfRangeException(nameof(maxRetryAttempts)); } +#pragma warning disable CA1512 // Use ArgumentOutOfRangeException throw helper MaxRetryAttempts = maxRetryAttempts; } diff --git a/src/TestFramework/TestFramework/Exceptions/AssertFailedException.cs b/src/TestFramework/TestFramework/Exceptions/AssertFailedException.cs index bff933dbd6..2bbd14c132 100644 --- a/src/TestFramework/TestFramework/Exceptions/AssertFailedException.cs +++ b/src/TestFramework/TestFramework/Exceptions/AssertFailedException.cs @@ -45,7 +45,7 @@ public AssertFailedException() /// Serialization info. /// Streaming context. #if NET8_0_OR_GREATER - [Obsolete(DiagnosticId = "SYSLIB0051")] + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] #endif [EditorBrowsable(EditorBrowsableState.Never)] protected AssertFailedException(SerializationInfo info, StreamingContext context) diff --git a/src/TestFramework/TestFramework/Exceptions/AssertInconclusiveException.cs b/src/TestFramework/TestFramework/Exceptions/AssertInconclusiveException.cs index b6734d5e38..277ce83509 100644 --- a/src/TestFramework/TestFramework/Exceptions/AssertInconclusiveException.cs +++ b/src/TestFramework/TestFramework/Exceptions/AssertInconclusiveException.cs @@ -45,7 +45,7 @@ public AssertInconclusiveException() /// Serialization info. /// Streaming context. #if NET8_0_OR_GREATER - [Obsolete(DiagnosticId = "SYSLIB0051")] + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] #endif [EditorBrowsable(EditorBrowsableState.Never)] protected AssertInconclusiveException(SerializationInfo info, StreamingContext context) diff --git a/src/TestFramework/TestFramework/Exceptions/InternalTestFailureException.cs b/src/TestFramework/TestFramework/Exceptions/InternalTestFailureException.cs index 78f3de327f..32cb00ab8f 100644 --- a/src/TestFramework/TestFramework/Exceptions/InternalTestFailureException.cs +++ b/src/TestFramework/TestFramework/Exceptions/InternalTestFailureException.cs @@ -54,7 +54,7 @@ public InternalTestFailureException() /// Serialization info. /// Streaming context. #if NET8_0_OR_GREATER - [Obsolete(DiagnosticId = "SYSLIB0051")] + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] #endif [EditorBrowsable(EditorBrowsableState.Never)] protected InternalTestFailureException(SerializationInfo info, StreamingContext context) diff --git a/src/TestFramework/TestFramework/Exceptions/UnitTestAssertException.cs b/src/TestFramework/TestFramework/Exceptions/UnitTestAssertException.cs index 37e2a86510..85978e9597 100644 --- a/src/TestFramework/TestFramework/Exceptions/UnitTestAssertException.cs +++ b/src/TestFramework/TestFramework/Exceptions/UnitTestAssertException.cs @@ -44,7 +44,7 @@ protected UnitTestAssertException(string msg) /// Serialization info. /// Streaming context. #if NET8_0_OR_GREATER - [Obsolete(DiagnosticId = "SYSLIB0051")] + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] #endif [EditorBrowsable(EditorBrowsableState.Never)] protected UnitTestAssertException(SerializationInfo info, StreamingContext context) diff --git a/src/TestFramework/TestFramework/Internal/DebugEx.cs b/src/TestFramework/TestFramework/Internal/DebugEx.cs index 77b9d8fd02..9fdce6f146 100644 --- a/src/TestFramework/TestFramework/Internal/DebugEx.cs +++ b/src/TestFramework/TestFramework/Internal/DebugEx.cs @@ -17,7 +17,9 @@ public static void Assert([DoesNotReturnIf(false)] bool b, string message) // ends up causing the job to timeout. We use FailFast instead. // FailFast is better than throwing an exception to avoid anyone // catching an exception and masking an assert failure. +#pragma warning disable CA2201 // Do not raise reserved exception types var ex = new Exception($"Debug.Assert failed: {message}"); +#pragma warning restore CA2201 // Do not raise reserved exception types Environment.FailFast(ex.Message, ex); } } diff --git a/src/TestFramework/TestFramework/TestDataRow.cs b/src/TestFramework/TestFramework/TestDataRow.cs index bd271d9c69..c8865a3806 100644 --- a/src/TestFramework/TestFramework/TestDataRow.cs +++ b/src/TestFramework/TestFramework/TestDataRow.cs @@ -13,11 +13,13 @@ namespace Microsoft.VisualStudio.TestTools.UnitTesting; [DataContract] public sealed class TestDataRow : ITestDataRow { +#pragma warning disable CS1574 // XML comment has cref attribute that could not be resolved /// /// Initializes a new instance of the class. /// - /// The value to be held by this instance, which could be a or if the test method has more than one parameter. + /// The value to be held by this instance, which could be a or if the test method has more than one parameter. public TestDataRow(T value) +#pragma warning restore CS1574 // XML comment has cref attribute that could not be resolved => Value = value; /// From 9f028f38a5263309f9344ed328cc991fa309bf13 Mon Sep 17 00:00:00 2001 From: Copilot <198982749+Copilot@users.noreply.github.com> Date: Tue, 10 Jun 2025 17:10:27 +0200 Subject: [PATCH 069/541] Fix MTP timeout parsing to use invariant culture instead of current culture (#5705) Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: Youssef1313 <31348972+Youssef1313@users.noreply.github.com> Co-authored-by: Youssef Victor --- .../PlatformCommandLineProvider.cs | 2 +- .../Hosts/TestHostBuilder.cs | 2 +- .../PlatformCommandLineProviderTests.cs | 73 +++++++++++++++++++ 3 files changed, 75 insertions(+), 2 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Platform/CommandLine/PlatformCommandLineProvider.cs b/src/Platform/Microsoft.Testing.Platform/CommandLine/PlatformCommandLineProvider.cs index d744fdd77b..33029f8f19 100644 --- a/src/Platform/Microsoft.Testing.Platform/CommandLine/PlatformCommandLineProvider.cs +++ b/src/Platform/Microsoft.Testing.Platform/CommandLine/PlatformCommandLineProvider.cs @@ -111,7 +111,7 @@ public Task ValidateOptionArgumentsAsync(CommandLineOption com { string arg = arguments[0]; int size = arg.Length; - if ((char.ToLowerInvariant(arg[size - 1]) != 'h' && char.ToLowerInvariant(arg[size - 1]) != 'm' && char.ToLowerInvariant(arg[size - 1]) != 's') || !float.TryParse(arg[..(size - 1)], out float _)) + if ((char.ToLowerInvariant(arg[size - 1]) != 'h' && char.ToLowerInvariant(arg[size - 1]) != 'm' && char.ToLowerInvariant(arg[size - 1]) != 's') || !float.TryParse(arg[..(size - 1)], NumberStyles.Float, CultureInfo.InvariantCulture, out float _)) { return ValidationResult.InvalidTask(PlatformResources.PlatformCommandLineTimeoutArgumentErrorMessage); } diff --git a/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostBuilder.cs b/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostBuilder.cs index ac796585c4..bd38701961 100644 --- a/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostBuilder.cs +++ b/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostBuilder.cs @@ -255,7 +255,7 @@ public async Task BuildAsync( { string arg = args[0]; int size = arg.Length; - if (!float.TryParse(arg[..(size - 1)], out float value)) + if (!float.TryParse(arg[..(size - 1)], NumberStyles.Float, CultureInfo.InvariantCulture, out float value)) { throw ApplicationStateGuard.Unreachable(); } diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/PlatformCommandLineProviderTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/PlatformCommandLineProviderTests.cs index 4ea02fad22..f838ea4e3c 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/PlatformCommandLineProviderTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/PlatformCommandLineProviderTests.cs @@ -181,4 +181,77 @@ public async Task IsNotValid_If_ExitOnProcess_Not_Running() Assert.IsFalse(validateOptionsResult.IsValid); Assert.IsTrue(validateOptionsResult.ErrorMessage.StartsWith($"Invalid PID '{pid}'", StringComparison.OrdinalIgnoreCase)); } + + [TestMethod] + [DataRow("1.5s")] + [DataRow("2.0m")] + [DataRow("0.5h")] + [DataRow("10s")] + [DataRow("30m")] + [DataRow("1h")] + public async Task IsValid_If_Timeout_Has_CorrectFormat_InvariantCulture(string timeout) + { + var provider = new PlatformCommandLineProvider(); + CommandLineOption option = provider.GetCommandLineOptions().First(x => x.Name == PlatformCommandLineProvider.TimeoutOptionKey); + + // Save current culture + CultureInfo originalCulture = CultureInfo.CurrentCulture; + try + { + // Test with various cultures to ensure invariant parsing works + foreach (string cultureName in new[] { "en-US", "de-DE", "fr-FR" }) + { + CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo(cultureName); + ValidationResult validateOptionsResult = await provider.ValidateOptionArgumentsAsync(option, [timeout]); + Assert.IsTrue(validateOptionsResult.IsValid, $"Failed with culture {cultureName} and timeout {timeout}"); + Assert.IsTrue(string.IsNullOrEmpty(validateOptionsResult.ErrorMessage)); + } + } + finally + { + // Restore original culture + CultureInfo.CurrentCulture = originalCulture; + } + } + + [TestMethod] + [DataRow("1,5s")] // German decimal separator + [DataRow("invalid")] + [DataRow("1.5")] // Missing unit + [DataRow("abc.5s")] + public async Task IsInvalid_If_Timeout_Has_IncorrectFormat(string timeout) + { + var provider = new PlatformCommandLineProvider(); + CommandLineOption option = provider.GetCommandLineOptions().First(x => x.Name == PlatformCommandLineProvider.TimeoutOptionKey); + + ValidationResult validateOptionsResult = await provider.ValidateOptionArgumentsAsync(option, [timeout]); + Assert.IsFalse(validateOptionsResult.IsValid); + Assert.AreEqual(PlatformResources.PlatformCommandLineTimeoutArgumentErrorMessage, validateOptionsResult.ErrorMessage); + } + + [TestMethod] + public async Task Timeout_Parsing_Uses_InvariantCulture_NotCurrentCulture() + { + var provider = new PlatformCommandLineProvider(); + CommandLineOption option = provider.GetCommandLineOptions().First(x => x.Name == PlatformCommandLineProvider.TimeoutOptionKey); + + // Save current culture + CultureInfo originalCulture = CultureInfo.CurrentCulture; + try + { + // Set culture to German where decimal separator is comma + CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("de-DE"); + // This should work because we use invariant culture (period as decimal separator) + ValidationResult validResult = await provider.ValidateOptionArgumentsAsync(option, ["1.5s"]); + Assert.IsTrue(validResult.IsValid, "1.5s should be valid when using invariant culture"); + // This should fail because comma is not valid in invariant culture + ValidationResult invalidResult = await provider.ValidateOptionArgumentsAsync(option, ["1,5s"]); + Assert.IsFalse(invalidResult.IsValid, "1,5s should be invalid when using invariant culture"); + } + finally + { + // Restore original culture + CultureInfo.CurrentCulture = originalCulture; + } + } } From 86e6728cb76176de01a74482f616f20c95c3fe94 Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Wed, 11 Jun 2025 01:37:01 +1000 Subject: [PATCH 070/541] prefer specific scoped variables (#5611) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Youssef Victor Co-authored-by: Amaury Levé --- samples/Playground/DebuggerUtility.cs | 5 ++--- .../Requests/TreeNodeFilter/TreeNodeFilter.cs | 4 +--- .../Microsoft.Testing.TestInfrastructure/DebuggerUtility.cs | 5 ++--- 3 files changed, 5 insertions(+), 9 deletions(-) diff --git a/samples/Playground/DebuggerUtility.cs b/samples/Playground/DebuggerUtility.cs index 1064e1a597..83103fd2fd 100644 --- a/samples/Playground/DebuggerUtility.cs +++ b/samples/Playground/DebuggerUtility.cs @@ -149,7 +149,6 @@ private static bool AttachVs(Process vs, int pid, bool enableLog = false) if (dn.StartsWith("!VisualStudio.DTE.", StringComparison.Ordinal) && dn.EndsWith(dteSuffix, StringComparison.Ordinal)) { - object dbg, lps; runningObjectTable.GetObject(moniker[0], out object dte); // The COM object can be busy, we retry few times, hoping that it won't be busy next time. @@ -157,8 +156,8 @@ private static bool AttachVs(Process vs, int pid, bool enableLog = false) { try { - dbg = dte.GetType().InvokeMember("Debugger", BindingFlags.GetProperty, null, dte, null, CultureInfo.InvariantCulture)!; - lps = dbg.GetType().InvokeMember("LocalProcesses", BindingFlags.GetProperty, null, dbg, null, CultureInfo.InvariantCulture)!; + object dbg = dte.GetType().InvokeMember("Debugger", BindingFlags.GetProperty, null, dte, null, CultureInfo.InvariantCulture)!; + object lps = dbg.GetType().InvokeMember("LocalProcesses", BindingFlags.GetProperty, null, dbg, null, CultureInfo.InvariantCulture)!; var lpn = (System.Collections.IEnumerator)lps.GetType().InvokeMember("GetEnumerator", BindingFlags.InvokeMethod, null, lps, null, CultureInfo.InvariantCulture)!; while (lpn.MoveNext()) diff --git a/src/Platform/Microsoft.Testing.Platform/Requests/TreeNodeFilter/TreeNodeFilter.cs b/src/Platform/Microsoft.Testing.Platform/Requests/TreeNodeFilter/TreeNodeFilter.cs index f20620f964..45968ab863 100644 --- a/src/Platform/Microsoft.Testing.Platform/Requests/TreeNodeFilter/TreeNodeFilter.cs +++ b/src/Platform/Microsoft.Testing.Platform/Requests/TreeNodeFilter/TreeNodeFilter.cs @@ -262,11 +262,9 @@ static void ProcessHigherPrecedenceOperators( Stack operatorStack, OperatorKind currentOp) { - OperatorKind topStackOperator; - while (operatorStack.Count != 0 && operatorStack.Peek() > currentOp) { - topStackOperator = operatorStack.Pop(); + OperatorKind topStackOperator = operatorStack.Pop(); ProcessStackOperator(topStackOperator, expressionStack, operatorStack); break; } diff --git a/test/Utilities/Microsoft.Testing.TestInfrastructure/DebuggerUtility.cs b/test/Utilities/Microsoft.Testing.TestInfrastructure/DebuggerUtility.cs index 2a7839e498..9af5032a7c 100644 --- a/test/Utilities/Microsoft.Testing.TestInfrastructure/DebuggerUtility.cs +++ b/test/Utilities/Microsoft.Testing.TestInfrastructure/DebuggerUtility.cs @@ -125,7 +125,6 @@ private static bool AttachVs(Process vs, int pid, bool enableLog = false) if (dn.StartsWith("!VisualStudio.DTE.", StringComparison.Ordinal) && dn.EndsWith(dteSuffix, StringComparison.Ordinal)) { - object dbg, lps; runningObjectTable.GetObject(moniker[0], out object dte); // The COM object can be busy, we retry few times, hoping that it won't be busy next time. @@ -133,8 +132,8 @@ private static bool AttachVs(Process vs, int pid, bool enableLog = false) { try { - dbg = dte.GetType().InvokeMember("Debugger", BindingFlags.GetProperty, null, dte, null, CultureInfo.InvariantCulture)!; - lps = dbg.GetType().InvokeMember("LocalProcesses", BindingFlags.GetProperty, null, dbg, null, CultureInfo.InvariantCulture)!; + object dbg = dte.GetType().InvokeMember("Debugger", BindingFlags.GetProperty, null, dte, null, CultureInfo.InvariantCulture)!; + object lps = dbg.GetType().InvokeMember("LocalProcesses", BindingFlags.GetProperty, null, dbg, null, CultureInfo.InvariantCulture)!; var lpn = (System.Collections.IEnumerator)lps.GetType().InvokeMember("GetEnumerator", BindingFlags.InvokeMethod, null, lps, null, CultureInfo.InvariantCulture)!; while (lpn.MoveNext()) From 0bc914379dd1521f8b0c75f860821e6b4ac5f547 Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Wed, 11 Jun 2025 07:53:21 +0000 Subject: [PATCH 071/541] [main] Update dependencies from devdiv/DevDiv/vs-code-coverage, dotnet/arcade (#5728) [main] Update dependencies from devdiv/DevDiv/vs-code-coverage, dotnet/arcade --- eng/Version.Details.xml | 16 ++++++++-------- eng/Versions.props | 4 ++-- eng/common/cross/build-rootfs.sh | 4 ++-- global.json | 2 +- 4 files changed, 13 insertions(+), 13 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index 42f087dac4..d3cc63ce58 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -1,21 +1,21 @@ - + https://github.com/dotnet/arcade - add492db56ebc80df604ba5a30723beef14ed3dd + d237be4630776450573bc588eb995bb8f9ebc04f - + https://github.com/dotnet/arcade - add492db56ebc80df604ba5a30723beef14ed3dd + d237be4630776450573bc588eb995bb8f9ebc04f - + https://github.com/dotnet/arcade - add492db56ebc80df604ba5a30723beef14ed3dd + d237be4630776450573bc588eb995bb8f9ebc04f - + https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage - 56072d0b01c97c921bf6dcbe81297f0e44551f04 + 7d78c65400a20ab1c9be42104ae4f40568f6885a diff --git a/eng/Versions.props b/eng/Versions.props index 3be3b98ff5..b0b97903d9 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -7,7 +7,7 @@ preview - 10.0.0-beta.25309.2 - 17.15.0-preview.25304.1 + 10.0.0-beta.25310.2 + 17.15.0-preview.25310.3 diff --git a/eng/common/cross/build-rootfs.sh b/eng/common/cross/build-rootfs.sh index d6f005b5da..8abfb71f72 100644 --- a/eng/common/cross/build-rootfs.sh +++ b/eng/common/cross/build-rootfs.sh @@ -295,8 +295,8 @@ while :; do ;; noble) # Ubuntu 24.04 __CodeName=noble - if [[ -n "$__LLDB_Package" ]]; then - __LLDB_Package="liblldb-18-dev" + if [[ -z "$__LLDB_Package" ]]; then + __LLDB_Package="liblldb-19-dev" fi ;; stretch) # Debian 9 diff --git a/global.json b/global.json index 08c258fca8..dd491d8f6c 100644 --- a/global.json +++ b/global.json @@ -28,7 +28,7 @@ "rollForward": "latestFeature" }, "msbuild-sdks": { - "Microsoft.DotNet.Arcade.Sdk": "10.0.0-beta.25309.2", + "Microsoft.DotNet.Arcade.Sdk": "10.0.0-beta.25310.2", "MSBuild.Sdk.Extras": "3.0.44" } } From 48fd1f390a6a2e4c8a203dd62d6d9852c26fc037 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Wed, 11 Jun 2025 12:22:01 +0200 Subject: [PATCH 072/541] Move files from adapter to platform services project (#5713) --- eng/verify-nupkgs.ps1 | 2 +- .../Execution/TcmTestPropertiesProvider.cs | 50 - .../Extensions/ExceptionExtensions.cs | 87 -- .../MSTest.TestAdapter.csproj | 22 - .../Properties/AssemblyInfo.cs | 19 + .../PublicAPI/PublicAPI.Shipped.txt | 138 --- .../PublicAPI/uwp/PublicAPI.Shipped.txt | 138 --- .../Resources/Resource.Designer.cs | 888 ------------------ .../Resources/Resource.resx | 418 --------- .../Resources/xlf/Resource.cs.xlf | 482 ---------- .../Resources/xlf/Resource.de.xlf | 482 ---------- .../Resources/xlf/Resource.es.xlf | 482 ---------- .../Resources/xlf/Resource.fr.xlf | 482 ---------- .../Resources/xlf/Resource.it.xlf | 482 ---------- .../Resources/xlf/Resource.ja.xlf | 483 ---------- .../Resources/xlf/Resource.ko.xlf | 482 ---------- .../Resources/xlf/Resource.pl.xlf | 482 ---------- .../Resources/xlf/Resource.pt-BR.xlf | 482 ---------- .../Resources/xlf/Resource.ru.xlf | 482 ---------- .../Resources/xlf/Resource.tr.xlf | 482 ---------- .../Resources/xlf/Resource.zh-Hans.xlf | 482 ---------- .../Resources/xlf/Resource.zh-Hant.xlf | 482 ---------- .../VSTestAdapter/MSTestDiscoverer.cs | 6 +- .../VSTestAdapter/MSTestExecutor.cs | 8 +- .../AssemblyResolver.cs | 4 +- .../Constants.cs | 44 - .../Deployment/AssemblyLoadWorker.cs | 2 +- .../Deployment/TestRunDirectories.cs | 4 +- .../Discovery/AssemblyEnumerationResult.cs | 0 .../Discovery/AssemblyEnumerator.cs | 13 +- .../Discovery/AssemblyEnumeratorWrapper.cs | 1 + .../Discovery/DiscoveryTestMethodInfo.cs | 0 .../Discovery/TestMethodValidator.cs | 1 + .../Discovery/TypeEnumerator.cs | 0 .../Discovery/TypeValidator.cs | 1 + .../Discovery/UnitTestDiscoverer.cs | 3 +- .../EngineConstants.cs} | 56 +- .../Execution/ClassCleanupManager.cs | 2 +- .../Execution/ExceptionHelper.cs | 3 +- .../Execution/LogMessageListener.cs | 4 +- .../Execution/TcmTestPropertiesProvider.cs | 52 + .../Execution/TestAssemblyInfo.cs | 6 +- .../Execution/TestAssemblySettingsProvider.cs | 0 .../Execution/TestCaseDiscoverySink.cs | 0 .../Execution/TestClassInfo.cs | 6 +- .../Execution/TestExecutionManager.cs | 19 +- .../Execution/TestMethodInfo.cs | 8 +- .../Execution/TestMethodRunner.cs | 2 + .../Execution/TestRunCancellationToken.cs | 4 +- .../Execution/TimeoutInfo.cs | 0 .../Execution/TypeCache.cs | 1 + .../Execution/UnitTestRunner.cs | 13 +- .../Extensions/ExceptionExtensions.cs | 78 ++ .../Extensions/MethodInfoExtensions.cs | 2 + .../Extensions/TestCaseExtensions.cs | 29 +- .../Extensions/TestContextExtensions.cs | 0 .../Extensions/TestResultExtensions.cs | 20 +- .../Extensions/UnitTestOutcomeExtensions.cs | 4 +- .../Helpers/AttributeHelpers.cs | 0 .../Helpers/DataSerializationHelper.cs | 2 +- .../Helpers/DictionaryHelper.cs | 0 .../Helpers/EnvironmentWrapper.cs | 0 .../Helpers/ExecutionContextHelpers.cs | 0 .../Helpers/FixtureKind.cs | 0 .../Helpers/FixtureMethodRunner.cs | 1 - .../Helpers/IEnvironment.cs | 0 .../Helpers/MSTestDiscovererHelpers.cs | 1 + .../Helpers/ReflectHelper.cs | 1 + .../Helpers/RunSettingsUtilities.cs | 1 + .../Helpers/RuntimeContext.cs | 0 .../Helpers/TestDataSourceHelpers.cs | 0 .../Helpers/TestRunParameters.cs | 1 + .../Helpers/UnitTestOutcomeHelper.cs | 0 .../IPlatformServiceProvider.cs | 0 .../Interfaces/IAdapterTraceLogger.cs | 4 +- .../Interfaces/IFileOperations.cs | 4 +- .../Interfaces/IReflectionOperations.cs | 4 +- .../Interfaces/ISettingsProvider.cs | 4 +- .../Interfaces/ITestDeployment.cs | 5 +- .../Interfaces/ITestSource.cs | 6 +- .../Interfaces/ITestSourceHost.cs | 4 +- .../Interfaces/IThreadOperations.cs | 4 +- .../Interfaces/ITraceListener.cs | 4 +- .../Interfaces/ITraceListenerManager.cs | 4 +- .../MSTestAdapter.PlatformServices.csproj | 7 +- .../MSTestSettings.cs | 20 +- .../ObjectModel/AdapterSettingsException.cs | 0 .../ObjectModel/DynamicDataType.cs | 0 .../ObjectModel/FixtureTestResult.cs | 0 .../ObjectModel/StackTraceInformation.cs | 0 .../ObjectModel/TestAssemblySettings.cs | 2 + .../ObjectModel/TestFailedException.cs | 0 .../ObjectModel/TestMethod.cs | 4 +- .../ObjectModel/TypeInspectionException.cs | 0 .../ObjectModel/UnitTestElement.cs | 35 +- .../ObjectModel/UnitTestOutcome.cs | 4 +- .../ObjectModel/UnitTestResult.cs | 4 +- .../PlatformServiceProvider.cs | 0 .../PublicAPI/PublicAPI.Shipped.txt | 138 +++ .../RecursiveDirectoryPath.cs | 4 +- .../Resources/Resource.Designer.cs | 843 ++++++++++++++++- .../Resources/Resource.resx | 298 ++++++ .../Resources/xlf/Resource.cs.xlf | 475 ++++++++++ .../Resources/xlf/Resource.de.xlf | 475 ++++++++++ .../Resources/xlf/Resource.es.xlf | 475 ++++++++++ .../Resources/xlf/Resource.fr.xlf | 475 ++++++++++ .../Resources/xlf/Resource.it.xlf | 475 ++++++++++ .../Resources/xlf/Resource.ja.xlf | 475 ++++++++++ .../Resources/xlf/Resource.ko.xlf | 475 ++++++++++ .../Resources/xlf/Resource.pl.xlf | 475 ++++++++++ .../Resources/xlf/Resource.pt-BR.xlf | 475 ++++++++++ .../Resources/xlf/Resource.ru.xlf | 475 ++++++++++ .../Resources/xlf/Resource.tr.xlf | 475 ++++++++++ .../Resources/xlf/Resource.zh-Hans.xlf | 475 ++++++++++ .../Resources/xlf/Resource.zh-Hant.xlf | 475 ++++++++++ .../RunConfigurationSettings.cs | 5 +- .../Services/FileOperations.cs | 4 +- .../Services/MSTestAdapterSettings.cs | 4 +- .../Services/ReflectionOperations.cs | 5 +- .../Services/SettingsProvider.cs | 4 +- .../Services/TestContextImplementation.cs | 4 +- .../Services/TestDataSource.cs | 4 +- .../Services/TestDeployment.cs | 4 +- .../Services/TestSource.cs | 21 +- .../Services/TestSourceHost.cs | 6 +- .../Services/ThreadOperations.cs | 4 +- .../Services/ThreadSafeStringWriter.cs | 4 +- .../Services/TraceListener.cs | 4 +- .../Services/TraceListenerManager.cs | 4 +- .../Services/TraceLogger.cs | 4 +- .../TestMethodFilter.cs | 7 +- .../Utilities/AppDomainUtilities.cs | 6 +- .../Utilities/DeploymentItemUtility.cs | 2 +- .../Utilities/VSInstallationUtilities.cs | 4 +- .../ArrayBuilder.Enumerator.cs | 2 +- .../BoundedCacheWithFactory.cs | 2 +- .../AppInsightsProvider.cs | 6 +- .../Helpers/System/IProcess.cs | 16 +- .../TestFramework.Extensions/MessageLevel.cs | 2 +- .../InternalTestFailureException.cs | 4 +- .../{Constants.cs => FrameworkConstants.cs} | 2 +- .../TestFramework/GenericParameterHelper.cs | 4 +- .../TestFramework/TestFramework.csproj | 1 + .../Discovery/AssemblyEnumeratorTests.cs | 1 + .../AssemblyEnumeratorWrapperTests.cs | 7 +- .../Discovery/TestMethodValidatorTests.cs | 6 +- ...sts.MockedMethodInfoWithExtraAttributes.cs | 0 .../Discovery/TypeEnumeratorTests.cs | 0 .../Discovery/TypeValidatorTests.cs | 25 +- .../Discovery/UnitTestDiscovererTests.cs | 0 .../Execution/ClassCleanupManagerTests.cs | 0 .../Execution/LogMessageListenerTests.cs | 0 .../TcmTestPropertiesProviderTests.cs | 37 +- .../Execution/TestAssemblyInfoTests.cs | 15 +- .../TestAssemblySettingsProviderTests.cs | 18 +- .../Execution/TestCaseDiscoverySinkTests.cs | 0 .../Execution/TestClassInfoTests.cs | 33 +- .../Execution/TestExecutionManagerTests.cs | 42 +- .../Execution/TestMethodFilterTests.cs | 16 +- .../Execution/TestMethodInfoTests.cs | 232 +++-- .../Execution/TestMethodRunnerTests.cs | 8 +- .../Execution/TestPropertyAttributeTests.cs | 0 .../Execution/TypeCacheTests.cs | 0 .../Execution/UnitTestResultTest.cs | 0 .../Execution/UnitTestRunnerTests.cs | 0 .../Extensions/ExceptionExtensionsTests.cs | 196 ++++ .../Extensions/MethodInfoExtensionsTests.cs | 22 +- .../Extensions/TestCaseExtensionsTests.cs | 15 +- .../Extensions/TestContextExtensionsTests.cs | 0 .../Extensions/TestResultExtensionsTests.cs | 9 +- .../UnitTestOutcomeExtensionsTests.cs | 20 +- .../Helpers/DataSerializationHelperTests.cs | 0 .../Helpers/DictionaryHelperTests.cs | 0 .../Helpers/ReflectHelperTests.cs | 0 .../Helpers/RunSettingsUtilitiesTests.cs | 0 .../Helpers/UnitTestOutcomeHelperTests.cs | 0 .../MSTestSettingsTests.cs | 5 +- .../ObjectModel/UnitTestElementTests.cs | 41 +- .../ObjectModel/UnitTestResultTests.cs | 0 .../PlatformServiceProviderTests.cs | 0 .../RunConfigurationSettingsTests.cs | 0 .../TestablePlatformServiceProvider.cs | 3 +- .../Utilities/VSInstallationUtilitiesTests.cs | 2 +- .../Extensions/ExceptionExtensionsTests.cs | 209 ----- .../MSTestAdapter.UnitTests.csproj | 4 + .../MSTestDiscovererTests.cs | 11 + .../MSTestExecutorTests.cs | 3 +- .../Attributes}/DynamicDataAttributeTests.cs | 476 +++++----- 188 files changed, 8592 insertions(+), 9012 deletions(-) delete mode 100644 src/Adapter/MSTest.TestAdapter/Execution/TcmTestPropertiesProvider.cs delete mode 100644 src/Adapter/MSTest.TestAdapter/Extensions/ExceptionExtensions.cs delete mode 100644 src/Adapter/MSTest.TestAdapter/Resources/Resource.Designer.cs delete mode 100644 src/Adapter/MSTest.TestAdapter/Resources/Resource.resx delete mode 100644 src/Adapter/MSTest.TestAdapter/Resources/xlf/Resource.cs.xlf delete mode 100644 src/Adapter/MSTest.TestAdapter/Resources/xlf/Resource.de.xlf delete mode 100644 src/Adapter/MSTest.TestAdapter/Resources/xlf/Resource.es.xlf delete mode 100644 src/Adapter/MSTest.TestAdapter/Resources/xlf/Resource.fr.xlf delete mode 100644 src/Adapter/MSTest.TestAdapter/Resources/xlf/Resource.it.xlf delete mode 100644 src/Adapter/MSTest.TestAdapter/Resources/xlf/Resource.ja.xlf delete mode 100644 src/Adapter/MSTest.TestAdapter/Resources/xlf/Resource.ko.xlf delete mode 100644 src/Adapter/MSTest.TestAdapter/Resources/xlf/Resource.pl.xlf delete mode 100644 src/Adapter/MSTest.TestAdapter/Resources/xlf/Resource.pt-BR.xlf delete mode 100644 src/Adapter/MSTest.TestAdapter/Resources/xlf/Resource.ru.xlf delete mode 100644 src/Adapter/MSTest.TestAdapter/Resources/xlf/Resource.tr.xlf delete mode 100644 src/Adapter/MSTest.TestAdapter/Resources/xlf/Resource.zh-Hans.xlf delete mode 100644 src/Adapter/MSTest.TestAdapter/Resources/xlf/Resource.zh-Hant.xlf delete mode 100644 src/Adapter/MSTestAdapter.PlatformServices/Constants.cs rename src/Adapter/{MSTest.TestAdapter => MSTestAdapter.PlatformServices}/Discovery/AssemblyEnumerationResult.cs (100%) rename src/Adapter/{MSTest.TestAdapter => MSTestAdapter.PlatformServices}/Discovery/AssemblyEnumerator.cs (97%) rename src/Adapter/{MSTest.TestAdapter => MSTestAdapter.PlatformServices}/Discovery/AssemblyEnumeratorWrapper.cs (98%) rename src/Adapter/{MSTest.TestAdapter => MSTestAdapter.PlatformServices}/Discovery/DiscoveryTestMethodInfo.cs (100%) rename src/Adapter/{MSTest.TestAdapter => MSTestAdapter.PlatformServices}/Discovery/TestMethodValidator.cs (97%) rename src/Adapter/{MSTest.TestAdapter => MSTestAdapter.PlatformServices}/Discovery/TypeEnumerator.cs (100%) rename src/Adapter/{MSTest.TestAdapter => MSTestAdapter.PlatformServices}/Discovery/TypeValidator.cs (99%) rename src/Adapter/{MSTest.TestAdapter => MSTestAdapter.PlatformServices}/Discovery/UnitTestDiscoverer.cs (98%) rename src/Adapter/{MSTest.TestAdapter/Constants.cs => MSTestAdapter.PlatformServices/EngineConstants.cs} (88%) rename src/Adapter/{MSTest.TestAdapter => MSTestAdapter.PlatformServices}/Execution/ClassCleanupManager.cs (97%) rename src/Adapter/{MSTest.TestAdapter => MSTestAdapter.PlatformServices}/Execution/ExceptionHelper.cs (97%) rename src/Adapter/{MSTest.TestAdapter => MSTestAdapter.PlatformServices}/Execution/LogMessageListener.cs (97%) create mode 100644 src/Adapter/MSTestAdapter.PlatformServices/Execution/TcmTestPropertiesProvider.cs rename src/Adapter/{MSTest.TestAdapter => MSTestAdapter.PlatformServices}/Execution/TestAssemblyInfo.cs (97%) rename src/Adapter/{MSTest.TestAdapter => MSTestAdapter.PlatformServices}/Execution/TestAssemblySettingsProvider.cs (100%) rename src/Adapter/{MSTest.TestAdapter => MSTestAdapter.PlatformServices}/Execution/TestCaseDiscoverySink.cs (100%) rename src/Adapter/{MSTest.TestAdapter => MSTestAdapter.PlatformServices}/Execution/TestClassInfo.cs (99%) rename src/Adapter/{MSTest.TestAdapter => MSTestAdapter.PlatformServices}/Execution/TestExecutionManager.cs (97%) rename src/Adapter/{MSTest.TestAdapter => MSTestAdapter.PlatformServices}/Execution/TestMethodInfo.cs (98%) rename src/Adapter/{MSTest.TestAdapter => MSTestAdapter.PlatformServices}/Execution/TestMethodRunner.cs (99%) rename src/Adapter/{MSTest.TestAdapter => MSTestAdapter.PlatformServices}/Execution/TestRunCancellationToken.cs (92%) rename src/Adapter/{MSTest.TestAdapter => MSTestAdapter.PlatformServices}/Execution/TimeoutInfo.cs (100%) rename src/Adapter/{MSTest.TestAdapter => MSTestAdapter.PlatformServices}/Execution/TypeCache.cs (99%) rename src/Adapter/{MSTest.TestAdapter => MSTestAdapter.PlatformServices}/Execution/UnitTestRunner.cs (95%) rename src/Adapter/{MSTest.TestAdapter => MSTestAdapter.PlatformServices}/Extensions/MethodInfoExtensions.cs (98%) rename src/Adapter/{MSTest.TestAdapter => MSTestAdapter.PlatformServices}/Extensions/TestCaseExtensions.cs (84%) rename src/Adapter/{MSTest.TestAdapter => MSTestAdapter.PlatformServices}/Extensions/TestContextExtensions.cs (100%) rename src/Adapter/{MSTest.TestAdapter => MSTestAdapter.PlatformServices}/Extensions/TestResultExtensions.cs (85%) rename src/Adapter/{MSTest.TestAdapter => MSTestAdapter.PlatformServices}/Extensions/UnitTestOutcomeExtensions.cs (92%) rename src/Adapter/{MSTest.TestAdapter => MSTestAdapter.PlatformServices}/Helpers/AttributeHelpers.cs (100%) rename src/Adapter/{MSTest.TestAdapter => MSTestAdapter.PlatformServices}/Helpers/DataSerializationHelper.cs (98%) rename src/Adapter/{MSTest.TestAdapter => MSTestAdapter.PlatformServices}/Helpers/DictionaryHelper.cs (100%) rename src/Adapter/{MSTest.TestAdapter => MSTestAdapter.PlatformServices}/Helpers/EnvironmentWrapper.cs (100%) rename src/Adapter/{MSTest.TestAdapter => MSTestAdapter.PlatformServices}/Helpers/ExecutionContextHelpers.cs (100%) rename src/Adapter/{MSTest.TestAdapter => MSTestAdapter.PlatformServices}/Helpers/FixtureKind.cs (100%) rename src/Adapter/{MSTest.TestAdapter => MSTestAdapter.PlatformServices}/Helpers/FixtureMethodRunner.cs (99%) rename src/Adapter/{MSTest.TestAdapter => MSTestAdapter.PlatformServices}/Helpers/IEnvironment.cs (100%) rename src/Adapter/{MSTest.TestAdapter => MSTestAdapter.PlatformServices}/Helpers/MSTestDiscovererHelpers.cs (96%) rename src/Adapter/{MSTest.TestAdapter => MSTestAdapter.PlatformServices}/Helpers/ReflectHelper.cs (99%) rename src/Adapter/{MSTest.TestAdapter => MSTestAdapter.PlatformServices}/Helpers/RunSettingsUtilities.cs (97%) rename src/Adapter/{MSTest.TestAdapter => MSTestAdapter.PlatformServices}/Helpers/RuntimeContext.cs (100%) rename src/Adapter/{MSTest.TestAdapter => MSTestAdapter.PlatformServices}/Helpers/TestDataSourceHelpers.cs (100%) rename src/Adapter/{MSTest.TestAdapter => MSTestAdapter.PlatformServices}/Helpers/TestRunParameters.cs (96%) rename src/Adapter/{MSTest.TestAdapter => MSTestAdapter.PlatformServices}/Helpers/UnitTestOutcomeHelper.cs (100%) rename src/Adapter/{MSTest.TestAdapter => MSTestAdapter.PlatformServices}/IPlatformServiceProvider.cs (100%) rename src/Adapter/{MSTest.TestAdapter => MSTestAdapter.PlatformServices}/MSTestSettings.cs (98%) rename src/Adapter/{MSTest.TestAdapter => MSTestAdapter.PlatformServices}/ObjectModel/AdapterSettingsException.cs (100%) rename src/Adapter/{MSTest.TestAdapter => MSTestAdapter.PlatformServices}/ObjectModel/DynamicDataType.cs (100%) rename src/Adapter/{MSTest.TestAdapter => MSTestAdapter.PlatformServices}/ObjectModel/FixtureTestResult.cs (100%) rename src/Adapter/{MSTest.TestAdapter => MSTestAdapter.PlatformServices}/ObjectModel/StackTraceInformation.cs (100%) rename src/Adapter/{MSTest.TestAdapter => MSTestAdapter.PlatformServices}/ObjectModel/TestAssemblySettings.cs (92%) rename src/Adapter/{MSTest.TestAdapter => MSTestAdapter.PlatformServices}/ObjectModel/TestFailedException.cs (100%) rename src/Adapter/{MSTest.TestAdapter => MSTestAdapter.PlatformServices}/ObjectModel/TestMethod.cs (97%) rename src/Adapter/{MSTest.TestAdapter => MSTestAdapter.PlatformServices}/ObjectModel/TypeInspectionException.cs (100%) rename src/Adapter/{MSTest.TestAdapter => MSTestAdapter.PlatformServices}/ObjectModel/UnitTestElement.cs (85%) rename src/Adapter/{MSTest.TestAdapter => MSTestAdapter.PlatformServices}/ObjectModel/UnitTestOutcome.cs (89%) rename src/Adapter/{MSTest.TestAdapter => MSTestAdapter.PlatformServices}/ObjectModel/UnitTestResult.cs (96%) rename src/Adapter/{MSTest.TestAdapter => MSTestAdapter.PlatformServices}/PlatformServiceProvider.cs (100%) rename src/Adapter/{MSTest.TestAdapter => MSTestAdapter.PlatformServices}/RunConfigurationSettings.cs (97%) rename src/Adapter/{MSTest.TestAdapter => MSTestAdapter.PlatformServices}/TestMethodFilter.cs (94%) rename src/TestFramework/TestFramework/{Constants.cs => FrameworkConstants.cs} (92%) rename test/UnitTests/{MSTestAdapter.UnitTests => MSTestAdapter.PlatformServices.UnitTests}/Discovery/AssemblyEnumeratorTests.cs (99%) rename test/UnitTests/{MSTestAdapter.UnitTests => MSTestAdapter.PlatformServices.UnitTests}/Discovery/AssemblyEnumeratorWrapperTests.cs (98%) rename test/UnitTests/{MSTestAdapter.UnitTests => MSTestAdapter.PlatformServices.UnitTests}/Discovery/TestMethodValidatorTests.cs (96%) rename test/UnitTests/{MSTestAdapter.UnitTests => MSTestAdapter.PlatformServices.UnitTests}/Discovery/TypeEnumeratorTests.MockedMethodInfoWithExtraAttributes.cs (100%) rename test/UnitTests/{MSTestAdapter.UnitTests => MSTestAdapter.PlatformServices.UnitTests}/Discovery/TypeEnumeratorTests.cs (100%) rename test/UnitTests/{MSTestAdapter.UnitTests => MSTestAdapter.PlatformServices.UnitTests}/Discovery/TypeValidatorTests.cs (95%) rename test/UnitTests/{MSTestAdapter.UnitTests => MSTestAdapter.PlatformServices.UnitTests}/Discovery/UnitTestDiscovererTests.cs (100%) rename test/UnitTests/{MSTestAdapter.UnitTests => MSTestAdapter.PlatformServices.UnitTests}/Execution/ClassCleanupManagerTests.cs (100%) rename test/UnitTests/{MSTestAdapter.UnitTests => MSTestAdapter.PlatformServices.UnitTests}/Execution/LogMessageListenerTests.cs (100%) rename test/UnitTests/{MSTestAdapter.UnitTests => MSTestAdapter.PlatformServices.UnitTests}/Execution/TcmTestPropertiesProviderTests.cs (87%) rename test/UnitTests/{MSTestAdapter.UnitTests => MSTestAdapter.PlatformServices.UnitTests}/Execution/TestAssemblyInfoTests.cs (96%) rename test/UnitTests/{MSTestAdapter.UnitTests => MSTestAdapter.PlatformServices.UnitTests}/Execution/TestAssemblySettingsProviderTests.cs (91%) rename test/UnitTests/{MSTestAdapter.UnitTests => MSTestAdapter.PlatformServices.UnitTests}/Execution/TestCaseDiscoverySinkTests.cs (100%) rename test/UnitTests/{MSTestAdapter.UnitTests => MSTestAdapter.PlatformServices.UnitTests}/Execution/TestClassInfoTests.cs (95%) rename test/UnitTests/{MSTestAdapter.UnitTests => MSTestAdapter.PlatformServices.UnitTests}/Execution/TestExecutionManagerTests.cs (97%) rename test/UnitTests/{MSTestAdapter.UnitTests => MSTestAdapter.PlatformServices.UnitTests}/Execution/TestMethodFilterTests.cs (93%) rename test/UnitTests/{MSTestAdapter.UnitTests => MSTestAdapter.PlatformServices.UnitTests}/Execution/TestMethodInfoTests.cs (91%) rename test/UnitTests/{MSTestAdapter.UnitTests => MSTestAdapter.PlatformServices.UnitTests}/Execution/TestMethodRunnerTests.cs (98%) rename test/UnitTests/{MSTestAdapter.UnitTests => MSTestAdapter.PlatformServices.UnitTests}/Execution/TestPropertyAttributeTests.cs (100%) rename test/UnitTests/{MSTestAdapter.UnitTests => MSTestAdapter.PlatformServices.UnitTests}/Execution/TypeCacheTests.cs (100%) rename test/UnitTests/{MSTestAdapter.UnitTests => MSTestAdapter.PlatformServices.UnitTests}/Execution/UnitTestResultTest.cs (100%) rename test/UnitTests/{MSTestAdapter.UnitTests => MSTestAdapter.PlatformServices.UnitTests}/Execution/UnitTestRunnerTests.cs (100%) rename test/UnitTests/{MSTestAdapter.UnitTests => MSTestAdapter.PlatformServices.UnitTests}/Extensions/MethodInfoExtensionsTests.cs (96%) rename test/UnitTests/{MSTestAdapter.UnitTests => MSTestAdapter.PlatformServices.UnitTests}/Extensions/TestCaseExtensionsTests.cs (79%) rename test/UnitTests/{MSTestAdapter.UnitTests => MSTestAdapter.PlatformServices.UnitTests}/Extensions/TestContextExtensionsTests.cs (100%) rename test/UnitTests/{MSTestAdapter.UnitTests => MSTestAdapter.PlatformServices.UnitTests}/Extensions/TestResultExtensionsTests.cs (96%) rename test/UnitTests/{MSTestAdapter.UnitTests => MSTestAdapter.PlatformServices.UnitTests}/Extensions/UnitTestOutcomeExtensionsTests.cs (73%) rename test/UnitTests/{MSTestAdapter.UnitTests => MSTestAdapter.PlatformServices.UnitTests}/Helpers/DataSerializationHelperTests.cs (100%) rename test/UnitTests/{MSTestAdapter.UnitTests => MSTestAdapter.PlatformServices.UnitTests}/Helpers/DictionaryHelperTests.cs (100%) rename test/UnitTests/{MSTestAdapter.UnitTests => MSTestAdapter.PlatformServices.UnitTests}/Helpers/ReflectHelperTests.cs (100%) rename test/UnitTests/{MSTestAdapter.UnitTests => MSTestAdapter.PlatformServices.UnitTests}/Helpers/RunSettingsUtilitiesTests.cs (100%) rename test/UnitTests/{MSTestAdapter.UnitTests => MSTestAdapter.PlatformServices.UnitTests}/Helpers/UnitTestOutcomeHelperTests.cs (100%) rename test/UnitTests/{MSTestAdapter.UnitTests => MSTestAdapter.PlatformServices.UnitTests}/MSTestSettingsTests.cs (99%) rename test/UnitTests/{MSTestAdapter.UnitTests => MSTestAdapter.PlatformServices.UnitTests}/ObjectModel/UnitTestElementTests.cs (86%) rename test/UnitTests/{MSTestAdapter.UnitTests => MSTestAdapter.PlatformServices.UnitTests}/ObjectModel/UnitTestResultTests.cs (100%) rename test/UnitTests/{MSTestAdapter.UnitTests => MSTestAdapter.PlatformServices.UnitTests}/PlatformServiceProviderTests.cs (100%) rename test/UnitTests/{MSTestAdapter.UnitTests => MSTestAdapter.PlatformServices.UnitTests}/RunConfigurationSettingsTests.cs (100%) rename test/UnitTests/{MSTestAdapter.UnitTests => MSTestAdapter.PlatformServices.UnitTests}/TestableImplementations/TestablePlatformServiceProvider.cs (97%) delete mode 100644 test/UnitTests/MSTestAdapter.UnitTests/Extensions/ExceptionExtensionsTests.cs rename test/UnitTests/{MSTestAdapter.UnitTests => TestFramework.UnitTests/Attributes}/DynamicDataAttributeTests.cs (62%) diff --git a/eng/verify-nupkgs.ps1 b/eng/verify-nupkgs.ps1 index 26e97d3fd1..4e267fc109 100644 --- a/eng/verify-nupkgs.ps1 +++ b/eng/verify-nupkgs.ps1 @@ -21,7 +21,7 @@ function Confirm-NugetPackages { $expectedNumOfFiles = @{ "MSTest.Sdk" = 15 "MSTest.TestFramework" = 162 - "MSTest.TestAdapter" = 93 + "MSTest.TestAdapter" = 80 "MSTest" = 14 "MSTest.Analyzers" = 56 } diff --git a/src/Adapter/MSTest.TestAdapter/Execution/TcmTestPropertiesProvider.cs b/src/Adapter/MSTest.TestAdapter/Execution/TcmTestPropertiesProvider.cs deleted file mode 100644 index 1735b1cf0b..0000000000 --- a/src/Adapter/MSTest.TestAdapter/Execution/TcmTestPropertiesProvider.cs +++ /dev/null @@ -1,50 +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 TestPlatformObjectModel = Microsoft.VisualStudio.TestPlatform.ObjectModel; - -namespace Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution; - -/// -/// Reads and parses the TcmTestProperties in order to populate them in TestRunParameters. -/// -internal static class TcmTestPropertiesProvider -{ - /// - /// Gets tcm properties from test case. - /// - /// Test case. - /// Tcm properties. - public static IDictionary GetTcmProperties(TestPlatformObjectModel.TestCase? testCase) - { - var tcmProperties = new Dictionary(); - - // Return empty properties when testCase is null or when test case id is zero. - if (testCase == null || - testCase.GetPropertyValue(Constants.TestCaseIdProperty, default) == 0) - { - return tcmProperties; - } - - // Step 1: Add common properties. - tcmProperties[Constants.TestRunIdProperty] = testCase.GetPropertyValue(Constants.TestRunIdProperty, default); - tcmProperties[Constants.TestPlanIdProperty] = testCase.GetPropertyValue(Constants.TestPlanIdProperty, default); - tcmProperties[Constants.BuildConfigurationIdProperty] = testCase.GetPropertyValue(Constants.BuildConfigurationIdProperty, default); - tcmProperties[Constants.BuildDirectoryProperty] = testCase.GetPropertyValue(Constants.BuildDirectoryProperty, default); - tcmProperties[Constants.BuildFlavorProperty] = testCase.GetPropertyValue(Constants.BuildFlavorProperty, default); - tcmProperties[Constants.BuildNumberProperty] = testCase.GetPropertyValue(Constants.BuildNumberProperty, default); - tcmProperties[Constants.BuildPlatformProperty] = testCase.GetPropertyValue(Constants.BuildPlatformProperty, default); - tcmProperties[Constants.BuildUriProperty] = testCase.GetPropertyValue(Constants.BuildUriProperty, default); - tcmProperties[Constants.TfsServerCollectionUrlProperty] = testCase.GetPropertyValue(Constants.TfsServerCollectionUrlProperty, default); - tcmProperties[Constants.TfsTeamProjectProperty] = testCase.GetPropertyValue(Constants.TfsTeamProjectProperty, default); - tcmProperties[Constants.IsInLabEnvironmentProperty] = testCase.GetPropertyValue(Constants.IsInLabEnvironmentProperty, default); - - // Step 2: Add test case specific properties. - tcmProperties[Constants.TestCaseIdProperty] = testCase.GetPropertyValue(Constants.TestCaseIdProperty, default); - tcmProperties[Constants.TestConfigurationIdProperty] = testCase.GetPropertyValue(Constants.TestConfigurationIdProperty, default); - tcmProperties[Constants.TestConfigurationNameProperty] = testCase.GetPropertyValue(Constants.TestConfigurationNameProperty, default); - tcmProperties[Constants.TestPointIdProperty] = testCase.GetPropertyValue(Constants.TestPointIdProperty, default); - - return tcmProperties; - } -} diff --git a/src/Adapter/MSTest.TestAdapter/Extensions/ExceptionExtensions.cs b/src/Adapter/MSTest.TestAdapter/Extensions/ExceptionExtensions.cs deleted file mode 100644 index c2a398faeb..0000000000 --- a/src/Adapter/MSTest.TestAdapter/Extensions/ExceptionExtensions.cs +++ /dev/null @@ -1,87 +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 Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution; -using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel; -using Microsoft.VisualStudio.TestTools.UnitTesting; - -using UTF = Microsoft.VisualStudio.TestTools.UnitTesting; - -namespace Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Extensions; - -/// -/// Extensions to type. -/// -internal static class ExceptionExtensions -{ - /// - /// TargetInvocationException and TypeInitializationException do not carry any useful information - /// to the user. Find the first inner exception that has useful information. - /// - internal static Exception GetRealException(this Exception exception) - { - // TargetInvocationException: Because .NET Framework wraps method.Invoke() into TargetInvocationException. - // TypeInitializationException: Because AssemblyInitialize is static, and often helpers that are also static - // are used to implement it, and they fail in constructor. - while (exception is TargetInvocationException or TypeInitializationException - && exception.InnerException is not null) - { - exception = exception.InnerException; - } - - return exception; - } - - /// - /// Get the exception message if available, empty otherwise. - /// - /// An object. - /// Exception message. - internal static string TryGetMessage(this Exception? exception) - { - if (exception == null) - { - return string.Format(CultureInfo.CurrentCulture, Resource.UTF_FailedToGetExceptionMessage, "null"); - } - - // It is safe to retrieve an exception message, it should not throw in any case. - return exception.Message ?? string.Empty; - } - - /// - /// Gets the for an exception. - /// - /// An instance. - /// StackTraceInformation for the exception. - internal static StackTraceInformation? TryGetStackTraceInformation(this Exception exception) => !StringEx.IsNullOrEmpty(exception.StackTrace) - ? ExceptionHelper.CreateStackTraceInformation(exception.StackTrace) - : null; - - /// - /// Checks whether exception is an Assert exception. - /// - /// An instance. - /// Framework's Outcome depending on type of assertion. - /// Exception message. - /// StackTraceInformation for the exception. - /// True, if Assert exception. False, otherwise. - internal static bool TryGetUnitTestAssertException(this Exception exception, out UTF.UnitTestOutcome outcome, - [NotNullWhen(true)] out string? exceptionMessage, out StackTraceInformation? exceptionStackTrace) - { - if (exception is UnitTestAssertException) - { - outcome = exception is AssertInconclusiveException - ? UTF.UnitTestOutcome.Inconclusive - : UTF.UnitTestOutcome.Failed; - - exceptionMessage = exception.TryGetMessage(); - exceptionStackTrace = exception.TryGetStackTraceInformation(); - return true; - } - - outcome = UTF.UnitTestOutcome.Failed; - exceptionMessage = null; - exceptionStackTrace = null; - return false; - } -} diff --git a/src/Adapter/MSTest.TestAdapter/MSTest.TestAdapter.csproj b/src/Adapter/MSTest.TestAdapter/MSTest.TestAdapter.csproj index 14ab40b3f2..74b07934a7 100644 --- a/src/Adapter/MSTest.TestAdapter/MSTest.TestAdapter.csproj +++ b/src/Adapter/MSTest.TestAdapter/MSTest.TestAdapter.csproj @@ -61,10 +61,6 @@ - - - - @@ -72,17 +68,6 @@ - - True - True - Resource.resx - - - ResXFileCodeGenerator - Resource.Designer.cs - Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter - Designer - @@ -109,13 +94,6 @@ - - - True - True - Resource.resx - - <_TemplateProperties>Version=$(Version) diff --git a/src/Adapter/MSTest.TestAdapter/Properties/AssemblyInfo.cs b/src/Adapter/MSTest.TestAdapter/Properties/AssemblyInfo.cs index 03648cfe6d..1986d819e5 100644 --- a/src/Adapter/MSTest.TestAdapter/Properties/AssemblyInfo.cs +++ b/src/Adapter/MSTest.TestAdapter/Properties/AssemblyInfo.cs @@ -3,5 +3,24 @@ using Microsoft.VisualStudio.TestPlatform; using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter; +using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution; +using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Extensions; +using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel; [assembly: TestExtensionTypes(typeof(MSTestDiscoverer), typeof(MSTestExecutor))] + +#pragma warning disable RS0016 // Add public types and members to the declared API (type forwarding is not public API) +[assembly: TypeForwardedTo(typeof(LogMessageListener))] +[assembly: TypeForwardedTo(typeof(MSTestSettings))] +[assembly: TypeForwardedTo(typeof(RunConfigurationSettings))] +[assembly: TypeForwardedTo(typeof(TestAssemblyInfo))] +[assembly: TypeForwardedTo(typeof(TestClassInfo))] +[assembly: TypeForwardedTo(typeof(TestExecutionManager))] +[assembly: TypeForwardedTo(typeof(TestMethod))] +[assembly: TypeForwardedTo(typeof(TestMethodInfo))] +[assembly: TypeForwardedTo(typeof(TestResultExtensions))] +[assembly: TypeForwardedTo(typeof(TestRunCancellationToken))] +[assembly: TypeForwardedTo(typeof(UnitTestOutcome))] +[assembly: TypeForwardedTo(typeof(UnitTestOutcomeExtensions))] +[assembly: TypeForwardedTo(typeof(UnitTestResult))] +#pragma warning restore RS0016 diff --git a/src/Adapter/MSTest.TestAdapter/PublicAPI/PublicAPI.Shipped.txt b/src/Adapter/MSTest.TestAdapter/PublicAPI/PublicAPI.Shipped.txt index 88c46e7489..7c85eb0167 100644 --- a/src/Adapter/MSTest.TestAdapter/PublicAPI/PublicAPI.Shipped.txt +++ b/src/Adapter/MSTest.TestAdapter/PublicAPI/PublicAPI.Shipped.txt @@ -1,65 +1,4 @@ #nullable enable -const Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestMethodInfo.TimeoutWhenNotSet = 0 -> int -const Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.MSTestSettings.SettingsName = "MSTest" -> string! -const Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.MSTestSettings.SettingsNameAlias = "MSTestV2" -> string! -const Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.TestMethod.TotalHierarchyLevels = 4 -> int -const Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.RunConfigurationSettings.SettingsName = "RunConfiguration" -> string! -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.LogMessageListener -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.LogMessageListener.DebugTrace.get -> string? -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.LogMessageListener.Dispose() -> void -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.LogMessageListener.GetAndClearDebugTrace() -> string? -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.LogMessageListener.GetAndClearStandardError() -> string? -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.LogMessageListener.GetAndClearStandardOutput() -> string? -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.LogMessageListener.LogMessageListener(bool captureDebugTraces) -> void -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.LogMessageListener.StandardError.get -> string! -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.LogMessageListener.StandardOutput.get -> string! -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestAssemblyInfo -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestAssemblyInfo.AssemblyCleanupMethod.get -> System.Reflection.MethodInfo? -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestAssemblyInfo.AssemblyInitializationException.get -> System.Exception? -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestAssemblyInfo.AssemblyInitializeMethod.get -> System.Reflection.MethodInfo? -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestAssemblyInfo.HasExecutableCleanupMethod.get -> bool -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestAssemblyInfo.IsAssemblyInitializeExecuted.get -> bool -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestAssemblyInfo.RunAssemblyCleanup() -> string? -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestAssemblyInfo.RunAssemblyInitialize(Microsoft.VisualStudio.TestTools.UnitTesting.TestContext! testContext) -> void -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestClassInfo -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestClassInfo.BaseClassCleanupMethodsStack.get -> System.Collections.Generic.Stack! -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestClassInfo.BaseClassInitAndCleanupMethods.get -> System.Collections.Generic.Queue!>! -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestClassInfo.BaseTestCleanupMethodsQueue.get -> System.Collections.Generic.Queue! -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestClassInfo.BaseTestInitializeMethodsQueue.get -> System.Collections.Generic.Queue! -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestClassInfo.ClassAttribute.get -> Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute! -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestClassInfo.ClassCleanupException.get -> System.Exception? -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestClassInfo.ClassCleanupMethod.get -> System.Reflection.MethodInfo? -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestClassInfo.ClassInitializationException.get -> System.Exception? -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestClassInfo.ClassInitializeMethod.get -> System.Reflection.MethodInfo? -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestClassInfo.ClassType.get -> System.Type! -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestClassInfo.Constructor.get -> System.Reflection.ConstructorInfo! -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestClassInfo.HasExecutableCleanupMethod.get -> bool -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestClassInfo.IsClassCleanupExecuted.get -> bool -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestClassInfo.IsClassInitializeExecuted.get -> bool -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestClassInfo.Parent.get -> Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestAssemblyInfo! -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestClassInfo.RunClassCleanup(Microsoft.VisualStudio.TestTools.UnitTesting.ClassCleanupBehavior classCleanupLifecycle = Microsoft.VisualStudio.TestTools.UnitTesting.ClassCleanupBehavior.EndOfAssembly) -> string? -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestClassInfo.RunClassInitialize(Microsoft.VisualStudio.TestTools.UnitTesting.TestContext! testContext) -> void -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestClassInfo.TestCleanupMethod.get -> System.Reflection.MethodInfo? -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestClassInfo.TestContextProperty.get -> System.Reflection.PropertyInfo? -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestClassInfo.TestInitializeMethod.get -> System.Reflection.MethodInfo? -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestExecutionManager -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestExecutionManager.RunTests(System.Collections.Generic.IEnumerable! tests, Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter.IRunContext? runContext, Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter.IFrameworkHandle! frameworkHandle, Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.TestRunCancellationToken! runCancellationToken) -> void -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestExecutionManager.RunTests(System.Collections.Generic.IEnumerable! sources, Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter.IRunContext? runContext, Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter.IFrameworkHandle! frameworkHandle, Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.TestRunCancellationToken! cancellationToken) -> void -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestExecutionManager.TestExecutionManager() -> void -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestMethodInfo -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestMethodInfo.Arguments.get -> object?[]? -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestMethodInfo.GetAllAttributes(bool inherit) -> System.Attribute![]? -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestMethodInfo.GetAttributes(bool inherit) -> TAttributeType![]! -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestMethodInfo.IsRunnable.get -> bool -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestMethodInfo.IsTimeoutSet.get -> bool -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestMethodInfo.MethodInfo.get -> System.Reflection.MethodInfo! -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestMethodInfo.NotRunnableReason.get -> string? -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestMethodInfo.ParameterTypes.get -> System.Reflection.ParameterInfo![]! -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestMethodInfo.ReturnType.get -> System.Type! -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestMethodInfo.TestClassName.get -> string! -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestMethodInfo.TestMethodName.get -> string! -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Extensions.TestResultExtensions -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Extensions.UnitTestOutcomeExtensions Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.MSTestDiscoverer Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.MSTestDiscoverer.DiscoverTests(System.Collections.Generic.IEnumerable! sources, Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter.IDiscoveryContext! discoveryContext, Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging.IMessageLogger! logger, Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter.ITestCaseDiscoverySink! discoverySink) -> void Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.MSTestDiscoverer.MSTestDiscoverer() -> void @@ -70,84 +9,7 @@ Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.MSTestExecutor.RunTests(S Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.MSTestExecutor.RunTests(System.Collections.Generic.IEnumerable? sources, Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter.IRunContext? runContext, Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter.IFrameworkHandle? frameworkHandle) -> void Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.MSTestExecutor.TestExecutionManager.get -> Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestExecutionManager! Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.MSTestExecutor.TestExecutionManager.set -> void -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.MSTestSettings -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.MSTestSettings.CaptureDebugTraces.get -> bool -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.MSTestSettings.ClassCleanupLifecycle.get -> Microsoft.VisualStudio.TestTools.UnitTesting.ClassCleanupBehavior? -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.MSTestSettings.DisableParallelization.get -> bool -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.MSTestSettings.EnableBaseClassTestMethodsFromOtherAssemblies.get -> bool -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.MSTestSettings.ForcedLegacyMode.get -> bool -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.MSTestSettings.MapInconclusiveToFailed.get -> bool -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.MSTestSettings.MapNotRunnableToFailed.get -> bool -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.MSTestSettings.MSTestSettings() -> void -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.MSTestSettings.ParallelizationScope.get -> Microsoft.VisualStudio.TestTools.UnitTesting.ExecutionScope? -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.MSTestSettings.ParallelizationWorkers.get -> int? -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.MSTestSettings.TestSettingsFile.get -> string? -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.MSTestSettings.TestTimeout.get -> int -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.MSTestSettings.TreatClassAndAssemblyCleanupWarningsAsErrors.get -> bool -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.MSTestSettings.TreatDiscoveryWarningsAsErrors.get -> bool -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.TestMethod -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.TestMethod.AssemblyName.get -> string! -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.TestMethod.DeclaringAssemblyName.get -> string? -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.TestMethod.DeclaringAssemblyName.set -> void -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.TestMethod.DeclaringClassFullName.get -> string? -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.TestMethod.DeclaringClassFullName.set -> void -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.TestMethod.FullClassName.get -> string! -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.TestMethod.HasManagedMethodAndTypeProperties.get -> bool -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.TestMethod.Hierarchy.get -> System.Collections.Generic.IReadOnlyCollection! -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.TestMethod.IsAsync.get -> bool -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.TestMethod.ManagedMethodName.get -> string? -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.TestMethod.ManagedTypeName.get -> string? -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.TestMethod.Name.get -> string! -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.TestMethod.TestIdGenerationStrategy.get -> Microsoft.VisualStudio.TestTools.UnitTesting.TestIdGenerationStrategy -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.TestMethod.TestMethod(string! name, string! fullClassName, string! assemblyName, bool isAsync) -> void -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestOutcome -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestOutcome.Error = 0 -> Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestOutcome -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestOutcome.Failed = 1 -> Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestOutcome -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestOutcome.Ignored = 4 -> Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestOutcome -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestOutcome.Inconclusive = 3 -> Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestOutcome -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestOutcome.InProgress = 8 -> Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestOutcome -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestOutcome.NotFound = 7 -> Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestOutcome -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestOutcome.NotRunnable = 5 -> Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestOutcome -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestOutcome.Passed = 6 -> Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestOutcome -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestOutcome.Timeout = 2 -> Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestOutcome -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestResult -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestResult.DatarowIndex.get -> int -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestResult.DebugTrace.get -> string? -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestResult.DisplayName.get -> string? -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestResult.Duration.get -> System.TimeSpan -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestResult.ErrorColumnNumber.get -> int -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestResult.ErrorFilePath.get -> string? -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestResult.ErrorLineNumber.get -> int -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestResult.ErrorMessage.get -> string? -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestResult.ErrorStackTrace.get -> string? -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestResult.ExecutionId.get -> System.Guid -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestResult.InnerResultsCount.get -> int -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestResult.Outcome.get -> Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestOutcome -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestResult.ParentExecId.get -> System.Guid -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestResult.ResultFiles.get -> System.Collections.Generic.IList? -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestResult.StandardError.get -> string? -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestResult.StandardOut.get -> string? -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestResult.TestContextMessages.get -> string? -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.RunConfigurationSettings -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.RunConfigurationSettings.CollectSourceInformation.get -> bool -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.RunConfigurationSettings.RunConfigurationSettings() -> void -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.TestRunCancellationToken -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.TestRunCancellationToken.Cancel() -> void -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.TestRunCancellationToken.Canceled.get -> bool -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.TestRunCancellationToken.Register(System.Action! callback) -> void -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.TestRunCancellationToken.TestRunCancellationToken() -> void -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.TestRunCancellationToken.Unregister() -> void Microsoft.VisualStudio.TestTools.UnitTesting.TestApplicationBuilderExtensions Microsoft.VisualStudio.TestTools.UnitTesting.TestingPlatformBuilderHook -static Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Extensions.TestResultExtensions.ToUnitTestResults(this Microsoft.VisualStudio.TestTools.UnitTesting.TestResult![]! testResults) -> Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestResult![]! -static Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Extensions.UnitTestOutcomeExtensions.ToUnitTestOutcome(this Microsoft.VisualStudio.TestTools.UnitTesting.UnitTestOutcome frameworkTestOutcome) -> Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestOutcome -static Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.MSTestSettings.CurrentSettings.get -> Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.MSTestSettings! -static Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.MSTestSettings.IsLegacyScenario(Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging.IMessageLogger! logger) -> bool -static Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.MSTestSettings.PopulateSettings(Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.MSTestSettings! settings) -> void -static Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.MSTestSettings.PopulateSettings(Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter.IDiscoveryContext? context) -> void -static Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.MSTestSettings.RunConfigurationSettings.get -> Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.RunConfigurationSettings! -static Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.RunConfigurationSettings.PopulateSettings(Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter.IDiscoveryContext? context) -> Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.RunConfigurationSettings! static Microsoft.VisualStudio.TestTools.UnitTesting.TestApplicationBuilderExtensions.AddMSTest(this Microsoft.Testing.Platform.Builder.ITestApplicationBuilder! testApplicationBuilder, System.Func!>! getTestAssemblies) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.TestingPlatformBuilderHook.AddExtensions(Microsoft.Testing.Platform.Builder.ITestApplicationBuilder! testApplicationBuilder, string![]! arguments) -> void -virtual Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestMethodInfo.Invoke(object?[]? arguments) -> Microsoft.VisualStudio.TestTools.UnitTesting.TestResult! -virtual Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestMethodInfo.InvokeAsync(object?[]? arguments) -> System.Threading.Tasks.Task! diff --git a/src/Adapter/MSTest.TestAdapter/PublicAPI/uwp/PublicAPI.Shipped.txt b/src/Adapter/MSTest.TestAdapter/PublicAPI/uwp/PublicAPI.Shipped.txt index bb20af004b..078eb58f29 100644 --- a/src/Adapter/MSTest.TestAdapter/PublicAPI/uwp/PublicAPI.Shipped.txt +++ b/src/Adapter/MSTest.TestAdapter/PublicAPI/uwp/PublicAPI.Shipped.txt @@ -1,65 +1,4 @@ #nullable enable -const Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestMethodInfo.TimeoutWhenNotSet = 0 -> int -const Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.MSTestSettings.SettingsName = "MSTest" -> string! -const Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.MSTestSettings.SettingsNameAlias = "MSTestV2" -> string! -const Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.TestMethod.TotalHierarchyLevels = 4 -> int -const Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.RunConfigurationSettings.SettingsName = "RunConfiguration" -> string! -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.LogMessageListener -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.LogMessageListener.DebugTrace.get -> string? -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.LogMessageListener.Dispose() -> void -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.LogMessageListener.GetAndClearDebugTrace() -> string? -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.LogMessageListener.GetAndClearStandardError() -> string? -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.LogMessageListener.GetAndClearStandardOutput() -> string? -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.LogMessageListener.LogMessageListener(bool captureDebugTraces) -> void -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.LogMessageListener.StandardError.get -> string! -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.LogMessageListener.StandardOutput.get -> string! -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestAssemblyInfo -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestAssemblyInfo.AssemblyCleanupMethod.get -> System.Reflection.MethodInfo? -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestAssemblyInfo.AssemblyInitializationException.get -> System.Exception? -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestAssemblyInfo.AssemblyInitializeMethod.get -> System.Reflection.MethodInfo? -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestAssemblyInfo.HasExecutableCleanupMethod.get -> bool -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestAssemblyInfo.IsAssemblyInitializeExecuted.get -> bool -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestAssemblyInfo.RunAssemblyCleanup() -> string? -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestAssemblyInfo.RunAssemblyInitialize(Microsoft.VisualStudio.TestTools.UnitTesting.TestContext! testContext) -> void -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestClassInfo -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestClassInfo.BaseClassCleanupMethodsStack.get -> System.Collections.Generic.Stack! -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestClassInfo.BaseClassInitAndCleanupMethods.get -> System.Collections.Generic.Queue!>! -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestClassInfo.BaseTestCleanupMethodsQueue.get -> System.Collections.Generic.Queue! -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestClassInfo.BaseTestInitializeMethodsQueue.get -> System.Collections.Generic.Queue! -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestClassInfo.ClassAttribute.get -> Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute! -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestClassInfo.ClassCleanupException.get -> System.Exception? -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestClassInfo.ClassCleanupMethod.get -> System.Reflection.MethodInfo? -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestClassInfo.ClassInitializationException.get -> System.Exception? -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestClassInfo.ClassInitializeMethod.get -> System.Reflection.MethodInfo? -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestClassInfo.ClassType.get -> System.Type! -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestClassInfo.Constructor.get -> System.Reflection.ConstructorInfo! -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestClassInfo.HasExecutableCleanupMethod.get -> bool -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestClassInfo.IsClassCleanupExecuted.get -> bool -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestClassInfo.IsClassInitializeExecuted.get -> bool -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestClassInfo.Parent.get -> Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestAssemblyInfo! -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestClassInfo.RunClassCleanup(Microsoft.VisualStudio.TestTools.UnitTesting.ClassCleanupBehavior classCleanupLifecycle = Microsoft.VisualStudio.TestTools.UnitTesting.ClassCleanupBehavior.EndOfAssembly) -> string? -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestClassInfo.RunClassInitialize(Microsoft.VisualStudio.TestTools.UnitTesting.TestContext! testContext) -> void -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestClassInfo.TestCleanupMethod.get -> System.Reflection.MethodInfo? -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestClassInfo.TestContextProperty.get -> System.Reflection.PropertyInfo? -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestClassInfo.TestInitializeMethod.get -> System.Reflection.MethodInfo? -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestExecutionManager -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestExecutionManager.RunTests(System.Collections.Generic.IEnumerable! tests, Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter.IRunContext? runContext, Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter.IFrameworkHandle! frameworkHandle, Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.TestRunCancellationToken! runCancellationToken) -> void -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestExecutionManager.RunTests(System.Collections.Generic.IEnumerable! sources, Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter.IRunContext? runContext, Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter.IFrameworkHandle! frameworkHandle, Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.TestRunCancellationToken! cancellationToken) -> void -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestExecutionManager.TestExecutionManager() -> void -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestMethodInfo -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestMethodInfo.Arguments.get -> object?[]? -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestMethodInfo.GetAllAttributes(bool inherit) -> System.Attribute![]? -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestMethodInfo.GetAttributes(bool inherit) -> TAttributeType![]! -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestMethodInfo.IsRunnable.get -> bool -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestMethodInfo.IsTimeoutSet.get -> bool -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestMethodInfo.MethodInfo.get -> System.Reflection.MethodInfo! -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestMethodInfo.NotRunnableReason.get -> string? -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestMethodInfo.ParameterTypes.get -> System.Reflection.ParameterInfo![]! -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestMethodInfo.ReturnType.get -> System.Type! -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestMethodInfo.TestClassName.get -> string! -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestMethodInfo.TestMethodName.get -> string! -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Extensions.TestResultExtensions -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Extensions.UnitTestOutcomeExtensions Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.MSTestDiscoverer Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.MSTestDiscoverer.DiscoverTests(System.Collections.Generic.IEnumerable! sources, Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter.IDiscoveryContext! discoveryContext, Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging.IMessageLogger! logger, Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter.ITestCaseDiscoverySink! discoverySink) -> void Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.MSTestDiscoverer.MSTestDiscoverer() -> void @@ -70,80 +9,3 @@ Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.MSTestExecutor.RunTests(S Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.MSTestExecutor.RunTests(System.Collections.Generic.IEnumerable? sources, Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter.IRunContext? runContext, Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter.IFrameworkHandle? frameworkHandle) -> void Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.MSTestExecutor.TestExecutionManager.get -> Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestExecutionManager! Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.MSTestExecutor.TestExecutionManager.set -> void -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.MSTestSettings -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.MSTestSettings.CaptureDebugTraces.get -> bool -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.MSTestSettings.ClassCleanupLifecycle.get -> Microsoft.VisualStudio.TestTools.UnitTesting.ClassCleanupBehavior? -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.MSTestSettings.DisableParallelization.get -> bool -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.MSTestSettings.EnableBaseClassTestMethodsFromOtherAssemblies.get -> bool -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.MSTestSettings.ForcedLegacyMode.get -> bool -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.MSTestSettings.MapInconclusiveToFailed.get -> bool -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.MSTestSettings.MapNotRunnableToFailed.get -> bool -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.MSTestSettings.MSTestSettings() -> void -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.MSTestSettings.ParallelizationScope.get -> Microsoft.VisualStudio.TestTools.UnitTesting.ExecutionScope? -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.MSTestSettings.ParallelizationWorkers.get -> int? -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.MSTestSettings.TestSettingsFile.get -> string? -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.MSTestSettings.TestTimeout.get -> int -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.MSTestSettings.TreatClassAndAssemblyCleanupWarningsAsErrors.get -> bool -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.MSTestSettings.TreatDiscoveryWarningsAsErrors.get -> bool -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.TestMethod -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.TestMethod.AssemblyName.get -> string! -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.TestMethod.DeclaringAssemblyName.get -> string? -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.TestMethod.DeclaringAssemblyName.set -> void -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.TestMethod.DeclaringClassFullName.get -> string? -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.TestMethod.DeclaringClassFullName.set -> void -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.TestMethod.FullClassName.get -> string! -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.TestMethod.HasManagedMethodAndTypeProperties.get -> bool -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.TestMethod.Hierarchy.get -> System.Collections.Generic.IReadOnlyCollection! -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.TestMethod.IsAsync.get -> bool -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.TestMethod.ManagedMethodName.get -> string? -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.TestMethod.ManagedTypeName.get -> string? -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.TestMethod.Name.get -> string! -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.TestMethod.TestIdGenerationStrategy.get -> Microsoft.VisualStudio.TestTools.UnitTesting.TestIdGenerationStrategy -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.TestMethod.TestMethod(string! name, string! fullClassName, string! assemblyName, bool isAsync) -> void -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestOutcome -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestOutcome.Error = 0 -> Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestOutcome -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestOutcome.Failed = 1 -> Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestOutcome -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestOutcome.Ignored = 4 -> Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestOutcome -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestOutcome.Inconclusive = 3 -> Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestOutcome -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestOutcome.InProgress = 8 -> Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestOutcome -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestOutcome.NotFound = 7 -> Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestOutcome -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestOutcome.NotRunnable = 5 -> Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestOutcome -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestOutcome.Passed = 6 -> Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestOutcome -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestOutcome.Timeout = 2 -> Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestOutcome -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestResult -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestResult.DatarowIndex.get -> int -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestResult.DebugTrace.get -> string? -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestResult.DisplayName.get -> string? -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestResult.Duration.get -> System.TimeSpan -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestResult.ErrorColumnNumber.get -> int -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestResult.ErrorFilePath.get -> string? -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestResult.ErrorLineNumber.get -> int -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestResult.ErrorMessage.get -> string? -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestResult.ErrorStackTrace.get -> string? -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestResult.ExecutionId.get -> System.Guid -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestResult.InnerResultsCount.get -> int -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestResult.Outcome.get -> Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestOutcome -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestResult.ParentExecId.get -> System.Guid -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestResult.ResultFiles.get -> System.Collections.Generic.IList? -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestResult.StandardError.get -> string? -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestResult.StandardOut.get -> string? -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestResult.TestContextMessages.get -> string? -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.RunConfigurationSettings -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.RunConfigurationSettings.CollectSourceInformation.get -> bool -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.RunConfigurationSettings.RunConfigurationSettings() -> void -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.TestRunCancellationToken -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.TestRunCancellationToken.Cancel() -> void -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.TestRunCancellationToken.Canceled.get -> bool -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.TestRunCancellationToken.Register(System.Action! callback) -> void -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.TestRunCancellationToken.TestRunCancellationToken() -> void -Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.TestRunCancellationToken.Unregister() -> void -static Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Extensions.TestResultExtensions.ToUnitTestResults(this Microsoft.VisualStudio.TestTools.UnitTesting.TestResult![]! testResults) -> Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestResult![]! -static Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Extensions.UnitTestOutcomeExtensions.ToUnitTestOutcome(this Microsoft.VisualStudio.TestTools.UnitTesting.UnitTestOutcome frameworkTestOutcome) -> Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestOutcome -static Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.MSTestSettings.CurrentSettings.get -> Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.MSTestSettings! -static Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.MSTestSettings.IsLegacyScenario(Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging.IMessageLogger! logger) -> bool -static Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.MSTestSettings.PopulateSettings(Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.MSTestSettings! settings) -> void -static Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.MSTestSettings.PopulateSettings(Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter.IDiscoveryContext? context) -> void -static Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.MSTestSettings.RunConfigurationSettings.get -> Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.RunConfigurationSettings! -static Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.RunConfigurationSettings.PopulateSettings(Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter.IDiscoveryContext? context) -> Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.RunConfigurationSettings! -virtual Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestMethodInfo.Invoke(object?[]? arguments) -> Microsoft.VisualStudio.TestTools.UnitTesting.TestResult! -virtual Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestMethodInfo.InvokeAsync(object?[]? arguments) -> System.Threading.Tasks.Task! diff --git a/src/Adapter/MSTest.TestAdapter/Resources/Resource.Designer.cs b/src/Adapter/MSTest.TestAdapter/Resources/Resource.Designer.cs deleted file mode 100644 index 8daf3f194b..0000000000 --- a/src/Adapter/MSTest.TestAdapter/Resources/Resource.Designer.cs +++ /dev/null @@ -1,888 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:4.0.30319.42000 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter { - using System; - - - /// - /// A strongly-typed resource class, for looking up localized strings, etc. - /// - // This class was auto-generated by the StronglyTypedResourceBuilder - // class via a tool like ResGen or Visual Studio. - // To add or remove a member, edit your .ResX file then rerun ResGen - // with the /str option, or rebuild your VS project. - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - internal class Resource { - - private static global::System.Resources.ResourceManager resourceMan; - - private static global::System.Globalization.CultureInfo resourceCulture; - - [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - internal Resource() { - } - - /// - /// Returns the cached ResourceManager instance used by this class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Resources.ResourceManager ResourceManager { - get { - if (object.ReferenceEquals(resourceMan, null)) { - global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Resources.Resource", typeof(Resource).Assembly); - resourceMan = temp; - } - return resourceMan; - } - } - - /// - /// Overrides the current thread's CurrentUICulture property for all - /// resource lookups using this strongly typed resource class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Globalization.CultureInfo Culture { - get { - return resourceCulture; - } - set { - resourceCulture = value; - } - } - - /// - /// Looks up a localized string similar to Assembly cleanup method '{0}.{1}' timed out after {2}ms. - /// - internal static string AssemblyCleanupTimedOut { - get { - return ResourceManager.GetString("AssemblyCleanupTimedOut", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Assembly cleanup method '{0}.{1}' was canceled. - /// - internal static string AssemblyCleanupWasCancelled { - get { - return ResourceManager.GetString("AssemblyCleanupWasCancelled", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Assembly initialize method '{0}.{1}' timed out after {2}ms. - /// - internal static string AssemblyInitializeTimedOut { - get { - return ResourceManager.GetString("AssemblyInitializeTimedOut", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Assembly initialize method '{0}.{1}' was canceled. - /// - internal static string AssemblyInitializeWasCancelled { - get { - return ResourceManager.GetString("AssemblyInitializeWasCancelled", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to MSTestAdapterV2. - /// - internal static string AttachmentSetDisplayName { - get { - return ResourceManager.GetString("AttachmentSetDisplayName", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Exception occurred while enumerating IDataSource attribute on "{0}.{1}": {2}. - /// - internal static string CannotEnumerateIDataSourceAttribute { - get { - return ResourceManager.GetString("CannotEnumerateIDataSourceAttribute", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Exception occurred while expanding IDataSource rows from attribute on "{0}.{1}": {2}. - /// - internal static string CannotExpandIDataSourceAttribute { - get { - return ResourceManager.GetString("CannotExpandIDataSourceAttribute", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Data on index {0} for "{1}" cannot be serialized. All data provided through "IDataSource" should be serializable. If you need to test non-serializable data sources, please make sure you add "TestDataSourceDiscovery" attribute on your test assembly and set the discovery option to "DuringExecution".. - /// - internal static string CannotExpandIDataSourceAttribute_CannotSerialize { - get { - return ResourceManager.GetString("CannotExpandIDataSourceAttribute_CannotSerialize", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Display name "{2}" on indexes {0} and {1} are duplicate. Display names should be unique.. - /// - internal static string CannotExpandIDataSourceAttribute_DuplicateDisplayName { - get { - return ResourceManager.GetString("CannotExpandIDataSourceAttribute_DuplicateDisplayName", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Cannot run test method '{0}.{1}': Test data doesn't match method parameters. Either the count or types are different. - ///Test expected {2} parameter(s), with types '{3}', - ///but received {4} argument(s), with types '{5}'.. - /// - internal static string CannotRunTestArgumentsMismatchError { - get { - return ResourceManager.GetString("CannotRunTestArgumentsMismatchError", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Cannot run test method '{0}.{1}': Method has parameters, but does not define any test source. Use '[DataRow]', '[DynamicData]', or a custom 'ITestDataSource' data source to provide test data.. - /// - internal static string CannotRunTestMethodNoDataError { - get { - return ResourceManager.GetString("CannotRunTestMethodNoDataError", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Class cleanup method '{0}.{1}' timed out after {2}ms. - /// - internal static string ClassCleanupTimedOut { - get { - return ResourceManager.GetString("ClassCleanupTimedOut", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Class cleanup method '{0}.{1}' was canceled. - /// - internal static string ClassCleanupWasCancelled { - get { - return ResourceManager.GetString("ClassCleanupWasCancelled", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Class initialize method '{0}.{1}' timed out after {2}ms. - /// - internal static string ClassInitializeTimedOut { - get { - return ResourceManager.GetString("ClassInitializeTimedOut", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Class initialize method '{0}.{1}' was canceled. - /// - internal static string ClassInitializeWasCancelled { - get { - return ResourceManager.GetString("ClassInitializeWasCancelled", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to MSTestAdapter failed to discover tests in class '{0}' of assembly '{1}' because {2}.. - /// - internal static string CouldNotInspectTypeDuringDiscovery { - get { - return ResourceManager.GetString("CouldNotInspectTypeDuringDiscovery", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to {0} (Data Row {1}). - /// - internal static string DataDrivenResultDisplayName { - get { - return ResourceManager.GetString("DataDrivenResultDisplayName", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Debug Trace:. - /// - internal static string DebugTraceBanner { - get { - return ResourceManager.GetString("DebugTraceBanner", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to [MSTest][Discovery][{0}] {1}. - /// - internal static string DiscoveryWarning { - get { - return ResourceManager.GetString("DiscoveryWarning", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Both '.runsettings' and '.testconfig.json' files have been detected. Please select only one of these test configuration files.. - /// - internal static string DuplicateConfigurationError { - get { - return ResourceManager.GetString("DuplicateConfigurationError", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to {0}: {1}. - /// - internal static string EnumeratorLoadTypeErrorFormat { - get { - return ResourceManager.GetString("EnumeratorLoadTypeErrorFormat", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to "{0}": (Failed to get exception description due to an exception of type "{1}".. - /// - internal static string ExceptionOccuredWhileGettingTheExceptionDescription { - get { - return ResourceManager.GetString("ExceptionOccuredWhileGettingTheExceptionDescription", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Exceptions thrown:. - /// - internal static string ExceptionsThrown { - get { - return ResourceManager.GetString("ExceptionsThrown", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Test '{0}' was canceled. - /// - internal static string Execution_Test_Cancelled { - get { - return ResourceManager.GetString("Execution_Test_Cancelled", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Test '{0}' timed out after {1}ms. - /// - internal static string Execution_Test_Timeout { - get { - return ResourceManager.GetString("Execution_Test_Timeout", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Getting custom attributes for type {0} threw exception (will ignore and use the reflection way): {1}. - /// - internal static string FailedToGetCustomAttribute { - get { - return ResourceManager.GetString("FailedToGetCustomAttribute", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The type of the generic parameter '{0}' could not be inferred.. - /// - internal static string GenericParameterCantBeInferred { - get { - return ResourceManager.GetString("GenericParameterCantBeInferred", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The generic test method '{0}' doesn't have arguments, so the generic parameter cannot be inferred.. - /// - internal static string GenericParameterCantBeInferredBecauseNoArguments { - get { - return ResourceManager.GetString("GenericParameterCantBeInferredBecauseNoArguments", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Found two conflicting types for generic parameter '{0}'. The conflicting types are '{1}' and '{2}'.. - /// - internal static string GenericParameterConflict { - get { - return ResourceManager.GetString("GenericParameterConflict", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}.. - /// - internal static string InvalidClassCleanupLifecycleValue { - get { - return ResourceManager.GetString("InvalidClassCleanupLifecycleValue", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}.. - /// - internal static string InvalidParallelScopeValue { - get { - return ResourceManager.GetString("InvalidParallelScopeValue", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer.. - /// - internal static string InvalidParallelWorkersValue { - get { - return ResourceManager.GetString("InvalidParallelWorkersValue", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Invalid settings '{0}'. Unexpected XmlAttribute: '{1}'.. - /// - internal static string InvalidSettingsXmlAttribute { - get { - return ResourceManager.GetString("InvalidSettingsXmlAttribute", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Invalid settings '{0}'. Unexpected XmlElement: '{1}'.. - /// - internal static string InvalidSettingsXmlElement { - get { - return ResourceManager.GetString("InvalidSettingsXmlElement", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Invalid value '{0}' for runsettings entry '{1}', setting will be ignored.. - /// - internal static string InvalidValue { - get { - return ResourceManager.GetString("InvalidValue", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Warning : A testsettings file or a vsmdi file is not supported with the MSTest V2 Adapter.. - /// - internal static string LegacyScenariosNotSupportedWarning { - get { - return ResourceManager.GetString("LegacyScenariosNotSupportedWarning", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to An older version of MSTestV2 package is loaded in assembly, test discovery might fail to discover all data tests if they depend on `.runsettings` file.. - /// - internal static string OlderTFMVersionFound { - get { - return ResourceManager.GetString("OlderTFMVersionFound", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Running tests in any of the provided sources is not supported for the selected platform. - /// - internal static string SourcesNotSupported { - get { - return ResourceManager.GetString("SourcesNotSupported", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Runsettings entry '<ExecutionApartmentState>STA</ExecutionApartmentState>' is not supported on non-Windows OSes.. - /// - internal static string STAIsOnlySupportedOnWindowsWarning { - get { - return ResourceManager.GetString("STAIsOnlySupportedOnWindowsWarning", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Failed to discover tests from assembly {0}. Reason:{1}. - /// - internal static string TestAssembly_AssemblyDiscoveryFailure { - get { - return ResourceManager.GetString("TestAssembly_AssemblyDiscoveryFailure", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to File does not exist: {0}. - /// - internal static string TestAssembly_FileDoesNotExist { - get { - return ResourceManager.GetString("TestAssembly_FileDoesNotExist", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Test cleanup method '{0}.{1}' timed out after {2}ms. - /// - internal static string TestCleanupTimedOut { - get { - return ResourceManager.GetString("TestCleanupTimedOut", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Test cleanup method '{0}.{1}' was canceled. - /// - internal static string TestCleanupWasCancelled { - get { - return ResourceManager.GetString("TestCleanupWasCancelled", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to TestContext cannot be Null.. - /// - internal static string TestContextIsNull { - get { - return ResourceManager.GetString("TestContextIsNull", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to TestContext Messages:. - /// - internal static string TestContextMessageBanner { - get { - return ResourceManager.GetString("TestContextMessageBanner", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Test initialize method '{0}.{1}' timed out after {2}ms. - /// - internal static string TestInitializeTimedOut { - get { - return ResourceManager.GetString("TestInitializeTimedOut", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Test initialize method '{0}.{1}' was canceled. - /// - internal static string TestInitializeWasCancelled { - get { - return ResourceManager.GetString("TestInitializeWasCancelled", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Test method {0} was not found.. - /// - internal static string TestNotFound { - get { - return ResourceManager.GetString("TestNotFound", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}). - /// - internal static string TestParallelizationBanner { - get { - return ResourceManager.GetString("TestParallelizationBanner", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Unable to load types from the test source '{0}'. Some or all of the tests in this source may not be discovered. - ///Error: {1}. - /// - internal static string TypeLoadFailed { - get { - return ResourceManager.GetString("TypeLoadFailed", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Assembly Cleanup method {0}.{1} failed. Error Message: {2}. StackTrace: {3}. - /// - internal static string UTA_AssemblyCleanupMethodWasUnsuccesful { - get { - return ResourceManager.GetString("UTA_AssemblyCleanupMethodWasUnsuccesful", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Assembly Initialization method {0}.{1} threw exception. {2}: {3}. Aborting test execution.. - /// - internal static string UTA_AssemblyInitMethodThrows { - get { - return ResourceManager.GetString("UTA_AssemblyInitMethodThrows", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Class Cleanup method {0}.{1} failed. Error Message: {2}. Stack Trace: {3}. - /// - internal static string UTA_ClassCleanupMethodWasUnsuccesful { - get { - return ResourceManager.GetString("UTA_ClassCleanupMethodWasUnsuccesful", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Class Initialization method {0}.{1} threw exception. {2}: {3}.. - /// - internal static string UTA_ClassInitMethodThrows { - get { - return ResourceManager.GetString("UTA_ClassInitMethodThrows", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'.. - /// - internal static string UTA_ClassOrAssemblyCleanupMethodHasWrongSignature { - get { - return ResourceManager.GetString("UTA_ClassOrAssemblyCleanupMethodHasWrongSignature", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should take a single parameter of type TestContext. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'.. - /// - internal static string UTA_ClassOrAssemblyInitializeMethodHasWrongSignature { - get { - return ResourceManager.GetString("UTA_ClassOrAssemblyInitializeMethodHasWrongSignature", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to TestCleanup method {0}.{1} threw exception. {2}.. - /// - internal static string UTA_CleanupMethodThrows { - get { - return ResourceManager.GetString("UTA_CleanupMethodThrows", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Error calling Test Cleanup method for test class {0}: {1}. - /// - internal static string UTA_CleanupMethodThrowsGeneralError { - get { - return ResourceManager.GetString("UTA_CleanupMethodThrowsGeneralError", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to TestCleanup Stack Trace. - /// - internal static string UTA_CleanupStackTrace { - get { - return ResourceManager.GetString("UTA_CleanupStackTrace", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to --- End of inner exception stack trace ---. - /// - internal static string UTA_EndOfInnerExceptionTrace { - get { - return ResourceManager.GetString("UTA_EndOfInnerExceptionTrace", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to UTA007: Method {1} defined in class {0} does not have correct signature. Test method marked with the [TestMethod] attribute must be non-static, public, return-type as void and should not take any parameter. Example: public void Test.Class1.Test(). Additionally, if you are using async-await in test method then return-type must be 'Task' or 'ValueTask'. Example: public async Task Test.Class1.Test2(). - /// - internal static string UTA_ErrorIncorrectTestMethodSignature { - get { - return ResourceManager.GetString("UTA_ErrorIncorrectTestMethodSignature", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to UTA031: class {0} does not have valid TestContext property. TestContext must be of type TestContext, must be non-static, and must be public. For example: public TestContext TestContext.. - /// - internal static string UTA_ErrorInValidTestContextSignature { - get { - return ResourceManager.GetString("UTA_ErrorInValidTestContextSignature", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to UTA054: {0}.{1} has invalid Timeout attribute. The timeout must be an integer value greater than 0.. - /// - internal static string UTA_ErrorInvalidTimeout { - get { - return ResourceManager.GetString("UTA_ErrorInvalidTimeout", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to UTA014: {0}: Cannot define more than one method with the AssemblyCleanup attribute inside an assembly.. - /// - internal static string UTA_ErrorMultiAssemblyClean { - get { - return ResourceManager.GetString("UTA_ErrorMultiAssemblyClean", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to UTA013: {0}: Cannot define more than one method with the AssemblyInitialize attribute inside an assembly.. - /// - internal static string UTA_ErrorMultiAssemblyInit { - get { - return ResourceManager.GetString("UTA_ErrorMultiAssemblyInit", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to UTA026: {0}: Cannot define more than one method with the ClassCleanup attribute inside a class.. - /// - internal static string UTA_ErrorMultiClassClean { - get { - return ResourceManager.GetString("UTA_ErrorMultiClassClean", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to UTA025: {0}: Cannot define more than one method with the ClassInitialize attribute inside a class.. - /// - internal static string UTA_ErrorMultiClassInit { - get { - return ResourceManager.GetString("UTA_ErrorMultiClassInit", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to UTA024: {0}: Cannot define more than one method with the TestCleanup attribute.. - /// - internal static string UTA_ErrorMultiClean { - get { - return ResourceManager.GetString("UTA_ErrorMultiClean", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to UTA018: {0}: Cannot define more than one method with the TestInitialize attribute.. - /// - internal static string UTA_ErrorMultiInit { - get { - return ResourceManager.GetString("UTA_ErrorMultiInit", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to UTA001: TestClass attribute defined on non-public class {0}. - /// - internal static string UTA_ErrorNonPublicTestClass { - get { - return ResourceManager.GetString("UTA_ErrorNonPublicTestClass", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to UTA023: {0}: Cannot define predefined property {2} on method {1}.. - /// - internal static string UTA_ErrorPredefinedTestProperty { - get { - return ResourceManager.GetString("UTA_ErrorPredefinedTestProperty", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to TestClass attribute defined on generic non-abstract class {0}. - /// - internal static string UTA_ErrorTestClassIsGenericNonAbstract { - get { - return ResourceManager.GetString("UTA_ErrorTestClassIsGenericNonAbstract", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to UTA021: {0}: Null or empty custom property defined on method {1}. The custom property must have a valid name.. - /// - internal static string UTA_ErrorTestPropertyNullOrEmpty { - get { - return ResourceManager.GetString("UTA_ErrorTestPropertyNullOrEmpty", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to An unhandled exception was thrown by the 'Execute' method. Please report this error to the author of the attribute '{0}'. - ///{1}. - /// - internal static string UTA_ExecuteThrewException { - get { - return ResourceManager.GetString("UTA_ExecuteThrewException", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The ExpectedException attribute defined on test method {0}.{1} threw an exception during construction. - ///{2}. - /// - internal static string UTA_ExpectedExceptionAttributeConstructionException { - get { - return ResourceManager.GetString("UTA_ExpectedExceptionAttributeConstructionException", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Failed to obtain the exception thrown by test method {0}.{1}.. - /// - internal static string UTA_FailedToGetTestMethodException { - get { - return ResourceManager.GetString("UTA_FailedToGetTestMethodException", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Initialization method {0}.{1} threw exception. {2}.. - /// - internal static string UTA_InitMethodThrows { - get { - return ResourceManager.GetString("UTA_InitMethodThrows", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Unable to create instance of class {0}. Error: {1}.. - /// - internal static string UTA_InstanceCreationError { - get { - return ResourceManager.GetString("UTA_InstanceCreationError", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Method {0}.{1} does not exist.. - /// - internal static string UTA_MethodDoesNotExists { - get { - return ResourceManager.GetString("UTA_MethodDoesNotExists", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The test method {0}.{1} has multiple attributes derived from '{2}' defined on it. Only one such attribute is allowed.. - /// - internal static string UTA_MultipleAttributesOnTestMethod { - get { - return ResourceManager.GetString("UTA_MultipleAttributesOnTestMethod", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Error in executing test. No result returned by extension. If using extension of TestMethodAttribute then please contact vendor.. - /// - internal static string UTA_NoTestResult { - get { - return ResourceManager.GetString("UTA_NoTestResult", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Cannot find a valid constructor for test class '{0}'. Valid constructors are 'public' and either parameterless or with one parameter of type 'TestContext'.. - /// - internal static string UTA_NoValidConstructor { - get { - return ResourceManager.GetString("UTA_NoValidConstructor", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Unable to find property {0}.TestContext. Error:{1}.. - /// - internal static string UTA_TestContextLoadError { - get { - return ResourceManager.GetString("UTA_TestContextLoadError", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Unable to set TestContext property for the class {0}. Error: {1}.. - /// - internal static string UTA_TestContextSetError { - get { - return ResourceManager.GetString("UTA_TestContextSetError", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The {0}.TestContext has incorrect type.. - /// - internal static string UTA_TestContextTypeMismatchLoadError { - get { - return ResourceManager.GetString("UTA_TestContextTypeMismatchLoadError", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Method {0}.{1} has wrong signature. The method must be non-static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'.. - /// - internal static string UTA_TestInitializeAndCleanupMethodHasWrongSignature { - get { - return ResourceManager.GetString("UTA_TestInitializeAndCleanupMethodHasWrongSignature", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Test method {0}.{1} threw exception: - ///{2}. - /// - internal static string UTA_TestMethodThrows { - get { - return ResourceManager.GetString("UTA_TestMethodThrows", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Unable to get type {0}. Error: {1}.. - /// - internal static string UTA_TypeLoadError { - get { - return ResourceManager.GetString("UTA_TypeLoadError", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The called code threw an exception that was caught, but the exception value was null. - /// - internal static string UTA_UserCodeThrewNullValueException { - get { - return ResourceManager.GetString("UTA_UserCodeThrewNullValueException", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to {0} For UWP projects, if you are using UI objects in test consider using [UITestMethod] attribute instead of [TestMethod] to execute test in UI thread.. - /// - internal static string UTA_WrongThread { - get { - return ResourceManager.GetString("UTA_WrongThread", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to (Failed to get the message for an exception of type {0} due to an exception.). - /// - internal static string UTF_FailedToGetExceptionMessage { - get { - return ResourceManager.GetString("UTF_FailedToGetExceptionMessage", resourceCulture); - } - } - } -} diff --git a/src/Adapter/MSTest.TestAdapter/Resources/Resource.resx b/src/Adapter/MSTest.TestAdapter/Resources/Resource.resx deleted file mode 100644 index 2d8bfb92aa..0000000000 --- a/src/Adapter/MSTest.TestAdapter/Resources/Resource.resx +++ /dev/null @@ -1,418 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - Test '{0}' timed out after {1}ms - - - Running tests in any of the provided sources is not supported for the selected platform - - - TestCleanup method {0}.{1} threw exception. {2}. - - - --- End of inner exception stack trace --- - - - UTA014: {0}: Cannot define more than one method with the AssemblyCleanup attribute inside an assembly. - - - UTA013: {0}: Cannot define more than one method with the AssemblyInitialize attribute inside an assembly. - - - UTA026: {0}: Cannot define more than one method with the ClassCleanup attribute inside a class. - - - UTA025: {0}: Cannot define more than one method with the ClassInitialize attribute inside a class. - - - UTA024: {0}: Cannot define more than one method with the TestCleanup attribute. - - - UTA018: {0}: Cannot define more than one method with the TestInitialize attribute. - - - Initialization method {0}.{1} threw exception. {2}. - - - Unable to create instance of class {0}. Error: {1}. - - - Unable to set TestContext property for the class {0}. Error: {1}. - - - (Failed to get the message for an exception of type {0} due to an exception.) - - - UTA031: class {0} does not have valid TestContext property. TestContext must be of type TestContext, must be non-static, and must be public. For example: public TestContext TestContext. - - - UTA001: TestClass attribute defined on non-public class {0} - - - MSTestAdapter failed to discover tests in class '{0}' of assembly '{1}' because {2}. - - - {0}: {1} - - - Unable to load types from the test source '{0}'. Some or all of the tests in this source may not be discovered. -Error: {1} - - - File does not exist: {0} - - - UTA007: Method {1} defined in class {0} does not have correct signature. Test method marked with the [TestMethod] attribute must be non-static, public, return-type as void and should not take any parameter. Example: public void Test.Class1.Test(). Additionally, if you are using async-await in test method then return-type must be 'Task' or 'ValueTask'. Example: public async Task Test.Class1.Test2() - - - TestContext cannot be Null. - - - Assembly Cleanup method {0}.{1} failed. Error Message: {2}. StackTrace: {3} - - - Assembly Initialization method {0}.{1} threw exception. {2}: {3}. Aborting test execution. - - - Class Cleanup method {0}.{1} failed. Error Message: {2}. Stack Trace: {3} - - - Class Initialization method {0}.{1} threw exception. {2}: {3}. - - - An unhandled exception was thrown by the 'Execute' method. Please report this error to the author of the attribute '{0}'. -{1} - - - Error in executing test. No result returned by extension. If using extension of TestMethodAttribute then please contact vendor. - - - Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. - - - Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should take a single parameter of type TestContext. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. - - - UTA054: {0}.{1} has invalid Timeout attribute. The timeout must be an integer value greater than 0. - - - UTA023: {0}: Cannot define predefined property {2} on method {1}. - - - UTA021: {0}: Null or empty custom property defined on method {1}. The custom property must have a valid name. - - - Method {0}.{1} does not exist. - - - Cannot find a valid constructor for test class '{0}'. Valid constructors are 'public' and either parameterless or with one parameter of type 'TestContext'. - - - Unable to find property {0}.TestContext. Error:{1}. - - - The {0}.TestContext has incorrect type. - - - Method {0}.{1} has wrong signature. The method must be non-static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. - - - Unable to get type {0}. Error: {1}. - - - Test method {0} was not found. - - - Debug Trace: - - - Failed to obtain the exception thrown by test method {0}.{1}. - - - Test method {0}.{1} threw exception: -{2} - - - {0} For UWP projects, if you are using UI objects in test consider using [UITestMethod] attribute instead of [TestMethod] to execute test in UI thread. - - - MSTestAdapterV2 - - - Invalid settings '{0}'. Unexpected XmlAttribute: '{1}'. - - - Invalid settings '{0}'. Unexpected XmlElement: '{1}'. - - - {0} (Data Row {1}) - - - The ExpectedException attribute defined on test method {0}.{1} threw an exception during construction. -{2} - - - The test method '{0}.{1}' has multiple attributes derived from '{2}' defined on it. Only one such attribute is allowed. - - - Warning : A testsettings file or a vsmdi file is not supported with the MSTest V2 Adapter. - - - TestContext Messages: - - - Error calling Test Cleanup method for test class {0}: {1} - - - TestCleanup Stack Trace - - - [MSTest][Discovery][{0}] {1} - - - Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) - `Workers` is a setting name that shouldn't be localized. 'Scope' is a setting name that shouldn't be localized. - - - Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. - 'Scope' is a setting name that shouldn't be localized. - - - Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. - 'ClassCleanupLifecycle' is a setting name that shouldn't be localized. - - - Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. - `Workers` is a setting name that shouldn't be localized. - - - Failed to discover tests from assembly {0}. Reason:{1} - - - Cannot run test method '{0}.{1}': Method has parameters, but does not define any test source. Use '[DataRow]', '[DynamicData]', or a custom 'ITestDataSource' data source to provide test data. - - - Test '{0}' was canceled - - - Exception occurred while enumerating IDataSource attribute on "{0}.{1}": {2} - {0}: TypeName with namespace, -{1}: Method name, -{2}: Exception details - - - "{0}": (Failed to get exception description due to an exception of type "{1}". - {0}: Type of the original exception that we're trying to get the description of. -{1}: Thrown exception - - - Exceptions thrown: - This is usually precedes by TestAssembly_AssemblyDiscoveryFailure message, and preceded by list of exceptions thrown in a test discovery session. - - - Getting custom attributes for type {0} threw exception (will ignore and use the reflection way): {1} - {0}: Attribute full type name. -{1}: Exception description - - - An older version of MSTestV2 package is loaded in assembly, test discovery might fail to discover all data tests if they depend on `.runsettings` file. - - - The called code threw an exception that was caught, but the exception value was null - - - Exception occurred while expanding IDataSource rows from attribute on "{0}.{1}": {2} - {0}: TypeName with namespace, -{1}: Method name, -{2}: CannotExpandIDataSourceAttribute_DuplicateDisplayName or CannotExpandIDataSourceAttribute_CannotSerialize - - - Display name "{2}" on indexes {0} and {1} are duplicate. Display names should be unique. - {0}, {1}: Zero based index if an element inside of an array -{2}: Test display name. - - - Data on index {0} for "{1}" cannot be serialized. All data provided through "IDataSource" should be serializable. If you need to test non-serializable data sources, please make sure you add "TestDataSourceDiscovery" attribute on your test assembly and set the discovery option to "DuringExecution". - {0}: Zero based index if an element inside of an array, -{1}: Test name - - - Assembly initialize method '{0}.{1}' timed out after {2}ms - - - Assembly initialize method '{0}.{1}' was canceled - - - Class initialize method '{0}.{1}' timed out after {2}ms - - - Class initialize method '{0}.{1}' was canceled - - - TestClass attribute defined on generic non-abstract class {0} - - - Assembly cleanup method '{0}.{1}' timed out after {2}ms - - - Assembly cleanup method '{0}.{1}' was canceled - - - Class cleanup method '{0}.{1}' timed out after {2}ms - - - Class cleanup method '{0}.{1}' was canceled - - - Test cleanup method '{0}.{1}' timed out after {2}ms - - - Test cleanup method '{0}.{1}' was canceled - - - Test initialize method '{0}.{1}' timed out after {2}ms - - - Test initialize method '{0}.{1}' was canceled - - - Runsettings entry '<ExecutionApartmentState>STA</ExecutionApartmentState>' is not supported on non-Windows OSes. - - - Cannot run test method '{0}.{1}': Test data doesn't match method parameters. Either the count or types are different. -Test expected {2} parameter(s), with types '{3}', -but received {4} argument(s), with types '{5}'. - - - Invalid value '{0}' for runsettings entry '{1}', setting will be ignored. - - - Both '.runsettings' and '.testconfig.json' files have been detected. Please select only one of these test configuration files. - - - The type of the generic parameter '{0}' could not be inferred. - - - The generic test method '{0}' doesn't have arguments, so the generic parameter cannot be inferred. - - - Found two conflicting types for generic parameter '{0}'. The conflicting types are '{1}' and '{2}'. - - diff --git a/src/Adapter/MSTest.TestAdapter/Resources/xlf/Resource.cs.xlf b/src/Adapter/MSTest.TestAdapter/Resources/xlf/Resource.cs.xlf deleted file mode 100644 index 53651299cc..0000000000 --- a/src/Adapter/MSTest.TestAdapter/Resources/xlf/Resource.cs.xlf +++ /dev/null @@ -1,482 +0,0 @@ - - - - - - Assembly cleanup method '{0}.{1}' timed out after {2}ms - Po {2} ms vypršel časový limit metody čištění sestavení {0}.{1}. - - - - Assembly cleanup method '{0}.{1}' was canceled - Metoda čištění sestavení {0}.{1} byla zrušena. - - - - Assembly initialize method '{0}.{1}' timed out after {2}ms - Po {2} ms vypršel časový limit metody inicializace sestavení {0}.{1}. - - - - Assembly initialize method '{0}.{1}' was canceled - Metoda inicializace sestavení {0}.{1} byla zrušena. - - - - Cannot run test method '{0}.{1}': Test data doesn't match method parameters. Either the count or types are different. -Test expected {2} parameter(s), with types '{3}', -but received {4} argument(s), with types '{5}'. - Testovací metodu {0}.{1} nejde spustit: Testovací data neodpovídají parametrům metody. Liší se počet nebo typy. -Pro test se očekával tento počet parametrů: {2} s typy {3}, -byl však přijat tento počet argumentů: {4} s typy {5}. - - - - Cannot run test method '{0}.{1}': Method has parameters, but does not define any test source. Use '[DataRow]', '[DynamicData]', or a custom 'ITestDataSource' data source to provide test data. - Nelze spustit testovací metodu {0}.{1}: Metoda má parametry, ale nedefinuje žádný zdroj testu. K poskytování testovacích dat použijte zdroj dat [DataRow] nebo [DynamicData], případně vlastní zdroj dat ITestDataSource. - - - - Class cleanup method '{0}.{1}' timed out after {2}ms - Po {2} ms vypršel časový limit metody čištění třídy {0}.{1}. - - - - Class cleanup method '{0}.{1}' was canceled - Metoda čištění třídy {0}.{1} byla zrušena. - - - - Class initialize method '{0}.{1}' timed out after {2}ms - Po {2} ms vypršel časový limit metody inicializace třídy {0}.{1}. - - - - Class initialize method '{0}.{1}' was canceled - Metoda inicializace třídy {0}.{1} byla zrušena. - - - - Both '.runsettings' and '.testconfig.json' files have been detected. Please select only one of these test configuration files. - Byly zjištěny soubory .runsettings i .testconfig.json. Vyberte prosím jenom jeden z těchto souborů konfigurace testu. - - - - Test '{0}' timed out after {1}ms - Časový limit '{0}' testu vypršel po {1}ms. - - - - The type of the generic parameter '{0}' could not be inferred. - Typ obecného parametru '{0}' nelze odvodit. - - - - The generic test method '{0}' doesn't have arguments, so the generic parameter cannot be inferred. - Obecná testovací metoda '{0}' nemá argumenty, takže obecný parametr nelze odvodit. - - - - Found two conflicting types for generic parameter '{0}'. The conflicting types are '{1}' and '{2}'. - Byly nalezeny dva konfliktní typy pro obecný parametr '{0}'. Konfliktní typy jsou '{1}' a '{2}'. - - - - Invalid value '{0}' for runsettings entry '{1}', setting will be ignored. - Neplatná hodnota {0} pro položku runsettings {1}. Nastavení bude ignorováno. - - - - Runsettings entry '<ExecutionApartmentState>STA</ExecutionApartmentState>' is not supported on non-Windows OSes. - Položka runsettings <ExecutionApartmentState>STA</ExecutionApartmentState> se v operačních systémech jiných než Windows nepodporuje. - - - - Running tests in any of the provided sources is not supported for the selected platform - Spouštění testů v některém z uvedených zdrojů se pro vybranou platformu nepodporuje. - - - - Test cleanup method '{0}.{1}' timed out after {2}ms - Po {2} ms vypršel časový limit metody čištění testu {0}.{1}. - - - - Test cleanup method '{0}.{1}' was canceled - Metoda čištění testu {0}.{1} byla zrušena. - - - - Test initialize method '{0}.{1}' timed out after {2}ms - Po {2} ms vypršel časový limit metody inicializace testu {0}.{1}. - - - - Test initialize method '{0}.{1}' was canceled - Metoda inicializace testu {0}.{1} byla zrušena. - - - - TestCleanup method {0}.{1} threw exception. {2}. - Metoda TestCleanup {0}.{1} vyvolala výjimku. {2}. - - - - --- End of inner exception stack trace --- - --- Konec trasování zásobníku pro vnitřní výjimku --- - - - - UTA014: {0}: Cannot define more than one method with the AssemblyCleanup attribute inside an assembly. - UTA014: {0}: V jednom sestavení nejde definovat více jak jednu metodu s atributem AssemblyCleanup. - - - - UTA013: {0}: Cannot define more than one method with the AssemblyInitialize attribute inside an assembly. - UTA013: {0}: V jednom sestavení nejde definovat více jak jednu metodu s atributem AssemblyInitialize. - - - - UTA026: {0}: Cannot define more than one method with the ClassCleanup attribute inside a class. - UTA026: {0}: Uvnitř třídy nejde definovat více jak jednu metodu s atributem ClassCleanup. - - - - UTA025: {0}: Cannot define more than one method with the ClassInitialize attribute inside a class. - UTA025: {0}: Uvnitř třídy nejde definovat více jak jednu metodu s atributem ClassInitialize. - - - - UTA024: {0}: Cannot define more than one method with the TestCleanup attribute. - UTA024: {0}: Nejde definovat více jak jednu metodu s atributem TestCleanup. - - - - UTA018: {0}: Cannot define more than one method with the TestInitialize attribute. - UTA018: {0}: Nejde definovat více jak jednu metodu s atributem TestInitialize. - - - - TestClass attribute defined on generic non-abstract class {0} - Atribut TestClass definovaný u obecné neabstraktní třídy {0} - - - - Initialization method {0}.{1} threw exception. {2}. - Inicializační metoda {0}.{1} způsobila výjimku. {2}. - - - - Unable to create instance of class {0}. Error: {1}. - Nepodařilo se vytvořit instanci třídy {0}. Chyba: {1}. - - - - The test method '{0}.{1}' has multiple attributes derived from '{2}' defined on it. Only one such attribute is allowed. - Testovací metoda {0}.{1} má definovaných více atributů odvozených od atributu {2}. Povolený je jenom jeden takový atribut. - - - - Cannot find a valid constructor for test class '{0}'. Valid constructors are 'public' and either parameterless or with one parameter of type 'TestContext'. - Nelze najít platný konstruktor pro testovací třídu {0}. Platné konstruktory jsou public a buď bez parametrů, nebo s jedním parametrem typu TestContext. - - - - Unable to set TestContext property for the class {0}. Error: {1}. - Pro třídu {0} se nepodařilo nastavit vlastnost TestContext. Chyba: {1}. - - - - (Failed to get the message for an exception of type {0} due to an exception.) - (Z důvodu výjimky se nepodařilo získat zprávu o výjimce typu {0}.) - - - - UTA031: class {0} does not have valid TestContext property. TestContext must be of type TestContext, must be non-static, and must be public. For example: public TestContext TestContext. - UTA031: Třída {0} nemá platnou vlastnost TestContext. Vlastnost TestContext musí být typu TestContext, musí být nestatická a musí být veřejná. Například: public TestContext TestContext - - - - UTA001: TestClass attribute defined on non-public class {0} - UTA001: Atribut TestClass se definoval v neveřejné třídě {0}. - - - - MSTestAdapter failed to discover tests in class '{0}' of assembly '{1}' because {2}. - MSTestAdapter nezjistil v třídě {0} sestavení {1} žádný test, protože: {2}. - - - - {0}: {1} - {0}: {1} - - - - Unable to load types from the test source '{0}'. Some or all of the tests in this source may not be discovered. -Error: {1} - Nepovedlo se načíst typy ze zdroje testu {0}. Je možné, že se některé nebo všechny testy v tomto zdroji nezjistily. -Chyba: {1} - - - - File does not exist: {0} - Neexistující soubor: {0} - - - - UTA007: Method {1} defined in class {0} does not have correct signature. Test method marked with the [TestMethod] attribute must be non-static, public, return-type as void and should not take any parameter. Example: public void Test.Class1.Test(). Additionally, if you are using async-await in test method then return-type must be 'Task' or 'ValueTask'. Example: public async Task Test.Class1.Test2() - UTA007: Metoda {1} definovaná ve třídě {0} nemá správný podpis. Testovací metoda označená atributem [TestMethod] nesmí být static ani public, musí mít návratový typ void a nesmí přijímat žádný parametr. Například: public void Test.Class1.Test(). Pokud navíc v testovací metodě používáte operátor async-await, musí být návratový typ Task nebo ValueTask. Například: public async Task Test.Class1.Test2() - - - - TestContext cannot be Null. - TestContext nemůže být Null. - - - - Assembly Cleanup method {0}.{1} failed. Error Message: {2}. StackTrace: {3} - Čisticí metoda sestavení {0}.{1} selhala. Chybová zpráva: {2}. Trasování zásobníku: {3} - - - - Assembly Initialization method {0}.{1} threw exception. {2}: {3}. Aborting test execution. - Inicializační metoda sestavení {0}.{1} vyvolala výjimku. {2}: {3}. Přerušuje se provádění testu. - - - - Class Cleanup method {0}.{1} failed. Error Message: {2}. Stack Trace: {3} - Čisticí metoda třídy {0}.{1} selhala. Chybová zpráva: {2}. Trasování zásobníku: {3} - - - - Class Initialization method {0}.{1} threw exception. {2}: {3}. - Inicializační metoda třídy {0}.{1} vyvolala výjimku. {2}: {3}. - - - - An unhandled exception was thrown by the 'Execute' method. Please report this error to the author of the attribute '{0}'. -{1} - Metoda Execute vyvolala neošetřenou výjimku. Nahlaste prosím tuto chybu autorovi '{0}' atributu. -{1} - - - - Error in executing test. No result returned by extension. If using extension of TestMethodAttribute then please contact vendor. - Při provádění testu došlo k chybě. Rozšíření nevrátilo žádný výsledek. Pokud používáte rozšíření třídy TestMethodAttribute, obraťte se na dodavatele. - - - - Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. - Metoda {0}.{1} má špatný podpis. Metoda musí být static nebo public, nevrací hodnotu a nesmí přijímat žádný parametr. Pokud navíc v metodě používáte operátor async-await, musí být návratový typ Task nebo ValueTask. - - - - Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should take a single parameter of type TestContext. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. - Metoda {0}.{1} má špatný podpis. Metoda musí být static nebo public, nevrací hodnotu a musí přijímat jeden parametr typu TestContext. Pokud navíc v metodě používáte operátor async-await, musí být návratový typ Task nebo ValueTask. - - - - UTA054: {0}.{1} has invalid Timeout attribute. The timeout must be an integer value greater than 0. - UTA054: {0}.{1} má neplatný atribut Timeout. Hodnota timeline musí být celé číslo větší než 0. - - - - UTA023: {0}: Cannot define predefined property {2} on method {1}. - UTA023: {0}: V metodě {1} nejde definovat předdefinovanou vlastnost {2}. - - - - UTA021: {0}: Null or empty custom property defined on method {1}. The custom property must have a valid name. - UTA021: {0}: V metodě {1} je definovaná vlastní vlastnost, která je null nebo je prázdná. Vlastní vlastnost musí mít platný název. - - - - Method {0}.{1} does not exist. - Metoda {0}.{1} neexistuje. - - - - Unable to find property {0}.TestContext. Error:{1}. - Nepodařilo se najít vlastnost {0}.TestContext. Chyba:{1}. - - - - The {0}.TestContext has incorrect type. - {0}.TestContext má nesprávný typ. - - - - Method {0}.{1} has wrong signature. The method must be non-static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. - Metoda {0}.{1} má špatný podpis. Metoda nesmí být static nebo public, nevrací hodnotu a nesmí přijímat žádný parametr. Pokud navíc v metodě používáte operátor async-await, musí být návratový typ Task nebo ValueTask. - - - - Unable to get type {0}. Error: {1}. - Nepodařilo se získat typ {0}. Chyba: {1}. - - - - Test method {0} was not found. - Testovací metoda {0} se nenašla. - - - - Debug Trace: - Trasování ladění: - - - - Failed to obtain the exception thrown by test method {0}.{1}. - Nepovedlo se získat výjimku vyvolanou testovací metodou {0}.{1}. - - - - Test method {0}.{1} threw exception: -{2} - V testovací metodě {0}.{1} došlo k výjimce: -{2} - - - - {0} For UWP projects, if you are using UI objects in test consider using [UITestMethod] attribute instead of [TestMethod] to execute test in UI thread. - {0}. Pokud v testu používáte objekty uživatelského rozhraní, zvažte u projektů pro platformu UPW použití atributu [UITestMethod] místo atributu [TestMethod], aby se test provedl ve vlákně uživatelského rozhraní. - - - - MSTestAdapterV2 - MSTestAdapterV2 - - - - Invalid settings '{0}'. Unexpected XmlAttribute: '{1}'. - Neplatné nastavení {0}. Neočekávaný XmlAttribute: {1}. - - - - Invalid settings '{0}'. Unexpected XmlElement: '{1}'. - Neplatné nastavení {0}. Neočekávaný XmlElement: {1}. - - - - {0} (Data Row {1}) - {0} (datový řádek {1}) - - - - The ExpectedException attribute defined on test method {0}.{1} threw an exception during construction. -{2} - Atribut ExpectedException definovaný u testovací metody {0}.{1} vyvolal během vytváření výjimku. -{2} - - - - Warning : A testsettings file or a vsmdi file is not supported with the MSTest V2 Adapter. - Upozornění: Adaptér MSTest V2 nepodporuje soubor testsettings ani vsmdi. - - - - TestContext Messages: - Zprávy pro TestContext: - - - - Error calling Test Cleanup method for test class {0}: {1} - Při volání čisticí metody testu pro třídu {0} došlo k chybě: {1} - - - - TestCleanup Stack Trace - Trasování zásobníku čištění testu - - - - [MSTest][Discovery][{0}] {1} - [MSTest][Discovery][{0}] {1} - - - - Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) - Je povolená paralelizace testu pro {0} (pracovní procesy: {1}, obor: {2}). - `Workers` is a setting name that shouldn't be localized. 'Scope' is a setting name that shouldn't be localized. - - - Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. - Pro Obor je zadaná neplatná hodnota {0}. Podporované obory jsou {1}. - 'Scope' is a setting name that shouldn't be localized. - - - Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. - Pro Pracovní procesy je zadaná neplatná hodnota {0}. Hodnota by měla být nezáporné celé číslo. - `Workers` is a setting name that shouldn't be localized. - - - Failed to discover tests from assembly {0}. Reason:{1} - Nepovedlo se zjistit testy ze sestavení {0}. Důvod:{1} - - - - Test '{0}' was canceled - Testovací '{0}' se zrušila. - - - - Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. - Pro classCleanupLifecycle byla zadána neplatná hodnota {0}. Podporované obory jsou {1}. - 'ClassCleanupLifecycle' is a setting name that shouldn't be localized. - - - Exception occurred while enumerating IDataSource attribute on "{0}.{1}": {2} - Při vytváření výčtu atributu IDataSource došlo k výjimce. „{0}.{1}“: {2} - {0}: TypeName with namespace, -{1}: Method name, -{2}: Exception details - - - "{0}": (Failed to get exception description due to an exception of type "{1}". - „{0}“: (Nepodařilo se získat popis výjimky z důvodu výjimky typu „{1}“. - {0}: Type of the original exception that we're trying to get the description of. -{1}: Thrown exception - - - Exceptions thrown: - Vyvolané výjimky: - This is usually precedes by TestAssembly_AssemblyDiscoveryFailure message, and preceded by list of exceptions thrown in a test discovery session. - - - Getting custom attributes for type {0} threw exception (will ignore and use the reflection way): {1} - Získání vlastních atributů pro typ {0} vyvolalo výjimku (bude ignorovat a používat způsob reflexe): {1} - {0}: Attribute full type name. -{1}: Exception description - - - An older version of MSTestV2 package is loaded in assembly, test discovery might fail to discover all data tests if they depend on `.runsettings` file. - V sestavení je načtena starší verze balíčku MSTestV2. Zjišťování testů může selhat při zjišťování všech testů dat, pokud jsou závislé na souboru .runsettings. - - - - The called code threw an exception that was caught, but the exception value was null - Volaný kód vyvolal výjimku, která byla zachycena, ale její hodnota byla null. - - - - Exception occurred while expanding IDataSource rows from attribute on "{0}.{1}": {2} - Došlo k výjimce při rozbalování řádků IDataSource z atributu na „{0}.{1}“: {2} - {0}: TypeName with namespace, -{1}: Method name, -{2}: CannotExpandIDataSourceAttribute_DuplicateDisplayName or CannotExpandIDataSourceAttribute_CannotSerialize - - - Display name "{2}" on indexes {0} and {1} are duplicate. Display names should be unique. - Zobrazovaný název „{2}“ u indexů {0} a {1} je duplicitní. Zobrazované názvy by měly být jedinečné. - {0}, {1}: Zero based index if an element inside of an array -{2}: Test display name. - - - Data on index {0} for "{1}" cannot be serialized. All data provided through "IDataSource" should be serializable. If you need to test non-serializable data sources, please make sure you add "TestDataSourceDiscovery" attribute on your test assembly and set the discovery option to "DuringExecution". - Data v {0} indexu pro „{1}“ nelze serializovat. Všechna data poskytnutá prostřednictvím „IDataSource“ by měla být serializovatelná. Pokud potřebujete testovat neserializovatelné zdroje dat, nezapomeňte do testovacího sestavení přidat atribut TestDataSourceDiscovery a nastavit možnost zjišťování na „DuringExecution“. - {0}: Zero based index if an element inside of an array, -{1}: Test name - - - - \ No newline at end of file diff --git a/src/Adapter/MSTest.TestAdapter/Resources/xlf/Resource.de.xlf b/src/Adapter/MSTest.TestAdapter/Resources/xlf/Resource.de.xlf deleted file mode 100644 index 458b366659..0000000000 --- a/src/Adapter/MSTest.TestAdapter/Resources/xlf/Resource.de.xlf +++ /dev/null @@ -1,482 +0,0 @@ - - - - - - Assembly cleanup method '{0}.{1}' timed out after {2}ms - Timeout der Assemblybereinigungsmethode "{0}.{1}" nach {2} ms - - - - Assembly cleanup method '{0}.{1}' was canceled - Die Assemblybereinigungsmethode "{0}.{1}" wurde abgebrochen - - - - Assembly initialize method '{0}.{1}' timed out after {2}ms - Timeout der Assemblyinitialisierungsmethode "{0}.{1}" nach {2} ms - - - - Assembly initialize method '{0}.{1}' was canceled - Die Assemblyinitialisierungsmethode "{0}.{1}" wurde abgebrochen - - - - Cannot run test method '{0}.{1}': Test data doesn't match method parameters. Either the count or types are different. -Test expected {2} parameter(s), with types '{3}', -but received {4} argument(s), with types '{5}'. - Die Testmethode „{0}.{1}“ kann nicht ausgeführt werden: Testdaten stimmen nicht mit Methodenparametern überein. Die Anzahl oder die Typen unterscheiden sich. -Test erwartete {2} Parameter mit den Typen „{3}“, -aber empfing {4} Argument(e) mit den Typen „{5}“. - - - - Cannot run test method '{0}.{1}': Method has parameters, but does not define any test source. Use '[DataRow]', '[DynamicData]', or a custom 'ITestDataSource' data source to provide test data. - Die Testmethode „{0}.{1}“ kann nicht ausgeführt werden: Die Methode verfügt über Parameter, definiert jedoch keine Testquelle. Verwenden Sie „[DataRow]“, „[DynamicData]“ oder eine benutzerdefinierte „ITestDataSource-Datenquelle“, um Testdaten bereitzustellen. - - - - Class cleanup method '{0}.{1}' timed out after {2}ms - Timeout der Klassenbereinigungsmethode "{0}.{1}" nach {2} ms - - - - Class cleanup method '{0}.{1}' was canceled - Die Klassenbereinigungsmethode "{0}.{1}" wurde abgebrochen - - - - Class initialize method '{0}.{1}' timed out after {2}ms - Timeout der Klasseninitialisierungsmethode "{0}.{1}" nach {2} ms - - - - Class initialize method '{0}.{1}' was canceled - Die Initialisierungsmethode "{0}.{1}" der Klasse wurde abgebrochen - - - - Both '.runsettings' and '.testconfig.json' files have been detected. Please select only one of these test configuration files. - Es wurden sowohl die Dateien „.runsettings“ als auch „.testconfig.json“ erkannt. Wählen Sie nur eine dieser Testkonfigurationsdateien aus. - - - - Test '{0}' timed out after {1}ms - Timeout bei test '{0}' nach {1}ms. - - - - The type of the generic parameter '{0}' could not be inferred. - Der Typ des generischen Parameters '{0}' konnte nicht abgeleitet werden. - - - - The generic test method '{0}' doesn't have arguments, so the generic parameter cannot be inferred. - Die generische Testmethode '{0}' hat keine Argumente, daher kann der generische Parameter nicht abgeleitet werden. - - - - Found two conflicting types for generic parameter '{0}'. The conflicting types are '{1}' and '{2}'. - Es wurden zwei in Konflikt stehende Typen für den generischen Parameter '{0}' gefunden. Die in Konflikt stehenden Typen sind '{1}' und '{2}'. - - - - Invalid value '{0}' for runsettings entry '{1}', setting will be ignored. - Ungültiger Wert "{0}" für runsettings-Eintrag "{1}". Die Einstellung wird ignoriert. - - - - Runsettings entry '<ExecutionApartmentState>STA</ExecutionApartmentState>' is not supported on non-Windows OSes. - Der Eintrag "<ExecutionApartmentState>STA</ExecutionApartmentState>" der Ausführungseinstellungen wird auf Nicht-Windows-Betriebssystemen nicht unterstützt. - - - - Running tests in any of the provided sources is not supported for the selected platform - Das Ausführen von Tests in einer der angegebenen Quellen wird für die ausgewählte Plattform nicht unterstützt. - - - - Test cleanup method '{0}.{1}' timed out after {2}ms - Timeout der Testbereinigungsmethode "{0}.{1}" nach {2} ms - - - - Test cleanup method '{0}.{1}' was canceled - Die Testbereinigungsmethode "{0}.{1}" wurde abgebrochen - - - - Test initialize method '{0}.{1}' timed out after {2}ms - Timeout der Testinitialisierungsmethode "{0}.{1}" nach {2} ms - - - - Test initialize method '{0}.{1}' was canceled - Die Testinitialisierungsmethode "{0}.{1}" wurde abgebrochen - - - - TestCleanup method {0}.{1} threw exception. {2}. - Die TestCleanup-Methode "{0}.{1}" hat eine Ausnahme ausgelöst. {2}. - - - - --- End of inner exception stack trace --- - --- Ende der internen Ausnahmestapelüberwachung --- - - - - UTA014: {0}: Cannot define more than one method with the AssemblyCleanup attribute inside an assembly. - UTA014: {0}: Es darf nur eine Methode mit dem Attribut 'AssemblyCleanup' innerhalb einer Assembly definiert werden. - - - - UTA013: {0}: Cannot define more than one method with the AssemblyInitialize attribute inside an assembly. - UTA013: {0}: Es darf nur eine Methode mit dem Attribut 'AssemblyInitialize' innerhalb einer Assembly definiert werden. - - - - UTA026: {0}: Cannot define more than one method with the ClassCleanup attribute inside a class. - UTA026: {0}: Es darf nur eine Methode mit dem Attribut 'ClassCleanup' innerhalb einer Klasse definiert werden. - - - - UTA025: {0}: Cannot define more than one method with the ClassInitialize attribute inside a class. - UTA025: {0}: Es darf nur eine Methode mit dem Attribut 'ClassInitialize' innerhalb einer Klasse definiert werden. - - - - UTA024: {0}: Cannot define more than one method with the TestCleanup attribute. - UTA024: {0}: Es darf nur eine Methode mit dem Attribut 'TestCleanup' definiert werden. - - - - UTA018: {0}: Cannot define more than one method with the TestInitialize attribute. - UTA018: {0}: Es darf nur eine Methode mit dem Attribut 'TestInitialize' definiert werden. - - - - TestClass attribute defined on generic non-abstract class {0} - TestClass-Attribut für generische nicht abstrakte Klasse {0} definiert - - - - Initialization method {0}.{1} threw exception. {2}. - Die Initialisierungsmethode '{0}.{1}' hat eine Ausnahme ausgelöst. {2}. - - - - Unable to create instance of class {0}. Error: {1}. - Es kann keine Instanz der Klasse '{0}' erstellt werden. Fehler: {1}. - - - - The test method '{0}.{1}' has multiple attributes derived from '{2}' defined on it. Only one such attribute is allowed. - Für die Testmethode „{0}.{1}“ sind mehrere Attribute definiert, die von „{2}“ abgeleitet sind. Nur ein einziges solches Attribut ist zulässig. - - - - Cannot find a valid constructor for test class '{0}'. Valid constructors are 'public' and either parameterless or with one parameter of type 'TestContext'. - Es wurde kein gültiger Konstruktor für die Testklasse "{0}" gefunden. Gültige Konstruktoren sind "public" und entweder parameterlos oder mit einem Parameter vom Typ "TestContext". - - - - Unable to set TestContext property for the class {0}. Error: {1}. - Die Eigenschaft 'TestContext' für die Klasse '{0}' kann nicht festgelegt werden. Fehler: {1}. - - - - (Failed to get the message for an exception of type {0} due to an exception.) - (Fehler beim Abrufen der Meldung für eine Ausnahme vom Typ "{0}" aufgrund einer Ausnahme.) - - - - UTA031: class {0} does not have valid TestContext property. TestContext must be of type TestContext, must be non-static, and must be public. For example: public TestContext TestContext. - UTA031: Die Klasse {0} weist keine gültige Eigenschaft TestContext auf. TestContext muss vom Typ TestContext sein, muss nicht statisch und öffentlich sein. Beispiel: 'public TestContext TestContext'. - - - - UTA001: TestClass attribute defined on non-public class {0} - UTA001: Für die nicht öffentliche Klasse '{0}' definiertes Attribut 'TestClass'. - - - - MSTestAdapter failed to discover tests in class '{0}' of assembly '{1}' because {2}. - Fehler von 'MSTestAdapter' beim Ermitteln von Tests in der Klasse "{0}" der Assembly "{1}". Ursache: {2}. - - - - {0}: {1} - {0}: {1} - - - - Unable to load types from the test source '{0}'. Some or all of the tests in this source may not be discovered. -Error: {1} - Fehler beim Laden von Typen aus der Testquelle "{0}". Möglicherweise werden einige oder alle Tests in dieser Quelle nicht ermittelt. -Fehler: {1} - - - - File does not exist: {0} - Die Datei ist nicht vorhanden: {0} - - - - UTA007: Method {1} defined in class {0} does not have correct signature. Test method marked with the [TestMethod] attribute must be non-static, public, return-type as void and should not take any parameter. Example: public void Test.Class1.Test(). Additionally, if you are using async-await in test method then return-type must be 'Task' or 'ValueTask'. Example: public async Task Test.Class1.Test2() - UTA007: Die in der Klasse {0} definierte Methode {1} weist nicht die richtige Signatur auf. Die mit dem [TestMethod]-Attribut markierte Testmethode muss nicht statisch und öffentlich sein, muss den Rückgabetyp „void“ aufweisen und darf keine Parameter annehmen. Beispiel: public void Test.Class1.Test(). Wenn Sie außerdem in der Testmethode „async-await“ verwenden, muss der Rückgabetyp „Task“ oder „ValueTask“ sein. Beispiel: public async Task Test.Class1.Test2() - - - - TestContext cannot be Null. - "TestContext" darf nicht NULL sein. - - - - Assembly Cleanup method {0}.{1} failed. Error Message: {2}. StackTrace: {3} - Fehler bei der Methode "{0}.{1}" für die Assemblybereinigung. Fehlermeldung: {2}. "StackTrace": {3} - - - - Assembly Initialization method {0}.{1} threw exception. {2}: {3}. Aborting test execution. - Die Methode "{0}.{1}" für die Assemblyinitialisierung hat eine Ausnahme ausgelöst. {2}: {3}. Die Ausführung des Tests wird abgebrochen. - - - - Class Cleanup method {0}.{1} failed. Error Message: {2}. Stack Trace: {3} - Fehler bei der Methode "{0}.{1}" für die Klassenbereinigung. Fehlermeldung: {2}. Stapelüberwachung: {3} - - - - Class Initialization method {0}.{1} threw exception. {2}: {3}. - Die Methode "{0}.{1}" für die Klasseninitialisierung hat eine Ausnahme ausgelöst. {2}: {3}. - - - - An unhandled exception was thrown by the 'Execute' method. Please report this error to the author of the attribute '{0}'. -{1} - Von der Methode "Execute" wurde eine nicht behandelte Ausnahme ausgelöst. Melden Sie diesen Fehler dem Autor des Attributs '{0}'. -{1} - - - - Error in executing test. No result returned by extension. If using extension of TestMethodAttribute then please contact vendor. - Fehler beim Ausführen des Tests. Von der Extension wurde kein Ergebnis zurückgegeben. Wenn Sie eine Extension von "TestMethodAttribute" verwenden, wenden Sie sich bitte an den Anbieter. - - - - Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. - Die Methode „{0}.{1}“ weist eine falsche Signatur auf. Die Methode muss statisch und öffentlich sein. Sie darf keinen Wert zurückgeben und keinen Parameter annehmen. Wenn Sie außerdem in der Methode „async-await“ verwenden, muss der Rückgabetyp „Task“ oder „ValueTask“ sein. - - - - Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should take a single parameter of type TestContext. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. - Die Methode „{0}.{1}“ weist eine falsche Signatur auf. Die Methode muss statisch und öffentlich sein. Sie darf keinen Wert zurückgeben und muss einen einzigen Parameter des Typs TestContext annehmen. Wenn Sie außerdem in der Methode „async-await“ verwenden, muss der Rückgabetyp „Task“ oder „ValueTask“ sein. - - - - UTA054: {0}.{1} has invalid Timeout attribute. The timeout must be an integer value greater than 0. - UTA054: {0}.{1} weist ein ungültiges Attribut „Timeout“ auf. Timeout muss eine ganze Zahl größer als 0 sein. - - - - UTA023: {0}: Cannot define predefined property {2} on method {1}. - UTA023: {0}: Die vordefinierte Eigenschaft "{2}" kann nicht für die Methode "{1}" definiert werden. - - - - UTA021: {0}: Null or empty custom property defined on method {1}. The custom property must have a valid name. - UTA021: {0}: Für die Methode "{1}" wurde eine benutzerdefinierte Eigenschaft mit dem Wert NULL oder eine benutzerdefinierte leere Eigenschaft definiert. Die benutzerdefinierte Eigenschaft muss einen gültigen Namen aufweisen. - - - - Method {0}.{1} does not exist. - Die Methode "{0}.{1}" ist nicht vorhanden. - - - - Unable to find property {0}.TestContext. Error:{1}. - Die Eigenschaft "{0}.TestContext" wurde nicht gefunden. Fehler: {1}. - - - - The {0}.TestContext has incorrect type. - "{0}.TestContext" weist einen falschen Typ auf. - - - - Method {0}.{1} has wrong signature. The method must be non-static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. - Die Methode „{0}.{1}“ weist eine falsche Signatur auf. Die Methode muss nicht statisch und öffentlich sein, und sie darf keinen Wert zurückgeben und keinen Parameter annehmen. Wenn Sie außerdem in der Methode „async-await“ verwenden, muss der Rückgabetyp „Task“ oder „ValueTask“ sein. - - - - Unable to get type {0}. Error: {1}. - Der Typ "{0}" kann nicht abgerufen werden. Fehler: {1}. - - - - Test method {0} was not found. - Die Testmethode "{0}" wurde nicht gefunden. - - - - Debug Trace: - Debugablaufverfolgung: - - - - Failed to obtain the exception thrown by test method {0}.{1}. - Fehler beim Abrufen der von der Testmethode "{0}.{1}" ausgelösten Ausnahme. - - - - Test method {0}.{1} threw exception: -{2} - Die Testmethode "{0}.{1}" hat eine Ausnahme ausgelöst: -{2} - - - - {0} For UWP projects, if you are using UI objects in test consider using [UITestMethod] attribute instead of [TestMethod] to execute test in UI thread. - {0}: Erwägen Sie für UWP-Projekte bei Einsatz von UI-Objekten im Test die Verwendung des [UITestMethod]-Attributs anstelle von "[TestMethod]", um den Test im UI-Thread auszuführen. - - - - MSTestAdapterV2 - MSTestAdapterV2 - - - - Invalid settings '{0}'. Unexpected XmlAttribute: '{1}'. - Ungültige Einstellungen "{0}". Unerwartetes XmlAttribute: "{1}". - - - - Invalid settings '{0}'. Unexpected XmlElement: '{1}'. - Ungültige Einstellungen "{0}". Unerwartetes XmlElement: "{1}". - - - - {0} (Data Row {1}) - {0} (Datenzeile {1}) - - - - The ExpectedException attribute defined on test method {0}.{1} threw an exception during construction. -{2} - Das für die Testmethode "{0}.{1}" definierte ExpectedException-Attribut hat während der Konstruktion eine Ausnahme ausgelöst. -{2} - - - - Warning : A testsettings file or a vsmdi file is not supported with the MSTest V2 Adapter. - Warnung: Eine TESTSETTINGS-Datei oder eine VSMDI-Datei wird vom MSTest-V2-Adapter nicht unterstützt. - - - - TestContext Messages: - TestContext-Meldungen: - - - - Error calling Test Cleanup method for test class {0}: {1} - Fehler beim Aufruf der Testbereinigungsmethode für die Testklasse "{0}": {1} - - - - TestCleanup Stack Trace - TestCleanup-Stapelüberwachung - - - - [MSTest][Discovery][{0}] {1} - [MSTest][Discovery][{0}] {1} - - - - Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) - Testparallelisierung aktiviert für {0} (Worker: {1}, Bereich: {2}) - `Workers` is a setting name that shouldn't be localized. 'Scope' is a setting name that shouldn't be localized. - - - Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. - Ungültiger Wert "{0}" für "Scope" angegeben. Unterstützte Bereiche: {1}. - 'Scope' is a setting name that shouldn't be localized. - - - Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. - Ungültiger Wert "{0}" für "Workers" angegeben. Der Wert muss eine nicht negative Ganzzahl sein. - `Workers` is a setting name that shouldn't be localized. - - - Failed to discover tests from assembly {0}. Reason:{1} - Fehler beim Ermitteln von Tests aus der Assembly "{0}". Ursache:{1} - - - - Test '{0}' was canceled - Test '{0}' wurde abgebrochen. - - - - Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. - Für "ClassCleanupLifecycle" wurde ein ungültiger Wert "{0}" angegeben. Unterstützte Bereiche sind {1}. - 'ClassCleanupLifecycle' is a setting name that shouldn't be localized. - - - Exception occurred while enumerating IDataSource attribute on "{0}.{1}": {2} - Ausnahme beim Auflisten des IDataSource-Attributs für "{0}.{1}": {2} - {0}: TypeName with namespace, -{1}: Method name, -{2}: Exception details - - - "{0}": (Failed to get exception description due to an exception of type "{1}". - "{0}": (Fehler beim Abrufen der Ausnahmebeschreibung aufgrund einer Ausnahme vom Typ "{1}". - {0}: Type of the original exception that we're trying to get the description of. -{1}: Thrown exception - - - Exceptions thrown: - Ausgelöste Ausnahmen: - This is usually precedes by TestAssembly_AssemblyDiscoveryFailure message, and preceded by list of exceptions thrown in a test discovery session. - - - Getting custom attributes for type {0} threw exception (will ignore and use the reflection way): {1} - Beim Abrufen von benutzerdefinierten Attributen für den Typ {0} wurde Ausnahme ausgelöst (wird ignoriert und die Reflektionsart verwendet): {1} - {0}: Attribute full type name. -{1}: Exception description - - - An older version of MSTestV2 package is loaded in assembly, test discovery might fail to discover all data tests if they depend on `.runsettings` file. - Eine ältere Version des MSTestV2-Pakets wird in die Assembly geladen. Bei der Testermittlung werden möglicherweise nicht alle Datentests ermittelt, wenn sie von der Datei ".runsettings" abhängen. - - - - The called code threw an exception that was caught, but the exception value was null - Der aufgerufene Code hat eine Ausnahme ausgelöst, die abgefangen wurde, aber der Ausnahmewert war NULL. - - - - Exception occurred while expanding IDataSource rows from attribute on "{0}.{1}": {2} - Ausnahme beim Erweitern von IDataSource-Zeilen aus dem Attribut auf "{0}.{1}": {2} - {0}: TypeName with namespace, -{1}: Method name, -{2}: CannotExpandIDataSourceAttribute_DuplicateDisplayName or CannotExpandIDataSourceAttribute_CannotSerialize - - - Display name "{2}" on indexes {0} and {1} are duplicate. Display names should be unique. - Der Anzeigename "{2}" für Indizes {0} und {1} ist doppelt vorhanden. Anzeigenamen sollten eindeutig sein. - {0}, {1}: Zero based index if an element inside of an array -{2}: Test display name. - - - Data on index {0} for "{1}" cannot be serialized. All data provided through "IDataSource" should be serializable. If you need to test non-serializable data sources, please make sure you add "TestDataSourceDiscovery" attribute on your test assembly and set the discovery option to "DuringExecution". - Daten im Index {0} für "{1}" können nicht serialisiert werden. Alle über "IDataSource" bereitgestellten Daten sollten serialisierbar sein. Wenn Sie nicht serialisierbare Datenquellen testen müssen, stellen Sie sicher, dass Sie der Testassembly das Attribut "TestDataSourceDiscovery" hinzufügen und die Ermittlungsoption auf "DuringExecution" festlegen. - {0}: Zero based index if an element inside of an array, -{1}: Test name - - - - \ No newline at end of file diff --git a/src/Adapter/MSTest.TestAdapter/Resources/xlf/Resource.es.xlf b/src/Adapter/MSTest.TestAdapter/Resources/xlf/Resource.es.xlf deleted file mode 100644 index b629fb9322..0000000000 --- a/src/Adapter/MSTest.TestAdapter/Resources/xlf/Resource.es.xlf +++ /dev/null @@ -1,482 +0,0 @@ - - - - - - Assembly cleanup method '{0}.{1}' timed out after {2}ms - Método de limpieza de ensamblado '{0}.{1}' se agotó el tiempo de espera después de {2}ms - - - - Assembly cleanup method '{0}.{1}' was canceled - Método de limpieza de ensamblado "{0}.{1}" se canceló - - - - Assembly initialize method '{0}.{1}' timed out after {2}ms - Método de inicialización de ensamblado '{0}.{1}' se agotó el tiempo de espera de después de {2}ms - - - - Assembly initialize method '{0}.{1}' was canceled - Método de inicialización de ensamblado "{0}.{1}" se canceló - - - - Cannot run test method '{0}.{1}': Test data doesn't match method parameters. Either the count or types are different. -Test expected {2} parameter(s), with types '{3}', -but received {4} argument(s), with types '{5}'. - No se puede ejecutar el método de prueba "{0}.{1}": los datos de prueba no coinciden con los parámetros del método. El recuento o los tipos son diferentes. -La prueba esperaba recibir {2} parámetro(s), con los tipos "{3}", -pero recibió {4} argumento(s), con los tipos "{5}". - - - - Cannot run test method '{0}.{1}': Method has parameters, but does not define any test source. Use '[DataRow]', '[DynamicData]', or a custom 'ITestDataSource' data source to provide test data. - No se puede ejecutar el método de prueba "{0}.{1}": el método tiene parámetros, pero no define ningún origen de prueba. Use "[DataRow]", "[DynamicData]" o un origen de datos "ITestDataSource" personalizado para proporcionar datos de prueba. - - - - Class cleanup method '{0}.{1}' timed out after {2}ms - Método de limpieza de clases '{0}.{1}' se agotó el tiempo de espera después de {2}ms - - - - Class cleanup method '{0}.{1}' was canceled - Método de limpieza de clases "{0}.{1}" se canceló - - - - Class initialize method '{0}.{1}' timed out after {2}ms - Método de inicialización de clase '{0}.{1}' se agotó el tiempo de espera después de {2}ms - - - - Class initialize method '{0}.{1}' was canceled - Método de inicialización de clase "{0}.{1}" se canceló - - - - Both '.runsettings' and '.testconfig.json' files have been detected. Please select only one of these test configuration files. - Se han detectado los archivos ".runsettings" y ".testconfig.json". Seleccione solo uno de estos archivos de configuración de prueba. - - - - Test '{0}' timed out after {1}ms - Se agotó el tiempo de espera de la '{0}' de pruebas después de {1}ms - - - - The type of the generic parameter '{0}' could not be inferred. - No se pudo inferir el tipo del parámetro genérico '{0}'. - - - - The generic test method '{0}' doesn't have arguments, so the generic parameter cannot be inferred. - El método de prueba genérico '{0}' no tiene argumentos, por lo que no se puede inferir el parámetro genérico. - - - - Found two conflicting types for generic parameter '{0}'. The conflicting types are '{1}' and '{2}'. - Se encontraron dos tipos en conflicto para el parámetro genérico '{0}'. Los tipos en conflicto son '{1}' y '{2}'. - - - - Invalid value '{0}' for runsettings entry '{1}', setting will be ignored. - Valor ''{0}'' no válido para la entrada runsettings ''{1}'', se omitirá la configuración. - - - - Runsettings entry '<ExecutionApartmentState>STA</ExecutionApartmentState>' is not supported on non-Windows OSes. - La entrada runsettings "<ExecutionApartmentState>STA</ExecutionApartmentState>" no se admite en sistemas operativos que no son de Windows. - - - - Running tests in any of the provided sources is not supported for the selected platform - La ejecución de pruebas en las fuentes proporcionadas no se admite para la plataforma seleccionada - - - - Test cleanup method '{0}.{1}' timed out after {2}ms - Método de limpieza de pruebas '{0}.{1}' se agotó el tiempo de espera después de {2}ms - - - - Test cleanup method '{0}.{1}' was canceled - Método de limpieza de pruebas "{0}.{1}" se canceló - - - - Test initialize method '{0}.{1}' timed out after {2}ms - Método de inicialización de prueba '{0}.{1}' se agotó el tiempo de espera después de {2}ms - - - - Test initialize method '{0}.{1}' was canceled - Método de inicialización de prueba "{0}.{1}" se canceló - - - - TestCleanup method {0}.{1} threw exception. {2}. - El método TestCleanup {0}.{1} devolvió una excepción. {2}. - - - - --- End of inner exception stack trace --- - --- Fin del seguimiento de la pila de excepción interna --- - - - - UTA014: {0}: Cannot define more than one method with the AssemblyCleanup attribute inside an assembly. - UTA014: {0}: No se puede definir más de un método con el atributo AssemblyCleanup dentro de un ensamblado. - - - - UTA013: {0}: Cannot define more than one method with the AssemblyInitialize attribute inside an assembly. - UTA013: {0}: No se puede definir más de un método con el atributo AssemblyInitialize dentro de un ensamblado. - - - - UTA026: {0}: Cannot define more than one method with the ClassCleanup attribute inside a class. - UTA026: {0}: No se puede definir más de un método con el atributo ClassCleanup dentro de una clase. - - - - UTA025: {0}: Cannot define more than one method with the ClassInitialize attribute inside a class. - UTA025: {0}: No se puede definir más de un método con el atributo ClassInitialize dentro de una clase. - - - - UTA024: {0}: Cannot define more than one method with the TestCleanup attribute. - UTA024: {0}: No se puede definir más de un método con el atributo TestCleanup. - - - - UTA018: {0}: Cannot define more than one method with the TestInitialize attribute. - UTA018: {0}: No se puede definir más de un método con el atributo TestInitialize. - - - - TestClass attribute defined on generic non-abstract class {0} - Atributo TestClass definido en una clase genérica no abstracta {0} - - - - Initialization method {0}.{1} threw exception. {2}. - El método de inicialización {0}.{1} devolvió una excepción. {2}. - - - - Unable to create instance of class {0}. Error: {1}. - No se puede crear una instancia de la clase {0}. Error: {1}. - - - - The test method '{0}.{1}' has multiple attributes derived from '{2}' defined on it. Only one such attribute is allowed. - El método de prueba '{0}.{1}' tiene varios atributos derivados de '{2}' definidos en él. Solo se permite un atributo de este tipo. - - - - Cannot find a valid constructor for test class '{0}'. Valid constructors are 'public' and either parameterless or with one parameter of type 'TestContext'. - No se encuentra un constructor válido para la clase de prueba '{0}'. Los constructores válidos son 'public' y sin parámetros o con un parámetro de tipo 'TestContext'. - - - - Unable to set TestContext property for the class {0}. Error: {1}. - No se puede establecer la propiedad TestContext para la clase {0}. Error: {1}. - - - - (Failed to get the message for an exception of type {0} due to an exception.) - (No se pudo obtener el mensaje para una excepción del tipo {0} debido a una excepción.) - - - - UTA031: class {0} does not have valid TestContext property. TestContext must be of type TestContext, must be non-static, and must be public. For example: public TestContext TestContext. - UTA031: la clase {0}no tiene la propiedad TestContext válida. TestContext debe ser de tipo TestContext, debe ser no estática y debe ser pública. Por ejemplo: public TestContext TestContext. - - - - UTA001: TestClass attribute defined on non-public class {0} - UTA001: se ha definido el atributo TestClass en la clase no pública {0} - - - - MSTestAdapter failed to discover tests in class '{0}' of assembly '{1}' because {2}. - MSTestAdapter no detectó pruebas en la clase '{0}' del ensamblado '{1}' porque {2}. - - - - {0}: {1} - {0}: {1} - - - - Unable to load types from the test source '{0}'. Some or all of the tests in this source may not be discovered. -Error: {1} - No se pueden cargar tipos del origen de prueba "{0}". Puede que no se detecten algunas o ninguna de las pruebas de este origen. -Error: {1} - - - - File does not exist: {0} - El archivo no existe: {0} - - - - UTA007: Method {1} defined in class {0} does not have correct signature. Test method marked with the [TestMethod] attribute must be non-static, public, return-type as void and should not take any parameter. Example: public void Test.Class1.Test(). Additionally, if you are using async-await in test method then return-type must be 'Task' or 'ValueTask'. Example: public async Task Test.Class1.Test2() - UTA007: El método {1} definido en la clase {0} no tiene la firma correcta. El método de prueba marcado con el atributo [TestMethod] debe ser no estático, público, con el tipo devuelto void y no debe tomar ningún parámetro. Ejemplo: public void Test.Class1.Test(). Además, si está usando async-await en el método de prueba, entonces el tipo de valor devuelto debe ser 'Task' o 'ValueTask'. Ejemplo: public async Task Test.Class1.Test2() - - - - TestContext cannot be Null. - TestContext no será null. - - - - Assembly Cleanup method {0}.{1} failed. Error Message: {2}. StackTrace: {3} - Error de método Cleanup de ensamblado {0}.{1}. Mensaje de error: {2}. StackTrace: {3} - - - - Assembly Initialization method {0}.{1} threw exception. {2}: {3}. Aborting test execution. - Excepción método inicialización ensamblado {0}.{1}. {2}: {3}. Anulada ejecución de prueba. - - - - Class Cleanup method {0}.{1} failed. Error Message: {2}. Stack Trace: {3} - Error de método Cleanup de clase {0}.{1}. Mensaje error: {2}. Seguimiento de pila: {3} - - - - Class Initialization method {0}.{1} threw exception. {2}: {3}. - Excepción del método inicialización clase {0}. {1}. {2}: {3}. - - - - An unhandled exception was thrown by the 'Execute' method. Please report this error to the author of the attribute '{0}'. -{1} - El método 'Execute' produjo una excepción no controlada. Informe de este error al autor del atributo '{0}'. -{1} - - - - Error in executing test. No result returned by extension. If using extension of TestMethodAttribute then please contact vendor. - No se pudo ejecutar prueba. Extensión no devolvió resultados. Si usa extensión TestMethodAttribute, contacte con el proveedor. - - - - Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. - El método {0}.{1} tiene una firma incorrecta. El método debe ser estático, público, no devolver un valor y no aceptar ningún parámetro. Además, si está usando async-await en el método entonces el tipo de valor devuelto debe ser 'Task' o 'ValueTask'. - - - - Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should take a single parameter of type TestContext. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. - El método {0}.{1} tiene una firma incorrecta. El método debe ser estático, público, no devolver ningún valor y debe tomar un único parámetro de tipo TestContext. Además, si está usando async-await en el método entonces el tipo de valor devuelto debe ser 'Task' o 'ValueTask'. - - - - UTA054: {0}.{1} has invalid Timeout attribute. The timeout must be an integer value greater than 0. - UTA054: {0}.{1} tiene un atributo Timeout no válido. El tiempo de espera debe ser un valor entero mayor que 0. - - - - UTA023: {0}: Cannot define predefined property {2} on method {1}. - UTA023: {0}: no se puede definir la propiedad predefinida {2} en el método {1}. - - - - UTA021: {0}: Null or empty custom property defined on method {1}. The custom property must have a valid name. - UTA021: {0}: se ha definido una propiedad personalizada nula o vacía en el método {1}. La propiedad personalizada debe tener un nombre válido. - - - - Method {0}.{1} does not exist. - El método {0}.{1} no existe. - - - - Unable to find property {0}.TestContext. Error:{1}. - No se puede encontrar la propiedad {0}.TestContext. Error:{1}. - - - - The {0}.TestContext has incorrect type. - Tipo {0}.TestContext no es correcto. - - - - Method {0}.{1} has wrong signature. The method must be non-static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. - El método {0}.{1} tiene una firma incorrecta. Debe ser un método no estático, público, no devolver ningún valor y no debe aceptar parámetros. Además, si está usando async-await en el método entonces el tipo de valor devuelto debe ser 'Task' o 'ValueTask'. - - - - Unable to get type {0}. Error: {1}. - No se puede obtener el tipo {0}. Error: {1}. - - - - Test method {0} was not found. - No encontrado método prueba {0}. - - - - Debug Trace: - Seguimiento de depuración: - - - - Failed to obtain the exception thrown by test method {0}.{1}. - No se pudo obtener la excepción iniciada por el método de prueba {0}.{1}. - - - - Test method {0}.{1} threw exception: -{2} - Excepción método de prueba {0}.{1}: -{2} - - - - {0} For UWP projects, if you are using UI objects in test consider using [UITestMethod] attribute instead of [TestMethod] to execute test in UI thread. - {0}. En proyectos de UWP, si usa objetos de interfaz de usuario en la prueba, podría usar el atributo [UITestMethod] en lugar de [TestMethod] para ejecutar la prueba en el subproceso de interfaz de usuario. - - - - MSTestAdapterV2 - MSTestAdapterV2 - - - - Invalid settings '{0}'. Unexpected XmlAttribute: '{1}'. - Valor no válido '{0}'. XmlAttribute no esperado: '{1}'. - - - - Invalid settings '{0}'. Unexpected XmlElement: '{1}'. - Valor no válido '{0}'. XmlElement no esperado: '{1}'. - - - - {0} (Data Row {1}) - {0} (Fila de datos {1}) - - - - The ExpectedException attribute defined on test method {0}.{1} threw an exception during construction. -{2} - El atributo ExpectedException definido en el método de prueba {0}.{1} inició una excepción durante la construcción. -{2} - - - - Warning : A testsettings file or a vsmdi file is not supported with the MSTest V2 Adapter. - Advertencia: No se admite un archivo testsettings o vsmdi con el adaptador de MSTest V2. - - - - TestContext Messages: - Mensajes de TestContext: - - - - Error calling Test Cleanup method for test class {0}: {1} - Error al llamar al método Test Cleanup para la clase de prueba {0}: {1} - - - - TestCleanup Stack Trace - Seguimiento de pila de TestCleanup - - - - [MSTest][Discovery][{0}] {1} - [MSTest][Discovery][{0}] {1} - - - - Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) - Probar paralelización habilitada para {0} (Trabajos: {1}, Ámbito: {2}) - `Workers` is a setting name that shouldn't be localized. 'Scope' is a setting name that shouldn't be localized. - - - Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. - Valor no válido "{0}" especificado para "Ámbito". Los ámbitos admitidos son {1}. - 'Scope' is a setting name that shouldn't be localized. - - - Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. - Valor no válido "{0}" especificado para "Trabajadores". El valor debe ser un entero no negativo. - `Workers` is a setting name that shouldn't be localized. - - - Failed to discover tests from assembly {0}. Reason:{1} - No se pudieron detectar pruebas desde el ensamblado {0}. Motivo:{1} - - - - Test '{0}' was canceled - Se canceló la '{0}' de pruebas - - - - Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. - Valor no válido "{0}" especificado para "ClassCleanupLifecycle". Los ámbitos admitidos son {1}. - 'ClassCleanupLifecycle' is a setting name that shouldn't be localized. - - - Exception occurred while enumerating IDataSource attribute on "{0}.{1}": {2} - Excepción al enumerar el atributo IDataSource en "{0}.{1}": {2} - {0}: TypeName with namespace, -{1}: Method name, -{2}: Exception details - - - "{0}": (Failed to get exception description due to an exception of type "{1}". - "{0}": (No se pudo obtener la descripción de la excepción debido a una excepción de tipo "{1}". - {0}: Type of the original exception that we're trying to get the description of. -{1}: Thrown exception - - - Exceptions thrown: - Excepciones devueltas: - This is usually precedes by TestAssembly_AssemblyDiscoveryFailure message, and preceded by list of exceptions thrown in a test discovery session. - - - Getting custom attributes for type {0} threw exception (will ignore and use the reflection way): {1} - Al obtener atributos personalizados para el tipo {0} se produjo una excepción (se omitirá y se usará la forma de reflexión): {1} - {0}: Attribute full type name. -{1}: Exception description - - - An older version of MSTestV2 package is loaded in assembly, test discovery might fail to discover all data tests if they depend on `.runsettings` file. - Hay una versión anterior del paquete MSTestV2 cargada en el ensamblado. Es posible que la detección de pruebas no detecte todas las pruebas de datos si dependen del archivo ".runsettings". - - - - The called code threw an exception that was caught, but the exception value was null - El código llamado produjo una excepción que se detectó, pero el valor de la excepción era null - - - - Exception occurred while expanding IDataSource rows from attribute on "{0}.{1}": {2} - Se produjo una excepción al expandir las filas de IDataSource del atributo en "{0}.{1}": {2} - {0}: TypeName with namespace, -{1}: Method name, -{2}: CannotExpandIDataSourceAttribute_DuplicateDisplayName or CannotExpandIDataSourceAttribute_CannotSerialize - - - Display name "{2}" on indexes {0} and {1} are duplicate. Display names should be unique. - El nombre para mostrar "{2}" en los índices {0} y {1} están duplicados. Los nombres para mostrar deben ser únicos. - {0}, {1}: Zero based index if an element inside of an array -{2}: Test display name. - - - Data on index {0} for "{1}" cannot be serialized. All data provided through "IDataSource" should be serializable. If you need to test non-serializable data sources, please make sure you add "TestDataSourceDiscovery" attribute on your test assembly and set the discovery option to "DuringExecution". - No se pueden serializar los datos del {0} de índice para "{1}". Todos los datos proporcionados a través de "IDataSource" deben ser serializables. Si necesita probar orígenes de datos no serializables, asegúrese de agregar el atributo "TestDataSourceDiscovery" en el ensamblado de prueba y establezca la opción de detección en "DuringExecution". - {0}: Zero based index if an element inside of an array, -{1}: Test name - - - - \ No newline at end of file diff --git a/src/Adapter/MSTest.TestAdapter/Resources/xlf/Resource.fr.xlf b/src/Adapter/MSTest.TestAdapter/Resources/xlf/Resource.fr.xlf deleted file mode 100644 index 945bc54b28..0000000000 --- a/src/Adapter/MSTest.TestAdapter/Resources/xlf/Resource.fr.xlf +++ /dev/null @@ -1,482 +0,0 @@ - - - - - - Assembly cleanup method '{0}.{1}' timed out after {2}ms - La méthode de nettoyage d’assembly « {0}.{1} » a expiré après {2}ms - - - - Assembly cleanup method '{0}.{1}' was canceled - La méthode de nettoyage de l’assembly « {0}.{1} » a été annulée - - - - Assembly initialize method '{0}.{1}' timed out after {2}ms - La méthode d'initialisation de l’assembly « {0}.{1} » a expiré après {2}ms - - - - Assembly initialize method '{0}.{1}' was canceled - La méthode d’initialisation de l’assembly « {0}.{1} » a été annulée - - - - Cannot run test method '{0}.{1}': Test data doesn't match method parameters. Either the count or types are different. -Test expected {2} parameter(s), with types '{3}', -but received {4} argument(s), with types '{5}'. - Impossible d’exécuter la méthode de test « {0}.{1} » : les données de test ne correspondent pas aux paramètres de la méthode. Le nombre ou les types sont différents. -Tester le ou les paramètres de {2} attendus, avec les types « {3} », -mais a reçu {4} argument(s), avec les types « {5} ». - - - - Cannot run test method '{0}.{1}': Method has parameters, but does not define any test source. Use '[DataRow]', '[DynamicData]', or a custom 'ITestDataSource' data source to provide test data. - Impossible d’exécuter la méthode de test « {0}.{1} » : la méthode a des paramètres, mais ne définit aucune source de test. Utilisez « [DataRow] », « [DynamicData] » ou une source de données « ITestDataSource » personnalisée pour fournir des données de test. - - - - Class cleanup method '{0}.{1}' timed out after {2}ms - La méthode de nettoyage de classe « {0}.{1} » a expiré après {2}ms - - - - Class cleanup method '{0}.{1}' was canceled - La méthode de nettoyage de la classe « {0}.{1} » a été annulée - - - - Class initialize method '{0}.{1}' timed out after {2}ms - La méthode d'initialisation de la classe « {0}.{1} » a expiré après {2}ms - - - - Class initialize method '{0}.{1}' was canceled - La méthode d’initialisation de la classe « {0}.{1} » a été annulée - - - - Both '.runsettings' and '.testconfig.json' files have been detected. Please select only one of these test configuration files. - Les fichiers « .runsettings » et « .testconfig.json » ont été détectés. Veuillez sélectionner un seul de ces fichiers de configuration de test. - - - - Test '{0}' timed out after {1}ms - Délai de '{0}' de test dépassé après {1}ms - - - - The type of the generic parameter '{0}' could not be inferred. - Impossible de déduire le type du paramètre générique '{0}'. - - - - The generic test method '{0}' doesn't have arguments, so the generic parameter cannot be inferred. - La méthode de test générique '{0}' n’a pas d’arguments. Le paramètre générique ne peut donc pas être déduit. - - - - Found two conflicting types for generic parameter '{0}'. The conflicting types are '{1}' and '{2}'. - Deux types en conflit ont été trouvés pour le paramètre générique '{0}'. Les types en conflit sont '{1}' et '{2}'. - - - - Invalid value '{0}' for runsettings entry '{1}', setting will be ignored. - Valeur non valide '{0}' pour l’entrée runsettings '{1}', le paramètre sera ignoré. - - - - Runsettings entry '<ExecutionApartmentState>STA</ExecutionApartmentState>' is not supported on non-Windows OSes. - L’entrée Runsettings « <ExecutionApartmentState>STA</ExecutionApartmentState> » n’est pas prise en charge sur les systèmes d’exploitation non Windows. - - - - Running tests in any of the provided sources is not supported for the selected platform - L'exécution de tests dans l'une des sources fournies n'est pas prise en charge pour la plateforme sélectionnée - - - - Test cleanup method '{0}.{1}' timed out after {2}ms - La méthode de nettoyage de test « {0}.{1} » a expiré après {2}ms - - - - Test cleanup method '{0}.{1}' was canceled - La méthode de nettoyage du test « {0}.{1} » a été annulée - - - - Test initialize method '{0}.{1}' timed out after {2}ms - La méthode d’initialisation de test « {0}.{1} » a expiré après {2}ms - - - - Test initialize method '{0}.{1}' was canceled - La méthode d’initialisation du test « {0}.{1} » a été annulée - - - - TestCleanup method {0}.{1} threw exception. {2}. - La méthode TestCleanup {0}.{1} a levé une exception. {2}. - - - - --- End of inner exception stack trace --- - --- Fin de la trace de la pile d'exception interne --- - - - - UTA014: {0}: Cannot define more than one method with the AssemblyCleanup attribute inside an assembly. - UTA014 : {0} : impossible de définir plus d'une méthode avec l'attribut AssemblyCleanup à l'intérieur d'un assembly. - - - - UTA013: {0}: Cannot define more than one method with the AssemblyInitialize attribute inside an assembly. - UTA013 : {0} : impossible de définir plus d'une méthode avec l'attribut AssemblyInitialize à l'intérieur d'un assembly. - - - - UTA026: {0}: Cannot define more than one method with the ClassCleanup attribute inside a class. - UTA026 : {0} : impossible de définir plus d'une méthode avec l'attribut ClassCleanup à l'intérieur d'une classe. - - - - UTA025: {0}: Cannot define more than one method with the ClassInitialize attribute inside a class. - UTA025 : {0} : impossible de définir plus d'une méthode avec l'attribut ClassInitialize à l'intérieur d'une classe. - - - - UTA024: {0}: Cannot define more than one method with the TestCleanup attribute. - UTA024 : {0} : impossible de définir plus d'une méthode avec l'attribut TestCleanup. - - - - UTA018: {0}: Cannot define more than one method with the TestInitialize attribute. - UTA018 : {0} : impossible de définir plus d'une méthode avec l'attribut TestInitialize. - - - - TestClass attribute defined on generic non-abstract class {0} - Attribut TestClass défini sur une classe non abstraite générique {0} - - - - Initialization method {0}.{1} threw exception. {2}. - La méthode Initialization {0}.{1} a levé une exception. {2}. - - - - Unable to create instance of class {0}. Error: {1}. - Impossible de créer une instance de la classe {0}. Erreur : {1}. - - - - The test method '{0}.{1}' has multiple attributes derived from '{2}' defined on it. Only one such attribute is allowed. - La méthode de test « {0}.{1} » possède plusieurs attributs dérivés de « {2} » qui lui sont définis. Un seul attribut de ce type est autorisé. - - - - Cannot find a valid constructor for test class '{0}'. Valid constructors are 'public' and either parameterless or with one parameter of type 'TestContext'. - Impossible de trouver un constructeur valide pour la classe de test « {0} ». Les constructeurs valides sont « publics » et sans paramètre ou avec un paramètre de type « TestContext ». - - - - Unable to set TestContext property for the class {0}. Error: {1}. - Impossible de définir la propriété TestContext pour la classe {0}. Erreur : {1}. - - - - (Failed to get the message for an exception of type {0} due to an exception.) - (Échec de la réception du message pour une exception de type {0} en raison d'une exception.) - - - - UTA031: class {0} does not have valid TestContext property. TestContext must be of type TestContext, must be non-static, and must be public. For example: public TestContext TestContext. - UTA031 : la classe {0} n'a pas de propriété TestContext valide. TestContext doit être de type TestContext, doit être non statique et doit être public. Par exemple : public TestContext TestContext. - - - - UTA001: TestClass attribute defined on non-public class {0} - UTA001 : attribut TestClass défini sur la classe non publique {0} - - - - MSTestAdapter failed to discover tests in class '{0}' of assembly '{1}' because {2}. - MSTestAdapter n'a pas découvert de tests dans la classe '{0}' de l'assembly '{1}', car {2}. - - - - {0}: {1} - {0} : {1} - - - - Unable to load types from the test source '{0}'. Some or all of the tests in this source may not be discovered. -Error: {1} - Impossible de charger les types à partir de la source de tests '{0}'. Une partie ou l'ensemble des tests de cette source ne peuvent pas être découverts. -Erreur : {1} - - - - File does not exist: {0} - Fichier inexistant : {0} - - - - UTA007: Method {1} defined in class {0} does not have correct signature. Test method marked with the [TestMethod] attribute must be non-static, public, return-type as void and should not take any parameter. Example: public void Test.Class1.Test(). Additionally, if you are using async-await in test method then return-type must be 'Task' or 'ValueTask'. Example: public async Task Test.Class1.Test2() - UTA007 : la méthode {1} définie dans la classe {0} ne dispose pas d'une signature correcte. Une méthode de test marquée avec l'attribut [TestMethod] doit être non statique, doit utiliser void pour return-type et ne doit accepter aucun paramètre. Exemple : public void Test.Class1.Test(). En outre, si vous utilisez async-await dans la méthode test, return-type doit être « Task » ou « ValueTask ». Exemple : public async Task Test.Class1.Test2() - - - - TestContext cannot be Null. - TestContext ne peut pas être null. - - - - Assembly Cleanup method {0}.{1} failed. Error Message: {2}. StackTrace: {3} - La méthode Cleanup d'assembly {0}.{1} a échoué. Message d'erreur : {2}. StackTrace : {3} - - - - Assembly Initialization method {0}.{1} threw exception. {2}: {3}. Aborting test execution. - La méthode d'assembly Initialization {0}.{1} a levé une exception. {2} : {3}. Abandon de l'exécution de tests. - - - - Class Cleanup method {0}.{1} failed. Error Message: {2}. Stack Trace: {3} - La méthode de classe Cleanup {0}.{1} a échoué. Message d'erreur : {2}. Trace de la pile : {3} - - - - Class Initialization method {0}.{1} threw exception. {2}: {3}. - La méthode de classe Initialization {0}.{1} a levé une exception. {2} : {3}. - - - - An unhandled exception was thrown by the 'Execute' method. Please report this error to the author of the attribute '{0}'. -{1} - Une exception non gérée a été levée par la méthode 'Execute'. Signalez cette erreur à l’auteur de l’attribut '{0}'. -{1} - - - - Error in executing test. No result returned by extension. If using extension of TestMethodAttribute then please contact vendor. - Erreur lors de l'exécution du test. L'extension n'a retourné aucun résultat. Si vous utilisez l'extension de TestMethodAttribute, contactez le fournisseur. - - - - Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. - La méthode {0}.{1} présente une signature incorrecte. La méthode doit être statique, publique et ne doit retourner aucune valeur ni accepter aucun paramètre. En outre, si vous utilisez async-await dans la méthode, return-type doit être « Task » ou « ValueTask ». - - - - Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should take a single parameter of type TestContext. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. - La méthode {0}.{1} présente une signature incorrecte. La méthode doit être statique, publique et ne doit retourner aucune valeur et accepter un seul paramètre de type TestContext. En outre, si vous utilisez async-await dans la méthode, return-type doit être « Task » ou « ValueTask ». - - - - UTA054: {0}.{1} has invalid Timeout attribute. The timeout must be an integer value greater than 0. - UTA054 : {0}.{1}possède un attribut de délai d’expiration non valide. Le délai d’expiration doit être un nombre entier supérieur à 0. - - - - UTA023: {0}: Cannot define predefined property {2} on method {1}. - UTA023 : {0} : Impossible de définir la propriété prédéfinie {2} sur la méthode {1}. - - - - UTA021: {0}: Null or empty custom property defined on method {1}. The custom property must have a valid name. - UTA021 : {0} : Une propriété null ou vide personnalisée est définie sur la méthode {1}. La propriété personnalisée doit posséder un nom valide. - - - - Method {0}.{1} does not exist. - La méthode {0}.{1} n'existe pas. - - - - Unable to find property {0}.TestContext. Error:{1}. - Propriété {0}.TestContext introuvable. Erreur :{1}. - - - - The {0}.TestContext has incorrect type. - {0}.TestContext possède un type incorrect. - - - - Method {0}.{1} has wrong signature. The method must be non-static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. - La méthode {0}.{1} présente une signature incorrecte. La méthode doit être non statique, publique et ne doit retourner aucune valeur ni accepter aucun paramètre. En outre, si vous utilisez async-await dans la méthode, return-type doit être « Task » ou « ValueTask ». - - - - Unable to get type {0}. Error: {1}. - Impossible d'obtenir le type {0}. Erreur : {1}. - - - - Test method {0} was not found. - Méthode de test {0} introuvable. - - - - Debug Trace: - Trace du débogage : - - - - Failed to obtain the exception thrown by test method {0}.{1}. - Échec de l'obtention de l'exception levée par la méthode de test {0}.{1}. - - - - Test method {0}.{1} threw exception: -{2} - La méthode de test {0}.{1} a levé une exception : -{2} - - - - {0} For UWP projects, if you are using UI objects in test consider using [UITestMethod] attribute instead of [TestMethod] to execute test in UI thread. - {0} Pour les projets UWP, si vous utilisez des objets d'IU dans un test, utilisez l'attribut [UITestMethod] à la place de [TestMethod] pour exécuter le test dans le thread d'interface utilisateur. - - - - MSTestAdapterV2 - MSTestAdapterV2 - - - - Invalid settings '{0}'. Unexpected XmlAttribute: '{1}'. - Paramètres non valides '{0}'. XmlAttribute inattendu : '{1}'. - - - - Invalid settings '{0}'. Unexpected XmlElement: '{1}'. - Paramètres non valides '{0}'. XmlElement inattendu : '{1}'. - - - - {0} (Data Row {1}) - {0} (ligne de données {1}) - - - - The ExpectedException attribute defined on test method {0}.{1} threw an exception during construction. -{2} - L'attribut ExpectedException défini dans la méthode de test {0}.{1} a levé une exception durant la construction. -{2} - - - - Warning : A testsettings file or a vsmdi file is not supported with the MSTest V2 Adapter. - Avertissement : L'adaptateur MSTest V2 ne prend pas en charge les fichiers testsettings ou vsmdi. - - - - TestContext Messages: - Messages TestContext : - - - - Error calling Test Cleanup method for test class {0}: {1} - Erreur lors de l'appel de la méthode Test Cleanup pour la classe de test {0} : {1} - - - - TestCleanup Stack Trace - Trace de la pile TestCleanup - - - - [MSTest][Discovery][{0}] {1} - [MSTest][Discovery][{0}] {1} - - - - Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) - Parallélisation des tests activée pour {0} (Workers : {1}, Étendue : {2}). - `Workers` is a setting name that shouldn't be localized. 'Scope' is a setting name that shouldn't be localized. - - - Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. - Valeur non valide '{0}' spécifiée pour la 'Portée'. Les portées prises en charge sont {1}. - 'Scope' is a setting name that shouldn't be localized. - - - Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. - Valeur non valide '{0}' spécifiée pour 'Workers'. La valeur doit être un entier non négatif. - `Workers` is a setting name that shouldn't be localized. - - - Failed to discover tests from assembly {0}. Reason:{1} - Échec de la découverte de tests à partir de l'assembly {0}. Raison :{1} - - - - Test '{0}' was canceled - Le test '{0}' a été annulé - - - - Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. - Valeur non valide '{0}' spécifiée pour la 'ClassCleanupLifecycle'. Les portées prises en charge sont {1}. - 'ClassCleanupLifecycle' is a setting name that shouldn't be localized. - - - Exception occurred while enumerating IDataSource attribute on "{0}.{1}": {2} - Une exception s’est produite lors de l’énumération de l’attribut IDataSource sur « {0}.{1} » : {2} - {0}: TypeName with namespace, -{1}: Method name, -{2}: Exception details - - - "{0}": (Failed to get exception description due to an exception of type "{1}". - « {0} » : (Échec de l’obtention de la description de l’exception en raison d’une exception de type « {1} ». - {0}: Type of the original exception that we're trying to get the description of. -{1}: Thrown exception - - - Exceptions thrown: - Exceptions levées/s : - This is usually precedes by TestAssembly_AssemblyDiscoveryFailure message, and preceded by list of exceptions thrown in a test discovery session. - - - Getting custom attributes for type {0} threw exception (will ignore and use the reflection way): {1} - L’obtention d’attributs personnalisés pour le type {0} a levé une exception (ignorera et utilisera la méthode de réflexion) : {1} - {0}: Attribute full type name. -{1}: Exception description - - - An older version of MSTestV2 package is loaded in assembly, test discovery might fail to discover all data tests if they depend on `.runsettings` file. - Une version antérieure du package MSTestV2 est chargée dans l’assembly. La découverte de tests risque de ne pas découvrir tous les tests de données s’ils dépendent du fichier '.runsettings'. - - - - The called code threw an exception that was caught, but the exception value was null - Le code appelé a levé une exception qui a été interceptée, mais la valeur de l’exception était nul - - - - Exception occurred while expanding IDataSource rows from attribute on "{0}.{1}": {2} - Une exception s’est produite lors du développement des lignes IDataSource à partir de l’attribut sur « {0}.{1} » : {2} - {0}: TypeName with namespace, -{1}: Method name, -{2}: CannotExpandIDataSourceAttribute_DuplicateDisplayName or CannotExpandIDataSourceAttribute_CannotSerialize - - - Display name "{2}" on indexes {0} and {1} are duplicate. Display names should be unique. - Le nom d’affichage « {2} » sur les index {0} et {1} est dupliqué. Les noms d’affichage doivent être uniques. - {0}, {1}: Zero based index if an element inside of an array -{2}: Test display name. - - - Data on index {0} for "{1}" cannot be serialized. All data provided through "IDataSource" should be serializable. If you need to test non-serializable data sources, please make sure you add "TestDataSourceDiscovery" attribute on your test assembly and set the discovery option to "DuringExecution". - Impossible de sérialiser les données de l’index {0} pour « {1} ». Toutes les données fournies via « IDataSource » doivent être sérialisables. Si vous devez tester des sources de données non sérialisables, veillez à ajouter l’attribut « TestDataSourceDiscovery » à votre assembly de test et définissez l’option de découverte sur « DuringExecution ». - {0}: Zero based index if an element inside of an array, -{1}: Test name - - - - \ No newline at end of file diff --git a/src/Adapter/MSTest.TestAdapter/Resources/xlf/Resource.it.xlf b/src/Adapter/MSTest.TestAdapter/Resources/xlf/Resource.it.xlf deleted file mode 100644 index 97bff51c03..0000000000 --- a/src/Adapter/MSTest.TestAdapter/Resources/xlf/Resource.it.xlf +++ /dev/null @@ -1,482 +0,0 @@ - - - - - - Assembly cleanup method '{0}.{1}' timed out after {2}ms - Metodo di pulizia dell’assembly '{0}. Time out di {1}' dopo {2} ms - - - - Assembly cleanup method '{0}.{1}' was canceled - Il metodo di pulizia dell'assembly "{0}.{1}" è stato annullato - - - - Assembly initialize method '{0}.{1}' timed out after {2}ms - Metodo di inizializzazione dell'assembly '{0}. Timeout di {1}' dopo {2} ms - - - - Assembly initialize method '{0}.{1}' was canceled - Il metodo di inizializzazione dell'assembly "{0}.{1}" è stato annullato - - - - Cannot run test method '{0}.{1}': Test data doesn't match method parameters. Either the count or types are different. -Test expected {2} parameter(s), with types '{3}', -but received {4} argument(s), with types '{5}'. - Impossibile eseguire il metodo di test "{0}.{1}": i dati del test non corrispondono ai parametri del metodo. Il numero o il tipo è diverso. -Il test prevedeva {2} parametri, con tipi "{3}", -ma ha ricevuto {4} argomenti, con tipi "{5}". - - - - Cannot run test method '{0}.{1}': Method has parameters, but does not define any test source. Use '[DataRow]', '[DynamicData]', or a custom 'ITestDataSource' data source to provide test data. - Impossibile eseguire il metodo di test "{0}.{1}": il metodo contiene parametri, ma non definisce alcuna origine test. Usare "[DataRow]", "[DynamicData]" o un'origine dati "ITestDataSource" personalizzata per fornire i dati del test. - - - - Class cleanup method '{0}.{1}' timed out after {2}ms - Time out del metodo di pulizia della classe '{0}. Time out di {1}' dopo {2} ms - - - - Class cleanup method '{0}.{1}' was canceled - Il metodo di pulizia della classe "{0}.{1}" è stato annullato - - - - Class initialize method '{0}.{1}' timed out after {2}ms - Metodo di inizializzazione della classe '{0}. Timeout di {1}' dopo {2} ms - - - - Class initialize method '{0}.{1}' was canceled - Il metodo di inizializzazione della classe "{0}.{1}" è stato annullato - - - - Both '.runsettings' and '.testconfig.json' files have been detected. Please select only one of these test configuration files. - Sono stati rilevati sia i file '.runsettings' sia '.testconfig.json'. Selezionare solo uno di questi file di configurazione di test. - - - - Test '{0}' timed out after {1}ms - Timeout del '{0}' di test dopo {1}ms - - - - The type of the generic parameter '{0}' could not be inferred. - Impossibile dedurre il tipo del parametro generico '{0}'. - - - - The generic test method '{0}' doesn't have arguments, so the generic parameter cannot be inferred. - Il metodo di test generico '{0}' non contiene argomenti, di conseguenza non è possibile dedurre il parametro generico. - - - - Found two conflicting types for generic parameter '{0}'. The conflicting types are '{1}' and '{2}'. - Sono stati trovati due tipi in conflitto per il parametro generico '{0}'. I tipi in conflitto sono '{1}' e '{2}'. - - - - Invalid value '{0}' for runsettings entry '{1}', setting will be ignored. - Valore non valido '{0}' per la voce runsettings '{1}'. L'impostazione verrà ignorata. - - - - Runsettings entry '<ExecutionApartmentState>STA</ExecutionApartmentState>' is not supported on non-Windows OSes. - La voce Runsettings '<ExecutionApartmentState>STA</ExecutionApartmentState>' non è supportata nei sistemi operativi non Windows. - - - - Running tests in any of the provided sources is not supported for the selected platform - L'esecuzione di test in una delle origini specificate non è supportata per la piattaforma selezionata - - - - Test cleanup method '{0}.{1}' timed out after {2}ms - Time out del metodo di pulizia della classe dei test '{0}. Time out di {1}' dopo {2} ms - - - - Test cleanup method '{0}.{1}' was canceled - Il metodo di pulizia del test "{0}.{1}" è stato annullato - - - - Test initialize method '{0}.{1}' timed out after {2}ms - Metodo di inizializzazione del test '{0}. Timeout di {1}' dopo {2} ms - - - - Test initialize method '{0}.{1}' was canceled - Il metodo di inizializzazione del test "{0}.{1}" è stato annullato - - - - TestCleanup method {0}.{1} threw exception. {2}. - Il metodo TestCleanup {0}.{1} ha generato un'eccezione. {2}. - - - - --- End of inner exception stack trace --- - --- Fine dell'analisi dello stack dell'eccezione interna --- - - - - UTA014: {0}: Cannot define more than one method with the AssemblyCleanup attribute inside an assembly. - UTA014: {0}: non è possibile definire più di un metodo con l'attributo AssemblyCleanup all'interno di un assembly. - - - - UTA013: {0}: Cannot define more than one method with the AssemblyInitialize attribute inside an assembly. - UTA013: {0}: non è possibile definire più di un metodo con l'attributo AssemblyInitialize all'interno di un assembly. - - - - UTA026: {0}: Cannot define more than one method with the ClassCleanup attribute inside a class. - UTA026: {0}: non è possibile definire più di un metodo con l'attributo ClassCleanup all'interno di una classe. - - - - UTA025: {0}: Cannot define more than one method with the ClassInitialize attribute inside a class. - UTA025: {0}: non è possibile definire più di un metodo con l'attributo ClassInitialize all'interno di una classe. - - - - UTA024: {0}: Cannot define more than one method with the TestCleanup attribute. - UTA024: {0}: non è possibile definire più di un metodo con l'attributo TestCleanup. - - - - UTA018: {0}: Cannot define more than one method with the TestInitialize attribute. - UTA018: {0}: non è possibile definire più di un metodo con l'attributo TestInitialize. - - - - TestClass attribute defined on generic non-abstract class {0} - Attributo TestClass definito nella classe generica non astratta {0} - - - - Initialization method {0}.{1} threw exception. {2}. - Il metodo di inizializzazione {0}.{1} ha generato un'eccezione. {2}. - - - - Unable to create instance of class {0}. Error: {1}. - Non è possibile creare un'istanza della classe {0}. Errore: {1}. - - - - The test method '{0}.{1}' has multiple attributes derived from '{2}' defined on it. Only one such attribute is allowed. - Il metodo di test '{0}.{1}' contiene più attributi derivati da '{2}' definito in esso. È consentito solo uno di tali attributi. - - - - Cannot find a valid constructor for test class '{0}'. Valid constructors are 'public' and either parameterless or with one parameter of type 'TestContext'. - Impossibile trovare un costruttore valido per la classe di test '{0}'. I costruttori validi sono 'public' e senza parametri o con un parametro di tipo 'TestContext'. - - - - Unable to set TestContext property for the class {0}. Error: {1}. - Non è possibile impostare la proprietà TestContext per la classe {0}. Errore: {1}. - - - - (Failed to get the message for an exception of type {0} due to an exception.) - Non è stato possibile ottenere il messaggio per un'eccezione di tipo {0} a causa di un'eccezione. - - - - UTA031: class {0} does not have valid TestContext property. TestContext must be of type TestContext, must be non-static, and must be public. For example: public TestContext TestContext. - UTA031: la classe {0} non dispone di una proprietà TestContext valida. La proprietà TestContext deve essere di tipo TestContext, non deve essere statica e deve essere pubblica. Ad esempio: public TestContext TestContext. - - - - UTA001: TestClass attribute defined on non-public class {0} - UTA001: è stato definito l'attributo TestClass per la classe non pubblica {0} - - - - MSTestAdapter failed to discover tests in class '{0}' of assembly '{1}' because {2}. - MSTestAdapter non è riuscito a individuare test nella classe '{0}' dell'assembly '{1}' perché {2}. - - - - {0}: {1} - {0}: {1} - - - - Unable to load types from the test source '{0}'. Some or all of the tests in this source may not be discovered. -Error: {1} - Non è possibile caricare i tipi dall'origine test '{0}'. È possibile che alcuni o tutti i test non siano stati individuati in questa origine. -Errore: {1} - - - - File does not exist: {0} - Il file {0} non esiste - - - - UTA007: Method {1} defined in class {0} does not have correct signature. Test method marked with the [TestMethod] attribute must be non-static, public, return-type as void and should not take any parameter. Example: public void Test.Class1.Test(). Additionally, if you are using async-await in test method then return-type must be 'Task' or 'ValueTask'. Example: public async Task Test.Class1.Test2() - UTA007: la firma del metodo {1} definito nella classe {0} non è corretta. Il metodo di test contrassegnato con l'attributo [TestMethod] deve essere pubblico e non statico, non deve accettare parametri e deve includere un tipo restituito void. Esempio: public void Test.Class1.Test(). Se inoltre nel metodo di test si usa async-await, il tipo restituito deve essere 'Task' o 'ValueTask'. Esempio: public async Task Test.Class1.Test2() - - - - TestContext cannot be Null. - TestContext non può essere Null. - - - - Assembly Cleanup method {0}.{1} failed. Error Message: {2}. StackTrace: {3} - Il metodo di pulizia assembly {0}.{1} non è riuscito. Messaggio di errore: {2}. Analisi dello stack: {3} - - - - Assembly Initialization method {0}.{1} threw exception. {2}: {3}. Aborting test execution. - Il metodo di inizializzazione assembly {0}.{1} ha generato un'eccezione. {2}: {3}. L'esecuzione del test verrà interrotta. - - - - Class Cleanup method {0}.{1} failed. Error Message: {2}. Stack Trace: {3} - Il metodo di pulizia classi {0}.{1} non è riuscito. Messaggio di errore: {2}. Analisi dello stack: {3} - - - - Class Initialization method {0}.{1} threw exception. {2}: {3}. - Il metodo di inizializzazione classi {0}.{1} ha generato un'eccezione. {2}: {3}. - - - - An unhandled exception was thrown by the 'Execute' method. Please report this error to the author of the attribute '{0}'. -{1} - Eccezione non gestita generata dal metodo 'Execute'. Segnalare l'errore all'autore dell'attributo '{0}'. -{1} - - - - Error in executing test. No result returned by extension. If using extension of TestMethodAttribute then please contact vendor. - Si è verificato un errore durante l'esecuzione del test. L'estensione non ha restituito alcun risultato. Se si usa l'estensione di TestMethodAttribute, contattare il fornitore. - - - - Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. - La firma del metodo {0}.{1}non è corretta. Il metodo deve essere statico e pubblico, non deve restituire un valore né accettare parametri. Se inoltre si usa async-await nel metodo di test, il tipo restituito deve essere 'Task' o 'ValueTask'. - - - - Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should take a single parameter of type TestContext. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. - La firma del metodo {0}.{1}non è corretta. Il metodo deve essere statico e pubblico, non deve restituire un valore e deve accettare un singolo parametro di tipo TestContext. Se inoltre si usa async-await nel metodo di test, il tipo restituito deve essere 'Task' o 'ValueTask'. - - - - UTA054: {0}.{1} has invalid Timeout attribute. The timeout must be an integer value greater than 0. - UTA054: {0}.{1} ha un attributo Timeout non valido. Il timeout deve essere un valore intero maggiore di 0. - - - - UTA023: {0}: Cannot define predefined property {2} on method {1}. - UTA023: {0}: non è possibile definire la proprietà predefinita {2} per il metodo {1}. - - - - UTA021: {0}: Null or empty custom property defined on method {1}. The custom property must have a valid name. - UTA021: {0}: per il metodo {1} è stata definita una proprietà personalizzata Null o vuota. Specificare un nome valido per la proprietà personalizzata. - - - - Method {0}.{1} does not exist. - Il metodo {0}.{1} non esiste. - - - - Unable to find property {0}.TestContext. Error:{1}. - La proprietà {0}.TestContext non è stata trovata. Errore: {1}. - - - - The {0}.TestContext has incorrect type. - Il tipo di {0}.TestContext non è corretto. - - - - Method {0}.{1} has wrong signature. The method must be non-static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. - La firma del metodo {0}.{1}non è corretta. Il metodo deve essere non statico e pubblico, non deve restituire un valore né accettare parametri. Se inoltre si usa async-await nel metodo di test, il tipo restituito deve essere 'Task' o 'ValueTask'. - - - - Unable to get type {0}. Error: {1}. - Non è possibile ottenere il tipo {0}. Errore: {1}. - - - - Test method {0} was not found. - Il metodo di test {0} non è stato trovato. - - - - Debug Trace: - Traccia di debug: - - - - Failed to obtain the exception thrown by test method {0}.{1}. - Non è stato possibile ottenere l'eccezione generata dal metodo di test {0}.{1}. - - - - Test method {0}.{1} threw exception: -{2} - Il metodo di test {0}.{1} ha generato un'eccezione: -{2} - - - - {0} For UWP projects, if you are using UI objects in test consider using [UITestMethod] attribute instead of [TestMethod] to execute test in UI thread. - {0}. Se, per i progetti della piattaforma UWP, nel test si usano oggetti dell'interfaccia utente, provare a specificare l'attributo [UITestMethod] invece di [TestMethod] per eseguire il test nel thread di UI. - - - - MSTestAdapterV2 - MSTestAdapterV2 - - - - Invalid settings '{0}'. Unexpected XmlAttribute: '{1}'. - Le impostazioni '{0}' non sono valide. Elemento XmlAttribute imprevisto: '{1}'. - - - - Invalid settings '{0}'. Unexpected XmlElement: '{1}'. - Le impostazioni '{0}' non sono valide. Elemento XmlElement imprevisto: '{1}'. - - - - {0} (Data Row {1}) - {0} (riga dati {1}) - - - - The ExpectedException attribute defined on test method {0}.{1} threw an exception during construction. -{2} - L'attributo ExpectedException definito nel metodo di test {0}.{1} ha generato un'eccezione durante la costruzione. -{2} - - - - Warning : A testsettings file or a vsmdi file is not supported with the MSTest V2 Adapter. - Avviso: con l'adattatore MSTest V2 non è possibile usare un file testsettings o un file vsmdi. - - - - TestContext Messages: - Messaggi di TestContext: - - - - Error calling Test Cleanup method for test class {0}: {1} - Si è verificato un errore durante la chiamata del metodo TestCleanup per la classe di test {0}: {1} - - - - TestCleanup Stack Trace - Analisi dello stato di TestCleanup - - - - [MSTest][Discovery][{0}] {1} - [MSTest][Individuazione][{0}] {1} - - - - Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) - Parallelizzazione test abilitata per {0} (Processi di lavoro: {1}. Ambito: {2}). - `Workers` is a setting name that shouldn't be localized. 'Scope' is a setting name that shouldn't be localized. - - - Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. - Il valore '{0}', specificato per 'Scope', non è valido. I valori supportati per Scope sono {1}. - 'Scope' is a setting name that shouldn't be localized. - - - Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. - Il valore '{0}', specificato per 'Workers', non è valido. Il valore deve essere un numero intero non negativo. - `Workers` is a setting name that shouldn't be localized. - - - Failed to discover tests from assembly {0}. Reason:{1} - Non è stato possibile individuare i test dall'assembly {0}. Motivo: {1} - - - - Test '{0}' was canceled - Il '{0}' di test è stato annullato - - - - Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. - Il valore '{0}', specificato per 'ClassCleanupLifecycle', non è valido. I valori supportati per Scope sono {1}. - 'ClassCleanupLifecycle' is a setting name that shouldn't be localized. - - - Exception occurred while enumerating IDataSource attribute on "{0}.{1}": {2} - Si è verificata un'eccezione durante l'enumerazione dell'attributo IDataSource in "{0}.{1}": {2} - {0}: TypeName with namespace, -{1}: Method name, -{2}: Exception details - - - "{0}": (Failed to get exception description due to an exception of type "{1}". - "{0}": (non è stato possibile ottenere la descrizione dell'eccezione a causa di un'eccezione di tipo "{1}". - {0}: Type of the original exception that we're trying to get the description of. -{1}: Thrown exception - - - Exceptions thrown: - Eccezioni generate: - This is usually precedes by TestAssembly_AssemblyDiscoveryFailure message, and preceded by list of exceptions thrown in a test discovery session. - - - Getting custom attributes for type {0} threw exception (will ignore and use the reflection way): {1} - Il recupero degli attributi personalizzati per il tipo {0} ha generato un'eccezione (verrà ignorata e verrà usata la modalità reflection): {1} - {0}: Attribute full type name. -{1}: Exception description - - - An older version of MSTestV2 package is loaded in assembly, test discovery might fail to discover all data tests if they depend on `.runsettings` file. - Nell'assembly è caricata una versione precedente del pacchetto MSTestV2. L'individuazione dei test potrebbe non riuscire a individuare tutti i test dei dati se dipendono dal file '.runsettings'. - - - - The called code threw an exception that was caught, but the exception value was null - Il codice chiamato ha generato un'eccezione che è stata rilevata, ma il valore dell'eccezione è Null - - - - Exception occurred while expanding IDataSource rows from attribute on "{0}.{1}": {2} - Si è verificata un'eccezione durante l'espansione delle righe IDataSource dall'attributo in "{0}.{1}": {2} - {0}: TypeName with namespace, -{1}: Method name, -{2}: CannotExpandIDataSourceAttribute_DuplicateDisplayName or CannotExpandIDataSourceAttribute_CannotSerialize - - - Display name "{2}" on indexes {0} and {1} are duplicate. Display names should be unique. - Il nome visualizzato "{2}" negli indici {0} e {1} è duplicato. I nomi visualizzati devono essere univoci. - {0}, {1}: Zero based index if an element inside of an array -{2}: Test display name. - - - Data on index {0} for "{1}" cannot be serialized. All data provided through "IDataSource" should be serializable. If you need to test non-serializable data sources, please make sure you add "TestDataSourceDiscovery" attribute on your test assembly and set the discovery option to "DuringExecution". - Non è possibile serializzare i dati nell'indice {0} per "{1}". Tutti i dati forniti tramite "IDataSource" devono essere serializzabili. Se è necessario testare origini dati non serializzabili, assicurarsi di aggiungere l'attributo "TestDataSourceDiscovery" nell'assembly di test e impostare l'opzione di individuazione su "DuringExecution". - {0}: Zero based index if an element inside of an array, -{1}: Test name - - - - \ No newline at end of file diff --git a/src/Adapter/MSTest.TestAdapter/Resources/xlf/Resource.ja.xlf b/src/Adapter/MSTest.TestAdapter/Resources/xlf/Resource.ja.xlf deleted file mode 100644 index 0e196b3b3f..0000000000 --- a/src/Adapter/MSTest.TestAdapter/Resources/xlf/Resource.ja.xlf +++ /dev/null @@ -1,483 +0,0 @@ - - - - - - Assembly cleanup method '{0}.{1}' timed out after {2}ms - アセンブリ クリーンアップ メソッド '{0}.{1}' が {2}ms 後にタイムアウトしました - - - - Assembly cleanup method '{0}.{1}' was canceled - アセンブリ クリーンアップ メソッド '{0}.{1}' が取り消されました - - - - Assembly initialize method '{0}.{1}' timed out after {2}ms - アセンブリ初期化メソッド '{0}.{1}' が {2}ms 後にタイムアウトになりました - - - - Assembly initialize method '{0}.{1}' was canceled - アセンブリ初期化メソッド '{0}.{1}' が取り消されました - - - - Cannot run test method '{0}.{1}': Test data doesn't match method parameters. Either the count or types are different. -Test expected {2} parameter(s), with types '{3}', -but received {4} argument(s), with types '{5}'. - テスト メソッド '{0}を実行できません。{1}': テスト データがメソッド パラメーターと一致しません。カウントまたは型が異なります。 -型 '{3}'、 - を持つ、予期された {2} パラメーターをテストします -ただし、型 '{5}' の引数 {4} を受け取りました。 - - - - Cannot run test method '{0}.{1}': Method has parameters, but does not define any test source. Use '[DataRow]', '[DynamicData]', or a custom 'ITestDataSource' data source to provide test data. - テスト メソッド '{0} を実行できません。{1}': メソッドにはパラメーターがありますが、テスト ソースは定義されていません。'[DataRow]'、'[DynamicData]'、カスタムの 'ITestDataSource' データ ソースを使用して、テスト データを提供します。 - - - - Class cleanup method '{0}.{1}' timed out after {2}ms - クラス クリーンアップ メソッド '{0}.{1}' が {2}ms 後にタイムアウトしました - - - - Class cleanup method '{0}.{1}' was canceled - クラス クリーンアップ メソッド '{0}.{1}' が取り消されました - - - - Class initialize method '{0}.{1}' timed out after {2}ms - クラス初期化メソッド '{0}.{1}' が {2}ms 後にタイムアウトになりました - - - - Class initialize method '{0}.{1}' was canceled - クラス初期化メソッド '{0}.{1}' が取り消されました - - - - Both '.runsettings' and '.testconfig.json' files have been detected. Please select only one of these test configuration files. - '.runsettings' ファイルと '.testconfig.json' ファイルの両方が検出されました。これらのテスト構成ファイルのいずれか 1 つだけを選択してください。 - - - - Test '{0}' timed out after {1}ms - テスト '{0}' が {1}ミリ秒後にタイムアウトしました - - - - The type of the generic parameter '{0}' could not be inferred. - ジェネリック パラメーター '{0}' の型を推論できませんでした。 - - - - The generic test method '{0}' doesn't have arguments, so the generic parameter cannot be inferred. - '{0}' ジェネリック テスト メソッドに引数がないため、ジェネリック パラメーターを推論できません。 - - - - Found two conflicting types for generic parameter '{0}'. The conflicting types are '{1}' and '{2}'. - ジェネリック パラメーター '{0}' に 2 つの競合する型が見つかりました。競合する型は '{1}' で '{2}'。 - - - - Invalid value '{0}' for runsettings entry '{1}', setting will be ignored. - runsettings エントリ '{1}' の値 '{0}' は無効です。設定は無視されます。 - - - - Runsettings entry '<ExecutionApartmentState>STA</ExecutionApartmentState>' is not supported on non-Windows OSes. - Runsettings エントリ '<ExecutionApartmentState>STA</ExecutionApartmentState>' は、Windows OS 以外ではサポートされていません。 - - - - Running tests in any of the provided sources is not supported for the selected platform - 指定されたソースのいずれかでのテストの実行は、選択されたプラットフォームでサポートされていません - - - - Test cleanup method '{0}.{1}' timed out after {2}ms - テスト クリーンアップ メソッド '{0}.{1}' が {2}ms 後にタイムアウトしました - - - - Test cleanup method '{0}.{1}' was canceled - テスト クリーンアップ メソッド '{0}.{1}' が取り消されました - - - - Test initialize method '{0}.{1}' timed out after {2}ms - テスト初期化メソッド '{0}.{1}' が {2}ms 後にタイムアウトになりました - - - - Test initialize method '{0}.{1}' was canceled - テスト初期化メソッド '{0}.{1}' が取り消されました - - - - TestCleanup method {0}.{1} threw exception. {2}. - TestCleanup メソッド {0}.{1} は例外をスローしました。{2}。 - - - - --- End of inner exception stack trace --- - --- 内部例外スタック トレースの終わり --- - - - - UTA014: {0}: Cannot define more than one method with the AssemblyCleanup attribute inside an assembly. - UTA014: {0}: 1 つのアセンブリ内で、AssemblyCleanup 属性を伴う 2 つ以上のメソッドを定義することはできません。 - - - - UTA013: {0}: Cannot define more than one method with the AssemblyInitialize attribute inside an assembly. - UTA013: {0}: 1 つのアセンブリ内で、AssemblyInitialize 属性を伴う 2 つ以上のメソッドを定義することはできません。 - - - - UTA026: {0}: Cannot define more than one method with the ClassCleanup attribute inside a class. - UTA026: {0}: 1 つのクラス内で、ClassCleanup 属性を伴う 2 つ以上のメソッドを定義することはできません。 - - - - UTA025: {0}: Cannot define more than one method with the ClassInitialize attribute inside a class. - UTA025: {0}: 1 つのクラス内で、ClassInitialize 属性を伴う 2 つ以上のメソッドを定義することはできません。 - - - - UTA024: {0}: Cannot define more than one method with the TestCleanup attribute. - UTA024: {0}: TestCleanup 属性を伴う 2 つ以上のメソッドを定義することはできません。 - - - - UTA018: {0}: Cannot define more than one method with the TestInitialize attribute. - UTA018: {0}: TestInitialize 属性を伴う 2 つ以上のメソッドを定義することはできません。 - - - - TestClass attribute defined on generic non-abstract class {0} - 汎用の非抽象クラス {0}で定義された TestClass 属性 - - - - Initialization method {0}.{1} threw exception. {2}. - 初期化メソッド {0}.{1} は例外をスローしました。{2}。 - - - - Unable to create instance of class {0}. Error: {1}. - クラス {0} のインスタンスを作成できません。エラー: {1}。 - - - - The test method '{0}.{1}' has multiple attributes derived from '{2}' defined on it. Only one such attribute is allowed. - テスト メソッド '{0}.{1}' には、 '{2}' から派生した属性が複数定義されています。このような属性は 1 つしか許可されません。 - - - - Cannot find a valid constructor for test class '{0}'. Valid constructors are 'public' and either parameterless or with one parameter of type 'TestContext'. - テスト クラス '{0}' の有効なコンストラクターが見つかりません。有効なコンストラクターは、'public' で、パラメーターがないもの、または 'TestContext' 型のパラメーター 1 個を取るものです。 - - - - Unable to set TestContext property for the class {0}. Error: {1}. - クラス {0} の TestContext プロパティを設定できません。エラー: {1}。 - - - - (Failed to get the message for an exception of type {0} due to an exception.) - (例外が発生したため、型 {0} の例外のメッセージを取得できませんでした。) - - - - UTA031: class {0} does not have valid TestContext property. TestContext must be of type TestContext, must be non-static, and must be public. For example: public TestContext TestContext. - UTA031: クラス {0} に有効な TestContext プロパティがありません。TestContext は TestContext 型で、非静的である必要があり、public である必要があります。たとえば、public TestContext TestContext です。 - - - - UTA001: TestClass attribute defined on non-public class {0} - UTA001: TestClass 属性がパブリックでないクラス {0} で定義されています - - - - MSTestAdapter failed to discover tests in class '{0}' of assembly '{1}' because {2}. - MSTestAdapter でアセンブリ '{1}' のクラス '{0}' にテストが見つかりませんでした。理由 {2}。 - - - - {0}: {1} - {0}: {1} - - - - Unable to load types from the test source '{0}'. Some or all of the tests in this source may not be discovered. -Error: {1} - テスト ソース '{0}' から型を読み込むことができません。このソース内の一部またはすべてのテストが見つからない可能性があります。 -エラー: {1} - - - - File does not exist: {0} - ファイルが存在しません: {0} - - - - UTA007: Method {1} defined in class {0} does not have correct signature. Test method marked with the [TestMethod] attribute must be non-static, public, return-type as void and should not take any parameter. Example: public void Test.Class1.Test(). Additionally, if you are using async-await in test method then return-type must be 'Task' or 'ValueTask'. Example: public async Task Test.Class1.Test2() - UTA007: クラス {0} で定義されているメソッド {1} に適切なシグネチャが含まれていません。[TestMethod] 属性でマークされたテスト メソッドは、non-static および public である必要があり、戻り値の型は void である必要があります。また、パラメーターを受け取ることはできません。例: public void Test.Class1.Test()。また、テスト メソッドで async-await を使用している場合、戻り値の型は 'Task' または 'ValueTask' である必要があります。例: public async Task Test.Class1.Test2() - - - - TestContext cannot be Null. - TestContext を Null にすることはできません。 - - - - Assembly Cleanup method {0}.{1} failed. Error Message: {2}. StackTrace: {3} - アセンブリ クリーンアップ メソッド {0}.{1} に失敗しました。エラー メッセージ: {2}。スタック トレース: {3} - - - - Assembly Initialization method {0}.{1} threw exception. {2}: {3}. Aborting test execution. - アセンブリ初期化メソッド {0}.{1} は例外をスローしました。{2}: {3}。テストの実行を中止しています。 - - - - Class Cleanup method {0}.{1} failed. Error Message: {2}. Stack Trace: {3} - クラス クリーンアップ メソッド {0}.{1} に失敗しました。エラー メッセージ: {2}。スタック トレース: {3} - - - - Class Initialization method {0}.{1} threw exception. {2}: {3}. - クラス初期化メソッド {0}.{1} は例外をスローしました。{2}: {3}。 - - - - An unhandled exception was thrown by the 'Execute' method. Please report this error to the author of the attribute '{0}'. -{1} - 'Execute' メソッドによってハンドルされない例外がスローされました。属性 '{0}' の作成者にこのエラーを報告してください。 -{1} - - - - Error in executing test. No result returned by extension. If using extension of TestMethodAttribute then please contact vendor. - テストの実行中にエラーが発生しました。拡張から結果が返されませんでした。TestMethodAttribute の拡張クラスを使用している場合は、ベンダーに連絡してください。 - - - - Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. - メソッド {0}。{1} は不適切なシグネチャを含んでいます。メソッドは static および public である必要があり、値を返しません。また、パラメーターを受け取ることはできません。また、メソッドで async-await を使用している場合、戻り値の型は 'Task' または 'ValueTask' である必要があります。 - - - - Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should take a single parameter of type TestContext. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. - メソッド {0}。{1} は不適切なシグネチャを含んでいます。メソッドは static および public である必要があり、値を返しません。また、TestContext 型の 1 つのパラメーターを受け取る必要があります。また、メソッドで async-await を使用している場合、戻り値の型は 'Task' または 'ValueTask' である必要があります。 - - - - UTA054: {0}.{1} has invalid Timeout attribute. The timeout must be an integer value greater than 0. - UTA054: {0}。{1} に無効な Timeout 属性があります。タイムアウトには、0 より大きい整数値を指定する必要があります。 - - - - UTA023: {0}: Cannot define predefined property {2} on method {1}. - UTA023: {0}: メソッド {1} 上の以前に定義されたプロパティ {2} を定義することはできません。 - - - - UTA021: {0}: Null or empty custom property defined on method {1}. The custom property must have a valid name. - UTA021: {0}: Null または空のカスタム プロパティが、メソッド {1} で定義されています。カスタム プロパティには有効な名前を指定しなければなりません。 - - - - Method {0}.{1} does not exist. - メソッド {0}.{1} は存在しません。 - - - - Unable to find property {0}.TestContext. Error:{1}. - プロパティ {0}.TestContext が見つかりません。エラー: {1}。 - - - - The {0}.TestContext has incorrect type. - {0}.TestContext は不適切な型を含んでいます。 - - - - Method {0}.{1} has wrong signature. The method must be non-static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. - メソッド {0}。{1} は不適切なシグネチャを含んでいます。メソッドは non-static および public である必要があり、値を返しません。また、パラメーターを受け取ることはできません。また、メソッドで async-await を使用している場合、戻り値の型は 'Task' または 'ValueTask' である必要があります。 - - - - Unable to get type {0}. Error: {1}. - 型 {0} を取得できません。エラー: {1}。 - - - - Test method {0} was not found. - テスト メソッド {0} が見つかりませんでした。 - - - - Debug Trace: - デバッグ トレース: - - - - Failed to obtain the exception thrown by test method {0}.{1}. - テスト メソッド {0}.{1} によってスローされた例外を取得できませんでした。 - - - - Test method {0}.{1} threw exception: -{2} - テスト メソッド {0}.{1} が例外をスローしました: -{2} - - - - {0} For UWP projects, if you are using UI objects in test consider using [UITestMethod] attribute instead of [TestMethod] to execute test in UI thread. - {0} UWP プロジェクトについて、テスト内で UI オブジェクトを使用している場合は、[TestMethod] の代わりに [UITestMethod] 属性を使用して UI スレッド内でテストを実行することを検討してください。 - - - - MSTestAdapterV2 - MSTestAdapterV2 - - - - Invalid settings '{0}'. Unexpected XmlAttribute: '{1}'. - 設定 '{0}' は無効です。予期しない XmlAttribute: '{1}'。 - - - - Invalid settings '{0}'. Unexpected XmlElement: '{1}'. - 設定 '{0}' は無効です。予期しない XmlElement: '{1}'。 - - - - {0} (Data Row {1}) - {0} (データ行 {1}) - - - - The ExpectedException attribute defined on test method {0}.{1} threw an exception during construction. -{2} - テスト メソッド {0}.{1} に定義されている ExpectedException 属性が、作成中に例外をスローしました。 -{2} - - - - Warning : A testsettings file or a vsmdi file is not supported with the MSTest V2 Adapter. - 警告: testsettings ファイル、vsmdi ファイルは MSTest V2 アダプターではサポートされていません。 - - - - TestContext Messages: - TestContext メッセージ: - - - - Error calling Test Cleanup method for test class {0}: {1} - テスト クラス {0} のテスト クリーンアップ メソッドの呼び出しでエラーが発生しました: {1} - - - - TestCleanup Stack Trace - TestCleanup スタック トレース - - - - [MSTest][Discovery][{0}] {1} - [MSTest][Discovery][{0}] {1} - - - - Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) - {0} でテスト並列処理が有効にされています (Workers: {1}、Scope: {2})。 - `Workers` is a setting name that shouldn't be localized. 'Scope' is a setting name that shouldn't be localized. - - - Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. - 無効な値 '{0}' が 'Scope' に指定されました。サポートされているスコープは {1} です。 - 'Scope' is a setting name that shouldn't be localized. - - - Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. - 無効な値 '{0}' が 'Workers' に指定されました。値は負ではない整数である必要があります。 - `Workers` is a setting name that shouldn't be localized. - - - Failed to discover tests from assembly {0}. Reason:{1} - アセンブリ {0} からテストを検出できませんでした。理由:{1} - - - - Test '{0}' was canceled - テスト '{0}' が取り消されました - - - - Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. - 'ClassCleanupLifecycle' に無効な値 '{0}' が指定されました。サポートされているスコープは {1} です。 - 'ClassCleanupLifecycle' is a setting name that shouldn't be localized. - - - Exception occurred while enumerating IDataSource attribute on "{0}.{1}": {2} - "{0}.{1}" で IDataSource 属性を列挙中に例外が発生しました: {2} - {0}: TypeName with namespace, -{1}: Method name, -{2}: Exception details - - - "{0}": (Failed to get exception description due to an exception of type "{1}". - "{0}": (種類が "{1}"の例外のため、例外の説明を取得できませんでした。 - {0}: Type of the original exception that we're trying to get the description of. -{1}: Thrown exception - - - Exceptions thrown: - スローされた例外: - This is usually precedes by TestAssembly_AssemblyDiscoveryFailure message, and preceded by list of exceptions thrown in a test discovery session. - - - Getting custom attributes for type {0} threw exception (will ignore and use the reflection way): {1} - 型 {0} のカスタム属性を取得中に例外がスローされました (無視してリフレクションの方法を使用します): {1} - {0}: Attribute full type name. -{1}: Exception description - - - An older version of MSTestV2 package is loaded in assembly, test discovery might fail to discover all data tests if they depend on `.runsettings` file. - 古いバージョンの MSTestV2 パッケージがアセンブリに読み込まれています。`.runsettings` ファイルに依存している場合、テスト検出ですべてのデータ テストを検出できない可能性があります。 - - - - The called code threw an exception that was caught, but the exception value was null - 呼び出されたコードはキャッチされた例外をスローしましたが、例外値が null でした - - - - Exception occurred while expanding IDataSource rows from attribute on "{0}.{1}": {2} - "{0}.{1}" の属性から IDataSource 行を展開中に例外が発生しました: {2} - {0}: TypeName with namespace, -{1}: Method name, -{2}: CannotExpandIDataSourceAttribute_DuplicateDisplayName or CannotExpandIDataSourceAttribute_CannotSerialize - - - Display name "{2}" on indexes {0} and {1} are duplicate. Display names should be unique. - インデックス {0} と {1} の表示名 "{2}" が重複しています。表示名は一意である必要があります。 - {0}, {1}: Zero based index if an element inside of an array -{2}: Test display name. - - - Data on index {0} for "{1}" cannot be serialized. All data provided through "IDataSource" should be serializable. If you need to test non-serializable data sources, please make sure you add "TestDataSourceDiscovery" attribute on your test assembly and set the discovery option to "DuringExecution". - "{1}" のインデックス {0} のデータをシリアル化できません。"IDataSource" を介して提供されるすべてのデータはシリアル化可能である必要があります。シリアル化できないデータ ソースをテストする必要がある場合は、テスト アセンブリに "TestDataSourceDiscovery" 属性を追加し、検出オプションを "DuringExecution" に設定してください。 - {0}: Zero based index if an element inside of an array, -{1}: Test name - - - - \ No newline at end of file diff --git a/src/Adapter/MSTest.TestAdapter/Resources/xlf/Resource.ko.xlf b/src/Adapter/MSTest.TestAdapter/Resources/xlf/Resource.ko.xlf deleted file mode 100644 index b652734ad5..0000000000 --- a/src/Adapter/MSTest.TestAdapter/Resources/xlf/Resource.ko.xlf +++ /dev/null @@ -1,482 +0,0 @@ - - - - - - Assembly cleanup method '{0}.{1}' timed out after {2}ms - {2}밀리초 후 어셈블리 정리 메서드 '{0}.{1}'이(가) 시간 초과되었습니다. - - - - Assembly cleanup method '{0}.{1}' was canceled - 어셈블리 정리 메서드 '{0}.{1}'이(가) 취소되었습니다. - - - - Assembly initialize method '{0}.{1}' timed out after {2}ms - {2}밀리초 후 '{0}.{1}' 어셈블리 초기화 메서드의 시간이 초과되었습니다. - - - - Assembly initialize method '{0}.{1}' was canceled - 어셈블리 초기화 메서드 '{0}.{1}'(이)가 취소되었습니다. - - - - Cannot run test method '{0}.{1}': Test data doesn't match method parameters. Either the count or types are different. -Test expected {2} parameter(s), with types '{3}', -but received {4} argument(s), with types '{5}'. - 테스트 메서드 '{0}{1}'을(를) 실행할 수 없음: 테스트 데이터가 메서드 매개 변수와 일치하지 않습니다. 개수 또는 형식이 다릅니다. -테스트에 {2} 매개 변수로 ‘{3}’ 형식이 필요하지만, -{4} 인수의 ‘{5}’ 형식을 받았습니다. - - - - Cannot run test method '{0}.{1}': Method has parameters, but does not define any test source. Use '[DataRow]', '[DynamicData]', or a custom 'ITestDataSource' data source to provide test data. - 테스트 메서드 '{0}{1}'을(를) 실행할 수 없음: 메서드에 매개 변수가 있지만 테스트 원본을 정의하지 않습니다. '[DataRow]', '[DynamicData]' 또는 사용자 지정 'ITestDataSource' 데이터 원본을 사용하여 테스트 데이터를 제공합니다. - - - - Class cleanup method '{0}.{1}' timed out after {2}ms - {2}밀리초 후 클래스 정리 메서드 '{0}.{1}'이(가) 시간 초과되었습니다. - - - - Class cleanup method '{0}.{1}' was canceled - 클래스 정리 메서드 '{0}.{1}'이(가) 취소되었습니다. - - - - Class initialize method '{0}.{1}' timed out after {2}ms - {2}밀리초 후 '{0}.{1}' 클래스 초기화 메서드의 시간이 초과되었습니다. - - - - Class initialize method '{0}.{1}' was canceled - '클래스 초기화 메서드 '{0}.{1}'이(가) 취소되었습니다. - - - - Both '.runsettings' and '.testconfig.json' files have been detected. Please select only one of these test configuration files. - '.runsettings' 및 '.testconfig.json' 파일이 모두 검색되었습니다. 이러한 테스트 구성 파일 중 하나만 선택하세요. - - - - Test '{0}' timed out after {1}ms - 테스트 '{0}' {1}밀리초 후에 시간 초과되었습니다. - - - - The type of the generic parameter '{0}' could not be inferred. - 제네릭 매개 변수 '{0}' 형식을 유추할 수 없습니다. - - - - The generic test method '{0}' doesn't have arguments, so the generic parameter cannot be inferred. - 제네릭 테스트 메서드 '{0}' 인수가 없으므로 제네릭 매개 변수를 유추할 수 없습니다. - - - - Found two conflicting types for generic parameter '{0}'. The conflicting types are '{1}' and '{2}'. - 제네릭 매개 변수 '{0}' 충돌하는 두 가지 형식을 찾았습니다. 충돌하는 형식은 '{1}' '{2}'. - - - - Invalid value '{0}' for runsettings entry '{1}', setting will be ignored. - runsettings 항목 '{1}'에 대해 '{0}' 값이 잘못되었습니다. 설정은 무시됩니다. - - - - Runsettings entry '<ExecutionApartmentState>STA</ExecutionApartmentState>' is not supported on non-Windows OSes. - Runsettings 항목 '<ExecutionApartmentState>STA</ExecutionApartmentState>'는 Windows 이외의 OS에서는 지원되지 않습니다. - - - - Running tests in any of the provided sources is not supported for the selected platform - 선택된 플랫폼의 경우 제공된 소스에서 테스트를 실행할 수 없습니다. - - - - Test cleanup method '{0}.{1}' timed out after {2}ms - {2}밀리초 후 테스트 정리 메서드 '{0}.{1}'이(가) 시간 초과되었습니다. - - - - Test cleanup method '{0}.{1}' was canceled - 테스트 정리 메서드 '{0}.{1}'이(가) 취소되었습니다. - - - - Test initialize method '{0}.{1}' timed out after {2}ms - {2}밀리초 후 '{0}.{1}' 테스트 초기화 메서드의 시간이 초과되었습니다. - - - - Test initialize method '{0}.{1}' was canceled - 테스트 초기화 메서드 '{0}.{1}'이(가) 취소되었습니다. - - - - TestCleanup method {0}.{1} threw exception. {2}. - TestCleanup 메서드 {0}.{1}에서 예외가 발생했습니다. {2}. - - - - --- End of inner exception stack trace --- - --- 내부 예외 스택 추적의 끝 --- - - - - UTA014: {0}: Cannot define more than one method with the AssemblyCleanup attribute inside an assembly. - UTA014: {0}: 어셈블리 내부에서 AssemblyCleanup 특성을 사용하는 메서드를 여러 개 정의할 수 없습니다. - - - - UTA013: {0}: Cannot define more than one method with the AssemblyInitialize attribute inside an assembly. - UTA013: {0}: 어셈블리 내부에서 AssemblyInitialize 특성을 사용하는 메서드를 여러 개 정의할 수 없습니다. - - - - UTA026: {0}: Cannot define more than one method with the ClassCleanup attribute inside a class. - UTA026: {0}: 클래스 내부에서 ClassCleanup 특성을 사용하는 메서드를 여러 개 정의할 수 없습니다. - - - - UTA025: {0}: Cannot define more than one method with the ClassInitialize attribute inside a class. - UTA025: {0}: 클래스 내부에서 ClassInitialize 특성을 사용하는 메서드를 여러 개 정의할 수 없습니다. - - - - UTA024: {0}: Cannot define more than one method with the TestCleanup attribute. - UTA024: {0}: TestCleanup 특성을 사용하는 메서드를 여러 개 정의할 수 없습니다. - - - - UTA018: {0}: Cannot define more than one method with the TestInitialize attribute. - UTA018: {0}: TestInitialize 특성을 사용하는 메서드를 여러 개 정의할 수 없습니다. - - - - TestClass attribute defined on generic non-abstract class {0} - 일반 비추상 클래스 {0}에 정의된 TestClass 속성 - - - - Initialization method {0}.{1} threw exception. {2}. - 초기화 메서드 {0}.{1}에서 예외를 throw했습니다. {2}. - - - - Unable to create instance of class {0}. Error: {1}. - {0} 클래스의 인스턴스를 만들 수 없습니다. 오류: {1} - - - - The test method '{0}.{1}' has multiple attributes derived from '{2}' defined on it. Only one such attribute is allowed. - 테스트 메서드 '{0}.{1}'에 {2}에서 파생된 여러 특성이 정의되어 있습니다. 이러한 특성은 하나만 허용됩니다. - - - - Cannot find a valid constructor for test class '{0}'. Valid constructors are 'public' and either parameterless or with one parameter of type 'TestContext'. - 테스트 클래스 '{0}'에 대한 유효한 생성자를 찾을 수 없습니다. 유효한 생성자는 'public'이며 매개 변수가 없거나 'TestContext' 유형의 매개 변수가 하나 있습니다. - - - - Unable to set TestContext property for the class {0}. Error: {1}. - {0} 클래스에 대해 TestContext 속성을 설정할 수 없습니다. 오류: {1} - - - - (Failed to get the message for an exception of type {0} due to an exception.) - (예외로 인해 {0} 형식의 예외에 대한 메시지를 가져오지 못했습니다.) - - - - UTA031: class {0} does not have valid TestContext property. TestContext must be of type TestContext, must be non-static, and must be public. For example: public TestContext TestContext. - UTA031: {0} 클래스에 유효한 TestContext 속성이 없습니다. TestContext는 TestContext 유형이어야 하고, 정적이 아니어야 하며, 일반적이어야 합니다. 예: public TestContext TestContext. - - - - UTA001: TestClass attribute defined on non-public class {0} - UTA001: public이 아닌 클래스 {0}에서 TestClass 특성을 정의했습니다. - - - - MSTestAdapter failed to discover tests in class '{0}' of assembly '{1}' because {2}. - MSTestAdapter가 {2} 때문에 어셈블리 '{1}'의 클래스 '{0}'에서 테스트를 검색하지 못했습니다. - - - - {0}: {1} - {0}: {1} - - - - Unable to load types from the test source '{0}'. Some or all of the tests in this source may not be discovered. -Error: {1} - 테스트 소스 '{0}'에서 형식을 로드할 수 없습니다. 이 소스의 일부 또는 모든 테스트를 검색할 수 없습니다. -오류: {1} - - - - File does not exist: {0} - 파일이 없습니다. {0} - - - - UTA007: Method {1} defined in class {0} does not have correct signature. Test method marked with the [TestMethod] attribute must be non-static, public, return-type as void and should not take any parameter. Example: public void Test.Class1.Test(). Additionally, if you are using async-await in test method then return-type must be 'Task' or 'ValueTask'. Example: public async Task Test.Class1.Test2() - UTA007: 클래스 {0}에 정의된 메서드 {1}에 올바른 서명이 없습니다. [TestMethod] 특성으로 표시된 테스트 메서드는 non-static, public, return-type이 void여야 하며 매개 변수를 사용하지 않아야 합니다. 예: public void Test.Class1.Test(). 또한 테스트 메서드에서 비동기 대기를 사용하는 경우 반환 형식은 Task여야 합니다. 예: public async Task Test.Class1.Test2() - - - - TestContext cannot be Null. - TestContext는 null일 수 없습니다. - - - - Assembly Cleanup method {0}.{1} failed. Error Message: {2}. StackTrace: {3} - 어셈블리 정리 메서드 {0}.{1}이(가) 실패했습니다. 오류 메시지: {2}. StackTrace: {3} - - - - Assembly Initialization method {0}.{1} threw exception. {2}: {3}. Aborting test execution. - 어셈블리 초기화 메서드 {0}.{1}에서 예외를 throw했습니다. {2}: {3}. 테스트 실행을 중단합니다. - - - - Class Cleanup method {0}.{1} failed. Error Message: {2}. Stack Trace: {3} - 클래스 정리 메서드 {0}.{1}이(가) 실패했습니다. 오류 메시지: {2}. 스택 추적: {3} - - - - Class Initialization method {0}.{1} threw exception. {2}: {3}. - 클래스 초기화 메서드 {0}.{1}에서 예외를 throw했습니다. {2}: {3} - - - - An unhandled exception was thrown by the 'Execute' method. Please report this error to the author of the attribute '{0}'. -{1} - 'Execute' 메서드에서 처리되지 않은 예외가 throw되었습니다. 특성 '{0}' 만든 이에게 이 오류를 보고하십시오. -{1} - - - - Error in executing test. No result returned by extension. If using extension of TestMethodAttribute then please contact vendor. - 테스트를 실행하는 중에 오류가 발생했습니다. 확장에서 결과가 반환되지 않았습니다. TestMethodAttribute 확장을 사용하는 경우 공급업체에 문의하세요. - - - - Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. - {0}.{1} 메서드의 서명이 잘못되었습니다. 메서드는 정적이고 공용이어야 하며, 값을 반환하거나 매개 변수를 취하지 않습니다. 또한 메서드에서 비동기 대기를 사용하는 경우 반환 형식은 'Task' 또는 'ValueTask'여야 합니다. - - - - Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should take a single parameter of type TestContext. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. - {0}.{1} 메서드의 서명이 잘못되었습니다. 메서드는 static, public이어야 하고, 값을 반환하지 않으며, TestContext 형식의 단일 매개 변수를 사용해야 합니다. 또한 메서드에서 비동기 대기를 사용하는 경우 반환 형식은 'Task' 또는 'ValueTask'여야 합니다. - - - - UTA054: {0}.{1} has invalid Timeout attribute. The timeout must be an integer value greater than 0. - UTA054: {0}.{1}에 잘못된 Timeout 특성이 있습니다. 시간 제한 값은 0보다 큰 정수여야 합니다. - - - - UTA023: {0}: Cannot define predefined property {2} on method {1}. - UTA023: {0}: {1} 메서드에서 미리 정의된 속성 {2}을(를) 정의할 수 없습니다. - - - - UTA021: {0}: Null or empty custom property defined on method {1}. The custom property must have a valid name. - UTA021: {0}: {1} 메서드에서 Null 또는 빈 사용자 지정 속성을 정의했습니다. 사용자 지정 속성에는 올바른 이름이 지정되어 있어야 합니다. - - - - Method {0}.{1} does not exist. - {0}.{1} 메서드가 없습니다. - - - - Unable to find property {0}.TestContext. Error:{1}. - {0}.TestContext 속성을 찾을 수 없습니다. 오류: {1} - - - - The {0}.TestContext has incorrect type. - {0}.TestContext의 형식이 잘못되었습니다. - - - - Method {0}.{1} has wrong signature. The method must be non-static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. - {0}.{1} 메서드의 서명이 잘못되었습니다. 메서드는 정적이 아니고 공용이어야 하며, 값을 반환하거나 매개 변수를 사용할 수 없습니다. 또한 메서드에서 비동기 대기를 사용하는 경우 반환 형식은 'Task' 또는 'ValueTask'여야 합니다. - - - - Unable to get type {0}. Error: {1}. - {0} 형식을 가져올 수 없습니다. 오류: {1} - - - - Test method {0} was not found. - {0} 테스트 메서드를 찾을 수 없습니다. - - - - Debug Trace: - 디버그 추적: - - - - Failed to obtain the exception thrown by test method {0}.{1}. - 테스트 메서드 {0}.{1}에서 throw한 예외를 가져오지 못했습니다. - - - - Test method {0}.{1} threw exception: -{2} - 테스트 메서드 {0}.{1}에서 예외를 throw했습니다. -{2} - - - - {0} For UWP projects, if you are using UI objects in test consider using [UITestMethod] attribute instead of [TestMethod] to execute test in UI thread. - {0} UWP 프로젝트의 경우 테스트에서 UI 개체를 사용 중이면 [TestMethod] 대신 [UITestMethod] 특성을 사용하여 UI 스레드에서 테스트를 실행하세요. - - - - MSTestAdapterV2 - MSTestAdapterV2 - - - - Invalid settings '{0}'. Unexpected XmlAttribute: '{1}'. - '{0}' 설정이 잘못되었습니다. 예기치 않은 XmlAttribute '{1}'이(가) 있습니다. - - - - Invalid settings '{0}'. Unexpected XmlElement: '{1}'. - '{0}' 설정이 잘못되었습니다. 예기치 않은 XmlElement '{1}'이(가) 있습니다. - - - - {0} (Data Row {1}) - {0}(데이터 행 {1}) - - - - The ExpectedException attribute defined on test method {0}.{1} threw an exception during construction. -{2} - 테스트 메서드 {0}.{1}에 정의된 ExpectedException 특성이 생성하는 동안 예외를 throw했습니다. -{2} - - - - Warning : A testsettings file or a vsmdi file is not supported with the MSTest V2 Adapter. - 경고: MSTest V2 어댑터에서는 testsettings 파일 또는 vsmdi 파일이 지원되지 않습니다. - - - - TestContext Messages: - TestContext 메시지: - - - - Error calling Test Cleanup method for test class {0}: {1} - 테스트 클래스 {0}에 대한 테스트 정리 메서드를 호출하는 오류: {1} - - - - TestCleanup Stack Trace - TestCleanup 스택 추적 - - - - [MSTest][Discovery][{0}] {1} - [MSTest][검색][{0}] {1} - - - - Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) - {0}에 대해 테스트 병렬 처리를 사용합니다(Workers: {1}, Scope: {2}). - `Workers` is a setting name that shouldn't be localized. 'Scope' is a setting name that shouldn't be localized. - - - Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. - 'Scope'에 대해 잘못된 값 '{0}'이(가) 지정되었습니다. 지원되는 범위는 {1}입니다. - 'Scope' is a setting name that shouldn't be localized. - - - Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. - 'Workers'에 대해 잘못된 값 '{0}'이(가) 지정되었습니다. 이 값은 음수가 아닌 정수여야 합니다. - `Workers` is a setting name that shouldn't be localized. - - - Failed to discover tests from assembly {0}. Reason:{1} - 어셈블리 {0}에서 테스트를 검색하지 못했습니다. 이유:{1} - - - - Test '{0}' was canceled - 테스트 '{0}' 취소되었습니다. - - - - Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. - 'ClassCleanupLifecycle'에 대해 '{0}' 잘못된 값이 지정되었습니다. 지원되는 범위는 {1}입니다. - 'ClassCleanupLifecycle' is a setting name that shouldn't be localized. - - - Exception occurred while enumerating IDataSource attribute on "{0}.{1}": {2} - "{0}.{1}"에서 IDataSource 특성을 열거하는 동안 예외가 발생했습니다. {2} - {0}: TypeName with namespace, -{1}: Method name, -{2}: Exception details - - - "{0}": (Failed to get exception description due to an exception of type "{1}". - "{0}": ("{1}" 형식의 예외로 인해 예외 설명을 가져오지 못했습니다. - {0}: Type of the original exception that we're trying to get the description of. -{1}: Thrown exception - - - Exceptions thrown: - 예외 발생: - This is usually precedes by TestAssembly_AssemblyDiscoveryFailure message, and preceded by list of exceptions thrown in a test discovery session. - - - Getting custom attributes for type {0} threw exception (will ignore and use the reflection way): {1} - {0} 형식에 대한 사용자 지정 특성을 가져오는 데 예외가 발생했습니다(무시하고 리플렉션 방법 사용). {1} - {0}: Attribute full type name. -{1}: Exception description - - - An older version of MSTestV2 package is loaded in assembly, test discovery might fail to discover all data tests if they depend on `.runsettings` file. - 이전 버전 MSTestV2 패키지가 어셈블리에 로드되어 테스트 검색이 '.runsettings' 파일에 종속된 경우 모든 데이터 테스트를 검색하지 못할 수 있습니다. - - - - The called code threw an exception that was caught, but the exception value was null - 호출된 코드에서 확인된 예외가 발생했지만 예외 값이 null입니다. - - - - Exception occurred while expanding IDataSource rows from attribute on "{0}.{1}": {2} - "{0}.{1}"의 특성에서 IDataSource 행을 확장하는 동안 예외가 발생했습니다. {2} - {0}: TypeName with namespace, -{1}: Method name, -{2}: CannotExpandIDataSourceAttribute_DuplicateDisplayName or CannotExpandIDataSourceAttribute_CannotSerialize - - - Display name "{2}" on indexes {0} and {1} are duplicate. Display names should be unique. - {0} 및 {1} 인덱스의 "{2}" 표시 이름이 중복됩니다. 표시 이름은 고유해야 합니다. - {0}, {1}: Zero based index if an element inside of an array -{2}: Test display name. - - - Data on index {0} for "{1}" cannot be serialized. All data provided through "IDataSource" should be serializable. If you need to test non-serializable data sources, please make sure you add "TestDataSourceDiscovery" attribute on your test assembly and set the discovery option to "DuringExecution". - "{1}"에 대한 {0} 인덱스의 데이터를 직렬화할 수 없습니다. "IDataSource"를 통해 제공된 모든 데이터를 직렬화할 수 있어야 합니다. 직렬화할 수 없는 데이터 원본을 테스트해야 하는 경우 테스트 어셈블리에 "TestDataSourceDiscovery" 특성을 추가하고 검색 옵션을 "DuringExecution"으로 설정하세요. - {0}: Zero based index if an element inside of an array, -{1}: Test name - - - - \ No newline at end of file diff --git a/src/Adapter/MSTest.TestAdapter/Resources/xlf/Resource.pl.xlf b/src/Adapter/MSTest.TestAdapter/Resources/xlf/Resource.pl.xlf deleted file mode 100644 index e229b5db52..0000000000 --- a/src/Adapter/MSTest.TestAdapter/Resources/xlf/Resource.pl.xlf +++ /dev/null @@ -1,482 +0,0 @@ - - - - - - Assembly cleanup method '{0}.{1}' timed out after {2}ms - Metoda oczyszczania zestawu „{0}.{1}” przekroczyła limit czasu po {2}ms - - - - Assembly cleanup method '{0}.{1}' was canceled - Anulowano metodę oczyszczania zestawu „{0}.{1}” - - - - Assembly initialize method '{0}.{1}' timed out after {2}ms - Metoda inicjalizacji zestawu „{0}.{1}” przekroczyła limit czasu po {2}ms - - - - Assembly initialize method '{0}.{1}' was canceled - Anulowano metodę inicjowania zestawu „{0}.{1}” - - - - Cannot run test method '{0}.{1}': Test data doesn't match method parameters. Either the count or types are different. -Test expected {2} parameter(s), with types '{3}', -but received {4} argument(s), with types '{5}'. - Nie można uruchomić metody testowej „{0}.{1}”: dane testowe nie są zgodne z parametrami metody. Liczba lub typy są różne. -Testowanie oczekiwanych {2} parametrów z typami „{3}”, -ale liczba odebranych argumentów to {4} z typami „{5}”. - - - - Cannot run test method '{0}.{1}': Method has parameters, but does not define any test source. Use '[DataRow]', '[DynamicData]', or a custom 'ITestDataSource' data source to provide test data. - Nie można uruchomić metody testowej „{0}.{1}”: metoda ma parametry, ale nie definiuje żadnego źródła testu. Użyj źródła danych „[DataRow]”, „[DynamicData]” lub niestandardowego źródła danych „ITestDataSource”, aby dostarczyć dane testowe. - - - - Class cleanup method '{0}.{1}' timed out after {2}ms - Metoda oczyszczania klasy „{0}.{1}” przekroczyła limit czasu po {2}ms - - - - Class cleanup method '{0}.{1}' was canceled - Anulowano metodę oczyszczania klasy „{0}.{1}” - - - - Class initialize method '{0}.{1}' timed out after {2}ms - Metoda inicjalizacji klasy „{0}.{1}” przekroczyła limit czasu po {2}ms - - - - Class initialize method '{0}.{1}' was canceled - Anulowano metodę inicjowania klasy „{0}.{1}” - - - - Both '.runsettings' and '.testconfig.json' files have been detected. Please select only one of these test configuration files. - Wykryto zarówno pliki „.runsettings”, jak i „.testconfig.json”. Wybierz tylko jeden z tych plików konfiguracji testu. - - - - Test '{0}' timed out after {1}ms - Upłynął limit czasu '{0}' testu po {1}ms - - - - The type of the generic parameter '{0}' could not be inferred. - Nie można wywnioskować typu '{0}' parametru ogólnego. - - - - The generic test method '{0}' doesn't have arguments, so the generic parameter cannot be inferred. - Ogólna metoda testowa '{0}' nie ma argumentów, więc nie można wywnioskować parametru ogólnego. - - - - Found two conflicting types for generic parameter '{0}'. The conflicting types are '{1}' and '{2}'. - Znaleziono dwa typy powodujące konflikt dla parametru ogólnego '{0}'. Typy powodujące konflikty są '{1}' i '{2}'. - - - - Invalid value '{0}' for runsettings entry '{1}', setting will be ignored. - Nieprawidłowa wartość „{0}” dla wpisu runsettings „{1}”. Ustawienie zostanie zignorowane. - - - - Runsettings entry '<ExecutionApartmentState>STA</ExecutionApartmentState>' is not supported on non-Windows OSes. - Wpis runsettings „<ExecutionApartmentState>STA</ExecutionApartmentState>” nie jest obsługiwany w systemach operacyjnych innych niż Windows. - - - - Running tests in any of the provided sources is not supported for the selected platform - Uruchamianie testów w żadnym z podanych źródeł nie jest obsługiwane dla wybranej platformy - - - - Test cleanup method '{0}.{1}' timed out after {2}ms - Metoda oczyszczania testu „{0}.{1}” przekroczyła limit czasu po {2}ms - - - - Test cleanup method '{0}.{1}' was canceled - Anulowano metodę oczyszczania testu „{0}.{1}” - - - - Test initialize method '{0}.{1}' timed out after {2}ms - Metoda inicjalizacji testu „{0}.{1}” przekroczyła limit czasu po {2}ms - - - - Test initialize method '{0}.{1}' was canceled - Anulowano metodę inicjowania testu „{0}.{1}” - - - - TestCleanup method {0}.{1} threw exception. {2}. - Metoda TestCleanup {0}.{1} zgłosiła wyjątek {2}. - - - - --- End of inner exception stack trace --- - --- Koniec śledzenia stosu wyjątku wewnętrznego --- - - - - UTA014: {0}: Cannot define more than one method with the AssemblyCleanup attribute inside an assembly. - UTA014: {0}: W zestawie nie można zdefiniować więcej niż jednej metody z atrybutem AssemblyCleanup. - - - - UTA013: {0}: Cannot define more than one method with the AssemblyInitialize attribute inside an assembly. - UTA013: {0}: W zestawie nie można zdefiniować więcej niż jednej metody z atrybutem AssemblyInitialize. - - - - UTA026: {0}: Cannot define more than one method with the ClassCleanup attribute inside a class. - UTA026: {0}: W klasie nie można zdefiniować więcej niż jednej metody z atrybutem ClassCleanup. - - - - UTA025: {0}: Cannot define more than one method with the ClassInitialize attribute inside a class. - UTA025: {0}: W klasie nie można zdefiniować więcej niż jednej metody z atrybutem ClassInitialize. - - - - UTA024: {0}: Cannot define more than one method with the TestCleanup attribute. - UTA024: {0}: Nie można zdefiniować więcej niż jednej metody z atrybutem TestCleanup. - - - - UTA018: {0}: Cannot define more than one method with the TestInitialize attribute. - UTA018: {0}: Nie można zdefiniować więcej niż jednej metody z atrybutem TestInitialize. - - - - TestClass attribute defined on generic non-abstract class {0} - Atrybut TestClass zdefiniowany w ogólnej klasie nieabstrakcyjnej {0} - - - - Initialization method {0}.{1} threw exception. {2}. - Metoda inicjowania {0}.{1} zgłosiła wyjątek. {2}. - - - - Unable to create instance of class {0}. Error: {1}. - Nie można utworzyć wystąpienia klasy {0}. Błąd: {1}. - - - - The test method '{0}.{1}' has multiple attributes derived from '{2}' defined on it. Only one such attribute is allowed. - Metoda testowa "{0}.{1}” ma zdefiniowanych wiele atrybutów pochodzących z „{2}”. Dozwolony jest tylko jeden taki atrybut. - - - - Cannot find a valid constructor for test class '{0}'. Valid constructors are 'public' and either parameterless or with one parameter of type 'TestContext'. - Nie można odnaleźć prawidłowego konstruktora dla klasy testowej „{0}”. Prawidłowe konstruktory są „publiczne” i albo bez parametrów, albo z jednym parametrem typu „TestContext”. - - - - Unable to set TestContext property for the class {0}. Error: {1}. - Nie można ustawić właściwości TestContext w klasie {0}. Błąd: {1}. - - - - (Failed to get the message for an exception of type {0} due to an exception.) - (Nie można pobrać komunikatu dotyczącego wyjątku typu {0} z powodu wyjątku). - - - - UTA031: class {0} does not have valid TestContext property. TestContext must be of type TestContext, must be non-static, and must be public. For example: public TestContext TestContext. - UTA031: Klasa {0}nie ma prawidłowej właściwości TestContext. Element TestContext musi być typu TestContext, musi być niestatyczny i musi być publiczny. Na przykład : public TestContext TestContext. - - - - UTA001: TestClass attribute defined on non-public class {0} - UTA001: Atrybut TestClass zdefiniowany dla niepublicznej klasy {0} - - - - MSTestAdapter failed to discover tests in class '{0}' of assembly '{1}' because {2}. - Adapter MSTestAdapter nie mógł odnaleźć testów w klasie „{0}” zestawu „{1}”, przyczyna: {2}. - - - - {0}: {1} - {0}: {1} - - - - Unable to load types from the test source '{0}'. Some or all of the tests in this source may not be discovered. -Error: {1} - Nie można załadować typów ze źródła testów „{0}”. Niektóre lub wszystkie testy w tym źródle mogły nie zostać odnalezione. -Błąd: {1} - - - - File does not exist: {0} - Plik nie istnieje: {0} - - - - UTA007: Method {1} defined in class {0} does not have correct signature. Test method marked with the [TestMethod] attribute must be non-static, public, return-type as void and should not take any parameter. Example: public void Test.Class1.Test(). Additionally, if you are using async-await in test method then return-type must be 'Task' or 'ValueTask'. Example: public async Task Test.Class1.Test2() - UTA007: metoda {1} zdefiniowana w klasie {0}nie ma poprawnej sygnatury. Metoda testowa oznaczona przez atrybut [TestMethod] musi być niestatyczna, publiczna, zwracać wartość typu void i nie powinna przyjmować żadnego parametru. Przykład: public void Test.Class1.Test(). Ponadto, jeśli używasz oczekiwanie asynchroniczne w metodzie testowej, wtedy zwracanym typem musi być „Task” lub „ValueTask”. Przykład: public async Task Test.Class1.Test2() - - - - TestContext cannot be Null. - Wartość TestContext nie może być równa null. - - - - Assembly Cleanup method {0}.{1} failed. Error Message: {2}. StackTrace: {3} - Metoda czyszczenia zestawu {0}.{1} nie powiodła się. Komunikat o błędzie: {2}. Ślad stosu: {3} - - - - Assembly Initialization method {0}.{1} threw exception. {2}: {3}. Aborting test execution. - Metoda inicjująca zestaw {0}.{1} nie powiodła się. {2}: {3}. Przerywanie wykonywania testu. - - - - Class Cleanup method {0}.{1} failed. Error Message: {2}. Stack Trace: {3} - Metoda czyszczenia klasy {0}.{1} nie powiodła się. Komunikat o błędzie: {2}. Ślad stosu: {3} - - - - Class Initialization method {0}.{1} threw exception. {2}: {3}. - Metoda inicjowania klasy {0}.{1} zgłosiła wyjątek. {2}: {3}. - - - - An unhandled exception was thrown by the 'Execute' method. Please report this error to the author of the attribute '{0}'. -{1} - Metoda Execute zgłosiła nieobsługiwany wyjątek. Zgłoś ten błąd autorowi atrybutu '{0}'. -{1} - - - - Error in executing test. No result returned by extension. If using extension of TestMethodAttribute then please contact vendor. - Błąd podczas wykonywania testu. Rozszerzenie nie zwróciło żadnego wyniku. W przypadku korzystania z rozszerzenia atrybutu TestMethodAttribute należy skontaktować się z dostawcą. - - - - Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. - Metoda {0}.{1}ma nieprawidłową sygnaturę. Metoda musi być statyczna, publiczna, nie może zwracać wartości i nie powinna przyjmować żadnego parametru. Ponadto jeśli w metodzie jest używane oczekiwanie asynchroniczne, wtedy zwracanym typem musi być typ „Task” lub „ValueTask”. - - - - Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should take a single parameter of type TestContext. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. - Metoda {0}.{1}ma nieprawidłową sygnaturę. Metoda musi być statyczna, publiczna, nie może zwracać wartości i powinna mieć jeden parametr typu TestContext. Ponadto jeśli w metodzie jest używane oczekiwanie asynchroniczne, wtedy zwracanym typem musi być typ „Task” lub „ValueTask”. - - - - UTA054: {0}.{1} has invalid Timeout attribute. The timeout must be an integer value greater than 0. - UTA054: {0}.{1} ma nieprawidłowy atrybut Timeout. Limit czasu musi być liczbą całkowitą większą niż 0. - - - - UTA023: {0}: Cannot define predefined property {2} on method {1}. - UTA023: {0}: Nie można zdefiniować wstępnie zdefiniowanej właściwości {2} dla metody {1}. - - - - UTA021: {0}: Null or empty custom property defined on method {1}. The custom property must have a valid name. - UTA021: {0}: Zerowa lub pusta niestandardowa właściwość została zdefiniowana dla metody {1}. Niestandardowa właściwość musi mieć prawidłową nazwę. - - - - Method {0}.{1} does not exist. - Metoda {0}.{1} nie istnieje. - - - - Unable to find property {0}.TestContext. Error:{1}. - Nie można znaleźć właściwości {0}.TestContext. Błąd:{1}. - - - - The {0}.TestContext has incorrect type. - Element {0}.TestContext ma niepoprawny typ. - - - - Method {0}.{1} has wrong signature. The method must be non-static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. - Metoda {0}.{1}ma nieprawidłową sygnaturę. Metoda musi być niestatyczna, publiczna, nie może zwracać wartości i nie powinna przyjmować żadnego parametru. Ponadto jeśli w metodzie jest używane oczekiwanie asynchroniczne, wtedy zwracanym typem musi być typ „Task” lub „ValueTask”. - - - - Unable to get type {0}. Error: {1}. - Nie można uzyskać typu {0}. Błąd: {1}. - - - - Test method {0} was not found. - Nie znaleziono metody testowej {0}. - - - - Debug Trace: - Ślad debugowania: - - - - Failed to obtain the exception thrown by test method {0}.{1}. - Nie powiodło się uzyskanie wyjątku zgłoszonego przez metodę testową {0}.{1}. - - - - Test method {0}.{1} threw exception: -{2} - Metoda testowa {0}.{1} zgłosiła wyjątek: -{2} - - - - {0} For UWP projects, if you are using UI objects in test consider using [UITestMethod] attribute instead of [TestMethod] to execute test in UI thread. - {0} Jeśli w projektach UWP korzystasz z obiektów interfejsu użytkownika podczas testowania, rozważ użycie atrybutu [UITestMethod] zamiast atrybutu [TestMethod], aby wykonywać test w wątku interfejsu użytkownika. - - - - MSTestAdapterV2 - MSTestAdapterV2 - - - - Invalid settings '{0}'. Unexpected XmlAttribute: '{1}'. - Nieprawidłowe ustawienia „{0}”. Nieoczekiwany atrybut XmlAttribute: „{1}”. - - - - Invalid settings '{0}'. Unexpected XmlElement: '{1}'. - Nieprawidłowe ustawienia „{0}”. Nieoczekiwany atrybut XmlElement: „{1}”. - - - - {0} (Data Row {1}) - {0} (wiersz danych {1}) - - - - The ExpectedException attribute defined on test method {0}.{1} threw an exception during construction. -{2} - Atrybut ExpectedException zdefiniowany dla metody testowej {0}.{1} zgłosił wyjątek w trakcie konstruowania. -{2} - - - - Warning : A testsettings file or a vsmdi file is not supported with the MSTest V2 Adapter. - Ostrzeżenie: Plik testsettings lub plik vsmdi nie jest obsługiwany przez adapter MSTest w wersji 2. - - - - TestContext Messages: - Komunikaty TestContext: - - - - Error calling Test Cleanup method for test class {0}: {1} - Błąd podczas wywoływania metody czyszczącej testu dla klasy testowej {0}: {1} - - - - TestCleanup Stack Trace - Ślad stosu dla TestCleanup - - - - [MSTest][Discovery][{0}] {1} - [MSTest][Discovery][{0}] {1} - - - - Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) - Przetwarzanie równoległe testów włączono dla {0} (procesy robocze: {1}, zakres: {2}) - `Workers` is a setting name that shouldn't be localized. 'Scope' is a setting name that shouldn't be localized. - - - Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. - Określono nieprawidłową wartość „{0}” dla właściwości „Scope”. Obsługiwane zakresy to {1}. - 'Scope' is a setting name that shouldn't be localized. - - - Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. - Określono nieprawidłową wartość „{0}” dla właściwości „Workers”. Wartość musi być nieujemną liczbą całkowitą. - `Workers` is a setting name that shouldn't be localized. - - - Failed to discover tests from assembly {0}. Reason:{1} - Nie można odnaleźć testów z zestawu {0}. Przyczyna:{1} - - - - Test '{0}' was canceled - Anulowano '{0}' testowe - - - - Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. - Dla ustawienia „ClassCleanupLifecycle” określono nieprawidłową wartość „{0}”. Obsługiwane zakresy to {1}. - 'ClassCleanupLifecycle' is a setting name that shouldn't be localized. - - - Exception occurred while enumerating IDataSource attribute on "{0}.{1}": {2} - Wystąpił wyjątek podczas wyliczania atrybutu IDataSource w przestrzeni nazwy „{0}.{1}”: {2} - {0}: TypeName with namespace, -{1}: Method name, -{2}: Exception details - - - "{0}": (Failed to get exception description due to an exception of type "{1}". - „{0}”: (Nie można uzyskać opisu wyjątku z powodu wyjątku typu „{1}”. - {0}: Type of the original exception that we're trying to get the description of. -{1}: Thrown exception - - - Exceptions thrown: - Zgłoszone wyjątki: - This is usually precedes by TestAssembly_AssemblyDiscoveryFailure message, and preceded by list of exceptions thrown in a test discovery session. - - - Getting custom attributes for type {0} threw exception (will ignore and use the reflection way): {1} - Pobieranie atrybutów niestandardowych dla typu {0} zgłosiło wyjątek (zignoruje i użyje sposobu odbicia): {1} - {0}: Attribute full type name. -{1}: Exception description - - - An older version of MSTestV2 package is loaded in assembly, test discovery might fail to discover all data tests if they depend on `.runsettings` file. - Starsza wersja pakietu MSTestV2 jest załadowana do zestawu. Odnajdywanie testów może nie odnaleźć wszystkich testów danych, jeśli zależą od pliku „.runsettings”. - - - - The called code threw an exception that was caught, but the exception value was null - Wywołany kod zgłosił wyjątek, który został przechwycony, ale wartość wyjątku miała wartość null - - - - Exception occurred while expanding IDataSource rows from attribute on "{0}.{1}": {2} - Wystąpił wyjątek podczas rozwijania wierszy IDataSource z atrybutu w przestrzeni nazw „{0}.{1}”: {2} - {0}: TypeName with namespace, -{1}: Method name, -{2}: CannotExpandIDataSourceAttribute_DuplicateDisplayName or CannotExpandIDataSourceAttribute_CannotSerialize - - - Display name "{2}" on indexes {0} and {1} are duplicate. Display names should be unique. - Nazwa wyświetlana „{2}” w indeksach {0} i {1} jest duplikatem. Nazwy wyświetlane powinny być unikatowe. - {0}, {1}: Zero based index if an element inside of an array -{2}: Test display name. - - - Data on index {0} for "{1}" cannot be serialized. All data provided through "IDataSource" should be serializable. If you need to test non-serializable data sources, please make sure you add "TestDataSourceDiscovery" attribute on your test assembly and set the discovery option to "DuringExecution". - Nie można serializować danych w indeksie {0} dla „{1}”. Wszystkie dane dostarczane za pomocą źródła „IDataSource” powinny być możliwe do serializacji. Jeśli chcesz przetestować nieserializowalne źródła danych, upewnij się, że dodasz atrybut „ TestDataSourceDiscovery” w zestawie testowym i ustaw opcję odnajdywania na wartość „DuringExecution”. - {0}: Zero based index if an element inside of an array, -{1}: Test name - - - - \ No newline at end of file diff --git a/src/Adapter/MSTest.TestAdapter/Resources/xlf/Resource.pt-BR.xlf b/src/Adapter/MSTest.TestAdapter/Resources/xlf/Resource.pt-BR.xlf deleted file mode 100644 index fbd82fe886..0000000000 --- a/src/Adapter/MSTest.TestAdapter/Resources/xlf/Resource.pt-BR.xlf +++ /dev/null @@ -1,482 +0,0 @@ - - - - - - Assembly cleanup method '{0}.{1}' timed out after {2}ms - O método de limpeza da montagem '{0}.{1}' atingiu o tempo limite após {2}ms - - - - Assembly cleanup method '{0}.{1}' was canceled - O método de limpeza do assembly "{0}.{1}" foi cancelado - - - - Assembly initialize method '{0}.{1}' timed out after {2}ms - O método de inicialização da montagem '{0}.{1}' atingiu o tempo limite após {2}ms - - - - Assembly initialize method '{0}.{1}' was canceled - O método de inicialização do assembly "{0}.{1}" foi cancelado - - - - Cannot run test method '{0}.{1}': Test data doesn't match method parameters. Either the count or types are different. -Test expected {2} parameter(s), with types '{3}', -but received {4} argument(s), with types '{5}'. - Não é possível executar o método de teste '{0}.{1}': Os dados de teste não correspondem aos parâmetros do método. A contagem ou os tipos são diferentes. -Testar {2} parâmetros esperados, com tipos '{3}', -mas {4} argumentos recebidos, com tipos '{5}'. - - - - Cannot run test method '{0}.{1}': Method has parameters, but does not define any test source. Use '[DataRow]', '[DynamicData]', or a custom 'ITestDataSource' data source to provide test data. - Não é possível executar o método de teste '{0}.{1}': o método tem parâmetros, mas não define nenhuma fonte de teste. Use '[DataRow]', '[DynamicData]' ou uma fonte de dados 'ITestDataSource' personalizada para fornecer dados de teste. - - - - Class cleanup method '{0}.{1}' timed out after {2}ms - O método de limpeza da classe '{0}.{1}' atingiu o tempo limite após {2}ms - - - - Class cleanup method '{0}.{1}' was canceled - O método de limpeza de classe "{0}.{1}" foi cancelado - - - - Class initialize method '{0}.{1}' timed out after {2}ms - O método de inicialização da classe '{0}.{1}' atingiu o tempo limite após {2}ms - - - - Class initialize method '{0}.{1}' was canceled - O método de inicialização de classe "{0}.{1}" foi cancelado - - - - Both '.runsettings' and '.testconfig.json' files have been detected. Please select only one of these test configuration files. - Ambos os arquivos '.runsettings' e '.testconfig.json' foram detectados. Selecione apenas um desses arquivos de configuração de teste. - - - - Test '{0}' timed out after {1}ms - Tempo '{0}' tempo limite do teste após {1}ms - - - - The type of the generic parameter '{0}' could not be inferred. - Não foi possível inferir o tipo '{0}' parâmetro genérico. - - - - The generic test method '{0}' doesn't have arguments, so the generic parameter cannot be inferred. - O método de teste genérico '{0}' não tem argumentos, portanto, o parâmetro genérico não pode ser inferido. - - - - Found two conflicting types for generic parameter '{0}'. The conflicting types are '{1}' and '{2}'. - Foram encontrados dois tipos conflitativos para parâmetro genérico '{0}'. Os tipos conflitativos são '{1}' e '{2}'. - - - - Invalid value '{0}' for runsettings entry '{1}', setting will be ignored. - Valor inválido "{0}" para a entrada runsettings "{1}", a configuração será ignorada. - - - - Runsettings entry '<ExecutionApartmentState>STA</ExecutionApartmentState>' is not supported on non-Windows OSes. - Não há suporte para a entrada runsettings "<ExecutionApartmentState>STA</ExecutionApartmentState>" em sistemas operacionais que não sejam Windows. - - - - Running tests in any of the provided sources is not supported for the selected platform - Não há suporte para execução de teste em qualquer uma das origens fontes fornecidas para a plataforma selecionada - - - - Test cleanup method '{0}.{1}' timed out after {2}ms - O método de limpeza do teste '{0}.{1}' atingiu o tempo limite após {2}ms - - - - Test cleanup method '{0}.{1}' was canceled - O método de limpeza de teste "{0}.{1}" foi cancelado - - - - Test initialize method '{0}.{1}' timed out after {2}ms - O método de inicialização do teste '{0}.{1}' atingiu o tempo limite após {2}ms - - - - Test initialize method '{0}.{1}' was canceled - O método de inicialização de teste "{0}.{1}" foi cancelado - - - - TestCleanup method {0}.{1} threw exception. {2}. - O método TestCleanup {0}.{1} gerou a exceção. {2}. - - - - --- End of inner exception stack trace --- - --- Fim do rastreamento de pilha de exceção interna --- - - - - UTA014: {0}: Cannot define more than one method with the AssemblyCleanup attribute inside an assembly. - UTA014: {0}: não é possível definir mais de um método com o atributo AssemblyCleanup em um assembly. - - - - UTA013: {0}: Cannot define more than one method with the AssemblyInitialize attribute inside an assembly. - UTA013: {0}: não é possível definir mais de um método com o atributo AssemblyInitialize dentro de um assembly. - - - - UTA026: {0}: Cannot define more than one method with the ClassCleanup attribute inside a class. - UTA026: {0}: não é possível definir mais de um método com o atributo ClassCleanup dentro de uma classe. - - - - UTA025: {0}: Cannot define more than one method with the ClassInitialize attribute inside a class. - UTA025: {0}: não é possível definir mais de um método com o atributo ClassInitialize em uma classe. - - - - UTA024: {0}: Cannot define more than one method with the TestCleanup attribute. - UTA024: {0}: não é possível definir mais de um método com o atributo TestCleanup. - - - - UTA018: {0}: Cannot define more than one method with the TestInitialize attribute. - UTA018: {0}: não é possível definir mais de um método com o atributo TestInitialize. - - - - TestClass attribute defined on generic non-abstract class {0} - Atributo TestClass definido em uma classe genérica não abstrata {0} - - - - Initialization method {0}.{1} threw exception. {2}. - O método de inicialização {0}.{1} gerou exceção. {2}. - - - - Unable to create instance of class {0}. Error: {1}. - Não é possível criar instância da classe {0}. Erro: {1}. - - - - The test method '{0}.{1}' has multiple attributes derived from '{2}' defined on it. Only one such attribute is allowed. - O método de teste '{0}.{1}' tem várias características derivadas de '{2}' definidas nele. Apenas uma dessas características tem permissão. - - - - Cannot find a valid constructor for test class '{0}'. Valid constructors are 'public' and either parameterless or with one parameter of type 'TestContext'. - Não é possível localizar um construtor válido para a classe de teste '{0}'. Construtores válidos são 'public' e sem parâmetros ou com um parâmetro do tipo 'TestContext'. - - - - Unable to set TestContext property for the class {0}. Error: {1}. - Não é definir a propriedade TestContext para a classe {0}. Erro: {1}. - - - - (Failed to get the message for an exception of type {0} due to an exception.) - (Falha ao obter a mensagem para uma exceção do tipo {0} devido a uma exceção.) - - - - UTA031: class {0} does not have valid TestContext property. TestContext must be of type TestContext, must be non-static, and must be public. For example: public TestContext TestContext. - UTA031: a classe {0} não tem uma propriedade TestContext válida. TestContext deve ser do tipo TestContext, não deve ser estático e deve ser público. Por exemplo: public TestContext TestContext. - - - - UTA001: TestClass attribute defined on non-public class {0} - UTA001: atributo TestClass definido em classe não pública {0} - - - - MSTestAdapter failed to discover tests in class '{0}' of assembly '{1}' because {2}. - O MSTestAdapter não conseguiu descobrir testes na classe '{0}' do assembly '{1}' devido a {2}. - - - - {0}: {1} - {0}: {1} - - - - Unable to load types from the test source '{0}'. Some or all of the tests in this source may not be discovered. -Error: {1} - Não é possível carregar tipos da fonte de teste '{0}'. Alguns ou todos os testes nessa fonte podem não ser descobertos. -Erro: {1} - - - - File does not exist: {0} - O arquivo não existe: {0} - - - - UTA007: Method {1} defined in class {0} does not have correct signature. Test method marked with the [TestMethod] attribute must be non-static, public, return-type as void and should not take any parameter. Example: public void Test.Class1.Test(). Additionally, if you are using async-await in test method then return-type must be 'Task' or 'ValueTask'. Example: public async Task Test.Class1.Test2() - UTA007: o método {1} definido na classe {0} não tem a assinatura correta. O método de teste marcado com o atributo [TestMethod] deve ser não estático, público, com tipo de retorno nulo e não deve receber parâmetros. Exemplo: Test.Class1.Test() público nulo. Além disso, se você estiver usando async-await no método de teste, return-type deverá ser "Task" ou "ValueTask". Exemplo: public async Task Test.Class1.Test2() - - - - TestContext cannot be Null. - TestContext não pode ser Nulo. - - - - Assembly Cleanup method {0}.{1} failed. Error Message: {2}. StackTrace: {3} - Falha no método de Limpeza de Assembly {0}.{1}. Mensagem de Erro: {2}. StackTrace: {3} - - - - Assembly Initialization method {0}.{1} threw exception. {2}: {3}. Aborting test execution. - O método de Inicialização de Assembly {0}.{1} lançou uma exceção. {2}: {3}. Anulando execução de teste. - - - - Class Cleanup method {0}.{1} failed. Error Message: {2}. Stack Trace: {3} - Falha no método de Limpeza de Classe {0}.{1}. Mensagem de Erro: {2}. Rastreamento de Pilha: {3} - - - - Class Initialization method {0}.{1} threw exception. {2}: {3}. - O método de Inicialização de Classe {0}.{1} lançou uma exceção. {2}: {3}. - - - - An unhandled exception was thrown by the 'Execute' method. Please report this error to the author of the attribute '{0}'. -{1} - Uma exceção sem tratamento foi lançada pelo método 'Execute'. Relate este erro ao autor do atributo '{0}'. -{1} - - - - Error in executing test. No result returned by extension. If using extension of TestMethodAttribute then please contact vendor. - Erro ao executar o teste. Nenhum resultado retornado pela extensão. Se usar a extensão de TestMethodAttribute, entre em contato com o fornecedor. - - - - Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. - O método {0}.{1} tem a assinatura incorreta. O método deve ser estático, público, não deve retornar um valor nem receber parâmetro. Além disso, se você estiver usando async-await no método, o return-type deverá ser "Task" ou "ValueTask". - - - - Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should take a single parameter of type TestContext. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. - O método {0}.{1} tem a assinatura incorreta. O método deve ser estático, público, não retornar um valor e deve usar um único parâmetro do tipo TestContext. Além disso, se você estiver usando async-await no método, o return-type deverá ser "Task" ou "ValueTask". - - - - UTA054: {0}.{1} has invalid Timeout attribute. The timeout must be an integer value greater than 0. - UTA054: {0}.{1} tem atributo Timeout inválido. O tempo limite deve ser um valor inteiro maior que 0. - - - - UTA023: {0}: Cannot define predefined property {2} on method {1}. - UTA023: {0}: não é possível definir a propriedade predefinida {2} no método {1}. - - - - UTA021: {0}: Null or empty custom property defined on method {1}. The custom property must have a valid name. - UTA021: {0}: Propriedade personalizada nula ou vazia definida no método {1}. A propriedade personalizada deve ter um nome válido. - - - - Method {0}.{1} does not exist. - O método {0}.{1} não existe. - - - - Unable to find property {0}.TestContext. Error:{1}. - Não é possível encontrar propriedade {0}.TestContext. Erro:{1}. - - - - The {0}.TestContext has incorrect type. - O {0}.TestContext é do tipo incorreto. - - - - Method {0}.{1} has wrong signature. The method must be non-static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. - O método {0}.{1} tem a assinatura incorreta. O método deve ser não estático, público, não deve retornar um valor e não deve receber nenhum parâmetro. Além disso, se você estiver usando async-await no método, o return-type deverá ser "Task" ou "ValueTask". - - - - Unable to get type {0}. Error: {1}. - Não é possível obter o tipo {0}. Erro: {1}. - - - - Test method {0} was not found. - O método de teste {0} não foi encontrado. - - - - Debug Trace: - Rastreamento de Depuração: - - - - Failed to obtain the exception thrown by test method {0}.{1}. - Falha ao obter a exceção lançada pelo método de teste {0}.{1}. - - - - Test method {0}.{1} threw exception: -{2} - O método de teste {0}.{1} lançou a exceção: -{2} - - - - {0} For UWP projects, if you are using UI objects in test consider using [UITestMethod] attribute instead of [TestMethod] to execute test in UI thread. - {0} Para projetos UWP, se você está usando objetos de IU no teste, considere usar o atributo [UITestMethod] em vez de [TestMethod] para executar o teste no thread da IU. - - - - MSTestAdapterV2 - MSTestAdapterV2 - - - - Invalid settings '{0}'. Unexpected XmlAttribute: '{1}'. - Configurações inválidas '{0}'. XmlAttribute inesperado: '{1}'. - - - - Invalid settings '{0}'. Unexpected XmlElement: '{1}'. - Configurações inválidas '{0}'. XmlElement inesperado: '{1}'. - - - - {0} (Data Row {1}) - {0} (Linha de Dados {1}) - - - - The ExpectedException attribute defined on test method {0}.{1} threw an exception during construction. -{2} - O atributo ExpectedException definido no método de teste {0}.{1} emitiu uma exceção durante a construção. -{2} - - - - Warning : A testsettings file or a vsmdi file is not supported with the MSTest V2 Adapter. - Aviso: um arquivo testsettings ou um arquivo vsmdi não tem suporte no MSTest V2 Adapter. - - - - TestContext Messages: - Mensagens TestContext: - - - - Error calling Test Cleanup method for test class {0}: {1} - Erro ao chamar o método Test Cleanup para a classe de teste {0}: {1} - - - - TestCleanup Stack Trace - Rastreamento de pilha TestCleanup - - - - [MSTest][Discovery][{0}] {1} - [MSTest][Descoberta][{0}] {1} - - - - Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) - Paralelização de Teste habilitada para {0} (Trabalhos: {1}, Escopo: {2}) - `Workers` is a setting name that shouldn't be localized. 'Scope' is a setting name that shouldn't be localized. - - - Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. - Valor inválido '{0}' especificado para 'Scope'. Os escopos compatíveis são {1}. - 'Scope' is a setting name that shouldn't be localized. - - - Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. - Valor inválido '{0}' especificado para 'Workers'. O valor deve ser um inteiro não negativo. - `Workers` is a setting name that shouldn't be localized. - - - Failed to discover tests from assembly {0}. Reason:{1} - Falha ao descobrir testes por meio do assembly {0}. Motivo: {1} - - - - Test '{0}' was canceled - O '{0}' teste foi cancelado - - - - Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. - Valor inválido '{0}' especificado para 'ClassCleanupLifecycle'. Os escopos suportados são {1}. - 'ClassCleanupLifecycle' is a setting name that shouldn't be localized. - - - Exception occurred while enumerating IDataSource attribute on "{0}.{1}": {2} - Ocorreu uma exceção ao enumerar o atributo IDataSource em "{0}.{1}": {2} - {0}: TypeName with namespace, -{1}: Method name, -{2}: Exception details - - - "{0}": (Failed to get exception description due to an exception of type "{1}". - "{0}": (Falha ao obter a descrição da exceção devido a uma exceção do tipo "{1}". - {0}: Type of the original exception that we're trying to get the description of. -{1}: Thrown exception - - - Exceptions thrown: - Exceções lançadas: - This is usually precedes by TestAssembly_AssemblyDiscoveryFailure message, and preceded by list of exceptions thrown in a test discovery session. - - - Getting custom attributes for type {0} threw exception (will ignore and use the reflection way): {1} - A obtenção de atributos personalizados para o tipo {0} gerou uma exceção (irá ignorar e usar o modo de reflexão): {1} - {0}: Attribute full type name. -{1}: Exception description - - - An older version of MSTestV2 package is loaded in assembly, test discovery might fail to discover all data tests if they depend on `.runsettings` file. - Uma versão mais antiga do pacote MSTestV2 é carregada no assembly, a descoberta de teste pode falhar ao descobrir todos os testes de dados se eles dependerem do arquivo `.runsettings`. - - - - The called code threw an exception that was caught, but the exception value was null - O código chamado lançou uma exceção que foi capturada, mas o valor da exceção era nulo - - - - Exception occurred while expanding IDataSource rows from attribute on "{0}.{1}": {2} - Ocorreu uma exceção ao expandir as linhas IDataSource do atributo em "{0}.{1}": {2} - {0}: TypeName with namespace, -{1}: Method name, -{2}: CannotExpandIDataSourceAttribute_DuplicateDisplayName or CannotExpandIDataSourceAttribute_CannotSerialize - - - Display name "{2}" on indexes {0} and {1} are duplicate. Display names should be unique. - O nome de exibição "{2}" nos índices {0} e {1} são duplicados. Os nomes de exibição devem ser exclusivos. - {0}, {1}: Zero based index if an element inside of an array -{2}: Test display name. - - - Data on index {0} for "{1}" cannot be serialized. All data provided through "IDataSource" should be serializable. If you need to test non-serializable data sources, please make sure you add "TestDataSourceDiscovery" attribute on your test assembly and set the discovery option to "DuringExecution". - Os dados no índice {0} para "{1}" não podem ser serializados. Todos os dados fornecidos por meio de "IDataSource" devem ser serializáveis. Se você precisar testar fontes de dados não serializáveis, certifique-se de adicionar o atributo "TestDataSourceDiscovery" em seu assembly de teste e defina a opção de descoberta como "DuringExecution". - {0}: Zero based index if an element inside of an array, -{1}: Test name - - - - \ No newline at end of file diff --git a/src/Adapter/MSTest.TestAdapter/Resources/xlf/Resource.ru.xlf b/src/Adapter/MSTest.TestAdapter/Resources/xlf/Resource.ru.xlf deleted file mode 100644 index 058011a770..0000000000 --- a/src/Adapter/MSTest.TestAdapter/Resources/xlf/Resource.ru.xlf +++ /dev/null @@ -1,482 +0,0 @@ - - - - - - Assembly cleanup method '{0}.{1}' timed out after {2}ms - Время ожидания метода очистки сборки "{0}.{1}" истекло через {2} мс - - - - Assembly cleanup method '{0}.{1}' was canceled - Метод очистки сборки "{0}.{1}" отменен - - - - Assembly initialize method '{0}.{1}' timed out after {2}ms - Время ожидания метода инициализации сборки "{0}.{1}" истекло через {2} мс - - - - Assembly initialize method '{0}.{1}' was canceled - Метод инициализации сборки "{0}.{1}" отменен - - - - Cannot run test method '{0}.{1}': Test data doesn't match method parameters. Either the count or types are different. -Test expected {2} parameter(s), with types '{3}', -but received {4} argument(s), with types '{5}'. - Не удается запустить метод теста "{0}.{1}": тестовые данные не соответствуют параметрам метода. Количество или типы отличаются. -Число ожидаемых для теста параметров: {2} с типами "{3}", -но число полученных аргументов: {4} с типами "{5}". - - - - Cannot run test method '{0}.{1}': Method has parameters, but does not define any test source. Use '[DataRow]', '[DynamicData]', or a custom 'ITestDataSource' data source to provide test data. - Не удается запустить метод теста "{0}.{1}": метод имеет параметры, но не определяет источник теста. Используйте "[DataRow]", "[DynamicData]" или настраиваемый источник данных "ITestDataSource" для предоставления тестовых данных. - - - - Class cleanup method '{0}.{1}' timed out after {2}ms - Время ожидания метода очистки класса "{0}.{1}" истекло через {2} мс - - - - Class cleanup method '{0}.{1}' was canceled - Метод очистки класса "{0}.{1}" отменен - - - - Class initialize method '{0}.{1}' timed out after {2}ms - Время ожидания метода инициализации класса "{0}.{1}" истекло через {2} мс - - - - Class initialize method '{0}.{1}' was canceled - Метод инициализации класса "{0}.{1}" отменен - - - - Both '.runsettings' and '.testconfig.json' files have been detected. Please select only one of these test configuration files. - Обнаружены файлы ".runsettings" и ".testconfig.json". Выберите только один из этих файлов тестовой конфигурации. - - - - Test '{0}' timed out after {1}ms - Время ожидания '{0}' истекло через {1}мс - - - - The type of the generic parameter '{0}' could not be inferred. - Не удалось определить тип универсального '{0}' параметра. - - - - The generic test method '{0}' doesn't have arguments, so the generic parameter cannot be inferred. - Универсальный метод '{0}' не имеет аргументов, поэтому невозможно вывести универсальный параметр. - - - - Found two conflicting types for generic parameter '{0}'. The conflicting types are '{1}' and '{2}'. - Обнаружены два конфликтующих типа для универсального параметра '{0}'. Конфликтуют типы '{1}' и '{2}'. - - - - Invalid value '{0}' for runsettings entry '{1}', setting will be ignored. - Недопустимое значение "{0}" для записи runsettings "{1}", параметр будет пропущен. - - - - Runsettings entry '<ExecutionApartmentState>STA</ExecutionApartmentState>' is not supported on non-Windows OSes. - Запись Runsettings "<ExecutionApartmentState>STA</ExecutionApartmentState>" не поддерживается в ОС, отличных от Windows. - - - - Running tests in any of the provided sources is not supported for the selected platform - Запуск тестов в любом из предоставленных источников не поддерживается на выбранной платформе - - - - Test cleanup method '{0}.{1}' timed out after {2}ms - Время ожидания метода очистки теста "{0}.{1}" истекло через {2} мс - - - - Test cleanup method '{0}.{1}' was canceled - Метод очистки теста "{0}.{1}" отменен - - - - Test initialize method '{0}.{1}' timed out after {2}ms - Время ожидания метода инициализации теста "{0}.{1}" истекло через {2} мс - - - - Test initialize method '{0}.{1}' was canceled - Метод инициализации теста "{0}.{1}" отменен - - - - TestCleanup method {0}.{1} threw exception. {2}. - Метод TestCleanup {0}.{1} создал исключение. {2}. - - - - --- End of inner exception stack trace --- - --- Конец трассировки стека внутренних исключений --- - - - - UTA014: {0}: Cannot define more than one method with the AssemblyCleanup attribute inside an assembly. - UTA014: {0}: в сборке невозможно определить несколько методов с атрибутом AssemblyCleanup. - - - - UTA013: {0}: Cannot define more than one method with the AssemblyInitialize attribute inside an assembly. - UTA013: {0}: в сборке невозможно определить несколько методов с атрибутом AssemblyInitialize. - - - - UTA026: {0}: Cannot define more than one method with the ClassCleanup attribute inside a class. - UTA026: {0}: в классе невозможно определить несколько методов с атрибутом ClassCleanup. - - - - UTA025: {0}: Cannot define more than one method with the ClassInitialize attribute inside a class. - UTA025: {0}: в классе невозможно определить несколько методов с атрибутом ClassInitialize. - - - - UTA024: {0}: Cannot define more than one method with the TestCleanup attribute. - UTA024: {0}: невозможно определить несколько методов с атрибутом TestCleanup. - - - - UTA018: {0}: Cannot define more than one method with the TestInitialize attribute. - UTA018: {0}: невозможно определить несколько методов с атрибутом TestInitialize. - - - - TestClass attribute defined on generic non-abstract class {0} - Атрибут TestClass, определенный в универсальном не абстрактном классе {0} - - - - Initialization method {0}.{1} threw exception. {2}. - Метод инициализации {0}.{1} вызвал исключение. {2}. - - - - Unable to create instance of class {0}. Error: {1}. - Не удалось создать экземпляр класса {0}. Ошибка: {1}. - - - - The test method '{0}.{1}' has multiple attributes derived from '{2}' defined on it. Only one such attribute is allowed. - У метода тестирования "{0}.{1}" есть несколько атрибутов, производных от заданного в нем "{2}". Допускается только один такой атрибут. - - - - Cannot find a valid constructor for test class '{0}'. Valid constructors are 'public' and either parameterless or with one parameter of type 'TestContext'. - Не удается найти допустимый конструктор для тестового класса "{0}". Допустимые конструкторы : "public" и конструкторы без параметров или с одним параметром типа "TestContext". - - - - Unable to set TestContext property for the class {0}. Error: {1}. - Не удалось задать свойство TestContext для класса {0}. Ошибка: {1}. - - - - (Failed to get the message for an exception of type {0} due to an exception.) - (Не удалось получить сообщение для исключения с типом {0} в связи с возникновением исключения.) - - - - UTA031: class {0} does not have valid TestContext property. TestContext must be of type TestContext, must be non-static, and must be public. For example: public TestContext TestContext. - UTA031: в классе {0} отсутствует допустимое свойство TestContext. Свойство TestContext должно относиться к типу TestContext, быть нестатическим и открытым. Например: public TestContext TestContext. - - - - UTA001: TestClass attribute defined on non-public class {0} - UTA001: атрибут TestClass определен в классе {0}, не являющемся открытым - - - - MSTestAdapter failed to discover tests in class '{0}' of assembly '{1}' because {2}. - Средству MSTestAdapter не удалось обнаружить тесты в классе "{0}" сборки "{1}", так как {2}. - - - - {0}: {1} - {0}: {1} - - - - Unable to load types from the test source '{0}'. Some or all of the tests in this source may not be discovered. -Error: {1} - Не удалось загрузить типы из тестового источника "{0}". В этом источнике могут быть не обнаружены некоторые или все тесты. -Ошибка: {1} - - - - File does not exist: {0} - Файл не существует: {0} - - - - UTA007: Method {1} defined in class {0} does not have correct signature. Test method marked with the [TestMethod] attribute must be non-static, public, return-type as void and should not take any parameter. Example: public void Test.Class1.Test(). Additionally, if you are using async-await in test method then return-type must be 'Task' or 'ValueTask'. Example: public async Task Test.Class1.Test2() - UTA007: метод {1}, определенный в классе {0}, имеет неправильную сигнатуру. Метод теста, помеченный атрибутом [TestMethod], должен быть нестатическим, открытым и иметь тип возвращаемого значения void; он также не должен принимать параметры. Пример: public void Test.Class1.Test(). Кроме того, при использовании async-await в методе теста возвращаемое значение должно иметь тип "Task" или "ValueTask". Пример: public async Task Test.Class1.Test2() - - - - TestContext cannot be Null. - TestContext не может иметь значение NULL. - - - - Assembly Cleanup method {0}.{1} failed. Error Message: {2}. StackTrace: {3} - Не удалось применить метод очистки сборки {0}.{1}. Сообщение об ошибке: {2}. Трассировка стека (StackTrace): {3}. - - - - Assembly Initialization method {0}.{1} threw exception. {2}: {3}. Aborting test execution. - Методом инициализации сборки {0}.{1} создано исключение. {2}: {3}. Выполнение теста прекращается. - - - - Class Cleanup method {0}.{1} failed. Error Message: {2}. Stack Trace: {3} - Не удалось применить метод очистки класса {0}.{1}. Сообщение об ошибке: {2}. Трассировка стека: {3}. - - - - Class Initialization method {0}.{1} threw exception. {2}: {3}. - Методом инициализации класса {0}.{1} создано исключение. {2}: {3}. - - - - An unhandled exception was thrown by the 'Execute' method. Please report this error to the author of the attribute '{0}'. -{1} - Необработанное исключение вызвано методом Execute. Сообщить об этой ошибке автору атрибута '{0}'. -{1} - - - - Error in executing test. No result returned by extension. If using extension of TestMethodAttribute then please contact vendor. - Ошибка при выполнении теста. Расширение не возвратило результаты. Если используется расширение атрибута TestMethodAttribute, обратитесь к поставщику. - - - - Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. - Метод {0}.{1} имеет неправильную сигнатуру. Метод должен быть статическим и открытым, не должен возвращать значение и принимать параметры. Кроме того, при использовании async-await в методе возвращаемое значение должно иметь тип "Task" или "ValueTask". - - - - Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should take a single parameter of type TestContext. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. - Метод {0}.{1} имеет неправильную сигнатуру. Метод должен быть статическим и открытым, не должен возвращать значение и должен принимать один параметр, имеющий тип TestContext. Кроме того, при использовании async-await в методе возвращаемое значение должно иметь тип "Task" или "ValueTask". - - - - UTA054: {0}.{1} has invalid Timeout attribute. The timeout must be an integer value greater than 0. - UTA054: {0}. {1} имеет недопустимый атрибут времени ожидания. Значение времени ожидания должно быть положительным целым числом. - - - - UTA023: {0}: Cannot define predefined property {2} on method {1}. - UTA023: {0}: не удается определить предопределенное свойство {2} в методе {1}. - - - - UTA021: {0}: Null or empty custom property defined on method {1}. The custom property must have a valid name. - UTA021: {0}: в методе {1} определено пользовательское свойство, имя которого имеет значение NULL или пусто. Пользовательское свойство должно иметь допустимое имя. - - - - Method {0}.{1} does not exist. - Метод {0}.{1} не существует. - - - - Unable to find property {0}.TestContext. Error:{1}. - Не удается найти свойство {0}.TestContext. Ошибка: {1}. - - - - The {0}.TestContext has incorrect type. - Для свойства {0}.TestContext указан неправильный тип. - - - - Method {0}.{1} has wrong signature. The method must be non-static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. - Метод {0}.{1} имеет неправильную сигнатуру. Метод должен быть нестатическим и открытым, не должен возвращать значение и принимать параметры. Кроме того, при использовании async-await в методе возвращаемое значение должно иметь тип "Task" или "ValueTask". - - - - Unable to get type {0}. Error: {1}. - Не удается получить тип {0}. Ошибка: {1}. - - - - Test method {0} was not found. - Метод теста {0} не найден. - - - - Debug Trace: - Трассировка отладки: - - - - Failed to obtain the exception thrown by test method {0}.{1}. - Не удалось получить исключение, созданное методом теста {0}.{1}. - - - - Test method {0}.{1} threw exception: -{2} - Метод теста {0}.{1} создал исключение: -{2}. - - - - {0} For UWP projects, if you are using UI objects in test consider using [UITestMethod] attribute instead of [TestMethod] to execute test in UI thread. - {0} В проектах UWP, если в тесте используются объекты пользовательского интерфейса, рассмотрите возможность использования атрибута [UITestMethod] вместо атрибута [TestMethod] для выполнения теста в потоке пользовательского интерфейса. - - - - MSTestAdapterV2 - MSTestAdapterV2 - - - - Invalid settings '{0}'. Unexpected XmlAttribute: '{1}'. - Недопустимые параметры "{0}". Непредвиденный атрибут XmlAttribute: "{1}". - - - - Invalid settings '{0}'. Unexpected XmlElement: '{1}'. - Недопустимые параметры "{0}". Непредвиденный элемент XmlElement: "{1}". - - - - {0} (Data Row {1}) - {0} (строка данных {1}) - - - - The ExpectedException attribute defined on test method {0}.{1} threw an exception during construction. -{2} - Атрибут ExpectedException, определенный в методе теста {0}.{1}, породил исключение во время создания. -{2} - - - - Warning : A testsettings file or a vsmdi file is not supported with the MSTest V2 Adapter. - Внимание! Адаптер MSTest версии 2 не поддерживает файл TESTSETTINGS или VSMDI. - - - - TestContext Messages: - Сообщения TestContext: - - - - Error calling Test Cleanup method for test class {0}: {1} - Ошибка при вызове метода TestCleanup для тестового класса {0}: {1} - - - - TestCleanup Stack Trace - Трассировка стека TestCleanup - - - - [MSTest][Discovery][{0}] {1} - [MSTest][Discovery][{0}] {1} - - - - Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) - Включена параллелизация тестов для {0} (рабочие роли: {1}, область: {2}) - `Workers` is a setting name that shouldn't be localized. 'Scope' is a setting name that shouldn't be localized. - - - Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. - В поле "Область" указано недопустимое значение "{0}". Поддерживаемые области: {1}. - 'Scope' is a setting name that shouldn't be localized. - - - Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. - В поле "Рабочие роли" указано недопустимое значение "{0}". Оно должно быть неотрицательным целым числом. - `Workers` is a setting name that shouldn't be localized. - - - Failed to discover tests from assembly {0}. Reason:{1} - Не удалось обнаружить тесты из сборки {0}. Причина:{1} - - - - Test '{0}' was canceled - Проверка '{0}' отменена - - - - Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. - Для параметра "ClassCleanupLifecycle" указано недопустимое значение "{0}". Поддерживаемые области: {1}. - 'ClassCleanupLifecycle' is a setting name that shouldn't be localized. - - - Exception occurred while enumerating IDataSource attribute on "{0}.{1}": {2} - Возникло исключение при перечислении атрибута IDataSource в "{0}.{1}": {2} - {0}: TypeName with namespace, -{1}: Method name, -{2}: Exception details - - - "{0}": (Failed to get exception description due to an exception of type "{1}". - "{0}": (Не удалось получить описание исключения из-за исключения типа "{1}". - {0}: Type of the original exception that we're trying to get the description of. -{1}: Thrown exception - - - Exceptions thrown: - Выданные исключения: - This is usually precedes by TestAssembly_AssemblyDiscoveryFailure message, and preceded by list of exceptions thrown in a test discovery session. - - - Getting custom attributes for type {0} threw exception (will ignore and use the reflection way): {1} - При получении настраиваемых атрибутов для типа {0} возникло исключение (оно будет проигнорировано и будет использовано отражение): {1} - {0}: Attribute full type name. -{1}: Exception description - - - An older version of MSTestV2 package is loaded in assembly, test discovery might fail to discover all data tests if they depend on `.runsettings` file. - В сборку загружена старая версия пакета MSTestV2. При обнаружении тестов могут быть обнаружены не все тесты данных, если они зависят от файла ".runsettings". - - - - The called code threw an exception that was caught, but the exception value was null - Вызванный код вызвал исключение, которое было перехвачено, но значение исключения было равно NULL - - - - Exception occurred while expanding IDataSource rows from attribute on "{0}.{1}": {2} - Возникло исключение при развертывании строк IDataSource из атрибута "{0}.{1}": {2} - {0}: TypeName with namespace, -{1}: Method name, -{2}: CannotExpandIDataSourceAttribute_DuplicateDisplayName or CannotExpandIDataSourceAttribute_CannotSerialize - - - Display name "{2}" on indexes {0} and {1} are duplicate. Display names should be unique. - Отображаемые имена "{2}" в индексах {0} и {1} дублируются. Отображаемые имена должны быть уникальными. - {0}, {1}: Zero based index if an element inside of an array -{2}: Test display name. - - - Data on index {0} for "{1}" cannot be serialized. All data provided through "IDataSource" should be serializable. If you need to test non-serializable data sources, please make sure you add "TestDataSourceDiscovery" attribute on your test assembly and set the discovery option to "DuringExecution". - Не удается сериализовать данные в индексе {0} для "{1}". Все данные, предоставленные через IDataSource, должны быть сериализуемыми. Если необходимо протестировать несериализуемые источники данных, добавьте атрибут "TestDataSourceDiscovery" в тестовую сборку и установите для параметра обнаружения значение "DuringExecution". - {0}: Zero based index if an element inside of an array, -{1}: Test name - - - - \ No newline at end of file diff --git a/src/Adapter/MSTest.TestAdapter/Resources/xlf/Resource.tr.xlf b/src/Adapter/MSTest.TestAdapter/Resources/xlf/Resource.tr.xlf deleted file mode 100644 index 5713804864..0000000000 --- a/src/Adapter/MSTest.TestAdapter/Resources/xlf/Resource.tr.xlf +++ /dev/null @@ -1,482 +0,0 @@ - - - - - - Assembly cleanup method '{0}.{1}' timed out after {2}ms - '{0}.{1}' derleme temizleme yöntemi {2}ms sonra zaman aşımına uğradı - - - - Assembly cleanup method '{0}.{1}' was canceled - '{0}.{1}' bütünleştirilmiş kod temizleme yöntemi iptal edildi - - - - Assembly initialize method '{0}.{1}' timed out after {2}ms - '{0}.{1}' derleme başlatma yöntemi {2}ms sonra zaman aşımına uğradı - - - - Assembly initialize method '{0}.{1}' was canceled - '{0}.{1}' derleme başlatma yöntemi iptal edildi - - - - Cannot run test method '{0}.{1}': Test data doesn't match method parameters. Either the count or types are different. -Test expected {2} parameter(s), with types '{3}', -but received {4} argument(s), with types '{5}'. - '{0}.{1}' test yöntemi çalıştırılamıyor: Test verileri yöntem parametreleriyle eşleşmiyor. Ya sayı ya da türler farklıdır. -Test '{3}' türüyle {2} parametre bekledi, -ancak, '{5}' türüyle {4} argüman aldı. - - - - Cannot run test method '{0}.{1}': Method has parameters, but does not define any test source. Use '[DataRow]', '[DynamicData]', or a custom 'ITestDataSource' data source to provide test data. - '{0}.{1}' test yöntemi çalıştırılamıyor: Yöntemin parametreleri var ancak herhangi bir test kaynağı tanımlamıyor. Test verilerini sağlamak için '[DataRow]', '[DynamicData]' veya özel bir 'ITestDataSource' veri kaynağı kullanın. - - - - Class cleanup method '{0}.{1}' timed out after {2}ms - '{0}.{1}' sınıf temizleme yöntemi {2}ms sonra zaman aşımına uğradı - - - - Class cleanup method '{0}.{1}' was canceled - '{0}.{1}' sınıf temizleme yöntemi iptal edildi - - - - Class initialize method '{0}.{1}' timed out after {2}ms - '{0}.{1}' sınıf başlatma yöntemi {2}ms sonra zaman aşımına uğradı - - - - Class initialize method '{0}.{1}' was canceled - '{0}.{1}' sınıf başlatma yöntemi iptal edildi - - - - Both '.runsettings' and '.testconfig.json' files have been detected. Please select only one of these test configuration files. - Hem '.runsettings' hem de '.testconfig.json' dosyaları algılandı. Lütfen bu test yapılandırma dosyalarından yalnızca birini seçin. - - - - Test '{0}' timed out after {1}ms - Test '{0}' ms sonra zaman aşımına {1}oldu - - - - The type of the generic parameter '{0}' could not be inferred. - Genel parametre türü '{0}' çıkarsanamadı. - - - - The generic test method '{0}' doesn't have arguments, so the generic parameter cannot be inferred. - Genel test '{0}' bağımsız değişkene sahip olmadığından genel parametre çıkarsanamıyor. - - - - Found two conflicting types for generic parameter '{0}'. The conflicting types are '{1}' and '{2}'. - Genel parametre türü için iki çakışan tür '{0}'. Çakışan türler '{1}' '{2}'. - - - - Invalid value '{0}' for runsettings entry '{1}', setting will be ignored. - '{1}' çalıştırma ayarları girişi için '{0}' değeri geçersiz, ayar yoksayılacak. - - - - Runsettings entry '<ExecutionApartmentState>STA</ExecutionApartmentState>' is not supported on non-Windows OSes. - '<ExecutionApartmentState>STA</ExecutionApartmentState>' çalışma ayarları girişi Windows dışı işletim sistemlerinde desteklenmiyor. - - - - Running tests in any of the provided sources is not supported for the selected platform - Testlerin sağlanan kaynakların herhangi birinde çalıştırılması seçili platformda desteklenmiyor - - - - Test cleanup method '{0}.{1}' timed out after {2}ms - '{0}.{1}' test temizleme yöntemi {2}ms sonra zaman aşımına uğradı - - - - Test cleanup method '{0}.{1}' was canceled - '{0}.{1}' test temizleme yöntemi iptal edildi - - - - Test initialize method '{0}.{1}' timed out after {2}ms - '{0}.{1}' test başlatma yöntemi {2}ms sonra zaman aşımına uğradı - - - - Test initialize method '{0}.{1}' was canceled - '{0}.{1}' test başlatma yöntemi iptal edildi - - - - TestCleanup method {0}.{1} threw exception. {2}. - TestCleanup metodu {0}.{1} özel durum oluşturdu. {2}. - - - - --- End of inner exception stack trace --- - --- İç özel durum yığın izlemesinin sonu --- - - - - UTA014: {0}: Cannot define more than one method with the AssemblyCleanup attribute inside an assembly. - UTA014: {0}: Bir bütünleştirilmiş kod içinde AssemblyCleanup özniteliği ile birden fazla metot tanımlanamaz. - - - - UTA013: {0}: Cannot define more than one method with the AssemblyInitialize attribute inside an assembly. - UTA013: {0}: Bir bütünleştirilmiş kod içinde AssemblyInitialize özniteliği ile birden fazla metot tanımlanamaz. - - - - UTA026: {0}: Cannot define more than one method with the ClassCleanup attribute inside a class. - UTA026: {0}: Bir sınıf içinde ClassCleanup özniteliği ile birden fazla metot tanımlanamaz. - - - - UTA025: {0}: Cannot define more than one method with the ClassInitialize attribute inside a class. - UTA025: {0}: Bir sınıf içinde ClassInitialize özniteliği ile birden fazla metot tanımlanamaz. - - - - UTA024: {0}: Cannot define more than one method with the TestCleanup attribute. - UTA024: {0}: TestCleanup özniteliği ile birden fazla metot tanımlanamaz. - - - - UTA018: {0}: Cannot define more than one method with the TestInitialize attribute. - UTA018: {0}: TestInitialize özniteliği ile birden fazla metot tanımlanamaz. - - - - TestClass attribute defined on generic non-abstract class {0} - {0} genel soyut olmayan sınıf üzerinde tanımlanan TestClass özniteliği - - - - Initialization method {0}.{1} threw exception. {2}. - Başlatma metodu {0}.{1} özel durum oluşturdu. {2}. - - - - Unable to create instance of class {0}. Error: {1}. - {0} sınıfının örneği oluşturulamıyor. Hata: {1}. - - - - The test method '{0}.{1}' has multiple attributes derived from '{2}' defined on it. Only one such attribute is allowed. - “{0}.{1}” test yöntemi, üzerinde tanımlanan “{2}” öğesinden türetilmiş birden fazla öznitelik içeriyor. Bu türde yalnızca bir tane özniteliğe izin verilir. - - - - Cannot find a valid constructor for test class '{0}'. Valid constructors are 'public' and either parameterless or with one parameter of type 'TestContext'. - '{0}' test sınıfı için geçerli bir oluşturucu bulunamıyor. Geçerli oluşturucular 'public' ve parametresiz veya 'TestContext' türünde tek bir parametre içeriyor. - - - - Unable to set TestContext property for the class {0}. Error: {1}. - {0} sınıfı için TestContext özelliği ayarlanamıyor. Hata: {1}. - - - - (Failed to get the message for an exception of type {0} due to an exception.) - (Bir özel durum nedeniyle, {0} türündeki özel durum iletisi alınamadı.) - - - - UTA031: class {0} does not have valid TestContext property. TestContext must be of type TestContext, must be non-static, and must be public. For example: public TestContext TestContext. - UTA031: {0}sınıfı geçerli bir TestContext özelliğine sahip değil. TestContext, TestContext türünde olmalı, static olmamalı ve public olmalıdır. Örnek: public TestContext TestContext. - - - - UTA001: TestClass attribute defined on non-public class {0} - UTA001: TestClass özniteliği genel olmayan {0} sınıfında tanımlanmış - - - - MSTestAdapter failed to discover tests in class '{0}' of assembly '{1}' because {2}. - MSTestAdapter, '{1}' bütünleştirilmiş kodunun '{0}' sınıfındaki testleri bulamadı. Nedeni: {2}. - - - - {0}: {1} - {0}: {1} - - - - Unable to load types from the test source '{0}'. Some or all of the tests in this source may not be discovered. -Error: {1} - '{0}' test kaynağından türler yüklenemiyor. Kaynaktaki testlerin bazıları veya tümü bulunamayabilir. -Hata: {1} - - - - File does not exist: {0} - Dosya yok: {0} - - - - UTA007: Method {1} defined in class {0} does not have correct signature. Test method marked with the [TestMethod] attribute must be non-static, public, return-type as void and should not take any parameter. Example: public void Test.Class1.Test(). Additionally, if you are using async-await in test method then return-type must be 'Task' or 'ValueTask'. Example: public async Task Test.Class1.Test2() - UTA007: {0} sınıfında tanımlanan {1} yönteminin imzası doğru değil. [TestMethod] özniteliğiyle işaretlenmiş test yöntemi statik olmayan, genel, dönüş türü void olan bir yöntem olmalıdır ve hiçbir parametre almamalıdır. Örnek: public void Test.Class1.Test(). Bunlara ek olarak, test metodunda async-await kullanıyorsanız return-type değeri 'Task' veya 'ValueTask' olmalıdır. Örnek: public async Task Test.Class1.Test2() - - - - TestContext cannot be Null. - TestContext, Null olamaz. - - - - Assembly Cleanup method {0}.{1} failed. Error Message: {2}. StackTrace: {3} - Bütünleştirilmiş Kod Temizleme metodu ({0}.{1}) başarısız oldu. Hata İletisi: {2}. StackTrace: {3} - - - - Assembly Initialization method {0}.{1} threw exception. {2}: {3}. Aborting test execution. - Bütünleştirilmiş Kod Başlatma metodu ({0}.{1}) özel durum oluşturdu. {2}: {3}. Test yürütmesi durduruluyor. - - - - Class Cleanup method {0}.{1} failed. Error Message: {2}. Stack Trace: {3} - Sınıf Temizleme metodu ({0}.{1}) başarısız oldu. Hata İletisi: {2}. Yığın İzlemesi: {3} - - - - Class Initialization method {0}.{1} threw exception. {2}: {3}. - Sınıf Başlatma metodu ({0}.{1}) özel durum oluşturdu. {2}: {3}. - - - - An unhandled exception was thrown by the 'Execute' method. Please report this error to the author of the attribute '{0}'. -{1} - 'Execute' metodu tarafından işlenmeyen bir özel durum oluşturuldu. Lütfen bu hatayı özniteliğin yazarına '{0}'. -{1} - - - - Error in executing test. No result returned by extension. If using extension of TestMethodAttribute then please contact vendor. - Test yürütülürken hata oluştu. Uzantı tarafından hiç sonuç döndürülmedi. TestMethodAttribute uzantısı kullanılıyorsa, lütfen satıcıya başvurun. - - - - Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. - {0}.{1} yönteminin imzası yanlış. Yöntem statik, genel, değer döndürmeyen bir yöntem olmalı, hiçbir parametre almamalıdır. Bunlara ek olarak, yöntemde async-await kullanıyorsanız return-type değeri 'Task' veya 'ValueTask' olmalıdır. - - - - Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should take a single parameter of type TestContext. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. - {0}.{1} yönteminin imzası yanlış. Yöntem statik, genel, değer döndürmeyen bir yöntem olmalı ve TestContext türünde tek bir parametre almalıdır. Bunlara ek olarak, yöntemde async-await kullanıyorsanız return-type değeri 'Task' veya 'ValueTask' olmalıdır. - - - - UTA054: {0}.{1} has invalid Timeout attribute. The timeout must be an integer value greater than 0. - UTA054: {0}.{1} Timeout özniteliği geçersiz. Zaman aşımı değeri 0'dan büyük bir tamsayı olmalıdır. - - - - UTA023: {0}: Cannot define predefined property {2} on method {1}. - UTA023: {0}: Önceden tanımlanmış {2} özelliği {1} metodunda tanımlanamaz. - - - - UTA021: {0}: Null or empty custom property defined on method {1}. The custom property must have a valid name. - UTA021: {0}: {1} metodunda null veya boş özel özellik tanımlanmış. Özel özellik geçerli bir ada sahip olmalıdır. - - - - Method {0}.{1} does not exist. - {0}.{1} metodu yok. - - - - Unable to find property {0}.TestContext. Error:{1}. - {0}.TestContext özelliği bulunamıyor. Hata:{1}. - - - - The {0}.TestContext has incorrect type. - {0}.TestContext yanlış türe sahip. - - - - Method {0}.{1} has wrong signature. The method must be non-static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. - {0}.{1} yönteminin imzası yanlış. Yöntem statik olmayan, genel, değer döndürmeyen bir yöntem olmalı, hiçbir parametre almamalıdır. Bunlara ek olarak, yöntemde async-await kullanıyorsanız return-type değeri 'Task' veya 'ValueTask' olmalıdır. - - - - Unable to get type {0}. Error: {1}. - {0} türü alınamıyor. Hata: {1}. - - - - Test method {0} was not found. - {0} test metodu bulunamadı. - - - - Debug Trace: - Hata Ayıklama İzleyici: - - - - Failed to obtain the exception thrown by test method {0}.{1}. - {0}.{1} metodu tarafından oluşturulan özel durum alınamadı. - - - - Test method {0}.{1} threw exception: -{2} - {0}.{1} test metodu özel durum oluşturdu: -{2} - - - - {0} For UWP projects, if you are using UI objects in test consider using [UITestMethod] attribute instead of [TestMethod] to execute test in UI thread. - {0} UWP projeleri için testte UI nesneleri kullanıyorsanız, testi UI iş parçacığında yürütmek için [TestMethod] yerine [UITestMethod] özniteliğini kullanabilirsiniz. - - - - MSTestAdapterV2 - MSTestAdapterV2 - - - - Invalid settings '{0}'. Unexpected XmlAttribute: '{1}'. - Geçersiz '{0}' ayarları. Beklenmeyen XmlAttribute: '{1}'. - - - - Invalid settings '{0}'. Unexpected XmlElement: '{1}'. - Geçersiz '{0}' ayarları. Beklenmeyen XmlElement: '{1}'. - - - - {0} (Data Row {1}) - {0} (Veri Satırı {1}) - - - - The ExpectedException attribute defined on test method {0}.{1} threw an exception during construction. -{2} - {0}.{1} test yöntemi üzerinde tanımlanan ExpectedException özniteliği, oluşturma sırasında bir özel durum oluşturdu. -{2} - - - - Warning : A testsettings file or a vsmdi file is not supported with the MSTest V2 Adapter. - Uyarı : MSTest V2 Adapter ile bir testsettings dosyası veya bir vsmdi dosyası desteklenmez. - - - - TestContext Messages: - TestContext İletileri: - - - - Error calling Test Cleanup method for test class {0}: {1} - {0} test sınıfı için Test Temizleme metodu çağrılırken hata oluştu: {1} - - - - TestCleanup Stack Trace - TestCleanup Yığın İzleme - - - - [MSTest][Discovery][{0}] {1} - [MSTest][Discovery][{0}] {1} - - - - Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) - {0} için Test Paralelleştirme etkin (Çalışanlar: {1}, Kapsam: {2}). - `Workers` is a setting name that shouldn't be localized. 'Scope' is a setting name that shouldn't be localized. - - - Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. - 'Scope' için geçersiz '{0}' değeri belirtildi. Desteklenen kapsamlar {1}. - 'Scope' is a setting name that shouldn't be localized. - - - Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. - 'Workers' için geçersiz '{0}' değeri belirtildi. Değer negatif olmayan bir tamsayı olmalıdır. - `Workers` is a setting name that shouldn't be localized. - - - Failed to discover tests from assembly {0}. Reason:{1} - {0} bütünleştirilmiş kodundan testler bulunamadı. Neden:{1} - - - - Test '{0}' was canceled - Test '{0}' iptal edildi - - - - Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. - 'ClassCleanupLifecycle' için geçersiz '{0}' değeri belirtildi. Desteklenen kapsamlar {1}'dir. - 'ClassCleanupLifecycle' is a setting name that shouldn't be localized. - - - Exception occurred while enumerating IDataSource attribute on "{0}.{1}": {2} - "{0}.{1} " üzerinde IDataSource özniteliği numaralandırılırken özel durum oluştu: {2} - {0}: TypeName with namespace, -{1}: Method name, -{2}: Exception details - - - "{0}": (Failed to get exception description due to an exception of type "{1}". - "{0}": ("{1}" türündeki bir istisna nedeniyle özel durum açıklaması alınamadı. - {0}: Type of the original exception that we're trying to get the description of. -{1}: Thrown exception - - - Exceptions thrown: - Oluşturulan özel durumlar: - This is usually precedes by TestAssembly_AssemblyDiscoveryFailure message, and preceded by list of exceptions thrown in a test discovery session. - - - Getting custom attributes for type {0} threw exception (will ignore and use the reflection way): {1} - {0} tipi için özel niteliklerin alınması özel durum oluşturdu (yok sayar ve yansıma yolunu kullanır): {1} - {0}: Attribute full type name. -{1}: Exception description - - - An older version of MSTestV2 package is loaded in assembly, test discovery might fail to discover all data tests if they depend on `.runsettings` file. - Montaja MSTestV2 paketinin daha eski bir sürümü yüklenir, test keşfi, `.runsettings` dosyasına bağlılarsa tüm veri testlerini keşfetmede başarısız olabilir. - - - - The called code threw an exception that was caught, but the exception value was null - Çağrılan kod, yakalanan bir özel durum yarattı, ancak özel durum değeri boştu - - - - Exception occurred while expanding IDataSource rows from attribute on "{0}.{1}": {2} - "{0}. {1}" üzerindeki öznitelikten IDataSource satırları genişletilirken özel durum oluştu: {2} - {0}: TypeName with namespace, -{1}: Method name, -{2}: CannotExpandIDataSourceAttribute_DuplicateDisplayName or CannotExpandIDataSourceAttribute_CannotSerialize - - - Display name "{2}" on indexes {0} and {1} are duplicate. Display names should be unique. - {0} ve {1}dizinlerinde görünen ad " {2}" yineleniyor. Görünen adlar benzersiz olmalıdır. - {0}, {1}: Zero based index if an element inside of an array -{2}: Test display name. - - - Data on index {0} for "{1}" cannot be serialized. All data provided through "IDataSource" should be serializable. If you need to test non-serializable data sources, please make sure you add "TestDataSourceDiscovery" attribute on your test assembly and set the discovery option to "DuringExecution". - "{1}" için {0} indeksindeki veriler serileştirilemez. "IDataSource" aracılığıyla sağlanan tüm veriler serileştirilebilir olmalıdır. Serileştirilemeyen veri kaynaklarını test etmeniz gerekiyorsa, lütfen test derlemenize "TestDataSourceDiscovery" özniteliğini eklediğinizden ve keşif seçeneğini "DuringExecution" olarak ayarladığınızdan emin olun. - {0}: Zero based index if an element inside of an array, -{1}: Test name - - - - \ No newline at end of file diff --git a/src/Adapter/MSTest.TestAdapter/Resources/xlf/Resource.zh-Hans.xlf b/src/Adapter/MSTest.TestAdapter/Resources/xlf/Resource.zh-Hans.xlf deleted file mode 100644 index 0e0b87553b..0000000000 --- a/src/Adapter/MSTest.TestAdapter/Resources/xlf/Resource.zh-Hans.xlf +++ /dev/null @@ -1,482 +0,0 @@ - - - - - - Assembly cleanup method '{0}.{1}' timed out after {2}ms - 程序集清理方法“{0}.{1}”在 {2} ms 后超时 - - - - Assembly cleanup method '{0}.{1}' was canceled - 已取消程序集清理方法“{0}.{1}” - - - - Assembly initialize method '{0}.{1}' timed out after {2}ms - 程序集初始化方法“{0}.{1}”在 {2} ms 后超时 - - - - Assembly initialize method '{0}.{1}' was canceled - 已取消程序集初始化方法“{0}.{1}” - - - - Cannot run test method '{0}.{1}': Test data doesn't match method parameters. Either the count or types are different. -Test expected {2} parameter(s), with types '{3}', -but received {4} argument(s), with types '{5}'. - 无法运行测试方法“{0}.{1}”: 测试数据与方法参数不匹配。计数或类型不同。 -测试需要类型为“{3}”的 {2} 参数, -但收到了类型为“{5}”的 {4} 参数。 - - - - Cannot run test method '{0}.{1}': Method has parameters, but does not define any test source. Use '[DataRow]', '[DynamicData]', or a custom 'ITestDataSource' data source to provide test data. - 无法运行测试方法“{0}.{1}”: 方法具有参数,但未定义任何测试源。使用 “[DataRow]”、“[DynamicData]” 或自定义 “ITestDataSource” 数据源提供测试数据。 - - - - Class cleanup method '{0}.{1}' timed out after {2}ms - 类清理方法“{0}.{1}”在 {2} ms 后超时 - - - - Class cleanup method '{0}.{1}' was canceled - 已取消类清理方法“{0}.{1}” - - - - Class initialize method '{0}.{1}' timed out after {2}ms - 类初始化方法“{0}.{1}”在 {2} ms 后超时 - - - - Class initialize method '{0}.{1}' was canceled - 已取消类初始化方法“{0}.{1}” - - - - Both '.runsettings' and '.testconfig.json' files have been detected. Please select only one of these test configuration files. - 检测到 ".runsettings" 和 ".testconfig.json" 文件。请仅选择其中一个测试配置文件。 - - - - Test '{0}' timed out after {1}ms - 测试 '{0}' 在 {1}毫秒后超时 - - - - The type of the generic parameter '{0}' could not be inferred. - 无法推断 '{0}' 泛型参数的类型。 - - - - The generic test method '{0}' doesn't have arguments, so the generic parameter cannot be inferred. - 泛型测试方法 '{0}' 没有参数,因此无法推断泛型参数。 - - - - Found two conflicting types for generic parameter '{0}'. The conflicting types are '{1}' and '{2}'. - 发现泛型参数 '{0}' 的两个冲突类型。冲突类型 '{1}' 和 '{2}'。 - - - - Invalid value '{0}' for runsettings entry '{1}', setting will be ignored. - runsettings 项“{0}”的值“{1}”无效,将忽略设置。 - - - - Runsettings entry '<ExecutionApartmentState>STA</ExecutionApartmentState>' is not supported on non-Windows OSes. - 非 Windows 操作系统不支持 Runsettings 条目 "<ExecutionApartmentState>STA</ExecutionApartmentState>"。 - - - - Running tests in any of the provided sources is not supported for the selected platform - 选定的平台不支持在任何提供的源中运行测试 - - - - Test cleanup method '{0}.{1}' timed out after {2}ms - 测试清理方法“{0}.{1}”在 {2} ms 后超时 - - - - Test cleanup method '{0}.{1}' was canceled - 已取消测试清理方法“{0}.{1}” - - - - Test initialize method '{0}.{1}' timed out after {2}ms - 测试初始化方法“{0}.{1}”在 {2} ms 后超时 - - - - Test initialize method '{0}.{1}' was canceled - 已取消测试初始化方法“{0}.{1}” - - - - TestCleanup method {0}.{1} threw exception. {2}. - TestCleanup 方法 {0}.{1} 引发异常。{2}。 - - - - --- End of inner exception stack trace --- - ---内部异常堆栈跟踪结束--- - - - - UTA014: {0}: Cannot define more than one method with the AssemblyCleanup attribute inside an assembly. - UTA014: {0}: 在一个程序集内部,不能定义多个具有 AssemblyCleanup 特性的方法。 - - - - UTA013: {0}: Cannot define more than one method with the AssemblyInitialize attribute inside an assembly. - UTA013: {0}: 在一个程序集内部,不能定义多个具有 AssemblyInitialize 特性的方法。 - - - - UTA026: {0}: Cannot define more than one method with the ClassCleanup attribute inside a class. - UTA026: {0}: 在一个类内部,不能定义多个具有 ClassCleanup 特性的方法。 - - - - UTA025: {0}: Cannot define more than one method with the ClassInitialize attribute inside a class. - UTA025: {0}: 在一个类内部,不能定义多个具有 ClassInitialize 特性的方法。 - - - - UTA024: {0}: Cannot define more than one method with the TestCleanup attribute. - UTA024: {0}: 不能定义多个具有 TestCleanup 特性的方法。 - - - - UTA018: {0}: Cannot define more than one method with the TestInitialize attribute. - UTA018: {0}: 不能定义多个具有 TestInitialize 特性的方法。 - - - - TestClass attribute defined on generic non-abstract class {0} - 在泛型非抽象类 {0} 上定义的 TestClass 特性 - - - - Initialization method {0}.{1} threw exception. {2}. - 初始化方法 {0}.{1} 引发异常。{2}。 - - - - Unable to create instance of class {0}. Error: {1}. - 无法创建类 {0} 的实例。错误: {1}。 - - - - The test method '{0}.{1}' has multiple attributes derived from '{2}' defined on it. Only one such attribute is allowed. - 测试方法“{0}.{1}”具有多个在其上定义的“{2}”的派生属性。仅允许一个此类属性。 - - - - Cannot find a valid constructor for test class '{0}'. Valid constructors are 'public' and either parameterless or with one parameter of type 'TestContext'. - 找不到测试类“{0}”的有效构造函数。有效的构造函数为 “public”,但该构造函数无参数或具有一个类型为 “TestContext” 的参数。 - - - - Unable to set TestContext property for the class {0}. Error: {1}. - 无法设置类 {0} 的 TestContext 属性。错误: {1}。 - - - - (Failed to get the message for an exception of type {0} due to an exception.) - (因异常而未能获取类型为 {0} 的异常的消息。) - - - - UTA031: class {0} does not have valid TestContext property. TestContext must be of type TestContext, must be non-static, and must be public. For example: public TestContext TestContext. - UTA031: 类 {0} 没有有效的 TestContext 属性。TestContext 必须是 TestContext 类型并且必须是非静态和公共的。例如: public TestContext TestContext。 - - - - UTA001: TestClass attribute defined on non-public class {0} - UTA001: 在非公共类 {0} 上定义的 TestClass 特性 - - - - MSTestAdapter failed to discover tests in class '{0}' of assembly '{1}' because {2}. - 由于 {2},MSTestAdapter 未能在程序集“{1}”的类“{0}”中发现测试。 - - - - {0}: {1} - {0}: {1} - - - - Unable to load types from the test source '{0}'. Some or all of the tests in this source may not be discovered. -Error: {1} - 无法从测试源“{0}”加载类型。可能无法发现此源中的部分或所有测试。 -错误: {1} - - - - File does not exist: {0} - 文件不存在: {0} - - - - UTA007: Method {1} defined in class {0} does not have correct signature. Test method marked with the [TestMethod] attribute must be non-static, public, return-type as void and should not take any parameter. Example: public void Test.Class1.Test(). Additionally, if you are using async-await in test method then return-type must be 'Task' or 'ValueTask'. Example: public async Task Test.Class1.Test2() - UTA007: 在类 {0} 中定义的方法 {1} 没有正确的签名。用 [TestMethod] 特性标记的测试方法必须是返回类型为 void 的非静态的公共方法,并且不应采用任何参数。示例: public void Test.Class1.Test()。此外,如果在测试方法中使用同步等待,则返回类型必须为“Task”或“Value Task”。示例: public async Task Test.Class1.Test2() - - - - TestContext cannot be Null. - TestContext 不能为 NULL。 - - - - Assembly Cleanup method {0}.{1} failed. Error Message: {2}. StackTrace: {3} - 程序集清理方法 {0}.{1} 失败。错误消息: {2}。StackTrace: {3} - - - - Assembly Initialization method {0}.{1} threw exception. {2}: {3}. Aborting test execution. - 程序集初始化方法 {0}.{1} 引发异常。{2}: {3}。正在中止测试的执行。 - - - - Class Cleanup method {0}.{1} failed. Error Message: {2}. Stack Trace: {3} - 类清理方法 {0}.{1} 失败。错误消息: {2}。堆栈跟踪: {3} - - - - Class Initialization method {0}.{1} threw exception. {2}: {3}. - 类初始化方法 {0}.{1} 引发异常。{2}: {3}。 - - - - An unhandled exception was thrown by the 'Execute' method. Please report this error to the author of the attribute '{0}'. -{1} - “Execute”方法引发了未经处理的异常。请将此错误报告给属性 '{0}' 的作者。 -{1} - - - - Error in executing test. No result returned by extension. If using extension of TestMethodAttribute then please contact vendor. - 执行测试时出错。扩展未返回任何结果。如果使用的是扩展 TestMethodAttribute ,请与供应商联系。 - - - - Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. - 方法 {0}。{1}的签名错误。该方法必须是静态的公共方法、不返回值并且不应采用任何参数。此外,如果在方法中使用同步等待,则返回类型必须为“Task”或“Value Task”。 - - - - Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should take a single parameter of type TestContext. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. - 方法 {0}。{1}的签名错误。该方法必须是静态的公共方法,不返回值,并且应采用一个 TestContext 类型的参数。此外,如果在方法中使用同步等待,则返回类型必须为“Task”或“Value Task”。 - - - - UTA054: {0}.{1} has invalid Timeout attribute. The timeout must be an integer value greater than 0. - UTA054: {0}。{1} 的超时属性无效。“超时”必须是大于零的整数值。 - - - - UTA023: {0}: Cannot define predefined property {2} on method {1}. - UTA023: {0}: 不能在方法 {1} 上定义预定义属性 {2}。 - - - - UTA021: {0}: Null or empty custom property defined on method {1}. The custom property must have a valid name. - UTA021: {0}: 对方法 {1} 定义了为 NULL 或为空的自定义属性。自定义属性必须具有有效名称。 - - - - Method {0}.{1} does not exist. - 方法 {0}.{1} 不存在。 - - - - Unable to find property {0}.TestContext. Error:{1}. - 无法找到属性 {0}.TestContext。错误: {1}。 - - - - The {0}.TestContext has incorrect type. - {0}.TestContext 的类型不正确。 - - - - Method {0}.{1} has wrong signature. The method must be non-static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. - 方法 {0}。{1}的签名错误。该方法必须是非静态的公共方法、不返回值并且不应采用任何参数。此外,如果在方法中使用同步等待,则返回类型必须为“Task”或“Value Task”。 - - - - Unable to get type {0}. Error: {1}. - 无法获取类型 {0}。错误: {1}。 - - - - Test method {0} was not found. - 未找到测试方法 {0}。 - - - - Debug Trace: - 调试跟踪: - - - - Failed to obtain the exception thrown by test method {0}.{1}. - 未能获取测试方法 {0}.{1} 引发的异常。 - - - - Test method {0}.{1} threw exception: -{2} - 测试方法 {0}.{1} 引发了异常: -{2} - - - - {0} For UWP projects, if you are using UI objects in test consider using [UITestMethod] attribute instead of [TestMethod] to execute test in UI thread. - {0} 对于 UWP 项目,如果在测试中使用 UI 对象,请考虑使用 [UITestMethod] 属性代替 [TestMethod] 属性在 UI 线程中执行测试。 - - - - MSTestAdapterV2 - MSTestAdapterV2 - - - - Invalid settings '{0}'. Unexpected XmlAttribute: '{1}'. - 设置“{0}”无效。意外的 XmlAttribute:“{1}”。 - - - - Invalid settings '{0}'. Unexpected XmlElement: '{1}'. - 设置“{0}”无效。意外的 XmlElement:“{1}”。 - - - - {0} (Data Row {1}) - {0} (数据行 {1}) - - - - The ExpectedException attribute defined on test method {0}.{1} threw an exception during construction. -{2} - 测试方法 {0}.{1} 上定义的 ExpectedException 属性在构造过程中引发了一个异常。 -{2} - - - - Warning : A testsettings file or a vsmdi file is not supported with the MSTest V2 Adapter. - 警告: MSTest V2 适配器不支持 testsettings 文件或 vsmdi 文件。 - - - - TestContext Messages: - TestContext 消息: - - - - Error calling Test Cleanup method for test class {0}: {1} - 为测试类 {0} 调用 Test Cleanup 方法时出错: {1} - - - - TestCleanup Stack Trace - TestCleanup 堆栈跟踪 - - - - [MSTest][Discovery][{0}] {1} - [MSTest][发现][{0}] {1} - - - - Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) - 已为 {0} 启用测试并行化(工作线程: {1},范围: {2}) - `Workers` is a setting name that shouldn't be localized. 'Scope' is a setting name that shouldn't be localized. - - - Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. - 为“范围”指定的值“{0}”无效。受支持的范围为 {1}。 - 'Scope' is a setting name that shouldn't be localized. - - - Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. - 为“辅助角色”指定的值“{0}”无效。该值应为非负整数。 - `Workers` is a setting name that shouldn't be localized. - - - Failed to discover tests from assembly {0}. Reason:{1} - 未能发现程序集 {0} 中的测试。原因: {1} - - - - Test '{0}' was canceled - 测试 '{0}' 已取消 - - - - Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. - 为“ClassCleanupLifecycle”指定的值“{0}”无效。支持的作用域为 {1}。 - 'ClassCleanupLifecycle' is a setting name that shouldn't be localized. - - - Exception occurred while enumerating IDataSource attribute on "{0}.{1}": {2} - 枚举 {0} 上的 IDataSource 属性时发生异常。{1}": {2} - {0}: TypeName with namespace, -{1}: Method name, -{2}: Exception details - - - "{0}": (Failed to get exception description due to an exception of type "{1}". - “{0}”:(由于类型“{1}”异常,无法获取异常说明。 - {0}: Type of the original exception that we're trying to get the description of. -{1}: Thrown exception - - - Exceptions thrown: - 引发的异常: - This is usually precedes by TestAssembly_AssemblyDiscoveryFailure message, and preceded by list of exceptions thrown in a test discovery session. - - - Getting custom attributes for type {0} threw exception (will ignore and use the reflection way): {1} - 获取类型 {0} 自定义属性引发异常(将忽略并使用反射方式): {1} - {0}: Attribute full type name. -{1}: Exception description - - - An older version of MSTestV2 package is loaded in assembly, test discovery might fail to discover all data tests if they depend on `.runsettings` file. - 程序集中加载了 MSTestV2 包的较旧版本,如果测试发现依赖于“.runsettings”文件,则它们可能无法发现所有数据测试。 - - - - The called code threw an exception that was caught, but the exception value was null - 调用的代码引发了捕获的异常,但异常值为 null - - - - Exception occurred while expanding IDataSource rows from attribute on "{0}.{1}": {2} - 从“{0}.{1}”上的属性扩展 IDataSource 行时出现异常: {2} - {0}: TypeName with namespace, -{1}: Method name, -{2}: CannotExpandIDataSourceAttribute_DuplicateDisplayName or CannotExpandIDataSourceAttribute_CannotSerialize - - - Display name "{2}" on indexes {0} and {1} are duplicate. Display names should be unique. - 索引 {0} 和 {1} 上的显示名称“{2}”重复。显示名称应是唯一的。 - {0}, {1}: Zero based index if an element inside of an array -{2}: Test display name. - - - Data on index {0} for "{1}" cannot be serialized. All data provided through "IDataSource" should be serializable. If you need to test non-serializable data sources, please make sure you add "TestDataSourceDiscovery" attribute on your test assembly and set the discovery option to "DuringExecution". - 无法序列化“{1}”的索引 {0} 上的数据。通过“IDataSource”提供的所有数据都应可序列化。如果需要测试不可序列化的数据源,请确保在测试程序集上添加“TestDataSourceDiscovery”属性,并将发现选项设置为“DuringExecution”。 - {0}: Zero based index if an element inside of an array, -{1}: Test name - - - - \ No newline at end of file diff --git a/src/Adapter/MSTest.TestAdapter/Resources/xlf/Resource.zh-Hant.xlf b/src/Adapter/MSTest.TestAdapter/Resources/xlf/Resource.zh-Hant.xlf deleted file mode 100644 index d247e040da..0000000000 --- a/src/Adapter/MSTest.TestAdapter/Resources/xlf/Resource.zh-Hant.xlf +++ /dev/null @@ -1,482 +0,0 @@ - - - - - - Assembly cleanup method '{0}.{1}' timed out after {2}ms - 組件清理方法 '{0}.{1}' 在 {2} 毫秒後已逾時 - - - - Assembly cleanup method '{0}.{1}' was canceled - 已取消組件清理方法 '{0}.{1}' - - - - Assembly initialize method '{0}.{1}' timed out after {2}ms - 組件初始化方法 '{0}.{1}' 在 {2} 毫秒後已逾時 - - - - Assembly initialize method '{0}.{1}' was canceled - 已取消組件初始化方法 '{0}.{1}' - - - - Cannot run test method '{0}.{1}': Test data doesn't match method parameters. Either the count or types are different. -Test expected {2} parameter(s), with types '{3}', -but received {4} argument(s), with types '{5}'. - 無法執行測試方法 '{0}.{1}': 測試資料不符合方法參數。計數或類型不同。 -測試預期的 {2} 參數,類型為 '{3}', -但收到 {4} 引數,類型為 '{5}'。 - - - - Cannot run test method '{0}.{1}': Method has parameters, but does not define any test source. Use '[DataRow]', '[DynamicData]', or a custom 'ITestDataSource' data source to provide test data. - 無法執行測試方法 '{0}.{1}': 方法具有參數,但未定義任何測試來源。使用 '[DataRow]'、'[DynamicData]' 或自訂 'ITestDataSource' 資料來源來提供測試資料。 - - - - Class cleanup method '{0}.{1}' timed out after {2}ms - 類別清理方法 '{0}.{1}' 在 {2} 毫秒後已逾時 - - - - Class cleanup method '{0}.{1}' was canceled - 已取消類別清理方法 '{0}.{1}' - - - - Class initialize method '{0}.{1}' timed out after {2}ms - 類別初始化方法 '{0}.{1}' 在 {2} 毫秒後已逾時 - - - - Class initialize method '{0}.{1}' was canceled - 已取消類別初始化方法 '{0}.{1}' - - - - Both '.runsettings' and '.testconfig.json' files have been detected. Please select only one of these test configuration files. - 偵測到 '.runsettings' 和 '.testconfig.json' 檔案。請只選取其中一個測試設定檔。 - - - - Test '{0}' timed out after {1}ms - 測試 '{0}' 在 {1}毫秒後逾時 - - - - The type of the generic parameter '{0}' could not be inferred. - 無法推斷泛型參數 '{0}' 的類型。 - - - - The generic test method '{0}' doesn't have arguments, so the generic parameter cannot be inferred. - 泛型測試方法 '{0}' 沒有自變數,因此無法推斷泛型參數。 - - - - Found two conflicting types for generic parameter '{0}'. The conflicting types are '{1}' and '{2}'. - 發現兩個衝突的泛型參數類型 '{0}'。衝突的類型 '{1}' 且 '{2}'。 - - - - Invalid value '{0}' for runsettings entry '{1}', setting will be ignored. - runsettings 項目 '{1}' 的值 '{0}' 無效,將忽略設定。 - - - - Runsettings entry '<ExecutionApartmentState>STA</ExecutionApartmentState>' is not supported on non-Windows OSes. - 非 Windows OS 不支援 Runsettings 項目 '<ExecutionApartmentState>STA</ExecutionApartmentState>'。 - - - - Running tests in any of the provided sources is not supported for the selected platform - 所選取的平台不支援在任何提供的來源中執行測試 - - - - Test cleanup method '{0}.{1}' timed out after {2}ms - 測試清理方法 '{0}.{1}' 在 {2} 毫秒後已逾時 - - - - Test cleanup method '{0}.{1}' was canceled - 已取消測試清理方法 '{0}.{1}' - - - - Test initialize method '{0}.{1}' timed out after {2}ms - 測試初始化方法 '{0}.{1}' 在 {2} 毫秒後已逾時 - - - - Test initialize method '{0}.{1}' was canceled - 已取消測試初始化方法 '{0}.{1}' - - - - TestCleanup method {0}.{1} threw exception. {2}. - TestCleanup 方法 {0}.{1} 擲回例外狀況。{2}。 - - - - --- End of inner exception stack trace --- - --- 已到達內部例外狀況堆疊追蹤的結尾 --- - - - - UTA014: {0}: Cannot define more than one method with the AssemblyCleanup attribute inside an assembly. - UTA014: {0}: 組件內不可定義一個以上具有 AssemblyCleanup 屬性的方法。 - - - - UTA013: {0}: Cannot define more than one method with the AssemblyInitialize attribute inside an assembly. - UTA013: {0}: 組件內不可定義一個以上具有 AssemblyInitialize 屬性的方法。 - - - - UTA026: {0}: Cannot define more than one method with the ClassCleanup attribute inside a class. - UTA026: {0}: 類別內不可定義一個以上具有 ClassCleanup 屬性的方法。 - - - - UTA025: {0}: Cannot define more than one method with the ClassInitialize attribute inside a class. - UTA025: {0}: 類別內不可定義一個以上具有 ClassInitialize 屬性的方法。 - - - - UTA024: {0}: Cannot define more than one method with the TestCleanup attribute. - UTA024: {0}: 不可定義一個以上具有 TestCleanup 屬性的方法。 - - - - UTA018: {0}: Cannot define more than one method with the TestInitialize attribute. - UTA018: {0}: 不可定義一個以上具有 TestInitialize 屬性的方法。 - - - - TestClass attribute defined on generic non-abstract class {0} - 在一般非抽象類別上定義的 TestClass 屬性 {0} - - - - Initialization method {0}.{1} threw exception. {2}. - 初始設定方法 {0}.{1} 擲回例外狀況。{2}。 - - - - Unable to create instance of class {0}. Error: {1}. - 無法建立類別 {0} 的執行個體。錯誤: {1}。 - - - - The test method '{0}.{1}' has multiple attributes derived from '{2}' defined on it. Only one such attribute is allowed. - 測試方法 '{0}.{1}' 具有多個衍生自 '{2}' 的屬性根據其定義。只允許一個此類屬性。 - - - - Cannot find a valid constructor for test class '{0}'. Valid constructors are 'public' and either parameterless or with one parameter of type 'TestContext'. - 找不到測試類別 '{0}' 的有效建構函式。有效的建構函式為 'public' 且無參數或具有一個類型為 'TestContext' 的參數。 - - - - Unable to set TestContext property for the class {0}. Error: {1}. - 無法設定類別 {0} 的 TestContext 屬性。錯誤: {1}。 - - - - (Failed to get the message for an exception of type {0} due to an exception.) - (因為發生例外狀況,所以無法取得類型 {0} 之例外狀況的訊息。) - - - - UTA031: class {0} does not have valid TestContext property. TestContext must be of type TestContext, must be non-static, and must be public. For example: public TestContext TestContext. - UTA031: 類別 {0}不具備有效的 TestContext 屬性。TestContext 必須是 TestContext 類型、必須是非靜態的,而且必須是公用的。例如: public TestContext TestContext。 - - - - UTA001: TestClass attribute defined on non-public class {0} - UTA001: 在非公用類別 {0} 上定義了 TestClass 屬性 - - - - MSTestAdapter failed to discover tests in class '{0}' of assembly '{1}' because {2}. - MSTestAdapter 無法在組件 '{1}' 的類別 '{0}' 中探索測試,因為 {2}。 - - - - {0}: {1} - {0}: {1} - - - - Unable to load types from the test source '{0}'. Some or all of the tests in this source may not be discovered. -Error: {1} - 無法從測試來源 '{0}' 載入類型。有可能無法探索此來源中的部分或所有測試。 -錯誤: {1} - - - - File does not exist: {0} - 檔案不存在: {0} - - - - UTA007: Method {1} defined in class {0} does not have correct signature. Test method marked with the [TestMethod] attribute must be non-static, public, return-type as void and should not take any parameter. Example: public void Test.Class1.Test(). Additionally, if you are using async-await in test method then return-type must be 'Task' or 'ValueTask'. Example: public async Task Test.Class1.Test2() - UTA007: 類別 {0} 中定義的方法 {1} 沒有正確的簽章。標記 [TestMethod] 屬性的測試方法必須為非靜態、公用、傳回類型為 void,而且不應該接受任何參數。範例: public void Test.Class1.Test()。此外,如果您在測試方法中使用 async-await,則傳回類型必須是 'Task' 或 'ValueTask'。範例: public async Task Test.Class1.Test2() - - - - TestContext cannot be Null. - TestContext 不可為 Null。 - - - - Assembly Cleanup method {0}.{1} failed. Error Message: {2}. StackTrace: {3} - 組件清除方法 {0}.{1} 失敗。錯誤訊息: {2}。堆疊追蹤: {3} - - - - Assembly Initialization method {0}.{1} threw exception. {2}: {3}. Aborting test execution. - 組件初始設定方法 {0}.{1} 擲回例外狀況。{2}: {3}。正在中止測試執行。 - - - - Class Cleanup method {0}.{1} failed. Error Message: {2}. Stack Trace: {3} - 類別清除方法 {0}.{1} 失敗。錯誤訊息: {2}。堆疊追蹤: {3} - - - - Class Initialization method {0}.{1} threw exception. {2}: {3}. - 類別初始設定方法 {0}.{1} 擲回例外狀況。{2}: {3}。 - - - - An unhandled exception was thrown by the 'Execute' method. Please report this error to the author of the attribute '{0}'. -{1} - 'Execute' 方法擲回未處理的例外狀況。請將此錯誤回報給屬性 '{0}' 的作者。 -{1} - - - - Error in executing test. No result returned by extension. If using extension of TestMethodAttribute then please contact vendor. - 執行測試時發生錯誤。擴充功能未傳回任何結果。如果您使用 TestMethodAttribute 的擴充功能,請連絡廠商。 - - - - Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. - 方法 {0}.{1} 有錯誤的簽章。方法必須為靜態、公用、不傳回值,並且不應該接受任何參數。此外,如果您在方法中使用 async-await,則傳回類型必須是 'Task' 或 'ValueTask'。 - - - - Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should take a single parameter of type TestContext. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. - 方法 {0}.{1} 有錯誤的簽章。方法必須為靜態、公用、不傳回值,並且應接受類型為 TestContext 的單一參數。此外,如果您在方法中使用 async-await,則傳回類型必須是 'Task' 或 'ValueTask'。 - - - - UTA054: {0}.{1} has invalid Timeout attribute. The timeout must be an integer value greater than 0. - UTA054: {0}。{1} 中具有無效的 Timeout 屬性。逾時必須為大於 0 的整數值。 - - - - UTA023: {0}: Cannot define predefined property {2} on method {1}. - UTA023: {0}: 不可在方法 {1} 上定義預先定義的屬性 {2}。 - - - - UTA021: {0}: Null or empty custom property defined on method {1}. The custom property must have a valid name. - UTA021: {0}: 在方法 {1} 上定義了 Null 或空白的自訂屬性。自訂屬性的名稱必須有效。 - - - - Method {0}.{1} does not exist. - 方法 {0}.{1} 不存在。 - - - - Unable to find property {0}.TestContext. Error:{1}. - 找不到屬性 {0}.TestContext。錯誤: {1}。 - - - - The {0}.TestContext has incorrect type. - {0}.TestContext 有不正確的類型。 - - - - Method {0}.{1} has wrong signature. The method must be non-static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. - 方法 {0}.{1} 有錯誤的簽章。方法必須為非靜態、公用、不傳回值,並且不應該接受任何參數。此外,如果您在方法中使用 async-await,則傳回類型必須是 'Task' 或 'ValueTask'。 - - - - Unable to get type {0}. Error: {1}. - 無法取得類型 {0}。錯誤: {1}。 - - - - Test method {0} was not found. - 找不到測試方法 {0}。 - - - - Debug Trace: - 偵錯追蹤: - - - - Failed to obtain the exception thrown by test method {0}.{1}. - 無法取得測試方法 {0}.{1} 所擲回的例外狀況。 - - - - Test method {0}.{1} threw exception: -{2} - 測試方法 {0}.{1} 擲回例外狀況: -{2} - - - - {0} For UWP projects, if you are using UI objects in test consider using [UITestMethod] attribute instead of [TestMethod] to execute test in UI thread. - {0} 針對 UWP 專案,如果您在測試中使用 UI 物件,請考慮使用 [UITestMethod] 屬性取代 [TestMethod] 在 UI 執行緒中執行測試。 - - - - MSTestAdapterV2 - MSTestAdapterV2 - - - - Invalid settings '{0}'. Unexpected XmlAttribute: '{1}'. - 設定 '{0}' 無效。未預期的 XmlAttribute: '{1}'。 - - - - Invalid settings '{0}'. Unexpected XmlElement: '{1}'. - 設定 '{0}' 無效。未預期的 XmlElement: '{1}'。 - - - - {0} (Data Row {1}) - {0} (資料列 {1}) - - - - The ExpectedException attribute defined on test method {0}.{1} threw an exception during construction. -{2} - 測試方法 {0} 上定義的 ExpectedException 屬性。{1} 在建構期間擲回例外狀況。 -{2} - - - - Warning : A testsettings file or a vsmdi file is not supported with the MSTest V2 Adapter. - 警告: MSTest V2 配接器不支援 testsettings 檔案 vsmdi 檔案。 - - - - TestContext Messages: - TestContext 訊息: - - - - Error calling Test Cleanup method for test class {0}: {1} - 呼叫測試類別 {0} 的測試清除方法時發生錯誤: {1} - - - - TestCleanup Stack Trace - TestCleanup 堆疊追蹤 - - - - [MSTest][Discovery][{0}] {1} - [MSTest][Discovery][{0}] {1} - - - - Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) - 已為 {0} 啟用平行測試 (背景工作角色: {1},範圍: {2}) - `Workers` is a setting name that shouldn't be localized. 'Scope' is a setting name that shouldn't be localized. - - - Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. - 為 'Scope' 指定的值 '{0}' 無效。支援的範圍為 {1}。 - 'Scope' is a setting name that shouldn't be localized. - - - Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. - 為 'Workers' 的值 '{0}' 無效。值應為非負整數。 - `Workers` is a setting name that shouldn't be localized. - - - Failed to discover tests from assembly {0}. Reason:{1} - 無法從組件 {0} 中探索測試。原因:{1} - - - - Test '{0}' was canceled - 已取消測試 '{0}' - - - - Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. - 為 'ClassCleanupLifecycle' 指定的值 '{0}' 無效。支援的範圍為 {1}。 - 'ClassCleanupLifecycle' is a setting name that shouldn't be localized. - - - Exception occurred while enumerating IDataSource attribute on "{0}.{1}": {2} - 列舉「{0}.{1}」上的 IDataSource 屬性時發生例外狀況: {2} - {0}: TypeName with namespace, -{1}: Method name, -{2}: Exception details - - - "{0}": (Failed to get exception description due to an exception of type "{1}". - 「{0}」: (因為類型「{1}」的例外狀況而無法取得例外狀況描述。 - {0}: Type of the original exception that we're trying to get the description of. -{1}: Thrown exception - - - Exceptions thrown: - 擲回的例外狀況數: - This is usually precedes by TestAssembly_AssemblyDiscoveryFailure message, and preceded by list of exceptions thrown in a test discovery session. - - - Getting custom attributes for type {0} threw exception (will ignore and use the reflection way): {1} - 取得類型 {0} 擲回例外狀況的自訂屬性 (將會略過並使用反映方式): {1} - {0}: Attribute full type name. -{1}: Exception description - - - An older version of MSTestV2 package is loaded in assembly, test discovery might fail to discover all data tests if they depend on `.runsettings` file. - 元件中已載入舊版的 MSTestV2 套件,如果測試探索相依於 '.runsettings' 檔案,則測試探索可能無法探索所有資料測試。 - - - - The called code threw an exception that was caught, but the exception value was null - 被呼叫的程式碼擲回攔截到的例外狀況,但例外狀況值為 Null - - - - Exception occurred while expanding IDataSource rows from attribute on "{0}.{1}": {2} - 從「{0}.{1}」上的屬性展開 IDataSource 資料列時發生例外狀況: {2} - {0}: TypeName with namespace, -{1}: Method name, -{2}: CannotExpandIDataSourceAttribute_DuplicateDisplayName or CannotExpandIDataSourceAttribute_CannotSerialize - - - Display name "{2}" on indexes {0} and {1} are duplicate. Display names should be unique. - 索引 {0} 和 {1} 上的顯示名稱「{2}」重複。顯示名稱必須是唯一的。 - {0}, {1}: Zero based index if an element inside of an array -{2}: Test display name. - - - Data on index {0} for "{1}" cannot be serialized. All data provided through "IDataSource" should be serializable. If you need to test non-serializable data sources, please make sure you add "TestDataSourceDiscovery" attribute on your test assembly and set the discovery option to "DuringExecution". - 無法序列化「{1}"」索引 {0} 上的資料。透過「IDataSource」提供的所有資料應可序列化。如果您需要測試不可序列化的資料來源,請務必在測試元件上新增「TestDataSourceDiscovery」屬性,並將探索選項設定為「DuringExecution」。 - {0}: Zero based index if an element inside of an array, -{1}: Test name - - - - \ No newline at end of file diff --git a/src/Adapter/MSTest.TestAdapter/VSTestAdapter/MSTestDiscoverer.cs b/src/Adapter/MSTest.TestAdapter/VSTestAdapter/MSTestDiscoverer.cs index 7fcb8c825d..27fe223424 100644 --- a/src/Adapter/MSTest.TestAdapter/VSTestAdapter/MSTestDiscoverer.cs +++ b/src/Adapter/MSTest.TestAdapter/VSTestAdapter/MSTestDiscoverer.cs @@ -11,15 +11,15 @@ namespace Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter; /// /// Contains the discovery logic for this adapter. /// -[DefaultExecutorUri(Constants.ExecutorUriString)] +[DefaultExecutorUri(MSTestAdapter.PlatformServices.EngineConstants.ExecutorUriString)] [FileExtension(".xap")] [FileExtension(".appx")] [FileExtension(".dll")] [FileExtension(".exe")] #if NET6_0_OR_GREATER -[Obsolete(Constants.PublicTypeObsoleteMessage, DiagnosticId = "MSTESTOBS")] +[Obsolete(TestTools.UnitTesting.FrameworkConstants.PublicTypeObsoleteMessage, DiagnosticId = "MSTESTOBS")] #else -[Obsolete(Constants.PublicTypeObsoleteMessage)] +[Obsolete(TestTools.UnitTesting.FrameworkConstants.PublicTypeObsoleteMessage)] #endif public class MSTestDiscoverer : ITestDiscoverer { diff --git a/src/Adapter/MSTest.TestAdapter/VSTestAdapter/MSTestExecutor.cs b/src/Adapter/MSTest.TestAdapter/VSTestAdapter/MSTestExecutor.cs index 35f125d683..d8fbda9796 100644 --- a/src/Adapter/MSTest.TestAdapter/VSTestAdapter/MSTestExecutor.cs +++ b/src/Adapter/MSTest.TestAdapter/VSTestAdapter/MSTestExecutor.cs @@ -2,21 +2,23 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution; +using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Interface; using Microsoft.VisualStudio.TestPlatform.ObjectModel; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging; +using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter; /// /// Contains the execution logic for this adapter. /// -[ExtensionUri(Constants.ExecutorUriString)] +[ExtensionUri(EngineConstants.ExecutorUriString)] #if NET6_0_OR_GREATER -[Obsolete(Constants.PublicTypeObsoleteMessage, DiagnosticId = "MSTESTOBS")] +[Obsolete(FrameworkConstants.PublicTypeObsoleteMessage, DiagnosticId = "MSTESTOBS")] #else -[Obsolete(Constants.PublicTypeObsoleteMessage)] +[Obsolete(FrameworkConstants.PublicTypeObsoleteMessage)] #endif public class MSTestExecutor : ITestExecutor { diff --git a/src/Adapter/MSTestAdapter.PlatformServices/AssemblyResolver.cs b/src/Adapter/MSTestAdapter.PlatformServices/AssemblyResolver.cs index 39ee56ac55..22480e260c 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/AssemblyResolver.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/AssemblyResolver.cs @@ -20,9 +20,9 @@ namespace Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; /// #if NETFRAMEWORK #if NET6_0_OR_GREATER -[Obsolete(Constants.PublicTypeObsoleteMessage, DiagnosticId = "MSTESTOBS")] +[Obsolete(TestTools.UnitTesting.FrameworkConstants.PublicTypeObsoleteMessage, DiagnosticId = "MSTESTOBS")] #else -[Obsolete(Constants.PublicTypeObsoleteMessage)] +[Obsolete(TestTools.UnitTesting.FrameworkConstants.PublicTypeObsoleteMessage)] #endif public #else diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Constants.cs b/src/Adapter/MSTestAdapter.PlatformServices/Constants.cs deleted file mode 100644 index 9651fb5b97..0000000000 --- a/src/Adapter/MSTestAdapter.PlatformServices/Constants.cs +++ /dev/null @@ -1,44 +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 Microsoft.VisualStudio.TestPlatform.ObjectModel; - -namespace Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; - -internal static class Constants -{ -#if NETFRAMEWORK - /// - /// Constants for detecting .net framework. - /// - public const string TargetFrameworkAttributeFullName = "System.Runtime.Versioning.TargetFrameworkAttribute"; - - public const string DotNetFrameWorkStringPrefix = ".NETFramework,Version="; - - public const string TargetFrameworkName = "TargetFrameworkName"; - - public const string PublicAssemblies = "PublicAssemblies"; - - public const string PrivateAssemblies = "PrivateAssemblies"; -#endif - - public static readonly TestProperty DeploymentItemsProperty = TestProperty.Register("MSTestDiscoverer.DeploymentItems", DeploymentItemsLabel, typeof(KeyValuePair[]), TestPropertyAttributes.Hidden, typeof(TestCase)); - - internal const string DllExtension = ".dll"; - internal const string ExeExtension = ".exe"; - internal const string AppxPackageExtension = ".appx"; - -#if NETFRAMEWORK - internal const string PhoneAppxPackageExtension = ".appx"; - - // These are tied to a specific VS version. Can be changed to have a list of supported version instead. - internal const string VisualStudioRootRegKey32ForDev14 = @"SOFTWARE\Microsoft\VisualStudio\" + VisualStudioVersion; - internal const string VisualStudioRootRegKey64ForDev14 = @"SOFTWARE\Wow6432Node\Microsoft\VisualStudio\" + VisualStudioVersion; - - internal const string VisualStudioVersion = "14.0"; -#endif - - private const string DeploymentItemsLabel = "DeploymentItems"; - - internal const string PublicTypeObsoleteMessage = "We will remove or hide this type starting with v4. If you are using this type, reach out to our team on https://github.com/microsoft/testfx."; -} diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Deployment/AssemblyLoadWorker.cs b/src/Adapter/MSTestAdapter.PlatformServices/Deployment/AssemblyLoadWorker.cs index ac9d21964f..3c2b3f7e20 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Deployment/AssemblyLoadWorker.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Deployment/AssemblyLoadWorker.cs @@ -130,7 +130,7 @@ private static string GetTargetFrameworkStringFromAssembly(Assembly assembly) string attributeName = declaringType.FullName; if (string.Equals( attributeName, - Constants.TargetFrameworkAttributeFullName, + EngineConstants.TargetFrameworkAttributeFullName, StringComparison.OrdinalIgnoreCase)) { dotNetVersion = data.ConstructorArguments[0].Value.ToString(); diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Deployment/TestRunDirectories.cs b/src/Adapter/MSTestAdapter.PlatformServices/Deployment/TestRunDirectories.cs index 1ed2e71877..c2c085bb46 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Deployment/TestRunDirectories.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Deployment/TestRunDirectories.cs @@ -11,9 +11,9 @@ namespace Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Dep /// The test run directories. /// #if NET6_0_OR_GREATER -[Obsolete(Constants.PublicTypeObsoleteMessage, DiagnosticId = "MSTESTOBS")] +[Obsolete(TestTools.UnitTesting.FrameworkConstants.PublicTypeObsoleteMessage, DiagnosticId = "MSTESTOBS")] #else -[Obsolete(Constants.PublicTypeObsoleteMessage)] +[Obsolete(TestTools.UnitTesting.FrameworkConstants.PublicTypeObsoleteMessage)] #endif [Serializable] public class TestRunDirectories diff --git a/src/Adapter/MSTest.TestAdapter/Discovery/AssemblyEnumerationResult.cs b/src/Adapter/MSTestAdapter.PlatformServices/Discovery/AssemblyEnumerationResult.cs similarity index 100% rename from src/Adapter/MSTest.TestAdapter/Discovery/AssemblyEnumerationResult.cs rename to src/Adapter/MSTestAdapter.PlatformServices/Discovery/AssemblyEnumerationResult.cs diff --git a/src/Adapter/MSTest.TestAdapter/Discovery/AssemblyEnumerator.cs b/src/Adapter/MSTestAdapter.PlatformServices/Discovery/AssemblyEnumerator.cs similarity index 97% rename from src/Adapter/MSTest.TestAdapter/Discovery/AssemblyEnumerator.cs rename to src/Adapter/MSTestAdapter.PlatformServices/Discovery/AssemblyEnumerator.cs index 34c6e1b21a..39a8adf671 100644 --- a/src/Adapter/MSTest.TestAdapter/Discovery/AssemblyEnumerator.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Discovery/AssemblyEnumerator.cs @@ -7,6 +7,7 @@ using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution; using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Helpers; using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel; +using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; using Microsoft.VisualStudio.TestPlatform.ObjectModel; using Microsoft.VisualStudio.TestTools.UnitTesting; using Microsoft.VisualStudio.TestTools.UnitTesting.Internal; @@ -271,13 +272,13 @@ private static void AddFixtureTests(DiscoveryTestMethodInfo testMethodInfo, List if (testMethodInfo.Parent.Parent.AssemblyInitializeMethod is not null) { tests.Add(GetAssemblyFixtureTest(testMethodInfo.Parent.Parent.AssemblyInitializeMethod, assemblyName, - classFullName, assemblyLocation, Constants.AssemblyInitializeFixtureTrait)); + classFullName, assemblyLocation, EngineConstants.AssemblyInitializeFixtureTrait)); } if (testMethodInfo.Parent.Parent.AssemblyCleanupMethod is not null) { tests.Add(GetAssemblyFixtureTest(testMethodInfo.Parent.Parent.AssemblyCleanupMethod, assemblyName, - classFullName, assemblyLocation, Constants.AssemblyCleanupFixtureTrait)); + classFullName, assemblyLocation, EngineConstants.AssemblyCleanupFixtureTrait)); } } @@ -290,13 +291,13 @@ private static void AddFixtureTests(DiscoveryTestMethodInfo testMethodInfo, List if (testMethodInfo.Parent.ClassInitializeMethod is not null) { tests.Add(GetClassFixtureTest(testMethodInfo.Parent.ClassInitializeMethod, classFullName, - assemblyLocation, Constants.ClassInitializeFixtureTrait)); + assemblyLocation, EngineConstants.ClassInitializeFixtureTrait)); } if (testMethodInfo.Parent.ClassCleanupMethod is not null) { tests.Add(GetClassFixtureTest(testMethodInfo.Parent.ClassCleanupMethod, classFullName, - assemblyLocation, Constants.ClassCleanupFixtureTrait)); + assemblyLocation, EngineConstants.ClassCleanupFixtureTrait)); } } @@ -304,7 +305,7 @@ static UnitTestElement GetAssemblyFixtureTest(MethodInfo methodInfo, string asse string assemblyLocation, string fixtureType) { string methodName = GetMethodName(methodInfo); - string[] hierarchy = [null!, assemblyName, Constants.AssemblyFixturesHierarchyClassName, methodName]; + string[] hierarchy = [null!, assemblyName, EngineConstants.AssemblyFixturesHierarchyClassName, methodName]; return GetFixtureTest(classFullName, assemblyLocation, fixtureType, methodName, hierarchy); } @@ -330,7 +331,7 @@ static UnitTestElement GetFixtureTest(string classFullName, string assemblyLocat return new UnitTestElement(method) { DisplayName = $"[{fixtureType}] {methodName}", - Traits = [new Trait(Constants.FixturesTestTrait, fixtureType)], + Traits = [new Trait(EngineConstants.FixturesTestTrait, fixtureType)], }; } } diff --git a/src/Adapter/MSTest.TestAdapter/Discovery/AssemblyEnumeratorWrapper.cs b/src/Adapter/MSTestAdapter.PlatformServices/Discovery/AssemblyEnumeratorWrapper.cs similarity index 98% rename from src/Adapter/MSTest.TestAdapter/Discovery/AssemblyEnumeratorWrapper.cs rename to src/Adapter/MSTestAdapter.PlatformServices/Discovery/AssemblyEnumeratorWrapper.cs index 5633389cbd..5bb2e65b9a 100644 --- a/src/Adapter/MSTest.TestAdapter/Discovery/AssemblyEnumeratorWrapper.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Discovery/AssemblyEnumeratorWrapper.cs @@ -2,6 +2,7 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel; +using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter; using Microsoft.VisualStudio.TestTools.UnitTesting; diff --git a/src/Adapter/MSTest.TestAdapter/Discovery/DiscoveryTestMethodInfo.cs b/src/Adapter/MSTestAdapter.PlatformServices/Discovery/DiscoveryTestMethodInfo.cs similarity index 100% rename from src/Adapter/MSTest.TestAdapter/Discovery/DiscoveryTestMethodInfo.cs rename to src/Adapter/MSTestAdapter.PlatformServices/Discovery/DiscoveryTestMethodInfo.cs diff --git a/src/Adapter/MSTest.TestAdapter/Discovery/TestMethodValidator.cs b/src/Adapter/MSTestAdapter.PlatformServices/Discovery/TestMethodValidator.cs similarity index 97% rename from src/Adapter/MSTest.TestAdapter/Discovery/TestMethodValidator.cs rename to src/Adapter/MSTestAdapter.PlatformServices/Discovery/TestMethodValidator.cs index 04ca9f18ba..846a92dd72 100644 --- a/src/Adapter/MSTest.TestAdapter/Discovery/TestMethodValidator.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Discovery/TestMethodValidator.cs @@ -3,6 +3,7 @@ using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Extensions; using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Helpers; +using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Discovery; diff --git a/src/Adapter/MSTest.TestAdapter/Discovery/TypeEnumerator.cs b/src/Adapter/MSTestAdapter.PlatformServices/Discovery/TypeEnumerator.cs similarity index 100% rename from src/Adapter/MSTest.TestAdapter/Discovery/TypeEnumerator.cs rename to src/Adapter/MSTestAdapter.PlatformServices/Discovery/TypeEnumerator.cs diff --git a/src/Adapter/MSTest.TestAdapter/Discovery/TypeValidator.cs b/src/Adapter/MSTestAdapter.PlatformServices/Discovery/TypeValidator.cs similarity index 99% rename from src/Adapter/MSTest.TestAdapter/Discovery/TypeValidator.cs rename to src/Adapter/MSTestAdapter.PlatformServices/Discovery/TypeValidator.cs index b82623ca7c..5589955516 100644 --- a/src/Adapter/MSTest.TestAdapter/Discovery/TypeValidator.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Discovery/TypeValidator.cs @@ -2,6 +2,7 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Helpers; +using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Discovery; diff --git a/src/Adapter/MSTest.TestAdapter/Discovery/UnitTestDiscoverer.cs b/src/Adapter/MSTestAdapter.PlatformServices/Discovery/UnitTestDiscoverer.cs similarity index 98% rename from src/Adapter/MSTest.TestAdapter/Discovery/UnitTestDiscoverer.cs rename to src/Adapter/MSTestAdapter.PlatformServices/Discovery/UnitTestDiscoverer.cs index b3b92c1548..2de1b9dcb4 100644 --- a/src/Adapter/MSTest.TestAdapter/Discovery/UnitTestDiscoverer.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Discovery/UnitTestDiscoverer.cs @@ -3,6 +3,7 @@ using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Discovery; using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel; +using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; using Microsoft.VisualStudio.TestPlatform.ObjectModel; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging; @@ -108,7 +109,7 @@ internal void SendTestCases(string source, IEnumerable testElem foreach (UnitTestElement testElement in testElements) { var testCase = testElement.ToTestCase(); - bool hasFixtureTraits = testCase.Traits.Any(t => t.Name == Constants.FixturesTestTrait); + bool hasFixtureTraits = testCase.Traits.Any(t => t.Name == EngineConstants.FixturesTestTrait); // Filter tests based on test case filters if (filterExpression != null && !filterExpression.MatchTestCase(testCase, p => _testMethodFilter.PropertyValueProvider(testCase, p))) diff --git a/src/Adapter/MSTest.TestAdapter/Constants.cs b/src/Adapter/MSTestAdapter.PlatformServices/EngineConstants.cs similarity index 88% rename from src/Adapter/MSTest.TestAdapter/Constants.cs rename to src/Adapter/MSTestAdapter.PlatformServices/EngineConstants.cs index 7052dcda1a..4b4bff2115 100644 --- a/src/Adapter/MSTest.TestAdapter/Constants.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/EngineConstants.cs @@ -3,14 +3,38 @@ using Microsoft.VisualStudio.TestPlatform.ObjectModel; -namespace Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter; +namespace Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; -/// -/// Constants used throughout. -/// -internal static class Constants +internal static class EngineConstants { - internal const string PublicTypeObsoleteMessage = "We will remove or hide this type starting with v4. If you are using this type, reach out to our team on https://github.com/microsoft/testfx."; +#if NETFRAMEWORK + /// + /// Constants for detecting .net framework. + /// + public const string TargetFrameworkAttributeFullName = "System.Runtime.Versioning.TargetFrameworkAttribute"; + + public const string DotNetFrameWorkStringPrefix = ".NETFramework,Version="; + + public const string TargetFrameworkName = "TargetFrameworkName"; + + public const string PublicAssemblies = "PublicAssemblies"; + + public const string PrivateAssemblies = "PrivateAssemblies"; +#endif + + internal const string DllExtension = ".dll"; + internal const string ExeExtension = ".exe"; + internal const string AppxPackageExtension = ".appx"; + +#if NETFRAMEWORK + internal const string PhoneAppxPackageExtension = ".appx"; + + // These are tied to a specific VS version. Can be changed to have a list of supported version instead. + internal const string VisualStudioRootRegKey32ForDev14 = @"SOFTWARE\Microsoft\VisualStudio\" + VisualStudioVersion; + internal const string VisualStudioRootRegKey64ForDev14 = @"SOFTWARE\Wow6432Node\Microsoft\VisualStudio\" + VisualStudioVersion; + + internal const string VisualStudioVersion = "14.0"; +#endif /// /// The 3rd level entry (class) name in the hierarchy array. @@ -42,21 +66,11 @@ internal static class Constants /// internal const string ClassCleanupFixtureTrait = "ClassCleanup"; - /// - /// Uri of the MSTest executor. - /// - internal const string ExecutorUriString = "executor://MSTestAdapter/v2"; - /// /// The name of test run parameters node in the runsettings. /// internal const string TestRunParametersName = "TestRunParameters"; - /// - /// The executor uri for this adapter. - /// - internal static readonly Uri ExecutorUri = new(ExecutorUriString); - #region Test Property registration internal static readonly TestProperty DescriptionProperty = TestProperty.Register("Description", DescriptionLabel, typeof(string), TestPropertyAttributes.Hidden, typeof(TestCase)); @@ -163,4 +177,14 @@ internal static class Constants private const string TfsTeamProject = "__Tfs_TeamProject__"; #endregion + + /// + /// Uri of the MSTest executor. + /// + internal const string ExecutorUriString = "executor://MSTestAdapter/v2"; + + /// + /// The executor uri for this adapter. + /// + internal static readonly Uri ExecutorUri = new(ExecutorUriString); } diff --git a/src/Adapter/MSTest.TestAdapter/Execution/ClassCleanupManager.cs b/src/Adapter/MSTestAdapter.PlatformServices/Execution/ClassCleanupManager.cs similarity index 97% rename from src/Adapter/MSTest.TestAdapter/Execution/ClassCleanupManager.cs rename to src/Adapter/MSTestAdapter.PlatformServices/Execution/ClassCleanupManager.cs index fca58e95d8..43f89ad3c1 100644 --- a/src/Adapter/MSTest.TestAdapter/Execution/ClassCleanupManager.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Execution/ClassCleanupManager.cs @@ -22,7 +22,7 @@ public ClassCleanupManager( ClassCleanupBehavior lifecycleFromAssembly, ReflectHelper reflectHelper) { - IEnumerable runnableTests = testsToRun.Where(t => t.Traits is null || !t.Traits.Any(t => t.Name == Constants.FixturesTestTrait)); + IEnumerable runnableTests = testsToRun.Where(t => t.Traits is null || !t.Traits.Any(t => t.Name == EngineConstants.FixturesTestTrait)); _remainingTestsByClass = new(runnableTests.GroupBy(t => t.TestMethod.FullClassName) .ToDictionary( diff --git a/src/Adapter/MSTest.TestAdapter/Execution/ExceptionHelper.cs b/src/Adapter/MSTestAdapter.PlatformServices/Execution/ExceptionHelper.cs similarity index 97% rename from src/Adapter/MSTest.TestAdapter/Execution/ExceptionHelper.cs rename to src/Adapter/MSTestAdapter.PlatformServices/Execution/ExceptionHelper.cs index eecbd05a4e..8e774940c0 100644 --- a/src/Adapter/MSTest.TestAdapter/Execution/ExceptionHelper.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Execution/ExceptionHelper.cs @@ -2,6 +2,7 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel; +using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution; @@ -15,7 +16,7 @@ internal static class ExceptionHelper /// Gets the types whose methods should be ignored in the reported call stacks. /// This is used to remove our stack that the user will not care about. /// - private static readonly List TypesToBeExcluded = [typeof(Assert).Namespace!, typeof(MSTestExecutor).Namespace!]; + private static readonly List TypesToBeExcluded = [typeof(Assert).Namespace!, "Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter"]; /// /// Gets the stack trace for an exception, including all stack traces for inner diff --git a/src/Adapter/MSTest.TestAdapter/Execution/LogMessageListener.cs b/src/Adapter/MSTestAdapter.PlatformServices/Execution/LogMessageListener.cs similarity index 97% rename from src/Adapter/MSTest.TestAdapter/Execution/LogMessageListener.cs rename to src/Adapter/MSTestAdapter.PlatformServices/Execution/LogMessageListener.cs index 39b3dada59..f58c8ce44f 100644 --- a/src/Adapter/MSTest.TestAdapter/Execution/LogMessageListener.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Execution/LogMessageListener.cs @@ -12,9 +12,9 @@ namespace Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution; /// Note that this class is not thread-safe and thus should only be used when unit tests are being run serially. /// #if NET6_0_OR_GREATER -[Obsolete(Constants.PublicTypeObsoleteMessage, DiagnosticId = "MSTESTOBS")] +[Obsolete(TestTools.UnitTesting.FrameworkConstants.PublicTypeObsoleteMessage, DiagnosticId = "MSTESTOBS")] #else -[Obsolete(Constants.PublicTypeObsoleteMessage)] +[Obsolete(TestTools.UnitTesting.FrameworkConstants.PublicTypeObsoleteMessage)] #endif public class LogMessageListener : IDisposable { diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Execution/TcmTestPropertiesProvider.cs b/src/Adapter/MSTestAdapter.PlatformServices/Execution/TcmTestPropertiesProvider.cs new file mode 100644 index 0000000000..5a80df389a --- /dev/null +++ b/src/Adapter/MSTestAdapter.PlatformServices/Execution/TcmTestPropertiesProvider.cs @@ -0,0 +1,52 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; + +using TestPlatformObjectModel = Microsoft.VisualStudio.TestPlatform.ObjectModel; + +namespace Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution; + +/// +/// Reads and parses the TcmTestProperties in order to populate them in TestRunParameters. +/// +internal static class TcmTestPropertiesProvider +{ + /// + /// Gets tcm properties from test case. + /// + /// Test case. + /// Tcm properties. + public static IDictionary GetTcmProperties(TestPlatformObjectModel.TestCase? testCase) + { + var tcmProperties = new Dictionary(); + + // Return empty properties when testCase is null or when test case id is zero. + if (testCase == null || + testCase.GetPropertyValue(EngineConstants.TestCaseIdProperty, default) == 0) + { + return tcmProperties; + } + + // Step 1: Add common properties. + tcmProperties[EngineConstants.TestRunIdProperty] = testCase.GetPropertyValue(EngineConstants.TestRunIdProperty, default); + tcmProperties[EngineConstants.TestPlanIdProperty] = testCase.GetPropertyValue(EngineConstants.TestPlanIdProperty, default); + tcmProperties[EngineConstants.BuildConfigurationIdProperty] = testCase.GetPropertyValue(EngineConstants.BuildConfigurationIdProperty, default); + tcmProperties[EngineConstants.BuildDirectoryProperty] = testCase.GetPropertyValue(EngineConstants.BuildDirectoryProperty, default); + tcmProperties[EngineConstants.BuildFlavorProperty] = testCase.GetPropertyValue(EngineConstants.BuildFlavorProperty, default); + tcmProperties[EngineConstants.BuildNumberProperty] = testCase.GetPropertyValue(EngineConstants.BuildNumberProperty, default); + tcmProperties[EngineConstants.BuildPlatformProperty] = testCase.GetPropertyValue(EngineConstants.BuildPlatformProperty, default); + tcmProperties[EngineConstants.BuildUriProperty] = testCase.GetPropertyValue(EngineConstants.BuildUriProperty, default); + tcmProperties[EngineConstants.TfsServerCollectionUrlProperty] = testCase.GetPropertyValue(EngineConstants.TfsServerCollectionUrlProperty, default); + tcmProperties[EngineConstants.TfsTeamProjectProperty] = testCase.GetPropertyValue(EngineConstants.TfsTeamProjectProperty, default); + tcmProperties[EngineConstants.IsInLabEnvironmentProperty] = testCase.GetPropertyValue(EngineConstants.IsInLabEnvironmentProperty, default); + + // Step 2: Add test case specific properties. + tcmProperties[EngineConstants.TestCaseIdProperty] = testCase.GetPropertyValue(EngineConstants.TestCaseIdProperty, default); + tcmProperties[EngineConstants.TestConfigurationIdProperty] = testCase.GetPropertyValue(EngineConstants.TestConfigurationIdProperty, default); + tcmProperties[EngineConstants.TestConfigurationNameProperty] = testCase.GetPropertyValue(EngineConstants.TestConfigurationNameProperty, default); + tcmProperties[EngineConstants.TestPointIdProperty] = testCase.GetPropertyValue(EngineConstants.TestPointIdProperty, default); + + return tcmProperties; + } +} diff --git a/src/Adapter/MSTest.TestAdapter/Execution/TestAssemblyInfo.cs b/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestAssemblyInfo.cs similarity index 97% rename from src/Adapter/MSTest.TestAdapter/Execution/TestAssemblyInfo.cs rename to src/Adapter/MSTestAdapter.PlatformServices/Execution/TestAssemblyInfo.cs index e3155f5def..21aab26542 100644 --- a/src/Adapter/MSTest.TestAdapter/Execution/TestAssemblyInfo.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestAssemblyInfo.cs @@ -4,6 +4,8 @@ using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Extensions; using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Helpers; using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel; +using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; +using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Extensions; using Microsoft.VisualStudio.TestTools.UnitTesting; using UnitTestOutcome = Microsoft.VisualStudio.TestTools.UnitTesting.UnitTestOutcome; @@ -14,9 +16,9 @@ namespace Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution; /// Defines TestAssembly Info object. /// #if NET6_0_OR_GREATER -[Obsolete(Constants.PublicTypeObsoleteMessage, DiagnosticId = "MSTESTOBS")] +[Obsolete(FrameworkConstants.PublicTypeObsoleteMessage, DiagnosticId = "MSTESTOBS")] #else -[Obsolete(Constants.PublicTypeObsoleteMessage)] +[Obsolete(FrameworkConstants.PublicTypeObsoleteMessage)] #endif public class TestAssemblyInfo { diff --git a/src/Adapter/MSTest.TestAdapter/Execution/TestAssemblySettingsProvider.cs b/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestAssemblySettingsProvider.cs similarity index 100% rename from src/Adapter/MSTest.TestAdapter/Execution/TestAssemblySettingsProvider.cs rename to src/Adapter/MSTestAdapter.PlatformServices/Execution/TestAssemblySettingsProvider.cs diff --git a/src/Adapter/MSTest.TestAdapter/Execution/TestCaseDiscoverySink.cs b/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestCaseDiscoverySink.cs similarity index 100% rename from src/Adapter/MSTest.TestAdapter/Execution/TestCaseDiscoverySink.cs rename to src/Adapter/MSTestAdapter.PlatformServices/Execution/TestCaseDiscoverySink.cs diff --git a/src/Adapter/MSTest.TestAdapter/Execution/TestClassInfo.cs b/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestClassInfo.cs similarity index 99% rename from src/Adapter/MSTest.TestAdapter/Execution/TestClassInfo.cs rename to src/Adapter/MSTestAdapter.PlatformServices/Execution/TestClassInfo.cs index ba55a398c4..85b388b123 100644 --- a/src/Adapter/MSTest.TestAdapter/Execution/TestClassInfo.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestClassInfo.cs @@ -4,6 +4,8 @@ using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Extensions; using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Helpers; using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel; +using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; +using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Extensions; using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Interface; using Microsoft.VisualStudio.TestTools.UnitTesting; @@ -15,9 +17,9 @@ namespace Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution; /// Defines the TestClassInfo object. /// #if NET6_0_OR_GREATER -[Obsolete(Constants.PublicTypeObsoleteMessage, DiagnosticId = "MSTESTOBS")] +[Obsolete(FrameworkConstants.PublicTypeObsoleteMessage, DiagnosticId = "MSTESTOBS")] #else -[Obsolete(Constants.PublicTypeObsoleteMessage)] +[Obsolete(FrameworkConstants.PublicTypeObsoleteMessage)] #endif public class TestClassInfo { diff --git a/src/Adapter/MSTest.TestAdapter/Execution/TestExecutionManager.cs b/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestExecutionManager.cs similarity index 97% rename from src/Adapter/MSTest.TestAdapter/Execution/TestExecutionManager.cs rename to src/Adapter/MSTestAdapter.PlatformServices/Execution/TestExecutionManager.cs index 5fe5f07078..4e8d7cd7a8 100644 --- a/src/Adapter/MSTest.TestAdapter/Execution/TestExecutionManager.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestExecutionManager.cs @@ -4,20 +4,23 @@ using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Extensions; using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Helpers; using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel; +using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; using Microsoft.VisualStudio.TestPlatform.ObjectModel; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging; using Microsoft.VisualStudio.TestTools.UnitTesting; +using ExecutionScope = Microsoft.VisualStudio.TestTools.UnitTesting.ExecutionScope; + namespace Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution; /// /// Class responsible for execution of tests at assembly level and sending tests via framework handle. /// #if NET6_0_OR_GREATER -[Obsolete(Constants.PublicTypeObsoleteMessage, DiagnosticId = "MSTESTOBS")] +[Obsolete(TestTools.UnitTesting.FrameworkConstants.PublicTypeObsoleteMessage, DiagnosticId = "MSTESTOBS")] #else -[Obsolete(Constants.PublicTypeObsoleteMessage)] +[Obsolete(TestTools.UnitTesting.FrameworkConstants.PublicTypeObsoleteMessage)] #endif public class TestExecutionManager { @@ -318,7 +321,7 @@ private static bool MatchTestFilter(ITestCaseFilterExpression? filterExpression, && !filterExpression.MatchTestCase(test, p => testMethodFilter.PropertyValueProvider(test, p))) { // If this is a fixture test, return true. Fixture tests are not filtered out and are always available for the status. - if (test.Traits.Any(t => t.Name == Constants.FixturesTestTrait)) + if (test.Traits.Any(t => t.Name == EngineConstants.FixturesTestTrait)) { return true; } @@ -348,7 +351,7 @@ private async Task ExecuteTestsInSourceAsync(IEnumerable tests, IRunCo } using MSTestAdapter.PlatformServices.Interface.ITestSourceHost isolationHost = PlatformServiceProvider.Instance.CreateTestSourceHost(source, runContext?.RunSettings, frameworkHandle); - bool usesAppDomains = isolationHost is MSTestAdapter.PlatformServices.TestSourceHost { UsesAppDomain: true }; + bool usesAppDomains = isolationHost is TestSourceHost { UsesAppDomain: true }; PlatformServiceProvider.Instance.AdapterTraceLogger.LogInfo("Created unit-test runner {0}", source); // Default test set is filtered tests based on user provided filter criteria @@ -420,7 +423,7 @@ private async Task ExecuteTestsInSourceAsync(IEnumerable tests, IRunCo // Create test sets for execution, we can execute them in parallel based on parallel settings // Parallel and not parallel sets. - IEnumerable> testSets = testsToRun.GroupBy(t => t.GetPropertyValue(Constants.DoNotParallelizeProperty, false)); + IEnumerable> testSets = testsToRun.GroupBy(t => t.GetPropertyValue(EngineConstants.DoNotParallelizeProperty, false)); IGrouping? parallelizableTestSet = testSets.FirstOrDefault(g => !g.Key); IGrouping? nonParallelizableTestSet = testSets.FirstOrDefault(g => g.Key); @@ -437,7 +440,7 @@ private async Task ExecuteTestsInSourceAsync(IEnumerable tests, IRunCo break; case ExecutionScope.ClassLevel: - queue = new ConcurrentQueue>(parallelizableTestSet.GroupBy(t => t.GetPropertyValue(Constants.TestClassNameProperty) as string)); + queue = new ConcurrentQueue>(parallelizableTestSet.GroupBy(t => t.GetPropertyValue(EngineConstants.TestClassNameProperty) as string)); break; } @@ -530,7 +533,7 @@ private async Task ExecuteTestsWithTestRunnerAsync( // If it is a fixture test, add it to the list of fixture tests and do not execute it. // It is executed by test itself. - if (currentTest.Traits.Any(t => t.Name == Constants.FixturesTestTrait)) + if (currentTest.Traits.Any(t => t.Name == EngineConstants.FixturesTestTrait)) { fixtureTests.Add(currentTest); continue; @@ -588,7 +591,7 @@ private async Task ExecuteTestsWithTestRunnerAsync( continue; } - Trait trait = currentTest.Traits.First(t => t.Name == Constants.FixturesTestTrait); + Trait trait = currentTest.Traits.First(t => t.Name == EngineConstants.FixturesTestTrait); var unitTestElement = currentTest.ToUnitTestElement(source); FixtureTestResult fixtureTestResult = testRunner.GetFixtureTestResult(unitTestElement.TestMethod, trait.Value); diff --git a/src/Adapter/MSTest.TestAdapter/Execution/TestMethodInfo.cs b/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestMethodInfo.cs similarity index 98% rename from src/Adapter/MSTest.TestAdapter/Execution/TestMethodInfo.cs rename to src/Adapter/MSTestAdapter.PlatformServices/Execution/TestMethodInfo.cs index 2be31c1b9b..0a57430762 100644 --- a/src/Adapter/MSTest.TestAdapter/Execution/TestMethodInfo.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestMethodInfo.cs @@ -18,9 +18,9 @@ namespace Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution; /// Defines the TestMethod Info object. /// #if NET6_0_OR_GREATER -[Obsolete(Constants.PublicTypeObsoleteMessage, DiagnosticId = "MSTESTOBS")] +[Obsolete(Microsoft.VisualStudio.TestTools.UnitTesting.FrameworkConstants.PublicTypeObsoleteMessage, DiagnosticId = "MSTESTOBS")] #else -[Obsolete(Constants.PublicTypeObsoleteMessage)] +[Obsolete(Microsoft.VisualStudio.TestTools.UnitTesting.FrameworkConstants.PublicTypeObsoleteMessage)] #endif public class TestMethodInfo : ITestMethod { @@ -644,7 +644,7 @@ private static TestFailedException HandleMethodException(Exception ex, Exception } // Get the real exception thrown by the test method - if (realException.TryGetUnitTestAssertException(out UTF.UnitTestOutcome outcome, out string? exceptionMessage, out StackTraceInformation? exceptionStackTraceInfo)) + if (realException.TryGetUnitTestAssertException(out UTFUnitTestOutcome outcome, out string? exceptionMessage, out StackTraceInformation? exceptionStackTraceInfo)) { return new TestFailedException(outcome, exceptionMessage, exceptionStackTraceInfo, realException); } @@ -747,7 +747,7 @@ private void RunTestCleanupMethod(TestResult result, ExecutionContext? execution } Exception realException = testCleanupException.GetRealException(); - UTF.UnitTestOutcome outcomeFromRealException = realException is AssertInconclusiveException ? UTF.UnitTestOutcome.Inconclusive : UTF.UnitTestOutcome.Failed; + UTFUnitTestOutcome outcomeFromRealException = realException is AssertInconclusiveException ? UTF.UnitTestOutcome.Inconclusive : UTF.UnitTestOutcome.Failed; result.Outcome = result.Outcome.GetMoreImportantOutcome(outcomeFromRealException); realException = testCleanupMethod != null diff --git a/src/Adapter/MSTest.TestAdapter/Execution/TestMethodRunner.cs b/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestMethodRunner.cs similarity index 99% rename from src/Adapter/MSTest.TestAdapter/Execution/TestMethodRunner.cs rename to src/Adapter/MSTestAdapter.PlatformServices/Execution/TestMethodRunner.cs index 8d770d8460..5c82521885 100644 --- a/src/Adapter/MSTest.TestAdapter/Execution/TestMethodRunner.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestMethodRunner.cs @@ -6,6 +6,8 @@ using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Helpers; using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel; using Microsoft.VisualStudio.TestPlatform.MSTestAdapter; +using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; +using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Extensions; using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Interface; using Microsoft.VisualStudio.TestTools.UnitTesting; using Microsoft.VisualStudio.TestTools.UnitTesting.Internal; diff --git a/src/Adapter/MSTest.TestAdapter/Execution/TestRunCancellationToken.cs b/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestRunCancellationToken.cs similarity index 92% rename from src/Adapter/MSTest.TestAdapter/Execution/TestRunCancellationToken.cs rename to src/Adapter/MSTestAdapter.PlatformServices/Execution/TestRunCancellationToken.cs index 51516465c7..607a553058 100644 --- a/src/Adapter/MSTest.TestAdapter/Execution/TestRunCancellationToken.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestRunCancellationToken.cs @@ -7,9 +7,9 @@ namespace Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter; /// Cancellation token supporting cancellation of a test run. /// #if NET6_0_OR_GREATER -[Obsolete(Constants.PublicTypeObsoleteMessage, DiagnosticId = "MSTESTOBS")] +[Obsolete(TestTools.UnitTesting.FrameworkConstants.PublicTypeObsoleteMessage, DiagnosticId = "MSTESTOBS")] #else -[Obsolete(Constants.PublicTypeObsoleteMessage)] +[Obsolete(TestTools.UnitTesting.FrameworkConstants.PublicTypeObsoleteMessage)] #endif public class TestRunCancellationToken { diff --git a/src/Adapter/MSTest.TestAdapter/Execution/TimeoutInfo.cs b/src/Adapter/MSTestAdapter.PlatformServices/Execution/TimeoutInfo.cs similarity index 100% rename from src/Adapter/MSTest.TestAdapter/Execution/TimeoutInfo.cs rename to src/Adapter/MSTestAdapter.PlatformServices/Execution/TimeoutInfo.cs diff --git a/src/Adapter/MSTest.TestAdapter/Execution/TypeCache.cs b/src/Adapter/MSTestAdapter.PlatformServices/Execution/TypeCache.cs similarity index 99% rename from src/Adapter/MSTest.TestAdapter/Execution/TypeCache.cs rename to src/Adapter/MSTestAdapter.PlatformServices/Execution/TypeCache.cs index 2d49d1fe10..f34f2d4016 100644 --- a/src/Adapter/MSTest.TestAdapter/Execution/TypeCache.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Execution/TypeCache.cs @@ -8,6 +8,7 @@ using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Extensions; using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Helpers; using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel; +using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Interface; using Microsoft.VisualStudio.TestTools.UnitTesting; diff --git a/src/Adapter/MSTest.TestAdapter/Execution/UnitTestRunner.cs b/src/Adapter/MSTestAdapter.PlatformServices/Execution/UnitTestRunner.cs similarity index 95% rename from src/Adapter/MSTest.TestAdapter/Execution/UnitTestRunner.cs rename to src/Adapter/MSTestAdapter.PlatformServices/Execution/UnitTestRunner.cs index 03093d24b9..af20854ed8 100644 --- a/src/Adapter/MSTest.TestAdapter/Execution/UnitTestRunner.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Execution/UnitTestRunner.cs @@ -8,6 +8,7 @@ using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel; using Microsoft.VisualStudio.TestPlatform.MSTestAdapter; using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; +using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Extensions; using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Interface; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging; using Microsoft.VisualStudio.TestTools.UnitTesting; @@ -93,25 +94,25 @@ internal FixtureTestResult GetFixtureTestResult(TestMethod testMethod, string fi { // For the fixture methods, we need to return the appropriate result. // Get matching testMethodInfo from the cache and return UnitTestOutcome for the fixture test. - if (fixtureType is Constants.ClassInitializeFixtureTrait or Constants.ClassCleanupFixtureTrait && + if (fixtureType is EngineConstants.ClassInitializeFixtureTrait or EngineConstants.ClassCleanupFixtureTrait && _classFixtureTests.TryGetValue(testMethod.AssemblyName + testMethod.FullClassName, out TestClassInfo? testClassInfo)) { UnitTestOutcome outcome = fixtureType switch { - Constants.ClassInitializeFixtureTrait => testClassInfo.IsClassInitializeExecuted ? GetOutcome(testClassInfo.ClassInitializationException) : UnitTestOutcome.Inconclusive, - Constants.ClassCleanupFixtureTrait => testClassInfo.IsClassCleanupExecuted ? GetOutcome(testClassInfo.ClassCleanupException) : UnitTestOutcome.Inconclusive, + EngineConstants.ClassInitializeFixtureTrait => testClassInfo.IsClassInitializeExecuted ? GetOutcome(testClassInfo.ClassInitializationException) : UnitTestOutcome.Inconclusive, + EngineConstants.ClassCleanupFixtureTrait => testClassInfo.IsClassCleanupExecuted ? GetOutcome(testClassInfo.ClassCleanupException) : UnitTestOutcome.Inconclusive, _ => throw ApplicationStateGuard.Unreachable(), }; return new FixtureTestResult(true, outcome); } - else if (fixtureType is Constants.AssemblyInitializeFixtureTrait or Constants.AssemblyCleanupFixtureTrait && + else if (fixtureType is EngineConstants.AssemblyInitializeFixtureTrait or EngineConstants.AssemblyCleanupFixtureTrait && _assemblyFixtureTests.TryGetValue(testMethod.AssemblyName, out TestAssemblyInfo? testAssemblyInfo)) { Exception? exception = fixtureType switch { - Constants.AssemblyInitializeFixtureTrait => testAssemblyInfo.AssemblyInitializationException, - Constants.AssemblyCleanupFixtureTrait => testAssemblyInfo.AssemblyCleanupException, + EngineConstants.AssemblyInitializeFixtureTrait => testAssemblyInfo.AssemblyInitializationException, + EngineConstants.AssemblyCleanupFixtureTrait => testAssemblyInfo.AssemblyCleanupException, _ => throw ApplicationStateGuard.Unreachable(), }; diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Extensions/ExceptionExtensions.cs b/src/Adapter/MSTestAdapter.PlatformServices/Extensions/ExceptionExtensions.cs index 249c88e47f..4dac689e2b 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Extensions/ExceptionExtensions.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Extensions/ExceptionExtensions.cs @@ -1,6 +1,12 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution; +using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +using UTF = Microsoft.VisualStudio.TestTools.UnitTesting; + namespace Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Extensions; /// @@ -30,4 +36,76 @@ internal static string GetExceptionMessage(this Exception exception) internal static bool IsOperationCanceledExceptionFromToken(this Exception ex, CancellationToken cancellationToken) => (ex is OperationCanceledException oce && oce.CancellationToken == cancellationToken) || (ex is AggregateException aggregateEx && aggregateEx.InnerExceptions.OfType().Any(oce => oce.CancellationToken == cancellationToken)); + + /// + /// TargetInvocationException and TypeInitializationException do not carry any useful information + /// to the user. Find the first inner exception that has useful information. + /// + internal static Exception GetRealException(this Exception exception) + { + // TargetInvocationException: Because .NET Framework wraps method.Invoke() into TargetInvocationException. + // TypeInitializationException: Because AssemblyInitialize is static, and often helpers that are also static + // are used to implement it, and they fail in constructor. + while (exception is TargetInvocationException or TypeInitializationException + && exception.InnerException is not null) + { + exception = exception.InnerException; + } + + return exception; + } + + /// + /// Get the exception message if available, empty otherwise. + /// + /// An object. + /// Exception message. + internal static string TryGetMessage(this Exception? exception) + { + if (exception == null) + { + return string.Format(CultureInfo.CurrentCulture, Resource.UTF_FailedToGetExceptionMessage, "null"); + } + + // It is safe to retrieve an exception message, it should not throw in any case. + return exception.Message ?? string.Empty; + } + + /// + /// Gets the for an exception. + /// + /// An instance. + /// StackTraceInformation for the exception. + internal static StackTraceInformation? TryGetStackTraceInformation(this Exception exception) + => !StringEx.IsNullOrEmpty(exception.StackTrace) + ? ExceptionHelper.CreateStackTraceInformation(exception.StackTrace) + : null; + + /// + /// Checks whether exception is an Assert exception. + /// + /// An instance. + /// Framework's Outcome depending on type of assertion. + /// Exception message. + /// StackTraceInformation for the exception. + /// True, if Assert exception. False, otherwise. + internal static bool TryGetUnitTestAssertException(this Exception exception, out UTF.UnitTestOutcome outcome, + [NotNullWhen(true)] out string? exceptionMessage, out StackTraceInformation? exceptionStackTrace) + { + if (exception is UnitTestAssertException) + { + outcome = exception is AssertInconclusiveException + ? UTF.UnitTestOutcome.Inconclusive + : UTF.UnitTestOutcome.Failed; + + exceptionMessage = exception.TryGetMessage(); + exceptionStackTrace = exception.TryGetStackTraceInformation(); + return true; + } + + outcome = UTF.UnitTestOutcome.Failed; + exceptionMessage = null; + exceptionStackTrace = null; + return false; + } } diff --git a/src/Adapter/MSTest.TestAdapter/Extensions/MethodInfoExtensions.cs b/src/Adapter/MSTestAdapter.PlatformServices/Extensions/MethodInfoExtensions.cs similarity index 98% rename from src/Adapter/MSTest.TestAdapter/Extensions/MethodInfoExtensions.cs rename to src/Adapter/MSTestAdapter.PlatformServices/Extensions/MethodInfoExtensions.cs index b34dab9522..46fb6e6d53 100644 --- a/src/Adapter/MSTest.TestAdapter/Extensions/MethodInfoExtensions.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Extensions/MethodInfoExtensions.cs @@ -4,6 +4,8 @@ using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Helpers; using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel; using Microsoft.VisualStudio.TestPlatform.MSTestAdapter; +using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; +using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Extensions; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Extensions; diff --git a/src/Adapter/MSTest.TestAdapter/Extensions/TestCaseExtensions.cs b/src/Adapter/MSTestAdapter.PlatformServices/Extensions/TestCaseExtensions.cs similarity index 84% rename from src/Adapter/MSTest.TestAdapter/Extensions/TestCaseExtensions.cs rename to src/Adapter/MSTestAdapter.PlatformServices/Extensions/TestCaseExtensions.cs index 44a8247390..434c6f5f8b 100644 --- a/src/Adapter/MSTest.TestAdapter/Extensions/TestCaseExtensions.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Extensions/TestCaseExtensions.cs @@ -3,6 +3,7 @@ using Microsoft.TestPlatform.AdapterUtilities; using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel; +using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; using Microsoft.VisualStudio.TestPlatform.ObjectModel; using Microsoft.VisualStudio.TestTools.UnitTesting; @@ -69,34 +70,34 @@ internal static string GetTestName(this TestCase testCase, string? testClassName /// The converted . internal static UnitTestElement ToUnitTestElement(this TestCase testCase, string source) { - string? testClassName = testCase.GetPropertyValue(Constants.TestClassNameProperty) as string; + string? testClassName = testCase.GetPropertyValue(EngineConstants.TestClassNameProperty) as string; string name = testCase.GetTestName(testClassName); var testIdGenerationStrategy = (TestIdGenerationStrategy)testCase.GetPropertyValue( - Constants.TestIdGenerationStrategyProperty, + EngineConstants.TestIdGenerationStrategyProperty, (int)TestIdGenerationStrategy.FullyQualified); TestMethod testMethod = testCase.ContainsManagedMethodAndType() ? new(testCase.GetManagedType(), testCase.GetManagedMethod(), testCase.GetHierarchy()!, name, testClassName!, source, testCase.DisplayName, testIdGenerationStrategy) : new(name, testClassName!, source, testCase.DisplayName, testIdGenerationStrategy); - var dataType = (DynamicDataType)testCase.GetPropertyValue(Constants.TestDynamicDataTypeProperty, (int)DynamicDataType.None); + var dataType = (DynamicDataType)testCase.GetPropertyValue(EngineConstants.TestDynamicDataTypeProperty, (int)DynamicDataType.None); if (dataType != DynamicDataType.None) { - string[]? data = testCase.GetPropertyValue(Constants.TestDynamicDataProperty, null); + string[]? data = testCase.GetPropertyValue(EngineConstants.TestDynamicDataProperty, null); testMethod.DataType = dataType; testMethod.SerializedData = data; - testMethod.TestDataSourceIgnoreMessage = testCase.GetPropertyValue(Constants.TestDataSourceIgnoreMessageProperty) as string; + testMethod.TestDataSourceIgnoreMessage = testCase.GetPropertyValue(EngineConstants.TestDataSourceIgnoreMessageProperty) as string; } - if (testCase.GetPropertyValue(Constants.DeclaringClassNameProperty) is string declaringClassName && declaringClassName != testClassName) + if (testCase.GetPropertyValue(EngineConstants.DeclaringClassNameProperty) is string declaringClassName && declaringClassName != testClassName) { testMethod.DeclaringClassFullName = declaringClassName; } UnitTestElement testElement = new(testMethod) { - TestCategory = testCase.GetPropertyValue(Constants.TestCategoryProperty) as string[], - Priority = testCase.GetPropertyValue(Constants.PriorityProperty) as int?, + TestCategory = testCase.GetPropertyValue(EngineConstants.TestCategoryProperty) as string[], + Priority = testCase.GetPropertyValue(EngineConstants.PriorityProperty) as int?, DisplayName = testCase.DisplayName, }; @@ -105,37 +106,37 @@ internal static UnitTestElement ToUnitTestElement(this TestCase testCase, string testElement.Traits = [.. testCase.Traits]; } - string? cssIteration = testCase.GetPropertyValue(Constants.CssIterationProperty, null); + string? cssIteration = testCase.GetPropertyValue(EngineConstants.CssIterationProperty, null); if (!StringEx.IsNullOrWhiteSpace(cssIteration)) { testElement.CssIteration = cssIteration; } - string? cssProjectStructure = testCase.GetPropertyValue(Constants.CssProjectStructureProperty, null); + string? cssProjectStructure = testCase.GetPropertyValue(EngineConstants.CssProjectStructureProperty, null); if (!StringEx.IsNullOrWhiteSpace(cssProjectStructure)) { testElement.CssProjectStructure = cssProjectStructure; } - string? description = testCase.GetPropertyValue(Constants.DescriptionProperty, null); + string? description = testCase.GetPropertyValue(EngineConstants.DescriptionProperty, null); if (!StringEx.IsNullOrWhiteSpace(description)) { testElement.Description = description; } - string[]? workItemIds = testCase.GetPropertyValue(Constants.WorkItemIdsProperty, null); + string[]? workItemIds = testCase.GetPropertyValue(EngineConstants.WorkItemIdsProperty, null); if (workItemIds is { Length: > 0 }) { testElement.WorkItemIds = workItemIds; } - KeyValuePair[]? deploymentItems = testCase.GetPropertyValue[]>(Constants.DeploymentItemsProperty, null); + KeyValuePair[]? deploymentItems = testCase.GetPropertyValue[]>(EngineConstants.DeploymentItemsProperty, null); if (deploymentItems is { Length: > 0 }) { testElement.DeploymentItems = deploymentItems; } - testElement.DoNotParallelize = testCase.GetPropertyValue(Constants.DoNotParallelizeProperty, false); + testElement.DoNotParallelize = testCase.GetPropertyValue(EngineConstants.DoNotParallelizeProperty, false); return testElement; } diff --git a/src/Adapter/MSTest.TestAdapter/Extensions/TestContextExtensions.cs b/src/Adapter/MSTestAdapter.PlatformServices/Extensions/TestContextExtensions.cs similarity index 100% rename from src/Adapter/MSTest.TestAdapter/Extensions/TestContextExtensions.cs rename to src/Adapter/MSTestAdapter.PlatformServices/Extensions/TestContextExtensions.cs diff --git a/src/Adapter/MSTest.TestAdapter/Extensions/TestResultExtensions.cs b/src/Adapter/MSTestAdapter.PlatformServices/Extensions/TestResultExtensions.cs similarity index 85% rename from src/Adapter/MSTest.TestAdapter/Extensions/TestResultExtensions.cs rename to src/Adapter/MSTestAdapter.PlatformServices/Extensions/TestResultExtensions.cs index 7f5c5b80ac..a92ccf186a 100644 --- a/src/Adapter/MSTest.TestAdapter/Extensions/TestResultExtensions.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Extensions/TestResultExtensions.cs @@ -3,6 +3,8 @@ using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Helpers; using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel; +using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; +using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Extensions; using Microsoft.VisualStudio.TestTools.UnitTesting; using UTF = Microsoft.VisualStudio.TestTools.UnitTesting; @@ -19,9 +21,9 @@ namespace Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Extensions; /// Extension methods for TestResult. /// #if NET6_0_OR_GREATER -[Obsolete(Constants.PublicTypeObsoleteMessage, DiagnosticId = "MSTESTOBS")] +[Obsolete(FrameworkConstants.PublicTypeObsoleteMessage, DiagnosticId = "MSTESTOBS")] #else -[Obsolete(Constants.PublicTypeObsoleteMessage)] +[Obsolete(FrameworkConstants.PublicTypeObsoleteMessage)] #endif public static class TestResultExtensions { @@ -34,7 +36,7 @@ public static class TestResultExtensions /// The end Time. /// The computer name. /// Current MSTest settings. - internal static VSTestTestResult ToTestResult(this UTF.TestResult frameworkTestResult, VSTestTestCase testCase, DateTimeOffset startTime, DateTimeOffset endTime, string computerName, MSTestSettings currentSettings) + internal static VSTestTestResult ToTestResult(this TestResult frameworkTestResult, VSTestTestCase testCase, DateTimeOffset startTime, DateTimeOffset endTime, string computerName, MSTestSettings currentSettings) { DebugEx.Assert(testCase != null, "testCase"); @@ -50,9 +52,9 @@ internal static VSTestTestResult ToTestResult(this UTF.TestResult frameworkTestR ComputerName = computerName, }; - testResult.SetPropertyValue(Constants.ExecutionIdProperty, frameworkTestResult.ExecutionId); - testResult.SetPropertyValue(Constants.ParentExecIdProperty, frameworkTestResult.ParentExecId); - testResult.SetPropertyValue(Constants.InnerResultsCountProperty, frameworkTestResult.InnerResultsCount); + testResult.SetPropertyValue(EngineConstants.ExecutionIdProperty, frameworkTestResult.ExecutionId); + testResult.SetPropertyValue(EngineConstants.ParentExecIdProperty, frameworkTestResult.ParentExecId); + testResult.SetPropertyValue(EngineConstants.InnerResultsCountProperty, frameworkTestResult.InnerResultsCount); if (!StringEx.IsNullOrEmpty(frameworkTestResult.LogOutput)) { @@ -82,7 +84,7 @@ internal static VSTestTestResult ToTestResult(this UTF.TestResult frameworkTestR if (frameworkTestResult.ResultFiles is { Count: > 0 }) { - VSTestAttachmentSet attachmentSet = new(Constants.ExecutorUri, Resource.AttachmentSetDisplayName); + VSTestAttachmentSet attachmentSet = new(EngineConstants.ExecutorUri, Resource.AttachmentSetDisplayName); foreach (string resultFile in frameworkTestResult.ResultFiles) { string pathToResultFile = PlatformServiceProvider.Instance.FileOperations.GetFullFilePath(resultFile); @@ -106,12 +108,12 @@ internal static VSTestTestResult ToTestResult(this UTF.TestResult frameworkTestR /// /// The test framework's TestResult object array. /// The serializable UnitTestResult object array. - public static UnitTestResult[] ToUnitTestResults(this UTF.TestResult[] testResults) + public static UnitTestResult[] ToUnitTestResults(this TestResult[] testResults) { var unitTestResults = new UnitTestResult[testResults.Length]; int i = 0; - foreach (UTF.TestResult testResult in testResults) + foreach (TestResult testResult in testResults) { UTF.UnitTestOutcome outcome = testResult.Outcome; diff --git a/src/Adapter/MSTest.TestAdapter/Extensions/UnitTestOutcomeExtensions.cs b/src/Adapter/MSTestAdapter.PlatformServices/Extensions/UnitTestOutcomeExtensions.cs similarity index 92% rename from src/Adapter/MSTest.TestAdapter/Extensions/UnitTestOutcomeExtensions.cs rename to src/Adapter/MSTestAdapter.PlatformServices/Extensions/UnitTestOutcomeExtensions.cs index ee6489d37e..171d7280b8 100644 --- a/src/Adapter/MSTest.TestAdapter/Extensions/UnitTestOutcomeExtensions.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Extensions/UnitTestOutcomeExtensions.cs @@ -11,9 +11,9 @@ namespace Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Extensions; /// Extension methods for . /// #if NET6_0_OR_GREATER -[Obsolete(Constants.PublicTypeObsoleteMessage, DiagnosticId = "MSTESTOBS")] +[Obsolete(TestTools.UnitTesting.FrameworkConstants.PublicTypeObsoleteMessage, DiagnosticId = "MSTESTOBS")] #else -[Obsolete(Constants.PublicTypeObsoleteMessage)] +[Obsolete(TestTools.UnitTesting.FrameworkConstants.PublicTypeObsoleteMessage)] #endif public static class UnitTestOutcomeExtensions { diff --git a/src/Adapter/MSTest.TestAdapter/Helpers/AttributeHelpers.cs b/src/Adapter/MSTestAdapter.PlatformServices/Helpers/AttributeHelpers.cs similarity index 100% rename from src/Adapter/MSTest.TestAdapter/Helpers/AttributeHelpers.cs rename to src/Adapter/MSTestAdapter.PlatformServices/Helpers/AttributeHelpers.cs diff --git a/src/Adapter/MSTest.TestAdapter/Helpers/DataSerializationHelper.cs b/src/Adapter/MSTestAdapter.PlatformServices/Helpers/DataSerializationHelper.cs similarity index 98% rename from src/Adapter/MSTest.TestAdapter/Helpers/DataSerializationHelper.cs rename to src/Adapter/MSTestAdapter.PlatformServices/Helpers/DataSerializationHelper.cs index 22becc21ab..c7c980e9fd 100644 --- a/src/Adapter/MSTest.TestAdapter/Helpers/DataSerializationHelper.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Helpers/DataSerializationHelper.cs @@ -17,7 +17,7 @@ internal static class DataSerializationHelper { UseSimpleDictionaryFormat = true, EmitTypeInformation = System.Runtime.Serialization.EmitTypeInformation.Always, - DateTimeFormat = new System.Runtime.Serialization.DateTimeFormat("O", CultureInfo.InvariantCulture), + DateTimeFormat = new DateTimeFormat("O", CultureInfo.InvariantCulture), #if NETFRAMEWORK DataContractSurrogate = SerializationSurrogateProvider.Instance, #endif diff --git a/src/Adapter/MSTest.TestAdapter/Helpers/DictionaryHelper.cs b/src/Adapter/MSTestAdapter.PlatformServices/Helpers/DictionaryHelper.cs similarity index 100% rename from src/Adapter/MSTest.TestAdapter/Helpers/DictionaryHelper.cs rename to src/Adapter/MSTestAdapter.PlatformServices/Helpers/DictionaryHelper.cs diff --git a/src/Adapter/MSTest.TestAdapter/Helpers/EnvironmentWrapper.cs b/src/Adapter/MSTestAdapter.PlatformServices/Helpers/EnvironmentWrapper.cs similarity index 100% rename from src/Adapter/MSTest.TestAdapter/Helpers/EnvironmentWrapper.cs rename to src/Adapter/MSTestAdapter.PlatformServices/Helpers/EnvironmentWrapper.cs diff --git a/src/Adapter/MSTest.TestAdapter/Helpers/ExecutionContextHelpers.cs b/src/Adapter/MSTestAdapter.PlatformServices/Helpers/ExecutionContextHelpers.cs similarity index 100% rename from src/Adapter/MSTest.TestAdapter/Helpers/ExecutionContextHelpers.cs rename to src/Adapter/MSTestAdapter.PlatformServices/Helpers/ExecutionContextHelpers.cs diff --git a/src/Adapter/MSTest.TestAdapter/Helpers/FixtureKind.cs b/src/Adapter/MSTestAdapter.PlatformServices/Helpers/FixtureKind.cs similarity index 100% rename from src/Adapter/MSTest.TestAdapter/Helpers/FixtureKind.cs rename to src/Adapter/MSTestAdapter.PlatformServices/Helpers/FixtureKind.cs diff --git a/src/Adapter/MSTest.TestAdapter/Helpers/FixtureMethodRunner.cs b/src/Adapter/MSTestAdapter.PlatformServices/Helpers/FixtureMethodRunner.cs similarity index 99% rename from src/Adapter/MSTest.TestAdapter/Helpers/FixtureMethodRunner.cs rename to src/Adapter/MSTestAdapter.PlatformServices/Helpers/FixtureMethodRunner.cs index 6653057879..69551cc173 100644 --- a/src/Adapter/MSTest.TestAdapter/Helpers/FixtureMethodRunner.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Helpers/FixtureMethodRunner.cs @@ -2,7 +2,6 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution; -using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Extensions; using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel; using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Extensions; diff --git a/src/Adapter/MSTest.TestAdapter/Helpers/IEnvironment.cs b/src/Adapter/MSTestAdapter.PlatformServices/Helpers/IEnvironment.cs similarity index 100% rename from src/Adapter/MSTest.TestAdapter/Helpers/IEnvironment.cs rename to src/Adapter/MSTestAdapter.PlatformServices/Helpers/IEnvironment.cs diff --git a/src/Adapter/MSTest.TestAdapter/Helpers/MSTestDiscovererHelpers.cs b/src/Adapter/MSTestAdapter.PlatformServices/Helpers/MSTestDiscovererHelpers.cs similarity index 96% rename from src/Adapter/MSTest.TestAdapter/Helpers/MSTestDiscovererHelpers.cs rename to src/Adapter/MSTestAdapter.PlatformServices/Helpers/MSTestDiscovererHelpers.cs index 3b76323e58..1a5b5ef336 100644 --- a/src/Adapter/MSTest.TestAdapter/Helpers/MSTestDiscovererHelpers.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Helpers/MSTestDiscovererHelpers.cs @@ -2,6 +2,7 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel; +using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Interface; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging; diff --git a/src/Adapter/MSTest.TestAdapter/Helpers/ReflectHelper.cs b/src/Adapter/MSTestAdapter.PlatformServices/Helpers/ReflectHelper.cs similarity index 99% rename from src/Adapter/MSTest.TestAdapter/Helpers/ReflectHelper.cs rename to src/Adapter/MSTestAdapter.PlatformServices/Helpers/ReflectHelper.cs index 40f114585f..861c8ca0d1 100644 --- a/src/Adapter/MSTest.TestAdapter/Helpers/ReflectHelper.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Helpers/ReflectHelper.cs @@ -4,6 +4,7 @@ using System.Security; using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution; +using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; using Microsoft.VisualStudio.TestPlatform.ObjectModel; using Microsoft.VisualStudio.TestTools.UnitTesting; diff --git a/src/Adapter/MSTest.TestAdapter/Helpers/RunSettingsUtilities.cs b/src/Adapter/MSTestAdapter.PlatformServices/Helpers/RunSettingsUtilities.cs similarity index 97% rename from src/Adapter/MSTest.TestAdapter/Helpers/RunSettingsUtilities.cs rename to src/Adapter/MSTestAdapter.PlatformServices/Helpers/RunSettingsUtilities.cs index e4a457b0cc..fa73447efd 100644 --- a/src/Adapter/MSTest.TestAdapter/Helpers/RunSettingsUtilities.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Helpers/RunSettingsUtilities.cs @@ -1,6 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; using Microsoft.VisualStudio.TestPlatform.ObjectModel; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Utilities; using Microsoft.VisualStudio.TestTools.UnitTesting; diff --git a/src/Adapter/MSTest.TestAdapter/Helpers/RuntimeContext.cs b/src/Adapter/MSTestAdapter.PlatformServices/Helpers/RuntimeContext.cs similarity index 100% rename from src/Adapter/MSTest.TestAdapter/Helpers/RuntimeContext.cs rename to src/Adapter/MSTestAdapter.PlatformServices/Helpers/RuntimeContext.cs diff --git a/src/Adapter/MSTest.TestAdapter/Helpers/TestDataSourceHelpers.cs b/src/Adapter/MSTestAdapter.PlatformServices/Helpers/TestDataSourceHelpers.cs similarity index 100% rename from src/Adapter/MSTest.TestAdapter/Helpers/TestDataSourceHelpers.cs rename to src/Adapter/MSTestAdapter.PlatformServices/Helpers/TestDataSourceHelpers.cs diff --git a/src/Adapter/MSTest.TestAdapter/Helpers/TestRunParameters.cs b/src/Adapter/MSTestAdapter.PlatformServices/Helpers/TestRunParameters.cs similarity index 96% rename from src/Adapter/MSTest.TestAdapter/Helpers/TestRunParameters.cs rename to src/Adapter/MSTestAdapter.PlatformServices/Helpers/TestRunParameters.cs index 9a324be172..8cd4b81655 100644 --- a/src/Adapter/MSTest.TestAdapter/Helpers/TestRunParameters.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Helpers/TestRunParameters.cs @@ -1,6 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; using Microsoft.VisualStudio.TestPlatform.ObjectModel; namespace Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Helpers; diff --git a/src/Adapter/MSTest.TestAdapter/Helpers/UnitTestOutcomeHelper.cs b/src/Adapter/MSTestAdapter.PlatformServices/Helpers/UnitTestOutcomeHelper.cs similarity index 100% rename from src/Adapter/MSTest.TestAdapter/Helpers/UnitTestOutcomeHelper.cs rename to src/Adapter/MSTestAdapter.PlatformServices/Helpers/UnitTestOutcomeHelper.cs diff --git a/src/Adapter/MSTest.TestAdapter/IPlatformServiceProvider.cs b/src/Adapter/MSTestAdapter.PlatformServices/IPlatformServiceProvider.cs similarity index 100% rename from src/Adapter/MSTest.TestAdapter/IPlatformServiceProvider.cs rename to src/Adapter/MSTestAdapter.PlatformServices/IPlatformServiceProvider.cs diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Interfaces/IAdapterTraceLogger.cs b/src/Adapter/MSTestAdapter.PlatformServices/Interfaces/IAdapterTraceLogger.cs index 14d14d6337..b751ea57bd 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Interfaces/IAdapterTraceLogger.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Interfaces/IAdapterTraceLogger.cs @@ -9,9 +9,9 @@ namespace Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Int /// A service to log any trace messages from the adapter that would be shown in *.TpTrace files. /// #if NET6_0_OR_GREATER -[Obsolete(Constants.PublicTypeObsoleteMessage, DiagnosticId = "MSTESTOBS")] +[Obsolete(TestTools.UnitTesting.FrameworkConstants.PublicTypeObsoleteMessage, DiagnosticId = "MSTESTOBS")] #else -[Obsolete(Constants.PublicTypeObsoleteMessage)] +[Obsolete(TestTools.UnitTesting.FrameworkConstants.PublicTypeObsoleteMessage)] #endif public interface IAdapterTraceLogger { diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Interfaces/IFileOperations.cs b/src/Adapter/MSTestAdapter.PlatformServices/Interfaces/IFileOperations.cs index b4b2c6b52d..ba498a72ba 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Interfaces/IFileOperations.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Interfaces/IFileOperations.cs @@ -7,9 +7,9 @@ namespace Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Int /// This service is responsible for any file based operations. /// #if NET6_0_OR_GREATER -[Obsolete(Constants.PublicTypeObsoleteMessage, DiagnosticId = "MSTESTOBS")] +[Obsolete(TestTools.UnitTesting.FrameworkConstants.PublicTypeObsoleteMessage, DiagnosticId = "MSTESTOBS")] #else -[Obsolete(Constants.PublicTypeObsoleteMessage)] +[Obsolete(TestTools.UnitTesting.FrameworkConstants.PublicTypeObsoleteMessage)] #endif public interface IFileOperations { diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Interfaces/IReflectionOperations.cs b/src/Adapter/MSTestAdapter.PlatformServices/Interfaces/IReflectionOperations.cs index 7a0c28d00e..e228b5ffae 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Interfaces/IReflectionOperations.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Interfaces/IReflectionOperations.cs @@ -7,9 +7,9 @@ namespace Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Int /// This service is responsible for platform specific reflection operations. /// #if NET6_0_OR_GREATER -[Obsolete(Constants.PublicTypeObsoleteMessage, DiagnosticId = "MSTESTOBS")] +[Obsolete(TestTools.UnitTesting.FrameworkConstants.PublicTypeObsoleteMessage, DiagnosticId = "MSTESTOBS")] #else -[Obsolete(Constants.PublicTypeObsoleteMessage)] +[Obsolete(TestTools.UnitTesting.FrameworkConstants.PublicTypeObsoleteMessage)] #endif public interface IReflectionOperations { diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Interfaces/ISettingsProvider.cs b/src/Adapter/MSTestAdapter.PlatformServices/Interfaces/ISettingsProvider.cs index eee9c84973..10a6767f95 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Interfaces/ISettingsProvider.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Interfaces/ISettingsProvider.cs @@ -7,9 +7,9 @@ namespace Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Int /// To read settings from the runsettings xml for the corresponding platform service. /// #if NET6_0_OR_GREATER -[Obsolete(Constants.PublicTypeObsoleteMessage, DiagnosticId = "MSTESTOBS")] +[Obsolete(TestTools.UnitTesting.FrameworkConstants.PublicTypeObsoleteMessage, DiagnosticId = "MSTESTOBS")] #else -[Obsolete(Constants.PublicTypeObsoleteMessage)] +[Obsolete(TestTools.UnitTesting.FrameworkConstants.PublicTypeObsoleteMessage)] #endif public interface ISettingsProvider { diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Interfaces/ITestDeployment.cs b/src/Adapter/MSTestAdapter.PlatformServices/Interfaces/ITestDeployment.cs index d7c914e5dd..4af0d5407f 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Interfaces/ITestDeployment.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Interfaces/ITestDeployment.cs @@ -3,6 +3,7 @@ using Microsoft.VisualStudio.TestPlatform.ObjectModel; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter; +using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Interface; @@ -10,9 +11,9 @@ namespace Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Int /// The TestDeployment interface. /// #if NET6_0_OR_GREATER -[Obsolete(Constants.PublicTypeObsoleteMessage, DiagnosticId = "MSTESTOBS")] +[Obsolete(FrameworkConstants.PublicTypeObsoleteMessage, DiagnosticId = "MSTESTOBS")] #else -[Obsolete(Constants.PublicTypeObsoleteMessage)] +[Obsolete(FrameworkConstants.PublicTypeObsoleteMessage)] #endif public interface ITestDeployment { diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Interfaces/ITestSource.cs b/src/Adapter/MSTestAdapter.PlatformServices/Interfaces/ITestSource.cs index 04d3f8a063..98d497656c 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Interfaces/ITestSource.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Interfaces/ITestSource.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 Microsoft.VisualStudio.TestTools.UnitTesting; + namespace Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Interface; /// @@ -8,9 +10,9 @@ namespace Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Int /// the test sources provided to the adapter. /// #if NET6_0_OR_GREATER -[Obsolete(Constants.PublicTypeObsoleteMessage, DiagnosticId = "MSTESTOBS")] +[Obsolete(FrameworkConstants.PublicTypeObsoleteMessage, DiagnosticId = "MSTESTOBS")] #else -[Obsolete(Constants.PublicTypeObsoleteMessage)] +[Obsolete(FrameworkConstants.PublicTypeObsoleteMessage)] #endif public interface ITestSource { diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Interfaces/ITestSourceHost.cs b/src/Adapter/MSTestAdapter.PlatformServices/Interfaces/ITestSourceHost.cs index 403e6c2d2e..b82ce61587 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Interfaces/ITestSourceHost.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Interfaces/ITestSourceHost.cs @@ -7,9 +7,9 @@ namespace Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Int /// A host that loads the test source.This can be in isolation for desktop using an AppDomain or just loading the source in the current context. /// #if NET6_0_OR_GREATER -[Obsolete(Constants.PublicTypeObsoleteMessage, DiagnosticId = "MSTESTOBS")] +[Obsolete(TestTools.UnitTesting.FrameworkConstants.PublicTypeObsoleteMessage, DiagnosticId = "MSTESTOBS")] #else -[Obsolete(Constants.PublicTypeObsoleteMessage)] +[Obsolete(TestTools.UnitTesting.FrameworkConstants.PublicTypeObsoleteMessage)] #endif public interface ITestSourceHost : IDisposable { diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Interfaces/IThreadOperations.cs b/src/Adapter/MSTestAdapter.PlatformServices/Interfaces/IThreadOperations.cs index f03762ff1d..44856437e2 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Interfaces/IThreadOperations.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Interfaces/IThreadOperations.cs @@ -7,9 +7,9 @@ namespace Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Int /// This service is responsible for any thread operations specific to a platform. /// #if NET6_0_OR_GREATER -[Obsolete(Constants.PublicTypeObsoleteMessage, DiagnosticId = "MSTESTOBS")] +[Obsolete(TestTools.UnitTesting.FrameworkConstants.PublicTypeObsoleteMessage, DiagnosticId = "MSTESTOBS")] #else -[Obsolete(Constants.PublicTypeObsoleteMessage)] +[Obsolete(TestTools.UnitTesting.FrameworkConstants.PublicTypeObsoleteMessage)] #endif public interface IThreadOperations { diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Interfaces/ITraceListener.cs b/src/Adapter/MSTestAdapter.PlatformServices/Interfaces/ITraceListener.cs index 6bc98aaec5..d5cf7dea56 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Interfaces/ITraceListener.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Interfaces/ITraceListener.cs @@ -7,9 +7,9 @@ namespace Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Int /// Operations on the TraceListener object that is implemented differently for each platform. /// #if NET6_0_OR_GREATER -[Obsolete(Constants.PublicTypeObsoleteMessage, DiagnosticId = "MSTESTOBS")] +[Obsolete(Microsoft.VisualStudio.TestTools.UnitTesting.FrameworkConstants.PublicTypeObsoleteMessage, DiagnosticId = "MSTESTOBS")] #else -[Obsolete(Constants.PublicTypeObsoleteMessage)] +[Obsolete(Microsoft.VisualStudio.TestTools.UnitTesting.FrameworkConstants.PublicTypeObsoleteMessage)] #endif public interface ITraceListener { diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Interfaces/ITraceListenerManager.cs b/src/Adapter/MSTestAdapter.PlatformServices/Interfaces/ITraceListenerManager.cs index 9dbe78d52e..22a133d415 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Interfaces/ITraceListenerManager.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Interfaces/ITraceListenerManager.cs @@ -8,9 +8,9 @@ namespace Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Int /// These operations are implemented differently for each platform service. /// #if NET6_0_OR_GREATER -[Obsolete(Constants.PublicTypeObsoleteMessage, DiagnosticId = "MSTESTOBS")] +[Obsolete(TestTools.UnitTesting.FrameworkConstants.PublicTypeObsoleteMessage, DiagnosticId = "MSTESTOBS")] #else -[Obsolete(Constants.PublicTypeObsoleteMessage)] +[Obsolete(TestTools.UnitTesting.FrameworkConstants.PublicTypeObsoleteMessage)] #endif public interface ITraceListenerManager { diff --git a/src/Adapter/MSTestAdapter.PlatformServices/MSTestAdapter.PlatformServices.csproj b/src/Adapter/MSTestAdapter.PlatformServices/MSTestAdapter.PlatformServices.csproj index bc76142b55..6d3a74107d 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/MSTestAdapter.PlatformServices.csproj +++ b/src/Adapter/MSTestAdapter.PlatformServices/MSTestAdapter.PlatformServices.csproj @@ -40,19 +40,16 @@ + - - - true - - + diff --git a/src/Adapter/MSTest.TestAdapter/MSTestSettings.cs b/src/Adapter/MSTestAdapter.PlatformServices/MSTestSettings.cs similarity index 98% rename from src/Adapter/MSTest.TestAdapter/MSTestSettings.cs rename to src/Adapter/MSTestAdapter.PlatformServices/MSTestSettings.cs index 65381bcc72..3e43158323 100644 --- a/src/Adapter/MSTest.TestAdapter/MSTestSettings.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/MSTestSettings.cs @@ -2,15 +2,15 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel; -using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Interface; -#if !WINDOWS_UWP using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; -#endif +using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Interface; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Utilities; using Microsoft.VisualStudio.TestTools.UnitTesting; +using ExecutionScope = Microsoft.VisualStudio.TestTools.UnitTesting.ExecutionScope; + namespace Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter; /// @@ -18,9 +18,9 @@ namespace Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter; /// [Serializable] #if NET6_0_OR_GREATER -[Obsolete(Constants.PublicTypeObsoleteMessage, DiagnosticId = "MSTESTOBS")] +[Obsolete(FrameworkConstants.PublicTypeObsoleteMessage, DiagnosticId = "MSTESTOBS")] #else -[Obsolete(Constants.PublicTypeObsoleteMessage)] +[Obsolete(FrameworkConstants.PublicTypeObsoleteMessage)] #endif public class MSTestSettings { @@ -833,8 +833,8 @@ private static void SetParallelSettings(XmlReader reader, MSTestSettings setting string.Format( CultureInfo.CurrentCulture, Resource.InvalidSettingsXmlElement, - ParallelizeSettingsName, - reader.Name)); + reader.Name, + ParallelizeSettingsName)); } } } @@ -992,9 +992,9 @@ internal static void SetSettingsFromConfig(IConfiguration configuration, IMessag : parallelWorkers > 0 ? parallelWorkers : throw new AdapterSettingsException(string.Format( - CultureInfo.CurrentCulture, - Resource.InvalidParallelWorkersValue, - workers)) + CultureInfo.CurrentCulture, + Resource.InvalidParallelWorkersValue, + workers)) : throw new AdapterSettingsException(string.Format( CultureInfo.CurrentCulture, Resource.InvalidParallelWorkersValue, diff --git a/src/Adapter/MSTest.TestAdapter/ObjectModel/AdapterSettingsException.cs b/src/Adapter/MSTestAdapter.PlatformServices/ObjectModel/AdapterSettingsException.cs similarity index 100% rename from src/Adapter/MSTest.TestAdapter/ObjectModel/AdapterSettingsException.cs rename to src/Adapter/MSTestAdapter.PlatformServices/ObjectModel/AdapterSettingsException.cs diff --git a/src/Adapter/MSTest.TestAdapter/ObjectModel/DynamicDataType.cs b/src/Adapter/MSTestAdapter.PlatformServices/ObjectModel/DynamicDataType.cs similarity index 100% rename from src/Adapter/MSTest.TestAdapter/ObjectModel/DynamicDataType.cs rename to src/Adapter/MSTestAdapter.PlatformServices/ObjectModel/DynamicDataType.cs diff --git a/src/Adapter/MSTest.TestAdapter/ObjectModel/FixtureTestResult.cs b/src/Adapter/MSTestAdapter.PlatformServices/ObjectModel/FixtureTestResult.cs similarity index 100% rename from src/Adapter/MSTest.TestAdapter/ObjectModel/FixtureTestResult.cs rename to src/Adapter/MSTestAdapter.PlatformServices/ObjectModel/FixtureTestResult.cs diff --git a/src/Adapter/MSTest.TestAdapter/ObjectModel/StackTraceInformation.cs b/src/Adapter/MSTestAdapter.PlatformServices/ObjectModel/StackTraceInformation.cs similarity index 100% rename from src/Adapter/MSTest.TestAdapter/ObjectModel/StackTraceInformation.cs rename to src/Adapter/MSTestAdapter.PlatformServices/ObjectModel/StackTraceInformation.cs diff --git a/src/Adapter/MSTest.TestAdapter/ObjectModel/TestAssemblySettings.cs b/src/Adapter/MSTestAdapter.PlatformServices/ObjectModel/TestAssemblySettings.cs similarity index 92% rename from src/Adapter/MSTest.TestAdapter/ObjectModel/TestAssemblySettings.cs rename to src/Adapter/MSTestAdapter.PlatformServices/ObjectModel/TestAssemblySettings.cs index 5e9a68270d..8854d53de3 100644 --- a/src/Adapter/MSTest.TestAdapter/ObjectModel/TestAssemblySettings.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/ObjectModel/TestAssemblySettings.cs @@ -3,6 +3,8 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; +using ExecutionScope = Microsoft.VisualStudio.TestTools.UnitTesting.ExecutionScope; + namespace Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel; [Serializable] diff --git a/src/Adapter/MSTest.TestAdapter/ObjectModel/TestFailedException.cs b/src/Adapter/MSTestAdapter.PlatformServices/ObjectModel/TestFailedException.cs similarity index 100% rename from src/Adapter/MSTest.TestAdapter/ObjectModel/TestFailedException.cs rename to src/Adapter/MSTestAdapter.PlatformServices/ObjectModel/TestFailedException.cs diff --git a/src/Adapter/MSTest.TestAdapter/ObjectModel/TestMethod.cs b/src/Adapter/MSTestAdapter.PlatformServices/ObjectModel/TestMethod.cs similarity index 97% rename from src/Adapter/MSTest.TestAdapter/ObjectModel/TestMethod.cs rename to src/Adapter/MSTestAdapter.PlatformServices/ObjectModel/TestMethod.cs index 2bb1e1a1b6..3b821899ed 100644 --- a/src/Adapter/MSTest.TestAdapter/ObjectModel/TestMethod.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/ObjectModel/TestMethod.cs @@ -16,9 +16,9 @@ namespace Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel; /// TestMethod contains information about a unit test method that needs to be executed. /// #if NET6_0_OR_GREATER -[Obsolete(Constants.PublicTypeObsoleteMessage, DiagnosticId = "MSTESTOBS")] +[Obsolete(FrameworkConstants.PublicTypeObsoleteMessage, DiagnosticId = "MSTESTOBS")] #else -[Obsolete(Constants.PublicTypeObsoleteMessage)] +[Obsolete(FrameworkConstants.PublicTypeObsoleteMessage)] #endif [Serializable] public sealed class TestMethod : ITestMethod diff --git a/src/Adapter/MSTest.TestAdapter/ObjectModel/TypeInspectionException.cs b/src/Adapter/MSTestAdapter.PlatformServices/ObjectModel/TypeInspectionException.cs similarity index 100% rename from src/Adapter/MSTest.TestAdapter/ObjectModel/TypeInspectionException.cs rename to src/Adapter/MSTestAdapter.PlatformServices/ObjectModel/TypeInspectionException.cs diff --git a/src/Adapter/MSTest.TestAdapter/ObjectModel/UnitTestElement.cs b/src/Adapter/MSTestAdapter.PlatformServices/ObjectModel/UnitTestElement.cs similarity index 85% rename from src/Adapter/MSTest.TestAdapter/ObjectModel/UnitTestElement.cs rename to src/Adapter/MSTestAdapter.PlatformServices/ObjectModel/UnitTestElement.cs index 5d5055f537..ea8e011ae4 100644 --- a/src/Adapter/MSTest.TestAdapter/ObjectModel/UnitTestElement.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/ObjectModel/UnitTestElement.cs @@ -3,6 +3,7 @@ using Microsoft.TestPlatform.AdapterUtilities; using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Extensions; +using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; using Microsoft.VisualStudio.TestPlatform.ObjectModel; using Microsoft.VisualStudio.TestTools.UnitTesting; @@ -107,7 +108,7 @@ internal TestCase ToTestCase() // : string.Format(CultureInfo.InvariantCulture, "{0}.{1}", this.TestMethod.FullClassName, this.TestMethod.Name); string testFullName = string.Format(CultureInfo.InvariantCulture, "{0}.{1}", TestMethod.FullClassName, TestMethod.Name); - TestCase testCase = new(testFullName, Constants.ExecutorUri, TestMethod.AssemblyName) + TestCase testCase = new(testFullName, EngineConstants.ExecutorUri, TestMethod.AssemblyName) { DisplayName = GetDisplayName(), }; @@ -116,11 +117,11 @@ internal TestCase ToTestCase() { testCase.SetPropertyValue(TestCaseExtensions.ManagedTypeProperty, TestMethod.ManagedTypeName); testCase.SetPropertyValue(TestCaseExtensions.ManagedMethodProperty, TestMethod.ManagedMethodName); - testCase.SetPropertyValue(Constants.TestClassNameProperty, TestMethod.ManagedTypeName); + testCase.SetPropertyValue(EngineConstants.TestClassNameProperty, TestMethod.ManagedTypeName); } else { - testCase.SetPropertyValue(Constants.TestClassNameProperty, TestMethod.FullClassName); + testCase.SetPropertyValue(EngineConstants.TestClassNameProperty, TestMethod.FullClassName); } IReadOnlyCollection hierarchy = TestMethod.Hierarchy; @@ -132,19 +133,19 @@ internal TestCase ToTestCase() // Set declaring type if present so the correct method info can be retrieved if (TestMethod.DeclaringClassFullName != null) { - testCase.SetPropertyValue(Constants.DeclaringClassNameProperty, TestMethod.DeclaringClassFullName); + testCase.SetPropertyValue(EngineConstants.DeclaringClassNameProperty, TestMethod.DeclaringClassFullName); } // Set only if some test category is present if (TestCategory is { Length: > 0 }) { - testCase.SetPropertyValue(Constants.TestCategoryProperty, TestCategory); + testCase.SetPropertyValue(EngineConstants.TestCategoryProperty, TestCategory); } // Set priority if present if (Priority != null) { - testCase.SetPropertyValue(Constants.PriorityProperty, Priority.Value); + testCase.SetPropertyValue(EngineConstants.PriorityProperty, Priority.Value); } if (Traits is { Length: > 0 }) @@ -154,34 +155,34 @@ internal TestCase ToTestCase() if (!StringEx.IsNullOrEmpty(CssIteration)) { - testCase.SetPropertyValue(Constants.CssIterationProperty, CssIteration); + testCase.SetPropertyValue(EngineConstants.CssIterationProperty, CssIteration); } if (!StringEx.IsNullOrEmpty(CssProjectStructure)) { - testCase.SetPropertyValue(Constants.CssProjectStructureProperty, CssProjectStructure); + testCase.SetPropertyValue(EngineConstants.CssProjectStructureProperty, CssProjectStructure); } if (!StringEx.IsNullOrEmpty(Description)) { - testCase.SetPropertyValue(Constants.DescriptionProperty, Description); + testCase.SetPropertyValue(EngineConstants.DescriptionProperty, Description); } if (WorkItemIds != null) { - testCase.SetPropertyValue(Constants.WorkItemIdsProperty, WorkItemIds); + testCase.SetPropertyValue(EngineConstants.WorkItemIdsProperty, WorkItemIds); } // The list of items to deploy before running this test. if (DeploymentItems is { Length: > 0 }) { - testCase.SetPropertyValue(Constants.DeploymentItemsProperty, DeploymentItems); + testCase.SetPropertyValue(EngineConstants.DeploymentItemsProperty, DeploymentItems); } // Set the Do not parallelize state if present if (DoNotParallelize) { - testCase.SetPropertyValue(Constants.DoNotParallelizeProperty, DoNotParallelize); + testCase.SetPropertyValue(EngineConstants.DoNotParallelizeProperty, DoNotParallelize); } // Store resolved data if any @@ -189,12 +190,12 @@ internal TestCase ToTestCase() { string?[]? data = TestMethod.SerializedData; - testCase.SetPropertyValue(Constants.TestDynamicDataTypeProperty, (int)TestMethod.DataType); - testCase.SetPropertyValue(Constants.TestDynamicDataProperty, data); + testCase.SetPropertyValue(EngineConstants.TestDynamicDataTypeProperty, (int)TestMethod.DataType); + testCase.SetPropertyValue(EngineConstants.TestDynamicDataProperty, data); // VSTest serialization doesn't handle null so instead don't set the property so that it's deserialized as null if (TestMethod.TestDataSourceIgnoreMessage is not null) { - testCase.SetPropertyValue(Constants.TestDataSourceIgnoreMessageProperty, TestMethod.TestDataSourceIgnoreMessage); + testCase.SetPropertyValue(EngineConstants.TestDataSourceIgnoreMessageProperty, TestMethod.TestDataSourceIgnoreMessage); } } @@ -205,7 +206,7 @@ internal TestCase ToTestCase() private void SetTestCaseId(TestCase testCase, string testFullName) { - testCase.SetPropertyValue(Constants.TestIdGenerationStrategyProperty, (int)TestMethod.TestIdGenerationStrategy); + testCase.SetPropertyValue(EngineConstants.TestIdGenerationStrategyProperty, (int)TestMethod.TestIdGenerationStrategy); switch (TestMethod.TestIdGenerationStrategy) { @@ -277,7 +278,7 @@ private Guid GenerateSerializedDataStrategyTestId(string testFullName) { var idProvider = new TestIdProvider(); - idProvider.AppendString(Constants.ExecutorUriString); + idProvider.AppendString(EngineConstants.ExecutorUriString); // Below comment is copied over from Test Platform. // If source is a file name then just use the filename for the identifier since the file might have moved between diff --git a/src/Adapter/MSTest.TestAdapter/ObjectModel/UnitTestOutcome.cs b/src/Adapter/MSTestAdapter.PlatformServices/ObjectModel/UnitTestOutcome.cs similarity index 89% rename from src/Adapter/MSTest.TestAdapter/ObjectModel/UnitTestOutcome.cs rename to src/Adapter/MSTestAdapter.PlatformServices/ObjectModel/UnitTestOutcome.cs index a519c454eb..4b8eaddc68 100644 --- a/src/Adapter/MSTest.TestAdapter/ObjectModel/UnitTestOutcome.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/ObjectModel/UnitTestOutcome.cs @@ -7,9 +7,9 @@ namespace Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel; /// Outcome of a test. /// #if NET6_0_OR_GREATER -[Obsolete(Constants.PublicTypeObsoleteMessage, DiagnosticId = "MSTESTOBS")] +[Obsolete(TestTools.UnitTesting.FrameworkConstants.PublicTypeObsoleteMessage, DiagnosticId = "MSTESTOBS")] #else -[Obsolete(Constants.PublicTypeObsoleteMessage)] +[Obsolete(TestTools.UnitTesting.FrameworkConstants.PublicTypeObsoleteMessage)] #endif public enum UnitTestOutcome : int { diff --git a/src/Adapter/MSTest.TestAdapter/ObjectModel/UnitTestResult.cs b/src/Adapter/MSTestAdapter.PlatformServices/ObjectModel/UnitTestResult.cs similarity index 96% rename from src/Adapter/MSTest.TestAdapter/ObjectModel/UnitTestResult.cs rename to src/Adapter/MSTestAdapter.PlatformServices/ObjectModel/UnitTestResult.cs index c317fa9dde..251e6df0e9 100644 --- a/src/Adapter/MSTest.TestAdapter/ObjectModel/UnitTestResult.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/ObjectModel/UnitTestResult.cs @@ -11,9 +11,9 @@ namespace Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel; [Serializable] [DebuggerDisplay("{DisplayName} ({Outcome})")] #if NET6_0_OR_GREATER -[Obsolete(Constants.PublicTypeObsoleteMessage, DiagnosticId = "MSTESTOBS")] +[Obsolete(TestTools.UnitTesting.FrameworkConstants.PublicTypeObsoleteMessage, DiagnosticId = "MSTESTOBS")] #else -[Obsolete(Constants.PublicTypeObsoleteMessage)] +[Obsolete(TestTools.UnitTesting.FrameworkConstants.PublicTypeObsoleteMessage)] #endif public class UnitTestResult { diff --git a/src/Adapter/MSTest.TestAdapter/PlatformServiceProvider.cs b/src/Adapter/MSTestAdapter.PlatformServices/PlatformServiceProvider.cs similarity index 100% rename from src/Adapter/MSTest.TestAdapter/PlatformServiceProvider.cs rename to src/Adapter/MSTestAdapter.PlatformServices/PlatformServiceProvider.cs diff --git a/src/Adapter/MSTestAdapter.PlatformServices/PublicAPI/PublicAPI.Shipped.txt b/src/Adapter/MSTestAdapter.PlatformServices/PublicAPI/PublicAPI.Shipped.txt index f7f5bbea05..feb5effa2e 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/PublicAPI/PublicAPI.Shipped.txt +++ b/src/Adapter/MSTestAdapter.PlatformServices/PublicAPI/PublicAPI.Shipped.txt @@ -1,4 +1,132 @@ #nullable enable +const Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestMethodInfo.TimeoutWhenNotSet = 0 -> int +const Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.MSTestSettings.SettingsName = "MSTest" -> string! +const Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.MSTestSettings.SettingsNameAlias = "MSTestV2" -> string! +const Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.TestMethod.TotalHierarchyLevels = 4 -> int +const Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.RunConfigurationSettings.SettingsName = "RunConfiguration" -> string! +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.LogMessageListener +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.LogMessageListener.DebugTrace.get -> string? +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.LogMessageListener.Dispose() -> void +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.LogMessageListener.GetAndClearDebugTrace() -> string? +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.LogMessageListener.GetAndClearStandardError() -> string? +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.LogMessageListener.GetAndClearStandardOutput() -> string? +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.LogMessageListener.LogMessageListener(bool captureDebugTraces) -> void +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.LogMessageListener.StandardError.get -> string! +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.LogMessageListener.StandardOutput.get -> string! +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestAssemblyInfo +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestAssemblyInfo.AssemblyCleanupMethod.get -> System.Reflection.MethodInfo? +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestAssemblyInfo.AssemblyInitializationException.get -> System.Exception? +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestAssemblyInfo.AssemblyInitializeMethod.get -> System.Reflection.MethodInfo? +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestAssemblyInfo.HasExecutableCleanupMethod.get -> bool +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestAssemblyInfo.IsAssemblyInitializeExecuted.get -> bool +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestAssemblyInfo.RunAssemblyCleanup() -> string? +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestAssemblyInfo.RunAssemblyInitialize(Microsoft.VisualStudio.TestTools.UnitTesting.TestContext! testContext) -> void +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestClassInfo +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestClassInfo.BaseClassCleanupMethodsStack.get -> System.Collections.Generic.Stack! +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestClassInfo.BaseClassInitAndCleanupMethods.get -> System.Collections.Generic.Queue!>! +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestClassInfo.BaseTestCleanupMethodsQueue.get -> System.Collections.Generic.Queue! +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestClassInfo.BaseTestInitializeMethodsQueue.get -> System.Collections.Generic.Queue! +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestClassInfo.ClassAttribute.get -> Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute! +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestClassInfo.ClassCleanupException.get -> System.Exception? +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestClassInfo.ClassCleanupMethod.get -> System.Reflection.MethodInfo? +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestClassInfo.ClassInitializationException.get -> System.Exception? +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestClassInfo.ClassInitializeMethod.get -> System.Reflection.MethodInfo? +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestClassInfo.ClassType.get -> System.Type! +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestClassInfo.Constructor.get -> System.Reflection.ConstructorInfo! +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestClassInfo.HasExecutableCleanupMethod.get -> bool +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestClassInfo.IsClassCleanupExecuted.get -> bool +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestClassInfo.IsClassInitializeExecuted.get -> bool +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestClassInfo.Parent.get -> Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestAssemblyInfo! +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestClassInfo.RunClassCleanup(Microsoft.VisualStudio.TestTools.UnitTesting.ClassCleanupBehavior classCleanupLifecycle = Microsoft.VisualStudio.TestTools.UnitTesting.ClassCleanupBehavior.EndOfAssembly) -> string? +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestClassInfo.RunClassInitialize(Microsoft.VisualStudio.TestTools.UnitTesting.TestContext! testContext) -> void +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestClassInfo.TestCleanupMethod.get -> System.Reflection.MethodInfo? +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestClassInfo.TestContextProperty.get -> System.Reflection.PropertyInfo? +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestClassInfo.TestInitializeMethod.get -> System.Reflection.MethodInfo? +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestExecutionManager +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestExecutionManager.RunTests(System.Collections.Generic.IEnumerable! tests, Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter.IRunContext? runContext, Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter.IFrameworkHandle! frameworkHandle, Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.TestRunCancellationToken! runCancellationToken) -> void +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestExecutionManager.RunTests(System.Collections.Generic.IEnumerable! sources, Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter.IRunContext? runContext, Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter.IFrameworkHandle! frameworkHandle, Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.TestRunCancellationToken! cancellationToken) -> void +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestExecutionManager.TestExecutionManager() -> void +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestMethodInfo +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestMethodInfo.Arguments.get -> object?[]? +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestMethodInfo.GetAllAttributes(bool inherit) -> System.Attribute![]? +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestMethodInfo.GetAttributes(bool inherit) -> TAttributeType![]! +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestMethodInfo.IsRunnable.get -> bool +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestMethodInfo.IsTimeoutSet.get -> bool +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestMethodInfo.MethodInfo.get -> System.Reflection.MethodInfo! +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestMethodInfo.NotRunnableReason.get -> string? +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestMethodInfo.ParameterTypes.get -> System.Reflection.ParameterInfo![]! +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestMethodInfo.ReturnType.get -> System.Type! +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestMethodInfo.TestClassName.get -> string! +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestMethodInfo.TestMethodName.get -> string! +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Extensions.TestResultExtensions +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Extensions.UnitTestOutcomeExtensions +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.MSTestSettings +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.MSTestSettings.CaptureDebugTraces.get -> bool +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.MSTestSettings.ClassCleanupLifecycle.get -> Microsoft.VisualStudio.TestTools.UnitTesting.ClassCleanupBehavior? +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.MSTestSettings.DisableParallelization.get -> bool +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.MSTestSettings.EnableBaseClassTestMethodsFromOtherAssemblies.get -> bool +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.MSTestSettings.ForcedLegacyMode.get -> bool +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.MSTestSettings.MapInconclusiveToFailed.get -> bool +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.MSTestSettings.MapNotRunnableToFailed.get -> bool +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.MSTestSettings.MSTestSettings() -> void +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.MSTestSettings.ParallelizationScope.get -> Microsoft.VisualStudio.TestTools.UnitTesting.ExecutionScope? +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.MSTestSettings.ParallelizationWorkers.get -> int? +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.MSTestSettings.TestSettingsFile.get -> string? +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.MSTestSettings.TestTimeout.get -> int +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.MSTestSettings.TreatClassAndAssemblyCleanupWarningsAsErrors.get -> bool +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.MSTestSettings.TreatDiscoveryWarningsAsErrors.get -> bool +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.TestMethod +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.TestMethod.AssemblyName.get -> string! +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.TestMethod.DeclaringAssemblyName.get -> string? +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.TestMethod.DeclaringAssemblyName.set -> void +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.TestMethod.DeclaringClassFullName.get -> string? +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.TestMethod.DeclaringClassFullName.set -> void +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.TestMethod.FullClassName.get -> string! +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.TestMethod.HasManagedMethodAndTypeProperties.get -> bool +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.TestMethod.Hierarchy.get -> System.Collections.Generic.IReadOnlyCollection! +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.TestMethod.IsAsync.get -> bool +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.TestMethod.ManagedMethodName.get -> string? +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.TestMethod.ManagedTypeName.get -> string? +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.TestMethod.Name.get -> string! +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.TestMethod.TestIdGenerationStrategy.get -> Microsoft.VisualStudio.TestTools.UnitTesting.TestIdGenerationStrategy +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.TestMethod.TestMethod(string! name, string! fullClassName, string! assemblyName, bool isAsync) -> void +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestOutcome +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestOutcome.Error = 0 -> Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestOutcome +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestOutcome.Failed = 1 -> Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestOutcome +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestOutcome.Ignored = 4 -> Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestOutcome +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestOutcome.Inconclusive = 3 -> Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestOutcome +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestOutcome.InProgress = 8 -> Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestOutcome +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestOutcome.NotFound = 7 -> Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestOutcome +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestOutcome.NotRunnable = 5 -> Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestOutcome +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestOutcome.Passed = 6 -> Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestOutcome +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestOutcome.Timeout = 2 -> Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestOutcome +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestResult +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestResult.DatarowIndex.get -> int +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestResult.DebugTrace.get -> string? +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestResult.DisplayName.get -> string? +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestResult.Duration.get -> System.TimeSpan +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestResult.ErrorColumnNumber.get -> int +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestResult.ErrorFilePath.get -> string? +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestResult.ErrorLineNumber.get -> int +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestResult.ErrorMessage.get -> string? +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestResult.ErrorStackTrace.get -> string? +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestResult.ExecutionId.get -> System.Guid +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestResult.InnerResultsCount.get -> int +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestResult.Outcome.get -> Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestOutcome +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestResult.ParentExecId.get -> System.Guid +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestResult.ResultFiles.get -> System.Collections.Generic.IList? +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestResult.StandardError.get -> string? +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestResult.StandardOut.get -> string? +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestResult.TestContextMessages.get -> string? +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.RunConfigurationSettings +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.RunConfigurationSettings.CollectSourceInformation.get -> bool +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.RunConfigurationSettings.RunConfigurationSettings() -> void +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.TestRunCancellationToken +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.TestRunCancellationToken.Cancel() -> void +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.TestRunCancellationToken.Canceled.get -> bool +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.TestRunCancellationToken.Register(System.Action! callback) -> void +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.TestRunCancellationToken.TestRunCancellationToken() -> void +Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.TestRunCancellationToken.Unregister() -> void Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.AdapterTraceLogger Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.AdapterTraceLogger.AdapterTraceLogger() -> void Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.AdapterTraceLogger.LogError(string! format, params object?[]! args) -> void @@ -150,3 +278,13 @@ override Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Thre override Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.ThreadSafeStringWriter.Write(char[]! buffer, int index, int count) -> void override Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.ThreadSafeStringWriter.Write(string? value) -> void override Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.ThreadSafeStringWriter.WriteLine(string? value) -> void +static Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Extensions.TestResultExtensions.ToUnitTestResults(this Microsoft.VisualStudio.TestTools.UnitTesting.TestResult![]! testResults) -> Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestResult![]! +static Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Extensions.UnitTestOutcomeExtensions.ToUnitTestOutcome(this Microsoft.VisualStudio.TestTools.UnitTesting.UnitTestOutcome frameworkTestOutcome) -> Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestOutcome +static Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.MSTestSettings.CurrentSettings.get -> Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.MSTestSettings! +static Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.MSTestSettings.IsLegacyScenario(Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging.IMessageLogger! logger) -> bool +static Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.MSTestSettings.PopulateSettings(Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.MSTestSettings! settings) -> void +static Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.MSTestSettings.PopulateSettings(Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter.IDiscoveryContext? context) -> void +static Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.MSTestSettings.RunConfigurationSettings.get -> Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.RunConfigurationSettings! +static Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.RunConfigurationSettings.PopulateSettings(Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter.IDiscoveryContext? context) -> Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.RunConfigurationSettings! +virtual Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestMethodInfo.Invoke(object?[]? arguments) -> Microsoft.VisualStudio.TestTools.UnitTesting.TestResult! +virtual Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestMethodInfo.InvokeAsync(object?[]? arguments) -> System.Threading.Tasks.Task! diff --git a/src/Adapter/MSTestAdapter.PlatformServices/RecursiveDirectoryPath.cs b/src/Adapter/MSTestAdapter.PlatformServices/RecursiveDirectoryPath.cs index c91bf7ed34..5593828ee9 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/RecursiveDirectoryPath.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/RecursiveDirectoryPath.cs @@ -20,9 +20,9 @@ namespace Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; /// [Serializable] #if NET6_0_OR_GREATER -[Obsolete(Constants.PublicTypeObsoleteMessage, DiagnosticId = "MSTESTOBS")] +[Obsolete(TestTools.UnitTesting.FrameworkConstants.PublicTypeObsoleteMessage, DiagnosticId = "MSTESTOBS")] #else -[Obsolete(Constants.PublicTypeObsoleteMessage)] +[Obsolete(TestTools.UnitTesting.FrameworkConstants.PublicTypeObsoleteMessage)] #endif [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1603:DocumentationMustContainValidXml", Justification = "Reviewed. Suppression is ok here.")] public class RecursiveDirectoryPath : MarshalByRefObject diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/Resource.Designer.cs b/src/Adapter/MSTestAdapter.PlatformServices/Resources/Resource.Designer.cs index 33f4d030e6..7a588aa40b 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/Resource.Designer.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/Resource.Designer.cs @@ -61,6 +61,87 @@ internal Resource() { } } + /// + /// Looks up a localized string similar to Assembly cleanup method '{0}.{1}' timed out after {2}ms. + /// + internal static string AssemblyCleanupTimedOut { + get { + return ResourceManager.GetString("AssemblyCleanupTimedOut", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Assembly cleanup method '{0}.{1}' was canceled. + /// + internal static string AssemblyCleanupWasCancelled { + get { + return ResourceManager.GetString("AssemblyCleanupWasCancelled", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Assembly initialize method '{0}.{1}' timed out after {2}ms. + /// + internal static string AssemblyInitializeTimedOut { + get { + return ResourceManager.GetString("AssemblyInitializeTimedOut", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Assembly initialize method '{0}.{1}' was canceled. + /// + internal static string AssemblyInitializeWasCancelled { + get { + return ResourceManager.GetString("AssemblyInitializeWasCancelled", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to MSTestAdapterV2. + /// + internal static string AttachmentSetDisplayName { + get { + return ResourceManager.GetString("AttachmentSetDisplayName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Exception occurred while enumerating IDataSource attribute on "{0}.{1}": {2}. + /// + internal static string CannotEnumerateIDataSourceAttribute { + get { + return ResourceManager.GetString("CannotEnumerateIDataSourceAttribute", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Exception occurred while expanding IDataSource rows from attribute on "{0}.{1}": {2}. + /// + internal static string CannotExpandIDataSourceAttribute { + get { + return ResourceManager.GetString("CannotExpandIDataSourceAttribute", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Data on index {0} for "{1}" cannot be serialized. All data provided through "IDataSource" should be serializable. If you need to test non-serializable data sources, please make sure you add "TestDataSourceDiscovery" attribute on your test assembly and set the discovery option to "DuringExecution".. + /// + internal static string CannotExpandIDataSourceAttribute_CannotSerialize { + get { + return ResourceManager.GetString("CannotExpandIDataSourceAttribute_CannotSerialize", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Display name "{2}" on indexes {0} and {1} are duplicate. Display names should be unique.. + /// + internal static string CannotExpandIDataSourceAttribute_DuplicateDisplayName { + get { + return ResourceManager.GetString("CannotExpandIDataSourceAttribute_DuplicateDisplayName", resourceCulture); + } + } + /// /// Looks up a localized string similar to Could not find file '{0}'.. /// @@ -70,6 +151,62 @@ internal static string CannotFindFile { } } + /// + /// Looks up a localized string similar to Cannot run test method '{0}.{1}': Test data doesn't match method parameters. Either the count or types are different. + ///Test expected {2} parameter(s), with types '{3}', + ///but received {4} argument(s), with types '{5}'.. + /// + internal static string CannotRunTestArgumentsMismatchError { + get { + return ResourceManager.GetString("CannotRunTestArgumentsMismatchError", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Cannot run test method '{0}.{1}': Method has parameters, but does not define any test source. Use '[DataRow]', '[DynamicData]', or a custom 'ITestDataSource' data source to provide test data.. + /// + internal static string CannotRunTestMethodNoDataError { + get { + return ResourceManager.GetString("CannotRunTestMethodNoDataError", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Class cleanup method '{0}.{1}' timed out after {2}ms. + /// + internal static string ClassCleanupTimedOut { + get { + return ResourceManager.GetString("ClassCleanupTimedOut", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Class cleanup method '{0}.{1}' was canceled. + /// + internal static string ClassCleanupWasCancelled { + get { + return ResourceManager.GetString("ClassCleanupWasCancelled", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Class initialize method '{0}.{1}' timed out after {2}ms. + /// + internal static string ClassInitializeTimedOut { + get { + return ResourceManager.GetString("ClassInitializeTimedOut", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Class initialize method '{0}.{1}' was canceled. + /// + internal static string ClassInitializeWasCancelled { + get { + return ResourceManager.GetString("ClassInitializeWasCancelled", resourceCulture); + } + } + /// /// Looks up a localized string similar to The parameter should not be null or empty.. /// @@ -79,6 +216,33 @@ internal static string Common_CannotBeNullOrEmpty { } } + /// + /// Looks up a localized string similar to MSTestAdapter failed to discover tests in class '{0}' of assembly '{1}' because {2}.. + /// + internal static string CouldNotInspectTypeDuringDiscovery { + get { + return ResourceManager.GetString("CouldNotInspectTypeDuringDiscovery", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {0} (Data Row {1}). + /// + internal static string DataDrivenResultDisplayName { + get { + return ResourceManager.GetString("DataDrivenResultDisplayName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Debug Trace:. + /// + internal static string DebugTraceBanner { + get { + return ResourceManager.GetString("DebugTraceBanner", resourceCulture); + } + } + /// /// Looks up a localized string similar to Test Run deployment issue: Bad deployment item: '{0}': output directory '{1}' specifies the item to be deployed outside deployment root directory which is not allowed.. /// @@ -196,6 +360,141 @@ internal static string DeploymentItemWithOutputDirectory { } } + /// + /// Looks up a localized string similar to [MSTest][Discovery][{0}] {1}. + /// + internal static string DiscoveryWarning { + get { + return ResourceManager.GetString("DiscoveryWarning", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Both '.runsettings' and '.testconfig.json' files have been detected. Please select only one of these test configuration files.. + /// + internal static string DuplicateConfigurationError { + get { + return ResourceManager.GetString("DuplicateConfigurationError", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {0}: {1}. + /// + internal static string EnumeratorLoadTypeErrorFormat { + get { + return ResourceManager.GetString("EnumeratorLoadTypeErrorFormat", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to "{0}": (Failed to get exception description due to an exception of type "{1}".. + /// + internal static string ExceptionOccuredWhileGettingTheExceptionDescription { + get { + return ResourceManager.GetString("ExceptionOccuredWhileGettingTheExceptionDescription", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Exceptions thrown:. + /// + internal static string ExceptionsThrown { + get { + return ResourceManager.GetString("ExceptionsThrown", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Test '{0}' was canceled. + /// + internal static string Execution_Test_Cancelled { + get { + return ResourceManager.GetString("Execution_Test_Cancelled", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Test '{0}' timed out after {1}ms. + /// + internal static string Execution_Test_Timeout { + get { + return ResourceManager.GetString("Execution_Test_Timeout", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Getting custom attributes for type {0} threw exception (will ignore and use the reflection way): {1}. + /// + internal static string FailedToGetCustomAttribute { + get { + return ResourceManager.GetString("FailedToGetCustomAttribute", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The type of the generic parameter '{0}' could not be inferred.. + /// + internal static string GenericParameterCantBeInferred { + get { + return ResourceManager.GetString("GenericParameterCantBeInferred", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The generic test method '{0}' doesn't have arguments, so the generic parameter cannot be inferred.. + /// + internal static string GenericParameterCantBeInferredBecauseNoArguments { + get { + return ResourceManager.GetString("GenericParameterCantBeInferredBecauseNoArguments", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Found two conflicting types for generic parameter '{0}'. The conflicting types are '{1}' and '{2}'.. + /// + internal static string GenericParameterConflict { + get { + return ResourceManager.GetString("GenericParameterConflict", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}.. + /// + internal static string InvalidClassCleanupLifecycleValue { + get { + return ResourceManager.GetString("InvalidClassCleanupLifecycleValue", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}.. + /// + internal static string InvalidParallelScopeValue { + get { + return ResourceManager.GetString("InvalidParallelScopeValue", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer.. + /// + internal static string InvalidParallelWorkersValue { + get { + return ResourceManager.GetString("InvalidParallelWorkersValue", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Invalid settings '{0}'. Unexpected XmlAttribute: '{1}'.. + /// + internal static string InvalidSettingsXmlAttribute { + get { + return ResourceManager.GetString("InvalidSettingsXmlAttribute", resourceCulture); + } + } + /// /// Looks up a localized string similar to MSTestAdapter encountered an unexpected element '{0}' in its settings '{1}'. Remove this element and try again.. /// @@ -205,6 +504,15 @@ internal static string InvalidSettingsXmlElement { } } + /// + /// Looks up a localized string similar to Invalid settings '{0}'. Unexpected XmlElement: '{1}'.. + /// + internal static string InvalidSettingsXmlElement1 { + get { + return ResourceManager.GetString("InvalidSettingsXmlElement1", resourceCulture); + } + } + /// /// Looks up a localized string similar to Invalid value '{0}' for runsettings entry '{1}', setting will be ignored.. /// @@ -214,6 +522,24 @@ internal static string InvalidValue { } } + /// + /// Looks up a localized string similar to Invalid value '{0}' for runsettings entry '{1}', setting will be ignored.. + /// + internal static string InvalidValue1 { + get { + return ResourceManager.GetString("InvalidValue1", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Warning : A testsettings file or a vsmdi file is not supported with the MSTest V2 Adapter.. + /// + internal static string LegacyScenariosNotSupportedWarning { + get { + return ResourceManager.GetString("LegacyScenariosNotSupportedWarning", resourceCulture); + } + } + /// /// Looks up a localized string similar to Test Run deployment issue: The assembly or module '{0}' was not found. Reason: {1}. /// @@ -233,29 +559,528 @@ internal static string MissingDeploymentDependencyWithoutReason { } /// - /// Looks up a localized string similar to {0}_{1} {2}. + /// Looks up a localized string similar to An older version of MSTestV2 package is loaded in assembly, test discovery might fail to discover all data tests if they depend on `.runsettings` file.. /// - internal static string TestRunName { + internal static string OlderTFMVersionFound { get { - return ResourceManager.GetString("TestRunName", resourceCulture); + return ResourceManager.GetString("OlderTFMVersionFound", resourceCulture); } } /// - /// Looks up a localized string similar to Data source '{0}' cannot be found in the test configuration settings. + /// Looks up a localized string similar to Running tests in any of the provided sources is not supported for the selected platform. /// - internal static string UTA_DataSourceConfigurationSectionMissing { + internal static string SourcesNotSupported { get { - return ResourceManager.GetString("UTA_DataSourceConfigurationSectionMissing", resourceCulture); + return ResourceManager.GetString("SourcesNotSupported", resourceCulture); } } /// - /// Looks up a localized string similar to The unit test adapter failed to connect to the data source or to read the data. For more information on troubleshooting this error, see "Troubleshooting Data-Driven Unit Tests" (http://go.microsoft.com/fwlink/?LinkId=62412) in the MSDN Library. Error details: {0}. + /// Looks up a localized string similar to Runsettings entry '<ExecutionApartmentState>STA</ExecutionApartmentState>' is not supported on non-Windows OSes.. /// - internal static string UTA_ErrorDataConnectionFailed { + internal static string STAIsOnlySupportedOnWindowsWarning { get { - return ResourceManager.GetString("UTA_ErrorDataConnectionFailed", resourceCulture); + return ResourceManager.GetString("STAIsOnlySupportedOnWindowsWarning", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Failed to discover tests from assembly {0}. Reason:{1}. + /// + internal static string TestAssembly_AssemblyDiscoveryFailure { + get { + return ResourceManager.GetString("TestAssembly_AssemblyDiscoveryFailure", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to File does not exist: {0}. + /// + internal static string TestAssembly_FileDoesNotExist { + get { + return ResourceManager.GetString("TestAssembly_FileDoesNotExist", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Test cleanup method '{0}.{1}' timed out after {2}ms. + /// + internal static string TestCleanupTimedOut { + get { + return ResourceManager.GetString("TestCleanupTimedOut", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Test cleanup method '{0}.{1}' was canceled. + /// + internal static string TestCleanupWasCancelled { + get { + return ResourceManager.GetString("TestCleanupWasCancelled", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to TestContext cannot be Null.. + /// + internal static string TestContextIsNull { + get { + return ResourceManager.GetString("TestContextIsNull", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to TestContext Messages:. + /// + internal static string TestContextMessageBanner { + get { + return ResourceManager.GetString("TestContextMessageBanner", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Test initialize method '{0}.{1}' timed out after {2}ms. + /// + internal static string TestInitializeTimedOut { + get { + return ResourceManager.GetString("TestInitializeTimedOut", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Test initialize method '{0}.{1}' was canceled. + /// + internal static string TestInitializeWasCancelled { + get { + return ResourceManager.GetString("TestInitializeWasCancelled", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Test method {0} was not found.. + /// + internal static string TestNotFound { + get { + return ResourceManager.GetString("TestNotFound", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}). + /// + internal static string TestParallelizationBanner { + get { + return ResourceManager.GetString("TestParallelizationBanner", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {0}_{1} {2}. + /// + internal static string TestRunName { + get { + return ResourceManager.GetString("TestRunName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Unable to load types from the test source '{0}'. Some or all of the tests in this source may not be discovered. + ///Error: {1}. + /// + internal static string TypeLoadFailed { + get { + return ResourceManager.GetString("TypeLoadFailed", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Assembly Cleanup method {0}.{1} failed. Error Message: {2}. StackTrace: {3}. + /// + internal static string UTA_AssemblyCleanupMethodWasUnsuccesful { + get { + return ResourceManager.GetString("UTA_AssemblyCleanupMethodWasUnsuccesful", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Assembly Initialization method {0}.{1} threw exception. {2}: {3}. Aborting test execution.. + /// + internal static string UTA_AssemblyInitMethodThrows { + get { + return ResourceManager.GetString("UTA_AssemblyInitMethodThrows", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Class Cleanup method {0}.{1} failed. Error Message: {2}. Stack Trace: {3}. + /// + internal static string UTA_ClassCleanupMethodWasUnsuccesful { + get { + return ResourceManager.GetString("UTA_ClassCleanupMethodWasUnsuccesful", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Class Initialization method {0}.{1} threw exception. {2}: {3}.. + /// + internal static string UTA_ClassInitMethodThrows { + get { + return ResourceManager.GetString("UTA_ClassInitMethodThrows", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'.. + /// + internal static string UTA_ClassOrAssemblyCleanupMethodHasWrongSignature { + get { + return ResourceManager.GetString("UTA_ClassOrAssemblyCleanupMethodHasWrongSignature", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should take a single parameter of type TestContext. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'.. + /// + internal static string UTA_ClassOrAssemblyInitializeMethodHasWrongSignature { + get { + return ResourceManager.GetString("UTA_ClassOrAssemblyInitializeMethodHasWrongSignature", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to TestCleanup method {0}.{1} threw exception. {2}.. + /// + internal static string UTA_CleanupMethodThrows { + get { + return ResourceManager.GetString("UTA_CleanupMethodThrows", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Error calling Test Cleanup method for test class {0}: {1}. + /// + internal static string UTA_CleanupMethodThrowsGeneralError { + get { + return ResourceManager.GetString("UTA_CleanupMethodThrowsGeneralError", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to TestCleanup Stack Trace. + /// + internal static string UTA_CleanupStackTrace { + get { + return ResourceManager.GetString("UTA_CleanupStackTrace", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Data source '{0}' cannot be found in the test configuration settings. + /// + internal static string UTA_DataSourceConfigurationSectionMissing { + get { + return ResourceManager.GetString("UTA_DataSourceConfigurationSectionMissing", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to --- End of inner exception stack trace ---. + /// + internal static string UTA_EndOfInnerExceptionTrace { + get { + return ResourceManager.GetString("UTA_EndOfInnerExceptionTrace", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The unit test adapter failed to connect to the data source or to read the data. For more information on troubleshooting this error, see "Troubleshooting Data-Driven Unit Tests" (http://go.microsoft.com/fwlink/?LinkId=62412) in the MSDN Library. Error details: {0}. + /// + internal static string UTA_ErrorDataConnectionFailed { + get { + return ResourceManager.GetString("UTA_ErrorDataConnectionFailed", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to UTA007: Method {1} defined in class {0} does not have correct signature. Test method marked with the [TestMethod] attribute must be non-static, public, return-type as void and should not take any parameter. Example: public void Test.Class1.Test(). Additionally, if you are using async-await in test method then return-type must be 'Task' or 'ValueTask'. Example: public async Task Test.Class1.Test2(). + /// + internal static string UTA_ErrorIncorrectTestMethodSignature { + get { + return ResourceManager.GetString("UTA_ErrorIncorrectTestMethodSignature", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to UTA031: class {0} does not have valid TestContext property. TestContext must be of type TestContext, must be non-static, and must be public. For example: public TestContext TestContext.. + /// + internal static string UTA_ErrorInValidTestContextSignature { + get { + return ResourceManager.GetString("UTA_ErrorInValidTestContextSignature", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to UTA054: {0}.{1} has invalid Timeout attribute. The timeout must be an integer value greater than 0.. + /// + internal static string UTA_ErrorInvalidTimeout { + get { + return ResourceManager.GetString("UTA_ErrorInvalidTimeout", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to UTA014: {0}: Cannot define more than one method with the AssemblyCleanup attribute inside an assembly.. + /// + internal static string UTA_ErrorMultiAssemblyClean { + get { + return ResourceManager.GetString("UTA_ErrorMultiAssemblyClean", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to UTA013: {0}: Cannot define more than one method with the AssemblyInitialize attribute inside an assembly.. + /// + internal static string UTA_ErrorMultiAssemblyInit { + get { + return ResourceManager.GetString("UTA_ErrorMultiAssemblyInit", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to UTA026: {0}: Cannot define more than one method with the ClassCleanup attribute inside a class.. + /// + internal static string UTA_ErrorMultiClassClean { + get { + return ResourceManager.GetString("UTA_ErrorMultiClassClean", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to UTA025: {0}: Cannot define more than one method with the ClassInitialize attribute inside a class.. + /// + internal static string UTA_ErrorMultiClassInit { + get { + return ResourceManager.GetString("UTA_ErrorMultiClassInit", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to UTA024: {0}: Cannot define more than one method with the TestCleanup attribute.. + /// + internal static string UTA_ErrorMultiClean { + get { + return ResourceManager.GetString("UTA_ErrorMultiClean", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to UTA018: {0}: Cannot define more than one method with the TestInitialize attribute.. + /// + internal static string UTA_ErrorMultiInit { + get { + return ResourceManager.GetString("UTA_ErrorMultiInit", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to UTA001: TestClass attribute defined on non-public class {0}. + /// + internal static string UTA_ErrorNonPublicTestClass { + get { + return ResourceManager.GetString("UTA_ErrorNonPublicTestClass", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to UTA023: {0}: Cannot define predefined property {2} on method {1}.. + /// + internal static string UTA_ErrorPredefinedTestProperty { + get { + return ResourceManager.GetString("UTA_ErrorPredefinedTestProperty", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to TestClass attribute defined on generic non-abstract class {0}. + /// + internal static string UTA_ErrorTestClassIsGenericNonAbstract { + get { + return ResourceManager.GetString("UTA_ErrorTestClassIsGenericNonAbstract", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to UTA021: {0}: Null or empty custom property defined on method {1}. The custom property must have a valid name.. + /// + internal static string UTA_ErrorTestPropertyNullOrEmpty { + get { + return ResourceManager.GetString("UTA_ErrorTestPropertyNullOrEmpty", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to An unhandled exception was thrown by the 'Execute' method. Please report this error to the author of the attribute '{0}'. + ///{1}. + /// + internal static string UTA_ExecuteThrewException { + get { + return ResourceManager.GetString("UTA_ExecuteThrewException", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The ExpectedException attribute defined on test method {0}.{1} threw an exception during construction. + ///{2}. + /// + internal static string UTA_ExpectedExceptionAttributeConstructionException { + get { + return ResourceManager.GetString("UTA_ExpectedExceptionAttributeConstructionException", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Failed to obtain the exception thrown by test method {0}.{1}.. + /// + internal static string UTA_FailedToGetTestMethodException { + get { + return ResourceManager.GetString("UTA_FailedToGetTestMethodException", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Initialization method {0}.{1} threw exception. {2}.. + /// + internal static string UTA_InitMethodThrows { + get { + return ResourceManager.GetString("UTA_InitMethodThrows", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Unable to create instance of class {0}. Error: {1}.. + /// + internal static string UTA_InstanceCreationError { + get { + return ResourceManager.GetString("UTA_InstanceCreationError", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Method {0}.{1} does not exist.. + /// + internal static string UTA_MethodDoesNotExists { + get { + return ResourceManager.GetString("UTA_MethodDoesNotExists", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The test method '{0}.{1}' has multiple attributes derived from '{2}' defined on it. Only one such attribute is allowed.. + /// + internal static string UTA_MultipleAttributesOnTestMethod { + get { + return ResourceManager.GetString("UTA_MultipleAttributesOnTestMethod", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Error in executing test. No result returned by extension. If using extension of TestMethodAttribute then please contact vendor.. + /// + internal static string UTA_NoTestResult { + get { + return ResourceManager.GetString("UTA_NoTestResult", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Cannot find a valid constructor for test class '{0}'. Valid constructors are 'public' and either parameterless or with one parameter of type 'TestContext'.. + /// + internal static string UTA_NoValidConstructor { + get { + return ResourceManager.GetString("UTA_NoValidConstructor", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Unable to find property {0}.TestContext. Error:{1}.. + /// + internal static string UTA_TestContextLoadError { + get { + return ResourceManager.GetString("UTA_TestContextLoadError", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Unable to set TestContext property for the class {0}. Error: {1}.. + /// + internal static string UTA_TestContextSetError { + get { + return ResourceManager.GetString("UTA_TestContextSetError", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The {0}.TestContext has incorrect type.. + /// + internal static string UTA_TestContextTypeMismatchLoadError { + get { + return ResourceManager.GetString("UTA_TestContextTypeMismatchLoadError", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Method {0}.{1} has wrong signature. The method must be non-static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'.. + /// + internal static string UTA_TestInitializeAndCleanupMethodHasWrongSignature { + get { + return ResourceManager.GetString("UTA_TestInitializeAndCleanupMethodHasWrongSignature", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Test method {0}.{1} threw exception: + ///{2}. + /// + internal static string UTA_TestMethodThrows { + get { + return ResourceManager.GetString("UTA_TestMethodThrows", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Unable to get type {0}. Error: {1}.. + /// + internal static string UTA_TypeLoadError { + get { + return ResourceManager.GetString("UTA_TypeLoadError", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The called code threw an exception that was caught, but the exception value was null. + /// + internal static string UTA_UserCodeThrewNullValueException { + get { + return ResourceManager.GetString("UTA_UserCodeThrewNullValueException", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {0} For UWP projects, if you are using UI objects in test consider using [UITestMethod] attribute instead of [TestMethod] to execute test in UI thread.. + /// + internal static string UTA_WrongThread { + get { + return ResourceManager.GetString("UTA_WrongThread", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to (Failed to get the message for an exception of type {0} due to an exception.). + /// + internal static string UTF_FailedToGetExceptionMessage { + get { + return ResourceManager.GetString("UTF_FailedToGetExceptionMessage", resourceCulture); } } diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/Resource.resx b/src/Adapter/MSTestAdapter.PlatformServices/Resources/Resource.resx index 414073c307..fa7e9078aa 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/Resource.resx +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/Resource.resx @@ -186,4 +186,302 @@ Invalid value '{0}' for runsettings entry '{1}', setting will be ignored. + + Assembly cleanup method '{0}.{1}' timed out after {2}ms + + + Assembly cleanup method '{0}.{1}' was canceled + + + Assembly initialize method '{0}.{1}' timed out after {2}ms + + + Assembly initialize method '{0}.{1}' was canceled + + + MSTestAdapterV2 + + + Exception occurred while enumerating IDataSource attribute on "{0}.{1}": {2} + {0}: TypeName with namespace, +{1}: Method name, +{2}: Exception details + + + Exception occurred while expanding IDataSource rows from attribute on "{0}.{1}": {2} + {0}: TypeName with namespace, +{1}: Method name, +{2}: CannotExpandIDataSourceAttribute_DuplicateDisplayName or CannotExpandIDataSourceAttribute_CannotSerialize + + + Data on index {0} for "{1}" cannot be serialized. All data provided through "IDataSource" should be serializable. If you need to test non-serializable data sources, please make sure you add "TestDataSourceDiscovery" attribute on your test assembly and set the discovery option to "DuringExecution". + {0}: Zero based index if an element inside of an array, +{1}: Test name + + + Display name "{2}" on indexes {0} and {1} are duplicate. Display names should be unique. + {0}, {1}: Zero based index if an element inside of an array +{2}: Test display name. + + + Cannot run test method '{0}.{1}': Test data doesn't match method parameters. Either the count or types are different. +Test expected {2} parameter(s), with types '{3}', +but received {4} argument(s), with types '{5}'. + + + Cannot run test method '{0}.{1}': Method has parameters, but does not define any test source. Use '[DataRow]', '[DynamicData]', or a custom 'ITestDataSource' data source to provide test data. + + + Class cleanup method '{0}.{1}' timed out after {2}ms + + + Class cleanup method '{0}.{1}' was canceled + + + Class initialize method '{0}.{1}' timed out after {2}ms + + + Class initialize method '{0}.{1}' was canceled + + + MSTestAdapter failed to discover tests in class '{0}' of assembly '{1}' because {2}. + + + {0} (Data Row {1}) + + + Debug Trace: + + + [MSTest][Discovery][{0}] {1} + + + Both '.runsettings' and '.testconfig.json' files have been detected. Please select only one of these test configuration files. + + + {0}: {1} + + + "{0}": (Failed to get exception description due to an exception of type "{1}". + {0}: Type of the original exception that we're trying to get the description of. +{1}: Thrown exception + + + Exceptions thrown: + This is usually precedes by TestAssembly_AssemblyDiscoveryFailure message, and preceded by list of exceptions thrown in a test discovery session. + + + Test '{0}' was canceled + + + Test '{0}' timed out after {1}ms + + + Getting custom attributes for type {0} threw exception (will ignore and use the reflection way): {1} + {0}: Attribute full type name. +{1}: Exception description + + + The type of the generic parameter '{0}' could not be inferred. + + + The generic test method '{0}' doesn't have arguments, so the generic parameter cannot be inferred. + + + Found two conflicting types for generic parameter '{0}'. The conflicting types are '{1}' and '{2}'. + + + Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. + 'ClassCleanupLifecycle' is a setting name that shouldn't be localized. + + + Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. + 'Scope' is a setting name that shouldn't be localized. + + + Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. + `Workers` is a setting name that shouldn't be localized. + + + Invalid settings '{0}'. Unexpected XmlAttribute: '{1}'. + + + Invalid settings '{0}'. Unexpected XmlElement: '{1}'. + + + Invalid value '{0}' for runsettings entry '{1}', setting will be ignored. + + + Warning : A testsettings file or a vsmdi file is not supported with the MSTest V2 Adapter. + + + An older version of MSTestV2 package is loaded in assembly, test discovery might fail to discover all data tests if they depend on `.runsettings` file. + + + Running tests in any of the provided sources is not supported for the selected platform + + + Failed to discover tests from assembly {0}. Reason:{1} + + + File does not exist: {0} + + + Test cleanup method '{0}.{1}' timed out after {2}ms + + + Test cleanup method '{0}.{1}' was canceled + + + TestContext cannot be Null. + + + TestContext Messages: + + + Test initialize method '{0}.{1}' timed out after {2}ms + + + Test initialize method '{0}.{1}' was canceled + + + Test method {0} was not found. + + + Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) + `Workers` is a setting name that shouldn't be localized. 'Scope' is a setting name that shouldn't be localized. + + + Unable to load types from the test source '{0}'. Some or all of the tests in this source may not be discovered. +Error: {1} + + + Assembly Cleanup method {0}.{1} failed. Error Message: {2}. StackTrace: {3} + + + Assembly Initialization method {0}.{1} threw exception. {2}: {3}. Aborting test execution. + + + Class Cleanup method {0}.{1} failed. Error Message: {2}. Stack Trace: {3} + + + Class Initialization method {0}.{1} threw exception. {2}: {3}. + + + Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + + + Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should take a single parameter of type TestContext. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + + + TestCleanup method {0}.{1} threw exception. {2}. + + + Error calling Test Cleanup method for test class {0}: {1} + + + TestCleanup Stack Trace + + + --- End of inner exception stack trace --- + + + UTA007: Method {1} defined in class {0} does not have correct signature. Test method marked with the [TestMethod] attribute must be non-static, public, return-type as void and should not take any parameter. Example: public void Test.Class1.Test(). Additionally, if you are using async-await in test method then return-type must be 'Task' or 'ValueTask'. Example: public async Task Test.Class1.Test2() + + + UTA031: class {0} does not have valid TestContext property. TestContext must be of type TestContext, must be non-static, and must be public. For example: public TestContext TestContext. + + + UTA054: {0}.{1} has invalid Timeout attribute. The timeout must be an integer value greater than 0. + + + UTA014: {0}: Cannot define more than one method with the AssemblyCleanup attribute inside an assembly. + + + UTA013: {0}: Cannot define more than one method with the AssemblyInitialize attribute inside an assembly. + + + UTA026: {0}: Cannot define more than one method with the ClassCleanup attribute inside a class. + + + UTA025: {0}: Cannot define more than one method with the ClassInitialize attribute inside a class. + + + UTA024: {0}: Cannot define more than one method with the TestCleanup attribute. + + + UTA018: {0}: Cannot define more than one method with the TestInitialize attribute. + + + UTA001: TestClass attribute defined on non-public class {0} + + + UTA023: {0}: Cannot define predefined property {2} on method {1}. + + + TestClass attribute defined on generic non-abstract class {0} + + + UTA021: {0}: Null or empty custom property defined on method {1}. The custom property must have a valid name. + + + An unhandled exception was thrown by the 'Execute' method. Please report this error to the author of the attribute '{0}'. +{1} + + + The ExpectedException attribute defined on test method {0}.{1} threw an exception during construction. +{2} + + + Failed to obtain the exception thrown by test method {0}.{1}. + + + Initialization method {0}.{1} threw exception. {2}. + + + Unable to create instance of class {0}. Error: {1}. + + + Method {0}.{1} does not exist. + + + The test method '{0}.{1}' has multiple attributes derived from '{2}' defined on it. Only one such attribute is allowed. + + + Error in executing test. No result returned by extension. If using extension of TestMethodAttribute then please contact vendor. + + + Cannot find a valid constructor for test class '{0}'. Valid constructors are 'public' and either parameterless or with one parameter of type 'TestContext'. + + + Unable to find property {0}.TestContext. Error:{1}. + + + Unable to set TestContext property for the class {0}. Error: {1}. + + + The {0}.TestContext has incorrect type. + + + Method {0}.{1} has wrong signature. The method must be non-static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + + + Test method {0}.{1} threw exception: +{2} + + + Unable to get type {0}. Error: {1}. + + + The called code threw an exception that was caught, but the exception value was null + + + {0} For UWP projects, if you are using UI objects in test consider using [UITestMethod] attribute instead of [TestMethod] to execute test in UI thread. + + + (Failed to get the message for an exception of type {0} due to an exception.) + + + Runsettings entry '<ExecutionApartmentState>STA</ExecutionApartmentState>' is not supported on non-Windows OSes. + \ No newline at end of file diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.cs.xlf b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.cs.xlf index b82c787000..19a49ea75c 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.cs.xlf +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.cs.xlf @@ -2,16 +2,116 @@ + + Assembly cleanup method '{0}.{1}' timed out after {2}ms + Assembly cleanup method '{0}.{1}' timed out after {2}ms + + + + Assembly cleanup method '{0}.{1}' was canceled + Assembly cleanup method '{0}.{1}' was canceled + + + + Assembly initialize method '{0}.{1}' timed out after {2}ms + Assembly initialize method '{0}.{1}' timed out after {2}ms + + + + Assembly initialize method '{0}.{1}' was canceled + Assembly initialize method '{0}.{1}' was canceled + + + + MSTestAdapterV2 + MSTestAdapterV2 + + + + Exception occurred while enumerating IDataSource attribute on "{0}.{1}": {2} + Exception occurred while enumerating IDataSource attribute on "{0}.{1}": {2} + {0}: TypeName with namespace, +{1}: Method name, +{2}: Exception details + + + Exception occurred while expanding IDataSource rows from attribute on "{0}.{1}": {2} + Exception occurred while expanding IDataSource rows from attribute on "{0}.{1}": {2} + {0}: TypeName with namespace, +{1}: Method name, +{2}: CannotExpandIDataSourceAttribute_DuplicateDisplayName or CannotExpandIDataSourceAttribute_CannotSerialize + + + Data on index {0} for "{1}" cannot be serialized. All data provided through "IDataSource" should be serializable. If you need to test non-serializable data sources, please make sure you add "TestDataSourceDiscovery" attribute on your test assembly and set the discovery option to "DuringExecution". + Data on index {0} for "{1}" cannot be serialized. All data provided through "IDataSource" should be serializable. If you need to test non-serializable data sources, please make sure you add "TestDataSourceDiscovery" attribute on your test assembly and set the discovery option to "DuringExecution". + {0}: Zero based index if an element inside of an array, +{1}: Test name + + + Display name "{2}" on indexes {0} and {1} are duplicate. Display names should be unique. + Display name "{2}" on indexes {0} and {1} are duplicate. Display names should be unique. + {0}, {1}: Zero based index if an element inside of an array +{2}: Test display name. + Could not find file '{0}'. Soubor {0} se nenašel. + + Cannot run test method '{0}.{1}': Test data doesn't match method parameters. Either the count or types are different. +Test expected {2} parameter(s), with types '{3}', +but received {4} argument(s), with types '{5}'. + Cannot run test method '{0}.{1}': Test data doesn't match method parameters. Either the count or types are different. +Test expected {2} parameter(s), with types '{3}', +but received {4} argument(s), with types '{5}'. + + + + Cannot run test method '{0}.{1}': Method has parameters, but does not define any test source. Use '[DataRow]', '[DynamicData]', or a custom 'ITestDataSource' data source to provide test data. + Cannot run test method '{0}.{1}': Method has parameters, but does not define any test source. Use '[DataRow]', '[DynamicData]', or a custom 'ITestDataSource' data source to provide test data. + + + + Class cleanup method '{0}.{1}' timed out after {2}ms + Class cleanup method '{0}.{1}' timed out after {2}ms + + + + Class cleanup method '{0}.{1}' was canceled + Class cleanup method '{0}.{1}' was canceled + + + + Class initialize method '{0}.{1}' timed out after {2}ms + Class initialize method '{0}.{1}' timed out after {2}ms + + + + Class initialize method '{0}.{1}' was canceled + Class initialize method '{0}.{1}' was canceled + + The parameter should not be null or empty. Parametr nemůže být null nebo prázdný. + + MSTestAdapter failed to discover tests in class '{0}' of assembly '{1}' because {2}. + MSTestAdapter failed to discover tests in class '{0}' of assembly '{1}' because {2}. + + + + {0} (Data Row {1}) + {0} (Data Row {1}) + + + + Debug Trace: + Debug Trace: + + Test Run deployment issue: Bad deployment item: '{0}': output directory '{1}' specifies the item to be deployed outside deployment root directory which is not allowed. Problém nasazení testovacího běhu: Chybná položka nasazení: {0}: výstupní adresář {1} určuje položku, která se má nasadit mimo kořenový adresář nasazení, což není povolené. @@ -77,16 +177,108 @@ položka nasazení {0} (adresář výstupu {1}) + + [MSTest][Discovery][{0}] {1} + [MSTest][Discovery][{0}] {1} + + + + Both '.runsettings' and '.testconfig.json' files have been detected. Please select only one of these test configuration files. + Both '.runsettings' and '.testconfig.json' files have been detected. Please select only one of these test configuration files. + + + + {0}: {1} + {0}: {1} + + + + "{0}": (Failed to get exception description due to an exception of type "{1}". + "{0}": (Failed to get exception description due to an exception of type "{1}". + {0}: Type of the original exception that we're trying to get the description of. +{1}: Thrown exception + + + Exceptions thrown: + Exceptions thrown: + This is usually precedes by TestAssembly_AssemblyDiscoveryFailure message, and preceded by list of exceptions thrown in a test discovery session. + + + Test '{0}' was canceled + Test '{0}' was canceled + + + + Test '{0}' timed out after {1}ms + Test '{0}' timed out after {1}ms + + + + Getting custom attributes for type {0} threw exception (will ignore and use the reflection way): {1} + Getting custom attributes for type {0} threw exception (will ignore and use the reflection way): {1} + {0}: Attribute full type name. +{1}: Exception description + + + The type of the generic parameter '{0}' could not be inferred. + The type of the generic parameter '{0}' could not be inferred. + + + + The generic test method '{0}' doesn't have arguments, so the generic parameter cannot be inferred. + The generic test method '{0}' doesn't have arguments, so the generic parameter cannot be inferred. + + + + Found two conflicting types for generic parameter '{0}'. The conflicting types are '{1}' and '{2}'. + Found two conflicting types for generic parameter '{0}'. The conflicting types are '{1}' and '{2}'. + + + + Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. + Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. + 'ClassCleanupLifecycle' is a setting name that shouldn't be localized. + + + Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. + Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. + 'Scope' is a setting name that shouldn't be localized. + + + Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. + Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. + `Workers` is a setting name that shouldn't be localized. + + + Invalid settings '{0}'. Unexpected XmlAttribute: '{1}'. + Invalid settings '{0}'. Unexpected XmlAttribute: '{1}'. + + MSTestAdapter encountered an unexpected element '{0}' in its settings '{1}'. Remove this element and try again. Nástroj MSTestAdapter zjistil neočekávaný prvek {0} v nastavení {1}. Odeberte tento prvek a zkuste to znovu. + + Invalid settings '{0}'. Unexpected XmlElement: '{1}'. + Invalid settings '{0}'. Unexpected XmlElement: '{1}'. + + Invalid value '{0}' for runsettings entry '{1}', setting will be ignored. Neplatná hodnota {0} pro položku runsettings {1}. Nastavení bude ignorováno. + + Invalid value '{0}' for runsettings entry '{1}', setting will be ignored. + Invalid value '{0}' for runsettings entry '{1}', setting will be ignored. + + + + Warning : A testsettings file or a vsmdi file is not supported with the MSTest V2 Adapter. + Warning : A testsettings file or a vsmdi file is not supported with the MSTest V2 Adapter. + + Test Run deployment issue: The assembly or module '{0}' was not found. Reason: {1} Problém nasazení testovacího běhu: Sestavení nebo modul {0} se nenašly. Důvod: {1} @@ -97,21 +289,304 @@ Problém nasazení testovacího běhu: Sestavení nebo modul {0} se nenašly. + + An older version of MSTestV2 package is loaded in assembly, test discovery might fail to discover all data tests if they depend on `.runsettings` file. + An older version of MSTestV2 package is loaded in assembly, test discovery might fail to discover all data tests if they depend on `.runsettings` file. + + + + Runsettings entry '<ExecutionApartmentState>STA</ExecutionApartmentState>' is not supported on non-Windows OSes. + Runsettings entry '<ExecutionApartmentState>STA</ExecutionApartmentState>' is not supported on non-Windows OSes. + + + + Running tests in any of the provided sources is not supported for the selected platform + Running tests in any of the provided sources is not supported for the selected platform + + + + Failed to discover tests from assembly {0}. Reason:{1} + Failed to discover tests from assembly {0}. Reason:{1} + + + + File does not exist: {0} + File does not exist: {0} + + + + Test cleanup method '{0}.{1}' timed out after {2}ms + Test cleanup method '{0}.{1}' timed out after {2}ms + + + + Test cleanup method '{0}.{1}' was canceled + Test cleanup method '{0}.{1}' was canceled + + + + TestContext cannot be Null. + TestContext cannot be Null. + + + + TestContext Messages: + TestContext Messages: + + + + Test initialize method '{0}.{1}' timed out after {2}ms + Test initialize method '{0}.{1}' timed out after {2}ms + + + + Test initialize method '{0}.{1}' was canceled + Test initialize method '{0}.{1}' was canceled + + + + Test method {0} was not found. + Test method {0} was not found. + + + + Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) + Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) + `Workers` is a setting name that shouldn't be localized. 'Scope' is a setting name that shouldn't be localized. + {0}_{1} {2} {0}_{1} {2} + + Unable to load types from the test source '{0}'. Some or all of the tests in this source may not be discovered. +Error: {1} + Unable to load types from the test source '{0}'. Some or all of the tests in this source may not be discovered. +Error: {1} + + + + Assembly Cleanup method {0}.{1} failed. Error Message: {2}. StackTrace: {3} + Assembly Cleanup method {0}.{1} failed. Error Message: {2}. StackTrace: {3} + + + + Assembly Initialization method {0}.{1} threw exception. {2}: {3}. Aborting test execution. + Assembly Initialization method {0}.{1} threw exception. {2}: {3}. Aborting test execution. + + + + Class Cleanup method {0}.{1} failed. Error Message: {2}. Stack Trace: {3} + Class Cleanup method {0}.{1} failed. Error Message: {2}. Stack Trace: {3} + + + + Class Initialization method {0}.{1} threw exception. {2}: {3}. + Class Initialization method {0}.{1} threw exception. {2}: {3}. + + + + Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + + + + Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should take a single parameter of type TestContext. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should take a single parameter of type TestContext. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + + + + TestCleanup method {0}.{1} threw exception. {2}. + TestCleanup method {0}.{1} threw exception. {2}. + + + + Error calling Test Cleanup method for test class {0}: {1} + Error calling Test Cleanup method for test class {0}: {1} + + + + TestCleanup Stack Trace + TestCleanup Stack Trace + + Data source '{0}' cannot be found in the test configuration settings Zdroj dat {0} se v nastavení konfigurace testu nenašel. + + --- End of inner exception stack trace --- + --- End of inner exception stack trace --- + + The unit test adapter failed to connect to the data source or to read the data. For more information on troubleshooting this error, see "Troubleshooting Data-Driven Unit Tests" (http://go.microsoft.com/fwlink/?LinkId=62412) in the MSDN Library. Error details: {0} Adaptéru testování částí se buď nepodařilo připojit ke zdroji dat, nebo přečíst data. Další informace o odstraňování této chyby najdete v knihovně MSDN v tématu Troubleshooting Data-Driven Unit Tests (http://go.microsoft.com/fwlink/?LinkId=62412). Podrobnosti o chybě: {0} + + UTA031: class {0} does not have valid TestContext property. TestContext must be of type TestContext, must be non-static, and must be public. For example: public TestContext TestContext. + UTA031: class {0} does not have valid TestContext property. TestContext must be of type TestContext, must be non-static, and must be public. For example: public TestContext TestContext. + + + + UTA007: Method {1} defined in class {0} does not have correct signature. Test method marked with the [TestMethod] attribute must be non-static, public, return-type as void and should not take any parameter. Example: public void Test.Class1.Test(). Additionally, if you are using async-await in test method then return-type must be 'Task' or 'ValueTask'. Example: public async Task Test.Class1.Test2() + UTA007: Method {1} defined in class {0} does not have correct signature. Test method marked with the [TestMethod] attribute must be non-static, public, return-type as void and should not take any parameter. Example: public void Test.Class1.Test(). Additionally, if you are using async-await in test method then return-type must be 'Task' or 'ValueTask'. Example: public async Task Test.Class1.Test2() + + + + UTA054: {0}.{1} has invalid Timeout attribute. The timeout must be an integer value greater than 0. + UTA054: {0}.{1} has invalid Timeout attribute. The timeout must be an integer value greater than 0. + + + + UTA014: {0}: Cannot define more than one method with the AssemblyCleanup attribute inside an assembly. + UTA014: {0}: Cannot define more than one method with the AssemblyCleanup attribute inside an assembly. + + + + UTA013: {0}: Cannot define more than one method with the AssemblyInitialize attribute inside an assembly. + UTA013: {0}: Cannot define more than one method with the AssemblyInitialize attribute inside an assembly. + + + + UTA026: {0}: Cannot define more than one method with the ClassCleanup attribute inside a class. + UTA026: {0}: Cannot define more than one method with the ClassCleanup attribute inside a class. + + + + UTA025: {0}: Cannot define more than one method with the ClassInitialize attribute inside a class. + UTA025: {0}: Cannot define more than one method with the ClassInitialize attribute inside a class. + + + + UTA024: {0}: Cannot define more than one method with the TestCleanup attribute. + UTA024: {0}: Cannot define more than one method with the TestCleanup attribute. + + + + UTA018: {0}: Cannot define more than one method with the TestInitialize attribute. + UTA018: {0}: Cannot define more than one method with the TestInitialize attribute. + + + + UTA001: TestClass attribute defined on non-public class {0} + UTA001: TestClass attribute defined on non-public class {0} + + + + UTA023: {0}: Cannot define predefined property {2} on method {1}. + UTA023: {0}: Cannot define predefined property {2} on method {1}. + + + + TestClass attribute defined on generic non-abstract class {0} + TestClass attribute defined on generic non-abstract class {0} + + + + UTA021: {0}: Null or empty custom property defined on method {1}. The custom property must have a valid name. + UTA021: {0}: Null or empty custom property defined on method {1}. The custom property must have a valid name. + + + + An unhandled exception was thrown by the 'Execute' method. Please report this error to the author of the attribute '{0}'. +{1} + An unhandled exception was thrown by the 'Execute' method. Please report this error to the author of the attribute '{0}'. +{1} + + + + The ExpectedException attribute defined on test method {0}.{1} threw an exception during construction. +{2} + The ExpectedException attribute defined on test method {0}.{1} threw an exception during construction. +{2} + + + + Failed to obtain the exception thrown by test method {0}.{1}. + Failed to obtain the exception thrown by test method {0}.{1}. + + + + Initialization method {0}.{1} threw exception. {2}. + Initialization method {0}.{1} threw exception. {2}. + + + + Unable to create instance of class {0}. Error: {1}. + Unable to create instance of class {0}. Error: {1}. + + + + Method {0}.{1} does not exist. + Method {0}.{1} does not exist. + + + + The test method '{0}.{1}' has multiple attributes derived from '{2}' defined on it. Only one such attribute is allowed. + The test method '{0}.{1}' has multiple attributes derived from '{2}' defined on it. Only one such attribute is allowed. + + + + Error in executing test. No result returned by extension. If using extension of TestMethodAttribute then please contact vendor. + Error in executing test. No result returned by extension. If using extension of TestMethodAttribute then please contact vendor. + + + + Cannot find a valid constructor for test class '{0}'. Valid constructors are 'public' and either parameterless or with one parameter of type 'TestContext'. + Cannot find a valid constructor for test class '{0}'. Valid constructors are 'public' and either parameterless or with one parameter of type 'TestContext'. + + + + Unable to find property {0}.TestContext. Error:{1}. + Unable to find property {0}.TestContext. Error:{1}. + + + + Unable to set TestContext property for the class {0}. Error: {1}. + Unable to set TestContext property for the class {0}. Error: {1}. + + + + The {0}.TestContext has incorrect type. + The {0}.TestContext has incorrect type. + + + + Method {0}.{1} has wrong signature. The method must be non-static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + Method {0}.{1} has wrong signature. The method must be non-static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + + + + Test method {0}.{1} threw exception: +{2} + Test method {0}.{1} threw exception: +{2} + + + + Unable to get type {0}. Error: {1}. + Unable to get type {0}. Error: {1}. + + + + The called code threw an exception that was caught, but the exception value was null + The called code threw an exception that was caught, but the exception value was null + + + + {0} For UWP projects, if you are using UI objects in test consider using [UITestMethod] attribute instead of [TestMethod] to execute test in UI thread. + {0} For UWP projects, if you are using UI objects in test consider using [UITestMethod] attribute instead of [TestMethod] to execute test in UI thread. + + + + (Failed to get the message for an exception of type {0} due to an exception.) + (Failed to get the message for an exception of type {0} due to an exception.) + + Wrong number of objects for permutation. Should be greater than zero. Chybný počet objektů pro permutaci. Počet musí být větší než nula. diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.de.xlf b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.de.xlf index a2fe24f8c5..620d697dde 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.de.xlf +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.de.xlf @@ -2,16 +2,116 @@ + + Assembly cleanup method '{0}.{1}' timed out after {2}ms + Assembly cleanup method '{0}.{1}' timed out after {2}ms + + + + Assembly cleanup method '{0}.{1}' was canceled + Assembly cleanup method '{0}.{1}' was canceled + + + + Assembly initialize method '{0}.{1}' timed out after {2}ms + Assembly initialize method '{0}.{1}' timed out after {2}ms + + + + Assembly initialize method '{0}.{1}' was canceled + Assembly initialize method '{0}.{1}' was canceled + + + + MSTestAdapterV2 + MSTestAdapterV2 + + + + Exception occurred while enumerating IDataSource attribute on "{0}.{1}": {2} + Exception occurred while enumerating IDataSource attribute on "{0}.{1}": {2} + {0}: TypeName with namespace, +{1}: Method name, +{2}: Exception details + + + Exception occurred while expanding IDataSource rows from attribute on "{0}.{1}": {2} + Exception occurred while expanding IDataSource rows from attribute on "{0}.{1}": {2} + {0}: TypeName with namespace, +{1}: Method name, +{2}: CannotExpandIDataSourceAttribute_DuplicateDisplayName or CannotExpandIDataSourceAttribute_CannotSerialize + + + Data on index {0} for "{1}" cannot be serialized. All data provided through "IDataSource" should be serializable. If you need to test non-serializable data sources, please make sure you add "TestDataSourceDiscovery" attribute on your test assembly and set the discovery option to "DuringExecution". + Data on index {0} for "{1}" cannot be serialized. All data provided through "IDataSource" should be serializable. If you need to test non-serializable data sources, please make sure you add "TestDataSourceDiscovery" attribute on your test assembly and set the discovery option to "DuringExecution". + {0}: Zero based index if an element inside of an array, +{1}: Test name + + + Display name "{2}" on indexes {0} and {1} are duplicate. Display names should be unique. + Display name "{2}" on indexes {0} and {1} are duplicate. Display names should be unique. + {0}, {1}: Zero based index if an element inside of an array +{2}: Test display name. + Could not find file '{0}'. Die Datei "{0}" konnte nicht gefunden werden. + + Cannot run test method '{0}.{1}': Test data doesn't match method parameters. Either the count or types are different. +Test expected {2} parameter(s), with types '{3}', +but received {4} argument(s), with types '{5}'. + Cannot run test method '{0}.{1}': Test data doesn't match method parameters. Either the count or types are different. +Test expected {2} parameter(s), with types '{3}', +but received {4} argument(s), with types '{5}'. + + + + Cannot run test method '{0}.{1}': Method has parameters, but does not define any test source. Use '[DataRow]', '[DynamicData]', or a custom 'ITestDataSource' data source to provide test data. + Cannot run test method '{0}.{1}': Method has parameters, but does not define any test source. Use '[DataRow]', '[DynamicData]', or a custom 'ITestDataSource' data source to provide test data. + + + + Class cleanup method '{0}.{1}' timed out after {2}ms + Class cleanup method '{0}.{1}' timed out after {2}ms + + + + Class cleanup method '{0}.{1}' was canceled + Class cleanup method '{0}.{1}' was canceled + + + + Class initialize method '{0}.{1}' timed out after {2}ms + Class initialize method '{0}.{1}' timed out after {2}ms + + + + Class initialize method '{0}.{1}' was canceled + Class initialize method '{0}.{1}' was canceled + + The parameter should not be null or empty. Der Parameter darf nicht NULL oder leer sein. + + MSTestAdapter failed to discover tests in class '{0}' of assembly '{1}' because {2}. + MSTestAdapter failed to discover tests in class '{0}' of assembly '{1}' because {2}. + + + + {0} (Data Row {1}) + {0} (Data Row {1}) + + + + Debug Trace: + Debug Trace: + + Test Run deployment issue: Bad deployment item: '{0}': output directory '{1}' specifies the item to be deployed outside deployment root directory which is not allowed. Problem bei der Testlaufbereitstellung: Ungültiges Bereitstellungselement: "{0}". Das Ausgabeverzeichnis "{1}" gibt das unzulässige Element an, das außerhalb des Bereitstellungsstammverzeichnisses bereitgestellt werden soll. @@ -77,16 +177,108 @@ Bereitstellungselement "{0}" (Ausgabeverzeichnis "{1}") + + [MSTest][Discovery][{0}] {1} + [MSTest][Discovery][{0}] {1} + + + + Both '.runsettings' and '.testconfig.json' files have been detected. Please select only one of these test configuration files. + Both '.runsettings' and '.testconfig.json' files have been detected. Please select only one of these test configuration files. + + + + {0}: {1} + {0}: {1} + + + + "{0}": (Failed to get exception description due to an exception of type "{1}". + "{0}": (Failed to get exception description due to an exception of type "{1}". + {0}: Type of the original exception that we're trying to get the description of. +{1}: Thrown exception + + + Exceptions thrown: + Exceptions thrown: + This is usually precedes by TestAssembly_AssemblyDiscoveryFailure message, and preceded by list of exceptions thrown in a test discovery session. + + + Test '{0}' was canceled + Test '{0}' was canceled + + + + Test '{0}' timed out after {1}ms + Test '{0}' timed out after {1}ms + + + + Getting custom attributes for type {0} threw exception (will ignore and use the reflection way): {1} + Getting custom attributes for type {0} threw exception (will ignore and use the reflection way): {1} + {0}: Attribute full type name. +{1}: Exception description + + + The type of the generic parameter '{0}' could not be inferred. + The type of the generic parameter '{0}' could not be inferred. + + + + The generic test method '{0}' doesn't have arguments, so the generic parameter cannot be inferred. + The generic test method '{0}' doesn't have arguments, so the generic parameter cannot be inferred. + + + + Found two conflicting types for generic parameter '{0}'. The conflicting types are '{1}' and '{2}'. + Found two conflicting types for generic parameter '{0}'. The conflicting types are '{1}' and '{2}'. + + + + Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. + Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. + 'ClassCleanupLifecycle' is a setting name that shouldn't be localized. + + + Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. + Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. + 'Scope' is a setting name that shouldn't be localized. + + + Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. + Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. + `Workers` is a setting name that shouldn't be localized. + + + Invalid settings '{0}'. Unexpected XmlAttribute: '{1}'. + Invalid settings '{0}'. Unexpected XmlAttribute: '{1}'. + + MSTestAdapter encountered an unexpected element '{0}' in its settings '{1}'. Remove this element and try again. "MSTestAdapter" hat ein unerwartetes Element "{0}" in den Einstellungen "{1}" ermittelt. Entfernen Sie dieses Element, und versuchen Sie es erneut. + + Invalid settings '{0}'. Unexpected XmlElement: '{1}'. + Invalid settings '{0}'. Unexpected XmlElement: '{1}'. + + Invalid value '{0}' for runsettings entry '{1}', setting will be ignored. Ungültiger Wert "{0}" für runsettings-Eintrag "{1}". Die Einstellung wird ignoriert. + + Invalid value '{0}' for runsettings entry '{1}', setting will be ignored. + Invalid value '{0}' for runsettings entry '{1}', setting will be ignored. + + + + Warning : A testsettings file or a vsmdi file is not supported with the MSTest V2 Adapter. + Warning : A testsettings file or a vsmdi file is not supported with the MSTest V2 Adapter. + + Test Run deployment issue: The assembly or module '{0}' was not found. Reason: {1} Problem bei der Testlaufbereitstellung: Die Assembly oder das Modul "{0}" wurde nicht gefunden. Ursache: {1} @@ -97,21 +289,304 @@ Problem bei der Testlaufbereitstellung: Die Assembly oder das Modul "{0}" wurde nicht gefunden. + + An older version of MSTestV2 package is loaded in assembly, test discovery might fail to discover all data tests if they depend on `.runsettings` file. + An older version of MSTestV2 package is loaded in assembly, test discovery might fail to discover all data tests if they depend on `.runsettings` file. + + + + Runsettings entry '<ExecutionApartmentState>STA</ExecutionApartmentState>' is not supported on non-Windows OSes. + Runsettings entry '<ExecutionApartmentState>STA</ExecutionApartmentState>' is not supported on non-Windows OSes. + + + + Running tests in any of the provided sources is not supported for the selected platform + Running tests in any of the provided sources is not supported for the selected platform + + + + Failed to discover tests from assembly {0}. Reason:{1} + Failed to discover tests from assembly {0}. Reason:{1} + + + + File does not exist: {0} + File does not exist: {0} + + + + Test cleanup method '{0}.{1}' timed out after {2}ms + Test cleanup method '{0}.{1}' timed out after {2}ms + + + + Test cleanup method '{0}.{1}' was canceled + Test cleanup method '{0}.{1}' was canceled + + + + TestContext cannot be Null. + TestContext cannot be Null. + + + + TestContext Messages: + TestContext Messages: + + + + Test initialize method '{0}.{1}' timed out after {2}ms + Test initialize method '{0}.{1}' timed out after {2}ms + + + + Test initialize method '{0}.{1}' was canceled + Test initialize method '{0}.{1}' was canceled + + + + Test method {0} was not found. + Test method {0} was not found. + + + + Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) + Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) + `Workers` is a setting name that shouldn't be localized. 'Scope' is a setting name that shouldn't be localized. + {0}_{1} {2} {0}{1} {2} + + Unable to load types from the test source '{0}'. Some or all of the tests in this source may not be discovered. +Error: {1} + Unable to load types from the test source '{0}'. Some or all of the tests in this source may not be discovered. +Error: {1} + + + + Assembly Cleanup method {0}.{1} failed. Error Message: {2}. StackTrace: {3} + Assembly Cleanup method {0}.{1} failed. Error Message: {2}. StackTrace: {3} + + + + Assembly Initialization method {0}.{1} threw exception. {2}: {3}. Aborting test execution. + Assembly Initialization method {0}.{1} threw exception. {2}: {3}. Aborting test execution. + + + + Class Cleanup method {0}.{1} failed. Error Message: {2}. Stack Trace: {3} + Class Cleanup method {0}.{1} failed. Error Message: {2}. Stack Trace: {3} + + + + Class Initialization method {0}.{1} threw exception. {2}: {3}. + Class Initialization method {0}.{1} threw exception. {2}: {3}. + + + + Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + + + + Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should take a single parameter of type TestContext. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should take a single parameter of type TestContext. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + + + + TestCleanup method {0}.{1} threw exception. {2}. + TestCleanup method {0}.{1} threw exception. {2}. + + + + Error calling Test Cleanup method for test class {0}: {1} + Error calling Test Cleanup method for test class {0}: {1} + + + + TestCleanup Stack Trace + TestCleanup Stack Trace + + Data source '{0}' cannot be found in the test configuration settings Die Datenquelle "{0}" wurde in den Testkonfigurationseinstellungen nicht gefunden. + + --- End of inner exception stack trace --- + --- End of inner exception stack trace --- + + The unit test adapter failed to connect to the data source or to read the data. For more information on troubleshooting this error, see "Troubleshooting Data-Driven Unit Tests" (http://go.microsoft.com/fwlink/?LinkId=62412) in the MSDN Library. Error details: {0} Der Komponententestadapter konnte keine Verbindung mit der Datenquelle herstellen bzw. die Daten nicht lesen. Weitere Informationen zur Problembehandlung dieses Fehlers finden Sie unter "Problembehandlung von datengesteuerten Komponententests" (http://go.microsoft.com/fwlink/?LinkId=62412) in der MSDN Library. Fehlerdetails: {0} + + UTA031: class {0} does not have valid TestContext property. TestContext must be of type TestContext, must be non-static, and must be public. For example: public TestContext TestContext. + UTA031: class {0} does not have valid TestContext property. TestContext must be of type TestContext, must be non-static, and must be public. For example: public TestContext TestContext. + + + + UTA007: Method {1} defined in class {0} does not have correct signature. Test method marked with the [TestMethod] attribute must be non-static, public, return-type as void and should not take any parameter. Example: public void Test.Class1.Test(). Additionally, if you are using async-await in test method then return-type must be 'Task' or 'ValueTask'. Example: public async Task Test.Class1.Test2() + UTA007: Method {1} defined in class {0} does not have correct signature. Test method marked with the [TestMethod] attribute must be non-static, public, return-type as void and should not take any parameter. Example: public void Test.Class1.Test(). Additionally, if you are using async-await in test method then return-type must be 'Task' or 'ValueTask'. Example: public async Task Test.Class1.Test2() + + + + UTA054: {0}.{1} has invalid Timeout attribute. The timeout must be an integer value greater than 0. + UTA054: {0}.{1} has invalid Timeout attribute. The timeout must be an integer value greater than 0. + + + + UTA014: {0}: Cannot define more than one method with the AssemblyCleanup attribute inside an assembly. + UTA014: {0}: Cannot define more than one method with the AssemblyCleanup attribute inside an assembly. + + + + UTA013: {0}: Cannot define more than one method with the AssemblyInitialize attribute inside an assembly. + UTA013: {0}: Cannot define more than one method with the AssemblyInitialize attribute inside an assembly. + + + + UTA026: {0}: Cannot define more than one method with the ClassCleanup attribute inside a class. + UTA026: {0}: Cannot define more than one method with the ClassCleanup attribute inside a class. + + + + UTA025: {0}: Cannot define more than one method with the ClassInitialize attribute inside a class. + UTA025: {0}: Cannot define more than one method with the ClassInitialize attribute inside a class. + + + + UTA024: {0}: Cannot define more than one method with the TestCleanup attribute. + UTA024: {0}: Cannot define more than one method with the TestCleanup attribute. + + + + UTA018: {0}: Cannot define more than one method with the TestInitialize attribute. + UTA018: {0}: Cannot define more than one method with the TestInitialize attribute. + + + + UTA001: TestClass attribute defined on non-public class {0} + UTA001: TestClass attribute defined on non-public class {0} + + + + UTA023: {0}: Cannot define predefined property {2} on method {1}. + UTA023: {0}: Cannot define predefined property {2} on method {1}. + + + + TestClass attribute defined on generic non-abstract class {0} + TestClass attribute defined on generic non-abstract class {0} + + + + UTA021: {0}: Null or empty custom property defined on method {1}. The custom property must have a valid name. + UTA021: {0}: Null or empty custom property defined on method {1}. The custom property must have a valid name. + + + + An unhandled exception was thrown by the 'Execute' method. Please report this error to the author of the attribute '{0}'. +{1} + An unhandled exception was thrown by the 'Execute' method. Please report this error to the author of the attribute '{0}'. +{1} + + + + The ExpectedException attribute defined on test method {0}.{1} threw an exception during construction. +{2} + The ExpectedException attribute defined on test method {0}.{1} threw an exception during construction. +{2} + + + + Failed to obtain the exception thrown by test method {0}.{1}. + Failed to obtain the exception thrown by test method {0}.{1}. + + + + Initialization method {0}.{1} threw exception. {2}. + Initialization method {0}.{1} threw exception. {2}. + + + + Unable to create instance of class {0}. Error: {1}. + Unable to create instance of class {0}. Error: {1}. + + + + Method {0}.{1} does not exist. + Method {0}.{1} does not exist. + + + + The test method '{0}.{1}' has multiple attributes derived from '{2}' defined on it. Only one such attribute is allowed. + The test method '{0}.{1}' has multiple attributes derived from '{2}' defined on it. Only one such attribute is allowed. + + + + Error in executing test. No result returned by extension. If using extension of TestMethodAttribute then please contact vendor. + Error in executing test. No result returned by extension. If using extension of TestMethodAttribute then please contact vendor. + + + + Cannot find a valid constructor for test class '{0}'. Valid constructors are 'public' and either parameterless or with one parameter of type 'TestContext'. + Cannot find a valid constructor for test class '{0}'. Valid constructors are 'public' and either parameterless or with one parameter of type 'TestContext'. + + + + Unable to find property {0}.TestContext. Error:{1}. + Unable to find property {0}.TestContext. Error:{1}. + + + + Unable to set TestContext property for the class {0}. Error: {1}. + Unable to set TestContext property for the class {0}. Error: {1}. + + + + The {0}.TestContext has incorrect type. + The {0}.TestContext has incorrect type. + + + + Method {0}.{1} has wrong signature. The method must be non-static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + Method {0}.{1} has wrong signature. The method must be non-static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + + + + Test method {0}.{1} threw exception: +{2} + Test method {0}.{1} threw exception: +{2} + + + + Unable to get type {0}. Error: {1}. + Unable to get type {0}. Error: {1}. + + + + The called code threw an exception that was caught, but the exception value was null + The called code threw an exception that was caught, but the exception value was null + + + + {0} For UWP projects, if you are using UI objects in test consider using [UITestMethod] attribute instead of [TestMethod] to execute test in UI thread. + {0} For UWP projects, if you are using UI objects in test consider using [UITestMethod] attribute instead of [TestMethod] to execute test in UI thread. + + + + (Failed to get the message for an exception of type {0} due to an exception.) + (Failed to get the message for an exception of type {0} due to an exception.) + + Wrong number of objects for permutation. Should be greater than zero. Falsche Anzahl von Objekten für die Permutation. Die Anzahl muss größer als NULL sein. diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.es.xlf b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.es.xlf index 1c05e7b8c1..ebee59c379 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.es.xlf +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.es.xlf @@ -2,16 +2,116 @@ + + Assembly cleanup method '{0}.{1}' timed out after {2}ms + Assembly cleanup method '{0}.{1}' timed out after {2}ms + + + + Assembly cleanup method '{0}.{1}' was canceled + Assembly cleanup method '{0}.{1}' was canceled + + + + Assembly initialize method '{0}.{1}' timed out after {2}ms + Assembly initialize method '{0}.{1}' timed out after {2}ms + + + + Assembly initialize method '{0}.{1}' was canceled + Assembly initialize method '{0}.{1}' was canceled + + + + MSTestAdapterV2 + MSTestAdapterV2 + + + + Exception occurred while enumerating IDataSource attribute on "{0}.{1}": {2} + Exception occurred while enumerating IDataSource attribute on "{0}.{1}": {2} + {0}: TypeName with namespace, +{1}: Method name, +{2}: Exception details + + + Exception occurred while expanding IDataSource rows from attribute on "{0}.{1}": {2} + Exception occurred while expanding IDataSource rows from attribute on "{0}.{1}": {2} + {0}: TypeName with namespace, +{1}: Method name, +{2}: CannotExpandIDataSourceAttribute_DuplicateDisplayName or CannotExpandIDataSourceAttribute_CannotSerialize + + + Data on index {0} for "{1}" cannot be serialized. All data provided through "IDataSource" should be serializable. If you need to test non-serializable data sources, please make sure you add "TestDataSourceDiscovery" attribute on your test assembly and set the discovery option to "DuringExecution". + Data on index {0} for "{1}" cannot be serialized. All data provided through "IDataSource" should be serializable. If you need to test non-serializable data sources, please make sure you add "TestDataSourceDiscovery" attribute on your test assembly and set the discovery option to "DuringExecution". + {0}: Zero based index if an element inside of an array, +{1}: Test name + + + Display name "{2}" on indexes {0} and {1} are duplicate. Display names should be unique. + Display name "{2}" on indexes {0} and {1} are duplicate. Display names should be unique. + {0}, {1}: Zero based index if an element inside of an array +{2}: Test display name. + Could not find file '{0}'. No se pudo encontrar el archivo '{0}'. + + Cannot run test method '{0}.{1}': Test data doesn't match method parameters. Either the count or types are different. +Test expected {2} parameter(s), with types '{3}', +but received {4} argument(s), with types '{5}'. + Cannot run test method '{0}.{1}': Test data doesn't match method parameters. Either the count or types are different. +Test expected {2} parameter(s), with types '{3}', +but received {4} argument(s), with types '{5}'. + + + + Cannot run test method '{0}.{1}': Method has parameters, but does not define any test source. Use '[DataRow]', '[DynamicData]', or a custom 'ITestDataSource' data source to provide test data. + Cannot run test method '{0}.{1}': Method has parameters, but does not define any test source. Use '[DataRow]', '[DynamicData]', or a custom 'ITestDataSource' data source to provide test data. + + + + Class cleanup method '{0}.{1}' timed out after {2}ms + Class cleanup method '{0}.{1}' timed out after {2}ms + + + + Class cleanup method '{0}.{1}' was canceled + Class cleanup method '{0}.{1}' was canceled + + + + Class initialize method '{0}.{1}' timed out after {2}ms + Class initialize method '{0}.{1}' timed out after {2}ms + + + + Class initialize method '{0}.{1}' was canceled + Class initialize method '{0}.{1}' was canceled + + The parameter should not be null or empty. El parámetro no debe ser NULL ni estar vacío. + + MSTestAdapter failed to discover tests in class '{0}' of assembly '{1}' because {2}. + MSTestAdapter failed to discover tests in class '{0}' of assembly '{1}' because {2}. + + + + {0} (Data Row {1}) + {0} (Data Row {1}) + + + + Debug Trace: + Debug Trace: + + Test Run deployment issue: Bad deployment item: '{0}': output directory '{1}' specifies the item to be deployed outside deployment root directory which is not allowed. Problema de implementación en la serie de pruebas: elemento de implementación incorrecto '{0}': el directorio de salida '{1}' especifica el elemento que se va a implementar fuera del directorio raíz de implementación, lo cual no está permitido. @@ -77,16 +177,108 @@ elemento de implementación '{0}' (directorio de salida '{1}') + + [MSTest][Discovery][{0}] {1} + [MSTest][Discovery][{0}] {1} + + + + Both '.runsettings' and '.testconfig.json' files have been detected. Please select only one of these test configuration files. + Both '.runsettings' and '.testconfig.json' files have been detected. Please select only one of these test configuration files. + + + + {0}: {1} + {0}: {1} + + + + "{0}": (Failed to get exception description due to an exception of type "{1}". + "{0}": (Failed to get exception description due to an exception of type "{1}". + {0}: Type of the original exception that we're trying to get the description of. +{1}: Thrown exception + + + Exceptions thrown: + Exceptions thrown: + This is usually precedes by TestAssembly_AssemblyDiscoveryFailure message, and preceded by list of exceptions thrown in a test discovery session. + + + Test '{0}' was canceled + Test '{0}' was canceled + + + + Test '{0}' timed out after {1}ms + Test '{0}' timed out after {1}ms + + + + Getting custom attributes for type {0} threw exception (will ignore and use the reflection way): {1} + Getting custom attributes for type {0} threw exception (will ignore and use the reflection way): {1} + {0}: Attribute full type name. +{1}: Exception description + + + The type of the generic parameter '{0}' could not be inferred. + The type of the generic parameter '{0}' could not be inferred. + + + + The generic test method '{0}' doesn't have arguments, so the generic parameter cannot be inferred. + The generic test method '{0}' doesn't have arguments, so the generic parameter cannot be inferred. + + + + Found two conflicting types for generic parameter '{0}'. The conflicting types are '{1}' and '{2}'. + Found two conflicting types for generic parameter '{0}'. The conflicting types are '{1}' and '{2}'. + + + + Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. + Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. + 'ClassCleanupLifecycle' is a setting name that shouldn't be localized. + + + Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. + Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. + 'Scope' is a setting name that shouldn't be localized. + + + Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. + Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. + `Workers` is a setting name that shouldn't be localized. + + + Invalid settings '{0}'. Unexpected XmlAttribute: '{1}'. + Invalid settings '{0}'. Unexpected XmlAttribute: '{1}'. + + MSTestAdapter encountered an unexpected element '{0}' in its settings '{1}'. Remove this element and try again. MSTestAdapter encontró un elemento inesperado '{0}' en su configuración '{1}'. Quite este elemento e inténtelo de nuevo. + + Invalid settings '{0}'. Unexpected XmlElement: '{1}'. + Invalid settings '{0}'. Unexpected XmlElement: '{1}'. + + Invalid value '{0}' for runsettings entry '{1}', setting will be ignored. Valor ''{0}'' no válido para la entrada runsettings ''{1}'', se omitirá la configuración. + + Invalid value '{0}' for runsettings entry '{1}', setting will be ignored. + Invalid value '{0}' for runsettings entry '{1}', setting will be ignored. + + + + Warning : A testsettings file or a vsmdi file is not supported with the MSTest V2 Adapter. + Warning : A testsettings file or a vsmdi file is not supported with the MSTest V2 Adapter. + + Test Run deployment issue: The assembly or module '{0}' was not found. Reason: {1} Problema de implementación en la serie de pruebas: no se encontró el ensamblado o el módulo '{0}'. Motivo: {1} @@ -97,21 +289,304 @@ Problema de implementación en la serie de pruebas: no se encontró el ensamblado o el módulo '{0}'. + + An older version of MSTestV2 package is loaded in assembly, test discovery might fail to discover all data tests if they depend on `.runsettings` file. + An older version of MSTestV2 package is loaded in assembly, test discovery might fail to discover all data tests if they depend on `.runsettings` file. + + + + Runsettings entry '<ExecutionApartmentState>STA</ExecutionApartmentState>' is not supported on non-Windows OSes. + Runsettings entry '<ExecutionApartmentState>STA</ExecutionApartmentState>' is not supported on non-Windows OSes. + + + + Running tests in any of the provided sources is not supported for the selected platform + Running tests in any of the provided sources is not supported for the selected platform + + + + Failed to discover tests from assembly {0}. Reason:{1} + Failed to discover tests from assembly {0}. Reason:{1} + + + + File does not exist: {0} + File does not exist: {0} + + + + Test cleanup method '{0}.{1}' timed out after {2}ms + Test cleanup method '{0}.{1}' timed out after {2}ms + + + + Test cleanup method '{0}.{1}' was canceled + Test cleanup method '{0}.{1}' was canceled + + + + TestContext cannot be Null. + TestContext cannot be Null. + + + + TestContext Messages: + TestContext Messages: + + + + Test initialize method '{0}.{1}' timed out after {2}ms + Test initialize method '{0}.{1}' timed out after {2}ms + + + + Test initialize method '{0}.{1}' was canceled + Test initialize method '{0}.{1}' was canceled + + + + Test method {0} was not found. + Test method {0} was not found. + + + + Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) + Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) + `Workers` is a setting name that shouldn't be localized. 'Scope' is a setting name that shouldn't be localized. + {0}_{1} {2} {0} {1} {2} + + Unable to load types from the test source '{0}'. Some or all of the tests in this source may not be discovered. +Error: {1} + Unable to load types from the test source '{0}'. Some or all of the tests in this source may not be discovered. +Error: {1} + + + + Assembly Cleanup method {0}.{1} failed. Error Message: {2}. StackTrace: {3} + Assembly Cleanup method {0}.{1} failed. Error Message: {2}. StackTrace: {3} + + + + Assembly Initialization method {0}.{1} threw exception. {2}: {3}. Aborting test execution. + Assembly Initialization method {0}.{1} threw exception. {2}: {3}. Aborting test execution. + + + + Class Cleanup method {0}.{1} failed. Error Message: {2}. Stack Trace: {3} + Class Cleanup method {0}.{1} failed. Error Message: {2}. Stack Trace: {3} + + + + Class Initialization method {0}.{1} threw exception. {2}: {3}. + Class Initialization method {0}.{1} threw exception. {2}: {3}. + + + + Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + + + + Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should take a single parameter of type TestContext. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should take a single parameter of type TestContext. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + + + + TestCleanup method {0}.{1} threw exception. {2}. + TestCleanup method {0}.{1} threw exception. {2}. + + + + Error calling Test Cleanup method for test class {0}: {1} + Error calling Test Cleanup method for test class {0}: {1} + + + + TestCleanup Stack Trace + TestCleanup Stack Trace + + Data source '{0}' cannot be found in the test configuration settings No se encuentra el origen de datos '{0}' en los valores de configuración de prueba + + --- End of inner exception stack trace --- + --- End of inner exception stack trace --- + + The unit test adapter failed to connect to the data source or to read the data. For more information on troubleshooting this error, see "Troubleshooting Data-Driven Unit Tests" (http://go.microsoft.com/fwlink/?LinkId=62412) in the MSDN Library. Error details: {0} El adaptador de pruebas unitarias no puede conectarse al origen de datos o leer los datos. Para obtener más información acerca de cómo solucionar este error, consulte "Solución de problemas de pruebas unitarias orientadas a datos" (http://go.microsoft.com/fwlink/?LinkId=62412) en la biblioteca de MSDN. Detalles del error: {0} + + UTA031: class {0} does not have valid TestContext property. TestContext must be of type TestContext, must be non-static, and must be public. For example: public TestContext TestContext. + UTA031: class {0} does not have valid TestContext property. TestContext must be of type TestContext, must be non-static, and must be public. For example: public TestContext TestContext. + + + + UTA007: Method {1} defined in class {0} does not have correct signature. Test method marked with the [TestMethod] attribute must be non-static, public, return-type as void and should not take any parameter. Example: public void Test.Class1.Test(). Additionally, if you are using async-await in test method then return-type must be 'Task' or 'ValueTask'. Example: public async Task Test.Class1.Test2() + UTA007: Method {1} defined in class {0} does not have correct signature. Test method marked with the [TestMethod] attribute must be non-static, public, return-type as void and should not take any parameter. Example: public void Test.Class1.Test(). Additionally, if you are using async-await in test method then return-type must be 'Task' or 'ValueTask'. Example: public async Task Test.Class1.Test2() + + + + UTA054: {0}.{1} has invalid Timeout attribute. The timeout must be an integer value greater than 0. + UTA054: {0}.{1} has invalid Timeout attribute. The timeout must be an integer value greater than 0. + + + + UTA014: {0}: Cannot define more than one method with the AssemblyCleanup attribute inside an assembly. + UTA014: {0}: Cannot define more than one method with the AssemblyCleanup attribute inside an assembly. + + + + UTA013: {0}: Cannot define more than one method with the AssemblyInitialize attribute inside an assembly. + UTA013: {0}: Cannot define more than one method with the AssemblyInitialize attribute inside an assembly. + + + + UTA026: {0}: Cannot define more than one method with the ClassCleanup attribute inside a class. + UTA026: {0}: Cannot define more than one method with the ClassCleanup attribute inside a class. + + + + UTA025: {0}: Cannot define more than one method with the ClassInitialize attribute inside a class. + UTA025: {0}: Cannot define more than one method with the ClassInitialize attribute inside a class. + + + + UTA024: {0}: Cannot define more than one method with the TestCleanup attribute. + UTA024: {0}: Cannot define more than one method with the TestCleanup attribute. + + + + UTA018: {0}: Cannot define more than one method with the TestInitialize attribute. + UTA018: {0}: Cannot define more than one method with the TestInitialize attribute. + + + + UTA001: TestClass attribute defined on non-public class {0} + UTA001: TestClass attribute defined on non-public class {0} + + + + UTA023: {0}: Cannot define predefined property {2} on method {1}. + UTA023: {0}: Cannot define predefined property {2} on method {1}. + + + + TestClass attribute defined on generic non-abstract class {0} + TestClass attribute defined on generic non-abstract class {0} + + + + UTA021: {0}: Null or empty custom property defined on method {1}. The custom property must have a valid name. + UTA021: {0}: Null or empty custom property defined on method {1}. The custom property must have a valid name. + + + + An unhandled exception was thrown by the 'Execute' method. Please report this error to the author of the attribute '{0}'. +{1} + An unhandled exception was thrown by the 'Execute' method. Please report this error to the author of the attribute '{0}'. +{1} + + + + The ExpectedException attribute defined on test method {0}.{1} threw an exception during construction. +{2} + The ExpectedException attribute defined on test method {0}.{1} threw an exception during construction. +{2} + + + + Failed to obtain the exception thrown by test method {0}.{1}. + Failed to obtain the exception thrown by test method {0}.{1}. + + + + Initialization method {0}.{1} threw exception. {2}. + Initialization method {0}.{1} threw exception. {2}. + + + + Unable to create instance of class {0}. Error: {1}. + Unable to create instance of class {0}. Error: {1}. + + + + Method {0}.{1} does not exist. + Method {0}.{1} does not exist. + + + + The test method '{0}.{1}' has multiple attributes derived from '{2}' defined on it. Only one such attribute is allowed. + The test method '{0}.{1}' has multiple attributes derived from '{2}' defined on it. Only one such attribute is allowed. + + + + Error in executing test. No result returned by extension. If using extension of TestMethodAttribute then please contact vendor. + Error in executing test. No result returned by extension. If using extension of TestMethodAttribute then please contact vendor. + + + + Cannot find a valid constructor for test class '{0}'. Valid constructors are 'public' and either parameterless or with one parameter of type 'TestContext'. + Cannot find a valid constructor for test class '{0}'. Valid constructors are 'public' and either parameterless or with one parameter of type 'TestContext'. + + + + Unable to find property {0}.TestContext. Error:{1}. + Unable to find property {0}.TestContext. Error:{1}. + + + + Unable to set TestContext property for the class {0}. Error: {1}. + Unable to set TestContext property for the class {0}. Error: {1}. + + + + The {0}.TestContext has incorrect type. + The {0}.TestContext has incorrect type. + + + + Method {0}.{1} has wrong signature. The method must be non-static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + Method {0}.{1} has wrong signature. The method must be non-static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + + + + Test method {0}.{1} threw exception: +{2} + Test method {0}.{1} threw exception: +{2} + + + + Unable to get type {0}. Error: {1}. + Unable to get type {0}. Error: {1}. + + + + The called code threw an exception that was caught, but the exception value was null + The called code threw an exception that was caught, but the exception value was null + + + + {0} For UWP projects, if you are using UI objects in test consider using [UITestMethod] attribute instead of [TestMethod] to execute test in UI thread. + {0} For UWP projects, if you are using UI objects in test consider using [UITestMethod] attribute instead of [TestMethod] to execute test in UI thread. + + + + (Failed to get the message for an exception of type {0} due to an exception.) + (Failed to get the message for an exception of type {0} due to an exception.) + + Wrong number of objects for permutation. Should be greater than zero. Número incorrecto de objetos para permutación. Debe ser una cantidad mayor que cero. diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.fr.xlf b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.fr.xlf index 0233a28fb8..8782a77f73 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.fr.xlf +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.fr.xlf @@ -2,16 +2,116 @@ + + Assembly cleanup method '{0}.{1}' timed out after {2}ms + Assembly cleanup method '{0}.{1}' timed out after {2}ms + + + + Assembly cleanup method '{0}.{1}' was canceled + Assembly cleanup method '{0}.{1}' was canceled + + + + Assembly initialize method '{0}.{1}' timed out after {2}ms + Assembly initialize method '{0}.{1}' timed out after {2}ms + + + + Assembly initialize method '{0}.{1}' was canceled + Assembly initialize method '{0}.{1}' was canceled + + + + MSTestAdapterV2 + MSTestAdapterV2 + + + + Exception occurred while enumerating IDataSource attribute on "{0}.{1}": {2} + Exception occurred while enumerating IDataSource attribute on "{0}.{1}": {2} + {0}: TypeName with namespace, +{1}: Method name, +{2}: Exception details + + + Exception occurred while expanding IDataSource rows from attribute on "{0}.{1}": {2} + Exception occurred while expanding IDataSource rows from attribute on "{0}.{1}": {2} + {0}: TypeName with namespace, +{1}: Method name, +{2}: CannotExpandIDataSourceAttribute_DuplicateDisplayName or CannotExpandIDataSourceAttribute_CannotSerialize + + + Data on index {0} for "{1}" cannot be serialized. All data provided through "IDataSource" should be serializable. If you need to test non-serializable data sources, please make sure you add "TestDataSourceDiscovery" attribute on your test assembly and set the discovery option to "DuringExecution". + Data on index {0} for "{1}" cannot be serialized. All data provided through "IDataSource" should be serializable. If you need to test non-serializable data sources, please make sure you add "TestDataSourceDiscovery" attribute on your test assembly and set the discovery option to "DuringExecution". + {0}: Zero based index if an element inside of an array, +{1}: Test name + + + Display name "{2}" on indexes {0} and {1} are duplicate. Display names should be unique. + Display name "{2}" on indexes {0} and {1} are duplicate. Display names should be unique. + {0}, {1}: Zero based index if an element inside of an array +{2}: Test display name. + Could not find file '{0}'. Le fichier '{0}' est introuvable. + + Cannot run test method '{0}.{1}': Test data doesn't match method parameters. Either the count or types are different. +Test expected {2} parameter(s), with types '{3}', +but received {4} argument(s), with types '{5}'. + Cannot run test method '{0}.{1}': Test data doesn't match method parameters. Either the count or types are different. +Test expected {2} parameter(s), with types '{3}', +but received {4} argument(s), with types '{5}'. + + + + Cannot run test method '{0}.{1}': Method has parameters, but does not define any test source. Use '[DataRow]', '[DynamicData]', or a custom 'ITestDataSource' data source to provide test data. + Cannot run test method '{0}.{1}': Method has parameters, but does not define any test source. Use '[DataRow]', '[DynamicData]', or a custom 'ITestDataSource' data source to provide test data. + + + + Class cleanup method '{0}.{1}' timed out after {2}ms + Class cleanup method '{0}.{1}' timed out after {2}ms + + + + Class cleanup method '{0}.{1}' was canceled + Class cleanup method '{0}.{1}' was canceled + + + + Class initialize method '{0}.{1}' timed out after {2}ms + Class initialize method '{0}.{1}' timed out after {2}ms + + + + Class initialize method '{0}.{1}' was canceled + Class initialize method '{0}.{1}' was canceled + + The parameter should not be null or empty. Le paramètre ne doit pas être une valeur Null ou être vide. + + MSTestAdapter failed to discover tests in class '{0}' of assembly '{1}' because {2}. + MSTestAdapter failed to discover tests in class '{0}' of assembly '{1}' because {2}. + + + + {0} (Data Row {1}) + {0} (Data Row {1}) + + + + Debug Trace: + Debug Trace: + + Test Run deployment issue: Bad deployment item: '{0}': output directory '{1}' specifies the item to be deployed outside deployment root directory which is not allowed. Problème de déploiement de la série de tests : élément de déploiement incorrect : '{0}' : le répertoire de sortie '{1}' spécifie l'élément à déployer en dehors du répertoire racine du déploiement, ce qui n'est pas autorisé. @@ -77,16 +177,108 @@ élément de déploiement '{0}' (répertoire de sortie '{1}') + + [MSTest][Discovery][{0}] {1} + [MSTest][Discovery][{0}] {1} + + + + Both '.runsettings' and '.testconfig.json' files have been detected. Please select only one of these test configuration files. + Both '.runsettings' and '.testconfig.json' files have been detected. Please select only one of these test configuration files. + + + + {0}: {1} + {0}: {1} + + + + "{0}": (Failed to get exception description due to an exception of type "{1}". + "{0}": (Failed to get exception description due to an exception of type "{1}". + {0}: Type of the original exception that we're trying to get the description of. +{1}: Thrown exception + + + Exceptions thrown: + Exceptions thrown: + This is usually precedes by TestAssembly_AssemblyDiscoveryFailure message, and preceded by list of exceptions thrown in a test discovery session. + + + Test '{0}' was canceled + Test '{0}' was canceled + + + + Test '{0}' timed out after {1}ms + Test '{0}' timed out after {1}ms + + + + Getting custom attributes for type {0} threw exception (will ignore and use the reflection way): {1} + Getting custom attributes for type {0} threw exception (will ignore and use the reflection way): {1} + {0}: Attribute full type name. +{1}: Exception description + + + The type of the generic parameter '{0}' could not be inferred. + The type of the generic parameter '{0}' could not be inferred. + + + + The generic test method '{0}' doesn't have arguments, so the generic parameter cannot be inferred. + The generic test method '{0}' doesn't have arguments, so the generic parameter cannot be inferred. + + + + Found two conflicting types for generic parameter '{0}'. The conflicting types are '{1}' and '{2}'. + Found two conflicting types for generic parameter '{0}'. The conflicting types are '{1}' and '{2}'. + + + + Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. + Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. + 'ClassCleanupLifecycle' is a setting name that shouldn't be localized. + + + Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. + Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. + 'Scope' is a setting name that shouldn't be localized. + + + Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. + Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. + `Workers` is a setting name that shouldn't be localized. + + + Invalid settings '{0}'. Unexpected XmlAttribute: '{1}'. + Invalid settings '{0}'. Unexpected XmlAttribute: '{1}'. + + MSTestAdapter encountered an unexpected element '{0}' in its settings '{1}'. Remove this element and try again. MSTestAdapter a rencontré un élément inattendu '{0}' dans ses paramètres '{1}'. Supprimez cet élément, puis réessayez. + + Invalid settings '{0}'. Unexpected XmlElement: '{1}'. + Invalid settings '{0}'. Unexpected XmlElement: '{1}'. + + Invalid value '{0}' for runsettings entry '{1}', setting will be ignored. Valeur non valide '{0}' pour l’entrée runsettings '{1}', le paramètre sera ignoré. + + Invalid value '{0}' for runsettings entry '{1}', setting will be ignored. + Invalid value '{0}' for runsettings entry '{1}', setting will be ignored. + + + + Warning : A testsettings file or a vsmdi file is not supported with the MSTest V2 Adapter. + Warning : A testsettings file or a vsmdi file is not supported with the MSTest V2 Adapter. + + Test Run deployment issue: The assembly or module '{0}' was not found. Reason: {1} Problème de déploiement de la série de tests : l'assembly ou le module '{0}' est introuvable. Raison : {1} @@ -97,21 +289,304 @@ Problème de déploiement de la série de tests : l'assembly ou le module '{0}' est introuvable. + + An older version of MSTestV2 package is loaded in assembly, test discovery might fail to discover all data tests if they depend on `.runsettings` file. + An older version of MSTestV2 package is loaded in assembly, test discovery might fail to discover all data tests if they depend on `.runsettings` file. + + + + Runsettings entry '<ExecutionApartmentState>STA</ExecutionApartmentState>' is not supported on non-Windows OSes. + Runsettings entry '<ExecutionApartmentState>STA</ExecutionApartmentState>' is not supported on non-Windows OSes. + + + + Running tests in any of the provided sources is not supported for the selected platform + Running tests in any of the provided sources is not supported for the selected platform + + + + Failed to discover tests from assembly {0}. Reason:{1} + Failed to discover tests from assembly {0}. Reason:{1} + + + + File does not exist: {0} + File does not exist: {0} + + + + Test cleanup method '{0}.{1}' timed out after {2}ms + Test cleanup method '{0}.{1}' timed out after {2}ms + + + + Test cleanup method '{0}.{1}' was canceled + Test cleanup method '{0}.{1}' was canceled + + + + TestContext cannot be Null. + TestContext cannot be Null. + + + + TestContext Messages: + TestContext Messages: + + + + Test initialize method '{0}.{1}' timed out after {2}ms + Test initialize method '{0}.{1}' timed out after {2}ms + + + + Test initialize method '{0}.{1}' was canceled + Test initialize method '{0}.{1}' was canceled + + + + Test method {0} was not found. + Test method {0} was not found. + + + + Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) + Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) + `Workers` is a setting name that shouldn't be localized. 'Scope' is a setting name that shouldn't be localized. + {0}_{1} {2} {0}_{1} {2} + + Unable to load types from the test source '{0}'. Some or all of the tests in this source may not be discovered. +Error: {1} + Unable to load types from the test source '{0}'. Some or all of the tests in this source may not be discovered. +Error: {1} + + + + Assembly Cleanup method {0}.{1} failed. Error Message: {2}. StackTrace: {3} + Assembly Cleanup method {0}.{1} failed. Error Message: {2}. StackTrace: {3} + + + + Assembly Initialization method {0}.{1} threw exception. {2}: {3}. Aborting test execution. + Assembly Initialization method {0}.{1} threw exception. {2}: {3}. Aborting test execution. + + + + Class Cleanup method {0}.{1} failed. Error Message: {2}. Stack Trace: {3} + Class Cleanup method {0}.{1} failed. Error Message: {2}. Stack Trace: {3} + + + + Class Initialization method {0}.{1} threw exception. {2}: {3}. + Class Initialization method {0}.{1} threw exception. {2}: {3}. + + + + Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + + + + Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should take a single parameter of type TestContext. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should take a single parameter of type TestContext. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + + + + TestCleanup method {0}.{1} threw exception. {2}. + TestCleanup method {0}.{1} threw exception. {2}. + + + + Error calling Test Cleanup method for test class {0}: {1} + Error calling Test Cleanup method for test class {0}: {1} + + + + TestCleanup Stack Trace + TestCleanup Stack Trace + + Data source '{0}' cannot be found in the test configuration settings Source de données '{0}' introuvable dans les paramètres de configuration de test + + --- End of inner exception stack trace --- + --- End of inner exception stack trace --- + + The unit test adapter failed to connect to the data source or to read the data. For more information on troubleshooting this error, see "Troubleshooting Data-Driven Unit Tests" (http://go.microsoft.com/fwlink/?LinkId=62412) in the MSDN Library. Error details: {0} L'adaptateur de test unitaire n'a pas réussi à se connecter à la source de données ou à lire les données. Pour plus d'informations sur le dépannage de l'erreur, consultez "Résolution des problèmes liés aux tests unitaires pilotés par les données" (http://go.microsoft.com/fwlink/?LinkId=62412) dans MSDN Library. Détails de l'erreur : {0} + + UTA031: class {0} does not have valid TestContext property. TestContext must be of type TestContext, must be non-static, and must be public. For example: public TestContext TestContext. + UTA031: class {0} does not have valid TestContext property. TestContext must be of type TestContext, must be non-static, and must be public. For example: public TestContext TestContext. + + + + UTA007: Method {1} defined in class {0} does not have correct signature. Test method marked with the [TestMethod] attribute must be non-static, public, return-type as void and should not take any parameter. Example: public void Test.Class1.Test(). Additionally, if you are using async-await in test method then return-type must be 'Task' or 'ValueTask'. Example: public async Task Test.Class1.Test2() + UTA007: Method {1} defined in class {0} does not have correct signature. Test method marked with the [TestMethod] attribute must be non-static, public, return-type as void and should not take any parameter. Example: public void Test.Class1.Test(). Additionally, if you are using async-await in test method then return-type must be 'Task' or 'ValueTask'. Example: public async Task Test.Class1.Test2() + + + + UTA054: {0}.{1} has invalid Timeout attribute. The timeout must be an integer value greater than 0. + UTA054: {0}.{1} has invalid Timeout attribute. The timeout must be an integer value greater than 0. + + + + UTA014: {0}: Cannot define more than one method with the AssemblyCleanup attribute inside an assembly. + UTA014: {0}: Cannot define more than one method with the AssemblyCleanup attribute inside an assembly. + + + + UTA013: {0}: Cannot define more than one method with the AssemblyInitialize attribute inside an assembly. + UTA013: {0}: Cannot define more than one method with the AssemblyInitialize attribute inside an assembly. + + + + UTA026: {0}: Cannot define more than one method with the ClassCleanup attribute inside a class. + UTA026: {0}: Cannot define more than one method with the ClassCleanup attribute inside a class. + + + + UTA025: {0}: Cannot define more than one method with the ClassInitialize attribute inside a class. + UTA025: {0}: Cannot define more than one method with the ClassInitialize attribute inside a class. + + + + UTA024: {0}: Cannot define more than one method with the TestCleanup attribute. + UTA024: {0}: Cannot define more than one method with the TestCleanup attribute. + + + + UTA018: {0}: Cannot define more than one method with the TestInitialize attribute. + UTA018: {0}: Cannot define more than one method with the TestInitialize attribute. + + + + UTA001: TestClass attribute defined on non-public class {0} + UTA001: TestClass attribute defined on non-public class {0} + + + + UTA023: {0}: Cannot define predefined property {2} on method {1}. + UTA023: {0}: Cannot define predefined property {2} on method {1}. + + + + TestClass attribute defined on generic non-abstract class {0} + TestClass attribute defined on generic non-abstract class {0} + + + + UTA021: {0}: Null or empty custom property defined on method {1}. The custom property must have a valid name. + UTA021: {0}: Null or empty custom property defined on method {1}. The custom property must have a valid name. + + + + An unhandled exception was thrown by the 'Execute' method. Please report this error to the author of the attribute '{0}'. +{1} + An unhandled exception was thrown by the 'Execute' method. Please report this error to the author of the attribute '{0}'. +{1} + + + + The ExpectedException attribute defined on test method {0}.{1} threw an exception during construction. +{2} + The ExpectedException attribute defined on test method {0}.{1} threw an exception during construction. +{2} + + + + Failed to obtain the exception thrown by test method {0}.{1}. + Failed to obtain the exception thrown by test method {0}.{1}. + + + + Initialization method {0}.{1} threw exception. {2}. + Initialization method {0}.{1} threw exception. {2}. + + + + Unable to create instance of class {0}. Error: {1}. + Unable to create instance of class {0}. Error: {1}. + + + + Method {0}.{1} does not exist. + Method {0}.{1} does not exist. + + + + The test method '{0}.{1}' has multiple attributes derived from '{2}' defined on it. Only one such attribute is allowed. + The test method '{0}.{1}' has multiple attributes derived from '{2}' defined on it. Only one such attribute is allowed. + + + + Error in executing test. No result returned by extension. If using extension of TestMethodAttribute then please contact vendor. + Error in executing test. No result returned by extension. If using extension of TestMethodAttribute then please contact vendor. + + + + Cannot find a valid constructor for test class '{0}'. Valid constructors are 'public' and either parameterless or with one parameter of type 'TestContext'. + Cannot find a valid constructor for test class '{0}'. Valid constructors are 'public' and either parameterless or with one parameter of type 'TestContext'. + + + + Unable to find property {0}.TestContext. Error:{1}. + Unable to find property {0}.TestContext. Error:{1}. + + + + Unable to set TestContext property for the class {0}. Error: {1}. + Unable to set TestContext property for the class {0}. Error: {1}. + + + + The {0}.TestContext has incorrect type. + The {0}.TestContext has incorrect type. + + + + Method {0}.{1} has wrong signature. The method must be non-static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + Method {0}.{1} has wrong signature. The method must be non-static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + + + + Test method {0}.{1} threw exception: +{2} + Test method {0}.{1} threw exception: +{2} + + + + Unable to get type {0}. Error: {1}. + Unable to get type {0}. Error: {1}. + + + + The called code threw an exception that was caught, but the exception value was null + The called code threw an exception that was caught, but the exception value was null + + + + {0} For UWP projects, if you are using UI objects in test consider using [UITestMethod] attribute instead of [TestMethod] to execute test in UI thread. + {0} For UWP projects, if you are using UI objects in test consider using [UITestMethod] attribute instead of [TestMethod] to execute test in UI thread. + + + + (Failed to get the message for an exception of type {0} due to an exception.) + (Failed to get the message for an exception of type {0} due to an exception.) + + Wrong number of objects for permutation. Should be greater than zero. Nombre d'objets erroné pour la permutation. Il doit être supérieur à zéro. diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.it.xlf b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.it.xlf index 4808a47f8f..04e9f2a74c 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.it.xlf +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.it.xlf @@ -2,16 +2,116 @@ + + Assembly cleanup method '{0}.{1}' timed out after {2}ms + Assembly cleanup method '{0}.{1}' timed out after {2}ms + + + + Assembly cleanup method '{0}.{1}' was canceled + Assembly cleanup method '{0}.{1}' was canceled + + + + Assembly initialize method '{0}.{1}' timed out after {2}ms + Assembly initialize method '{0}.{1}' timed out after {2}ms + + + + Assembly initialize method '{0}.{1}' was canceled + Assembly initialize method '{0}.{1}' was canceled + + + + MSTestAdapterV2 + MSTestAdapterV2 + + + + Exception occurred while enumerating IDataSource attribute on "{0}.{1}": {2} + Exception occurred while enumerating IDataSource attribute on "{0}.{1}": {2} + {0}: TypeName with namespace, +{1}: Method name, +{2}: Exception details + + + Exception occurred while expanding IDataSource rows from attribute on "{0}.{1}": {2} + Exception occurred while expanding IDataSource rows from attribute on "{0}.{1}": {2} + {0}: TypeName with namespace, +{1}: Method name, +{2}: CannotExpandIDataSourceAttribute_DuplicateDisplayName or CannotExpandIDataSourceAttribute_CannotSerialize + + + Data on index {0} for "{1}" cannot be serialized. All data provided through "IDataSource" should be serializable. If you need to test non-serializable data sources, please make sure you add "TestDataSourceDiscovery" attribute on your test assembly and set the discovery option to "DuringExecution". + Data on index {0} for "{1}" cannot be serialized. All data provided through "IDataSource" should be serializable. If you need to test non-serializable data sources, please make sure you add "TestDataSourceDiscovery" attribute on your test assembly and set the discovery option to "DuringExecution". + {0}: Zero based index if an element inside of an array, +{1}: Test name + + + Display name "{2}" on indexes {0} and {1} are duplicate. Display names should be unique. + Display name "{2}" on indexes {0} and {1} are duplicate. Display names should be unique. + {0}, {1}: Zero based index if an element inside of an array +{2}: Test display name. + Could not find file '{0}'. Il file '{0}' non è stato trovato. + + Cannot run test method '{0}.{1}': Test data doesn't match method parameters. Either the count or types are different. +Test expected {2} parameter(s), with types '{3}', +but received {4} argument(s), with types '{5}'. + Cannot run test method '{0}.{1}': Test data doesn't match method parameters. Either the count or types are different. +Test expected {2} parameter(s), with types '{3}', +but received {4} argument(s), with types '{5}'. + + + + Cannot run test method '{0}.{1}': Method has parameters, but does not define any test source. Use '[DataRow]', '[DynamicData]', or a custom 'ITestDataSource' data source to provide test data. + Cannot run test method '{0}.{1}': Method has parameters, but does not define any test source. Use '[DataRow]', '[DynamicData]', or a custom 'ITestDataSource' data source to provide test data. + + + + Class cleanup method '{0}.{1}' timed out after {2}ms + Class cleanup method '{0}.{1}' timed out after {2}ms + + + + Class cleanup method '{0}.{1}' was canceled + Class cleanup method '{0}.{1}' was canceled + + + + Class initialize method '{0}.{1}' timed out after {2}ms + Class initialize method '{0}.{1}' timed out after {2}ms + + + + Class initialize method '{0}.{1}' was canceled + Class initialize method '{0}.{1}' was canceled + + The parameter should not be null or empty. Il parametro non deve essere vuoto o Null. + + MSTestAdapter failed to discover tests in class '{0}' of assembly '{1}' because {2}. + MSTestAdapter failed to discover tests in class '{0}' of assembly '{1}' because {2}. + + + + {0} (Data Row {1}) + {0} (Data Row {1}) + + + + Debug Trace: + Debug Trace: + + Test Run deployment issue: Bad deployment item: '{0}': output directory '{1}' specifies the item to be deployed outside deployment root directory which is not allowed. Problema di distribuzione dell'esecuzione dei test: l'elemento di distribuzione '{0}' non è corretto. La directory di output '{1}' specifica l'elemento da distribuire all'esterno della directory radice della distribuzione e questa operazione non consentita. @@ -77,16 +177,108 @@ elemento di distribuzione '{0}' (directory di output '{1}') + + [MSTest][Discovery][{0}] {1} + [MSTest][Discovery][{0}] {1} + + + + Both '.runsettings' and '.testconfig.json' files have been detected. Please select only one of these test configuration files. + Both '.runsettings' and '.testconfig.json' files have been detected. Please select only one of these test configuration files. + + + + {0}: {1} + {0}: {1} + + + + "{0}": (Failed to get exception description due to an exception of type "{1}". + "{0}": (Failed to get exception description due to an exception of type "{1}". + {0}: Type of the original exception that we're trying to get the description of. +{1}: Thrown exception + + + Exceptions thrown: + Exceptions thrown: + This is usually precedes by TestAssembly_AssemblyDiscoveryFailure message, and preceded by list of exceptions thrown in a test discovery session. + + + Test '{0}' was canceled + Test '{0}' was canceled + + + + Test '{0}' timed out after {1}ms + Test '{0}' timed out after {1}ms + + + + Getting custom attributes for type {0} threw exception (will ignore and use the reflection way): {1} + Getting custom attributes for type {0} threw exception (will ignore and use the reflection way): {1} + {0}: Attribute full type name. +{1}: Exception description + + + The type of the generic parameter '{0}' could not be inferred. + The type of the generic parameter '{0}' could not be inferred. + + + + The generic test method '{0}' doesn't have arguments, so the generic parameter cannot be inferred. + The generic test method '{0}' doesn't have arguments, so the generic parameter cannot be inferred. + + + + Found two conflicting types for generic parameter '{0}'. The conflicting types are '{1}' and '{2}'. + Found two conflicting types for generic parameter '{0}'. The conflicting types are '{1}' and '{2}'. + + + + Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. + Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. + 'ClassCleanupLifecycle' is a setting name that shouldn't be localized. + + + Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. + Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. + 'Scope' is a setting name that shouldn't be localized. + + + Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. + Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. + `Workers` is a setting name that shouldn't be localized. + + + Invalid settings '{0}'. Unexpected XmlAttribute: '{1}'. + Invalid settings '{0}'. Unexpected XmlAttribute: '{1}'. + + MSTestAdapter encountered an unexpected element '{0}' in its settings '{1}'. Remove this element and try again. MSTestAdapter ha rilevato un elemento imprevisto '{0}' nelle impostazioni '{1}'. Rimuovere l'elemento e riprovare. + + Invalid settings '{0}'. Unexpected XmlElement: '{1}'. + Invalid settings '{0}'. Unexpected XmlElement: '{1}'. + + Invalid value '{0}' for runsettings entry '{1}', setting will be ignored. Valore non valido '{0}' per la voce runsettings '{1}'. L'impostazione verrà ignorata. + + Invalid value '{0}' for runsettings entry '{1}', setting will be ignored. + Invalid value '{0}' for runsettings entry '{1}', setting will be ignored. + + + + Warning : A testsettings file or a vsmdi file is not supported with the MSTest V2 Adapter. + Warning : A testsettings file or a vsmdi file is not supported with the MSTest V2 Adapter. + + Test Run deployment issue: The assembly or module '{0}' was not found. Reason: {1} Problema di distribuzione dell'esecuzione dei test: l'assembly o il modulo '{0}' non è stato trovato. Motivo: {1} @@ -97,21 +289,304 @@ Problema di distribuzione dell'esecuzione dei test: l'assembly o il modulo '{0}' non è stato trovato. + + An older version of MSTestV2 package is loaded in assembly, test discovery might fail to discover all data tests if they depend on `.runsettings` file. + An older version of MSTestV2 package is loaded in assembly, test discovery might fail to discover all data tests if they depend on `.runsettings` file. + + + + Runsettings entry '<ExecutionApartmentState>STA</ExecutionApartmentState>' is not supported on non-Windows OSes. + Runsettings entry '<ExecutionApartmentState>STA</ExecutionApartmentState>' is not supported on non-Windows OSes. + + + + Running tests in any of the provided sources is not supported for the selected platform + Running tests in any of the provided sources is not supported for the selected platform + + + + Failed to discover tests from assembly {0}. Reason:{1} + Failed to discover tests from assembly {0}. Reason:{1} + + + + File does not exist: {0} + File does not exist: {0} + + + + Test cleanup method '{0}.{1}' timed out after {2}ms + Test cleanup method '{0}.{1}' timed out after {2}ms + + + + Test cleanup method '{0}.{1}' was canceled + Test cleanup method '{0}.{1}' was canceled + + + + TestContext cannot be Null. + TestContext cannot be Null. + + + + TestContext Messages: + TestContext Messages: + + + + Test initialize method '{0}.{1}' timed out after {2}ms + Test initialize method '{0}.{1}' timed out after {2}ms + + + + Test initialize method '{0}.{1}' was canceled + Test initialize method '{0}.{1}' was canceled + + + + Test method {0} was not found. + Test method {0} was not found. + + + + Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) + Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) + `Workers` is a setting name that shouldn't be localized. 'Scope' is a setting name that shouldn't be localized. + {0}_{1} {2} {0}_{1} {2} + + Unable to load types from the test source '{0}'. Some or all of the tests in this source may not be discovered. +Error: {1} + Unable to load types from the test source '{0}'. Some or all of the tests in this source may not be discovered. +Error: {1} + + + + Assembly Cleanup method {0}.{1} failed. Error Message: {2}. StackTrace: {3} + Assembly Cleanup method {0}.{1} failed. Error Message: {2}. StackTrace: {3} + + + + Assembly Initialization method {0}.{1} threw exception. {2}: {3}. Aborting test execution. + Assembly Initialization method {0}.{1} threw exception. {2}: {3}. Aborting test execution. + + + + Class Cleanup method {0}.{1} failed. Error Message: {2}. Stack Trace: {3} + Class Cleanup method {0}.{1} failed. Error Message: {2}. Stack Trace: {3} + + + + Class Initialization method {0}.{1} threw exception. {2}: {3}. + Class Initialization method {0}.{1} threw exception. {2}: {3}. + + + + Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + + + + Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should take a single parameter of type TestContext. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should take a single parameter of type TestContext. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + + + + TestCleanup method {0}.{1} threw exception. {2}. + TestCleanup method {0}.{1} threw exception. {2}. + + + + Error calling Test Cleanup method for test class {0}: {1} + Error calling Test Cleanup method for test class {0}: {1} + + + + TestCleanup Stack Trace + TestCleanup Stack Trace + + Data source '{0}' cannot be found in the test configuration settings L'origine dati '{0}' non è stata trovata nelle impostazioni della configurazione di test + + --- End of inner exception stack trace --- + --- End of inner exception stack trace --- + + The unit test adapter failed to connect to the data source or to read the data. For more information on troubleshooting this error, see "Troubleshooting Data-Driven Unit Tests" (http://go.microsoft.com/fwlink/?LinkId=62412) in the MSDN Library. Error details: {0} L'adattatore di unit test non è riuscito a connettersi all'origine dati o a leggere i dati. Per altre informazioni sulla risoluzione di questo errore, vedere "Risoluzione dei problemi relativi a unit test basati su dati" (http://go.microsoft.com/fwlink/?LinkId=62412) in MSDN Library. Dettagli errore: {0} + + UTA031: class {0} does not have valid TestContext property. TestContext must be of type TestContext, must be non-static, and must be public. For example: public TestContext TestContext. + UTA031: class {0} does not have valid TestContext property. TestContext must be of type TestContext, must be non-static, and must be public. For example: public TestContext TestContext. + + + + UTA007: Method {1} defined in class {0} does not have correct signature. Test method marked with the [TestMethod] attribute must be non-static, public, return-type as void and should not take any parameter. Example: public void Test.Class1.Test(). Additionally, if you are using async-await in test method then return-type must be 'Task' or 'ValueTask'. Example: public async Task Test.Class1.Test2() + UTA007: Method {1} defined in class {0} does not have correct signature. Test method marked with the [TestMethod] attribute must be non-static, public, return-type as void and should not take any parameter. Example: public void Test.Class1.Test(). Additionally, if you are using async-await in test method then return-type must be 'Task' or 'ValueTask'. Example: public async Task Test.Class1.Test2() + + + + UTA054: {0}.{1} has invalid Timeout attribute. The timeout must be an integer value greater than 0. + UTA054: {0}.{1} has invalid Timeout attribute. The timeout must be an integer value greater than 0. + + + + UTA014: {0}: Cannot define more than one method with the AssemblyCleanup attribute inside an assembly. + UTA014: {0}: Cannot define more than one method with the AssemblyCleanup attribute inside an assembly. + + + + UTA013: {0}: Cannot define more than one method with the AssemblyInitialize attribute inside an assembly. + UTA013: {0}: Cannot define more than one method with the AssemblyInitialize attribute inside an assembly. + + + + UTA026: {0}: Cannot define more than one method with the ClassCleanup attribute inside a class. + UTA026: {0}: Cannot define more than one method with the ClassCleanup attribute inside a class. + + + + UTA025: {0}: Cannot define more than one method with the ClassInitialize attribute inside a class. + UTA025: {0}: Cannot define more than one method with the ClassInitialize attribute inside a class. + + + + UTA024: {0}: Cannot define more than one method with the TestCleanup attribute. + UTA024: {0}: Cannot define more than one method with the TestCleanup attribute. + + + + UTA018: {0}: Cannot define more than one method with the TestInitialize attribute. + UTA018: {0}: Cannot define more than one method with the TestInitialize attribute. + + + + UTA001: TestClass attribute defined on non-public class {0} + UTA001: TestClass attribute defined on non-public class {0} + + + + UTA023: {0}: Cannot define predefined property {2} on method {1}. + UTA023: {0}: Cannot define predefined property {2} on method {1}. + + + + TestClass attribute defined on generic non-abstract class {0} + TestClass attribute defined on generic non-abstract class {0} + + + + UTA021: {0}: Null or empty custom property defined on method {1}. The custom property must have a valid name. + UTA021: {0}: Null or empty custom property defined on method {1}. The custom property must have a valid name. + + + + An unhandled exception was thrown by the 'Execute' method. Please report this error to the author of the attribute '{0}'. +{1} + An unhandled exception was thrown by the 'Execute' method. Please report this error to the author of the attribute '{0}'. +{1} + + + + The ExpectedException attribute defined on test method {0}.{1} threw an exception during construction. +{2} + The ExpectedException attribute defined on test method {0}.{1} threw an exception during construction. +{2} + + + + Failed to obtain the exception thrown by test method {0}.{1}. + Failed to obtain the exception thrown by test method {0}.{1}. + + + + Initialization method {0}.{1} threw exception. {2}. + Initialization method {0}.{1} threw exception. {2}. + + + + Unable to create instance of class {0}. Error: {1}. + Unable to create instance of class {0}. Error: {1}. + + + + Method {0}.{1} does not exist. + Method {0}.{1} does not exist. + + + + The test method '{0}.{1}' has multiple attributes derived from '{2}' defined on it. Only one such attribute is allowed. + The test method '{0}.{1}' has multiple attributes derived from '{2}' defined on it. Only one such attribute is allowed. + + + + Error in executing test. No result returned by extension. If using extension of TestMethodAttribute then please contact vendor. + Error in executing test. No result returned by extension. If using extension of TestMethodAttribute then please contact vendor. + + + + Cannot find a valid constructor for test class '{0}'. Valid constructors are 'public' and either parameterless or with one parameter of type 'TestContext'. + Cannot find a valid constructor for test class '{0}'. Valid constructors are 'public' and either parameterless or with one parameter of type 'TestContext'. + + + + Unable to find property {0}.TestContext. Error:{1}. + Unable to find property {0}.TestContext. Error:{1}. + + + + Unable to set TestContext property for the class {0}. Error: {1}. + Unable to set TestContext property for the class {0}. Error: {1}. + + + + The {0}.TestContext has incorrect type. + The {0}.TestContext has incorrect type. + + + + Method {0}.{1} has wrong signature. The method must be non-static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + Method {0}.{1} has wrong signature. The method must be non-static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + + + + Test method {0}.{1} threw exception: +{2} + Test method {0}.{1} threw exception: +{2} + + + + Unable to get type {0}. Error: {1}. + Unable to get type {0}. Error: {1}. + + + + The called code threw an exception that was caught, but the exception value was null + The called code threw an exception that was caught, but the exception value was null + + + + {0} For UWP projects, if you are using UI objects in test consider using [UITestMethod] attribute instead of [TestMethod] to execute test in UI thread. + {0} For UWP projects, if you are using UI objects in test consider using [UITestMethod] attribute instead of [TestMethod] to execute test in UI thread. + + + + (Failed to get the message for an exception of type {0} due to an exception.) + (Failed to get the message for an exception of type {0} due to an exception.) + + Wrong number of objects for permutation. Should be greater than zero. Il numero di oggetti non è corretto per la permutazione. Deve essere maggiore di zero. diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.ja.xlf b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.ja.xlf index 68681a9ea2..f77c60ebb2 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.ja.xlf +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.ja.xlf @@ -2,16 +2,116 @@ + + Assembly cleanup method '{0}.{1}' timed out after {2}ms + Assembly cleanup method '{0}.{1}' timed out after {2}ms + + + + Assembly cleanup method '{0}.{1}' was canceled + Assembly cleanup method '{0}.{1}' was canceled + + + + Assembly initialize method '{0}.{1}' timed out after {2}ms + Assembly initialize method '{0}.{1}' timed out after {2}ms + + + + Assembly initialize method '{0}.{1}' was canceled + Assembly initialize method '{0}.{1}' was canceled + + + + MSTestAdapterV2 + MSTestAdapterV2 + + + + Exception occurred while enumerating IDataSource attribute on "{0}.{1}": {2} + Exception occurred while enumerating IDataSource attribute on "{0}.{1}": {2} + {0}: TypeName with namespace, +{1}: Method name, +{2}: Exception details + + + Exception occurred while expanding IDataSource rows from attribute on "{0}.{1}": {2} + Exception occurred while expanding IDataSource rows from attribute on "{0}.{1}": {2} + {0}: TypeName with namespace, +{1}: Method name, +{2}: CannotExpandIDataSourceAttribute_DuplicateDisplayName or CannotExpandIDataSourceAttribute_CannotSerialize + + + Data on index {0} for "{1}" cannot be serialized. All data provided through "IDataSource" should be serializable. If you need to test non-serializable data sources, please make sure you add "TestDataSourceDiscovery" attribute on your test assembly and set the discovery option to "DuringExecution". + Data on index {0} for "{1}" cannot be serialized. All data provided through "IDataSource" should be serializable. If you need to test non-serializable data sources, please make sure you add "TestDataSourceDiscovery" attribute on your test assembly and set the discovery option to "DuringExecution". + {0}: Zero based index if an element inside of an array, +{1}: Test name + + + Display name "{2}" on indexes {0} and {1} are duplicate. Display names should be unique. + Display name "{2}" on indexes {0} and {1} are duplicate. Display names should be unique. + {0}, {1}: Zero based index if an element inside of an array +{2}: Test display name. + Could not find file '{0}'. ファイル '{0}' が見つかりませんでした。 + + Cannot run test method '{0}.{1}': Test data doesn't match method parameters. Either the count or types are different. +Test expected {2} parameter(s), with types '{3}', +but received {4} argument(s), with types '{5}'. + Cannot run test method '{0}.{1}': Test data doesn't match method parameters. Either the count or types are different. +Test expected {2} parameter(s), with types '{3}', +but received {4} argument(s), with types '{5}'. + + + + Cannot run test method '{0}.{1}': Method has parameters, but does not define any test source. Use '[DataRow]', '[DynamicData]', or a custom 'ITestDataSource' data source to provide test data. + Cannot run test method '{0}.{1}': Method has parameters, but does not define any test source. Use '[DataRow]', '[DynamicData]', or a custom 'ITestDataSource' data source to provide test data. + + + + Class cleanup method '{0}.{1}' timed out after {2}ms + Class cleanup method '{0}.{1}' timed out after {2}ms + + + + Class cleanup method '{0}.{1}' was canceled + Class cleanup method '{0}.{1}' was canceled + + + + Class initialize method '{0}.{1}' timed out after {2}ms + Class initialize method '{0}.{1}' timed out after {2}ms + + + + Class initialize method '{0}.{1}' was canceled + Class initialize method '{0}.{1}' was canceled + + The parameter should not be null or empty. パラメーターを null または空にすることはできません。 + + MSTestAdapter failed to discover tests in class '{0}' of assembly '{1}' because {2}. + MSTestAdapter failed to discover tests in class '{0}' of assembly '{1}' because {2}. + + + + {0} (Data Row {1}) + {0} (Data Row {1}) + + + + Debug Trace: + Debug Trace: + + Test Run deployment issue: Bad deployment item: '{0}': output directory '{1}' specifies the item to be deployed outside deployment root directory which is not allowed. テストの実行の配置問題です: 配置項目が正しくありません: '{0}': 出力ディレクトリ '{1}' は、項目が配置ルート ディレクトリ外に配置されるように指定していますが、それは許可されません。 @@ -77,16 +177,108 @@ 配置項目 '{0}' (出力ディレクトリ '{1}') + + [MSTest][Discovery][{0}] {1} + [MSTest][Discovery][{0}] {1} + + + + Both '.runsettings' and '.testconfig.json' files have been detected. Please select only one of these test configuration files. + Both '.runsettings' and '.testconfig.json' files have been detected. Please select only one of these test configuration files. + + + + {0}: {1} + {0}: {1} + + + + "{0}": (Failed to get exception description due to an exception of type "{1}". + "{0}": (Failed to get exception description due to an exception of type "{1}". + {0}: Type of the original exception that we're trying to get the description of. +{1}: Thrown exception + + + Exceptions thrown: + Exceptions thrown: + This is usually precedes by TestAssembly_AssemblyDiscoveryFailure message, and preceded by list of exceptions thrown in a test discovery session. + + + Test '{0}' was canceled + Test '{0}' was canceled + + + + Test '{0}' timed out after {1}ms + Test '{0}' timed out after {1}ms + + + + Getting custom attributes for type {0} threw exception (will ignore and use the reflection way): {1} + Getting custom attributes for type {0} threw exception (will ignore and use the reflection way): {1} + {0}: Attribute full type name. +{1}: Exception description + + + The type of the generic parameter '{0}' could not be inferred. + The type of the generic parameter '{0}' could not be inferred. + + + + The generic test method '{0}' doesn't have arguments, so the generic parameter cannot be inferred. + The generic test method '{0}' doesn't have arguments, so the generic parameter cannot be inferred. + + + + Found two conflicting types for generic parameter '{0}'. The conflicting types are '{1}' and '{2}'. + Found two conflicting types for generic parameter '{0}'. The conflicting types are '{1}' and '{2}'. + + + + Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. + Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. + 'ClassCleanupLifecycle' is a setting name that shouldn't be localized. + + + Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. + Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. + 'Scope' is a setting name that shouldn't be localized. + + + Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. + Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. + `Workers` is a setting name that shouldn't be localized. + + + Invalid settings '{0}'. Unexpected XmlAttribute: '{1}'. + Invalid settings '{0}'. Unexpected XmlAttribute: '{1}'. + + MSTestAdapter encountered an unexpected element '{0}' in its settings '{1}'. Remove this element and try again. MSTestAdapter で設定 '{1}' に予期しない要素 '{0}' が見つかりました。この要素を削除して、もう一度お試しください。 + + Invalid settings '{0}'. Unexpected XmlElement: '{1}'. + Invalid settings '{0}'. Unexpected XmlElement: '{1}'. + + Invalid value '{0}' for runsettings entry '{1}', setting will be ignored. runsettings エントリ '{1}' の値 '{0}' は無効です。設定は無視されます。 + + Invalid value '{0}' for runsettings entry '{1}', setting will be ignored. + Invalid value '{0}' for runsettings entry '{1}', setting will be ignored. + + + + Warning : A testsettings file or a vsmdi file is not supported with the MSTest V2 Adapter. + Warning : A testsettings file or a vsmdi file is not supported with the MSTest V2 Adapter. + + Test Run deployment issue: The assembly or module '{0}' was not found. Reason: {1} テストの実行の配置問題です: アセンブリまたはモジュール '{0}' が見つかりませんでした。理由: {1} @@ -97,21 +289,304 @@ テストの実行の配置問題です: アセンブリまたはモジュール '{0}' が見つかりませんでした。 + + An older version of MSTestV2 package is loaded in assembly, test discovery might fail to discover all data tests if they depend on `.runsettings` file. + An older version of MSTestV2 package is loaded in assembly, test discovery might fail to discover all data tests if they depend on `.runsettings` file. + + + + Runsettings entry '<ExecutionApartmentState>STA</ExecutionApartmentState>' is not supported on non-Windows OSes. + Runsettings entry '<ExecutionApartmentState>STA</ExecutionApartmentState>' is not supported on non-Windows OSes. + + + + Running tests in any of the provided sources is not supported for the selected platform + Running tests in any of the provided sources is not supported for the selected platform + + + + Failed to discover tests from assembly {0}. Reason:{1} + Failed to discover tests from assembly {0}. Reason:{1} + + + + File does not exist: {0} + File does not exist: {0} + + + + Test cleanup method '{0}.{1}' timed out after {2}ms + Test cleanup method '{0}.{1}' timed out after {2}ms + + + + Test cleanup method '{0}.{1}' was canceled + Test cleanup method '{0}.{1}' was canceled + + + + TestContext cannot be Null. + TestContext cannot be Null. + + + + TestContext Messages: + TestContext Messages: + + + + Test initialize method '{0}.{1}' timed out after {2}ms + Test initialize method '{0}.{1}' timed out after {2}ms + + + + Test initialize method '{0}.{1}' was canceled + Test initialize method '{0}.{1}' was canceled + + + + Test method {0} was not found. + Test method {0} was not found. + + + + Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) + Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) + `Workers` is a setting name that shouldn't be localized. 'Scope' is a setting name that shouldn't be localized. + {0}_{1} {2} {0}_{1} {2} + + Unable to load types from the test source '{0}'. Some or all of the tests in this source may not be discovered. +Error: {1} + Unable to load types from the test source '{0}'. Some or all of the tests in this source may not be discovered. +Error: {1} + + + + Assembly Cleanup method {0}.{1} failed. Error Message: {2}. StackTrace: {3} + Assembly Cleanup method {0}.{1} failed. Error Message: {2}. StackTrace: {3} + + + + Assembly Initialization method {0}.{1} threw exception. {2}: {3}. Aborting test execution. + Assembly Initialization method {0}.{1} threw exception. {2}: {3}. Aborting test execution. + + + + Class Cleanup method {0}.{1} failed. Error Message: {2}. Stack Trace: {3} + Class Cleanup method {0}.{1} failed. Error Message: {2}. Stack Trace: {3} + + + + Class Initialization method {0}.{1} threw exception. {2}: {3}. + Class Initialization method {0}.{1} threw exception. {2}: {3}. + + + + Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + + + + Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should take a single parameter of type TestContext. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should take a single parameter of type TestContext. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + + + + TestCleanup method {0}.{1} threw exception. {2}. + TestCleanup method {0}.{1} threw exception. {2}. + + + + Error calling Test Cleanup method for test class {0}: {1} + Error calling Test Cleanup method for test class {0}: {1} + + + + TestCleanup Stack Trace + TestCleanup Stack Trace + + Data source '{0}' cannot be found in the test configuration settings データ ソース '{0}' がテスト構成の設定に見つかりません + + --- End of inner exception stack trace --- + --- End of inner exception stack trace --- + + The unit test adapter failed to connect to the data source or to read the data. For more information on troubleshooting this error, see "Troubleshooting Data-Driven Unit Tests" (http://go.microsoft.com/fwlink/?LinkId=62412) in the MSDN Library. Error details: {0} 単体テスト アダプターがデータ ソースに接続できなかったか、データを読み取れませんでした。このエラーのトラブルシューティングの詳細については、MSDN ライブラリの「方法: データ ドリブン単体テストを作成する」(http://go.microsoft.com/fwlink/?LinkId=62412) をご覧ください。エラーの詳細: {0} + + UTA031: class {0} does not have valid TestContext property. TestContext must be of type TestContext, must be non-static, and must be public. For example: public TestContext TestContext. + UTA031: class {0} does not have valid TestContext property. TestContext must be of type TestContext, must be non-static, and must be public. For example: public TestContext TestContext. + + + + UTA007: Method {1} defined in class {0} does not have correct signature. Test method marked with the [TestMethod] attribute must be non-static, public, return-type as void and should not take any parameter. Example: public void Test.Class1.Test(). Additionally, if you are using async-await in test method then return-type must be 'Task' or 'ValueTask'. Example: public async Task Test.Class1.Test2() + UTA007: Method {1} defined in class {0} does not have correct signature. Test method marked with the [TestMethod] attribute must be non-static, public, return-type as void and should not take any parameter. Example: public void Test.Class1.Test(). Additionally, if you are using async-await in test method then return-type must be 'Task' or 'ValueTask'. Example: public async Task Test.Class1.Test2() + + + + UTA054: {0}.{1} has invalid Timeout attribute. The timeout must be an integer value greater than 0. + UTA054: {0}.{1} has invalid Timeout attribute. The timeout must be an integer value greater than 0. + + + + UTA014: {0}: Cannot define more than one method with the AssemblyCleanup attribute inside an assembly. + UTA014: {0}: Cannot define more than one method with the AssemblyCleanup attribute inside an assembly. + + + + UTA013: {0}: Cannot define more than one method with the AssemblyInitialize attribute inside an assembly. + UTA013: {0}: Cannot define more than one method with the AssemblyInitialize attribute inside an assembly. + + + + UTA026: {0}: Cannot define more than one method with the ClassCleanup attribute inside a class. + UTA026: {0}: Cannot define more than one method with the ClassCleanup attribute inside a class. + + + + UTA025: {0}: Cannot define more than one method with the ClassInitialize attribute inside a class. + UTA025: {0}: Cannot define more than one method with the ClassInitialize attribute inside a class. + + + + UTA024: {0}: Cannot define more than one method with the TestCleanup attribute. + UTA024: {0}: Cannot define more than one method with the TestCleanup attribute. + + + + UTA018: {0}: Cannot define more than one method with the TestInitialize attribute. + UTA018: {0}: Cannot define more than one method with the TestInitialize attribute. + + + + UTA001: TestClass attribute defined on non-public class {0} + UTA001: TestClass attribute defined on non-public class {0} + + + + UTA023: {0}: Cannot define predefined property {2} on method {1}. + UTA023: {0}: Cannot define predefined property {2} on method {1}. + + + + TestClass attribute defined on generic non-abstract class {0} + TestClass attribute defined on generic non-abstract class {0} + + + + UTA021: {0}: Null or empty custom property defined on method {1}. The custom property must have a valid name. + UTA021: {0}: Null or empty custom property defined on method {1}. The custom property must have a valid name. + + + + An unhandled exception was thrown by the 'Execute' method. Please report this error to the author of the attribute '{0}'. +{1} + An unhandled exception was thrown by the 'Execute' method. Please report this error to the author of the attribute '{0}'. +{1} + + + + The ExpectedException attribute defined on test method {0}.{1} threw an exception during construction. +{2} + The ExpectedException attribute defined on test method {0}.{1} threw an exception during construction. +{2} + + + + Failed to obtain the exception thrown by test method {0}.{1}. + Failed to obtain the exception thrown by test method {0}.{1}. + + + + Initialization method {0}.{1} threw exception. {2}. + Initialization method {0}.{1} threw exception. {2}. + + + + Unable to create instance of class {0}. Error: {1}. + Unable to create instance of class {0}. Error: {1}. + + + + Method {0}.{1} does not exist. + Method {0}.{1} does not exist. + + + + The test method '{0}.{1}' has multiple attributes derived from '{2}' defined on it. Only one such attribute is allowed. + The test method '{0}.{1}' has multiple attributes derived from '{2}' defined on it. Only one such attribute is allowed. + + + + Error in executing test. No result returned by extension. If using extension of TestMethodAttribute then please contact vendor. + Error in executing test. No result returned by extension. If using extension of TestMethodAttribute then please contact vendor. + + + + Cannot find a valid constructor for test class '{0}'. Valid constructors are 'public' and either parameterless or with one parameter of type 'TestContext'. + Cannot find a valid constructor for test class '{0}'. Valid constructors are 'public' and either parameterless or with one parameter of type 'TestContext'. + + + + Unable to find property {0}.TestContext. Error:{1}. + Unable to find property {0}.TestContext. Error:{1}. + + + + Unable to set TestContext property for the class {0}. Error: {1}. + Unable to set TestContext property for the class {0}. Error: {1}. + + + + The {0}.TestContext has incorrect type. + The {0}.TestContext has incorrect type. + + + + Method {0}.{1} has wrong signature. The method must be non-static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + Method {0}.{1} has wrong signature. The method must be non-static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + + + + Test method {0}.{1} threw exception: +{2} + Test method {0}.{1} threw exception: +{2} + + + + Unable to get type {0}. Error: {1}. + Unable to get type {0}. Error: {1}. + + + + The called code threw an exception that was caught, but the exception value was null + The called code threw an exception that was caught, but the exception value was null + + + + {0} For UWP projects, if you are using UI objects in test consider using [UITestMethod] attribute instead of [TestMethod] to execute test in UI thread. + {0} For UWP projects, if you are using UI objects in test consider using [UITestMethod] attribute instead of [TestMethod] to execute test in UI thread. + + + + (Failed to get the message for an exception of type {0} due to an exception.) + (Failed to get the message for an exception of type {0} due to an exception.) + + Wrong number of objects for permutation. Should be greater than zero. 順列のオブジェクト数が正しくありません。ゼロより大きくなければなりません。 diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.ko.xlf b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.ko.xlf index d602b1e260..f5f89ac3d6 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.ko.xlf +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.ko.xlf @@ -2,16 +2,116 @@ + + Assembly cleanup method '{0}.{1}' timed out after {2}ms + Assembly cleanup method '{0}.{1}' timed out after {2}ms + + + + Assembly cleanup method '{0}.{1}' was canceled + Assembly cleanup method '{0}.{1}' was canceled + + + + Assembly initialize method '{0}.{1}' timed out after {2}ms + Assembly initialize method '{0}.{1}' timed out after {2}ms + + + + Assembly initialize method '{0}.{1}' was canceled + Assembly initialize method '{0}.{1}' was canceled + + + + MSTestAdapterV2 + MSTestAdapterV2 + + + + Exception occurred while enumerating IDataSource attribute on "{0}.{1}": {2} + Exception occurred while enumerating IDataSource attribute on "{0}.{1}": {2} + {0}: TypeName with namespace, +{1}: Method name, +{2}: Exception details + + + Exception occurred while expanding IDataSource rows from attribute on "{0}.{1}": {2} + Exception occurred while expanding IDataSource rows from attribute on "{0}.{1}": {2} + {0}: TypeName with namespace, +{1}: Method name, +{2}: CannotExpandIDataSourceAttribute_DuplicateDisplayName or CannotExpandIDataSourceAttribute_CannotSerialize + + + Data on index {0} for "{1}" cannot be serialized. All data provided through "IDataSource" should be serializable. If you need to test non-serializable data sources, please make sure you add "TestDataSourceDiscovery" attribute on your test assembly and set the discovery option to "DuringExecution". + Data on index {0} for "{1}" cannot be serialized. All data provided through "IDataSource" should be serializable. If you need to test non-serializable data sources, please make sure you add "TestDataSourceDiscovery" attribute on your test assembly and set the discovery option to "DuringExecution". + {0}: Zero based index if an element inside of an array, +{1}: Test name + + + Display name "{2}" on indexes {0} and {1} are duplicate. Display names should be unique. + Display name "{2}" on indexes {0} and {1} are duplicate. Display names should be unique. + {0}, {1}: Zero based index if an element inside of an array +{2}: Test display name. + Could not find file '{0}'. '{0}' 파일을 찾을 수 없습니다. + + Cannot run test method '{0}.{1}': Test data doesn't match method parameters. Either the count or types are different. +Test expected {2} parameter(s), with types '{3}', +but received {4} argument(s), with types '{5}'. + Cannot run test method '{0}.{1}': Test data doesn't match method parameters. Either the count or types are different. +Test expected {2} parameter(s), with types '{3}', +but received {4} argument(s), with types '{5}'. + + + + Cannot run test method '{0}.{1}': Method has parameters, but does not define any test source. Use '[DataRow]', '[DynamicData]', or a custom 'ITestDataSource' data source to provide test data. + Cannot run test method '{0}.{1}': Method has parameters, but does not define any test source. Use '[DataRow]', '[DynamicData]', or a custom 'ITestDataSource' data source to provide test data. + + + + Class cleanup method '{0}.{1}' timed out after {2}ms + Class cleanup method '{0}.{1}' timed out after {2}ms + + + + Class cleanup method '{0}.{1}' was canceled + Class cleanup method '{0}.{1}' was canceled + + + + Class initialize method '{0}.{1}' timed out after {2}ms + Class initialize method '{0}.{1}' timed out after {2}ms + + + + Class initialize method '{0}.{1}' was canceled + Class initialize method '{0}.{1}' was canceled + + The parameter should not be null or empty. 매개 변수는 null이거나 비워 둘 수 없습니다. + + MSTestAdapter failed to discover tests in class '{0}' of assembly '{1}' because {2}. + MSTestAdapter failed to discover tests in class '{0}' of assembly '{1}' because {2}. + + + + {0} (Data Row {1}) + {0} (Data Row {1}) + + + + Debug Trace: + Debug Trace: + + Test Run deployment issue: Bad deployment item: '{0}': output directory '{1}' specifies the item to be deployed outside deployment root directory which is not allowed. 테스트 실행 배포 문제: 잘못된 배포 항목: '{0}': 출력 디렉터리 '{1}'에서 항목을 배포 루트 디렉터리 외부에 배포하도록 지정하며 이는 허용되지 않습니다. @@ -77,16 +177,108 @@ 배포 항목 '{0}'(출력 디렉터리 '{1}') + + [MSTest][Discovery][{0}] {1} + [MSTest][Discovery][{0}] {1} + + + + Both '.runsettings' and '.testconfig.json' files have been detected. Please select only one of these test configuration files. + Both '.runsettings' and '.testconfig.json' files have been detected. Please select only one of these test configuration files. + + + + {0}: {1} + {0}: {1} + + + + "{0}": (Failed to get exception description due to an exception of type "{1}". + "{0}": (Failed to get exception description due to an exception of type "{1}". + {0}: Type of the original exception that we're trying to get the description of. +{1}: Thrown exception + + + Exceptions thrown: + Exceptions thrown: + This is usually precedes by TestAssembly_AssemblyDiscoveryFailure message, and preceded by list of exceptions thrown in a test discovery session. + + + Test '{0}' was canceled + Test '{0}' was canceled + + + + Test '{0}' timed out after {1}ms + Test '{0}' timed out after {1}ms + + + + Getting custom attributes for type {0} threw exception (will ignore and use the reflection way): {1} + Getting custom attributes for type {0} threw exception (will ignore and use the reflection way): {1} + {0}: Attribute full type name. +{1}: Exception description + + + The type of the generic parameter '{0}' could not be inferred. + The type of the generic parameter '{0}' could not be inferred. + + + + The generic test method '{0}' doesn't have arguments, so the generic parameter cannot be inferred. + The generic test method '{0}' doesn't have arguments, so the generic parameter cannot be inferred. + + + + Found two conflicting types for generic parameter '{0}'. The conflicting types are '{1}' and '{2}'. + Found two conflicting types for generic parameter '{0}'. The conflicting types are '{1}' and '{2}'. + + + + Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. + Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. + 'ClassCleanupLifecycle' is a setting name that shouldn't be localized. + + + Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. + Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. + 'Scope' is a setting name that shouldn't be localized. + + + Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. + Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. + `Workers` is a setting name that shouldn't be localized. + + + Invalid settings '{0}'. Unexpected XmlAttribute: '{1}'. + Invalid settings '{0}'. Unexpected XmlAttribute: '{1}'. + + MSTestAdapter encountered an unexpected element '{0}' in its settings '{1}'. Remove this element and try again. MSTestAdapter의 '{1}' 설정에서 예기치 않은 요소 '{0}'이(가) 발견되었습니다. 이 요소를 제거하고 다시 시도하세요. + + Invalid settings '{0}'. Unexpected XmlElement: '{1}'. + Invalid settings '{0}'. Unexpected XmlElement: '{1}'. + + Invalid value '{0}' for runsettings entry '{1}', setting will be ignored. runsettings 항목 '{1}'에 대해 '{0}' 값이 잘못되었습니다. 설정은 무시됩니다. + + Invalid value '{0}' for runsettings entry '{1}', setting will be ignored. + Invalid value '{0}' for runsettings entry '{1}', setting will be ignored. + + + + Warning : A testsettings file or a vsmdi file is not supported with the MSTest V2 Adapter. + Warning : A testsettings file or a vsmdi file is not supported with the MSTest V2 Adapter. + + Test Run deployment issue: The assembly or module '{0}' was not found. Reason: {1} 테스트 실행 배포 문제: 어셈블리 또는 모듈 '{0}'을(를) 찾을 수 없습니다. 이유: {1} @@ -97,21 +289,304 @@ 테스트 실행 배포 문제: 어셈블리 또는 모듈 '{0}'을(를) 찾을 수 없습니다. + + An older version of MSTestV2 package is loaded in assembly, test discovery might fail to discover all data tests if they depend on `.runsettings` file. + An older version of MSTestV2 package is loaded in assembly, test discovery might fail to discover all data tests if they depend on `.runsettings` file. + + + + Runsettings entry '<ExecutionApartmentState>STA</ExecutionApartmentState>' is not supported on non-Windows OSes. + Runsettings entry '<ExecutionApartmentState>STA</ExecutionApartmentState>' is not supported on non-Windows OSes. + + + + Running tests in any of the provided sources is not supported for the selected platform + Running tests in any of the provided sources is not supported for the selected platform + + + + Failed to discover tests from assembly {0}. Reason:{1} + Failed to discover tests from assembly {0}. Reason:{1} + + + + File does not exist: {0} + File does not exist: {0} + + + + Test cleanup method '{0}.{1}' timed out after {2}ms + Test cleanup method '{0}.{1}' timed out after {2}ms + + + + Test cleanup method '{0}.{1}' was canceled + Test cleanup method '{0}.{1}' was canceled + + + + TestContext cannot be Null. + TestContext cannot be Null. + + + + TestContext Messages: + TestContext Messages: + + + + Test initialize method '{0}.{1}' timed out after {2}ms + Test initialize method '{0}.{1}' timed out after {2}ms + + + + Test initialize method '{0}.{1}' was canceled + Test initialize method '{0}.{1}' was canceled + + + + Test method {0} was not found. + Test method {0} was not found. + + + + Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) + Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) + `Workers` is a setting name that shouldn't be localized. 'Scope' is a setting name that shouldn't be localized. + {0}_{1} {2} {0}_{1} {2} + + Unable to load types from the test source '{0}'. Some or all of the tests in this source may not be discovered. +Error: {1} + Unable to load types from the test source '{0}'. Some or all of the tests in this source may not be discovered. +Error: {1} + + + + Assembly Cleanup method {0}.{1} failed. Error Message: {2}. StackTrace: {3} + Assembly Cleanup method {0}.{1} failed. Error Message: {2}. StackTrace: {3} + + + + Assembly Initialization method {0}.{1} threw exception. {2}: {3}. Aborting test execution. + Assembly Initialization method {0}.{1} threw exception. {2}: {3}. Aborting test execution. + + + + Class Cleanup method {0}.{1} failed. Error Message: {2}. Stack Trace: {3} + Class Cleanup method {0}.{1} failed. Error Message: {2}. Stack Trace: {3} + + + + Class Initialization method {0}.{1} threw exception. {2}: {3}. + Class Initialization method {0}.{1} threw exception. {2}: {3}. + + + + Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + + + + Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should take a single parameter of type TestContext. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should take a single parameter of type TestContext. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + + + + TestCleanup method {0}.{1} threw exception. {2}. + TestCleanup method {0}.{1} threw exception. {2}. + + + + Error calling Test Cleanup method for test class {0}: {1} + Error calling Test Cleanup method for test class {0}: {1} + + + + TestCleanup Stack Trace + TestCleanup Stack Trace + + Data source '{0}' cannot be found in the test configuration settings 테스트 구성 설정에서 데이터 원본 '{0}'을(를) 찾을 수 없습니다. + + --- End of inner exception stack trace --- + --- End of inner exception stack trace --- + + The unit test adapter failed to connect to the data source or to read the data. For more information on troubleshooting this error, see "Troubleshooting Data-Driven Unit Tests" (http://go.microsoft.com/fwlink/?LinkId=62412) in the MSDN Library. Error details: {0} 단위 테스트 어댑터가 데이터 원본에 연결하거나 데이터를 읽지 못했습니다. 이 오류를 해결하는 방법에 대한 자세한 내용은 MSDN 라이브러리에서 "데이터 기반 단위 테스트 문제 해결"(http://go.microsoft.com/fwlink/?LinkId=62412)을 참조하십시오. 오류 세부 정보: {0} + + UTA031: class {0} does not have valid TestContext property. TestContext must be of type TestContext, must be non-static, and must be public. For example: public TestContext TestContext. + UTA031: class {0} does not have valid TestContext property. TestContext must be of type TestContext, must be non-static, and must be public. For example: public TestContext TestContext. + + + + UTA007: Method {1} defined in class {0} does not have correct signature. Test method marked with the [TestMethod] attribute must be non-static, public, return-type as void and should not take any parameter. Example: public void Test.Class1.Test(). Additionally, if you are using async-await in test method then return-type must be 'Task' or 'ValueTask'. Example: public async Task Test.Class1.Test2() + UTA007: Method {1} defined in class {0} does not have correct signature. Test method marked with the [TestMethod] attribute must be non-static, public, return-type as void and should not take any parameter. Example: public void Test.Class1.Test(). Additionally, if you are using async-await in test method then return-type must be 'Task' or 'ValueTask'. Example: public async Task Test.Class1.Test2() + + + + UTA054: {0}.{1} has invalid Timeout attribute. The timeout must be an integer value greater than 0. + UTA054: {0}.{1} has invalid Timeout attribute. The timeout must be an integer value greater than 0. + + + + UTA014: {0}: Cannot define more than one method with the AssemblyCleanup attribute inside an assembly. + UTA014: {0}: Cannot define more than one method with the AssemblyCleanup attribute inside an assembly. + + + + UTA013: {0}: Cannot define more than one method with the AssemblyInitialize attribute inside an assembly. + UTA013: {0}: Cannot define more than one method with the AssemblyInitialize attribute inside an assembly. + + + + UTA026: {0}: Cannot define more than one method with the ClassCleanup attribute inside a class. + UTA026: {0}: Cannot define more than one method with the ClassCleanup attribute inside a class. + + + + UTA025: {0}: Cannot define more than one method with the ClassInitialize attribute inside a class. + UTA025: {0}: Cannot define more than one method with the ClassInitialize attribute inside a class. + + + + UTA024: {0}: Cannot define more than one method with the TestCleanup attribute. + UTA024: {0}: Cannot define more than one method with the TestCleanup attribute. + + + + UTA018: {0}: Cannot define more than one method with the TestInitialize attribute. + UTA018: {0}: Cannot define more than one method with the TestInitialize attribute. + + + + UTA001: TestClass attribute defined on non-public class {0} + UTA001: TestClass attribute defined on non-public class {0} + + + + UTA023: {0}: Cannot define predefined property {2} on method {1}. + UTA023: {0}: Cannot define predefined property {2} on method {1}. + + + + TestClass attribute defined on generic non-abstract class {0} + TestClass attribute defined on generic non-abstract class {0} + + + + UTA021: {0}: Null or empty custom property defined on method {1}. The custom property must have a valid name. + UTA021: {0}: Null or empty custom property defined on method {1}. The custom property must have a valid name. + + + + An unhandled exception was thrown by the 'Execute' method. Please report this error to the author of the attribute '{0}'. +{1} + An unhandled exception was thrown by the 'Execute' method. Please report this error to the author of the attribute '{0}'. +{1} + + + + The ExpectedException attribute defined on test method {0}.{1} threw an exception during construction. +{2} + The ExpectedException attribute defined on test method {0}.{1} threw an exception during construction. +{2} + + + + Failed to obtain the exception thrown by test method {0}.{1}. + Failed to obtain the exception thrown by test method {0}.{1}. + + + + Initialization method {0}.{1} threw exception. {2}. + Initialization method {0}.{1} threw exception. {2}. + + + + Unable to create instance of class {0}. Error: {1}. + Unable to create instance of class {0}. Error: {1}. + + + + Method {0}.{1} does not exist. + Method {0}.{1} does not exist. + + + + The test method '{0}.{1}' has multiple attributes derived from '{2}' defined on it. Only one such attribute is allowed. + The test method '{0}.{1}' has multiple attributes derived from '{2}' defined on it. Only one such attribute is allowed. + + + + Error in executing test. No result returned by extension. If using extension of TestMethodAttribute then please contact vendor. + Error in executing test. No result returned by extension. If using extension of TestMethodAttribute then please contact vendor. + + + + Cannot find a valid constructor for test class '{0}'. Valid constructors are 'public' and either parameterless or with one parameter of type 'TestContext'. + Cannot find a valid constructor for test class '{0}'. Valid constructors are 'public' and either parameterless or with one parameter of type 'TestContext'. + + + + Unable to find property {0}.TestContext. Error:{1}. + Unable to find property {0}.TestContext. Error:{1}. + + + + Unable to set TestContext property for the class {0}. Error: {1}. + Unable to set TestContext property for the class {0}. Error: {1}. + + + + The {0}.TestContext has incorrect type. + The {0}.TestContext has incorrect type. + + + + Method {0}.{1} has wrong signature. The method must be non-static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + Method {0}.{1} has wrong signature. The method must be non-static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + + + + Test method {0}.{1} threw exception: +{2} + Test method {0}.{1} threw exception: +{2} + + + + Unable to get type {0}. Error: {1}. + Unable to get type {0}. Error: {1}. + + + + The called code threw an exception that was caught, but the exception value was null + The called code threw an exception that was caught, but the exception value was null + + + + {0} For UWP projects, if you are using UI objects in test consider using [UITestMethod] attribute instead of [TestMethod] to execute test in UI thread. + {0} For UWP projects, if you are using UI objects in test consider using [UITestMethod] attribute instead of [TestMethod] to execute test in UI thread. + + + + (Failed to get the message for an exception of type {0} due to an exception.) + (Failed to get the message for an exception of type {0} due to an exception.) + + Wrong number of objects for permutation. Should be greater than zero. 순열의 개체 수가 잘못되었습니다. 개체 수는 0보다 커야 합니다. diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.pl.xlf b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.pl.xlf index 56730517f6..2b3586b4f4 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.pl.xlf +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.pl.xlf @@ -2,16 +2,116 @@ + + Assembly cleanup method '{0}.{1}' timed out after {2}ms + Assembly cleanup method '{0}.{1}' timed out after {2}ms + + + + Assembly cleanup method '{0}.{1}' was canceled + Assembly cleanup method '{0}.{1}' was canceled + + + + Assembly initialize method '{0}.{1}' timed out after {2}ms + Assembly initialize method '{0}.{1}' timed out after {2}ms + + + + Assembly initialize method '{0}.{1}' was canceled + Assembly initialize method '{0}.{1}' was canceled + + + + MSTestAdapterV2 + MSTestAdapterV2 + + + + Exception occurred while enumerating IDataSource attribute on "{0}.{1}": {2} + Exception occurred while enumerating IDataSource attribute on "{0}.{1}": {2} + {0}: TypeName with namespace, +{1}: Method name, +{2}: Exception details + + + Exception occurred while expanding IDataSource rows from attribute on "{0}.{1}": {2} + Exception occurred while expanding IDataSource rows from attribute on "{0}.{1}": {2} + {0}: TypeName with namespace, +{1}: Method name, +{2}: CannotExpandIDataSourceAttribute_DuplicateDisplayName or CannotExpandIDataSourceAttribute_CannotSerialize + + + Data on index {0} for "{1}" cannot be serialized. All data provided through "IDataSource" should be serializable. If you need to test non-serializable data sources, please make sure you add "TestDataSourceDiscovery" attribute on your test assembly and set the discovery option to "DuringExecution". + Data on index {0} for "{1}" cannot be serialized. All data provided through "IDataSource" should be serializable. If you need to test non-serializable data sources, please make sure you add "TestDataSourceDiscovery" attribute on your test assembly and set the discovery option to "DuringExecution". + {0}: Zero based index if an element inside of an array, +{1}: Test name + + + Display name "{2}" on indexes {0} and {1} are duplicate. Display names should be unique. + Display name "{2}" on indexes {0} and {1} are duplicate. Display names should be unique. + {0}, {1}: Zero based index if an element inside of an array +{2}: Test display name. + Could not find file '{0}'. Nie można odnaleźć pliku „{0}”. + + Cannot run test method '{0}.{1}': Test data doesn't match method parameters. Either the count or types are different. +Test expected {2} parameter(s), with types '{3}', +but received {4} argument(s), with types '{5}'. + Cannot run test method '{0}.{1}': Test data doesn't match method parameters. Either the count or types are different. +Test expected {2} parameter(s), with types '{3}', +but received {4} argument(s), with types '{5}'. + + + + Cannot run test method '{0}.{1}': Method has parameters, but does not define any test source. Use '[DataRow]', '[DynamicData]', or a custom 'ITestDataSource' data source to provide test data. + Cannot run test method '{0}.{1}': Method has parameters, but does not define any test source. Use '[DataRow]', '[DynamicData]', or a custom 'ITestDataSource' data source to provide test data. + + + + Class cleanup method '{0}.{1}' timed out after {2}ms + Class cleanup method '{0}.{1}' timed out after {2}ms + + + + Class cleanup method '{0}.{1}' was canceled + Class cleanup method '{0}.{1}' was canceled + + + + Class initialize method '{0}.{1}' timed out after {2}ms + Class initialize method '{0}.{1}' timed out after {2}ms + + + + Class initialize method '{0}.{1}' was canceled + Class initialize method '{0}.{1}' was canceled + + The parameter should not be null or empty. Parametr nie może mieć wartości null ani być pusty. + + MSTestAdapter failed to discover tests in class '{0}' of assembly '{1}' because {2}. + MSTestAdapter failed to discover tests in class '{0}' of assembly '{1}' because {2}. + + + + {0} (Data Row {1}) + {0} (Data Row {1}) + + + + Debug Trace: + Debug Trace: + + Test Run deployment issue: Bad deployment item: '{0}': output directory '{1}' specifies the item to be deployed outside deployment root directory which is not allowed. Problem wdrażania przebiegu testu: nieprawidłowy element wdrożenia: „{0}”: katalog wyjściowy „{1}” określa element do wdrożenia poza głównym katalogiem wdrożenia. Taka sytuacja jest niedozwolona. @@ -77,16 +177,108 @@ element wdrożenia „{0}” (katalog wyjściowy „{1}”) + + [MSTest][Discovery][{0}] {1} + [MSTest][Discovery][{0}] {1} + + + + Both '.runsettings' and '.testconfig.json' files have been detected. Please select only one of these test configuration files. + Both '.runsettings' and '.testconfig.json' files have been detected. Please select only one of these test configuration files. + + + + {0}: {1} + {0}: {1} + + + + "{0}": (Failed to get exception description due to an exception of type "{1}". + "{0}": (Failed to get exception description due to an exception of type "{1}". + {0}: Type of the original exception that we're trying to get the description of. +{1}: Thrown exception + + + Exceptions thrown: + Exceptions thrown: + This is usually precedes by TestAssembly_AssemblyDiscoveryFailure message, and preceded by list of exceptions thrown in a test discovery session. + + + Test '{0}' was canceled + Test '{0}' was canceled + + + + Test '{0}' timed out after {1}ms + Test '{0}' timed out after {1}ms + + + + Getting custom attributes for type {0} threw exception (will ignore and use the reflection way): {1} + Getting custom attributes for type {0} threw exception (will ignore and use the reflection way): {1} + {0}: Attribute full type name. +{1}: Exception description + + + The type of the generic parameter '{0}' could not be inferred. + The type of the generic parameter '{0}' could not be inferred. + + + + The generic test method '{0}' doesn't have arguments, so the generic parameter cannot be inferred. + The generic test method '{0}' doesn't have arguments, so the generic parameter cannot be inferred. + + + + Found two conflicting types for generic parameter '{0}'. The conflicting types are '{1}' and '{2}'. + Found two conflicting types for generic parameter '{0}'. The conflicting types are '{1}' and '{2}'. + + + + Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. + Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. + 'ClassCleanupLifecycle' is a setting name that shouldn't be localized. + + + Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. + Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. + 'Scope' is a setting name that shouldn't be localized. + + + Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. + Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. + `Workers` is a setting name that shouldn't be localized. + + + Invalid settings '{0}'. Unexpected XmlAttribute: '{1}'. + Invalid settings '{0}'. Unexpected XmlAttribute: '{1}'. + + MSTestAdapter encountered an unexpected element '{0}' in its settings '{1}'. Remove this element and try again. Adapter MSTestAdapter napotkał nieoczekiwany element „{0}” w ustawieniach „{1}”. Usuń ten element i spróbuj ponownie. + + Invalid settings '{0}'. Unexpected XmlElement: '{1}'. + Invalid settings '{0}'. Unexpected XmlElement: '{1}'. + + Invalid value '{0}' for runsettings entry '{1}', setting will be ignored. Nieprawidłowa wartość „{0}” dla wpisu runsettings „{1}”. Ustawienie zostanie zignorowane. + + Invalid value '{0}' for runsettings entry '{1}', setting will be ignored. + Invalid value '{0}' for runsettings entry '{1}', setting will be ignored. + + + + Warning : A testsettings file or a vsmdi file is not supported with the MSTest V2 Adapter. + Warning : A testsettings file or a vsmdi file is not supported with the MSTest V2 Adapter. + + Test Run deployment issue: The assembly or module '{0}' was not found. Reason: {1} Problem wdrażania przebiegu testu: nie znaleziono zestawu lub modułu „{0}”. Przyczyna: {1} @@ -97,21 +289,304 @@ Problem wdrażania przebiegu testu: nie znaleziono zestawu lub modułu „{0}”. + + An older version of MSTestV2 package is loaded in assembly, test discovery might fail to discover all data tests if they depend on `.runsettings` file. + An older version of MSTestV2 package is loaded in assembly, test discovery might fail to discover all data tests if they depend on `.runsettings` file. + + + + Runsettings entry '<ExecutionApartmentState>STA</ExecutionApartmentState>' is not supported on non-Windows OSes. + Runsettings entry '<ExecutionApartmentState>STA</ExecutionApartmentState>' is not supported on non-Windows OSes. + + + + Running tests in any of the provided sources is not supported for the selected platform + Running tests in any of the provided sources is not supported for the selected platform + + + + Failed to discover tests from assembly {0}. Reason:{1} + Failed to discover tests from assembly {0}. Reason:{1} + + + + File does not exist: {0} + File does not exist: {0} + + + + Test cleanup method '{0}.{1}' timed out after {2}ms + Test cleanup method '{0}.{1}' timed out after {2}ms + + + + Test cleanup method '{0}.{1}' was canceled + Test cleanup method '{0}.{1}' was canceled + + + + TestContext cannot be Null. + TestContext cannot be Null. + + + + TestContext Messages: + TestContext Messages: + + + + Test initialize method '{0}.{1}' timed out after {2}ms + Test initialize method '{0}.{1}' timed out after {2}ms + + + + Test initialize method '{0}.{1}' was canceled + Test initialize method '{0}.{1}' was canceled + + + + Test method {0} was not found. + Test method {0} was not found. + + + + Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) + Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) + `Workers` is a setting name that shouldn't be localized. 'Scope' is a setting name that shouldn't be localized. + {0}_{1} {2} {0}_{1} {2} + + Unable to load types from the test source '{0}'. Some or all of the tests in this source may not be discovered. +Error: {1} + Unable to load types from the test source '{0}'. Some or all of the tests in this source may not be discovered. +Error: {1} + + + + Assembly Cleanup method {0}.{1} failed. Error Message: {2}. StackTrace: {3} + Assembly Cleanup method {0}.{1} failed. Error Message: {2}. StackTrace: {3} + + + + Assembly Initialization method {0}.{1} threw exception. {2}: {3}. Aborting test execution. + Assembly Initialization method {0}.{1} threw exception. {2}: {3}. Aborting test execution. + + + + Class Cleanup method {0}.{1} failed. Error Message: {2}. Stack Trace: {3} + Class Cleanup method {0}.{1} failed. Error Message: {2}. Stack Trace: {3} + + + + Class Initialization method {0}.{1} threw exception. {2}: {3}. + Class Initialization method {0}.{1} threw exception. {2}: {3}. + + + + Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + + + + Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should take a single parameter of type TestContext. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should take a single parameter of type TestContext. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + + + + TestCleanup method {0}.{1} threw exception. {2}. + TestCleanup method {0}.{1} threw exception. {2}. + + + + Error calling Test Cleanup method for test class {0}: {1} + Error calling Test Cleanup method for test class {0}: {1} + + + + TestCleanup Stack Trace + TestCleanup Stack Trace + + Data source '{0}' cannot be found in the test configuration settings W ustawieniach konfiguracji testu nie można znaleźć źródła danych „{0}” + + --- End of inner exception stack trace --- + --- End of inner exception stack trace --- + + The unit test adapter failed to connect to the data source or to read the data. For more information on troubleshooting this error, see "Troubleshooting Data-Driven Unit Tests" (http://go.microsoft.com/fwlink/?LinkId=62412) in the MSDN Library. Error details: {0} Adapter testu jednostkowego nie mógł połączyć się ze źródłem danych lub odczytać danych. Aby uzyskać więcej informacji o rozwiązywaniu tego błędu, zobacz „Rozwiązywanie problemów z testami jednostkowymi sterowanymi danymi” (http://go.microsoft.com/fwlink/?LinkId=62412) w bibliotece MSDN. Szczegóły błędu: {0} + + UTA031: class {0} does not have valid TestContext property. TestContext must be of type TestContext, must be non-static, and must be public. For example: public TestContext TestContext. + UTA031: class {0} does not have valid TestContext property. TestContext must be of type TestContext, must be non-static, and must be public. For example: public TestContext TestContext. + + + + UTA007: Method {1} defined in class {0} does not have correct signature. Test method marked with the [TestMethod] attribute must be non-static, public, return-type as void and should not take any parameter. Example: public void Test.Class1.Test(). Additionally, if you are using async-await in test method then return-type must be 'Task' or 'ValueTask'. Example: public async Task Test.Class1.Test2() + UTA007: Method {1} defined in class {0} does not have correct signature. Test method marked with the [TestMethod] attribute must be non-static, public, return-type as void and should not take any parameter. Example: public void Test.Class1.Test(). Additionally, if you are using async-await in test method then return-type must be 'Task' or 'ValueTask'. Example: public async Task Test.Class1.Test2() + + + + UTA054: {0}.{1} has invalid Timeout attribute. The timeout must be an integer value greater than 0. + UTA054: {0}.{1} has invalid Timeout attribute. The timeout must be an integer value greater than 0. + + + + UTA014: {0}: Cannot define more than one method with the AssemblyCleanup attribute inside an assembly. + UTA014: {0}: Cannot define more than one method with the AssemblyCleanup attribute inside an assembly. + + + + UTA013: {0}: Cannot define more than one method with the AssemblyInitialize attribute inside an assembly. + UTA013: {0}: Cannot define more than one method with the AssemblyInitialize attribute inside an assembly. + + + + UTA026: {0}: Cannot define more than one method with the ClassCleanup attribute inside a class. + UTA026: {0}: Cannot define more than one method with the ClassCleanup attribute inside a class. + + + + UTA025: {0}: Cannot define more than one method with the ClassInitialize attribute inside a class. + UTA025: {0}: Cannot define more than one method with the ClassInitialize attribute inside a class. + + + + UTA024: {0}: Cannot define more than one method with the TestCleanup attribute. + UTA024: {0}: Cannot define more than one method with the TestCleanup attribute. + + + + UTA018: {0}: Cannot define more than one method with the TestInitialize attribute. + UTA018: {0}: Cannot define more than one method with the TestInitialize attribute. + + + + UTA001: TestClass attribute defined on non-public class {0} + UTA001: TestClass attribute defined on non-public class {0} + + + + UTA023: {0}: Cannot define predefined property {2} on method {1}. + UTA023: {0}: Cannot define predefined property {2} on method {1}. + + + + TestClass attribute defined on generic non-abstract class {0} + TestClass attribute defined on generic non-abstract class {0} + + + + UTA021: {0}: Null or empty custom property defined on method {1}. The custom property must have a valid name. + UTA021: {0}: Null or empty custom property defined on method {1}. The custom property must have a valid name. + + + + An unhandled exception was thrown by the 'Execute' method. Please report this error to the author of the attribute '{0}'. +{1} + An unhandled exception was thrown by the 'Execute' method. Please report this error to the author of the attribute '{0}'. +{1} + + + + The ExpectedException attribute defined on test method {0}.{1} threw an exception during construction. +{2} + The ExpectedException attribute defined on test method {0}.{1} threw an exception during construction. +{2} + + + + Failed to obtain the exception thrown by test method {0}.{1}. + Failed to obtain the exception thrown by test method {0}.{1}. + + + + Initialization method {0}.{1} threw exception. {2}. + Initialization method {0}.{1} threw exception. {2}. + + + + Unable to create instance of class {0}. Error: {1}. + Unable to create instance of class {0}. Error: {1}. + + + + Method {0}.{1} does not exist. + Method {0}.{1} does not exist. + + + + The test method '{0}.{1}' has multiple attributes derived from '{2}' defined on it. Only one such attribute is allowed. + The test method '{0}.{1}' has multiple attributes derived from '{2}' defined on it. Only one such attribute is allowed. + + + + Error in executing test. No result returned by extension. If using extension of TestMethodAttribute then please contact vendor. + Error in executing test. No result returned by extension. If using extension of TestMethodAttribute then please contact vendor. + + + + Cannot find a valid constructor for test class '{0}'. Valid constructors are 'public' and either parameterless or with one parameter of type 'TestContext'. + Cannot find a valid constructor for test class '{0}'. Valid constructors are 'public' and either parameterless or with one parameter of type 'TestContext'. + + + + Unable to find property {0}.TestContext. Error:{1}. + Unable to find property {0}.TestContext. Error:{1}. + + + + Unable to set TestContext property for the class {0}. Error: {1}. + Unable to set TestContext property for the class {0}. Error: {1}. + + + + The {0}.TestContext has incorrect type. + The {0}.TestContext has incorrect type. + + + + Method {0}.{1} has wrong signature. The method must be non-static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + Method {0}.{1} has wrong signature. The method must be non-static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + + + + Test method {0}.{1} threw exception: +{2} + Test method {0}.{1} threw exception: +{2} + + + + Unable to get type {0}. Error: {1}. + Unable to get type {0}. Error: {1}. + + + + The called code threw an exception that was caught, but the exception value was null + The called code threw an exception that was caught, but the exception value was null + + + + {0} For UWP projects, if you are using UI objects in test consider using [UITestMethod] attribute instead of [TestMethod] to execute test in UI thread. + {0} For UWP projects, if you are using UI objects in test consider using [UITestMethod] attribute instead of [TestMethod] to execute test in UI thread. + + + + (Failed to get the message for an exception of type {0} due to an exception.) + (Failed to get the message for an exception of type {0} due to an exception.) + + Wrong number of objects for permutation. Should be greater than zero. Nieprawidłowa liczba obiektów permutacji. Ta liczba powinna być większa od zera. diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.pt-BR.xlf b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.pt-BR.xlf index 613c27c07d..e3ccfc9b90 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.pt-BR.xlf +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.pt-BR.xlf @@ -2,16 +2,116 @@ + + Assembly cleanup method '{0}.{1}' timed out after {2}ms + Assembly cleanup method '{0}.{1}' timed out after {2}ms + + + + Assembly cleanup method '{0}.{1}' was canceled + Assembly cleanup method '{0}.{1}' was canceled + + + + Assembly initialize method '{0}.{1}' timed out after {2}ms + Assembly initialize method '{0}.{1}' timed out after {2}ms + + + + Assembly initialize method '{0}.{1}' was canceled + Assembly initialize method '{0}.{1}' was canceled + + + + MSTestAdapterV2 + MSTestAdapterV2 + + + + Exception occurred while enumerating IDataSource attribute on "{0}.{1}": {2} + Exception occurred while enumerating IDataSource attribute on "{0}.{1}": {2} + {0}: TypeName with namespace, +{1}: Method name, +{2}: Exception details + + + Exception occurred while expanding IDataSource rows from attribute on "{0}.{1}": {2} + Exception occurred while expanding IDataSource rows from attribute on "{0}.{1}": {2} + {0}: TypeName with namespace, +{1}: Method name, +{2}: CannotExpandIDataSourceAttribute_DuplicateDisplayName or CannotExpandIDataSourceAttribute_CannotSerialize + + + Data on index {0} for "{1}" cannot be serialized. All data provided through "IDataSource" should be serializable. If you need to test non-serializable data sources, please make sure you add "TestDataSourceDiscovery" attribute on your test assembly and set the discovery option to "DuringExecution". + Data on index {0} for "{1}" cannot be serialized. All data provided through "IDataSource" should be serializable. If you need to test non-serializable data sources, please make sure you add "TestDataSourceDiscovery" attribute on your test assembly and set the discovery option to "DuringExecution". + {0}: Zero based index if an element inside of an array, +{1}: Test name + + + Display name "{2}" on indexes {0} and {1} are duplicate. Display names should be unique. + Display name "{2}" on indexes {0} and {1} are duplicate. Display names should be unique. + {0}, {1}: Zero based index if an element inside of an array +{2}: Test display name. + Could not find file '{0}'. Não foi possível encontrar o arquivo '{0}'. + + Cannot run test method '{0}.{1}': Test data doesn't match method parameters. Either the count or types are different. +Test expected {2} parameter(s), with types '{3}', +but received {4} argument(s), with types '{5}'. + Cannot run test method '{0}.{1}': Test data doesn't match method parameters. Either the count or types are different. +Test expected {2} parameter(s), with types '{3}', +but received {4} argument(s), with types '{5}'. + + + + Cannot run test method '{0}.{1}': Method has parameters, but does not define any test source. Use '[DataRow]', '[DynamicData]', or a custom 'ITestDataSource' data source to provide test data. + Cannot run test method '{0}.{1}': Method has parameters, but does not define any test source. Use '[DataRow]', '[DynamicData]', or a custom 'ITestDataSource' data source to provide test data. + + + + Class cleanup method '{0}.{1}' timed out after {2}ms + Class cleanup method '{0}.{1}' timed out after {2}ms + + + + Class cleanup method '{0}.{1}' was canceled + Class cleanup method '{0}.{1}' was canceled + + + + Class initialize method '{0}.{1}' timed out after {2}ms + Class initialize method '{0}.{1}' timed out after {2}ms + + + + Class initialize method '{0}.{1}' was canceled + Class initialize method '{0}.{1}' was canceled + + The parameter should not be null or empty. O parâmetro não deve ser nulo ou vazio. + + MSTestAdapter failed to discover tests in class '{0}' of assembly '{1}' because {2}. + MSTestAdapter failed to discover tests in class '{0}' of assembly '{1}' because {2}. + + + + {0} (Data Row {1}) + {0} (Data Row {1}) + + + + Debug Trace: + Debug Trace: + + Test Run deployment issue: Bad deployment item: '{0}': output directory '{1}' specifies the item to be deployed outside deployment root directory which is not allowed. Problema de implantação de Execução de Teste: item de implantação inválido: '{0}': o diretório de saída '{1}' especifica o item a ser implantado fora do diretório raiz de implantação, o que não é permitido. @@ -77,16 +177,108 @@ item de implantação '{0}' (diretório de saída '{1}') + + [MSTest][Discovery][{0}] {1} + [MSTest][Discovery][{0}] {1} + + + + Both '.runsettings' and '.testconfig.json' files have been detected. Please select only one of these test configuration files. + Both '.runsettings' and '.testconfig.json' files have been detected. Please select only one of these test configuration files. + + + + {0}: {1} + {0}: {1} + + + + "{0}": (Failed to get exception description due to an exception of type "{1}". + "{0}": (Failed to get exception description due to an exception of type "{1}". + {0}: Type of the original exception that we're trying to get the description of. +{1}: Thrown exception + + + Exceptions thrown: + Exceptions thrown: + This is usually precedes by TestAssembly_AssemblyDiscoveryFailure message, and preceded by list of exceptions thrown in a test discovery session. + + + Test '{0}' was canceled + Test '{0}' was canceled + + + + Test '{0}' timed out after {1}ms + Test '{0}' timed out after {1}ms + + + + Getting custom attributes for type {0} threw exception (will ignore and use the reflection way): {1} + Getting custom attributes for type {0} threw exception (will ignore and use the reflection way): {1} + {0}: Attribute full type name. +{1}: Exception description + + + The type of the generic parameter '{0}' could not be inferred. + The type of the generic parameter '{0}' could not be inferred. + + + + The generic test method '{0}' doesn't have arguments, so the generic parameter cannot be inferred. + The generic test method '{0}' doesn't have arguments, so the generic parameter cannot be inferred. + + + + Found two conflicting types for generic parameter '{0}'. The conflicting types are '{1}' and '{2}'. + Found two conflicting types for generic parameter '{0}'. The conflicting types are '{1}' and '{2}'. + + + + Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. + Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. + 'ClassCleanupLifecycle' is a setting name that shouldn't be localized. + + + Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. + Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. + 'Scope' is a setting name that shouldn't be localized. + + + Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. + Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. + `Workers` is a setting name that shouldn't be localized. + + + Invalid settings '{0}'. Unexpected XmlAttribute: '{1}'. + Invalid settings '{0}'. Unexpected XmlAttribute: '{1}'. + + MSTestAdapter encountered an unexpected element '{0}' in its settings '{1}'. Remove this element and try again. MSTestAdapter encontrou um elemento inesperado '{0}' em suas configurações '{1}'. Remova este elemento e tente novamente. + + Invalid settings '{0}'. Unexpected XmlElement: '{1}'. + Invalid settings '{0}'. Unexpected XmlElement: '{1}'. + + Invalid value '{0}' for runsettings entry '{1}', setting will be ignored. Valor inválido "{0}" para a entrada runsettings "{1}", a configuração será ignorada. + + Invalid value '{0}' for runsettings entry '{1}', setting will be ignored. + Invalid value '{0}' for runsettings entry '{1}', setting will be ignored. + + + + Warning : A testsettings file or a vsmdi file is not supported with the MSTest V2 Adapter. + Warning : A testsettings file or a vsmdi file is not supported with the MSTest V2 Adapter. + + Test Run deployment issue: The assembly or module '{0}' was not found. Reason: {1} Problema de implantação de Execução de Teste: o assembly ou módulo '{0}' não foi encontrado. Motivo: {1} @@ -97,21 +289,304 @@ Problema de implantação de Execução de Teste: o assembly ou módulo '{0}' não foi encontrado. + + An older version of MSTestV2 package is loaded in assembly, test discovery might fail to discover all data tests if they depend on `.runsettings` file. + An older version of MSTestV2 package is loaded in assembly, test discovery might fail to discover all data tests if they depend on `.runsettings` file. + + + + Runsettings entry '<ExecutionApartmentState>STA</ExecutionApartmentState>' is not supported on non-Windows OSes. + Runsettings entry '<ExecutionApartmentState>STA</ExecutionApartmentState>' is not supported on non-Windows OSes. + + + + Running tests in any of the provided sources is not supported for the selected platform + Running tests in any of the provided sources is not supported for the selected platform + + + + Failed to discover tests from assembly {0}. Reason:{1} + Failed to discover tests from assembly {0}. Reason:{1} + + + + File does not exist: {0} + File does not exist: {0} + + + + Test cleanup method '{0}.{1}' timed out after {2}ms + Test cleanup method '{0}.{1}' timed out after {2}ms + + + + Test cleanup method '{0}.{1}' was canceled + Test cleanup method '{0}.{1}' was canceled + + + + TestContext cannot be Null. + TestContext cannot be Null. + + + + TestContext Messages: + TestContext Messages: + + + + Test initialize method '{0}.{1}' timed out after {2}ms + Test initialize method '{0}.{1}' timed out after {2}ms + + + + Test initialize method '{0}.{1}' was canceled + Test initialize method '{0}.{1}' was canceled + + + + Test method {0} was not found. + Test method {0} was not found. + + + + Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) + Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) + `Workers` is a setting name that shouldn't be localized. 'Scope' is a setting name that shouldn't be localized. + {0}_{1} {2} {0}_{1} {2} + + Unable to load types from the test source '{0}'. Some or all of the tests in this source may not be discovered. +Error: {1} + Unable to load types from the test source '{0}'. Some or all of the tests in this source may not be discovered. +Error: {1} + + + + Assembly Cleanup method {0}.{1} failed. Error Message: {2}. StackTrace: {3} + Assembly Cleanup method {0}.{1} failed. Error Message: {2}. StackTrace: {3} + + + + Assembly Initialization method {0}.{1} threw exception. {2}: {3}. Aborting test execution. + Assembly Initialization method {0}.{1} threw exception. {2}: {3}. Aborting test execution. + + + + Class Cleanup method {0}.{1} failed. Error Message: {2}. Stack Trace: {3} + Class Cleanup method {0}.{1} failed. Error Message: {2}. Stack Trace: {3} + + + + Class Initialization method {0}.{1} threw exception. {2}: {3}. + Class Initialization method {0}.{1} threw exception. {2}: {3}. + + + + Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + + + + Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should take a single parameter of type TestContext. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should take a single parameter of type TestContext. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + + + + TestCleanup method {0}.{1} threw exception. {2}. + TestCleanup method {0}.{1} threw exception. {2}. + + + + Error calling Test Cleanup method for test class {0}: {1} + Error calling Test Cleanup method for test class {0}: {1} + + + + TestCleanup Stack Trace + TestCleanup Stack Trace + + Data source '{0}' cannot be found in the test configuration settings A fonte de dados '{0}' não pode ser encontrada nas configurações de teste + + --- End of inner exception stack trace --- + --- End of inner exception stack trace --- + + The unit test adapter failed to connect to the data source or to read the data. For more information on troubleshooting this error, see "Troubleshooting Data-Driven Unit Tests" (http://go.microsoft.com/fwlink/?LinkId=62412) in the MSDN Library. Error details: {0} O adaptador de teste de unidade falhou ao conectar-se à fonte de dados ou ao ler os dados. Para obter mais informações sobre como solucionar esse erro, consulte "Solucionando Problemas em Testes de Unidade Controlados por Dados" (http://go.microsoft.com/fwlink/?LinkId=62412) na Biblioteca do MSDN. Detalhes do erro: {0} + + UTA031: class {0} does not have valid TestContext property. TestContext must be of type TestContext, must be non-static, and must be public. For example: public TestContext TestContext. + UTA031: class {0} does not have valid TestContext property. TestContext must be of type TestContext, must be non-static, and must be public. For example: public TestContext TestContext. + + + + UTA007: Method {1} defined in class {0} does not have correct signature. Test method marked with the [TestMethod] attribute must be non-static, public, return-type as void and should not take any parameter. Example: public void Test.Class1.Test(). Additionally, if you are using async-await in test method then return-type must be 'Task' or 'ValueTask'. Example: public async Task Test.Class1.Test2() + UTA007: Method {1} defined in class {0} does not have correct signature. Test method marked with the [TestMethod] attribute must be non-static, public, return-type as void and should not take any parameter. Example: public void Test.Class1.Test(). Additionally, if you are using async-await in test method then return-type must be 'Task' or 'ValueTask'. Example: public async Task Test.Class1.Test2() + + + + UTA054: {0}.{1} has invalid Timeout attribute. The timeout must be an integer value greater than 0. + UTA054: {0}.{1} has invalid Timeout attribute. The timeout must be an integer value greater than 0. + + + + UTA014: {0}: Cannot define more than one method with the AssemblyCleanup attribute inside an assembly. + UTA014: {0}: Cannot define more than one method with the AssemblyCleanup attribute inside an assembly. + + + + UTA013: {0}: Cannot define more than one method with the AssemblyInitialize attribute inside an assembly. + UTA013: {0}: Cannot define more than one method with the AssemblyInitialize attribute inside an assembly. + + + + UTA026: {0}: Cannot define more than one method with the ClassCleanup attribute inside a class. + UTA026: {0}: Cannot define more than one method with the ClassCleanup attribute inside a class. + + + + UTA025: {0}: Cannot define more than one method with the ClassInitialize attribute inside a class. + UTA025: {0}: Cannot define more than one method with the ClassInitialize attribute inside a class. + + + + UTA024: {0}: Cannot define more than one method with the TestCleanup attribute. + UTA024: {0}: Cannot define more than one method with the TestCleanup attribute. + + + + UTA018: {0}: Cannot define more than one method with the TestInitialize attribute. + UTA018: {0}: Cannot define more than one method with the TestInitialize attribute. + + + + UTA001: TestClass attribute defined on non-public class {0} + UTA001: TestClass attribute defined on non-public class {0} + + + + UTA023: {0}: Cannot define predefined property {2} on method {1}. + UTA023: {0}: Cannot define predefined property {2} on method {1}. + + + + TestClass attribute defined on generic non-abstract class {0} + TestClass attribute defined on generic non-abstract class {0} + + + + UTA021: {0}: Null or empty custom property defined on method {1}. The custom property must have a valid name. + UTA021: {0}: Null or empty custom property defined on method {1}. The custom property must have a valid name. + + + + An unhandled exception was thrown by the 'Execute' method. Please report this error to the author of the attribute '{0}'. +{1} + An unhandled exception was thrown by the 'Execute' method. Please report this error to the author of the attribute '{0}'. +{1} + + + + The ExpectedException attribute defined on test method {0}.{1} threw an exception during construction. +{2} + The ExpectedException attribute defined on test method {0}.{1} threw an exception during construction. +{2} + + + + Failed to obtain the exception thrown by test method {0}.{1}. + Failed to obtain the exception thrown by test method {0}.{1}. + + + + Initialization method {0}.{1} threw exception. {2}. + Initialization method {0}.{1} threw exception. {2}. + + + + Unable to create instance of class {0}. Error: {1}. + Unable to create instance of class {0}. Error: {1}. + + + + Method {0}.{1} does not exist. + Method {0}.{1} does not exist. + + + + The test method '{0}.{1}' has multiple attributes derived from '{2}' defined on it. Only one such attribute is allowed. + The test method '{0}.{1}' has multiple attributes derived from '{2}' defined on it. Only one such attribute is allowed. + + + + Error in executing test. No result returned by extension. If using extension of TestMethodAttribute then please contact vendor. + Error in executing test. No result returned by extension. If using extension of TestMethodAttribute then please contact vendor. + + + + Cannot find a valid constructor for test class '{0}'. Valid constructors are 'public' and either parameterless or with one parameter of type 'TestContext'. + Cannot find a valid constructor for test class '{0}'. Valid constructors are 'public' and either parameterless or with one parameter of type 'TestContext'. + + + + Unable to find property {0}.TestContext. Error:{1}. + Unable to find property {0}.TestContext. Error:{1}. + + + + Unable to set TestContext property for the class {0}. Error: {1}. + Unable to set TestContext property for the class {0}. Error: {1}. + + + + The {0}.TestContext has incorrect type. + The {0}.TestContext has incorrect type. + + + + Method {0}.{1} has wrong signature. The method must be non-static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + Method {0}.{1} has wrong signature. The method must be non-static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + + + + Test method {0}.{1} threw exception: +{2} + Test method {0}.{1} threw exception: +{2} + + + + Unable to get type {0}. Error: {1}. + Unable to get type {0}. Error: {1}. + + + + The called code threw an exception that was caught, but the exception value was null + The called code threw an exception that was caught, but the exception value was null + + + + {0} For UWP projects, if you are using UI objects in test consider using [UITestMethod] attribute instead of [TestMethod] to execute test in UI thread. + {0} For UWP projects, if you are using UI objects in test consider using [UITestMethod] attribute instead of [TestMethod] to execute test in UI thread. + + + + (Failed to get the message for an exception of type {0} due to an exception.) + (Failed to get the message for an exception of type {0} due to an exception.) + + Wrong number of objects for permutation. Should be greater than zero. Número incorreto de objetos para permutação. Deve ser maior que zero. diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.ru.xlf b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.ru.xlf index adadbea84e..bb50ff73ac 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.ru.xlf +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.ru.xlf @@ -2,16 +2,116 @@ + + Assembly cleanup method '{0}.{1}' timed out after {2}ms + Assembly cleanup method '{0}.{1}' timed out after {2}ms + + + + Assembly cleanup method '{0}.{1}' was canceled + Assembly cleanup method '{0}.{1}' was canceled + + + + Assembly initialize method '{0}.{1}' timed out after {2}ms + Assembly initialize method '{0}.{1}' timed out after {2}ms + + + + Assembly initialize method '{0}.{1}' was canceled + Assembly initialize method '{0}.{1}' was canceled + + + + MSTestAdapterV2 + MSTestAdapterV2 + + + + Exception occurred while enumerating IDataSource attribute on "{0}.{1}": {2} + Exception occurred while enumerating IDataSource attribute on "{0}.{1}": {2} + {0}: TypeName with namespace, +{1}: Method name, +{2}: Exception details + + + Exception occurred while expanding IDataSource rows from attribute on "{0}.{1}": {2} + Exception occurred while expanding IDataSource rows from attribute on "{0}.{1}": {2} + {0}: TypeName with namespace, +{1}: Method name, +{2}: CannotExpandIDataSourceAttribute_DuplicateDisplayName or CannotExpandIDataSourceAttribute_CannotSerialize + + + Data on index {0} for "{1}" cannot be serialized. All data provided through "IDataSource" should be serializable. If you need to test non-serializable data sources, please make sure you add "TestDataSourceDiscovery" attribute on your test assembly and set the discovery option to "DuringExecution". + Data on index {0} for "{1}" cannot be serialized. All data provided through "IDataSource" should be serializable. If you need to test non-serializable data sources, please make sure you add "TestDataSourceDiscovery" attribute on your test assembly and set the discovery option to "DuringExecution". + {0}: Zero based index if an element inside of an array, +{1}: Test name + + + Display name "{2}" on indexes {0} and {1} are duplicate. Display names should be unique. + Display name "{2}" on indexes {0} and {1} are duplicate. Display names should be unique. + {0}, {1}: Zero based index if an element inside of an array +{2}: Test display name. + Could not find file '{0}'. Не удалось найти файл "{0}". + + Cannot run test method '{0}.{1}': Test data doesn't match method parameters. Either the count or types are different. +Test expected {2} parameter(s), with types '{3}', +but received {4} argument(s), with types '{5}'. + Cannot run test method '{0}.{1}': Test data doesn't match method parameters. Either the count or types are different. +Test expected {2} parameter(s), with types '{3}', +but received {4} argument(s), with types '{5}'. + + + + Cannot run test method '{0}.{1}': Method has parameters, but does not define any test source. Use '[DataRow]', '[DynamicData]', or a custom 'ITestDataSource' data source to provide test data. + Cannot run test method '{0}.{1}': Method has parameters, but does not define any test source. Use '[DataRow]', '[DynamicData]', or a custom 'ITestDataSource' data source to provide test data. + + + + Class cleanup method '{0}.{1}' timed out after {2}ms + Class cleanup method '{0}.{1}' timed out after {2}ms + + + + Class cleanup method '{0}.{1}' was canceled + Class cleanup method '{0}.{1}' was canceled + + + + Class initialize method '{0}.{1}' timed out after {2}ms + Class initialize method '{0}.{1}' timed out after {2}ms + + + + Class initialize method '{0}.{1}' was canceled + Class initialize method '{0}.{1}' was canceled + + The parameter should not be null or empty. Этот параметр не должен быть пустым или иметь значение NULL. + + MSTestAdapter failed to discover tests in class '{0}' of assembly '{1}' because {2}. + MSTestAdapter failed to discover tests in class '{0}' of assembly '{1}' because {2}. + + + + {0} (Data Row {1}) + {0} (Data Row {1}) + + + + Debug Trace: + Debug Trace: + + Test Run deployment issue: Bad deployment item: '{0}': output directory '{1}' specifies the item to be deployed outside deployment root directory which is not allowed. Ошибка развертывания при тестовом запуске: недопустимый элемент развертывания "{0}". В выходном каталоге "{1}" указано, что развертывание этого элемента должно быть выполнено не в корневом каталоге развертывания, что запрещено. @@ -77,16 +177,108 @@ элемент развертывания "{0}" (выходной каталог "{1}") + + [MSTest][Discovery][{0}] {1} + [MSTest][Discovery][{0}] {1} + + + + Both '.runsettings' and '.testconfig.json' files have been detected. Please select only one of these test configuration files. + Both '.runsettings' and '.testconfig.json' files have been detected. Please select only one of these test configuration files. + + + + {0}: {1} + {0}: {1} + + + + "{0}": (Failed to get exception description due to an exception of type "{1}". + "{0}": (Failed to get exception description due to an exception of type "{1}". + {0}: Type of the original exception that we're trying to get the description of. +{1}: Thrown exception + + + Exceptions thrown: + Exceptions thrown: + This is usually precedes by TestAssembly_AssemblyDiscoveryFailure message, and preceded by list of exceptions thrown in a test discovery session. + + + Test '{0}' was canceled + Test '{0}' was canceled + + + + Test '{0}' timed out after {1}ms + Test '{0}' timed out after {1}ms + + + + Getting custom attributes for type {0} threw exception (will ignore and use the reflection way): {1} + Getting custom attributes for type {0} threw exception (will ignore and use the reflection way): {1} + {0}: Attribute full type name. +{1}: Exception description + + + The type of the generic parameter '{0}' could not be inferred. + The type of the generic parameter '{0}' could not be inferred. + + + + The generic test method '{0}' doesn't have arguments, so the generic parameter cannot be inferred. + The generic test method '{0}' doesn't have arguments, so the generic parameter cannot be inferred. + + + + Found two conflicting types for generic parameter '{0}'. The conflicting types are '{1}' and '{2}'. + Found two conflicting types for generic parameter '{0}'. The conflicting types are '{1}' and '{2}'. + + + + Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. + Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. + 'ClassCleanupLifecycle' is a setting name that shouldn't be localized. + + + Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. + Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. + 'Scope' is a setting name that shouldn't be localized. + + + Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. + Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. + `Workers` is a setting name that shouldn't be localized. + + + Invalid settings '{0}'. Unexpected XmlAttribute: '{1}'. + Invalid settings '{0}'. Unexpected XmlAttribute: '{1}'. + + MSTestAdapter encountered an unexpected element '{0}' in its settings '{1}'. Remove this element and try again. MSTestAdapter обнаружил непредвиденный элемент "{0}" в параметрах "{1}". Удалите этот элемент и повторите попытку. + + Invalid settings '{0}'. Unexpected XmlElement: '{1}'. + Invalid settings '{0}'. Unexpected XmlElement: '{1}'. + + Invalid value '{0}' for runsettings entry '{1}', setting will be ignored. Недопустимое значение "{0}" для записи runsettings "{1}", параметр будет пропущен. + + Invalid value '{0}' for runsettings entry '{1}', setting will be ignored. + Invalid value '{0}' for runsettings entry '{1}', setting will be ignored. + + + + Warning : A testsettings file or a vsmdi file is not supported with the MSTest V2 Adapter. + Warning : A testsettings file or a vsmdi file is not supported with the MSTest V2 Adapter. + + Test Run deployment issue: The assembly or module '{0}' was not found. Reason: {1} Ошибка развертывания тестового запуска: не удалось найти сборку или модуль "{0}". Причина: {1} @@ -97,21 +289,304 @@ Ошибка развертывания тестового запуска: не удалось найти сборку или модуль "{0}". + + An older version of MSTestV2 package is loaded in assembly, test discovery might fail to discover all data tests if they depend on `.runsettings` file. + An older version of MSTestV2 package is loaded in assembly, test discovery might fail to discover all data tests if they depend on `.runsettings` file. + + + + Runsettings entry '<ExecutionApartmentState>STA</ExecutionApartmentState>' is not supported on non-Windows OSes. + Runsettings entry '<ExecutionApartmentState>STA</ExecutionApartmentState>' is not supported on non-Windows OSes. + + + + Running tests in any of the provided sources is not supported for the selected platform + Running tests in any of the provided sources is not supported for the selected platform + + + + Failed to discover tests from assembly {0}. Reason:{1} + Failed to discover tests from assembly {0}. Reason:{1} + + + + File does not exist: {0} + File does not exist: {0} + + + + Test cleanup method '{0}.{1}' timed out after {2}ms + Test cleanup method '{0}.{1}' timed out after {2}ms + + + + Test cleanup method '{0}.{1}' was canceled + Test cleanup method '{0}.{1}' was canceled + + + + TestContext cannot be Null. + TestContext cannot be Null. + + + + TestContext Messages: + TestContext Messages: + + + + Test initialize method '{0}.{1}' timed out after {2}ms + Test initialize method '{0}.{1}' timed out after {2}ms + + + + Test initialize method '{0}.{1}' was canceled + Test initialize method '{0}.{1}' was canceled + + + + Test method {0} was not found. + Test method {0} was not found. + + + + Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) + Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) + `Workers` is a setting name that shouldn't be localized. 'Scope' is a setting name that shouldn't be localized. + {0}_{1} {2} {0}_{1} {2} + + Unable to load types from the test source '{0}'. Some or all of the tests in this source may not be discovered. +Error: {1} + Unable to load types from the test source '{0}'. Some or all of the tests in this source may not be discovered. +Error: {1} + + + + Assembly Cleanup method {0}.{1} failed. Error Message: {2}. StackTrace: {3} + Assembly Cleanup method {0}.{1} failed. Error Message: {2}. StackTrace: {3} + + + + Assembly Initialization method {0}.{1} threw exception. {2}: {3}. Aborting test execution. + Assembly Initialization method {0}.{1} threw exception. {2}: {3}. Aborting test execution. + + + + Class Cleanup method {0}.{1} failed. Error Message: {2}. Stack Trace: {3} + Class Cleanup method {0}.{1} failed. Error Message: {2}. Stack Trace: {3} + + + + Class Initialization method {0}.{1} threw exception. {2}: {3}. + Class Initialization method {0}.{1} threw exception. {2}: {3}. + + + + Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + + + + Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should take a single parameter of type TestContext. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should take a single parameter of type TestContext. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + + + + TestCleanup method {0}.{1} threw exception. {2}. + TestCleanup method {0}.{1} threw exception. {2}. + + + + Error calling Test Cleanup method for test class {0}: {1} + Error calling Test Cleanup method for test class {0}: {1} + + + + TestCleanup Stack Trace + TestCleanup Stack Trace + + Data source '{0}' cannot be found in the test configuration settings Не удалось найти источник данных "{0}" в параметрах конфигурации теста + + --- End of inner exception stack trace --- + --- End of inner exception stack trace --- + + The unit test adapter failed to connect to the data source or to read the data. For more information on troubleshooting this error, see "Troubleshooting Data-Driven Unit Tests" (http://go.microsoft.com/fwlink/?LinkId=62412) in the MSDN Library. Error details: {0} Адаптеру модульных тестов не удалось подключиться к источнику данных, чтобы считать данные. Дополнительные сведения об устранении этой ошибки см. в разделе "Устранение неполадок в модульных тестах на основе данных" (http://go.microsoft.com/fwlink/?LinkId=62412) в библиотеке MSDN. Подробности об ошибке: {0} + + UTA031: class {0} does not have valid TestContext property. TestContext must be of type TestContext, must be non-static, and must be public. For example: public TestContext TestContext. + UTA031: class {0} does not have valid TestContext property. TestContext must be of type TestContext, must be non-static, and must be public. For example: public TestContext TestContext. + + + + UTA007: Method {1} defined in class {0} does not have correct signature. Test method marked with the [TestMethod] attribute must be non-static, public, return-type as void and should not take any parameter. Example: public void Test.Class1.Test(). Additionally, if you are using async-await in test method then return-type must be 'Task' or 'ValueTask'. Example: public async Task Test.Class1.Test2() + UTA007: Method {1} defined in class {0} does not have correct signature. Test method marked with the [TestMethod] attribute must be non-static, public, return-type as void and should not take any parameter. Example: public void Test.Class1.Test(). Additionally, if you are using async-await in test method then return-type must be 'Task' or 'ValueTask'. Example: public async Task Test.Class1.Test2() + + + + UTA054: {0}.{1} has invalid Timeout attribute. The timeout must be an integer value greater than 0. + UTA054: {0}.{1} has invalid Timeout attribute. The timeout must be an integer value greater than 0. + + + + UTA014: {0}: Cannot define more than one method with the AssemblyCleanup attribute inside an assembly. + UTA014: {0}: Cannot define more than one method with the AssemblyCleanup attribute inside an assembly. + + + + UTA013: {0}: Cannot define more than one method with the AssemblyInitialize attribute inside an assembly. + UTA013: {0}: Cannot define more than one method with the AssemblyInitialize attribute inside an assembly. + + + + UTA026: {0}: Cannot define more than one method with the ClassCleanup attribute inside a class. + UTA026: {0}: Cannot define more than one method with the ClassCleanup attribute inside a class. + + + + UTA025: {0}: Cannot define more than one method with the ClassInitialize attribute inside a class. + UTA025: {0}: Cannot define more than one method with the ClassInitialize attribute inside a class. + + + + UTA024: {0}: Cannot define more than one method with the TestCleanup attribute. + UTA024: {0}: Cannot define more than one method with the TestCleanup attribute. + + + + UTA018: {0}: Cannot define more than one method with the TestInitialize attribute. + UTA018: {0}: Cannot define more than one method with the TestInitialize attribute. + + + + UTA001: TestClass attribute defined on non-public class {0} + UTA001: TestClass attribute defined on non-public class {0} + + + + UTA023: {0}: Cannot define predefined property {2} on method {1}. + UTA023: {0}: Cannot define predefined property {2} on method {1}. + + + + TestClass attribute defined on generic non-abstract class {0} + TestClass attribute defined on generic non-abstract class {0} + + + + UTA021: {0}: Null or empty custom property defined on method {1}. The custom property must have a valid name. + UTA021: {0}: Null or empty custom property defined on method {1}. The custom property must have a valid name. + + + + An unhandled exception was thrown by the 'Execute' method. Please report this error to the author of the attribute '{0}'. +{1} + An unhandled exception was thrown by the 'Execute' method. Please report this error to the author of the attribute '{0}'. +{1} + + + + The ExpectedException attribute defined on test method {0}.{1} threw an exception during construction. +{2} + The ExpectedException attribute defined on test method {0}.{1} threw an exception during construction. +{2} + + + + Failed to obtain the exception thrown by test method {0}.{1}. + Failed to obtain the exception thrown by test method {0}.{1}. + + + + Initialization method {0}.{1} threw exception. {2}. + Initialization method {0}.{1} threw exception. {2}. + + + + Unable to create instance of class {0}. Error: {1}. + Unable to create instance of class {0}. Error: {1}. + + + + Method {0}.{1} does not exist. + Method {0}.{1} does not exist. + + + + The test method '{0}.{1}' has multiple attributes derived from '{2}' defined on it. Only one such attribute is allowed. + The test method '{0}.{1}' has multiple attributes derived from '{2}' defined on it. Only one such attribute is allowed. + + + + Error in executing test. No result returned by extension. If using extension of TestMethodAttribute then please contact vendor. + Error in executing test. No result returned by extension. If using extension of TestMethodAttribute then please contact vendor. + + + + Cannot find a valid constructor for test class '{0}'. Valid constructors are 'public' and either parameterless or with one parameter of type 'TestContext'. + Cannot find a valid constructor for test class '{0}'. Valid constructors are 'public' and either parameterless or with one parameter of type 'TestContext'. + + + + Unable to find property {0}.TestContext. Error:{1}. + Unable to find property {0}.TestContext. Error:{1}. + + + + Unable to set TestContext property for the class {0}. Error: {1}. + Unable to set TestContext property for the class {0}. Error: {1}. + + + + The {0}.TestContext has incorrect type. + The {0}.TestContext has incorrect type. + + + + Method {0}.{1} has wrong signature. The method must be non-static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + Method {0}.{1} has wrong signature. The method must be non-static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + + + + Test method {0}.{1} threw exception: +{2} + Test method {0}.{1} threw exception: +{2} + + + + Unable to get type {0}. Error: {1}. + Unable to get type {0}. Error: {1}. + + + + The called code threw an exception that was caught, but the exception value was null + The called code threw an exception that was caught, but the exception value was null + + + + {0} For UWP projects, if you are using UI objects in test consider using [UITestMethod] attribute instead of [TestMethod] to execute test in UI thread. + {0} For UWP projects, if you are using UI objects in test consider using [UITestMethod] attribute instead of [TestMethod] to execute test in UI thread. + + + + (Failed to get the message for an exception of type {0} due to an exception.) + (Failed to get the message for an exception of type {0} due to an exception.) + + Wrong number of objects for permutation. Should be greater than zero. Неправильное число объектов для перестановки. Оно должно быть больше нуля. diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.tr.xlf b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.tr.xlf index 79d35b165a..e63490a10a 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.tr.xlf +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.tr.xlf @@ -2,16 +2,116 @@ + + Assembly cleanup method '{0}.{1}' timed out after {2}ms + Assembly cleanup method '{0}.{1}' timed out after {2}ms + + + + Assembly cleanup method '{0}.{1}' was canceled + Assembly cleanup method '{0}.{1}' was canceled + + + + Assembly initialize method '{0}.{1}' timed out after {2}ms + Assembly initialize method '{0}.{1}' timed out after {2}ms + + + + Assembly initialize method '{0}.{1}' was canceled + Assembly initialize method '{0}.{1}' was canceled + + + + MSTestAdapterV2 + MSTestAdapterV2 + + + + Exception occurred while enumerating IDataSource attribute on "{0}.{1}": {2} + Exception occurred while enumerating IDataSource attribute on "{0}.{1}": {2} + {0}: TypeName with namespace, +{1}: Method name, +{2}: Exception details + + + Exception occurred while expanding IDataSource rows from attribute on "{0}.{1}": {2} + Exception occurred while expanding IDataSource rows from attribute on "{0}.{1}": {2} + {0}: TypeName with namespace, +{1}: Method name, +{2}: CannotExpandIDataSourceAttribute_DuplicateDisplayName or CannotExpandIDataSourceAttribute_CannotSerialize + + + Data on index {0} for "{1}" cannot be serialized. All data provided through "IDataSource" should be serializable. If you need to test non-serializable data sources, please make sure you add "TestDataSourceDiscovery" attribute on your test assembly and set the discovery option to "DuringExecution". + Data on index {0} for "{1}" cannot be serialized. All data provided through "IDataSource" should be serializable. If you need to test non-serializable data sources, please make sure you add "TestDataSourceDiscovery" attribute on your test assembly and set the discovery option to "DuringExecution". + {0}: Zero based index if an element inside of an array, +{1}: Test name + + + Display name "{2}" on indexes {0} and {1} are duplicate. Display names should be unique. + Display name "{2}" on indexes {0} and {1} are duplicate. Display names should be unique. + {0}, {1}: Zero based index if an element inside of an array +{2}: Test display name. + Could not find file '{0}'. '{0}' adlı dosya bulunamadı. + + Cannot run test method '{0}.{1}': Test data doesn't match method parameters. Either the count or types are different. +Test expected {2} parameter(s), with types '{3}', +but received {4} argument(s), with types '{5}'. + Cannot run test method '{0}.{1}': Test data doesn't match method parameters. Either the count or types are different. +Test expected {2} parameter(s), with types '{3}', +but received {4} argument(s), with types '{5}'. + + + + Cannot run test method '{0}.{1}': Method has parameters, but does not define any test source. Use '[DataRow]', '[DynamicData]', or a custom 'ITestDataSource' data source to provide test data. + Cannot run test method '{0}.{1}': Method has parameters, but does not define any test source. Use '[DataRow]', '[DynamicData]', or a custom 'ITestDataSource' data source to provide test data. + + + + Class cleanup method '{0}.{1}' timed out after {2}ms + Class cleanup method '{0}.{1}' timed out after {2}ms + + + + Class cleanup method '{0}.{1}' was canceled + Class cleanup method '{0}.{1}' was canceled + + + + Class initialize method '{0}.{1}' timed out after {2}ms + Class initialize method '{0}.{1}' timed out after {2}ms + + + + Class initialize method '{0}.{1}' was canceled + Class initialize method '{0}.{1}' was canceled + + The parameter should not be null or empty. Parametre null veya boş olmamalıdır. + + MSTestAdapter failed to discover tests in class '{0}' of assembly '{1}' because {2}. + MSTestAdapter failed to discover tests in class '{0}' of assembly '{1}' because {2}. + + + + {0} (Data Row {1}) + {0} (Data Row {1}) + + + + Debug Trace: + Debug Trace: + + Test Run deployment issue: Bad deployment item: '{0}': output directory '{1}' specifies the item to be deployed outside deployment root directory which is not allowed. Test Çalıştırması dağıtım sorunu: '{0}' dağıtım öğesi hatalı: '{1}' çıktı dizininde öğenin dağıtım kök dizini dışında dağıtılması gerektiği belirtilmiş, ancak buna izin verilmiyor. @@ -77,16 +177,108 @@ '{0}' dağıtım öğesi (çıktı dizini '{1}') + + [MSTest][Discovery][{0}] {1} + [MSTest][Discovery][{0}] {1} + + + + Both '.runsettings' and '.testconfig.json' files have been detected. Please select only one of these test configuration files. + Both '.runsettings' and '.testconfig.json' files have been detected. Please select only one of these test configuration files. + + + + {0}: {1} + {0}: {1} + + + + "{0}": (Failed to get exception description due to an exception of type "{1}". + "{0}": (Failed to get exception description due to an exception of type "{1}". + {0}: Type of the original exception that we're trying to get the description of. +{1}: Thrown exception + + + Exceptions thrown: + Exceptions thrown: + This is usually precedes by TestAssembly_AssemblyDiscoveryFailure message, and preceded by list of exceptions thrown in a test discovery session. + + + Test '{0}' was canceled + Test '{0}' was canceled + + + + Test '{0}' timed out after {1}ms + Test '{0}' timed out after {1}ms + + + + Getting custom attributes for type {0} threw exception (will ignore and use the reflection way): {1} + Getting custom attributes for type {0} threw exception (will ignore and use the reflection way): {1} + {0}: Attribute full type name. +{1}: Exception description + + + The type of the generic parameter '{0}' could not be inferred. + The type of the generic parameter '{0}' could not be inferred. + + + + The generic test method '{0}' doesn't have arguments, so the generic parameter cannot be inferred. + The generic test method '{0}' doesn't have arguments, so the generic parameter cannot be inferred. + + + + Found two conflicting types for generic parameter '{0}'. The conflicting types are '{1}' and '{2}'. + Found two conflicting types for generic parameter '{0}'. The conflicting types are '{1}' and '{2}'. + + + + Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. + Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. + 'ClassCleanupLifecycle' is a setting name that shouldn't be localized. + + + Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. + Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. + 'Scope' is a setting name that shouldn't be localized. + + + Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. + Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. + `Workers` is a setting name that shouldn't be localized. + + + Invalid settings '{0}'. Unexpected XmlAttribute: '{1}'. + Invalid settings '{0}'. Unexpected XmlAttribute: '{1}'. + + MSTestAdapter encountered an unexpected element '{0}' in its settings '{1}'. Remove this element and try again. MSTestAdapter, '{1}' ayarlarında beklenmedik bir öğeyle ('{0}') karşılaştı. Bu öğeyi kaldırıp yeniden deneyin. + + Invalid settings '{0}'. Unexpected XmlElement: '{1}'. + Invalid settings '{0}'. Unexpected XmlElement: '{1}'. + + Invalid value '{0}' for runsettings entry '{1}', setting will be ignored. '{1}' çalıştırma ayarları girişi için '{0}' değeri geçersiz, ayar yoksayılacak. + + Invalid value '{0}' for runsettings entry '{1}', setting will be ignored. + Invalid value '{0}' for runsettings entry '{1}', setting will be ignored. + + + + Warning : A testsettings file or a vsmdi file is not supported with the MSTest V2 Adapter. + Warning : A testsettings file or a vsmdi file is not supported with the MSTest V2 Adapter. + + Test Run deployment issue: The assembly or module '{0}' was not found. Reason: {1} Test Çalıştırması dağıtım sorunu: '{0}' adlı bütünleştirilmiş kod veya modül bulunamadı. Nedeni: {1} @@ -97,21 +289,304 @@ Test Çalıştırması dağıtım sorunu: '{0}' adlı bütünleştirilmiş kod veya modül bulunamadı. + + An older version of MSTestV2 package is loaded in assembly, test discovery might fail to discover all data tests if they depend on `.runsettings` file. + An older version of MSTestV2 package is loaded in assembly, test discovery might fail to discover all data tests if they depend on `.runsettings` file. + + + + Runsettings entry '<ExecutionApartmentState>STA</ExecutionApartmentState>' is not supported on non-Windows OSes. + Runsettings entry '<ExecutionApartmentState>STA</ExecutionApartmentState>' is not supported on non-Windows OSes. + + + + Running tests in any of the provided sources is not supported for the selected platform + Running tests in any of the provided sources is not supported for the selected platform + + + + Failed to discover tests from assembly {0}. Reason:{1} + Failed to discover tests from assembly {0}. Reason:{1} + + + + File does not exist: {0} + File does not exist: {0} + + + + Test cleanup method '{0}.{1}' timed out after {2}ms + Test cleanup method '{0}.{1}' timed out after {2}ms + + + + Test cleanup method '{0}.{1}' was canceled + Test cleanup method '{0}.{1}' was canceled + + + + TestContext cannot be Null. + TestContext cannot be Null. + + + + TestContext Messages: + TestContext Messages: + + + + Test initialize method '{0}.{1}' timed out after {2}ms + Test initialize method '{0}.{1}' timed out after {2}ms + + + + Test initialize method '{0}.{1}' was canceled + Test initialize method '{0}.{1}' was canceled + + + + Test method {0} was not found. + Test method {0} was not found. + + + + Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) + Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) + `Workers` is a setting name that shouldn't be localized. 'Scope' is a setting name that shouldn't be localized. + {0}_{1} {2} {0}_{1} {2} + + Unable to load types from the test source '{0}'. Some or all of the tests in this source may not be discovered. +Error: {1} + Unable to load types from the test source '{0}'. Some or all of the tests in this source may not be discovered. +Error: {1} + + + + Assembly Cleanup method {0}.{1} failed. Error Message: {2}. StackTrace: {3} + Assembly Cleanup method {0}.{1} failed. Error Message: {2}. StackTrace: {3} + + + + Assembly Initialization method {0}.{1} threw exception. {2}: {3}. Aborting test execution. + Assembly Initialization method {0}.{1} threw exception. {2}: {3}. Aborting test execution. + + + + Class Cleanup method {0}.{1} failed. Error Message: {2}. Stack Trace: {3} + Class Cleanup method {0}.{1} failed. Error Message: {2}. Stack Trace: {3} + + + + Class Initialization method {0}.{1} threw exception. {2}: {3}. + Class Initialization method {0}.{1} threw exception. {2}: {3}. + + + + Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + + + + Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should take a single parameter of type TestContext. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should take a single parameter of type TestContext. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + + + + TestCleanup method {0}.{1} threw exception. {2}. + TestCleanup method {0}.{1} threw exception. {2}. + + + + Error calling Test Cleanup method for test class {0}: {1} + Error calling Test Cleanup method for test class {0}: {1} + + + + TestCleanup Stack Trace + TestCleanup Stack Trace + + Data source '{0}' cannot be found in the test configuration settings Test yapılandırması ayarlarında '{0}' adlı veri kaynağı bulunamıyor + + --- End of inner exception stack trace --- + --- End of inner exception stack trace --- + + The unit test adapter failed to connect to the data source or to read the data. For more information on troubleshooting this error, see "Troubleshooting Data-Driven Unit Tests" (http://go.microsoft.com/fwlink/?LinkId=62412) in the MSDN Library. Error details: {0} Birim test bağdaştırıcısı, veri kaynağına bağlanamadı veya verileri okuyamadı. Bu hata ile ilgili daha fazla sorun giderme bilgisi için MSDN Kitaplığı'ndaki "Veri Temelli Birim Testleriyle İlgili Sorunları Giderme" (http://go.microsoft.com/fwlink/?LinkId=62412) konusuna bakın. Hata ayrıntıları: {0} + + UTA031: class {0} does not have valid TestContext property. TestContext must be of type TestContext, must be non-static, and must be public. For example: public TestContext TestContext. + UTA031: class {0} does not have valid TestContext property. TestContext must be of type TestContext, must be non-static, and must be public. For example: public TestContext TestContext. + + + + UTA007: Method {1} defined in class {0} does not have correct signature. Test method marked with the [TestMethod] attribute must be non-static, public, return-type as void and should not take any parameter. Example: public void Test.Class1.Test(). Additionally, if you are using async-await in test method then return-type must be 'Task' or 'ValueTask'. Example: public async Task Test.Class1.Test2() + UTA007: Method {1} defined in class {0} does not have correct signature. Test method marked with the [TestMethod] attribute must be non-static, public, return-type as void and should not take any parameter. Example: public void Test.Class1.Test(). Additionally, if you are using async-await in test method then return-type must be 'Task' or 'ValueTask'. Example: public async Task Test.Class1.Test2() + + + + UTA054: {0}.{1} has invalid Timeout attribute. The timeout must be an integer value greater than 0. + UTA054: {0}.{1} has invalid Timeout attribute. The timeout must be an integer value greater than 0. + + + + UTA014: {0}: Cannot define more than one method with the AssemblyCleanup attribute inside an assembly. + UTA014: {0}: Cannot define more than one method with the AssemblyCleanup attribute inside an assembly. + + + + UTA013: {0}: Cannot define more than one method with the AssemblyInitialize attribute inside an assembly. + UTA013: {0}: Cannot define more than one method with the AssemblyInitialize attribute inside an assembly. + + + + UTA026: {0}: Cannot define more than one method with the ClassCleanup attribute inside a class. + UTA026: {0}: Cannot define more than one method with the ClassCleanup attribute inside a class. + + + + UTA025: {0}: Cannot define more than one method with the ClassInitialize attribute inside a class. + UTA025: {0}: Cannot define more than one method with the ClassInitialize attribute inside a class. + + + + UTA024: {0}: Cannot define more than one method with the TestCleanup attribute. + UTA024: {0}: Cannot define more than one method with the TestCleanup attribute. + + + + UTA018: {0}: Cannot define more than one method with the TestInitialize attribute. + UTA018: {0}: Cannot define more than one method with the TestInitialize attribute. + + + + UTA001: TestClass attribute defined on non-public class {0} + UTA001: TestClass attribute defined on non-public class {0} + + + + UTA023: {0}: Cannot define predefined property {2} on method {1}. + UTA023: {0}: Cannot define predefined property {2} on method {1}. + + + + TestClass attribute defined on generic non-abstract class {0} + TestClass attribute defined on generic non-abstract class {0} + + + + UTA021: {0}: Null or empty custom property defined on method {1}. The custom property must have a valid name. + UTA021: {0}: Null or empty custom property defined on method {1}. The custom property must have a valid name. + + + + An unhandled exception was thrown by the 'Execute' method. Please report this error to the author of the attribute '{0}'. +{1} + An unhandled exception was thrown by the 'Execute' method. Please report this error to the author of the attribute '{0}'. +{1} + + + + The ExpectedException attribute defined on test method {0}.{1} threw an exception during construction. +{2} + The ExpectedException attribute defined on test method {0}.{1} threw an exception during construction. +{2} + + + + Failed to obtain the exception thrown by test method {0}.{1}. + Failed to obtain the exception thrown by test method {0}.{1}. + + + + Initialization method {0}.{1} threw exception. {2}. + Initialization method {0}.{1} threw exception. {2}. + + + + Unable to create instance of class {0}. Error: {1}. + Unable to create instance of class {0}. Error: {1}. + + + + Method {0}.{1} does not exist. + Method {0}.{1} does not exist. + + + + The test method '{0}.{1}' has multiple attributes derived from '{2}' defined on it. Only one such attribute is allowed. + The test method '{0}.{1}' has multiple attributes derived from '{2}' defined on it. Only one such attribute is allowed. + + + + Error in executing test. No result returned by extension. If using extension of TestMethodAttribute then please contact vendor. + Error in executing test. No result returned by extension. If using extension of TestMethodAttribute then please contact vendor. + + + + Cannot find a valid constructor for test class '{0}'. Valid constructors are 'public' and either parameterless or with one parameter of type 'TestContext'. + Cannot find a valid constructor for test class '{0}'. Valid constructors are 'public' and either parameterless or with one parameter of type 'TestContext'. + + + + Unable to find property {0}.TestContext. Error:{1}. + Unable to find property {0}.TestContext. Error:{1}. + + + + Unable to set TestContext property for the class {0}. Error: {1}. + Unable to set TestContext property for the class {0}. Error: {1}. + + + + The {0}.TestContext has incorrect type. + The {0}.TestContext has incorrect type. + + + + Method {0}.{1} has wrong signature. The method must be non-static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + Method {0}.{1} has wrong signature. The method must be non-static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + + + + Test method {0}.{1} threw exception: +{2} + Test method {0}.{1} threw exception: +{2} + + + + Unable to get type {0}. Error: {1}. + Unable to get type {0}. Error: {1}. + + + + The called code threw an exception that was caught, but the exception value was null + The called code threw an exception that was caught, but the exception value was null + + + + {0} For UWP projects, if you are using UI objects in test consider using [UITestMethod] attribute instead of [TestMethod] to execute test in UI thread. + {0} For UWP projects, if you are using UI objects in test consider using [UITestMethod] attribute instead of [TestMethod] to execute test in UI thread. + + + + (Failed to get the message for an exception of type {0} due to an exception.) + (Failed to get the message for an exception of type {0} due to an exception.) + + Wrong number of objects for permutation. Should be greater than zero. Permütasyon için nesne sayısı yanlış. Değer, sıfırdan büyük olmalıdır. diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.zh-Hans.xlf b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.zh-Hans.xlf index 813ddf8f72..c81aa4644c 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.zh-Hans.xlf +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.zh-Hans.xlf @@ -2,16 +2,116 @@ + + Assembly cleanup method '{0}.{1}' timed out after {2}ms + Assembly cleanup method '{0}.{1}' timed out after {2}ms + + + + Assembly cleanup method '{0}.{1}' was canceled + Assembly cleanup method '{0}.{1}' was canceled + + + + Assembly initialize method '{0}.{1}' timed out after {2}ms + Assembly initialize method '{0}.{1}' timed out after {2}ms + + + + Assembly initialize method '{0}.{1}' was canceled + Assembly initialize method '{0}.{1}' was canceled + + + + MSTestAdapterV2 + MSTestAdapterV2 + + + + Exception occurred while enumerating IDataSource attribute on "{0}.{1}": {2} + Exception occurred while enumerating IDataSource attribute on "{0}.{1}": {2} + {0}: TypeName with namespace, +{1}: Method name, +{2}: Exception details + + + Exception occurred while expanding IDataSource rows from attribute on "{0}.{1}": {2} + Exception occurred while expanding IDataSource rows from attribute on "{0}.{1}": {2} + {0}: TypeName with namespace, +{1}: Method name, +{2}: CannotExpandIDataSourceAttribute_DuplicateDisplayName or CannotExpandIDataSourceAttribute_CannotSerialize + + + Data on index {0} for "{1}" cannot be serialized. All data provided through "IDataSource" should be serializable. If you need to test non-serializable data sources, please make sure you add "TestDataSourceDiscovery" attribute on your test assembly and set the discovery option to "DuringExecution". + Data on index {0} for "{1}" cannot be serialized. All data provided through "IDataSource" should be serializable. If you need to test non-serializable data sources, please make sure you add "TestDataSourceDiscovery" attribute on your test assembly and set the discovery option to "DuringExecution". + {0}: Zero based index if an element inside of an array, +{1}: Test name + + + Display name "{2}" on indexes {0} and {1} are duplicate. Display names should be unique. + Display name "{2}" on indexes {0} and {1} are duplicate. Display names should be unique. + {0}, {1}: Zero based index if an element inside of an array +{2}: Test display name. + Could not find file '{0}'. 找不到文件“{0}”。 + + Cannot run test method '{0}.{1}': Test data doesn't match method parameters. Either the count or types are different. +Test expected {2} parameter(s), with types '{3}', +but received {4} argument(s), with types '{5}'. + Cannot run test method '{0}.{1}': Test data doesn't match method parameters. Either the count or types are different. +Test expected {2} parameter(s), with types '{3}', +but received {4} argument(s), with types '{5}'. + + + + Cannot run test method '{0}.{1}': Method has parameters, but does not define any test source. Use '[DataRow]', '[DynamicData]', or a custom 'ITestDataSource' data source to provide test data. + Cannot run test method '{0}.{1}': Method has parameters, but does not define any test source. Use '[DataRow]', '[DynamicData]', or a custom 'ITestDataSource' data source to provide test data. + + + + Class cleanup method '{0}.{1}' timed out after {2}ms + Class cleanup method '{0}.{1}' timed out after {2}ms + + + + Class cleanup method '{0}.{1}' was canceled + Class cleanup method '{0}.{1}' was canceled + + + + Class initialize method '{0}.{1}' timed out after {2}ms + Class initialize method '{0}.{1}' timed out after {2}ms + + + + Class initialize method '{0}.{1}' was canceled + Class initialize method '{0}.{1}' was canceled + + The parameter should not be null or empty. 参数不应为 NULL 或为空。 + + MSTestAdapter failed to discover tests in class '{0}' of assembly '{1}' because {2}. + MSTestAdapter failed to discover tests in class '{0}' of assembly '{1}' because {2}. + + + + {0} (Data Row {1}) + {0} (Data Row {1}) + + + + Debug Trace: + Debug Trace: + + Test Run deployment issue: Bad deployment item: '{0}': output directory '{1}' specifies the item to be deployed outside deployment root directory which is not allowed. 测试运行部署问题: 错误的部署项:“{0}”: 输出目录“{1}”指定将该项部署到部署根目录的外部,这是不允许的。 @@ -77,16 +177,108 @@ 部署项“{0}”(输出目录“{1}”) + + [MSTest][Discovery][{0}] {1} + [MSTest][Discovery][{0}] {1} + + + + Both '.runsettings' and '.testconfig.json' files have been detected. Please select only one of these test configuration files. + Both '.runsettings' and '.testconfig.json' files have been detected. Please select only one of these test configuration files. + + + + {0}: {1} + {0}: {1} + + + + "{0}": (Failed to get exception description due to an exception of type "{1}". + "{0}": (Failed to get exception description due to an exception of type "{1}". + {0}: Type of the original exception that we're trying to get the description of. +{1}: Thrown exception + + + Exceptions thrown: + Exceptions thrown: + This is usually precedes by TestAssembly_AssemblyDiscoveryFailure message, and preceded by list of exceptions thrown in a test discovery session. + + + Test '{0}' was canceled + Test '{0}' was canceled + + + + Test '{0}' timed out after {1}ms + Test '{0}' timed out after {1}ms + + + + Getting custom attributes for type {0} threw exception (will ignore and use the reflection way): {1} + Getting custom attributes for type {0} threw exception (will ignore and use the reflection way): {1} + {0}: Attribute full type name. +{1}: Exception description + + + The type of the generic parameter '{0}' could not be inferred. + The type of the generic parameter '{0}' could not be inferred. + + + + The generic test method '{0}' doesn't have arguments, so the generic parameter cannot be inferred. + The generic test method '{0}' doesn't have arguments, so the generic parameter cannot be inferred. + + + + Found two conflicting types for generic parameter '{0}'. The conflicting types are '{1}' and '{2}'. + Found two conflicting types for generic parameter '{0}'. The conflicting types are '{1}' and '{2}'. + + + + Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. + Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. + 'ClassCleanupLifecycle' is a setting name that shouldn't be localized. + + + Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. + Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. + 'Scope' is a setting name that shouldn't be localized. + + + Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. + Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. + `Workers` is a setting name that shouldn't be localized. + + + Invalid settings '{0}'. Unexpected XmlAttribute: '{1}'. + Invalid settings '{0}'. Unexpected XmlAttribute: '{1}'. + + MSTestAdapter encountered an unexpected element '{0}' in its settings '{1}'. Remove this element and try again. MSTestAdapter 在其设置“{1}”中遇到意外的元素“{0}”。删除此元素,然后再试一次。 + + Invalid settings '{0}'. Unexpected XmlElement: '{1}'. + Invalid settings '{0}'. Unexpected XmlElement: '{1}'. + + Invalid value '{0}' for runsettings entry '{1}', setting will be ignored. runsettings 项 ‘{1}’ 的值 ‘{0}’ 无效,将忽略设置。 + + Invalid value '{0}' for runsettings entry '{1}', setting will be ignored. + Invalid value '{0}' for runsettings entry '{1}', setting will be ignored. + + + + Warning : A testsettings file or a vsmdi file is not supported with the MSTest V2 Adapter. + Warning : A testsettings file or a vsmdi file is not supported with the MSTest V2 Adapter. + + Test Run deployment issue: The assembly or module '{0}' was not found. Reason: {1} 测试运行部署问题: 找不到程序集或模块“{0}”。原因: {1} @@ -97,21 +289,304 @@ 测试运行部署问题: 找不到程序集或模块“{0}”。 + + An older version of MSTestV2 package is loaded in assembly, test discovery might fail to discover all data tests if they depend on `.runsettings` file. + An older version of MSTestV2 package is loaded in assembly, test discovery might fail to discover all data tests if they depend on `.runsettings` file. + + + + Runsettings entry '<ExecutionApartmentState>STA</ExecutionApartmentState>' is not supported on non-Windows OSes. + Runsettings entry '<ExecutionApartmentState>STA</ExecutionApartmentState>' is not supported on non-Windows OSes. + + + + Running tests in any of the provided sources is not supported for the selected platform + Running tests in any of the provided sources is not supported for the selected platform + + + + Failed to discover tests from assembly {0}. Reason:{1} + Failed to discover tests from assembly {0}. Reason:{1} + + + + File does not exist: {0} + File does not exist: {0} + + + + Test cleanup method '{0}.{1}' timed out after {2}ms + Test cleanup method '{0}.{1}' timed out after {2}ms + + + + Test cleanup method '{0}.{1}' was canceled + Test cleanup method '{0}.{1}' was canceled + + + + TestContext cannot be Null. + TestContext cannot be Null. + + + + TestContext Messages: + TestContext Messages: + + + + Test initialize method '{0}.{1}' timed out after {2}ms + Test initialize method '{0}.{1}' timed out after {2}ms + + + + Test initialize method '{0}.{1}' was canceled + Test initialize method '{0}.{1}' was canceled + + + + Test method {0} was not found. + Test method {0} was not found. + + + + Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) + Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) + `Workers` is a setting name that shouldn't be localized. 'Scope' is a setting name that shouldn't be localized. + {0}_{1} {2} {0}_{1} {2} + + Unable to load types from the test source '{0}'. Some or all of the tests in this source may not be discovered. +Error: {1} + Unable to load types from the test source '{0}'. Some or all of the tests in this source may not be discovered. +Error: {1} + + + + Assembly Cleanup method {0}.{1} failed. Error Message: {2}. StackTrace: {3} + Assembly Cleanup method {0}.{1} failed. Error Message: {2}. StackTrace: {3} + + + + Assembly Initialization method {0}.{1} threw exception. {2}: {3}. Aborting test execution. + Assembly Initialization method {0}.{1} threw exception. {2}: {3}. Aborting test execution. + + + + Class Cleanup method {0}.{1} failed. Error Message: {2}. Stack Trace: {3} + Class Cleanup method {0}.{1} failed. Error Message: {2}. Stack Trace: {3} + + + + Class Initialization method {0}.{1} threw exception. {2}: {3}. + Class Initialization method {0}.{1} threw exception. {2}: {3}. + + + + Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + + + + Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should take a single parameter of type TestContext. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should take a single parameter of type TestContext. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + + + + TestCleanup method {0}.{1} threw exception. {2}. + TestCleanup method {0}.{1} threw exception. {2}. + + + + Error calling Test Cleanup method for test class {0}: {1} + Error calling Test Cleanup method for test class {0}: {1} + + + + TestCleanup Stack Trace + TestCleanup Stack Trace + + Data source '{0}' cannot be found in the test configuration settings 在测试配置设置中找不到数据源“{0}” + + --- End of inner exception stack trace --- + --- End of inner exception stack trace --- + + The unit test adapter failed to connect to the data source or to read the data. For more information on troubleshooting this error, see "Troubleshooting Data-Driven Unit Tests" (http://go.microsoft.com/fwlink/?LinkId=62412) in the MSDN Library. Error details: {0} 单元测试适配器未能连接到数据源或读取数据。有关解决此错误的详细信息,请查看 MSDN 库中的“数据驱动单元测试疑难解答”(http://go.microsoft.com/fwlink/?LinkId=62412)。错误详细信息: {0} + + UTA031: class {0} does not have valid TestContext property. TestContext must be of type TestContext, must be non-static, and must be public. For example: public TestContext TestContext. + UTA031: class {0} does not have valid TestContext property. TestContext must be of type TestContext, must be non-static, and must be public. For example: public TestContext TestContext. + + + + UTA007: Method {1} defined in class {0} does not have correct signature. Test method marked with the [TestMethod] attribute must be non-static, public, return-type as void and should not take any parameter. Example: public void Test.Class1.Test(). Additionally, if you are using async-await in test method then return-type must be 'Task' or 'ValueTask'. Example: public async Task Test.Class1.Test2() + UTA007: Method {1} defined in class {0} does not have correct signature. Test method marked with the [TestMethod] attribute must be non-static, public, return-type as void and should not take any parameter. Example: public void Test.Class1.Test(). Additionally, if you are using async-await in test method then return-type must be 'Task' or 'ValueTask'. Example: public async Task Test.Class1.Test2() + + + + UTA054: {0}.{1} has invalid Timeout attribute. The timeout must be an integer value greater than 0. + UTA054: {0}.{1} has invalid Timeout attribute. The timeout must be an integer value greater than 0. + + + + UTA014: {0}: Cannot define more than one method with the AssemblyCleanup attribute inside an assembly. + UTA014: {0}: Cannot define more than one method with the AssemblyCleanup attribute inside an assembly. + + + + UTA013: {0}: Cannot define more than one method with the AssemblyInitialize attribute inside an assembly. + UTA013: {0}: Cannot define more than one method with the AssemblyInitialize attribute inside an assembly. + + + + UTA026: {0}: Cannot define more than one method with the ClassCleanup attribute inside a class. + UTA026: {0}: Cannot define more than one method with the ClassCleanup attribute inside a class. + + + + UTA025: {0}: Cannot define more than one method with the ClassInitialize attribute inside a class. + UTA025: {0}: Cannot define more than one method with the ClassInitialize attribute inside a class. + + + + UTA024: {0}: Cannot define more than one method with the TestCleanup attribute. + UTA024: {0}: Cannot define more than one method with the TestCleanup attribute. + + + + UTA018: {0}: Cannot define more than one method with the TestInitialize attribute. + UTA018: {0}: Cannot define more than one method with the TestInitialize attribute. + + + + UTA001: TestClass attribute defined on non-public class {0} + UTA001: TestClass attribute defined on non-public class {0} + + + + UTA023: {0}: Cannot define predefined property {2} on method {1}. + UTA023: {0}: Cannot define predefined property {2} on method {1}. + + + + TestClass attribute defined on generic non-abstract class {0} + TestClass attribute defined on generic non-abstract class {0} + + + + UTA021: {0}: Null or empty custom property defined on method {1}. The custom property must have a valid name. + UTA021: {0}: Null or empty custom property defined on method {1}. The custom property must have a valid name. + + + + An unhandled exception was thrown by the 'Execute' method. Please report this error to the author of the attribute '{0}'. +{1} + An unhandled exception was thrown by the 'Execute' method. Please report this error to the author of the attribute '{0}'. +{1} + + + + The ExpectedException attribute defined on test method {0}.{1} threw an exception during construction. +{2} + The ExpectedException attribute defined on test method {0}.{1} threw an exception during construction. +{2} + + + + Failed to obtain the exception thrown by test method {0}.{1}. + Failed to obtain the exception thrown by test method {0}.{1}. + + + + Initialization method {0}.{1} threw exception. {2}. + Initialization method {0}.{1} threw exception. {2}. + + + + Unable to create instance of class {0}. Error: {1}. + Unable to create instance of class {0}. Error: {1}. + + + + Method {0}.{1} does not exist. + Method {0}.{1} does not exist. + + + + The test method '{0}.{1}' has multiple attributes derived from '{2}' defined on it. Only one such attribute is allowed. + The test method '{0}.{1}' has multiple attributes derived from '{2}' defined on it. Only one such attribute is allowed. + + + + Error in executing test. No result returned by extension. If using extension of TestMethodAttribute then please contact vendor. + Error in executing test. No result returned by extension. If using extension of TestMethodAttribute then please contact vendor. + + + + Cannot find a valid constructor for test class '{0}'. Valid constructors are 'public' and either parameterless or with one parameter of type 'TestContext'. + Cannot find a valid constructor for test class '{0}'. Valid constructors are 'public' and either parameterless or with one parameter of type 'TestContext'. + + + + Unable to find property {0}.TestContext. Error:{1}. + Unable to find property {0}.TestContext. Error:{1}. + + + + Unable to set TestContext property for the class {0}. Error: {1}. + Unable to set TestContext property for the class {0}. Error: {1}. + + + + The {0}.TestContext has incorrect type. + The {0}.TestContext has incorrect type. + + + + Method {0}.{1} has wrong signature. The method must be non-static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + Method {0}.{1} has wrong signature. The method must be non-static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + + + + Test method {0}.{1} threw exception: +{2} + Test method {0}.{1} threw exception: +{2} + + + + Unable to get type {0}. Error: {1}. + Unable to get type {0}. Error: {1}. + + + + The called code threw an exception that was caught, but the exception value was null + The called code threw an exception that was caught, but the exception value was null + + + + {0} For UWP projects, if you are using UI objects in test consider using [UITestMethod] attribute instead of [TestMethod] to execute test in UI thread. + {0} For UWP projects, if you are using UI objects in test consider using [UITestMethod] attribute instead of [TestMethod] to execute test in UI thread. + + + + (Failed to get the message for an exception of type {0} due to an exception.) + (Failed to get the message for an exception of type {0} due to an exception.) + + Wrong number of objects for permutation. Should be greater than zero. 排列的对象数不正确。应大于零。 diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.zh-Hant.xlf b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.zh-Hant.xlf index aae5f14299..70e0deb2f4 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.zh-Hant.xlf +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.zh-Hant.xlf @@ -2,16 +2,116 @@ + + Assembly cleanup method '{0}.{1}' timed out after {2}ms + Assembly cleanup method '{0}.{1}' timed out after {2}ms + + + + Assembly cleanup method '{0}.{1}' was canceled + Assembly cleanup method '{0}.{1}' was canceled + + + + Assembly initialize method '{0}.{1}' timed out after {2}ms + Assembly initialize method '{0}.{1}' timed out after {2}ms + + + + Assembly initialize method '{0}.{1}' was canceled + Assembly initialize method '{0}.{1}' was canceled + + + + MSTestAdapterV2 + MSTestAdapterV2 + + + + Exception occurred while enumerating IDataSource attribute on "{0}.{1}": {2} + Exception occurred while enumerating IDataSource attribute on "{0}.{1}": {2} + {0}: TypeName with namespace, +{1}: Method name, +{2}: Exception details + + + Exception occurred while expanding IDataSource rows from attribute on "{0}.{1}": {2} + Exception occurred while expanding IDataSource rows from attribute on "{0}.{1}": {2} + {0}: TypeName with namespace, +{1}: Method name, +{2}: CannotExpandIDataSourceAttribute_DuplicateDisplayName or CannotExpandIDataSourceAttribute_CannotSerialize + + + Data on index {0} for "{1}" cannot be serialized. All data provided through "IDataSource" should be serializable. If you need to test non-serializable data sources, please make sure you add "TestDataSourceDiscovery" attribute on your test assembly and set the discovery option to "DuringExecution". + Data on index {0} for "{1}" cannot be serialized. All data provided through "IDataSource" should be serializable. If you need to test non-serializable data sources, please make sure you add "TestDataSourceDiscovery" attribute on your test assembly and set the discovery option to "DuringExecution". + {0}: Zero based index if an element inside of an array, +{1}: Test name + + + Display name "{2}" on indexes {0} and {1} are duplicate. Display names should be unique. + Display name "{2}" on indexes {0} and {1} are duplicate. Display names should be unique. + {0}, {1}: Zero based index if an element inside of an array +{2}: Test display name. + Could not find file '{0}'. 找不到檔案 '{0}'。 + + Cannot run test method '{0}.{1}': Test data doesn't match method parameters. Either the count or types are different. +Test expected {2} parameter(s), with types '{3}', +but received {4} argument(s), with types '{5}'. + Cannot run test method '{0}.{1}': Test data doesn't match method parameters. Either the count or types are different. +Test expected {2} parameter(s), with types '{3}', +but received {4} argument(s), with types '{5}'. + + + + Cannot run test method '{0}.{1}': Method has parameters, but does not define any test source. Use '[DataRow]', '[DynamicData]', or a custom 'ITestDataSource' data source to provide test data. + Cannot run test method '{0}.{1}': Method has parameters, but does not define any test source. Use '[DataRow]', '[DynamicData]', or a custom 'ITestDataSource' data source to provide test data. + + + + Class cleanup method '{0}.{1}' timed out after {2}ms + Class cleanup method '{0}.{1}' timed out after {2}ms + + + + Class cleanup method '{0}.{1}' was canceled + Class cleanup method '{0}.{1}' was canceled + + + + Class initialize method '{0}.{1}' timed out after {2}ms + Class initialize method '{0}.{1}' timed out after {2}ms + + + + Class initialize method '{0}.{1}' was canceled + Class initialize method '{0}.{1}' was canceled + + The parameter should not be null or empty. 參數不可為 null 或空白。 + + MSTestAdapter failed to discover tests in class '{0}' of assembly '{1}' because {2}. + MSTestAdapter failed to discover tests in class '{0}' of assembly '{1}' because {2}. + + + + {0} (Data Row {1}) + {0} (Data Row {1}) + + + + Debug Trace: + Debug Trace: + + Test Run deployment issue: Bad deployment item: '{0}': output directory '{1}' specifies the item to be deployed outside deployment root directory which is not allowed. 測試回合部署問題: 部署項目錯誤: '{0}': 輸出目錄 '{1}' 指定要將項目部署到部署根目錄之外,但不允許這情況。 @@ -77,16 +177,108 @@ 部署項目 '{0}' (輸出目錄 '{1}') + + [MSTest][Discovery][{0}] {1} + [MSTest][Discovery][{0}] {1} + + + + Both '.runsettings' and '.testconfig.json' files have been detected. Please select only one of these test configuration files. + Both '.runsettings' and '.testconfig.json' files have been detected. Please select only one of these test configuration files. + + + + {0}: {1} + {0}: {1} + + + + "{0}": (Failed to get exception description due to an exception of type "{1}". + "{0}": (Failed to get exception description due to an exception of type "{1}". + {0}: Type of the original exception that we're trying to get the description of. +{1}: Thrown exception + + + Exceptions thrown: + Exceptions thrown: + This is usually precedes by TestAssembly_AssemblyDiscoveryFailure message, and preceded by list of exceptions thrown in a test discovery session. + + + Test '{0}' was canceled + Test '{0}' was canceled + + + + Test '{0}' timed out after {1}ms + Test '{0}' timed out after {1}ms + + + + Getting custom attributes for type {0} threw exception (will ignore and use the reflection way): {1} + Getting custom attributes for type {0} threw exception (will ignore and use the reflection way): {1} + {0}: Attribute full type name. +{1}: Exception description + + + The type of the generic parameter '{0}' could not be inferred. + The type of the generic parameter '{0}' could not be inferred. + + + + The generic test method '{0}' doesn't have arguments, so the generic parameter cannot be inferred. + The generic test method '{0}' doesn't have arguments, so the generic parameter cannot be inferred. + + + + Found two conflicting types for generic parameter '{0}'. The conflicting types are '{1}' and '{2}'. + Found two conflicting types for generic parameter '{0}'. The conflicting types are '{1}' and '{2}'. + + + + Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. + Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. + 'ClassCleanupLifecycle' is a setting name that shouldn't be localized. + + + Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. + Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. + 'Scope' is a setting name that shouldn't be localized. + + + Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. + Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. + `Workers` is a setting name that shouldn't be localized. + + + Invalid settings '{0}'. Unexpected XmlAttribute: '{1}'. + Invalid settings '{0}'. Unexpected XmlAttribute: '{1}'. + + MSTestAdapter encountered an unexpected element '{0}' in its settings '{1}'. Remove this element and try again. MSTestAdapter 在其設定 '{1}' 中遇到未預期的項目 '{0}'。請移除此項目,然後再試一次。 + + Invalid settings '{0}'. Unexpected XmlElement: '{1}'. + Invalid settings '{0}'. Unexpected XmlElement: '{1}'. + + Invalid value '{0}' for runsettings entry '{1}', setting will be ignored. runsettings 項目 '{1}' 的值 '{0}' 無效,將忽略設定。 + + Invalid value '{0}' for runsettings entry '{1}', setting will be ignored. + Invalid value '{0}' for runsettings entry '{1}', setting will be ignored. + + + + Warning : A testsettings file or a vsmdi file is not supported with the MSTest V2 Adapter. + Warning : A testsettings file or a vsmdi file is not supported with the MSTest V2 Adapter. + + Test Run deployment issue: The assembly or module '{0}' was not found. Reason: {1} 測試回合部署問題: 找不到組件或模組 '{0}'。原因: {1} @@ -97,21 +289,304 @@ 測試回合部署問題: 找不到組件或模組 '{0}'。 + + An older version of MSTestV2 package is loaded in assembly, test discovery might fail to discover all data tests if they depend on `.runsettings` file. + An older version of MSTestV2 package is loaded in assembly, test discovery might fail to discover all data tests if they depend on `.runsettings` file. + + + + Runsettings entry '<ExecutionApartmentState>STA</ExecutionApartmentState>' is not supported on non-Windows OSes. + Runsettings entry '<ExecutionApartmentState>STA</ExecutionApartmentState>' is not supported on non-Windows OSes. + + + + Running tests in any of the provided sources is not supported for the selected platform + Running tests in any of the provided sources is not supported for the selected platform + + + + Failed to discover tests from assembly {0}. Reason:{1} + Failed to discover tests from assembly {0}. Reason:{1} + + + + File does not exist: {0} + File does not exist: {0} + + + + Test cleanup method '{0}.{1}' timed out after {2}ms + Test cleanup method '{0}.{1}' timed out after {2}ms + + + + Test cleanup method '{0}.{1}' was canceled + Test cleanup method '{0}.{1}' was canceled + + + + TestContext cannot be Null. + TestContext cannot be Null. + + + + TestContext Messages: + TestContext Messages: + + + + Test initialize method '{0}.{1}' timed out after {2}ms + Test initialize method '{0}.{1}' timed out after {2}ms + + + + Test initialize method '{0}.{1}' was canceled + Test initialize method '{0}.{1}' was canceled + + + + Test method {0} was not found. + Test method {0} was not found. + + + + Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) + Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) + `Workers` is a setting name that shouldn't be localized. 'Scope' is a setting name that shouldn't be localized. + {0}_{1} {2} {0}_{1} {2} + + Unable to load types from the test source '{0}'. Some or all of the tests in this source may not be discovered. +Error: {1} + Unable to load types from the test source '{0}'. Some or all of the tests in this source may not be discovered. +Error: {1} + + + + Assembly Cleanup method {0}.{1} failed. Error Message: {2}. StackTrace: {3} + Assembly Cleanup method {0}.{1} failed. Error Message: {2}. StackTrace: {3} + + + + Assembly Initialization method {0}.{1} threw exception. {2}: {3}. Aborting test execution. + Assembly Initialization method {0}.{1} threw exception. {2}: {3}. Aborting test execution. + + + + Class Cleanup method {0}.{1} failed. Error Message: {2}. Stack Trace: {3} + Class Cleanup method {0}.{1} failed. Error Message: {2}. Stack Trace: {3} + + + + Class Initialization method {0}.{1} threw exception. {2}: {3}. + Class Initialization method {0}.{1} threw exception. {2}: {3}. + + + + Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + + + + Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should take a single parameter of type TestContext. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should take a single parameter of type TestContext. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + + + + TestCleanup method {0}.{1} threw exception. {2}. + TestCleanup method {0}.{1} threw exception. {2}. + + + + Error calling Test Cleanup method for test class {0}: {1} + Error calling Test Cleanup method for test class {0}: {1} + + + + TestCleanup Stack Trace + TestCleanup Stack Trace + + Data source '{0}' cannot be found in the test configuration settings 在測試組態設定中找不到資料來源 '{0}' + + --- End of inner exception stack trace --- + --- End of inner exception stack trace --- + + The unit test adapter failed to connect to the data source or to read the data. For more information on troubleshooting this error, see "Troubleshooting Data-Driven Unit Tests" (http://go.microsoft.com/fwlink/?LinkId=62412) in the MSDN Library. Error details: {0} 單元測試配接器無法連接至資料來源或無法讀取資料。如需為此錯誤進行疑難排解的詳細資訊,請參閱 MSDN Library 上的<如何: 建立資料驅動型單元測試>(http://go.microsoft.com/fwlink/?LinkId=62412)。錯誤詳細資料: {0} + + UTA031: class {0} does not have valid TestContext property. TestContext must be of type TestContext, must be non-static, and must be public. For example: public TestContext TestContext. + UTA031: class {0} does not have valid TestContext property. TestContext must be of type TestContext, must be non-static, and must be public. For example: public TestContext TestContext. + + + + UTA007: Method {1} defined in class {0} does not have correct signature. Test method marked with the [TestMethod] attribute must be non-static, public, return-type as void and should not take any parameter. Example: public void Test.Class1.Test(). Additionally, if you are using async-await in test method then return-type must be 'Task' or 'ValueTask'. Example: public async Task Test.Class1.Test2() + UTA007: Method {1} defined in class {0} does not have correct signature. Test method marked with the [TestMethod] attribute must be non-static, public, return-type as void and should not take any parameter. Example: public void Test.Class1.Test(). Additionally, if you are using async-await in test method then return-type must be 'Task' or 'ValueTask'. Example: public async Task Test.Class1.Test2() + + + + UTA054: {0}.{1} has invalid Timeout attribute. The timeout must be an integer value greater than 0. + UTA054: {0}.{1} has invalid Timeout attribute. The timeout must be an integer value greater than 0. + + + + UTA014: {0}: Cannot define more than one method with the AssemblyCleanup attribute inside an assembly. + UTA014: {0}: Cannot define more than one method with the AssemblyCleanup attribute inside an assembly. + + + + UTA013: {0}: Cannot define more than one method with the AssemblyInitialize attribute inside an assembly. + UTA013: {0}: Cannot define more than one method with the AssemblyInitialize attribute inside an assembly. + + + + UTA026: {0}: Cannot define more than one method with the ClassCleanup attribute inside a class. + UTA026: {0}: Cannot define more than one method with the ClassCleanup attribute inside a class. + + + + UTA025: {0}: Cannot define more than one method with the ClassInitialize attribute inside a class. + UTA025: {0}: Cannot define more than one method with the ClassInitialize attribute inside a class. + + + + UTA024: {0}: Cannot define more than one method with the TestCleanup attribute. + UTA024: {0}: Cannot define more than one method with the TestCleanup attribute. + + + + UTA018: {0}: Cannot define more than one method with the TestInitialize attribute. + UTA018: {0}: Cannot define more than one method with the TestInitialize attribute. + + + + UTA001: TestClass attribute defined on non-public class {0} + UTA001: TestClass attribute defined on non-public class {0} + + + + UTA023: {0}: Cannot define predefined property {2} on method {1}. + UTA023: {0}: Cannot define predefined property {2} on method {1}. + + + + TestClass attribute defined on generic non-abstract class {0} + TestClass attribute defined on generic non-abstract class {0} + + + + UTA021: {0}: Null or empty custom property defined on method {1}. The custom property must have a valid name. + UTA021: {0}: Null or empty custom property defined on method {1}. The custom property must have a valid name. + + + + An unhandled exception was thrown by the 'Execute' method. Please report this error to the author of the attribute '{0}'. +{1} + An unhandled exception was thrown by the 'Execute' method. Please report this error to the author of the attribute '{0}'. +{1} + + + + The ExpectedException attribute defined on test method {0}.{1} threw an exception during construction. +{2} + The ExpectedException attribute defined on test method {0}.{1} threw an exception during construction. +{2} + + + + Failed to obtain the exception thrown by test method {0}.{1}. + Failed to obtain the exception thrown by test method {0}.{1}. + + + + Initialization method {0}.{1} threw exception. {2}. + Initialization method {0}.{1} threw exception. {2}. + + + + Unable to create instance of class {0}. Error: {1}. + Unable to create instance of class {0}. Error: {1}. + + + + Method {0}.{1} does not exist. + Method {0}.{1} does not exist. + + + + The test method '{0}.{1}' has multiple attributes derived from '{2}' defined on it. Only one such attribute is allowed. + The test method '{0}.{1}' has multiple attributes derived from '{2}' defined on it. Only one such attribute is allowed. + + + + Error in executing test. No result returned by extension. If using extension of TestMethodAttribute then please contact vendor. + Error in executing test. No result returned by extension. If using extension of TestMethodAttribute then please contact vendor. + + + + Cannot find a valid constructor for test class '{0}'. Valid constructors are 'public' and either parameterless or with one parameter of type 'TestContext'. + Cannot find a valid constructor for test class '{0}'. Valid constructors are 'public' and either parameterless or with one parameter of type 'TestContext'. + + + + Unable to find property {0}.TestContext. Error:{1}. + Unable to find property {0}.TestContext. Error:{1}. + + + + Unable to set TestContext property for the class {0}. Error: {1}. + Unable to set TestContext property for the class {0}. Error: {1}. + + + + The {0}.TestContext has incorrect type. + The {0}.TestContext has incorrect type. + + + + Method {0}.{1} has wrong signature. The method must be non-static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + Method {0}.{1} has wrong signature. The method must be non-static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + + + + Test method {0}.{1} threw exception: +{2} + Test method {0}.{1} threw exception: +{2} + + + + Unable to get type {0}. Error: {1}. + Unable to get type {0}. Error: {1}. + + + + The called code threw an exception that was caught, but the exception value was null + The called code threw an exception that was caught, but the exception value was null + + + + {0} For UWP projects, if you are using UI objects in test consider using [UITestMethod] attribute instead of [TestMethod] to execute test in UI thread. + {0} For UWP projects, if you are using UI objects in test consider using [UITestMethod] attribute instead of [TestMethod] to execute test in UI thread. + + + + (Failed to get the message for an exception of type {0} due to an exception.) + (Failed to get the message for an exception of type {0} due to an exception.) + + Wrong number of objects for permutation. Should be greater than zero. 排列的物件數目錯誤。應大於零。 diff --git a/src/Adapter/MSTest.TestAdapter/RunConfigurationSettings.cs b/src/Adapter/MSTestAdapter.PlatformServices/RunConfigurationSettings.cs similarity index 97% rename from src/Adapter/MSTest.TestAdapter/RunConfigurationSettings.cs rename to src/Adapter/MSTestAdapter.PlatformServices/RunConfigurationSettings.cs index b2c9b24b54..41b1ad7058 100644 --- a/src/Adapter/MSTest.TestAdapter/RunConfigurationSettings.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/RunConfigurationSettings.cs @@ -2,6 +2,7 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. #if !WINDOWS_UWP +using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Interface; #endif @@ -16,9 +17,9 @@ namespace Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter; /// The run configuration settings. /// #if NET6_0_OR_GREATER -[Obsolete(Constants.PublicTypeObsoleteMessage, DiagnosticId = "MSTESTOBS")] +[Obsolete(FrameworkConstants.PublicTypeObsoleteMessage, DiagnosticId = "MSTESTOBS")] #else -[Obsolete(Constants.PublicTypeObsoleteMessage)] +[Obsolete(FrameworkConstants.PublicTypeObsoleteMessage)] #endif public class RunConfigurationSettings { diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Services/FileOperations.cs b/src/Adapter/MSTestAdapter.PlatformServices/Services/FileOperations.cs index 9f5399670c..7fb908212a 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Services/FileOperations.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Services/FileOperations.cs @@ -16,9 +16,9 @@ namespace Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; /// The file operations. /// #if NET6_0_OR_GREATER -[Obsolete(Constants.PublicTypeObsoleteMessage, DiagnosticId = "MSTESTOBS")] +[Obsolete(TestTools.UnitTesting.FrameworkConstants.PublicTypeObsoleteMessage, DiagnosticId = "MSTESTOBS")] #else -[Obsolete(Constants.PublicTypeObsoleteMessage)] +[Obsolete(TestTools.UnitTesting.FrameworkConstants.PublicTypeObsoleteMessage)] #endif public class FileOperations : IFileOperations { diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Services/MSTestAdapterSettings.cs b/src/Adapter/MSTestAdapter.PlatformServices/Services/MSTestAdapterSettings.cs index 8266bf58e7..a10c3af83e 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Services/MSTestAdapterSettings.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Services/MSTestAdapterSettings.cs @@ -14,9 +14,9 @@ namespace Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; /// The MSTest settings. /// #if NET6_0_OR_GREATER -[Obsolete(Constants.PublicTypeObsoleteMessage, DiagnosticId = "MSTESTOBS")] +[Obsolete(TestTools.UnitTesting.FrameworkConstants.PublicTypeObsoleteMessage, DiagnosticId = "MSTESTOBS")] #else -[Obsolete(Constants.PublicTypeObsoleteMessage)] +[Obsolete(TestTools.UnitTesting.FrameworkConstants.PublicTypeObsoleteMessage)] #endif public class MSTestAdapterSettings { diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Services/ReflectionOperations.cs b/src/Adapter/MSTestAdapter.PlatformServices/Services/ReflectionOperations.cs index b1bf6dcfbb..cf49b2781d 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Services/ReflectionOperations.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Services/ReflectionOperations.cs @@ -2,6 +2,7 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Interface; +using Microsoft.VisualStudio.TestTools.UnitTesting; #if NETFRAMEWORK using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Utilities; #endif @@ -12,9 +13,9 @@ namespace Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; /// This service is responsible for platform specific reflection operations. /// #if NET6_0_OR_GREATER -[Obsolete(Constants.PublicTypeObsoleteMessage, DiagnosticId = "MSTESTOBS")] +[Obsolete(FrameworkConstants.PublicTypeObsoleteMessage, DiagnosticId = "MSTESTOBS")] #else -[Obsolete(Constants.PublicTypeObsoleteMessage)] +[Obsolete(FrameworkConstants.PublicTypeObsoleteMessage)] #endif public class ReflectionOperations : IReflectionOperations { diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Services/SettingsProvider.cs b/src/Adapter/MSTestAdapter.PlatformServices/Services/SettingsProvider.cs index 26e97bf5d5..875e151358 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Services/SettingsProvider.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Services/SettingsProvider.cs @@ -9,9 +9,9 @@ namespace Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; /// Class to read settings from the runsettings xml for the desktop. /// #if NET6_0_OR_GREATER -[Obsolete(Constants.PublicTypeObsoleteMessage, DiagnosticId = "MSTESTOBS")] +[Obsolete(TestTools.UnitTesting.FrameworkConstants.PublicTypeObsoleteMessage, DiagnosticId = "MSTESTOBS")] #else -[Obsolete(Constants.PublicTypeObsoleteMessage)] +[Obsolete(TestTools.UnitTesting.FrameworkConstants.PublicTypeObsoleteMessage)] #endif public class MSTestSettingsProvider : ISettingsProvider { diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Services/TestContextImplementation.cs b/src/Adapter/MSTestAdapter.PlatformServices/Services/TestContextImplementation.cs index c129f79d52..46ceff8d42 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Services/TestContextImplementation.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Services/TestContextImplementation.cs @@ -20,9 +20,9 @@ namespace Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; /// like GetProperty<string>("TestName") or GetProperty<string>("FullyQualifiedTestClassName"). /// #if NET6_0_OR_GREATER -[Obsolete(Constants.PublicTypeObsoleteMessage, DiagnosticId = "MSTESTOBS")] +[Obsolete(FrameworkConstants.PublicTypeObsoleteMessage, DiagnosticId = "MSTESTOBS")] #else -[Obsolete(Constants.PublicTypeObsoleteMessage)] +[Obsolete(FrameworkConstants.PublicTypeObsoleteMessage)] #endif public class TestContextImplementation : TestContext, ITestContext { diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Services/TestDataSource.cs b/src/Adapter/MSTestAdapter.PlatformServices/Services/TestDataSource.cs index 4f1a4f90d9..d5c02e07cf 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Services/TestDataSource.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Services/TestDataSource.cs @@ -24,9 +24,9 @@ namespace Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; /// a ReflectionTypeLoadException. /// #if NET6_0_OR_GREATER -[Obsolete(Constants.PublicTypeObsoleteMessage, DiagnosticId = "MSTESTOBS")] +[Obsolete(TestTools.UnitTesting.FrameworkConstants.PublicTypeObsoleteMessage, DiagnosticId = "MSTESTOBS")] #else -[Obsolete(Constants.PublicTypeObsoleteMessage)] +[Obsolete(TestTools.UnitTesting.FrameworkConstants.PublicTypeObsoleteMessage)] #endif public class TestDataSource : ITestDataSource { diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Services/TestDeployment.cs b/src/Adapter/MSTestAdapter.PlatformServices/Services/TestDeployment.cs index 03a50cdfa3..bb745acf5b 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Services/TestDeployment.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Services/TestDeployment.cs @@ -23,9 +23,9 @@ namespace Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; /// The test deployment. /// #if NET6_0_OR_GREATER -[Obsolete(Constants.PublicTypeObsoleteMessage, DiagnosticId = "MSTESTOBS")] +[Obsolete(TestTools.UnitTesting.FrameworkConstants.PublicTypeObsoleteMessage, DiagnosticId = "MSTESTOBS")] #else -[Obsolete(Constants.PublicTypeObsoleteMessage)] +[Obsolete(TestTools.UnitTesting.FrameworkConstants.PublicTypeObsoleteMessage)] #endif public class TestDeployment : ITestDeployment { diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Services/TestSource.cs b/src/Adapter/MSTestAdapter.PlatformServices/Services/TestSource.cs index de06dce3fb..b93d0aaa05 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Services/TestSource.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Services/TestSource.cs @@ -5,6 +5,7 @@ using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.AppContainer; #endif using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Interface; +using Microsoft.VisualStudio.TestTools.UnitTesting; #if NETFRAMEWORK using Microsoft.VisualStudio.TestPlatform.ObjectModel.Utilities; #endif @@ -16,9 +17,9 @@ namespace Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; /// the test sources provided to the adapter. /// #if NET6_0_OR_GREATER -[Obsolete(Constants.PublicTypeObsoleteMessage, DiagnosticId = "MSTESTOBS")] +[Obsolete(FrameworkConstants.PublicTypeObsoleteMessage, DiagnosticId = "MSTESTOBS")] #else -[Obsolete(Constants.PublicTypeObsoleteMessage)] +[Obsolete(FrameworkConstants.PublicTypeObsoleteMessage)] #endif public class TestSource : ITestSource { @@ -27,7 +28,7 @@ public class TestSource : ITestSource private static readonly IEnumerable ExecutableExtensions = new HashSet() { - Constants.ExeExtension, + EngineConstants.ExeExtension, // Required only for store 8.1. In future if that support is needed, uncomment this. // Constants.DllExtension @@ -62,13 +63,13 @@ public class TestSource : ITestSource /// public IEnumerable ValidSourceExtensions => new List { - Constants.DllExtension, + EngineConstants.DllExtension, #if NETFRAMEWORK - Constants.PhoneAppxPackageExtension, + EngineConstants.PhoneAppxPackageExtension, #elif WINDOWS_UWP || WIN_UI - Constants.AppxPackageExtension, + EngineConstants.AppxPackageExtension, #endif - Constants.ExeExtension, + EngineConstants.ExeExtension, }; /// @@ -149,7 +150,7 @@ public IEnumerable GetTestSources(IEnumerable sources) { // WinUI Desktop uses .NET 6, which builds both a .dll and an .exe. // The manifest will provide the .exe, but the tests are inside the .dll, so we replace the name here. - newSources.Add(Path.Combine(appxSourceDirectory, Path.ChangeExtension(filePath, Constants.DllExtension))); + newSources.Add(Path.Combine(appxSourceDirectory, Path.ChangeExtension(filePath, EngineConstants.DllExtension))); } } @@ -170,7 +171,7 @@ private static bool ContainsAppxSource(IEnumerable sources) { foreach (string source in sources) { - if (string.Equals(Path.GetExtension(source), Constants.AppxPackageExtension, StringComparison.OrdinalIgnoreCase)) + if (string.Equals(Path.GetExtension(source), EngineConstants.AppxPackageExtension, StringComparison.OrdinalIgnoreCase)) { return true; } @@ -190,7 +191,7 @@ private static bool ContainsAppxSource(IEnumerable sources) { foreach (string source in sources) { - if (string.Equals(Path.GetExtension(source), Constants.AppxPackageExtension, StringComparison.OrdinalIgnoreCase)) + if (string.Equals(Path.GetExtension(source), EngineConstants.AppxPackageExtension, StringComparison.OrdinalIgnoreCase)) { return source; } diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Services/TestSourceHost.cs b/src/Adapter/MSTestAdapter.PlatformServices/Services/TestSourceHost.cs index 54f530d721..ec7f34c21d 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Services/TestSourceHost.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Services/TestSourceHost.cs @@ -22,9 +22,9 @@ namespace Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; /// A host that loads the test source. This can be in isolation for desktop using an AppDomain or just loading the source in the current context. /// #if NET6_0_OR_GREATER -[Obsolete(Constants.PublicTypeObsoleteMessage, DiagnosticId = "MSTESTOBS")] +[Obsolete(TestTools.UnitTesting.FrameworkConstants.PublicTypeObsoleteMessage, DiagnosticId = "MSTESTOBS")] #else -[Obsolete(Constants.PublicTypeObsoleteMessage)] +[Obsolete(TestTools.UnitTesting.FrameworkConstants.PublicTypeObsoleteMessage)] #endif public class TestSourceHost : ITestSourceHost { @@ -346,7 +346,7 @@ internal string GetAppBaseAsPerPlatform() // UWP platform service assembly at the test source location and since CLR starts looking for assemblies from the app base location, // there would be a mismatch of platform service assemblies during discovery. DebugEx.Assert(_targetFrameworkVersion is not null, "Target framework version is null."); - return _targetFrameworkVersion.Contains(Constants.DotNetFrameWorkStringPrefix) + return _targetFrameworkVersion.Contains(EngineConstants.DotNetFrameWorkStringPrefix) ? Path.GetDirectoryName(_sourceFileName) ?? Path.GetDirectoryName(typeof(TestSourceHost).Assembly.Location) : Path.GetDirectoryName(typeof(TestSourceHost).Assembly.Location); } diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Services/ThreadOperations.cs b/src/Adapter/MSTestAdapter.PlatformServices/Services/ThreadOperations.cs index 294ec53bfd..756793e443 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Services/ThreadOperations.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Services/ThreadOperations.cs @@ -10,9 +10,9 @@ namespace Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; /// This service is responsible for any Async operations specific to a platform. /// #if NET6_0_OR_GREATER -[Obsolete(Constants.PublicTypeObsoleteMessage, DiagnosticId = "MSTESTOBS")] +[Obsolete(TestTools.UnitTesting.FrameworkConstants.PublicTypeObsoleteMessage, DiagnosticId = "MSTESTOBS")] #else -[Obsolete(Constants.PublicTypeObsoleteMessage)] +[Obsolete(TestTools.UnitTesting.FrameworkConstants.PublicTypeObsoleteMessage)] #endif public class ThreadOperations : IThreadOperations { diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Services/ThreadSafeStringWriter.cs b/src/Adapter/MSTestAdapter.PlatformServices/Services/ThreadSafeStringWriter.cs index 95a4de695d..3859b40cd8 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Services/ThreadSafeStringWriter.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Services/ThreadSafeStringWriter.cs @@ -7,9 +7,9 @@ namespace Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; /// AsyncContext aware, thread safe string writer that allows output writes from different threads to end up in the same async local context. /// #if NET6_0_OR_GREATER -[Obsolete(Constants.PublicTypeObsoleteMessage, DiagnosticId = "MSTESTOBS")] +[Obsolete(TestTools.UnitTesting.FrameworkConstants.PublicTypeObsoleteMessage, DiagnosticId = "MSTESTOBS")] #else -[Obsolete(Constants.PublicTypeObsoleteMessage)] +[Obsolete(TestTools.UnitTesting.FrameworkConstants.PublicTypeObsoleteMessage)] #endif public class ThreadSafeStringWriter : StringWriter { diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Services/TraceListener.cs b/src/Adapter/MSTestAdapter.PlatformServices/Services/TraceListener.cs index 5308c23d72..485b351528 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Services/TraceListener.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Services/TraceListener.cs @@ -13,9 +13,9 @@ namespace Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; /// like Close(), Dispose() etc. /// #if NET6_0_OR_GREATER -[Obsolete(Constants.PublicTypeObsoleteMessage, DiagnosticId = "MSTESTOBS")] +[Obsolete(TestTools.UnitTesting.FrameworkConstants.PublicTypeObsoleteMessage, DiagnosticId = "MSTESTOBS")] #else -[Obsolete(Constants.PublicTypeObsoleteMessage)] +[Obsolete(TestTools.UnitTesting.FrameworkConstants.PublicTypeObsoleteMessage)] #endif public class TraceListenerWrapper : #if !WINDOWS_UWP && !WIN_UI diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Services/TraceListenerManager.cs b/src/Adapter/MSTestAdapter.PlatformServices/Services/TraceListenerManager.cs index e811d1cd15..1e427fc766 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Services/TraceListenerManager.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Services/TraceListenerManager.cs @@ -10,9 +10,9 @@ namespace Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; /// Responsible for performing Add(), Remove(), Close(), Dispose() operations on traceListener object. /// #if NET6_0_OR_GREATER -[Obsolete(Constants.PublicTypeObsoleteMessage, DiagnosticId = "MSTESTOBS")] +[Obsolete(TestTools.UnitTesting.FrameworkConstants.PublicTypeObsoleteMessage, DiagnosticId = "MSTESTOBS")] #else -[Obsolete(Constants.PublicTypeObsoleteMessage)] +[Obsolete(TestTools.UnitTesting.FrameworkConstants.PublicTypeObsoleteMessage)] #endif public class TraceListenerManager : ITraceListenerManager { diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Services/TraceLogger.cs b/src/Adapter/MSTestAdapter.PlatformServices/Services/TraceLogger.cs index 44baf76b71..982509eaef 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Services/TraceLogger.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Services/TraceLogger.cs @@ -10,9 +10,9 @@ namespace Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; /// A service to log any trace messages from the adapter that would be shown in *.TpTrace files. /// #if NET6_0_OR_GREATER -[Obsolete(Constants.PublicTypeObsoleteMessage, DiagnosticId = "MSTESTOBS")] +[Obsolete(TestTools.UnitTesting.FrameworkConstants.PublicTypeObsoleteMessage, DiagnosticId = "MSTESTOBS")] #else -[Obsolete(Constants.PublicTypeObsoleteMessage)] +[Obsolete(TestTools.UnitTesting.FrameworkConstants.PublicTypeObsoleteMessage)] #endif public class AdapterTraceLogger : IAdapterTraceLogger { diff --git a/src/Adapter/MSTest.TestAdapter/TestMethodFilter.cs b/src/Adapter/MSTestAdapter.PlatformServices/TestMethodFilter.cs similarity index 94% rename from src/Adapter/MSTest.TestAdapter/TestMethodFilter.cs rename to src/Adapter/MSTestAdapter.PlatformServices/TestMethodFilter.cs index a713f7acc8..5db7934e25 100644 --- a/src/Adapter/MSTest.TestAdapter/TestMethodFilter.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/TestMethodFilter.cs @@ -1,6 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; using Microsoft.VisualStudio.TestPlatform.ObjectModel; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging; @@ -17,12 +18,12 @@ internal sealed class TestMethodFilter internal TestMethodFilter() => _supportedProperties = new Dictionary(StringComparer.OrdinalIgnoreCase) { - [Constants.TestCategoryProperty.Label] = Constants.TestCategoryProperty, - [Constants.PriorityProperty.Label] = Constants.PriorityProperty, + [EngineConstants.TestCategoryProperty.Label] = EngineConstants.TestCategoryProperty, + [EngineConstants.PriorityProperty.Label] = EngineConstants.PriorityProperty, [TestCaseProperties.FullyQualifiedName.Label] = TestCaseProperties.FullyQualifiedName, [TestCaseProperties.DisplayName.Label] = TestCaseProperties.DisplayName, [TestCaseProperties.Id.Label] = TestCaseProperties.Id, - [Constants.TestClassNameProperty.Label] = Constants.TestClassNameProperty, + [EngineConstants.TestClassNameProperty.Label] = EngineConstants.TestClassNameProperty, }; /// diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Utilities/AppDomainUtilities.cs b/src/Adapter/MSTestAdapter.PlatformServices/Utilities/AppDomainUtilities.cs index a80126e0b1..a4151b99a3 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Utilities/AppDomainUtilities.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Utilities/AppDomainUtilities.cs @@ -42,7 +42,7 @@ internal static void SetAppDomainFrameworkVersionBasedOnTestSource(AppDomainSetu { if (GetTargetFrameworkVersionFromVersionString(frameworkVersionString).CompareTo(Version45) > 0) { - PropertyInfo? pInfo = typeof(AppDomainSetup).GetProperty(Constants.TargetFrameworkName); + PropertyInfo? pInfo = typeof(AppDomainSetup).GetProperty(EngineConstants.TargetFrameworkName); pInfo?.SetValue(setup, frameworkVersionString, null); } } @@ -227,9 +227,9 @@ internal static Version GetTargetFrameworkVersionFromVersionString(string versio { try { - if (version.Length > Constants.DotNetFrameWorkStringPrefix.Length + 1) + if (version.Length > EngineConstants.DotNetFrameWorkStringPrefix.Length + 1) { - string versionPart = version.Substring(Constants.DotNetFrameWorkStringPrefix.Length + 1); + string versionPart = version.Substring(EngineConstants.DotNetFrameWorkStringPrefix.Length + 1); return new Version(versionPart); } } diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Utilities/DeploymentItemUtility.cs b/src/Adapter/MSTestAdapter.PlatformServices/Utilities/DeploymentItemUtility.cs index e274bbf7c3..892345da66 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Utilities/DeploymentItemUtility.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Utilities/DeploymentItemUtility.cs @@ -227,7 +227,7 @@ private static List GetDeploymentItems(IEnumerable deploymentIte /// /// The test Case. /// The . - private static KeyValuePair[]? GetDeploymentItems(TestCase testCase) => testCase.GetPropertyValue(Constants.DeploymentItemsProperty) as + private static KeyValuePair[]? GetDeploymentItems(TestCase testCase) => testCase.GetPropertyValue(EngineConstants.DeploymentItemsProperty) as KeyValuePair[]; private static KeyValuePair[]? ToKeyValuePairs(IEnumerable deploymentItemList) diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Utilities/VSInstallationUtilities.cs b/src/Adapter/MSTestAdapter.PlatformServices/Utilities/VSInstallationUtilities.cs index 3083c603c8..07b01ef1dc 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Utilities/VSInstallationUtilities.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Utilities/VSInstallationUtilities.cs @@ -11,9 +11,9 @@ namespace Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Uti /// Utilities to get Visual Studio installation paths. /// #if NET6_0_OR_GREATER -[Obsolete(Constants.PublicTypeObsoleteMessage, DiagnosticId = "MSTESTOBS")] +[Obsolete(TestTools.UnitTesting.FrameworkConstants.PublicTypeObsoleteMessage, DiagnosticId = "MSTESTOBS")] #else -[Obsolete(Constants.PublicTypeObsoleteMessage)] +[Obsolete(TestTools.UnitTesting.FrameworkConstants.PublicTypeObsoleteMessage)] #endif public static class VSInstallationUtilities { diff --git a/src/Analyzers/MSTest.Analyzers/RoslynAnalyzerHelpers/ArrayBuilder.Enumerator.cs b/src/Analyzers/MSTest.Analyzers/RoslynAnalyzerHelpers/ArrayBuilder.Enumerator.cs index 2a2fd9a7e4..48340fbf6a 100644 --- a/src/Analyzers/MSTest.Analyzers/RoslynAnalyzerHelpers/ArrayBuilder.Enumerator.cs +++ b/src/Analyzers/MSTest.Analyzers/RoslynAnalyzerHelpers/ArrayBuilder.Enumerator.cs @@ -32,7 +32,7 @@ public readonly void Dispose() { } - readonly object? System.Collections.IEnumerator.Current => Current; + readonly object? IEnumerator.Current => Current; public void Reset() => _index = -1; } diff --git a/src/Analyzers/MSTest.Analyzers/RoslynAnalyzerHelpers/BoundedCacheWithFactory.cs b/src/Analyzers/MSTest.Analyzers/RoslynAnalyzerHelpers/BoundedCacheWithFactory.cs index 87250620aa..3a760e6bd9 100644 --- a/src/Analyzers/MSTest.Analyzers/RoslynAnalyzerHelpers/BoundedCacheWithFactory.cs +++ b/src/Analyzers/MSTest.Analyzers/RoslynAnalyzerHelpers/BoundedCacheWithFactory.cs @@ -4,7 +4,7 @@ namespace Analyzer.Utilities; /// /// Provides bounded cache for analyzers. -/// Acts as a good alternative to +/// Acts as a good alternative to /// when the cached value has a cyclic reference to the key preventing early garbage collection of entries. /// internal sealed class BoundedCacheWithFactory diff --git a/src/Platform/Microsoft.Testing.Extensions.Telemetry/AppInsightsProvider.cs b/src/Platform/Microsoft.Testing.Extensions.Telemetry/AppInsightsProvider.cs index 070495036b..3eb596cfa9 100644 --- a/src/Platform/Microsoft.Testing.Extensions.Telemetry/AppInsightsProvider.cs +++ b/src/Platform/Microsoft.Testing.Extensions.Telemetry/AppInsightsProvider.cs @@ -260,10 +260,10 @@ private static void AssertHashed(string key, string value) } #if NET7_0_OR_GREATER - [System.Text.RegularExpressions.GeneratedRegex("[a-f0-9]{64}")] - private static partial System.Text.RegularExpressions.Regex GetValidHashPattern(); + [GeneratedRegex("[a-f0-9]{64}")] + private static partial Regex GetValidHashPattern(); #else - private static System.Text.RegularExpressions.Regex GetValidHashPattern() + private static Regex GetValidHashPattern() => new("[a-f0-9]{64}"); #endif #endif diff --git a/src/Platform/Microsoft.Testing.Platform/Helpers/System/IProcess.cs b/src/Platform/Microsoft.Testing.Platform/Helpers/System/IProcess.cs index c64b4bbd97..df8a966669 100644 --- a/src/Platform/Microsoft.Testing.Platform/Helpers/System/IProcess.cs +++ b/src/Platform/Microsoft.Testing.Platform/Helpers/System/IProcess.cs @@ -7,23 +7,23 @@ internal interface IProcess : IDisposable { event EventHandler Exited; - /// + /// int Id { get; } - /// + /// string Name { get; } - /// + /// int ExitCode { get; } - /// + /// bool HasExited { get; } #if NETCOREAPP - /// + /// IMainModule? MainModule { get; } #else - /// + /// IMainModule MainModule { get; } #endif @@ -32,9 +32,9 @@ internal interface IProcess : IDisposable /// Task WaitForExitAsync(); - /// + /// void WaitForExit(); - /// + /// void Kill(); } diff --git a/src/TestFramework/TestFramework.Extensions/MessageLevel.cs b/src/TestFramework/TestFramework.Extensions/MessageLevel.cs index 064b617131..4d6fecd6f7 100644 --- a/src/TestFramework/TestFramework.Extensions/MessageLevel.cs +++ b/src/TestFramework/TestFramework.Extensions/MessageLevel.cs @@ -4,7 +4,7 @@ namespace Microsoft.VisualStudio.TestTools.UnitTesting; /// -/// Specifies the severity level of messages displayed using the API. +/// Specifies the severity level of messages displayed using the API. /// public enum MessageLevel { diff --git a/src/TestFramework/TestFramework/Exceptions/InternalTestFailureException.cs b/src/TestFramework/TestFramework/Exceptions/InternalTestFailureException.cs index 32cb00ab8f..519eb8b651 100644 --- a/src/TestFramework/TestFramework/Exceptions/InternalTestFailureException.cs +++ b/src/TestFramework/TestFramework/Exceptions/InternalTestFailureException.cs @@ -14,9 +14,9 @@ namespace Microsoft.VisualStudio.TestTools.UnitTesting; /// For all practical purposes either use AssertFailedException/AssertInconclusiveException. /// #if NET6_0_OR_GREATER -[Obsolete(Constants.PublicTypeObsoleteMessage, DiagnosticId = "MSTESTOBS")] +[Obsolete(FrameworkConstants.PublicTypeObsoleteMessage, DiagnosticId = "MSTESTOBS")] #else -[Obsolete(Constants.PublicTypeObsoleteMessage)] +[Obsolete(FrameworkConstants.PublicTypeObsoleteMessage)] #endif [Serializable] public class InternalTestFailureException : UnitTestAssertException diff --git a/src/TestFramework/TestFramework/Constants.cs b/src/TestFramework/TestFramework/FrameworkConstants.cs similarity index 92% rename from src/TestFramework/TestFramework/Constants.cs rename to src/TestFramework/TestFramework/FrameworkConstants.cs index 6973e5008c..7f37a607f6 100644 --- a/src/TestFramework/TestFramework/Constants.cs +++ b/src/TestFramework/TestFramework/FrameworkConstants.cs @@ -6,7 +6,7 @@ namespace Microsoft.VisualStudio.TestTools.UnitTesting; /// /// Constants used throughout. /// -internal static class Constants +internal static class FrameworkConstants { internal const string PublicTypeObsoleteMessage = "We will remove or hide this type starting with v4. If you are using this type, reach out to our team on https://github.com/microsoft/testfx."; } diff --git a/src/TestFramework/TestFramework/GenericParameterHelper.cs b/src/TestFramework/TestFramework/GenericParameterHelper.cs index 2012f7c748..238cbe201d 100644 --- a/src/TestFramework/TestFramework/GenericParameterHelper.cs +++ b/src/TestFramework/TestFramework/GenericParameterHelper.cs @@ -16,9 +16,9 @@ namespace Microsoft.VisualStudio.TestTools.UnitTesting; [SuppressMessage("Microsoft.Design", "CA1036:OverrideMethodsOnComparableTypes", Justification = "Compat reasons.")] [SuppressMessage("Design", "CA1010:Generic interface should also be implemented", Justification = "Part of the public API")] #if NET6_0_OR_GREATER -[Obsolete(Constants.PublicTypeObsoleteMessage, DiagnosticId = "MSTESTOBS")] +[Obsolete(FrameworkConstants.PublicTypeObsoleteMessage, DiagnosticId = "MSTESTOBS")] #else -[Obsolete(Constants.PublicTypeObsoleteMessage)] +[Obsolete(FrameworkConstants.PublicTypeObsoleteMessage)] #endif // GenericParameterHelper in full CLR version also implements ICloneable, but we don't have ICloneable in core CLR public class GenericParameterHelper : IComparable, IEnumerable diff --git a/src/TestFramework/TestFramework/TestFramework.csproj b/src/TestFramework/TestFramework/TestFramework.csproj index 5aa402300c..cce5f87580 100644 --- a/src/TestFramework/TestFramework/TestFramework.csproj +++ b/src/TestFramework/TestFramework/TestFramework.csproj @@ -40,6 +40,7 @@ + diff --git a/test/UnitTests/MSTestAdapter.UnitTests/Discovery/AssemblyEnumeratorTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Discovery/AssemblyEnumeratorTests.cs similarity index 99% rename from test/UnitTests/MSTestAdapter.UnitTests/Discovery/AssemblyEnumeratorTests.cs rename to test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Discovery/AssemblyEnumeratorTests.cs index afb9c13dde..bb874f4757 100644 --- a/test/UnitTests/MSTestAdapter.UnitTests/Discovery/AssemblyEnumeratorTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Discovery/AssemblyEnumeratorTests.cs @@ -7,6 +7,7 @@ using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Discovery; using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Helpers; using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel; +using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.TestableImplementations; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging; diff --git a/test/UnitTests/MSTestAdapter.UnitTests/Discovery/AssemblyEnumeratorWrapperTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Discovery/AssemblyEnumeratorWrapperTests.cs similarity index 98% rename from test/UnitTests/MSTestAdapter.UnitTests/Discovery/AssemblyEnumeratorWrapperTests.cs rename to test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Discovery/AssemblyEnumeratorWrapperTests.cs index 95d6da8f50..4276e16d93 100644 --- a/test/UnitTests/MSTestAdapter.UnitTests/Discovery/AssemblyEnumeratorWrapperTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Discovery/AssemblyEnumeratorWrapperTests.cs @@ -3,14 +3,13 @@ using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter; using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Discovery; +using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.TestableImplementations; using Moq; using TestFramework.ForTestingMSTest; -using UTF = Microsoft.VisualStudio.TestTools.UnitTesting; - namespace Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Discovery; public class AssemblyEnumeratorWrapperTests : TestContainer @@ -178,11 +177,11 @@ private void SetupMocks(string assemblyName, bool doesFileExist, bool isAssembly #region dummy implementations. - [UTF.TestClass] + [TestClass] public class ValidTestClass { // This is just a dummy method for test validation. - [UTF.TestMethod] + [TestMethod] public void ValidTestMethod() { } diff --git a/test/UnitTests/MSTestAdapter.UnitTests/Discovery/TestMethodValidatorTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Discovery/TestMethodValidatorTests.cs similarity index 96% rename from test/UnitTests/MSTestAdapter.UnitTests/Discovery/TestMethodValidatorTests.cs rename to test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Discovery/TestMethodValidatorTests.cs index e660a7a115..faf2d778f2 100644 --- a/test/UnitTests/MSTestAdapter.UnitTests/Discovery/TestMethodValidatorTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Discovery/TestMethodValidatorTests.cs @@ -8,8 +8,6 @@ using TestFramework.ForTestingMSTest; -using UTF = Microsoft.VisualStudio.TestTools.UnitTesting; - namespace Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Discovery; public class TestMethodValidatorTests : TestContainer @@ -34,7 +32,7 @@ public TestMethodValidatorTests() public void IsValidTestMethodShouldReturnFalseForMethodsWithoutATestMethodAttributeOrItsDerivedAttributes() { _mockReflectHelper.Setup( - rh => rh.IsAttributeDefined(It.IsAny(), false)).Returns(false); + rh => rh.IsAttributeDefined(It.IsAny(), false)).Returns(false); Verify(!_testMethodValidator.IsValidTestMethod(_mockMethodInfo.Object, _type, _warnings)); } @@ -190,7 +188,7 @@ public void WhenDiscoveryOfInternalsIsEnabledIsValidTestMethodShouldReturnFalseF private void SetupTestMethod() => _mockReflectHelper.Setup( - rh => rh.IsAttributeDefined(It.IsAny(), false)).Returns(true); + rh => rh.IsAttributeDefined(It.IsAny(), false)).Returns(true); } #region Dummy types diff --git a/test/UnitTests/MSTestAdapter.UnitTests/Discovery/TypeEnumeratorTests.MockedMethodInfoWithExtraAttributes.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Discovery/TypeEnumeratorTests.MockedMethodInfoWithExtraAttributes.cs similarity index 100% rename from test/UnitTests/MSTestAdapter.UnitTests/Discovery/TypeEnumeratorTests.MockedMethodInfoWithExtraAttributes.cs rename to test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Discovery/TypeEnumeratorTests.MockedMethodInfoWithExtraAttributes.cs diff --git a/test/UnitTests/MSTestAdapter.UnitTests/Discovery/TypeEnumeratorTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Discovery/TypeEnumeratorTests.cs similarity index 100% rename from test/UnitTests/MSTestAdapter.UnitTests/Discovery/TypeEnumeratorTests.cs rename to test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Discovery/TypeEnumeratorTests.cs diff --git a/test/UnitTests/MSTestAdapter.UnitTests/Discovery/TypeValidatorTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Discovery/TypeValidatorTests.cs similarity index 95% rename from test/UnitTests/MSTestAdapter.UnitTests/Discovery/TypeValidatorTests.cs rename to test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Discovery/TypeValidatorTests.cs index 3e15bc8c09..0450385460 100644 --- a/test/UnitTests/MSTestAdapter.UnitTests/Discovery/TypeValidatorTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Discovery/TypeValidatorTests.cs @@ -1,17 +1,14 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. -using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter; using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Discovery; using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Helpers; +using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; using Moq; using TestFramework.ForTestingMSTest; -using UTF = Microsoft.VisualStudio.TestTools.UnitTesting; -using UTFExtension = Microsoft.VisualStudio.TestTools.UnitTesting; - namespace Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Discovery; public class TypeValidatorTests : TestContainer @@ -41,15 +38,15 @@ public TypeValidatorTests() public void IsValidTestClassShouldReturnFalseForClassesNotHavingTestClassAttributeOrDerivedAttributeTypes() { - _mockReflectHelper.Setup(rh => rh.IsAttributeDefined(It.IsAny(), false)).Returns(false); + _mockReflectHelper.Setup(rh => rh.IsAttributeDefined(It.IsAny(), false)).Returns(false); Verify(!_typeValidator.IsValidTestClass(typeof(TypeValidatorTests), _warnings)); } public void IsValidTestClassShouldReturnTrueForClassesMarkedByAnAttributeDerivedFromTestClass() { - _mockReflectHelper.Setup(rh => rh.IsAttributeDefined(It.IsAny(), false)).Returns(false); + _mockReflectHelper.Setup(rh => rh.IsAttributeDefined(It.IsAny(), false)).Returns(false); _mockReflectHelper.Setup( - rh => rh.IsAttributeDefined(It.IsAny(), false)).Returns(true); + rh => rh.IsAttributeDefined(It.IsAny(), false)).Returns(true); Verify(_typeValidator.IsValidTestClass(typeof(TypeValidatorTests), _warnings)); } @@ -393,7 +390,7 @@ private static Type[] GetAllTestTypes() #region private methods - private void SetupTestClass() => _mockReflectHelper.Setup(rh => rh.IsAttributeDefined(It.IsAny(), false)).Returns(true); + private void SetupTestClass() => _mockReflectHelper.Setup(rh => rh.IsAttributeDefined(It.IsAny(), false)).Returns(true); #endregion } @@ -412,27 +409,27 @@ public class GenericClass; public class ClassWithTestContextGetterOnly { - public UTFExtension.TestContext TestContext { get; } = null!; + public TestContext TestContext { get; } = null!; } public class ClassWithTestContextPrivateSetter { - public UTFExtension.TestContext TestContext { get; private set; } = null!; + public TestContext TestContext { get; private set; } = null!; } public class ClassWithStaticTestContext { - public static UTFExtension.TestContext TestContext { get; set; } = null!; + public static TestContext TestContext { get; set; } = null!; } public abstract class ClassWithAbstractTestContext { - public abstract UTFExtension.TestContext TestContext { get; set; } + public abstract TestContext TestContext { get; set; } } public class ClassWithTestContext { - public UTFExtension.TestContext TestContext { get; set; } = null!; + public TestContext TestContext { get; set; } = null!; } public class GenericClassWithProperty @@ -456,7 +453,7 @@ public class GenericClassWithTestContext public bool Something { get; } - public UTFExtension.TestContext TestContext { get; set; } = null!; + public TestContext TestContext { get; set; } = null!; } public class PublicTestClass; diff --git a/test/UnitTests/MSTestAdapter.UnitTests/Discovery/UnitTestDiscovererTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Discovery/UnitTestDiscovererTests.cs similarity index 100% rename from test/UnitTests/MSTestAdapter.UnitTests/Discovery/UnitTestDiscovererTests.cs rename to test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Discovery/UnitTestDiscovererTests.cs diff --git a/test/UnitTests/MSTestAdapter.UnitTests/Execution/ClassCleanupManagerTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/ClassCleanupManagerTests.cs similarity index 100% rename from test/UnitTests/MSTestAdapter.UnitTests/Execution/ClassCleanupManagerTests.cs rename to test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/ClassCleanupManagerTests.cs diff --git a/test/UnitTests/MSTestAdapter.UnitTests/Execution/LogMessageListenerTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/LogMessageListenerTests.cs similarity index 100% rename from test/UnitTests/MSTestAdapter.UnitTests/Execution/LogMessageListenerTests.cs rename to test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/LogMessageListenerTests.cs diff --git a/test/UnitTests/MSTestAdapter.UnitTests/Execution/TcmTestPropertiesProviderTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TcmTestPropertiesProviderTests.cs similarity index 87% rename from test/UnitTests/MSTestAdapter.UnitTests/Execution/TcmTestPropertiesProviderTests.cs rename to test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TcmTestPropertiesProviderTests.cs index 9c14439ad2..44116b386d 100644 --- a/test/UnitTests/MSTestAdapter.UnitTests/Execution/TcmTestPropertiesProviderTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TcmTestPropertiesProviderTests.cs @@ -2,33 +2,32 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution; +using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; using Microsoft.VisualStudio.TestPlatform.ObjectModel; using TestFramework.ForTestingMSTest; -using TestAdapterConstants = Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Constants; - namespace Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Execution; public class TcmTestPropertiesProviderTests : TestContainer { private readonly TestProperty[] _tcmKnownProperties = [ - TestAdapterConstants.TestRunIdProperty, - TestAdapterConstants.TestPlanIdProperty, - TestAdapterConstants.BuildConfigurationIdProperty, - TestAdapterConstants.BuildDirectoryProperty, - TestAdapterConstants.BuildFlavorProperty, - TestAdapterConstants.BuildNumberProperty, - TestAdapterConstants.BuildPlatformProperty, - TestAdapterConstants.BuildUriProperty, - TestAdapterConstants.TfsServerCollectionUrlProperty, - TestAdapterConstants.TfsTeamProjectProperty, - TestAdapterConstants.IsInLabEnvironmentProperty, - TestAdapterConstants.TestCaseIdProperty, - TestAdapterConstants.TestConfigurationIdProperty, - TestAdapterConstants.TestConfigurationNameProperty, - TestAdapterConstants.TestPointIdProperty, + EngineConstants.TestRunIdProperty, + EngineConstants.TestPlanIdProperty, + EngineConstants.BuildConfigurationIdProperty, + EngineConstants.BuildDirectoryProperty, + EngineConstants.BuildFlavorProperty, + EngineConstants.BuildNumberProperty, + EngineConstants.BuildPlatformProperty, + EngineConstants.BuildUriProperty, + EngineConstants.TfsServerCollectionUrlProperty, + EngineConstants.TfsTeamProjectProperty, + EngineConstants.IsInLabEnvironmentProperty, + EngineConstants.TestCaseIdProperty, + EngineConstants.TestConfigurationIdProperty, + EngineConstants.TestConfigurationNameProperty, + EngineConstants.TestPointIdProperty, ]; public void GetTcmPropertiesShouldReturnEmptyDictionaryIfTestCaseIsNull() @@ -220,9 +219,9 @@ public void GetTcmPropertiesShouldHandleDuplicateTestsProperlyFromTestCase() private void SetTestCaseProperties(TestCase testCase, object[] propertiesValue) { - System.Collections.IEnumerator tcmKnownPropertiesEnumerator = _tcmKnownProperties.GetEnumerator(); + IEnumerator tcmKnownPropertiesEnumerator = _tcmKnownProperties.GetEnumerator(); - System.Collections.IEnumerator propertiesValueEnumerator = propertiesValue.GetEnumerator(); + IEnumerator propertiesValueEnumerator = propertiesValue.GetEnumerator(); while (tcmKnownPropertiesEnumerator.MoveNext() && propertiesValueEnumerator.MoveNext()) { object? property = tcmKnownPropertiesEnumerator.Current; diff --git a/test/UnitTests/MSTestAdapter.UnitTests/Execution/TestAssemblyInfoTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestAssemblyInfoTests.cs similarity index 96% rename from test/UnitTests/MSTestAdapter.UnitTests/Execution/TestAssemblyInfoTests.cs rename to test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestAssemblyInfoTests.cs index c2f674af8d..e95b9c01cc 100644 --- a/test/UnitTests/MSTestAdapter.UnitTests/Execution/TestAssemblyInfoTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestAssemblyInfoTests.cs @@ -9,7 +9,6 @@ using TestFramework.ForTestingMSTest; using UTF = Microsoft.VisualStudio.TestTools.UnitTesting; -using UTFExtension = Microsoft.VisualStudio.TestTools.UnitTesting; namespace Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Execution; @@ -19,14 +18,14 @@ public class TestAssemblyInfoTests : TestContainer private readonly MethodInfo _dummyMethodInfo; - private readonly UTFExtension.TestContext _testContext; + private readonly TestContext _testContext; public TestAssemblyInfoTests() { _testAssemblyInfo = new TestAssemblyInfo(typeof(TestAssemblyInfoTests).Assembly); _dummyMethodInfo = typeof(TestAssemblyInfoTests).GetMethods().First(); - var testContext = new Mock(); + var testContext = new Mock(); testContext.SetupGet(x => x.CancellationTokenSource).Returns(new CancellationTokenSource()); _testContext = testContext.Object; } @@ -152,7 +151,7 @@ public void RunAssemblyInitializeShouldThrowTestFailedExceptionOnAssertionFailur Verify(exception.StackTraceInformation!.ErrorStackTrace.StartsWith( " at Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Execution.TestAssemblyInfoTests.<>c.", StringComparison.Ordinal)); #endif - Verify(exception.InnerException!.GetType() == typeof(UTF.AssertFailedException)); + Verify(exception.InnerException!.GetType() == typeof(AssertFailedException)); } public void RunAssemblyInitializeShouldThrowTestFailedExceptionWithInconclusiveOnAssertInconclusive() @@ -169,7 +168,7 @@ public void RunAssemblyInitializeShouldThrowTestFailedExceptionWithInconclusiveO Verify(exception.StackTraceInformation!.ErrorStackTrace.StartsWith( " at Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Execution.TestAssemblyInfoTests.<>c.", StringComparison.Ordinal)); #endif - Verify(exception.InnerException!.GetType() == typeof(UTF.AssertInconclusiveException)); + Verify(exception.InnerException!.GetType() == typeof(AssertInconclusiveException)); } public void RunAssemblyInitializeShouldThrowTestFailedExceptionWithNonAssertExceptions() @@ -311,16 +310,16 @@ public void RunAssemblyCleanupShouldThrowTheInnerMostExceptionWhenThereAreMultip #endregion - [UTF.TestClass] + [TestClass] public class DummyTestClass { public static Action AssemblyInitializeMethodBody { get; set; } = null!; public static Action AssemblyCleanupMethodBody { get; set; } = null!; - public UTFExtension.TestContext TestContext { get; set; } = null!; + public TestContext TestContext { get; set; } = null!; - public static void AssemblyInitializeMethod(UTFExtension.TestContext testContext) => AssemblyInitializeMethodBody.Invoke(testContext); + public static void AssemblyInitializeMethod(TestContext testContext) => AssemblyInitializeMethodBody.Invoke(testContext); public static void AssemblyCleanupMethod() => AssemblyCleanupMethodBody.Invoke(); } diff --git a/test/UnitTests/MSTestAdapter.UnitTests/Execution/TestAssemblySettingsProviderTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestAssemblySettingsProviderTests.cs similarity index 91% rename from test/UnitTests/MSTestAdapter.UnitTests/Execution/TestAssemblySettingsProviderTests.cs rename to test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestAssemblySettingsProviderTests.cs index 9d7754323d..328091f21f 100644 --- a/test/UnitTests/MSTestAdapter.UnitTests/Execution/TestAssemblySettingsProviderTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestAssemblySettingsProviderTests.cs @@ -9,7 +9,7 @@ using TestFramework.ForTestingMSTest; -using UTF = Microsoft.VisualStudio.TestTools.UnitTesting; +using ExecutionScope = Microsoft.VisualStudio.TestTools.UnitTesting.ExecutionScope; namespace Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Execution; @@ -58,8 +58,8 @@ public void GetSettingsShouldSetParallelWorkers() .Returns(Assembly.GetExecutingAssembly()); _testablePlatformServiceProvider .MockReflectionOperations - .Setup(ro => ro.GetCustomAttributes(It.IsAny(), typeof(UTF.ParallelizeAttribute))) - .Returns([new UTF.ParallelizeAttribute { Workers = 10 }]); + .Setup(ro => ro.GetCustomAttributes(It.IsAny(), typeof(ParallelizeAttribute))) + .Returns([new ParallelizeAttribute { Workers = 10 }]); // Act. MSTest.TestAdapter.ObjectModel.TestAssemblySettings settings = new TestAssemblySettingsProvider().GetSettings("Foo"); @@ -77,8 +77,8 @@ public void GetSettingsShouldSetParallelWorkersToProcessorCountIfZero() .Returns(Assembly.GetExecutingAssembly()); _testablePlatformServiceProvider .MockReflectionOperations - .Setup(ro => ro.GetCustomAttributes(It.IsAny(), typeof(UTF.ParallelizeAttribute))) - .Returns([new UTF.ParallelizeAttribute { Workers = 0 }]); + .Setup(ro => ro.GetCustomAttributes(It.IsAny(), typeof(ParallelizeAttribute))) + .Returns([new ParallelizeAttribute { Workers = 0 }]); // Act. MSTest.TestAdapter.ObjectModel.TestAssemblySettings settings = new TestAssemblySettingsProvider().GetSettings("Foo"); @@ -111,8 +111,8 @@ public void GetSettingsShouldSetParallelScope() .Returns(Assembly.GetExecutingAssembly()); _testablePlatformServiceProvider .MockReflectionOperations - .Setup(ro => ro.GetCustomAttributes(It.IsAny(), typeof(UTF.ParallelizeAttribute))) - .Returns([new UTF.ParallelizeAttribute { Scope = ExecutionScope.MethodLevel }]); + .Setup(ro => ro.GetCustomAttributes(It.IsAny(), typeof(ParallelizeAttribute))) + .Returns([new ParallelizeAttribute { Scope = ExecutionScope.MethodLevel }]); // Act. MSTest.TestAdapter.ObjectModel.TestAssemblySettings settings = new TestAssemblySettingsProvider().GetSettings("Foo"); @@ -145,8 +145,8 @@ public void GetSettingsShouldSetCanParallelizeAssemblyToFalseIfDoNotParallelizeI .Returns(Assembly.GetExecutingAssembly()); _testablePlatformServiceProvider .MockReflectionOperations - .Setup(ro => ro.GetCustomAttributes(It.IsAny(), typeof(UTF.DoNotParallelizeAttribute))) - .Returns([new UTF.DoNotParallelizeAttribute()]); + .Setup(ro => ro.GetCustomAttributes(It.IsAny(), typeof(DoNotParallelizeAttribute))) + .Returns([new DoNotParallelizeAttribute()]); // Act. MSTest.TestAdapter.ObjectModel.TestAssemblySettings settings = new TestAssemblySettingsProvider().GetSettings("Foo"); diff --git a/test/UnitTests/MSTestAdapter.UnitTests/Execution/TestCaseDiscoverySinkTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestCaseDiscoverySinkTests.cs similarity index 100% rename from test/UnitTests/MSTestAdapter.UnitTests/Execution/TestCaseDiscoverySinkTests.cs rename to test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestCaseDiscoverySinkTests.cs diff --git a/test/UnitTests/MSTestAdapter.UnitTests/Execution/TestClassInfoTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestClassInfoTests.cs similarity index 95% rename from test/UnitTests/MSTestAdapter.UnitTests/Execution/TestClassInfoTests.cs rename to test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestClassInfoTests.cs index a079faea13..3e0a7eaad0 100644 --- a/test/UnitTests/MSTestAdapter.UnitTests/Execution/TestClassInfoTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestClassInfoTests.cs @@ -11,7 +11,6 @@ using TestFramework.ForTestingMSTest; using UTF = Microsoft.VisualStudio.TestTools.UnitTesting; -using UTFExtension = Microsoft.VisualStudio.TestTools.UnitTesting; namespace Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Execution; @@ -55,11 +54,11 @@ public void ClearDiagnosticMessages() private readonly ConstructorInfo _testClassConstructor; - private readonly UTF.TestClassAttribute _testClassAttribute; + private readonly TestClassAttribute _testClassAttribute; private readonly TestAssemblyInfo _testAssemblyInfo; - private readonly UTFExtension.TestContext _testContext; + private readonly TestContext _testContext; private readonly TestClassInfo _testClassInfo; @@ -77,7 +76,7 @@ public TestClassInfoTests() _testClassAttribute, _testAssemblyInfo); - var testContext = new Mock(); + var testContext = new Mock(); testContext.SetupGet(x => x.CancellationTokenSource).Returns(new CancellationTokenSource()); _testContext = testContext.Object; @@ -363,7 +362,7 @@ public void RunClassInitializeShouldThrowTestFailedExceptionOnAssertionFailure() Verify(exception.StackTraceInformation!.ErrorStackTrace.StartsWith( " at Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Execution.TestClassInfoTests.<>c.", StringComparison.Ordinal)); #endif - Verify(exception.InnerException!.GetType() == typeof(UTF.AssertFailedException)); + Verify(exception.InnerException!.GetType() == typeof(AssertFailedException)); } public void RunClassInitializeShouldThrowTestFailedExceptionWithInconclusiveOnAssertInconclusive() @@ -382,7 +381,7 @@ public void RunClassInitializeShouldThrowTestFailedExceptionWithInconclusiveOnAs Verify(exception.StackTraceInformation!.ErrorStackTrace.StartsWith( " at Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Execution.TestClassInfoTests.<>c.", StringComparison.Ordinal)); #endif - Verify(exception.InnerException!.GetType() == typeof(UTF.AssertInconclusiveException)); + Verify(exception.InnerException!.GetType() == typeof(AssertInconclusiveException)); } public void RunClassInitializeShouldThrowTestFailedExceptionWithNonAssertExceptions() @@ -627,10 +626,10 @@ public class DummyGrandParentTestClass public static Action CleanupClassMethodBody { get; set; } = null!; - public UTFExtension.TestContext BaseTestContext { get; set; } = null!; + public TestContext BaseTestContext { get; set; } = null!; - [UTF.ClassInitialize(UTF.InheritanceBehavior.BeforeEachDerivedClass)] - public static void InitClassMethod(UTFExtension.TestContext testContext) => ClassInitMethodBody?.Invoke(testContext); + [ClassInitialize(UTF.InheritanceBehavior.BeforeEachDerivedClass)] + public static void InitClassMethod(TestContext testContext) => ClassInitMethodBody?.Invoke(testContext); public static void ClassCleanupMethod() => CleanupClassMethodBody?.Invoke(); } @@ -642,10 +641,10 @@ public class DummyBaseTestClass : DummyGrandParentTestClass public static Action ClassCleanupMethodBody { get; set; } = null!; - public UTFExtension.TestContext TestContext { get; set; } = null!; + public TestContext TestContext { get; set; } = null!; - [UTF.ClassInitialize(UTF.InheritanceBehavior.BeforeEachDerivedClass)] - public static void InitBaseClassMethod(UTFExtension.TestContext testContext) => ClassInitializeMethodBody?.Invoke(testContext); + [ClassInitialize(UTF.InheritanceBehavior.BeforeEachDerivedClass)] + public static void InitBaseClassMethod(TestContext testContext) => ClassInitializeMethodBody?.Invoke(testContext); public static void CleanupClassMethod() => ClassCleanupMethodBody?.Invoke(); } @@ -657,9 +656,9 @@ public class DummyDerivedTestClass : DummyBaseTestClass public static Action DerivedClassCleanupMethodBody { get; set; } = null!; - public UTFExtension.TestContext Context { get; set; } = null!; + public TestContext Context { get; set; } = null!; - public static void InitDerivedClassMethod(UTFExtension.TestContext testContext) => DerivedClassInitializeMethodBody?.Invoke(testContext); + public static void InitDerivedClassMethod(TestContext testContext) => DerivedClassInitializeMethodBody?.Invoke(testContext); public static void CleanupDerivedClassMethod() => DerivedClassCleanupMethodBody?.Invoke(); } @@ -671,14 +670,14 @@ public class DummyTestClass public static Action ClassCleanupMethodBody { get; set; } = null!; - public UTFExtension.TestContext TestContext { get; set; } = null!; + public TestContext TestContext { get; set; } = null!; - public static void ClassInitializeMethod(UTFExtension.TestContext testContext) => ClassInitializeMethodBody?.Invoke(testContext); + public static void ClassInitializeMethod(TestContext testContext) => ClassInitializeMethodBody?.Invoke(testContext); public static void ClassCleanupMethod() => ClassCleanupMethodBody?.Invoke(); } - private class DummyTestClassAttribute : UTF.TestClassAttribute; + private class DummyTestClassAttribute : TestClassAttribute; private static class FailingStaticHelper { diff --git a/test/UnitTests/MSTestAdapter.UnitTests/Execution/TestExecutionManagerTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestExecutionManagerTests.cs similarity index 97% rename from test/UnitTests/MSTestAdapter.UnitTests/Execution/TestExecutionManagerTests.cs rename to test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestExecutionManagerTests.cs index 2f1fe65132..f70d4e8d4c 100644 --- a/test/UnitTests/MSTestAdapter.UnitTests/Execution/TestExecutionManagerTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestExecutionManagerTests.cs @@ -16,7 +16,7 @@ using TestFramework.ForTestingMSTest; -using TestAdapterConstants = Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Constants; +using ExecutionScope = Microsoft.VisualStudio.TestTools.UnitTesting.ExecutionScope; using TestResult = Microsoft.VisualStudio.TestPlatform.ObjectModel.TestResult; namespace Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Execution; @@ -30,21 +30,21 @@ public class TestExecutionManagerTests : TestContainer private readonly TestProperty[] _tcmKnownProperties = [ - TestAdapterConstants.TestRunIdProperty, - TestAdapterConstants.TestPlanIdProperty, - TestAdapterConstants.BuildConfigurationIdProperty, - TestAdapterConstants.BuildDirectoryProperty, - TestAdapterConstants.BuildFlavorProperty, - TestAdapterConstants.BuildNumberProperty, - TestAdapterConstants.BuildPlatformProperty, - TestAdapterConstants.BuildUriProperty, - TestAdapterConstants.TfsServerCollectionUrlProperty, - TestAdapterConstants.TfsTeamProjectProperty, - TestAdapterConstants.IsInLabEnvironmentProperty, - TestAdapterConstants.TestCaseIdProperty, - TestAdapterConstants.TestConfigurationIdProperty, - TestAdapterConstants.TestConfigurationNameProperty, - TestAdapterConstants.TestPointIdProperty, + EngineConstants.TestRunIdProperty, + EngineConstants.TestPlanIdProperty, + EngineConstants.BuildConfigurationIdProperty, + EngineConstants.BuildDirectoryProperty, + EngineConstants.BuildFlavorProperty, + EngineConstants.BuildNumberProperty, + EngineConstants.BuildPlatformProperty, + EngineConstants.BuildUriProperty, + EngineConstants.TfsServerCollectionUrlProperty, + EngineConstants.TfsTeamProjectProperty, + EngineConstants.IsInLabEnvironmentProperty, + EngineConstants.TestCaseIdProperty, + EngineConstants.TestConfigurationIdProperty, + EngineConstants.TestConfigurationNameProperty, + EngineConstants.TestPointIdProperty, ]; private TestableRunContextTestExecutionTests _runContext; @@ -666,8 +666,8 @@ public async Task RunTestsForTestShouldRunNonParallelizableTestsSeparately() TestCase testCase3 = GetTestCase(typeof(DummyTestClassWithDoNotParallelizeMethods), "TestMethod3"); TestCase testCase4 = GetTestCase(typeof(DummyTestClassWithDoNotParallelizeMethods), "TestMethod4"); - testCase3.SetPropertyValue(TestAdapterConstants.DoNotParallelizeProperty, true); - testCase4.SetPropertyValue(TestAdapterConstants.DoNotParallelizeProperty, true); + testCase3.SetPropertyValue(EngineConstants.DoNotParallelizeProperty, true); + testCase4.SetPropertyValue(EngineConstants.DoNotParallelizeProperty, true); TestCase[] tests = [testCase1, testCase2, testCase3, testCase4]; _runContext.MockRunSettings.Setup(rs => rs.SettingsXml).Returns( @@ -776,7 +776,7 @@ private async Task RunTestsForTestShouldRunTestsInTheParentDomainsApartmentState TestCase testCase3 = GetTestCase(typeof(DummyTestClassWithDoNotParallelizeMethods), "TestMethod3"); TestCase testCase4 = GetTestCase(typeof(DummyTestClassWithDoNotParallelizeMethods), "TestMethod4"); - testCase4.SetPropertyValue(TestAdapterConstants.DoNotParallelizeProperty, true); + testCase4.SetPropertyValue(EngineConstants.DoNotParallelizeProperty, true); TestCase[] tests = [testCase1, testCase2, testCase3, testCase4]; _runContext.MockRunSettings.Setup(rs => rs.SettingsXml).Returns( @@ -861,9 +861,9 @@ private void VerifyTcmProperties(IDictionary? tcmProperties, Tes private void SetTestCaseProperties(TestCase testCase, object[] propertiesValue) { - System.Collections.IEnumerator tcmKnownPropertiesEnumerator = _tcmKnownProperties.GetEnumerator(); + IEnumerator tcmKnownPropertiesEnumerator = _tcmKnownProperties.GetEnumerator(); - System.Collections.IEnumerator propertiesValueEnumerator = propertiesValue.GetEnumerator(); + IEnumerator propertiesValueEnumerator = propertiesValue.GetEnumerator(); while (tcmKnownPropertiesEnumerator.MoveNext() && propertiesValueEnumerator.MoveNext()) { object? property = tcmKnownPropertiesEnumerator.Current; diff --git a/test/UnitTests/MSTestAdapter.UnitTests/Execution/TestMethodFilterTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestMethodFilterTests.cs similarity index 93% rename from test/UnitTests/MSTestAdapter.UnitTests/Execution/TestMethodFilterTests.cs rename to test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestMethodFilterTests.cs index e416447e4b..38c133d45a 100644 --- a/test/UnitTests/MSTestAdapter.UnitTests/Execution/TestMethodFilterTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestMethodFilterTests.cs @@ -2,15 +2,13 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter; +using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; using Microsoft.VisualStudio.TestPlatform.ObjectModel; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging; using TestFramework.ForTestingMSTest; -using UTF = Microsoft.VisualStudio.TestTools.UnitTesting; -using UTFExtension = Microsoft.VisualStudio.TestTools.UnitTesting; - namespace Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Execution; public class TestMethodFilterTests : TestContainer @@ -59,7 +57,7 @@ public void PropertyProviderValueForInvalidPropertyNameReturnsNull() { Type type = typeof(DummyTestClassWithTestMethods); string fullName = $"{type.FullName}.TestMethod"; - TestCase testCase = new(fullName, MSTest.TestAdapter.Constants.ExecutorUri, Assembly.GetExecutingAssembly().FullName!); + TestCase testCase = new(fullName, EngineConstants.ExecutorUri, Assembly.GetExecutingAssembly().FullName!); object? result = _testMethodFilter.PropertyValueProvider(testCase, null); Verify(result is null); @@ -70,7 +68,7 @@ public void PropertyProviderValueForSupportedPropertyNameWhichIsNotSetReturnsNul Type type = typeof(DummyTestClassWithTestMethods); string fullName = $"{type.FullName}.TestMethod"; - TestCase testCase = new(fullName, MSTest.TestAdapter.Constants.ExecutorUri, Assembly.GetExecutingAssembly().FullName!); + TestCase testCase = new(fullName, EngineConstants.ExecutorUri, Assembly.GetExecutingAssembly().FullName!); object? result = _testMethodFilter.PropertyValueProvider(testCase, "Priority"); Verify(result is null); } @@ -80,7 +78,7 @@ public void PropertyProviderValueForValidTestAndSupportedPropertyNameReturnsValu Type type = typeof(DummyTestClassWithTestMethods); string fullName = $"{type.FullName}.TestMethod"; - TestCase testCase = new(fullName, MSTest.TestAdapter.Constants.ExecutorUri, Assembly.GetExecutingAssembly().FullName!); + TestCase testCase = new(fullName, EngineConstants.ExecutorUri, Assembly.GetExecutingAssembly().FullName!); object? result = _testMethodFilter.PropertyValueProvider(testCase, "FullyQualifiedName"); Verify(fullName.Equals(result)); @@ -163,9 +161,9 @@ public void GetFilterExpressionForDiscoveryContextWithGetTestCaseFilterThrowingE [DummyTestClass] internal class DummyTestClassWithTestMethods { - public UTFExtension.TestContext TestContext { get; set; } = null!; + public TestContext TestContext { get; set; } = null!; - [UTF.TestMethod] + [TestMethod] public void TestMethod() { } @@ -232,5 +230,5 @@ private sealed class TestableTestCaseFilterExpression : ITestCaseFilterExpressio public bool MatchTestCase(TestCase testCase, Func propertyValueProvider) => throw new NotImplementedException(); } - private class DummyTestClassAttribute : UTF.TestClassAttribute; + private class DummyTestClassAttribute : TestClassAttribute; } diff --git a/test/UnitTests/MSTestAdapter.UnitTests/Execution/TestMethodInfoTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestMethodInfoTests.cs similarity index 91% rename from test/UnitTests/MSTestAdapter.UnitTests/Execution/TestMethodInfoTests.cs rename to test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestMethodInfoTests.cs index b91c041b66..d0af85fbd1 100644 --- a/test/UnitTests/MSTestAdapter.UnitTests/Execution/TestMethodInfoTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestMethodInfoTests.cs @@ -12,9 +12,7 @@ using TestFramework.ForTestingMSTest; -using Resource = Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Resource; using UTF = Microsoft.VisualStudio.TestTools.UnitTesting; -using UTFExtension = Microsoft.VisualStudio.TestTools.UnitTesting; namespace Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Execution; @@ -27,9 +25,9 @@ public class TestMethodInfoTests : TestContainer private readonly MethodInfo _methodInfo; - private readonly UTF.TestClassAttribute _classAttribute; + private readonly TestClassAttribute _classAttribute; - private readonly UTF.TestMethodAttribute _testMethodAttribute; + private readonly TestMethodAttribute _testMethodAttribute; private readonly TestAssemblyInfo _testAssemblyInfo; @@ -39,20 +37,20 @@ public class TestMethodInfoTests : TestContainer private readonly TestClassInfo _testClassInfo; - private readonly UTF.ExpectedExceptionAttribute _expectedException; + private readonly ExpectedExceptionAttribute _expectedException; public TestMethodInfoTests() { _constructorInfo = typeof(DummyTestClass).GetConstructor([])!; _methodInfo = typeof(DummyTestClass).GetMethods().Single(m => m.Name.Equals("DummyTestMethod", StringComparison.Ordinal)); - _classAttribute = new UTF.TestClassAttribute(); - _testMethodAttribute = new UTF.TestMethodAttribute(); + _classAttribute = new TestClassAttribute(); + _testMethodAttribute = new TestMethodAttribute(); _testAssemblyInfo = new TestAssemblyInfo(typeof(DummyTestClass).Assembly); var testMethod = new TestMethod("dummyTestName", "dummyClassName", "dummyAssemblyName", false); _testContextImplementation = new TestContextImplementation(testMethod, new ThreadSafeStringWriter(null!, "test"), new Dictionary()); _testClassInfo = new TestClassInfo(typeof(DummyTestClass), _constructorInfo, true, _classAttribute, _testAssemblyInfo); - _expectedException = new UTF.ExpectedExceptionAttribute(typeof(DivideByZeroException)); + _expectedException = new ExpectedExceptionAttribute(typeof(DivideByZeroException)); _testMethodInfo = new TestMethodInfo( _methodInfo, @@ -96,7 +94,7 @@ public void TestMethodInfoInvokeShouldWaitForAsyncTestMethodsToComplete() Executor = _testMethodAttribute, }; - UTF.TestResult result = method.Invoke(null); + TestResult result = method.Invoke(null); Verify(methodCalled); Verify(result.Outcome == UTF.UnitTestOutcome.Passed); @@ -104,7 +102,7 @@ public void TestMethodInfoInvokeShouldWaitForAsyncTestMethodsToComplete() public void TestMethodInfoInvokeAsyncShouldHandleThrowAssertInconclusive() { - DummyTestClass.DummyAsyncTestMethodBody = () => Task.Run(() => throw new UTF.AssertInconclusiveException()); + DummyTestClass.DummyAsyncTestMethodBody = () => Task.Run(() => throw new AssertInconclusiveException()); MethodInfo asyncMethodInfo = typeof(DummyTestClass).GetMethod("DummyAsyncTestMethod")!; var method = new TestMethodInfo( @@ -116,7 +114,7 @@ public void TestMethodInfoInvokeAsyncShouldHandleThrowAssertInconclusive() Executor = _testMethodAttribute, }; - UTF.TestResult result = method.Invoke(null); + TestResult result = method.Invoke(null); Verify(result.Outcome == UTF.UnitTestOutcome.Inconclusive); } @@ -135,14 +133,14 @@ public void TestMethodInfoInvokeAsyncShouldHandleAssertInconclusive() Executor = _testMethodAttribute, }; - UTF.TestResult result = method.Invoke(null); + TestResult result = method.Invoke(null); Verify(result.Outcome == UTF.UnitTestOutcome.Inconclusive); } public void TestMethodInfoInvokeShouldHandleThrowAssertInconclusive() { - DummyTestClass.TestMethodBody = d => throw new UTF.AssertInconclusiveException(); + DummyTestClass.TestMethodBody = d => throw new AssertInconclusiveException(); MethodInfo dummyMethodInfo = typeof(DummyTestClass).GetMethod("DummyTestMethod")!; var method = new TestMethodInfo( @@ -154,7 +152,7 @@ public void TestMethodInfoInvokeShouldHandleThrowAssertInconclusive() Executor = _testMethodAttribute, }; - UTF.TestResult result = method.Invoke(null); + TestResult result = method.Invoke(null); Verify(result.Outcome == UTF.UnitTestOutcome.Inconclusive); } @@ -173,7 +171,7 @@ public void TestMethodInfoInvokeShouldHandleAssertInconclusive() Executor = _testMethodAttribute, }; - UTF.TestResult result = method.Invoke(null); + TestResult result = method.Invoke(null); Verify(result.Outcome == UTF.UnitTestOutcome.Inconclusive); } @@ -191,7 +189,7 @@ public void TestMethodInfoInvokeShouldReportTestContextMessages() Executor = _testMethodAttribute, }; - UTF.TestResult result = method.Invoke(null); + TestResult result = method.Invoke(null); Verify(result.TestContextMessages!.Contains("TestContext")); } @@ -209,7 +207,7 @@ public void TestMethodInfoInvokeShouldClearTestContextMessagesAfterReporting() Executor = _testMethodAttribute, }; - UTF.TestResult result = method.Invoke(null); + TestResult result = method.Invoke(null); Verify(result.TestContextMessages!.Contains("TestContext")); @@ -242,7 +240,7 @@ public void Invoke_WhenTestMethodThrowsMissingMethodException_TestOutcomeIsFaile Executor = _testMethodAttribute, }; - UTF.TestResult result = method.Invoke(null); + TestResult result = method.Invoke(null); Verify(result.Outcome == UTF.UnitTestOutcome.Failed); Verify(result.TestFailureException is TestFailedException); @@ -258,7 +256,7 @@ public void TestMethodInfoInvokeShouldCreateNewInstanceOfTestClassOnEveryCall() int ctorCallCount = 0; DummyTestClass.TestConstructorMethodBody = () => ctorCallCount++; - UTF.TestResult result = _testMethodInfo.Invoke(null); + TestResult result = _testMethodInfo.Invoke(null); _testMethodInfo.Invoke(null); Verify(result.Outcome == UTF.UnitTestOutcome.Passed); @@ -269,7 +267,7 @@ public void TestMethodInfoInvokeShouldMarkOutcomeFailedIfTestClassConstructorThr { DummyTestClass.TestConstructorMethodBody = () => throw new NotImplementedException(); - UTF.TestResult result = _testMethodInfo.Invoke(null); + TestResult result = _testMethodInfo.Invoke(null); Verify(result.Outcome == UTF.UnitTestOutcome.Failed); } @@ -278,7 +276,7 @@ public void TestMethodInfoInvokeShouldSetErrorMessageIfTestClassConstructorThrow { DummyTestClass.TestConstructorMethodBody = () => throw new NotImplementedException("dummyExceptionMessage"); - UTF.TestResult result = _testMethodInfo.Invoke(null); + TestResult result = _testMethodInfo.Invoke(null); string errorMessage = string.Format( CultureInfo.InvariantCulture, @@ -298,7 +296,7 @@ public void TestMethodInfoInvokeShouldSetErrorMessageIfTestClassConstructorThrow Executor = _testMethodAttribute, }; - UTF.TestResult result = method.Invoke(null); + TestResult result = method.Invoke(null); string errorMessage = string.Format( CultureInfo.InvariantCulture, Resource.UTA_InstanceCreationError, @@ -345,7 +343,7 @@ public void TestMethodInfoInvokeShouldSetResultFilesIfTestContextHasAttachments( { Mock testContext = new(); testContext.Setup(tc => tc.GetResultFiles()).Returns(["C:\\temp.txt"]); - var mockInnerContext = new Mock(); + var mockInnerContext = new Mock(); testContext.SetupGet(tc => tc.Context).Returns(mockInnerContext.Object); mockInnerContext.SetupGet(tc => tc.CancellationTokenSource).Returns(new CancellationTokenSource()); @@ -355,13 +353,13 @@ public void TestMethodInfoInvokeShouldSetResultFilesIfTestContextHasAttachments( Executor = _testMethodAttribute, }; - UTF.TestResult result = method.Invoke(null); + TestResult result = method.Invoke(null); Verify(result.ResultFiles!.Contains("C:\\temp.txt")); } public void TestMethodInfoInvoke_WhenCtorHasOneParameterOfTypeTestContext_SetsItToTestContext() { - ConstructorInfo ctorInfo = typeof(DummyTestClass).GetConstructor([typeof(UTFExtension.TestContext)])!; + ConstructorInfo ctorInfo = typeof(DummyTestClass).GetConstructor([typeof(TestContext)])!; var testClassInfo = new TestClassInfo(typeof(DummyTestClass), ctorInfo, false, _classAttribute, _testAssemblyInfo); var testMethodInfo = new TestMethodInfo(_methodInfo, testClassInfo, _testContextImplementation) { @@ -369,7 +367,7 @@ public void TestMethodInfoInvoke_WhenCtorHasOneParameterOfTypeTestContext_SetsIt Executor = _testMethodAttribute, }; - UTF.TestResult result = testMethodInfo.Invoke(null); + TestResult result = testMethodInfo.Invoke(null); Verify(result.Outcome == UTF.UnitTestOutcome.Passed); } @@ -387,7 +385,7 @@ public void TestMethodInfoInvokeShouldNotThrowIfTestContextIsNotPresent() Executor = _testMethodAttribute, }; - UTF.TestResult result; + TestResult result; void RunMethod() => result = method.Invoke(null); RunMethod(); @@ -403,7 +401,7 @@ public void TestMethodInfoInvokeShouldNotThrowIfTestContextDoesNotHaveASetter() Executor = _testMethodAttribute, }; - UTF.TestResult result; + TestResult result; void RunMethod() => result = method.Invoke(null); RunMethod(); @@ -412,8 +410,8 @@ public void TestMethodInfoInvokeShouldNotThrowIfTestContextDoesNotHaveASetter() public void TestMethodInfoInvokeShouldSetTestContextForTestClassInstance() { - UTFExtension.TestContext? testContext = null; - DummyTestClass.TestContextSetterBody = context => testContext = context as UTFExtension.TestContext; + TestContext? testContext = null; + DummyTestClass.TestContextSetterBody = context => testContext = context as TestContext; _testMethodInfo.Invoke(null); @@ -424,7 +422,7 @@ public void TestMethodInfoInvokeShouldMarkOutcomeFailedIfSetTestContextThrows() { DummyTestClass.TestContextSetterBody = value => throw new NotImplementedException(); - UTF.TestResult result = _testMethodInfo.Invoke(null); + TestResult result = _testMethodInfo.Invoke(null); Verify(result.Outcome == UTF.UnitTestOutcome.Failed); } @@ -459,17 +457,17 @@ public void TestMethodInfoInvokeShouldSetStackTraceInformationIfSetTestContextTh public void TestMethodInfoInvoke_WhenCtorHasOneParameterOfTypeTestContextAndTestContextProperty_InitializeBothTestContexts() { - ConstructorInfo ctorInfo = typeof(DummyTestClass).GetConstructor([typeof(UTFExtension.TestContext)])!; + ConstructorInfo ctorInfo = typeof(DummyTestClass).GetConstructor([typeof(TestContext)])!; var testClassInfo = new TestClassInfo(typeof(DummyTestClass), ctorInfo, false, _classAttribute, _testAssemblyInfo); var testMethodInfo = new TestMethodInfo(_methodInfo, testClassInfo, _testContextImplementation) { TimeoutInfo = TimeoutInfo.FromTimeout(3600 * 1000), Executor = _testMethodAttribute, }; - UTFExtension.TestContext? testContext = null; - DummyTestClass.TestContextSetterBody = context => testContext = context as UTFExtension.TestContext; + TestContext? testContext = null; + DummyTestClass.TestContextSetterBody = context => testContext = context as TestContext; - UTF.TestResult result = testMethodInfo.Invoke(null); + TestResult result = testMethodInfo.Invoke(null); Verify(result.Outcome == UTF.UnitTestOutcome.Passed); Verify(_testContextImplementation.Equals(testContext)); @@ -485,7 +483,7 @@ public void TestMethodInfoInvokeShouldCallTestInitialize() DummyTestClass.TestInitializeMethodBody = classInstance => testInitializeCalled = true; _testClassInfo.TestInitializeMethod = typeof(DummyTestClass).GetMethod("DummyTestInitializeMethod")!; - UTF.TestResult result = _testMethodInfo.Invoke(null); + TestResult result = _testMethodInfo.Invoke(null); Verify(testInitializeCalled); Verify(result.Outcome == UTF.UnitTestOutcome.Passed); @@ -497,7 +495,7 @@ public void TestMethodInfoInvokeShouldCallAsyncTestInitializeAndWaitForCompletio DummyTestClass.DummyAsyncTestMethodBody = () => Task.Run(() => testInitializeCalled = true); _testClassInfo.TestInitializeMethod = typeof(DummyTestClass).GetMethod("DummyAsyncTestMethod")!; - UTF.TestResult result = _testMethodInfo.Invoke(null); + TestResult result = _testMethodInfo.Invoke(null); Verify(testInitializeCalled); Verify(result.Outcome == UTF.UnitTestOutcome.Passed); @@ -513,7 +511,7 @@ public void TestMethodInfoInvokeShouldCallTestInitializeOfAllBaseClasses() _testClassInfo.BaseTestInitializeMethodsQueue.Enqueue(typeof(DummyTestClassBase).GetMethod("DummyBaseTestClassMethod")!); _testClassInfo.BaseTestInitializeMethodsQueue.Enqueue(typeof(DummyTestClass).GetMethod("DummyAsyncTestMethod")!); - UTF.TestResult result = _testMethodInfo.Invoke(null); + TestResult result = _testMethodInfo.Invoke(null); var expectedCallOrder = new List { @@ -529,7 +527,7 @@ public void TestMethodInfoInvokeShouldNotThrowIfTestInitializeIsNull() { _testClassInfo.TestInitializeMethod = null; - UTF.TestResult result = _testMethodInfo.Invoke(null); + TestResult result = _testMethodInfo.Invoke(null); Verify(result.Outcome == UTF.UnitTestOutcome.Passed); } @@ -538,7 +536,7 @@ public void TestMethodInfoInvokeShouldNotThrowIfTestInitializeForBaseClassIsNull { _testClassInfo.BaseTestInitializeMethodsQueue.Enqueue(null!); - UTF.TestResult result = _testMethodInfo.Invoke(null); + TestResult result = _testMethodInfo.Invoke(null); Verify(result.Outcome == UTF.UnitTestOutcome.Passed); } @@ -563,7 +561,7 @@ public void TestMethodInfoInvokeWhenTestThrowsReturnsExpectedResult() }; // Act. - UTF.TestResult result = testMethodInfo.Invoke(null); + TestResult result = testMethodInfo.Invoke(null); // Assert. Verify(result.Outcome == UTF.UnitTestOutcome.Failed); @@ -593,7 +591,7 @@ public void TestInitialize_WhenTestReturnsTaskFromException_DisplayProperExcepti }; // Act. - UTF.TestResult result = testMethodInfo.Invoke(null); + TestResult result = testMethodInfo.Invoke(null); // Assert. Verify(result.Outcome == UTF.UnitTestOutcome.Failed); @@ -634,7 +632,7 @@ public void TestMethodInfoInvokeWhenTestThrowsAssertFailReturnsExpectedResult() }; // Act. - UTF.TestResult result = testMethodInfo.Invoke(null); + TestResult result = testMethodInfo.Invoke(null); // Assert. Verify(result.Outcome == UTF.UnitTestOutcome.Failed); @@ -643,7 +641,7 @@ public void TestMethodInfoInvokeWhenTestThrowsAssertFailReturnsExpectedResult() Verify(exception is not null); Verify(errorMessage == exception.Message); Verify(exception.Outcome == UTF.UnitTestOutcome.Failed); - Verify(exception.InnerException!.GetType() == typeof(UTF.AssertFailedException)); + Verify(exception.InnerException!.GetType() == typeof(AssertFailedException)); #if DEBUG Verify(exception.StackTraceInformation!.ErrorStackTrace.StartsWith( " at Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Execution.TestMethodInfoTests.<>c.b__", StringComparison.Ordinal)); @@ -670,7 +668,7 @@ public void TestMethodInfoInvokeWhenTestThrowsAssertInconclusiveReturnsExpectedR }; // Act. - UTF.TestResult result = testMethodInfo.Invoke(null); + TestResult result = testMethodInfo.Invoke(null); // Assert. Verify(result.Outcome == UTF.UnitTestOutcome.Inconclusive); @@ -679,7 +677,7 @@ public void TestMethodInfoInvokeWhenTestThrowsAssertInconclusiveReturnsExpectedR Verify(exception is not null); Verify(errorMessage == exception.Message); Verify(exception.Outcome == UTF.UnitTestOutcome.Inconclusive); - Verify(exception.InnerException!.GetType() == typeof(UTF.AssertInconclusiveException)); + Verify(exception.InnerException!.GetType() == typeof(AssertInconclusiveException)); #if DEBUG Verify(exception.StackTraceInformation!.ErrorStackTrace.StartsWith( " at Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Execution.TestMethodInfoTests.<>c.b__", StringComparison.Ordinal)); @@ -702,7 +700,7 @@ public void TestCleanup_WhenTestReturnsTaskFromException_DisplayProperException( }; // Act. - UTF.TestResult result = testMethodInfo.Invoke(null); + TestResult result = testMethodInfo.Invoke(null); // Assert. Verify(result.Outcome == UTF.UnitTestOutcome.Failed); @@ -733,7 +731,7 @@ public void TestMethodInfoInvokeShouldCallTestCleanup() DummyTestClass.DummyAsyncTestMethodBody = () => Task.Run(() => cleanupMethodCalled = true); _testClassInfo.TestCleanupMethod = typeof(DummyTestClass).GetMethod("DummyAsyncTestMethod")!; - UTF.TestResult result = _testMethodInfo.Invoke(null); + TestResult result = _testMethodInfo.Invoke(null); Verify(result.Outcome == UTF.UnitTestOutcome.Passed); Verify(cleanupMethodCalled); @@ -745,7 +743,7 @@ public void TestMethodInfoInvokeShouldCallAsyncTestCleanup() DummyTestClass.TestCleanupMethodBody = classInstance => cleanupMethodCalled = true; _testClassInfo.TestCleanupMethod = typeof(DummyTestClass).GetMethod("DummyTestCleanupMethod")!; - UTF.TestResult result = _testMethodInfo.Invoke(null); + TestResult result = _testMethodInfo.Invoke(null); Verify(result.Outcome == UTF.UnitTestOutcome.Passed); Verify(cleanupMethodCalled); @@ -755,7 +753,7 @@ public void TestMethodInfoInvokeShouldNotThrowIfTestCleanupMethodIsNull() { _testClassInfo.TestCleanupMethod = null; - UTF.TestResult result = _testMethodInfo.Invoke(null); + TestResult result = _testMethodInfo.Invoke(null); Verify(result.Outcome == UTF.UnitTestOutcome.Passed); } @@ -769,7 +767,7 @@ public void TestMethodInfoInvokeShouldCallTestCleanupForBaseTestClasses() _testClassInfo.BaseTestCleanupMethodsQueue.Enqueue(typeof(DummyTestClassBase).GetMethod("DummyBaseTestClassMethod")!); _testClassInfo.BaseTestCleanupMethodsQueue.Enqueue(typeof(DummyTestClassBase).GetMethod("DummyBaseTestClassMethod")!); - UTF.TestResult result = _testMethodInfo.Invoke(null); + TestResult result = _testMethodInfo.Invoke(null); var expectedCallOrder = new List { @@ -791,7 +789,7 @@ public void TestMethodInfoInvokeShouldCallTestCleanupForBaseTestClassesAlways() _testClassInfo.BaseTestCleanupMethodsQueue.Enqueue(typeof(DummyTestClassBase).GetMethod("DummyBaseTestClassMethod")!); _testMethodInfo.Invoke(null); - UTF.TestResult result = _testMethodInfo.Invoke(null); + TestResult result = _testMethodInfo.Invoke(null); var expectedCallOrder = new List { @@ -819,7 +817,7 @@ public void TestMethodInfoInvokeWhenTestCleanupThrowsReturnsExpectedResult() _testClassInfo.TestCleanupMethod!.Name, "System.ArgumentException: Some exception message ---> System.InvalidOperationException: Inner exception message"); - UTF.TestResult result = _testMethodInfo.Invoke(null); + TestResult result = _testMethodInfo.Invoke(null); Verify(result.Outcome == UTF.UnitTestOutcome.Failed); @@ -848,7 +846,7 @@ public void TestMethodInfoInvokeWhenTestCleanupThrowsAssertInconclusiveReturnsEx _testClassInfo.TestCleanupMethod.Name, "Microsoft.VisualStudio.TestTools.UnitTesting.AssertInconclusiveException: Assert.Inconclusive failed. Test inconclusive"); - UTF.TestResult result = _testMethodInfo.Invoke(null); + TestResult result = _testMethodInfo.Invoke(null); Verify(result.Outcome == UTF.UnitTestOutcome.Inconclusive); @@ -856,7 +854,7 @@ public void TestMethodInfoInvokeWhenTestCleanupThrowsAssertInconclusiveReturnsEx Verify(exception is not null); Verify(exception.Outcome == UTF.UnitTestOutcome.Inconclusive); Verify(expectedErrorMessage == exception.Message); - Verify(exception.InnerException!.GetType() == typeof(UTF.AssertInconclusiveException)); + Verify(exception.InnerException!.GetType() == typeof(AssertInconclusiveException)); #if DEBUG Verify(exception.StackTraceInformation!.ErrorStackTrace.StartsWith( " at Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Execution.TestMethodInfoTests.<>c.b__", StringComparison.Ordinal)); @@ -875,7 +873,7 @@ public void TestMethodInfoInvokeWhenTestCleanupThrowsAssertFailedReturnsExpected _testClassInfo.TestCleanupMethod!.Name, "Microsoft.VisualStudio.TestTools.UnitTesting.AssertFailedException: Assert.Fail failed. Test failed"); - UTF.TestResult result = _testMethodInfo.Invoke(null); + TestResult result = _testMethodInfo.Invoke(null); Verify(result.Outcome == UTF.UnitTestOutcome.Failed); @@ -883,7 +881,7 @@ public void TestMethodInfoInvokeWhenTestCleanupThrowsAssertFailedReturnsExpected Verify(exception is not null); Verify(exception.Outcome == UTF.UnitTestOutcome.Failed); Verify(expectedErrorMessage == exception.Message); - Verify(exception.InnerException!.GetType() == typeof(UTF.AssertFailedException)); + Verify(exception.InnerException!.GetType() == typeof(AssertFailedException)); #if DEBUG Verify(exception.StackTraceInformation!.ErrorStackTrace.StartsWith( " at Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Execution.TestMethodInfoTests.<>c.b__", StringComparison.Ordinal)); @@ -896,7 +894,7 @@ public void TestMethodInfoInvokeShouldAppendErrorMessagesIfBothTestMethodAndTest DummyTestClass.TestMethodBody = classInstance => throw new NotImplementedException("dummyMethodError"); _testClassInfo.TestCleanupMethod = typeof(DummyTestClass).GetMethod("DummyTestCleanupMethod")!; - UTF.TestResult result = _testMethodInfo.Invoke(null); + TestResult result = _testMethodInfo.Invoke(null); var exception = result.TestFailureException as AggregateException; string errorMessage = string.Format( CultureInfo.CurrentCulture, @@ -923,7 +921,7 @@ public void TestMethodInfoInvokeShouldAppendStackTraceInformationIfBothTestMetho DummyTestClass.TestMethodBody = classInstance => throw new NotImplementedException("dummyMethodError"); _testClassInfo.TestCleanupMethod = typeof(DummyTestClass).GetMethod("DummyTestCleanupMethod")!; - UTF.TestResult result = _testMethodInfo.Invoke(null); + TestResult result = _testMethodInfo.Invoke(null); var exception = result.TestFailureException as AggregateException; Verify(result.Outcome == UTF.UnitTestOutcome.Failed); @@ -936,10 +934,10 @@ public void TestMethodInfoInvokeShouldAppendStackTraceInformationIfBothTestMetho public void TestMethodInfoInvokeShouldSetOutcomeAsInconclusiveIfTestCleanupIsInconclusive() { - DummyTestClass.TestCleanupMethodBody = classInstance => throw new UTF.AssertInconclusiveException(); + DummyTestClass.TestCleanupMethodBody = classInstance => throw new AssertInconclusiveException(); _testClassInfo.TestCleanupMethod = typeof(DummyTestClass).GetMethod("DummyTestCleanupMethod")!; - UTF.TestResult result = _testMethodInfo.Invoke(null); + TestResult result = _testMethodInfo.Invoke(null); var exception = result.TestFailureException as TestFailedException; Verify(result.Outcome == UTF.UnitTestOutcome.Inconclusive); @@ -949,11 +947,11 @@ public void TestMethodInfoInvokeShouldSetOutcomeAsInconclusiveIfTestCleanupIsInc public void TestMethodInfoInvokeShouldSetMoreImportantOutcomeIfTestCleanupIsInconclusiveButTestMethodFails() { - DummyTestClass.TestCleanupMethodBody = classInstance => throw new UTF.AssertInconclusiveException(); + DummyTestClass.TestCleanupMethodBody = classInstance => throw new AssertInconclusiveException(); DummyTestClass.TestMethodBody = classInstance => Fail(); _testClassInfo.TestCleanupMethod = typeof(DummyTestClass).GetMethod("DummyTestCleanupMethod")!; - UTF.TestResult result = _testMethodInfo.Invoke(null); + TestResult result = _testMethodInfo.Invoke(null); Verify(result.Outcome == UTF.UnitTestOutcome.Failed); } @@ -1051,7 +1049,7 @@ public void TestMethodInfoInvokeShouldCallTestCleanupEvenIfTestMethodThrows() DummyTestClass.TestCleanupMethodBody = classInstance => testCleanupMethodCalled = true; _testClassInfo.TestCleanupMethod = typeof(DummyTestClass).GetMethod("DummyTestCleanupMethod")!; - UTF.TestResult result = _testMethodInfo.Invoke(null); + TestResult result = _testMethodInfo.Invoke(null); Verify(testCleanupMethodCalled); Verify(result.Outcome == UTF.UnitTestOutcome.Failed); @@ -1065,7 +1063,7 @@ public void TestMethodInfoInvokeShouldCallTestCleanupEvenIfTestInitializeMethodT _testClassInfo.TestInitializeMethod = typeof(DummyTestClass).GetMethod("DummyTestInitializeMethod")!; _testClassInfo.TestCleanupMethod = typeof(DummyTestClass).GetMethod("DummyTestCleanupMethod")!; - UTF.TestResult result = _testMethodInfo.Invoke(null); + TestResult result = _testMethodInfo.Invoke(null); Verify(testCleanupMethodCalled); Verify(result.Outcome == UTF.UnitTestOutcome.Failed); @@ -1079,7 +1077,7 @@ public void TestMethodInfoInvokeShouldCallTestCleanupIfTestClassInstanceIsNotNul DummyTestClass.TestConstructorMethodBody = () => throw new NotImplementedException(); DummyTestClass.TestCleanupMethodBody = classInstance => testCleanupMethodCalled = true; - UTF.TestResult result = _testMethodInfo.Invoke(null); + TestResult result = _testMethodInfo.Invoke(null); Verify(!testCleanupMethodCalled); Verify(result.Outcome == UTF.UnitTestOutcome.Failed); @@ -1107,7 +1105,7 @@ public void TestMethodInfoInvokeShouldSetResultAsPassedIfExpectedExceptionIsThro ExpectedException = _expectedException, }; - UTF.TestResult result = testMethodInfo.Invoke(null); + TestResult result = testMethodInfo.Invoke(null); Verify(result.Outcome == UTF.UnitTestOutcome.Passed); } @@ -1122,7 +1120,7 @@ public void TestMethodInfoInvokeShouldSetResultAsFailedIfExceptionDifferentFromE ExpectedException = _expectedException, }; - UTF.TestResult result = testMethodInfo.Invoke(null); + TestResult result = testMethodInfo.Invoke(null); Verify(result.Outcome == UTF.UnitTestOutcome.Failed); string message = "Test method threw exception System.IndexOutOfRangeException, but exception System.DivideByZeroException was expected. " + @@ -1139,7 +1137,7 @@ public void TestMethodInfoInvokeShouldSetResultAsFailedWhenExceptionIsExpectedBu Executor = _testMethodAttribute, ExpectedException = _expectedException, }; - UTF.TestResult result = testMethodInfo.Invoke(null); + TestResult result = testMethodInfo.Invoke(null); Verify(result.Outcome == UTF.UnitTestOutcome.Failed); string message = "Test method did not throw expected exception System.DivideByZeroException."; Verify(result.TestFailureException!.Message.Contains(message)); @@ -1147,14 +1145,14 @@ public void TestMethodInfoInvokeShouldSetResultAsFailedWhenExceptionIsExpectedBu public void TestMethodInfoInvokeShouldSetResultAsInconclusiveWhenExceptionIsAssertInconclusiveException() { - DummyTestClass.TestMethodBody = o => throw new UTF.AssertInconclusiveException(); + DummyTestClass.TestMethodBody = o => throw new AssertInconclusiveException(); var testMethodInfo = new TestMethodInfo(_methodInfo, _testClassInfo, _testContextImplementation) { TimeoutInfo = TimeoutInfo.FromTimeout(3600 * 1000), Executor = _testMethodAttribute, ExpectedException = _expectedException, }; - UTF.TestResult result = testMethodInfo.Invoke(null); + TestResult result = testMethodInfo.Invoke(null); Verify(result.Outcome == UTF.UnitTestOutcome.Inconclusive); string message = "Exception of type 'Microsoft.VisualStudio.TestTools.UnitTesting.AssertInconclusiveException' was thrown."; Verify(message == result.TestFailureException!.Message); @@ -1163,7 +1161,7 @@ public void TestMethodInfoInvokeShouldSetResultAsInconclusiveWhenExceptionIsAsse public void TestMethodInfoInvokeShouldSetTestOutcomeBeforeTestCleanup() { UTF.UnitTestOutcome testOutcome = UTF.UnitTestOutcome.Unknown; - DummyTestClass.TestMethodBody = o => throw new UTF.AssertInconclusiveException(); + DummyTestClass.TestMethodBody = o => throw new AssertInconclusiveException(); DummyTestClass.TestCleanupMethodBody = c => { if (DummyTestClass.GetTestContext() != null) @@ -1179,7 +1177,7 @@ public void TestMethodInfoInvokeShouldSetTestOutcomeBeforeTestCleanup() ExpectedException = _expectedException, }; - UTF.TestResult result = testMethodInfo.Invoke(null); + TestResult result = testMethodInfo.Invoke(null); Verify(testOutcome == UTF.UnitTestOutcome.Inconclusive); } @@ -1198,7 +1196,7 @@ public void HandleMethodExceptionShouldInvokeVerifyOfCustomExpectedException() }; DummyTestClass.TestMethodBody = o => throw new DivideByZeroException(); - UTF.TestResult result = method.Invoke(null); + TestResult result = method.Invoke(null); Verify(customExpectedException.IsVerifyInvoked); Verify(result.Outcome == UTF.UnitTestOutcome.Passed); } @@ -1217,7 +1215,7 @@ public void HandleMethodExceptionShouldSetOutcomeAsFailedIfVerifyOfExpectedExcep }; DummyTestClass.TestMethodBody = o => throw new DivideByZeroException(); - UTF.TestResult result = method.Invoke(null); + TestResult result = method.Invoke(null); Verify(result.TestFailureException!.Message == "The exception message doesn't contain the string defined in the exception attribute"); Verify(result.Outcome == UTF.UnitTestOutcome.Failed); } @@ -1235,8 +1233,8 @@ public void HandleMethodExceptionShouldSetOutcomeAsInconclusiveIfVerifyOfExpecte ExpectedException = customExpectedException, }; - DummyTestClass.TestMethodBody = o => throw new UTF.AssertInconclusiveException(); - UTF.TestResult result = method.Invoke(null); + DummyTestClass.TestMethodBody = o => throw new AssertInconclusiveException(); + TestResult result = method.Invoke(null); string message = "Exception of type 'Microsoft.VisualStudio.TestTools.UnitTesting.AssertInconclusiveException' was thrown."; Verify(result.TestFailureException!.Message == message); Verify(result.Outcome == UTF.UnitTestOutcome.Inconclusive); @@ -1256,14 +1254,14 @@ public void HandleMethodExceptionShouldInvokeVerifyOfDerivedCustomExpectedExcept }; DummyTestClass.TestMethodBody = o => throw new DivideByZeroException(); - UTF.TestResult result = method.Invoke(null); + TestResult result = method.Invoke(null); Verify(derivedCustomExpectedException.IsVerifyInvoked); Verify(result.Outcome == UTF.UnitTestOutcome.Passed); } public void VerifyShouldNotThrowIfThrownExceptionCanBeAssignedToExpectedException() { - UTF.ExpectedExceptionAttribute expectedException = new(typeof(Exception)) + ExpectedExceptionAttribute expectedException = new(typeof(Exception)) { AllowDerivedTypes = true, }; @@ -1278,13 +1276,13 @@ public void VerifyShouldNotThrowIfThrownExceptionCanBeAssignedToExpectedExceptio }; DummyTestClass.TestMethodBody = o => throw new DivideByZeroException(); - UTF.TestResult result = method.Invoke(null); + TestResult result = method.Invoke(null); Verify(result.Outcome == UTF.UnitTestOutcome.Passed); } public void VerifyShouldThrowExceptionIfThrownExceptionCannotBeAssignedToExpectedException() { - UTF.ExpectedExceptionAttribute expectedException = new(typeof(DivideByZeroException), "Custom Exception") + ExpectedExceptionAttribute expectedException = new(typeof(DivideByZeroException), "Custom Exception") { AllowDerivedTypes = true, }; @@ -1299,7 +1297,7 @@ public void VerifyShouldThrowExceptionIfThrownExceptionCannotBeAssignedToExpecte }; DummyTestClass.TestMethodBody = o => throw new ArgumentNullException(); - UTF.TestResult result = method.Invoke(null); + TestResult result = method.Invoke(null); string message = "Test method threw exception System.ArgumentNullException, but exception System.DivideByZeroException" + " or a type derived from it was expected. Exception message: System.ArgumentNullException: Value cannot be null."; Verify(result.TestFailureException!.Message == message); @@ -1308,7 +1306,7 @@ public void VerifyShouldThrowExceptionIfThrownExceptionCannotBeAssignedToExpecte public void VerifyShouldRethrowExceptionIfThrownExceptionIsAssertFailedException() { - UTF.ExpectedExceptionAttribute expectedException = new(typeof(DivideByZeroException)) + ExpectedExceptionAttribute expectedException = new(typeof(DivideByZeroException)) { AllowDerivedTypes = true, }; @@ -1322,8 +1320,8 @@ public void VerifyShouldRethrowExceptionIfThrownExceptionIsAssertFailedException ExpectedException = expectedException, }; - DummyTestClass.TestMethodBody = o => throw new UTF.AssertFailedException(); - UTF.TestResult result = method.Invoke(null); + DummyTestClass.TestMethodBody = o => throw new AssertFailedException(); + TestResult result = method.Invoke(null); string message = "Exception of type 'Microsoft.VisualStudio.TestTools.UnitTesting.AssertFailedException' was thrown."; Verify(result.TestFailureException!.Message == message); Verify(result.Outcome == UTF.UnitTestOutcome.Failed); @@ -1331,7 +1329,7 @@ public void VerifyShouldRethrowExceptionIfThrownExceptionIsAssertFailedException public void VerifyShouldRethrowExceptionIfThrownExceptionIsAssertInconclusiveException() { - UTF.ExpectedExceptionAttribute expectedException = new(typeof(DivideByZeroException)) + ExpectedExceptionAttribute expectedException = new(typeof(DivideByZeroException)) { AllowDerivedTypes = true, }; @@ -1345,8 +1343,8 @@ public void VerifyShouldRethrowExceptionIfThrownExceptionIsAssertInconclusiveExc ExpectedException = expectedException, }; - DummyTestClass.TestMethodBody = o => throw new UTF.AssertInconclusiveException(); - UTF.TestResult result = method.Invoke(null); + DummyTestClass.TestMethodBody = o => throw new AssertInconclusiveException(); + TestResult result = method.Invoke(null); string message = "Exception of type 'Microsoft.VisualStudio.TestTools.UnitTesting.AssertInconclusiveException' was thrown."; Verify(result.TestFailureException!.Message == message); Verify(result.Outcome == UTF.UnitTestOutcome.Inconclusive); @@ -1354,7 +1352,7 @@ public void VerifyShouldRethrowExceptionIfThrownExceptionIsAssertInconclusiveExc public void VerifyShouldThrowIfThrownExceptionIsNotSameAsExpectedException() { - UTF.ExpectedExceptionAttribute expectedException = new(typeof(Exception)); + ExpectedExceptionAttribute expectedException = new(typeof(Exception)); var method = new TestMethodInfo( _methodInfo, _testClassInfo, @@ -1366,7 +1364,7 @@ public void VerifyShouldThrowIfThrownExceptionIsNotSameAsExpectedException() }; DummyTestClass.TestMethodBody = o => throw new DivideByZeroException(); - UTF.TestResult result = method.Invoke(null); + TestResult result = method.Invoke(null); string message = "Test method threw exception System.DivideByZeroException, but exception System.Exception was expected. " + "Exception message: System.DivideByZeroException: Attempted to divide by zero."; Verify(result.TestFailureException!.Message == message); @@ -1375,7 +1373,7 @@ public void VerifyShouldThrowIfThrownExceptionIsNotSameAsExpectedException() public void VerifyShouldRethrowIfThrownExceptionIsAssertExceptionWhichIsNotSameAsExpectedException() { - UTF.ExpectedExceptionAttribute expectedException = new(typeof(Exception)); + ExpectedExceptionAttribute expectedException = new(typeof(Exception)); var method = new TestMethodInfo( _methodInfo, _testClassInfo, @@ -1386,8 +1384,8 @@ public void VerifyShouldRethrowIfThrownExceptionIsAssertExceptionWhichIsNotSameA ExpectedException = expectedException, }; - DummyTestClass.TestMethodBody = o => throw new UTF.AssertInconclusiveException(); - UTF.TestResult result = method.Invoke(null); + DummyTestClass.TestMethodBody = o => throw new AssertInconclusiveException(); + TestResult result = method.Invoke(null); string message = "Exception of type 'Microsoft.VisualStudio.TestTools.UnitTesting.AssertInconclusiveException' was thrown."; Verify(result.TestFailureException!.Message == message); Verify(result.Outcome == UTF.UnitTestOutcome.Inconclusive); @@ -1400,7 +1398,7 @@ public void ResolveExpectedExceptionShouldThrowWhenAttributeIsDefinedTwice_Diffe typeof(DummyTestClassForExpectedException), typeof(DummyTestClassForExpectedException).GetConstructor([])!, isParameterlessConstructor: true, - new UTF.TestClassAttribute(), + new TestClassAttribute(), new TestAssemblyInfo(typeof(DummyTestClassForExpectedException).Assembly)); TypeInspectionException ex = UTF.Assert.ThrowsException(() => new TestMethodInfo(testMethodInfo, classInfo, _testContextImplementation) @@ -1418,7 +1416,7 @@ public void ResolveExpectedExceptionShouldThrowWhenAttributeIsDefinedTwice_SameC typeof(DummyTestClassForExpectedException), typeof(DummyTestClassForExpectedException).GetConstructor([])!, isParameterlessConstructor: true, - new UTF.TestClassAttribute(), + new TestClassAttribute(), new TestAssemblyInfo(typeof(DummyTestClassForExpectedException).Assembly)); TypeInspectionException ex = UTF.Assert.ThrowsException(() => new TestMethodInfo(testMethodInfo, classInfo, _testContextImplementation) @@ -1437,7 +1435,7 @@ public void ResolveExpectedExceptionHelperShouldReturnExpectedExceptionAttribute typeof(DummyTestClassForExpectedException), typeof(DummyTestClassForExpectedException).GetConstructor([])!, isParameterlessConstructor: true, - new UTF.TestClassAttribute(), + new TestClassAttribute(), new TestAssemblyInfo(typeof(DummyTestClassForExpectedException).Assembly)); var testMethodInfo = new TestMethodInfo(methodInfo, classInfo, _testContextImplementation) @@ -1447,7 +1445,7 @@ public void ResolveExpectedExceptionHelperShouldReturnExpectedExceptionAttribute }; Verify(testMethodInfo.ExpectedException is not null); - Verify(((UTF.ExpectedExceptionAttribute)testMethodInfo.ExpectedException).ExceptionType == typeof(DivideByZeroException)); + Verify(((ExpectedExceptionAttribute)testMethodInfo.ExpectedException).ExceptionType == typeof(DivideByZeroException)); } public void ResolveExpectedExceptionHelperShouldReturnNullIfExpectedExceptionAttributeIsNotPresent() @@ -1458,7 +1456,7 @@ public void ResolveExpectedExceptionHelperShouldReturnNullIfExpectedExceptionAtt typeof(DummyTestClassForExpectedException), typeof(DummyTestClassForExpectedException).GetConstructor([])!, isParameterlessConstructor: true, - new UTF.TestClassAttribute(), + new TestClassAttribute(), new TestAssemblyInfo(typeof(DummyTestClassForExpectedException).Assembly)); var testMethodInfo = new TestMethodInfo(methodInfo, classInfo, _testContextImplementation) @@ -1486,7 +1484,7 @@ public void TestMethodInfoInvokeShouldInitializeClassInstanceTestInitializeAndTe DummyTestClass.TestMethodBody = classInstance => callOrder.Add("testMethodInfo"); DummyTestClass.TestCleanupMethodBody = classInstance => callOrder.Add("testCleanup"); - UTF.TestResult result = _testMethodInfo.Invoke(null); + TestResult result = _testMethodInfo.Invoke(null); var expectedCallOrder = new List { @@ -1522,7 +1520,7 @@ public void TestMethodInfoInvokeShouldReturnTestFailureOnTimeout() Executor = _testMethodAttribute, }; - UTF.TestResult result = method.Invoke(null); + TestResult result = method.Invoke(null); Verify(result.Outcome == UTF.UnitTestOutcome.Timeout); Verify(result.TestFailureException!.Message.Equals("Test 'DummyTestMethod' timed out after 1ms", StringComparison.Ordinal)); @@ -1537,7 +1535,7 @@ public void TestMethodInfoInvokeShouldReturnTestPassedOnCompletionWithinTimeout( TimeoutInfo = TimeoutInfo.FromTimeout(3600 * 1000), Executor = _testMethodAttribute, }; - UTF.TestResult result = method.Invoke(null); + TestResult result = method.Invoke(null); Verify(result.Outcome == UTF.UnitTestOutcome.Passed); } @@ -1557,7 +1555,7 @@ public void TestMethodInfoInvokeShouldCancelTokenSourceOnTimeout() TimeoutInfo = TimeoutInfo.FromTimeout(1), Executor = _testMethodAttribute, }; - UTF.TestResult result = method.Invoke(null); + TestResult result = method.Invoke(null); Verify(result.Outcome == UTF.UnitTestOutcome.Timeout); Verify(result.TestFailureException!.Message.Equals("Test 'DummyTestMethod' timed out after 1ms", StringComparison.Ordinal)); @@ -1591,7 +1589,7 @@ public void TestMethodInfoInvokeShouldFailOnTokenSourceCancellation() TimeoutInfo = TimeoutInfo.FromTimeout(100000), Executor = _testMethodAttribute, }; - UTF.TestResult result = method.Invoke(null); + TestResult result = method.Invoke(null); Verify(result.Outcome == UTF.UnitTestOutcome.Timeout); Verify(result.TestFailureException!.Message.Equals("Test 'DummyTestMethod' was canceled", StringComparison.Ordinal)); @@ -1762,11 +1760,11 @@ public class DummyTestClassBase public class DummyTestClass : DummyTestClassBase { - private static UTFExtension.TestContext s_tc = null!; + private static TestContext s_tc = null!; public DummyTestClass() => TestConstructorMethodBody(); - public DummyTestClass(UTFExtension.TestContext tc) => Verify(tc is not null); + public DummyTestClass(TestContext tc) => Verify(tc is not null); public static Action TestConstructorMethodBody { get; set; } = null!; @@ -1784,9 +1782,9 @@ public class DummyTestClass : DummyTestClassBase public static Func DummyAsyncTestMethodBody { get; set; } = null!; - public static UTFExtension.TestContext GetTestContext() => s_tc; + public static TestContext GetTestContext() => s_tc; - public UTFExtension.TestContext TestContext + public TestContext TestContext { get => throw new NotImplementedException(); @@ -1836,7 +1834,7 @@ public DummyTestClassWithParameterizedCtor(int x) public class DummyTestClassWithTestContextWithoutSetter { - public UTFExtension.TestContext TestContext { get; } = null!; + public TestContext TestContext { get; } = null!; } public class DummyTestClassWithDisposable : IDisposable @@ -1859,7 +1857,7 @@ public void DummyTestMethod() /// /// Custom Expected exception attribute which overrides the Verify method. /// - public class CustomExpectedExceptionAttribute : UTF.ExpectedExceptionBaseAttribute + public class CustomExpectedExceptionAttribute : ExpectedExceptionBaseAttribute { public CustomExpectedExceptionAttribute(Type exceptionType, string noExceptionMessage) : base(noExceptionMessage) => ExceptionType = exceptionType; @@ -1871,9 +1869,9 @@ public CustomExpectedExceptionAttribute(Type exceptionType, string noExceptionMe protected internal override void Verify(Exception exception) { IsVerifyInvoked = true; - if (exception is UTF.AssertInconclusiveException) + if (exception is AssertInconclusiveException) { - throw new UTF.AssertInconclusiveException(); + throw new AssertInconclusiveException(); } else if (!exception.Message.Contains(NoExceptionMessage)) { @@ -1897,9 +1895,9 @@ public DerivedCustomExpectedExceptionAttribute(Type exceptionType, string noExce protected internal override void Verify(Exception exception) { IsVerifyInvoked = true; - if (exception is UTF.AssertInconclusiveException) + if (exception is AssertInconclusiveException) { - throw new UTF.AssertInconclusiveException(); + throw new AssertInconclusiveException(); } else if (!exception.Message.Contains(NoExceptionMessage)) { @@ -1912,18 +1910,18 @@ protected internal override void Verify(Exception exception) public class DummyTestClassForExpectedException { - private class MyExpectedException1Attribute : UTF.ExpectedExceptionBaseAttribute + private class MyExpectedException1Attribute : ExpectedExceptionBaseAttribute { protected internal override void Verify(Exception exception) => throw new NotImplementedException(); } [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] - public class MyExpectedException2Attribute : UTF.ExpectedExceptionBaseAttribute + public class MyExpectedException2Attribute : ExpectedExceptionBaseAttribute { protected internal override void Verify(Exception exception) => throw new NotImplementedException(); } - [UTF.ExpectedException(typeof(Exception))] + [ExpectedException(typeof(Exception))] [MyExpectedException1] public void DummyTestMethod1() @@ -1936,7 +1934,7 @@ public void DummyTestMethod2() { } - [UTF.ExpectedException(typeof(DivideByZeroException))] + [ExpectedException(typeof(DivideByZeroException))] public void TestMethodWithExpectedException() { } diff --git a/test/UnitTests/MSTestAdapter.UnitTests/Execution/TestMethodRunnerTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestMethodRunnerTests.cs similarity index 98% rename from test/UnitTests/MSTestAdapter.UnitTests/Execution/TestMethodRunnerTests.cs rename to test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestMethodRunnerTests.cs index 4c9f11f909..473077cfb9 100644 --- a/test/UnitTests/MSTestAdapter.UnitTests/Execution/TestMethodRunnerTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestMethodRunnerTests.cs @@ -266,7 +266,7 @@ public async Task RunTestMethodShouldSetDataRowIndexForDataDrivenTestsWhenDataIs // Setup mocks _testablePlatformServiceProvider.MockReflectionOperations.Setup(rf => rf.GetCustomAttributes(methodInfo, It.IsAny())).Returns(attributes); - var testMethodInfo = new TestableTestMethodInfo(methodInfo, _testClassInfo, _testMethodOptions, () => new UTF.TestResult()); + var testMethodInfo = new TestableTestMethodInfo(methodInfo, _testClassInfo, _testMethodOptions, () => new TestResult()); var testMethodRunner = new TestMethodRunner(testMethodInfo, _testMethod, _testContextImplementation); _testablePlatformServiceProvider.MockTestDataSource.Setup(tds => tds.GetData(testMethodInfo, _testContextImplementation)).Returns([1, 2, 3]); @@ -293,7 +293,7 @@ public async Task RunTestMethodShouldRunOnlyDataSourceTestsWhenBothDataSourceAnd // Setup mocks _testablePlatformServiceProvider.MockReflectionOperations.Setup(rf => rf.GetCustomAttributes(_methodInfo, It.IsAny())).Returns(attributes); - var testMethodInfo = new TestableTestMethodInfo(_methodInfo, _testClassInfo, _testMethodOptions, () => new UTF.TestResult()); + var testMethodInfo = new TestableTestMethodInfo(_methodInfo, _testClassInfo, _testMethodOptions, () => new TestResult()); var testMethodRunner = new TestMethodRunner(testMethodInfo, _testMethod, _testContextImplementation); _testablePlatformServiceProvider.MockTestDataSource.Setup(tds => tds.GetData(testMethodInfo, _testContextImplementation)).Returns([1, 2, 3]); @@ -388,7 +388,7 @@ public async Task RunTestMethodWithEmptyDataSourceShouldNotFailBecauseConsiderEm private async Task RunTestMethodWithEmptyDataSourceShouldFailIfConsiderEmptyDataSourceAsInconclusiveIsNotTrueHelper(bool considerEmptyAsInconclusive) { - Mock? existingMock = _testablePlatformServiceProvider.MockReflectionOperations; + Mock? existingMock = _testablePlatformServiceProvider.MockReflectionOperations; try { // We want this test to go through the "real" reflection to hit the product code path relevant for the test. @@ -459,7 +459,7 @@ private class TestableTestMethodInfo : TestMethodInfo { private readonly Func _invokeTest; - internal TestableTestMethodInfo(MethodInfo testMethod, TestClassInfo parent, TestMethodOptions testMethodOptions, Func invoke) + internal TestableTestMethodInfo(MethodInfo testMethod, TestClassInfo parent, TestMethodOptions testMethodOptions, Func invoke) : base(testMethod, parent, testMethodOptions.TestContext) { TimeoutInfo = testMethodOptions.TimeoutInfo; diff --git a/test/UnitTests/MSTestAdapter.UnitTests/Execution/TestPropertyAttributeTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestPropertyAttributeTests.cs similarity index 100% rename from test/UnitTests/MSTestAdapter.UnitTests/Execution/TestPropertyAttributeTests.cs rename to test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestPropertyAttributeTests.cs diff --git a/test/UnitTests/MSTestAdapter.UnitTests/Execution/TypeCacheTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TypeCacheTests.cs similarity index 100% rename from test/UnitTests/MSTestAdapter.UnitTests/Execution/TypeCacheTests.cs rename to test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TypeCacheTests.cs diff --git a/test/UnitTests/MSTestAdapter.UnitTests/Execution/UnitTestResultTest.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/UnitTestResultTest.cs similarity index 100% rename from test/UnitTests/MSTestAdapter.UnitTests/Execution/UnitTestResultTest.cs rename to test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/UnitTestResultTest.cs diff --git a/test/UnitTests/MSTestAdapter.UnitTests/Execution/UnitTestRunnerTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/UnitTestRunnerTests.cs similarity index 100% rename from test/UnitTests/MSTestAdapter.UnitTests/Execution/UnitTestRunnerTests.cs rename to test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/UnitTestRunnerTests.cs diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Extensions/ExceptionExtensionsTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Extensions/ExceptionExtensionsTests.cs index 4aba233eba..ec2af07cf3 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Extensions/ExceptionExtensionsTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Extensions/ExceptionExtensionsTests.cs @@ -1,10 +1,14 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel; +using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Extensions; using TestFramework.ForTestingMSTest; +using UTF = Microsoft.VisualStudio.TestTools.UnitTesting; + namespace MSTestAdapter.PlatformServices.Tests.Extensions; public class ExceptionExtensionsTests : TestContainer @@ -27,4 +31,196 @@ public void GetExceptionMessageShouldReturnInnerExceptionMessageAsWell() Verify(expectedMessage == ex.GetExceptionMessage()); } + + #region TryGetExceptionMessage scenarios + + public void ExceptionTryGetMessageGetsTheExceptionMessage() + { + var exception = new Exception("dummyMessage"); + + Verify(exception.TryGetMessage() == "dummyMessage"); + } + + public void ExceptionTryGetMessageReturnsEmptyStringIfExceptionMessageIsNull() + { + var exception = new DummyException(() => null!); + + Verify(exception.TryGetMessage() == string.Empty); + } + + public void ExceptionTryGetMessageReturnsErrorMessageIfExceptionIsNull() + { + string errorMessage = string.Format(CultureInfo.InvariantCulture, Resource.UTF_FailedToGetExceptionMessage, "null"); + + var exception = (Exception?)null; + + Verify(errorMessage == exception.TryGetMessage()); + } + + public void ExceptionTryGetMessageShouldThrowIfExceptionMessageThrows() + { + var exception = new DummyException(() => throw new NotImplementedException()); + + VerifyThrows(() => exception.TryGetMessage()); + } + + #endregion + + #region TryGetStackTraceInformation scenarios + + public void TryGetStackTraceInformationReturnsNullIfExceptionStackTraceIsNullOrEmpty() + { + var exception = new DummyExceptionForStackTrace(() => null!); + + Verify(exception.TryGetStackTraceInformation() is null); + } + + public void TryGetStackTraceInformationReturnsStackTraceForAnException() + { + var exception = new DummyExceptionForStackTrace(() => " at A()\r\n at B()"); + + StackTraceInformation? stackTraceInformation = exception.TryGetStackTraceInformation(); + + Verify(stackTraceInformation!.ErrorStackTrace.StartsWith(" at A()", StringComparison.Ordinal)); + Verify(stackTraceInformation.ErrorFilePath is null); + Verify(stackTraceInformation.ErrorLineNumber == 0); + } + + public void TryGetStackTraceInformationShouldThrowIfStackTraceThrows() + { + var exception = new DummyExceptionForStackTrace(() => throw new NotImplementedException()); + + VerifyThrows(() => exception.TryGetStackTraceInformation()); + } + +#pragma warning disable CA1710 // Identifiers should have correct suffix + public class DummyExceptionForStackTrace : Exception +#pragma warning restore CA1710 // Identifiers should have correct suffix + { + private readonly Func _getStackTrace; + + public DummyExceptionForStackTrace(Func getStackTrace) => _getStackTrace = getStackTrace; + + public override string StackTrace => _getStackTrace(); + } + + internal class DummyException : Exception + { + private readonly Func _getMessage; + + public DummyException(Func message) => _getMessage = message; + + public override string Message => _getMessage(); + } + + #endregion + + #region IsUnitTestAssertException scenarios + + public void IsUnitTestAssertExceptionReturnsTrueIfExceptionIsAssertException() + { + var exception = new AssertInconclusiveException(); + Verify(exception.TryGetUnitTestAssertException(out _, out _, out _)); + } + + public void IsUnitTestAssertExceptionReturnsFalseIfExceptionIsNotAssertException() + { + var exception = new NotImplementedException(); + Verify(!exception.TryGetUnitTestAssertException(out _, out _, out _)); + } + + public void IsUnitTestAssertExceptionSetsOutcomeAsInconclusiveIfAssertInconclusiveException() + { + var exception = new AssertInconclusiveException("Dummy Message", new NotImplementedException("notImplementedException")); + exception.TryGetUnitTestAssertException(out UTF.UnitTestOutcome outcome, out string? exceptionMessage, out _); + + Verify(outcome == UTF.UnitTestOutcome.Inconclusive); + Verify(exceptionMessage == "Dummy Message"); + } + + public void IsUnitTestAssertExceptionSetsOutcomeAsFailedIfAssertFailedException() + { + var exception = new AssertFailedException("Dummy Message", new NotImplementedException("notImplementedException")); + exception.TryGetUnitTestAssertException(out UTF.UnitTestOutcome outcome, out string? exceptionMessage, out _); + + Verify(outcome == UTF.UnitTestOutcome.Failed); + Verify(exceptionMessage == "Dummy Message"); + } + #endregion + + #region GetRealException scenarios + public void GetRealExceptionGetsTheTopExceptionWhenThereIsJustOne() + { + var exception = new InvalidOperationException(); + Exception actual = exception.GetRealException(); + + Verify(actual is InvalidOperationException); + } + + public void GetRealExceptionGetsTheInnerExceptionWhenTheExceptionIsTargetInvocation() + { + var exception = new TargetInvocationException(new InvalidOperationException()); + Exception actual = exception.GetRealException(); + + Verify(actual is InvalidOperationException); + } + + public void GetRealExceptionGetsTheTargetInvocationExceptionWhenTargetInvocationIsProvidedWithNullInnerException() + { + var exception = new TargetInvocationException(null); + Exception actual = exception.GetRealException(); + + Verify(actual is TargetInvocationException); + } + + public void GetRealExceptionGetsTheInnerMostRealException() + { + var exception = new TargetInvocationException(new TargetInvocationException(new TargetInvocationException(new InvalidOperationException()))); + Exception actual = exception.GetRealException(); + + Verify(actual is InvalidOperationException); + } + + public void GetRealExceptionGetsTheInnerMostTargetInvocationException() + { + var exception = new TargetInvocationException(new TargetInvocationException(new TargetInvocationException("inner most", null))); + Exception actual = exception.GetRealException(); + + Verify(actual is TargetInvocationException); + Verify(actual.Message == "inner most"); + } + + public void GetRealExceptionGetsTheInnerExceptionWhenTheExceptionIsTypeInitialization() + { + var exception = new TypeInitializationException("some type", new InvalidOperationException()); + Exception actual = exception.GetRealException(); + + Verify(actual is InvalidOperationException); + } + + public void GetRealExceptionGetsTheTypeInitializationExceptionWhenTypeInitializationIsProvidedWithNullInnerException() + { + var exception = new TypeInitializationException("some type", null); + Exception actual = exception.GetRealException(); + + Verify(actual is TypeInitializationException); + } + + public void GetRealExceptionGetsTheInnerMostRealExceptionOfTypeInitialization() + { + var exception = new TypeInitializationException("some type", new TypeInitializationException("some type", new TypeInitializationException("some type", new InvalidOperationException()))); + Exception actual = exception.GetRealException(); + + Verify(actual is InvalidOperationException); + } + + public void GetRealExceptionGetsTheInnerMostTypeInitializationException() + { + var exception = new TypeInitializationException("some type", new TypeInitializationException("some type", new TypeInitializationException("inner most", null))); + Exception actual = exception.GetRealException(); + + Verify(actual is TypeInitializationException); + Verify(actual.Message == "The type initializer for 'inner most' threw an exception."); + } + #endregion } diff --git a/test/UnitTests/MSTestAdapter.UnitTests/Extensions/MethodInfoExtensionsTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Extensions/MethodInfoExtensionsTests.cs similarity index 96% rename from test/UnitTests/MSTestAdapter.UnitTests/Extensions/MethodInfoExtensionsTests.cs rename to test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Extensions/MethodInfoExtensionsTests.cs index b8887cb5f2..3341676ab3 100644 --- a/test/UnitTests/MSTestAdapter.UnitTests/Extensions/MethodInfoExtensionsTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Extensions/MethodInfoExtensionsTests.cs @@ -1,14 +1,14 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. -using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter; using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Extensions; using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel; +using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; +using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Extensions; using TestFramework.ForTestingMSTest; using UTF = Microsoft.VisualStudio.TestTools.UnitTesting; -using UTFExtension = Microsoft.VisualStudio.TestTools.UnitTesting; namespace Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Extensions; @@ -244,13 +244,13 @@ public void HasCorrectTestMethodSignatureShouldReturnFalseForAsyncTestMethodsWit public void HasCorrectTimeoutShouldReturnFalseForMethodsWithInvalidTimeoutAttribute() { - var timeoutAttribute = new UTF.TimeoutAttribute(-11); + var timeoutAttribute = new TimeoutAttribute(-11); Verify(!timeoutAttribute.HasCorrectTimeout); } public void HasCorrectTimeoutShouldReturnTrueForMethodsWithTimeoutAttribute() { - var timeoutAttribute = new UTF.TimeoutAttribute(11); + var timeoutAttribute = new TimeoutAttribute(11); Verify(timeoutAttribute.HasCorrectTimeout); } @@ -462,18 +462,18 @@ public static void PublicStaticMethodWithInt(int a) { } - public static int PublicStaticMethodWithTCReturningInt(UTFExtension.TestContext tc) => 0; + public static int PublicStaticMethodWithTCReturningInt(TestContext tc) => 0; - public static void PublicStaticMethodWithTC(UTFExtension.TestContext tc) + public static void PublicStaticMethodWithTC(TestContext tc) { } - public static async Task PublicStaticAsyncTaskMethodWithTC(UTFExtension.TestContext tc) => await Task.FromResult(true).ConfigureAwait(false); + public static async Task PublicStaticAsyncTaskMethodWithTC(TestContext tc) => await Task.FromResult(true).ConfigureAwait(false); - public static Task PublicStaticNonAsyncTaskMethodWithTC(UTFExtension.TestContext tc) => Task.FromResult(true); + public static Task PublicStaticNonAsyncTaskMethodWithTC(TestContext tc) => Task.FromResult(true); [SuppressMessage("Usage", "VSTHRD100:Avoid async void methods", Justification = "Done on purpose")] - public static async void PublicStaticAsyncVoidMethodWithTC(UTFExtension.TestContext tc) => await Task.FromResult(true).ConfigureAwait(false); + public static async void PublicStaticAsyncVoidMethodWithTC(TestContext tc) => await Task.FromResult(true).ConfigureAwait(false); public static int PublicStaticMethodReturningInt() => 0; @@ -507,12 +507,12 @@ public void PublicMethodWithInt(int a) public Task PublicNonAsyncTaskMethod() => Task.FromResult(true); - [UTF.Timeout(-11)] + [Timeout(-11)] public void PublicMethodWithInvalidTimeout() { } - [UTF.Timeout(11)] + [Timeout(11)] public void PublicMethodWithTimeout() { } diff --git a/test/UnitTests/MSTestAdapter.UnitTests/Extensions/TestCaseExtensionsTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Extensions/TestCaseExtensionsTests.cs similarity index 79% rename from test/UnitTests/MSTestAdapter.UnitTests/Extensions/TestCaseExtensionsTests.cs rename to test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Extensions/TestCaseExtensionsTests.cs index 5e2ba8b8df..1c8ad83b56 100644 --- a/test/UnitTests/MSTestAdapter.UnitTests/Extensions/TestCaseExtensionsTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Extensions/TestCaseExtensionsTests.cs @@ -2,12 +2,11 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Extensions; +using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; using Microsoft.VisualStudio.TestPlatform.ObjectModel; using TestFramework.ForTestingMSTest; -using Constants = Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Constants; - namespace Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Extensions; public class TestCaseExtensionsTests : TestContainer @@ -20,9 +19,9 @@ public void ToUnitTestElementShouldReturnUnitTestElementWithFieldsSet() }; string[] testCategories = ["DummyCategory"]; - testCase.SetPropertyValue(Constants.PriorityProperty, 2); - testCase.SetPropertyValue(Constants.TestCategoryProperty, testCategories); - testCase.SetPropertyValue(Constants.TestClassNameProperty, "DummyClassName"); + testCase.SetPropertyValue(EngineConstants.PriorityProperty, 2); + testCase.SetPropertyValue(EngineConstants.TestCategoryProperty, testCategories); + testCase.SetPropertyValue(EngineConstants.TestClassNameProperty, "DummyClassName"); var resultUnitTestElement = testCase.ToUnitTestElement(testCase.Source); @@ -37,7 +36,7 @@ public void ToUnitTestElementShouldReturnUnitTestElementWithFieldsSet() public void ToUnitTestElementForTestCaseWithNoPropertiesShouldReturnUnitTestElementWithDefaultFields() { TestCase testCase = new("DummyClass.DummyMethod", new("DummyUri", UriKind.Relative), Assembly.GetCallingAssembly().FullName!); - testCase.SetPropertyValue(Constants.TestClassNameProperty, "DummyClassName"); + testCase.SetPropertyValue(EngineConstants.TestClassNameProperty, "DummyClassName"); var resultUnitTestElement = testCase.ToUnitTestElement(testCase.Source); @@ -49,8 +48,8 @@ public void ToUnitTestElementForTestCaseWithNoPropertiesShouldReturnUnitTestElem public void ToUnitTestElementShouldAddDeclaringClassNameToTestElementWhenAvailable() { TestCase testCase = new("DummyClass.DummyMethod", new("DummyUri", UriKind.Relative), Assembly.GetCallingAssembly().FullName!); - testCase.SetPropertyValue(Constants.TestClassNameProperty, "DummyClassName"); - testCase.SetPropertyValue(Constants.DeclaringClassNameProperty, "DummyDeclaringClassName"); + testCase.SetPropertyValue(EngineConstants.TestClassNameProperty, "DummyClassName"); + testCase.SetPropertyValue(EngineConstants.DeclaringClassNameProperty, "DummyDeclaringClassName"); var resultUnitTestElement = testCase.ToUnitTestElement(testCase.Source); diff --git a/test/UnitTests/MSTestAdapter.UnitTests/Extensions/TestContextExtensionsTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Extensions/TestContextExtensionsTests.cs similarity index 100% rename from test/UnitTests/MSTestAdapter.UnitTests/Extensions/TestContextExtensionsTests.cs rename to test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Extensions/TestContextExtensionsTests.cs diff --git a/test/UnitTests/MSTestAdapter.UnitTests/Extensions/TestResultExtensionsTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Extensions/TestResultExtensionsTests.cs similarity index 96% rename from test/UnitTests/MSTestAdapter.UnitTests/Extensions/TestResultExtensionsTests.cs rename to test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Extensions/TestResultExtensionsTests.cs index 0f9877ebca..28f878600d 100644 --- a/test/UnitTests/MSTestAdapter.UnitTests/Extensions/TestResultExtensionsTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Extensions/TestResultExtensionsTests.cs @@ -2,6 +2,7 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Extensions; +using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; using TestFramework.ForTestingMSTest; @@ -32,7 +33,7 @@ public void ToUnitTestResultsForTestResultWithExceptionConvertsToUnitTestResults public void ToUnitTestResultsForTestResultShouldSetLoggingDataForConvertedUnitTestResults() { var timespan = default(TimeSpan); - var result = new UTF.TestResult + var result = new TestResult { DebugTrace = "debugTrace", DisplayName = "displayName", @@ -166,9 +167,9 @@ public void ToUnitTestResultsForTestResultShouldSetParentInfo() var convertedResult = result.ToTestResult(new(), default, default, string.Empty, new()); - Verify(executionId == (Guid)convertedResult.GetPropertyValue(MSTest.TestAdapter.Constants.ExecutionIdProperty)!); - Verify(parentExecId == (Guid)convertedResult.GetPropertyValue(MSTest.TestAdapter.Constants.ParentExecIdProperty)!); - Verify(innerResultsCount == (int)convertedResult.GetPropertyValue(MSTest.TestAdapter.Constants.InnerResultsCountProperty)!); + Verify(executionId == (Guid)convertedResult.GetPropertyValue(EngineConstants.ExecutionIdProperty)!); + Verify(parentExecId == (Guid)convertedResult.GetPropertyValue(EngineConstants.ParentExecIdProperty)!); + Verify(innerResultsCount == (int)convertedResult.GetPropertyValue(EngineConstants.InnerResultsCountProperty)!); } public void ToUnitTestResultsShouldHaveResultsFileProvidedToTestResult() diff --git a/test/UnitTests/MSTestAdapter.UnitTests/Extensions/UnitTestOutcomeExtensionsTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Extensions/UnitTestOutcomeExtensionsTests.cs similarity index 73% rename from test/UnitTests/MSTestAdapter.UnitTests/Extensions/UnitTestOutcomeExtensionsTests.cs rename to test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Extensions/UnitTestOutcomeExtensionsTests.cs index 77c056e763..86bc0fb6cb 100644 --- a/test/UnitTests/MSTestAdapter.UnitTests/Extensions/UnitTestOutcomeExtensionsTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Extensions/UnitTestOutcomeExtensionsTests.cs @@ -14,7 +14,7 @@ public class UnitTestOutcomeExtensionsTests : TestContainer { public void ToUnitTestOutComeForPassedTestResultsConvertsToPassedUnitTestOutCome() { - UTF.UnitTestOutcome frameworkOutcome = UTF.UnitTestOutcome.Passed; + UnitTestOutcome frameworkOutcome = UTF.UnitTestOutcome.Passed; var convertedOutcome = frameworkOutcome.ToUnitTestOutcome(); Verify(convertedOutcome == AdapterTestOutcome.Passed); @@ -22,7 +22,7 @@ public void ToUnitTestOutComeForPassedTestResultsConvertsToPassedUnitTestOutCome public void ToUnitTestResultsForFailedTestResultsConvertsToFailedUnitTestResults() { - UTF.UnitTestOutcome frameworkOutcome = UTF.UnitTestOutcome.Failed; + UnitTestOutcome frameworkOutcome = UTF.UnitTestOutcome.Failed; var convertedOutcome = frameworkOutcome.ToUnitTestOutcome(); Verify(convertedOutcome == AdapterTestOutcome.Failed); @@ -30,7 +30,7 @@ public void ToUnitTestResultsForFailedTestResultsConvertsToFailedUnitTestResults public void ToUnitTestResultsForInProgressTestResultsConvertsToInProgressUnitTestResults() { - UTF.UnitTestOutcome frameworkOutcome = UTF.UnitTestOutcome.InProgress; + UnitTestOutcome frameworkOutcome = UTF.UnitTestOutcome.InProgress; var convertedOutcome = frameworkOutcome.ToUnitTestOutcome(); Verify(convertedOutcome == AdapterTestOutcome.InProgress); @@ -38,7 +38,7 @@ public void ToUnitTestResultsForInProgressTestResultsConvertsToInProgressUnitTes public void ToUnitTestResultsForInconclusiveTestResultsConvertsToInconclusiveUnitTestResults() { - UTF.UnitTestOutcome frameworkOutcome = UTF.UnitTestOutcome.Inconclusive; + UnitTestOutcome frameworkOutcome = UTF.UnitTestOutcome.Inconclusive; var convertedOutcome = frameworkOutcome.ToUnitTestOutcome(); Verify(convertedOutcome == AdapterTestOutcome.Inconclusive); @@ -46,7 +46,7 @@ public void ToUnitTestResultsForInconclusiveTestResultsConvertsToInconclusiveUni public void ToUnitTestResultsForTimeoutTestResultsConvertsToTimeoutUnitTestResults() { - UTF.UnitTestOutcome frameworkOutcome = UTF.UnitTestOutcome.Timeout; + UnitTestOutcome frameworkOutcome = UTF.UnitTestOutcome.Timeout; var convertedOutcome = frameworkOutcome.ToUnitTestOutcome(); Verify(convertedOutcome == AdapterTestOutcome.Timeout); @@ -54,7 +54,7 @@ public void ToUnitTestResultsForTimeoutTestResultsConvertsToTimeoutUnitTestResul public void ToUnitTestResultsForUnknownTestResultsConvertsToErrorUnitTestResults() { - UTF.UnitTestOutcome frameworkOutcome = UTF.UnitTestOutcome.Unknown; + UnitTestOutcome frameworkOutcome = UTF.UnitTestOutcome.Unknown; var convertedOutcome = frameworkOutcome.ToUnitTestOutcome(); Verify(convertedOutcome == AdapterTestOutcome.Error); @@ -62,25 +62,25 @@ public void ToUnitTestResultsForUnknownTestResultsConvertsToErrorUnitTestResults public void GetMoreImportantOutcomeShouldReturnFailIfTwoOutcomesAreFailedAndInconclusive() { - UTF.UnitTestOutcome resultOutcome = UTF.UnitTestOutcome.Failed.GetMoreImportantOutcome(UTF.UnitTestOutcome.Inconclusive); + UnitTestOutcome resultOutcome = UTF.UnitTestOutcome.Failed.GetMoreImportantOutcome(UTF.UnitTestOutcome.Inconclusive); Verify(resultOutcome == UTF.UnitTestOutcome.Failed); } public void GetMoreImportantOutcomeShouldReturnInconclusiveIfTwoOutcomesArePassedAndInconclusive() { - UTF.UnitTestOutcome resultOutcome = UTF.UnitTestOutcome.Passed.GetMoreImportantOutcome(UTF.UnitTestOutcome.Inconclusive); + UnitTestOutcome resultOutcome = UTF.UnitTestOutcome.Passed.GetMoreImportantOutcome(UTF.UnitTestOutcome.Inconclusive); Verify(resultOutcome == UTF.UnitTestOutcome.Inconclusive); } public void GetMoreImportantOutcomeShouldReturnFailedIfTwoOutcomesArePassedAndFailed() { - UTF.UnitTestOutcome resultOutcome = UTF.UnitTestOutcome.Passed.GetMoreImportantOutcome(UTF.UnitTestOutcome.Failed); + UnitTestOutcome resultOutcome = UTF.UnitTestOutcome.Passed.GetMoreImportantOutcome(UTF.UnitTestOutcome.Failed); Verify(resultOutcome == UTF.UnitTestOutcome.Failed); } public void GetMoreImportantOutcomeShouldReturnFailedIfBothOutcomesAreFailed() { - UTF.UnitTestOutcome resultOutcome = UTF.UnitTestOutcome.Failed.GetMoreImportantOutcome(UTF.UnitTestOutcome.Failed); + UnitTestOutcome resultOutcome = UTF.UnitTestOutcome.Failed.GetMoreImportantOutcome(UTF.UnitTestOutcome.Failed); Verify(resultOutcome == UTF.UnitTestOutcome.Failed); } } diff --git a/test/UnitTests/MSTestAdapter.UnitTests/Helpers/DataSerializationHelperTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Helpers/DataSerializationHelperTests.cs similarity index 100% rename from test/UnitTests/MSTestAdapter.UnitTests/Helpers/DataSerializationHelperTests.cs rename to test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Helpers/DataSerializationHelperTests.cs diff --git a/test/UnitTests/MSTestAdapter.UnitTests/Helpers/DictionaryHelperTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Helpers/DictionaryHelperTests.cs similarity index 100% rename from test/UnitTests/MSTestAdapter.UnitTests/Helpers/DictionaryHelperTests.cs rename to test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Helpers/DictionaryHelperTests.cs diff --git a/test/UnitTests/MSTestAdapter.UnitTests/Helpers/ReflectHelperTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Helpers/ReflectHelperTests.cs similarity index 100% rename from test/UnitTests/MSTestAdapter.UnitTests/Helpers/ReflectHelperTests.cs rename to test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Helpers/ReflectHelperTests.cs diff --git a/test/UnitTests/MSTestAdapter.UnitTests/Helpers/RunSettingsUtilitiesTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Helpers/RunSettingsUtilitiesTests.cs similarity index 100% rename from test/UnitTests/MSTestAdapter.UnitTests/Helpers/RunSettingsUtilitiesTests.cs rename to test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Helpers/RunSettingsUtilitiesTests.cs diff --git a/test/UnitTests/MSTestAdapter.UnitTests/Helpers/UnitTestOutcomeHelperTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Helpers/UnitTestOutcomeHelperTests.cs similarity index 100% rename from test/UnitTests/MSTestAdapter.UnitTests/Helpers/UnitTestOutcomeHelperTests.cs rename to test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Helpers/UnitTestOutcomeHelperTests.cs diff --git a/test/UnitTests/MSTestAdapter.UnitTests/MSTestSettingsTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/MSTestSettingsTests.cs similarity index 99% rename from test/UnitTests/MSTestAdapter.UnitTests/MSTestSettingsTests.cs rename to test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/MSTestSettingsTests.cs index 688b87b1bb..af31738440 100644 --- a/test/UnitTests/MSTestAdapter.UnitTests/MSTestSettingsTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/MSTestSettingsTests.cs @@ -3,6 +3,7 @@ using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter; using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel; +using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Interface; using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.TestableImplementations; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter; @@ -11,6 +12,8 @@ using Moq; using TestFramework.ForTestingMSTest; + +using ExecutionScope = Microsoft.VisualStudio.TestTools.UnitTesting.ExecutionScope; #pragma warning disable CS0618 // Type or member is obsolete namespace Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests; @@ -563,7 +566,7 @@ public void GetSettingsShouldThrowWhenParallelizeHasInvalidElements() """; AdapterSettingsException exception = VerifyThrows(() => MSTestSettings.GetSettings(runSettingsXml, MSTestSettings.SettingsNameAlias, _mockMessageLogger.Object)); - Verify(exception.Message.Contains("Invalid settings 'Parallelize'. Unexpected XmlElement: 'Hola'.")); + Verify(exception.Message.Contains("MSTestAdapter encountered an unexpected element 'Hola' in its settings 'Parallelize'. Remove this element and try again.")); } public void GetSettingsShouldBeAbleToReadAfterParallelizationSettings() diff --git a/test/UnitTests/MSTestAdapter.UnitTests/ObjectModel/UnitTestElementTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/ObjectModel/UnitTestElementTests.cs similarity index 86% rename from test/UnitTests/MSTestAdapter.UnitTests/ObjectModel/UnitTestElementTests.cs rename to test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/ObjectModel/UnitTestElementTests.cs index cc4c0ed328..688de5c88e 100644 --- a/test/UnitTests/MSTestAdapter.UnitTests/ObjectModel/UnitTestElementTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/ObjectModel/UnitTestElementTests.cs @@ -2,14 +2,13 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel; +using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; using Microsoft.VisualStudio.TestPlatform.ObjectModel; using Polyfills; using TestFramework.ForTestingMSTest; -using Constants = Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Constants; - namespace Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.ObjectModel; public class UnitTestElementTests : TestContainer @@ -43,7 +42,7 @@ public void ToTestCaseShouldSetExecutorUri() { var testCase = _unitTestElement.ToTestCase(); - Verify(testCase.ExecutorUri == Constants.ExecutorUri); + Verify(testCase.ExecutorUri == EngineConstants.ExecutorUri); } public void ToTestCaseShouldSetAssemblyName() @@ -72,7 +71,7 @@ public void ToTestCaseShouldSetTestClassNameProperty() { var testCase = _unitTestElement.ToTestCase(); - Verify((testCase.GetPropertyValue(Constants.TestClassNameProperty) as string) == "C"); + Verify((testCase.GetPropertyValue(EngineConstants.TestClassNameProperty) as string) == "C"); } public void ToTestCaseShouldSetDeclaringClassNameIfPresent() @@ -80,12 +79,12 @@ public void ToTestCaseShouldSetDeclaringClassNameIfPresent() _testMethod.DeclaringClassFullName = null; var testCase = _unitTestElement.ToTestCase(); - Verify(testCase.GetPropertyValue(Constants.DeclaringClassNameProperty) is null); + Verify(testCase.GetPropertyValue(EngineConstants.DeclaringClassNameProperty) is null); _testMethod.DeclaringClassFullName = "DC"; testCase = _unitTestElement.ToTestCase(); - Verify((testCase.GetPropertyValue(Constants.DeclaringClassNameProperty) as string) == "DC"); + Verify((testCase.GetPropertyValue(EngineConstants.DeclaringClassNameProperty) as string) == "DC"); } public void ToTestCaseShouldSetTestCategoryIfPresent() @@ -93,17 +92,17 @@ public void ToTestCaseShouldSetTestCategoryIfPresent() _unitTestElement.TestCategory = null; var testCase = _unitTestElement.ToTestCase(); - Verify(testCase.GetPropertyValue(Constants.TestCategoryProperty) is null); + Verify(testCase.GetPropertyValue(EngineConstants.TestCategoryProperty) is null); _unitTestElement.TestCategory = []; testCase = _unitTestElement.ToTestCase(); - Verify(testCase.GetPropertyValue(Constants.TestCategoryProperty) is null); + Verify(testCase.GetPropertyValue(EngineConstants.TestCategoryProperty) is null); _unitTestElement.TestCategory = ["TC"]; testCase = _unitTestElement.ToTestCase(); - Verify(new string[] { "TC" }.SequenceEqual((string[])testCase.GetPropertyValue(Constants.TestCategoryProperty)!)); + Verify(new string[] { "TC" }.SequenceEqual((string[])testCase.GetPropertyValue(EngineConstants.TestCategoryProperty)!)); } public void ToTestCaseShouldSetPriorityIfPresent() @@ -111,12 +110,12 @@ public void ToTestCaseShouldSetPriorityIfPresent() _unitTestElement.Priority = null; var testCase = _unitTestElement.ToTestCase(); - Verify((int)testCase.GetPropertyValue(Constants.PriorityProperty)! == 0); + Verify((int)testCase.GetPropertyValue(EngineConstants.PriorityProperty)! == 0); _unitTestElement.Priority = 1; testCase = _unitTestElement.ToTestCase(); - Verify((int)testCase.GetPropertyValue(Constants.PriorityProperty)! == 1); + Verify((int)testCase.GetPropertyValue(EngineConstants.PriorityProperty)! == 1); } public void ToTestCaseShouldSetTraitsIfPresent() @@ -146,10 +145,10 @@ public void ToTestCaseShouldSetPropertiesIfPresent() var testCase = _unitTestElement.ToTestCase(); - Verify((testCase.GetPropertyValue(Constants.CssIterationProperty) as string) == "12"); - Verify((testCase.GetPropertyValue(Constants.CssProjectStructureProperty) as string) == "ProjectStructure"); - Verify((testCase.GetPropertyValue(Constants.DescriptionProperty) as string) == "I am a dummy test"); - Verify(new string[] { "2312", "22332" }.SequenceEqual((string[])testCase.GetPropertyValue(Constants.WorkItemIdsProperty)!)); + Verify((testCase.GetPropertyValue(EngineConstants.CssIterationProperty) as string) == "12"); + Verify((testCase.GetPropertyValue(EngineConstants.CssProjectStructureProperty) as string) == "ProjectStructure"); + Verify((testCase.GetPropertyValue(EngineConstants.DescriptionProperty) as string) == "I am a dummy test"); + Verify(new string[] { "2312", "22332" }.SequenceEqual((string[])testCase.GetPropertyValue(EngineConstants.WorkItemIdsProperty)!)); } public void ToTestCaseShouldSetDeploymentItemPropertyIfPresent() @@ -157,17 +156,17 @@ public void ToTestCaseShouldSetDeploymentItemPropertyIfPresent() _unitTestElement.DeploymentItems = null; var testCase = _unitTestElement.ToTestCase(); - Verify(testCase.GetPropertyValue(Constants.DeploymentItemsProperty) is null); + Verify(testCase.GetPropertyValue(EngineConstants.DeploymentItemsProperty) is null); _unitTestElement.DeploymentItems = []; testCase = _unitTestElement.ToTestCase(); - Verify(testCase.GetPropertyValue(Constants.DeploymentItemsProperty) is null); + Verify(testCase.GetPropertyValue(EngineConstants.DeploymentItemsProperty) is null); _unitTestElement.DeploymentItems = [new("s", "d")]; testCase = _unitTestElement.ToTestCase(); - Verify(_unitTestElement.DeploymentItems.SequenceEqual(testCase.GetPropertyValue(Constants.DeploymentItemsProperty) as KeyValuePair[])); + Verify(_unitTestElement.DeploymentItems.SequenceEqual(testCase.GetPropertyValue(EngineConstants.DeploymentItemsProperty) as KeyValuePair[])); } [Obsolete("Remove test case when enum entry is removed")] @@ -179,7 +178,7 @@ public void ToTestCase_WhenStrategyIsLegacy_UsesDefaultTestCaseId() var testCase = new UnitTestElement(new("MyMethod", "MyProduct.MyNamespace.MyClass", "MyAssembly", null, TestIdGenerationStrategy.Legacy) { DataType = dataType }).ToTestCase(); var expectedTestCase = new TestCase(testCase.FullyQualifiedName, testCase.ExecutorUri, testCase.Source); Verify(expectedTestCase.Id == testCase.Id); - Verify(testCase.GetPropertyValue(Constants.TestIdGenerationStrategyProperty)!.Equals((int)TestIdGenerationStrategy.Legacy)); + Verify(testCase.GetPropertyValue(EngineConstants.TestIdGenerationStrategyProperty)!.Equals((int)TestIdGenerationStrategy.Legacy)); } #pragma warning restore CA2263 // Prefer generic overload when type is known } @@ -201,7 +200,7 @@ public void ToTestCase_WhenStrategyIsDisplayName_DoesNotUseDefaultTestCaseId() Verify(expectedTestCase.Id != testCase.Id); } - Verify(testCase.GetPropertyValue(Constants.TestIdGenerationStrategyProperty)!.Equals((int)TestIdGenerationStrategy.DisplayName)); + Verify(testCase.GetPropertyValue(EngineConstants.TestIdGenerationStrategyProperty)!.Equals((int)TestIdGenerationStrategy.DisplayName)); } #pragma warning restore CA2263 // Prefer generic overload when type is known } @@ -214,7 +213,7 @@ public void ToTestCase_WhenStrategyIsData_DoesNotUseDefaultTestCaseId() var testCase = new UnitTestElement(new("MyMethod", "MyProduct.MyNamespace.MyClass", "MyAssembly", null, TestIdGenerationStrategy.FullyQualified) { DataType = dataType }).ToTestCase(); var expectedTestCase = new TestCase(testCase.FullyQualifiedName, testCase.ExecutorUri, testCase.Source); Verify(expectedTestCase.Id != testCase.Id); - Verify(testCase.GetPropertyValue(Constants.TestIdGenerationStrategyProperty)!.Equals((int)TestIdGenerationStrategy.FullyQualified)); + Verify(testCase.GetPropertyValue(EngineConstants.TestIdGenerationStrategyProperty)!.Equals((int)TestIdGenerationStrategy.FullyQualified)); } #pragma warning restore CA2263 // Prefer generic overload when type is known } diff --git a/test/UnitTests/MSTestAdapter.UnitTests/ObjectModel/UnitTestResultTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/ObjectModel/UnitTestResultTests.cs similarity index 100% rename from test/UnitTests/MSTestAdapter.UnitTests/ObjectModel/UnitTestResultTests.cs rename to test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/ObjectModel/UnitTestResultTests.cs diff --git a/test/UnitTests/MSTestAdapter.UnitTests/PlatformServiceProviderTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/PlatformServiceProviderTests.cs similarity index 100% rename from test/UnitTests/MSTestAdapter.UnitTests/PlatformServiceProviderTests.cs rename to test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/PlatformServiceProviderTests.cs diff --git a/test/UnitTests/MSTestAdapter.UnitTests/RunConfigurationSettingsTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/RunConfigurationSettingsTests.cs similarity index 100% rename from test/UnitTests/MSTestAdapter.UnitTests/RunConfigurationSettingsTests.cs rename to test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/RunConfigurationSettingsTests.cs diff --git a/test/UnitTests/MSTestAdapter.UnitTests/TestableImplementations/TestablePlatformServiceProvider.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/TestableImplementations/TestablePlatformServiceProvider.cs similarity index 97% rename from test/UnitTests/MSTestAdapter.UnitTests/TestableImplementations/TestablePlatformServiceProvider.cs rename to test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/TestableImplementations/TestablePlatformServiceProvider.cs index 8cbc5c2de4..42019d64fc 100644 --- a/test/UnitTests/MSTestAdapter.UnitTests/TestableImplementations/TestablePlatformServiceProvider.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/TestableImplementations/TestablePlatformServiceProvider.cs @@ -10,7 +10,6 @@ using ITestDataSource = Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Interface.ITestDataSource; using ITestMethod = Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Interface.ObjectModel.ITestMethod; -using UTF = Microsoft.VisualStudio.TestTools.UnitTesting; namespace Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.TestableImplementations; @@ -70,7 +69,7 @@ public IReflectionOperations2 ReflectionOperations public bool IsGracefulStopRequested { get; set; } - public ITestContext GetTestContext(ITestMethod testMethod, StringWriter writer, IDictionary properties, IMessageLogger messageLogger, UTF.UnitTestOutcome outcome) + public ITestContext GetTestContext(ITestMethod testMethod, StringWriter writer, IDictionary properties, IMessageLogger messageLogger, UnitTestOutcome outcome) { var testContextImpl = new TestContextImplementation(testMethod, writer, properties, messageLogger); testContextImpl.SetOutcome(outcome); diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Utilities/VSInstallationUtilitiesTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Utilities/VSInstallationUtilitiesTests.cs index 1f772ec276..5f836c7f96 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Utilities/VSInstallationUtilitiesTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Utilities/VSInstallationUtilitiesTests.cs @@ -14,7 +14,7 @@ public void CheckResolutionPathsDoNotContainPrivateAssembliesPathTest() { TestSourceHost isolatedHost = new(null!, null, null); List paths = isolatedHost.GetResolutionPaths(Assembly.GetExecutingAssembly().FullName, true); - Verify(!paths.Contains(Constants.PublicAssemblies) || paths.Contains(Constants.PrivateAssemblies)); + Verify(!paths.Contains(EngineConstants.PublicAssemblies) || paths.Contains(EngineConstants.PrivateAssemblies)); } } #endif diff --git a/test/UnitTests/MSTestAdapter.UnitTests/Extensions/ExceptionExtensionsTests.cs b/test/UnitTests/MSTestAdapter.UnitTests/Extensions/ExceptionExtensionsTests.cs deleted file mode 100644 index 4bea35ee12..0000000000 --- a/test/UnitTests/MSTestAdapter.UnitTests/Extensions/ExceptionExtensionsTests.cs +++ /dev/null @@ -1,209 +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 Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter; -using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Extensions; - -using TestFramework.ForTestingMSTest; - -using UTF = Microsoft.VisualStudio.TestTools.UnitTesting; - -namespace Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Extensions; - -/// -/// Tests for class. -/// -public class ExceptionExtensionsTests : TestContainer -{ - #region TryGetExceptionMessage scenarios - - public void ExceptionTryGetMessageGetsTheExceptionMessage() - { - var exception = new Exception("dummyMessage"); - - Verify(exception.TryGetMessage() == "dummyMessage"); - } - - public void ExceptionTryGetMessageReturnsEmptyStringIfExceptionMessageIsNull() - { - var exception = new DummyException(() => null!); - - Verify(exception.TryGetMessage() == string.Empty); - } - - public void ExceptionTryGetMessageReturnsErrorMessageIfExceptionIsNull() - { - string errorMessage = string.Format(CultureInfo.InvariantCulture, Resource.UTF_FailedToGetExceptionMessage, "null"); - - var exception = (Exception?)null; - - Verify(errorMessage == exception.TryGetMessage()); - } - - public void ExceptionTryGetMessageShouldThrowIfExceptionMessageThrows() - { - var exception = new DummyException(() => throw new NotImplementedException()); - - VerifyThrows(() => exception.TryGetMessage()); - } - - #endregion - - #region TryGetStackTraceInformation scenarios - - public void TryGetStackTraceInformationReturnsNullIfExceptionStackTraceIsNullOrEmpty() - { - var exception = new DummyExceptionForStackTrace(() => null!); - - Verify(exception.TryGetStackTraceInformation() is null); - } - - public void TryGetStackTraceInformationReturnsStackTraceForAnException() - { - var exception = new DummyExceptionForStackTrace(() => " at A()\r\n at B()"); - - MSTest.TestAdapter.ObjectModel.StackTraceInformation? stackTraceInformation = exception.TryGetStackTraceInformation(); - - Verify(stackTraceInformation!.ErrorStackTrace.StartsWith(" at A()", StringComparison.Ordinal)); - Verify(stackTraceInformation.ErrorFilePath is null); - Verify(stackTraceInformation.ErrorLineNumber == 0); - } - - public void TryGetStackTraceInformationShouldThrowIfStackTraceThrows() - { - var exception = new DummyExceptionForStackTrace(() => throw new NotImplementedException()); - - VerifyThrows(() => exception.TryGetStackTraceInformation()); - } - -#pragma warning disable CA1710 // Identifiers should have correct suffix - public class DummyExceptionForStackTrace : Exception -#pragma warning restore CA1710 // Identifiers should have correct suffix - { - private readonly Func _getStackTrace; - - public DummyExceptionForStackTrace(Func getStackTrace) => _getStackTrace = getStackTrace; - - public override string StackTrace => _getStackTrace(); - } - - internal class DummyException : Exception - { - private readonly Func _getMessage; - - public DummyException(Func message) => _getMessage = message; - - public override string Message => _getMessage(); - } - - #endregion - - #region IsUnitTestAssertException scenarios - - public void IsUnitTestAssertExceptionReturnsTrueIfExceptionIsAssertException() - { - var exception = new UTF.AssertInconclusiveException(); - Verify(exception.TryGetUnitTestAssertException(out _, out _, out _)); - } - - public void IsUnitTestAssertExceptionReturnsFalseIfExceptionIsNotAssertException() - { - var exception = new NotImplementedException(); - Verify(!exception.TryGetUnitTestAssertException(out _, out _, out _)); - } - - public void IsUnitTestAssertExceptionSetsOutcomeAsInconclusiveIfAssertInconclusiveException() - { - var exception = new UTF.AssertInconclusiveException("Dummy Message", new NotImplementedException("notImplementedException")); - exception.TryGetUnitTestAssertException(out UTF.UnitTestOutcome outcome, out string? exceptionMessage, out _); - - Verify(outcome == UTF.UnitTestOutcome.Inconclusive); - Verify(exceptionMessage == "Dummy Message"); - } - - public void IsUnitTestAssertExceptionSetsOutcomeAsFailedIfAssertFailedException() - { - var exception = new UTF.AssertFailedException("Dummy Message", new NotImplementedException("notImplementedException")); - exception.TryGetUnitTestAssertException(out UTF.UnitTestOutcome outcome, out string? exceptionMessage, out _); - - Verify(outcome == UTF.UnitTestOutcome.Failed); - Verify(exceptionMessage == "Dummy Message"); - } - #endregion - - #region GetRealException scenarios - public void GetRealExceptionGetsTheTopExceptionWhenThereIsJustOne() - { - var exception = new InvalidOperationException(); - Exception actual = exception.GetRealException(); - - Verify(actual is InvalidOperationException); - } - - public void GetRealExceptionGetsTheInnerExceptionWhenTheExceptionIsTargetInvocation() - { - var exception = new TargetInvocationException(new InvalidOperationException()); - Exception actual = exception.GetRealException(); - - Verify(actual is InvalidOperationException); - } - - public void GetRealExceptionGetsTheTargetInvocationExceptionWhenTargetInvocationIsProvidedWithNullInnerException() - { - var exception = new TargetInvocationException(null); - Exception actual = exception.GetRealException(); - - Verify(actual is TargetInvocationException); - } - - public void GetRealExceptionGetsTheInnerMostRealException() - { - var exception = new TargetInvocationException(new TargetInvocationException(new TargetInvocationException(new InvalidOperationException()))); - Exception actual = exception.GetRealException(); - - Verify(actual is InvalidOperationException); - } - - public void GetRealExceptionGetsTheInnerMostTargetInvocationException() - { - var exception = new TargetInvocationException(new TargetInvocationException(new TargetInvocationException("inner most", null))); - Exception actual = exception.GetRealException(); - - Verify(actual is TargetInvocationException); - Verify(actual.Message == "inner most"); - } - - public void GetRealExceptionGetsTheInnerExceptionWhenTheExceptionIsTypeInitialization() - { - var exception = new TypeInitializationException("some type", new InvalidOperationException()); - Exception actual = exception.GetRealException(); - - Verify(actual is InvalidOperationException); - } - - public void GetRealExceptionGetsTheTypeInitializationExceptionWhenTypeInitializationIsProvidedWithNullInnerException() - { - var exception = new TypeInitializationException("some type", null); - Exception actual = exception.GetRealException(); - - Verify(actual is TypeInitializationException); - } - - public void GetRealExceptionGetsTheInnerMostRealExceptionOfTypeInitialization() - { - var exception = new TypeInitializationException("some type", new TypeInitializationException("some type", new TypeInitializationException("some type", new InvalidOperationException()))); - Exception actual = exception.GetRealException(); - - Verify(actual is InvalidOperationException); - } - - public void GetRealExceptionGetsTheInnerMostTypeInitializationException() - { - var exception = new TypeInitializationException("some type", new TypeInitializationException("some type", new TypeInitializationException("inner most", null))); - Exception actual = exception.GetRealException(); - - Verify(actual is TypeInitializationException); - Verify(actual.Message == "The type initializer for 'inner most' threw an exception."); - } - #endregion -} diff --git a/test/UnitTests/MSTestAdapter.UnitTests/MSTestAdapter.UnitTests.csproj b/test/UnitTests/MSTestAdapter.UnitTests/MSTestAdapter.UnitTests.csproj index 80b1c28992..bedb8b4472 100644 --- a/test/UnitTests/MSTestAdapter.UnitTests/MSTestAdapter.UnitTests.csproj +++ b/test/UnitTests/MSTestAdapter.UnitTests/MSTestAdapter.UnitTests.csproj @@ -21,6 +21,10 @@ + + + + diff --git a/test/UnitTests/MSTestAdapter.UnitTests/MSTestDiscovererTests.cs b/test/UnitTests/MSTestAdapter.UnitTests/MSTestDiscovererTests.cs index c738849994..ea65306c21 100644 --- a/test/UnitTests/MSTestAdapter.UnitTests/MSTestDiscovererTests.cs +++ b/test/UnitTests/MSTestAdapter.UnitTests/MSTestDiscovererTests.cs @@ -226,4 +226,15 @@ public void AreValidSourcesShouldReturnFalseForInvalidSourceExtensions() _testablePlatformServiceProvider.MockTestSourceValidator.SetupGet(ts => ts.ValidSourceExtensions).Returns(new List { ".nte", ".tep" }); Verify(!MSTestDiscovererHelpers.AreValidSources(new List { "dummy.te" })); } + + [TestClass] + public class DummyClass + { + [TestMethod] + public void DummyTestMethod() + { + // This is a dummy test method to ensure that the MSTestDiscoverer can discover tests. + // It does not perform any assertions or operations. + } + } } diff --git a/test/UnitTests/MSTestAdapter.UnitTests/MSTestExecutorTests.cs b/test/UnitTests/MSTestAdapter.UnitTests/MSTestExecutorTests.cs index 65ac7fc0d9..ca7774fca5 100644 --- a/test/UnitTests/MSTestAdapter.UnitTests/MSTestExecutorTests.cs +++ b/test/UnitTests/MSTestAdapter.UnitTests/MSTestExecutorTests.cs @@ -2,6 +2,7 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter; +using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; using Microsoft.VisualStudio.TestPlatform.ObjectModel; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter; @@ -32,7 +33,7 @@ public void MSTestExecutorShouldProvideTestExecutionUri() var extensionUriString = (ExtensionUriAttribute)testExecutor.GetType().GetCustomAttributes(typeof(ExtensionUriAttribute), false).Single(); - Verify(extensionUriString.ExtensionUri == MSTest.TestAdapter.Constants.ExecutorUriString); + Verify(extensionUriString.ExtensionUri == EngineConstants.ExecutorUriString); } public async Task RunTestsShouldNotExecuteTestsIfTestSettingsIsGiven() diff --git a/test/UnitTests/MSTestAdapter.UnitTests/DynamicDataAttributeTests.cs b/test/UnitTests/TestFramework.UnitTests/Attributes/DynamicDataAttributeTests.cs similarity index 62% rename from test/UnitTests/MSTestAdapter.UnitTests/DynamicDataAttributeTests.cs rename to test/UnitTests/TestFramework.UnitTests/Attributes/DynamicDataAttributeTests.cs index 8bc201d4ec..93630f184b 100644 --- a/test/UnitTests/MSTestAdapter.UnitTests/DynamicDataAttributeTests.cs +++ b/test/UnitTests/TestFramework.UnitTests/Attributes/DynamicDataAttributeTests.cs @@ -1,8 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. -using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter; - using TestFramework.ForTestingMSTest; namespace Microsoft.VisualStudio.TestPlatform.TestFramework.UnitTests.Attributes; @@ -19,8 +17,6 @@ public DynamicDataAttributeTests() _testMethodInfo = _dummyTestClass.GetType().GetTypeInfo().GetDeclaredMethod("TestMethod1")!; _dynamicDataAttribute = new DynamicDataAttribute("ReusableTestDataProperty"); - // Initializes DynamicDataProvider. Normally this happens automatically but we are running outside of test adapter. - _ = PlatformServiceProvider.Instance; DynamicDataAttribute.TestIdGenerationStrategy = TestIdGenerationStrategy.FullyQualified; } @@ -264,268 +260,268 @@ public void DynamicDataSource_WithValueTupleWithTupleSyntax_Works() dynamicDataAttribute = new DynamicDataAttribute(nameof(TestClassTupleData.GetDataWithValueTupleWithTupleSyntax), typeof(TestClassTupleData), DynamicDataSourceType.Method); dynamicDataAttribute.GetData(testMethodInfo); } -} - -/// -/// The dummy test class. -/// -[TestClass] -internal class DummyTestClass -{ - /// - /// Gets the reusable test data property. - /// - public static IEnumerable ReusableTestDataProperty => [[1, 2, 3], [4, 5, 6]]; - - /// - /// Gets the null test data property. - /// - public static IEnumerable NullProperty => null!; - - /// - /// Gets the empty test data property. - /// - public static IEnumerable EmptyProperty => []; - - /// - /// Gets the wrong test data property i.e. Property returning something other than - /// expected data type of . - /// - public static string WrongDataTypeProperty => "Dummy"; - - /// - /// The reusable test data method. - /// - /// - /// The . - /// - public static IEnumerable ReusableTestDataMethod() => [[1, 2, 3], [4, 5, 6]]; - - /// - /// The custom display name method. - /// - /// - /// The method info of test method. - /// - /// - /// The test data which is passed to test method. - /// - /// - /// The . - /// - public static string GetCustomDynamicDataDisplayName(MethodInfo methodInfo, object[] data) - => $"DynamicDataTestWithDisplayName {methodInfo.Name} with {data.Length} parameters"; /// - /// Custom display name method with missing parameters. + /// The dummy test class. /// - /// - /// The . - /// - public static string GetDynamicDataDisplayNameWithMissingParameters() => throw new InvalidOperationException(); - - /// - /// Custom display name method with invalid return type. - /// - public static void GetDynamicDataDisplayNameWithInvalidReturnType() => throw new InvalidOperationException(); - - /// - /// Custom display name method with invalid first parameter type. - /// - /// - /// The method info of test method. - /// - /// - /// The test data which is passed to test method. - /// - /// - /// The . - /// - public static string GetDynamicDataDisplayNameWithInvalidFirstParameterType(string methodInfo, object[] data) => throw new InvalidOperationException(); - - /// - /// Custom display name method with invalid second parameter. - /// - /// - /// The method info of test method. - /// - /// - /// The test data which is passed to test method. - /// - /// - /// The . - /// - public static string GetDynamicDataDisplayNameWithInvalidSecondParameterType(MethodInfo methodInfo, string data) => throw new InvalidOperationException(); - - /// - /// Custom display name method that is not static. - /// - /// - /// The method info of test method. - /// - /// - /// The test data which is passed to test method. - /// - /// - /// The . - /// - public string GetDynamicDataDisplayNameNonStatic(MethodInfo methodInfo, object[] data) => throw new InvalidOperationException(); - - /// - /// The test method 1. - /// - [TestMethod] - [DynamicData("ReusableTestDataProperty")] - public void TestMethod1() - { - } + [TestClass] + internal class DummyTestClass + { + /// + /// Gets the reusable test data property. + /// + public static IEnumerable ReusableTestDataProperty => [[1, 2, 3], [4, 5, 6]]; + + /// + /// Gets the null test data property. + /// + public static IEnumerable NullProperty => null!; + + /// + /// Gets the empty test data property. + /// + public static IEnumerable EmptyProperty => []; + + /// + /// Gets the wrong test data property i.e. Property returning something other than + /// expected data type of . + /// + public static string WrongDataTypeProperty => "Dummy"; + + /// + /// The reusable test data method. + /// + /// + /// The . + /// + public static IEnumerable ReusableTestDataMethod() => [[1, 2, 3], [4, 5, 6]]; + + /// + /// The custom display name method. + /// + /// + /// The method info of test method. + /// + /// + /// The test data which is passed to test method. + /// + /// + /// The . + /// + public static string GetCustomDynamicDataDisplayName(MethodInfo methodInfo, object[] data) + => $"DynamicDataTestWithDisplayName {methodInfo.Name} with {data.Length} parameters"; + + /// + /// Custom display name method with missing parameters. + /// + /// + /// The . + /// + public static string GetDynamicDataDisplayNameWithMissingParameters() => throw new InvalidOperationException(); + + /// + /// Custom display name method with invalid return type. + /// + public static void GetDynamicDataDisplayNameWithInvalidReturnType() => throw new InvalidOperationException(); + + /// + /// Custom display name method with invalid first parameter type. + /// + /// + /// The method info of test method. + /// + /// + /// The test data which is passed to test method. + /// + /// + /// The . + /// + public static string GetDynamicDataDisplayNameWithInvalidFirstParameterType(string methodInfo, object[] data) => throw new InvalidOperationException(); + + /// + /// Custom display name method with invalid second parameter. + /// + /// + /// The method info of test method. + /// + /// + /// The test data which is passed to test method. + /// + /// + /// The . + /// + public static string GetDynamicDataDisplayNameWithInvalidSecondParameterType(MethodInfo methodInfo, string data) => throw new InvalidOperationException(); + + /// + /// Custom display name method that is not static. + /// + /// + /// The method info of test method. + /// + /// + /// The test data which is passed to test method. + /// + /// + /// The . + /// + public string GetDynamicDataDisplayNameNonStatic(MethodInfo methodInfo, object[] data) => throw new InvalidOperationException(); + + /// + /// The test method 1. + /// + [TestMethod] + [DynamicData("ReusableTestDataProperty")] + public void TestMethod1() + { + } - /// - /// The test method 2. - /// - [TestMethod] - [DynamicData("ReusableTestDataMethod")] - public void TestMethod2() - { - } + /// + /// The test method 2. + /// + [TestMethod] + [DynamicData("ReusableTestDataMethod")] + public void TestMethod2() + { + } - /// - /// The test method 3. - /// - [TestMethod] - [DynamicData("WrongDataTypeProperty")] - public void TestMethod3() - { - } + /// + /// The test method 3. + /// + [TestMethod] + [DynamicData("WrongDataTypeProperty")] + public void TestMethod3() + { + } - /// - /// The test method 4. - /// - [TestMethod] - [DynamicData("NullProperty")] - public void TestMethod4() - { - } + /// + /// The test method 4. + /// + [TestMethod] + [DynamicData("NullProperty")] + public void TestMethod4() + { + } - /// - /// The test method 5. - /// - [TestMethod] - [DynamicData("EmptyProperty")] - public void TestMethod5() - { - } + /// + /// The test method 5. + /// + [TestMethod] + [DynamicData("EmptyProperty")] + public void TestMethod5() + { + } - /// - /// DataRow test method 1. - /// - [DataRow("First", "Second", null)] - [DataRow(null, "First", "Second")] - [DataRow("First", null, "Second")] - [TestMethod] - public void DataRowTestMethod() - { - } + /// + /// DataRow test method 1. + /// + [DataRow("First", "Second", null)] + [DataRow(null, "First", "Second")] + [DataRow("First", null, "Second")] + [TestMethod] + public void DataRowTestMethod() + { + } - /// - /// Custom display name method that is private. - /// - /// - /// The method info of test method. - /// - /// - /// The test data which is passed to test method. - /// - /// - /// The . - /// + /// + /// Custom display name method that is private. + /// + /// + /// The method info of test method. + /// + /// + /// The test data which is passed to test method. + /// + /// + /// The . + /// #pragma warning disable IDE0051 // Remove unused private members - private static string GetDynamicDataDisplayNamePrivate(MethodInfo methodInfo, object[] data) => throw new InvalidOperationException(); -} - -public class DummyTestClass2 -{ - /// - /// Gets the reusable test data property. - /// - public static IEnumerable ReusableTestDataProperty2 => [[1, 2, 3], [4, 5, 6]]; - - /// - /// The reusable test data method. - /// - /// - /// The . - /// - public static IEnumerable ReusableTestDataMethod2() => [[1, 2, 3], [4, 5, 6]]; - - /// - /// The custom display name method. - /// - /// - /// The method info of test method. - /// - /// - /// The test data which is passed to test method. - /// - /// - /// The . - /// - public static string GetCustomDynamicDataDisplayName2(MethodInfo methodInfo, object[] data) - => $"DynamicDataTestWithDisplayName {methodInfo.Name} with {data.Length} parameters"; -} - -[TestClass] -internal class TestClassTupleData -{ - public static IEnumerable> GetDataWithTuple() - { - yield return new(0, "0"); - yield return new(1, "1"); - } - - public static IEnumerable> DataWithTuple - { - get + private static string GetDynamicDataDisplayNamePrivate(MethodInfo methodInfo, object[] data) => throw new InvalidOperationException(); + } + + public class DummyTestClass2 + { + /// + /// Gets the reusable test data property. + /// + public static IEnumerable ReusableTestDataProperty2 => [[1, 2, 3], [4, 5, 6]]; + + /// + /// The reusable test data method. + /// + /// + /// The . + /// + public static IEnumerable ReusableTestDataMethod2() => [[1, 2, 3], [4, 5, 6]]; + + /// + /// The custom display name method. + /// + /// + /// The method info of test method. + /// + /// + /// The test data which is passed to test method. + /// + /// + /// The . + /// + public static string GetCustomDynamicDataDisplayName2(MethodInfo methodInfo, object[] data) + => $"DynamicDataTestWithDisplayName {methodInfo.Name} with {data.Length} parameters"; + } + + [TestClass] + internal class TestClassTupleData + { + public static IEnumerable> GetDataWithTuple() { yield return new(0, "0"); yield return new(1, "1"); } - } - [SuppressMessage("StyleCop.CSharp.ReadabilityRules", "SA1141:Use tuple syntax", Justification = "We want to explicitly test this syntax")] - public static IEnumerable> GetDataWithValueTuple() - { - yield return new(0, "0"); - yield return new(1, "1"); - } + public static IEnumerable> DataWithTuple + { + get + { + yield return new(0, "0"); + yield return new(1, "1"); + } + } - [SuppressMessage("StyleCop.CSharp.ReadabilityRules", "SA1141:Use tuple syntax", Justification = "We want to explicitly test this syntax")] - public static IEnumerable> DataWithValueTuple - { - get + [SuppressMessage("StyleCop.CSharp.ReadabilityRules", "SA1141:Use tuple syntax", Justification = "We want to explicitly test this syntax")] + public static IEnumerable> GetDataWithValueTuple() { yield return new(0, "0"); yield return new(1, "1"); } - } - public static IEnumerable<(int Integer, string AsString)> GetDataWithValueTupleWithTupleSyntax() - { - yield return (0, "0"); - yield return (1, "1"); - } + [SuppressMessage("StyleCop.CSharp.ReadabilityRules", "SA1141:Use tuple syntax", Justification = "We want to explicitly test this syntax")] + public static IEnumerable> DataWithValueTuple + { + get + { + yield return new(0, "0"); + yield return new(1, "1"); + } + } - public static IEnumerable<(int Integer, string AsString)> DataWithValueTupleWithTupleSyntax - { - get + public static IEnumerable<(int Integer, string AsString)> GetDataWithValueTupleWithTupleSyntax() { yield return (0, "0"); yield return (1, "1"); } - } - [DataTestMethod] - public void DynamicDataTestWithTuple(int value, string integerAsString) - { + public static IEnumerable<(int Integer, string AsString)> DataWithValueTupleWithTupleSyntax + { + get + { + yield return (0, "0"); + yield return (1, "1"); + } + } + + [DataTestMethod] + public void DynamicDataTestWithTuple(int value, string integerAsString) + { + } } } From fd87dd5c26e769cf93afb3805ef8fdaad6ec1da9 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Wed, 11 Jun 2025 18:49:18 +0200 Subject: [PATCH 073/541] Update MSTest version in samples (#5738) --- samples/public/Directory.Build.props | 2 +- samples/public/global.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/samples/public/Directory.Build.props b/samples/public/Directory.Build.props index 803b6a98c5..94c524b6b1 100644 --- a/samples/public/Directory.Build.props +++ b/samples/public/Directory.Build.props @@ -3,7 +3,7 @@ 9.0.0 17.14.2 - 3.9.0 + 3.9.2 1.0.0-alpha.25256.6 1.50.0 1.7.0 diff --git a/samples/public/global.json b/samples/public/global.json index ccda54a3fa..0026bd52f7 100644 --- a/samples/public/global.json +++ b/samples/public/global.json @@ -1,5 +1,5 @@ { "msbuild-sdks": { - "MSTest.Sdk": "3.9.0" + "MSTest.Sdk": "3.9.2" } } From 36824495f3a713ba693b3e1906c3c0fa3153515f Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Wed, 11 Jun 2025 18:50:41 +0200 Subject: [PATCH 074/541] Update dogfooding versions (#5737) --- Directory.Packages.props | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Directory.Packages.props b/Directory.Packages.props index 01279aa849..458b3be720 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -29,8 +29,8 @@ 1.1.3-beta1.24423.1 - 3.10.0-preview.25304.2 - 1.8.0-preview.25304.2 + 3.10.0-preview.25311.1 + 1.8.0-preview.25311.1 From b3b81f44e18c4f1c5acdbb3974791b3023e158d1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Jare=C5=A1?= Date: Wed, 11 Jun 2025 21:10:48 +0200 Subject: [PATCH 075/541] Add 3.9.2 changelogs (#5726) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Amaury Levé --- docs/Changelog-Platform.md | 17 +++++++++++++++++ docs/Changelog.md | 28 ++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+) diff --git a/docs/Changelog-Platform.md b/docs/Changelog-Platform.md index f965061f16..0e8ee74760 100644 --- a/docs/Changelog-Platform.md +++ b/docs/Changelog-Platform.md @@ -4,6 +4,23 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) +## [3.9.2] - 2025-06-10 + +See full log [of v3.9.1...v3.9.2](https://github.com/microsoft/testfx/compare/v3.9.1...v3.9.2) + +### Fixed + +* Allow framework authors to use TestCase.FullyQualifiedName as the TestNodeUid by @Youssef1313 in [#5658](https://github.com/microsoft/testfx/pull/5658) + +### Artifacts + +* Microsoft.Testing.Extensions.CrashDump: [1.7.2](https://www.nuget.org/packages/Microsoft.Testing.Extensions.CrashDump/1.7.2) +* Microsoft.Testing.Extensions.HangDump: [1.7.2](https://www.nuget.org/packages/Microsoft.Testing.Extensions.HangDump/1.7.2) +* Microsoft.Testing.Extensions.HotReload: [1.7.2](https://www.nuget.org/packages/Microsoft.Testing.Extensions.HotReload/1.7.2) +* Microsoft.Testing.Extensions.Retry: [1.7.2](https://www.nuget.org/packages/Microsoft.Testing.Extensions.Retry/1.7.2) +* Microsoft.Testing.Extensions.TrxReport: [1.7.2](https://www.nuget.org/packages/Microsoft.Testing.Extensions.TrxReport/1.7.2) +* Microsoft.Testing.Extensions.AzureDevOpsReport [1.0.0-alpha.25310.6](https://www.nuget.org/packages/Microsoft.Testing.Extensions.AzureDevOpsReport/1.0.0-alpha.25310.6) + ## [1.7.1] - 2025-05-27 See full log [of v3.9.0...v3.9.1](https://github.com/microsoft/testfx/compare/v3.9.0...v3.9.1) diff --git a/docs/Changelog.md b/docs/Changelog.md index 06bd4a8ed2..9513782ff4 100644 --- a/docs/Changelog.md +++ b/docs/Changelog.md @@ -4,6 +4,34 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) +## [3.9.2] - 2025-06-10 + +See full log [of v3.9.1...v3.9.2](https://github.com/microsoft/testfx/compare/v3.9.1...v3.9.2) + +### Fixed + +* Fix MSTEST0042 (duplicate data row) false positive with Zero/NegativeZero by @Youssef1313 in [#5684](https://github.com/microsoft/testfx/pull/5684) +* Ensure TestMethodAttribute.Execute is run on the correct execution context by @Youssef1313 in [#5688](https://github.com/microsoft/testfx/pull/5688) +* Avoid loading System.Threading.Tasks.Extensions when not needed by @Youssef1313 in [#5694](https://github.com/microsoft/testfx/pull/5694) +* Fix UseAsync property in TestMethodAttribute derived classes to use type checks by @Youssef1313 and @Copilot in [#5708](https://github.com/microsoft/testfx/pull/5708) +* Fix UnitTestRunner leaking some test class instances by @Youssef1313 in [#5715](https://github.com/microsoft/testfx/pull/5715) + +### Artifacts + +* MSTest: [3.9.2](https://www.nuget.org/packages/MSTest/3.9.2) +* MSTest.TestFramework: [3.9.2](https://www.nuget.org/packages/MSTest.TestFramework/3.9.2) +* MSTest.TestAdapter: [3.9.2](https://www.nuget.org/packages/MSTest.TestAdapter/3.9.2) +* MSTest.Analyzers: [3.9.2](https://www.nuget.org/packages/MSTest.Analyzers/3.9.2) +* MSTest.Sdk: [3.9.2](https://www.nuget.org/packages/MSTest.Sdk/3.9.2) +* Microsoft.Testing.Extensions.CrashDump: [1.7.2](https://www.nuget.org/packages/Microsoft.Testing.Extensions.CrashDump/1.7.2) +* Microsoft.Testing.Extensions.HangDump: [1.7.2](https://www.nuget.org/packages/Microsoft.Testing.Extensions.HangDump/1.7.2) +* Microsoft.Testing.Extensions.HotReload: [1.7.2](https://www.nuget.org/packages/Microsoft.Testing.Extensions.HotReload/1.7.2) +* Microsoft.Testing.Extensions.Retry: [1.7.2](https://www.nuget.org/packages/Microsoft.Testing.Extensions.Retry/1.7.2) +* Microsoft.Testing.Extensions.TrxReport: [1.7.2](https://www.nuget.org/packages/Microsoft.Testing.Extensions.TrxReport/1.7.2) +* Microsoft.Testing.Extensions.AzureDevOpsReport [1.0.0-alpha.25310.6](https://www.nuget.org/packages/Microsoft.Testing.Extensions.AzureDevOpsReport/1.0.0-alpha.25310.6) +* MSTest.SourceGeneration: [1.0.0-alpha.25310.6](https://www.nuget.org/packages/MSTest.SourceGeneration/1.0.0-alpha.25310.6) +* MSTest.Engine: [1.0.0-alpha.25310.6](https://www.nuget.org/packages/MSTest.Engine/1.0.0-alpha.25310.6) + ## [3.9.1] - 2025-05-27 See full log [of v3.9.0...v3.9.1](https://github.com/microsoft/testfx/compare/v3.9.0...v3.9.1) From 41337cfc200d6291ab4ca7d24d948fb35530798b Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Wed, 11 Jun 2025 22:04:49 +0200 Subject: [PATCH 076/541] Use ConfigureAwait(false) (#5719) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Amaury Levé --- .editorconfig | 3 + samples/.editorconfig | 3 + .../Engine/BFSTestNodeVisitor.cs | 4 +- .../Engine/TestArgumentsManager.cs | 4 +- .../Engine/TestFixtureManager.cs | 14 +- .../Engine/TestFrameworkEngine.cs | 22 ++-- .../Engine/TestSessionContext.cs | 2 +- .../Engine/ThreadPoolTestNodeRunner.cs | 26 ++-- .../TestFramework/TestFramework.cs | 6 +- ...ternalUnsafeActionParameterizedTestNode.cs | 2 +- ...alUnsafeActionTaskParameterizedTestNode.cs | 6 +- ...lUnsafeAsyncActionParameterizedTestNode.cs | 2 +- ...afeAsyncActionTaskParameterizedTestNode.cs | 6 +- .../InternalUnsafeAsyncActionTestNode.cs | 2 +- .../MSTestBridgedTestFramework.cs | 2 +- .../VSTestAdapter/MSTestExecutor.cs | 10 +- .../Execution/TestExecutionManager.cs | 16 +-- .../Execution/TestMethodInfo.cs | 14 +- .../Execution/TestMethodRunner.cs | 26 ++-- .../Execution/UnitTestRunner.cs | 4 +- ...onArgsShouldAvoidConditionalAccessFixer.cs | 2 +- .../AzureDevOpsReporter.cs | 10 +- .../CrashDumpProcessLifetimeHandler.cs | 8 +- .../HangDumpActivityIndicator.cs | 52 ++++---- .../HangDumpProcessLifetimeHandler.cs | 54 ++++---- .../HotReloadHandler.cs | 8 +- .../HotReloadTestHostTestFrameworkInvoker.cs | 14 +- .../MSBuildConsumer.cs | 14 +- ...SBuildTestApplicationLifecycleCallbacks.cs | 4 +- .../RetryDataConsumer.cs | 6 +- .../RetryExecutionFilterFactory.cs | 2 +- .../RetryLifecycleCallbacks.cs | 6 +- .../RetryOrchestrator.cs | 26 ++-- .../AppInsightsProvider.cs | 18 +-- .../TrxCompareTool.cs | 6 +- .../TrxDataConsumer.cs | 14 +- .../TrxProcessLifetimeHandler.cs | 16 +-- .../TrxReportEngine.cs | 20 +-- .../TrxTestApplicationLifecycleCallbacks.cs | 2 +- .../RunSettingsConfigurationProvider.cs | 2 +- .../ObjectModel/FrameworkHandlerAdapter.cs | 2 +- ...ngleSessionVSTestAndTestAnywhereAdapter.cs | 14 +- ...RunSettingsEnvironmentVariableProvider .cs | 4 +- .../VSTestBridgedTestFrameworkBase.cs | 2 +- .../Tasks/InvokeTestingPlatformTask.cs | 2 +- .../Builder/TestApplication.cs | 44 +++---- .../Builder/TestApplicationBuilder.cs | 2 +- .../CommandLine/CommandLineHandler.cs | 114 ++++++++--------- .../CommandLine/CommandLineManager.cs | 4 +- .../CommandLineOptionsValidator.cs | 12 +- .../InformativeCommandLineTestHost.cs | 2 +- .../Configurations/AggregatedConfiguration.cs | 2 +- .../Configurations/ConfigurationManager.cs | 10 +- .../JsonConfigurationProvider.cs | 4 +- .../AbortForMaxFailedTestsExtension.cs | 4 +- .../IAsyncInitializableExtension.cs | 2 +- .../Helpers/CountDownEventExtensions.cs | 8 +- .../Helpers/DisposeHelper.cs | 4 +- .../Helpers/System/SystemAsyncMonitor.cs | 8 +- .../Helpers/System/SystemFileSystem.cs | 2 +- .../Helpers/TaskExtensions.cs | 8 +- .../Hosts/CommonTestHost.cs | 58 ++++----- .../Hosts/ConsoleTestHost.cs | 16 +-- .../Hosts/ServerTestHost.cs | 80 ++++++------ .../Hosts/TestHostBuilder.cs | 120 +++++++++--------- .../Hosts/TestHostControlledHost.cs | 10 +- .../Hosts/TestHostControllersTestHost.cs | 76 +++++------ .../Hosts/TestHostOchestratorHost.cs | 4 +- .../Hosts/ToolsTestHost.cs | 16 +-- .../IPC/NamedPipeClient.cs | 36 +++--- .../IPC/NamedPipeServer.cs | 40 +++--- .../Logging/FileLogger.cs | 20 +-- .../Logging/FileLoggerCategory.cs | 2 +- .../Logging/FileLoggerProvider.cs | 4 +- .../Logging/Logger.cs | 2 +- .../Logging/LoggerFactory.cs | 2 +- .../Logging/LoggingManager.cs | 4 +- .../Messages/AsynchronousMessageBus.cs | 14 +- .../Messages/ChannelConsumerDataProcessor.cs | 16 +-- ...onsumingEnumerableConsumerDataProcessor.cs | 10 +- .../Messages/MessageBusProxy.cs | 8 +- .../OutputDevice/BrowserOutputDevice.cs | 10 +- .../OutputDevice/OutputDeviceManager.cs | 2 +- .../OutputDevice/ProxyOutputDevice.cs | 22 ++-- .../OutputDevice/TerminalOutputDevice.cs | 30 ++--- .../ConsoleTestExecutionRequestFactory.cs | 2 +- .../Requests/TestHostTestFrameworkInvoker.cs | 26 ++-- .../DotnetTest/DotnetTestConnection.cs | 16 +-- .../DotnetTest/IPC/DotnetTestDataConsumer.cs | 16 +-- .../ServerMode/JsonRpc/Json/Json.cs | 10 +- .../JsonRpc/MessageHandlerFactory.cs | 6 +- .../ServerMode/JsonRpc/PassiveNode.cs | 20 +-- .../PerRequestServerDataConsumerService.cs | 18 +-- .../JsonRpc/ServerModePerCallOutputDevice.cs | 26 ++-- .../JsonRpc/StreamMessageHandler.cs | 24 ++-- .../ServerMode/JsonRpc/TcpMessageHandler.cs | 2 +- .../Services/StopPoliciesService.cs | 10 +- .../Services/TestApplicationResult.cs | 2 +- .../ExtensionInformationCollector.cs | 4 +- .../Telemetry/ServerTelemetry.cs | 4 +- .../Telemetry/TelemetryManager.cs | 20 +-- .../TestHost/TestHostManager.cs | 32 ++--- .../PassiveNodeDataConsumer.cs | 4 +- .../SystemEnvironmentVariableProvider.cs | 2 +- .../TestHostControllersManager.cs | 26 ++-- .../TestHostOrchestratorManager.cs | 4 +- .../Tools/ToolsManager.cs | 4 +- .../Attributes/UWP_UITestMethodAttribute.cs | 4 +- .../Attributes/WinUI_UITestMethodAttribute.cs | 6 +- .../Attributes/TestMethod/RetryAttribute.cs | 4 +- .../TestMethod/TestMethodAttribute.cs | 2 +- test/.editorconfig | 4 + 112 files changed, 812 insertions(+), 800 deletions(-) diff --git a/.editorconfig b/.editorconfig index dfbcbe5b01..5386ccd6ae 100644 --- a/.editorconfig +++ b/.editorconfig @@ -428,6 +428,9 @@ dotnet_diagnostic.CA1854.severity = warning # CA1863: Use 'CompositeFormat' dotnet_diagnostic.CA1863.severity = none +# CA2007: Consider calling ConfigureAwait on the awaited task +dotnet_diagnostic.CA2007.severity = warning + # CA2016: Forward the 'CancellationToken' parameter to methods dotnet_diagnostic.CA2016.severity = warning diff --git a/samples/.editorconfig b/samples/.editorconfig index 6fcce99672..2a4c6b6b21 100644 --- a/samples/.editorconfig +++ b/samples/.editorconfig @@ -9,3 +9,6 @@ root = false #### .NET Coding Conventions #### dotnet_analyzer_diagnostic.category-StyleCop.CSharp.DocumentationRules.severity = none # Disable StyleCop.CSharp.DocumentationRules + +# CA2007: Consider calling ConfigureAwait on the awaited task +dotnet_diagnostic.CA2007.severity = none diff --git a/src/Adapter/MSTest.Engine/Engine/BFSTestNodeVisitor.cs b/src/Adapter/MSTest.Engine/Engine/BFSTestNodeVisitor.cs index 0b83379dc2..a4111e8f36 100644 --- a/src/Adapter/MSTest.Engine/Engine/BFSTestNodeVisitor.cs +++ b/src/Adapter/MSTest.Engine/Engine/BFSTestNodeVisitor.cs @@ -78,14 +78,14 @@ public async Task VisitAsync(Func onIncludedTestNo // If the node is expandable, we expand it (replacing the original node) if (TestArgumentsManager.IsExpandableTestNode(currentNode)) { - currentNode = await _testArgumentsManager.ExpandTestNodeAsync(currentNode); + currentNode = await _testArgumentsManager.ExpandTestNodeAsync(currentNode).ConfigureAwait(false); } // If the node is not filtered out by the test execution filter, we call the callback with the node. if (_testExecutionFilter is not TestNodeUidListFilter listFilter || listFilter.TestNodeUids.Any(uid => currentNode.StableUid.ToPlatformTestNodeUid() == uid)) { - await onIncludedTestNodeAsync(currentNode, parentNodeUid); + await onIncludedTestNodeAsync(currentNode, parentNodeUid).ConfigureAwait(false); } foreach (TestNode childNode in currentNode.Tests) diff --git a/src/Adapter/MSTest.Engine/Engine/TestArgumentsManager.cs b/src/Adapter/MSTest.Engine/Engine/TestArgumentsManager.cs index 095208b484..d193d1871d 100644 --- a/src/Adapter/MSTest.Engine/Engine/TestArgumentsManager.cs +++ b/src/Adapter/MSTest.Engine/Engine/TestArgumentsManager.cs @@ -67,7 +67,7 @@ internal async Task ExpandTestNodeAsync(TestNode currentNode) break; case ITaskParameterizedTestNode parameterizedTestNode: - foreach (object? arguments in await parameterizedTestNode.GetArguments()) + foreach (object? arguments in await parameterizedTestNode.GetArguments().ConfigureAwait(false)) { ExpandNodeWithArguments(currentNode, arguments, ref argumentsRowIndex, expandedTestNodes, expandedTestNodeUids, argumentPropertiesProvider, isIndexArgumentPropertiesProvider); @@ -77,7 +77,7 @@ internal async Task ExpandTestNodeAsync(TestNode currentNode) #if NET case IAsyncParameterizedTestNode parameterizedTestNode: - await foreach (object? arguments in parameterizedTestNode.GetArguments()) + await foreach (object? arguments in parameterizedTestNode.GetArguments().ConfigureAwait(false)) { ExpandNodeWithArguments(currentNode, arguments, ref argumentsRowIndex, expandedTestNodes, expandedTestNodeUids, argumentPropertiesProvider, isIndexArgumentPropertiesProvider); diff --git a/src/Adapter/MSTest.Engine/Engine/TestFixtureManager.cs b/src/Adapter/MSTest.Engine/Engine/TestFixtureManager.cs index 3553ebc4ef..9da126c44b 100644 --- a/src/Adapter/MSTest.Engine/Engine/TestFixtureManager.cs +++ b/src/Adapter/MSTest.Engine/Engine/TestFixtureManager.cs @@ -58,7 +58,7 @@ public async Task GetFixtureAsync(string fixtureId) if (!fixture.IsValueCreated || !fixture.Value.IsCompleted) { - await fixture.Value; + await fixture.Value.ConfigureAwait(false); } // We can safely cast here because we know that the fixture is of type TFixture and is awaited. @@ -114,7 +114,7 @@ internal async Task SetupUsedFixturesAsync(TestNode testNode) { if (!lazyFixture.IsValueCreated || !lazyFixture.Value.IsCompleted) { - await lazyFixture.Value; + await lazyFixture.Value.ConfigureAwait(false); } } } @@ -142,7 +142,7 @@ internal async Task CleanUnusedFixturesAsync(TestNode testNode) // cleaning the fixture multiple times. if (usesCount == 0) { - await CleanupAndDisposeFixtureAsync(fixtureId); + await CleanupAndDisposeFixtureAsync(fixtureId).ConfigureAwait(false); } } } @@ -167,7 +167,7 @@ private void TryRegisterFixture(string fixtureId, Func> { fixtureInstancesPerType.Add( typeof(TFixture), - new(async () => await CreateAndInitializeFixtureAsync(asyncFactory, _cancellationToken), LazyThreadSafetyMode.ExecutionAndPublication)); + new(async () => await CreateAndInitializeFixtureAsync(asyncFactory, _cancellationToken).ConfigureAwait(false), LazyThreadSafetyMode.ExecutionAndPublication)); } } else @@ -177,14 +177,14 @@ private void TryRegisterFixture(string fixtureId, Func> new() { [typeof(TFixture)] = new( - async () => await CreateAndInitializeFixtureAsync(asyncFactory, _cancellationToken), + async () => await CreateAndInitializeFixtureAsync(asyncFactory, _cancellationToken).ConfigureAwait(false), LazyThreadSafetyMode.ExecutionAndPublication), }); } static async Task CreateAndInitializeFixtureAsync(Func> asyncFactory, CancellationToken cancellationToken) { - TFixture fixture = await asyncFactory(); + TFixture fixture = await asyncFactory().ConfigureAwait(false); return fixture; } } @@ -207,7 +207,7 @@ private async Task CleanupAndDisposeFixtureAsync(FixtureId fixtureId) object fixture = lazyFixture.Value.Result; #pragma warning restore VSTHRD103 // Call async methods when in an async method - await DisposeHelper.DisposeAsync(fixture); + await DisposeHelper.DisposeAsync(fixture).ConfigureAwait(false); } } diff --git a/src/Adapter/MSTest.Engine/Engine/TestFrameworkEngine.cs b/src/Adapter/MSTest.Engine/Engine/TestFrameworkEngine.cs index 0855e884df..00527b1d27 100644 --- a/src/Adapter/MSTest.Engine/Engine/TestFrameworkEngine.cs +++ b/src/Adapter/MSTest.Engine/Engine/TestFrameworkEngine.cs @@ -48,13 +48,13 @@ public TestFrameworkEngine(TestFrameworkConfiguration testFrameworkConfiguration public string Description => _extension.Description; - public async Task IsEnabledAsync() => await _extension.IsEnabledAsync(); + public async Task IsEnabledAsync() => await _extension.IsEnabledAsync().ConfigureAwait(false); public async Task ExecuteRequestAsync(TestExecutionRequest testExecutionRequest, IMessageBus messageBus, CancellationToken cancellationToken) => testExecutionRequest switch { - DiscoverTestExecutionRequest discoveryRequest => await ExecuteTestNodeDiscoveryAsync(discoveryRequest, messageBus, cancellationToken), - RunTestExecutionRequest runRequest => await ExecuteTestNodeRunAsync(runRequest, messageBus, cancellationToken), + DiscoverTestExecutionRequest discoveryRequest => await ExecuteTestNodeDiscoveryAsync(discoveryRequest, messageBus, cancellationToken).ConfigureAwait(false), + RunTestExecutionRequest runRequest => await ExecuteTestNodeRunAsync(runRequest, messageBus, cancellationToken).ConfigureAwait(false), _ => Result.Fail($"Unexpected request type: '{testExecutionRequest.GetType().FullName}'"), }; @@ -71,7 +71,7 @@ private async Task ExecuteTestNodeRunAsync(RunTestExecutionRequest reque { foreach (ITestNodesBuilder testNodeBuilder in _testNodesBuilders) { - TestNode[] testNodes = await testNodeBuilder.BuildAsync(testSessionContext); + TestNode[] testNodes = await testNodeBuilder.BuildAsync(testSessionContext).ConfigureAwait(false); allRootTestNodes.AddRange(testNodes); } @@ -99,7 +99,7 @@ await testNodesVisitor.VisitAsync((testNode, parentTestNodeUid) => fixtureManager.RegisterFixtureUsage(testNode, fixtureIds); return Task.CompletedTask; - }); + }).ConfigureAwait(false); if (testNodesVisitor.DuplicatedNodes.Length > 0) { @@ -119,13 +119,13 @@ await testNodesVisitor.VisitAsync((testNode, parentTestNodeUid) => testNodeRunner.StartTests(); // Finally, we want to wait for all tests to complete. - return await testNodeRunner.WaitAllTestsAsync(cancellationToken); + return await testNodeRunner.WaitAllTestsAsync(cancellationToken).ConfigureAwait(false); } finally { foreach (ITestNodesBuilder testNodeBuilder in _testNodesBuilders) { - await DisposeHelper.DisposeAsync(testNodeBuilder); + await DisposeHelper.DisposeAsync(testNodeBuilder).ConfigureAwait(false); } } @@ -151,7 +151,7 @@ private async Task ExecuteTestNodeDiscoveryAsync(DiscoverTestExecutionRe { foreach (ITestNodesBuilder testNodeBuilder in _testNodesBuilders) { - TestNode[] testNodes = await testNodeBuilder.BuildAsync(testSessionContext); + TestNode[] testNodes = await testNodeBuilder.BuildAsync(testSessionContext).ConfigureAwait(false); allRootTestNodes.AddRange(testNodes); } @@ -171,8 +171,8 @@ await testNodesVisitor.VisitAsync(async (testNode, parentTestNodeUid) => } await messageBus.PublishAsync(this, new TestNodeUpdateMessage(request.Session.SessionUid, progressNode, - parentTestNodeUid?.ToPlatformTestNodeUid())); - }); + parentTestNodeUid?.ToPlatformTestNodeUid())).ConfigureAwait(false); + }).ConfigureAwait(false); if (testNodesVisitor.DuplicatedNodes.Length > 0) { @@ -191,7 +191,7 @@ await testNodesVisitor.VisitAsync(async (testNode, parentTestNodeUid) => { foreach (ITestNodesBuilder testNodeBuilder in _testNodesBuilders) { - await DisposeHelper.DisposeAsync(testNodeBuilder); + await DisposeHelper.DisposeAsync(testNodeBuilder).ConfigureAwait(false); } } diff --git a/src/Adapter/MSTest.Engine/Engine/TestSessionContext.cs b/src/Adapter/MSTest.Engine/Engine/TestSessionContext.cs index 8db024032c..22042a1e5b 100644 --- a/src/Adapter/MSTest.Engine/Engine/TestSessionContext.cs +++ b/src/Adapter/MSTest.Engine/Engine/TestSessionContext.cs @@ -27,5 +27,5 @@ public TestSessionContext(IConfiguration configuration, ITestFixtureManager _, I public IConfiguration Configuration { get; } public async Task AddTestAttachmentAsync(FileInfo file, string displayName, string? description = null) - => await _publishDataAsync(new SessionFileArtifact(_sessionUid, file, displayName, description)); + => await _publishDataAsync(new SessionFileArtifact(_sessionUid, file, displayName, description)).ConfigureAwait(false); } diff --git a/src/Adapter/MSTest.Engine/Engine/ThreadPoolTestNodeRunner.cs b/src/Adapter/MSTest.Engine/Engine/ThreadPoolTestNodeRunner.cs index f8d32269cc..3070130114 100644 --- a/src/Adapter/MSTest.Engine/Engine/ThreadPoolTestNodeRunner.cs +++ b/src/Adapter/MSTest.Engine/Engine/ThreadPoolTestNodeRunner.cs @@ -63,12 +63,12 @@ public void EnqueueTest(TestNode frameworkTestNode, TestNodeUid? parentTestNodeU { // We don't have a timeout here because we can have really slow fixture and it's on user // the decision on how much to wait for it. - await _waitForStart.Task; + await _waitForStart.Task.ConfigureAwait(false); // Handle the global parallelism. if (_maxParallelTests is not null) { - await _maxParallelTests.WaitAsync(); + await _maxParallelTests.WaitAsync().ConfigureAwait(false); } try @@ -77,9 +77,9 @@ public void EnqueueTest(TestNode frameworkTestNode, TestNodeUid? parentTestNodeU PlatformTestNode progressNode = frameworkTestNode.ToPlatformTestNode(); progressNode.Properties.Add(InProgressTestNodeStateProperty.CachedInstance); - await _publishDataAsync(new TestNodeUpdateMessage(_sessionUid, progressNode, parentTestNodeUid?.ToPlatformTestNodeUid())); + await _publishDataAsync(new TestNodeUpdateMessage(_sessionUid, progressNode, parentTestNodeUid?.ToPlatformTestNodeUid())).ConfigureAwait(false); - Result result = await CreateTestRunTaskAsync(frameworkTestNode, parentTestNodeUid); + Result result = await CreateTestRunTaskAsync(frameworkTestNode, parentTestNodeUid).ConfigureAwait(false); _runningTestNodeUids.TryRemove(frameworkTestNode.StableUid, out int count); @@ -118,7 +118,7 @@ private async Task CreateTestRunTaskAsync(TestNode testNode, TestNodeUid { try { - await _testFixtureManager.SetupUsedFixturesAsync(testNode); + await _testFixtureManager.SetupUsedFixturesAsync(testNode).ConfigureAwait(false); } catch (Exception ex) { @@ -135,7 +135,7 @@ private async Task CreateTestRunTaskAsync(TestNode testNode, TestNodeUid switch (testNode) { case IAsyncActionTestNode actionTestNode: - await actionTestNode.InvokeAsync(testExecutionContext); + await actionTestNode.InvokeAsync(testExecutionContext).ConfigureAwait(false); break; case IActionTestNode actionTestNode: @@ -145,7 +145,7 @@ private async Task CreateTestRunTaskAsync(TestNode testNode, TestNodeUid case IParameterizedAsyncActionTestNode actionTestNode: await actionTestNode.InvokeAsync( testExecutionContext, - action => InvokeTestNodeAndPublishResultAsync(testNode, parentTestNodeUid, (_, _) => action(), skipPublishResult: false)); + action => InvokeTestNodeAndPublishResultAsync(testNode, parentTestNodeUid, (_, _) => action(), skipPublishResult: false)).ConfigureAwait(false); break; default: @@ -154,12 +154,12 @@ await actionTestNode.InvokeAsync( }, // Because parameterized tests report multiple results (one per parameter set), we don't want to publish the result // of the overall test node execution, but only the results of the individual parameterized tests. - skipPublishResult: testNode is IParameterizedAsyncActionTestNode); + skipPublishResult: testNode is IParameterizedAsyncActionTestNode).ConfigureAwait(false); // Try to cleanup the fixture is not more used. try { - await _testFixtureManager.CleanUnusedFixturesAsync(testNode); + await _testFixtureManager.CleanUnusedFixturesAsync(testNode).ConfigureAwait(false); return result; } catch (Exception ex) @@ -177,8 +177,8 @@ public async Task WaitAllTestsAsync(CancellationToken cancellationToken) try { _ensureTaskQueuedCountdownEvent.Signal(); - await _ensureTaskQueuedCountdownEvent.WaitAsync(cancellationToken); - Result[] results = await Task.WhenAll(_runningTests); + await _ensureTaskQueuedCountdownEvent.WaitAsync(cancellationToken).ConfigureAwait(false); + Result[] results = await Task.WhenAll(_runningTests).ConfigureAwait(false); return Result.Combine(results); } catch (OperationCanceledException ex) when (ex.CancellationToken == cancellationToken) @@ -216,7 +216,7 @@ private async Task InvokeTestNodeAndPublishResultAsync(TestNode testNode // If we're already enqueued we cancel the test before the start // The test could not use the cancellation and we should wait the end of the test self to cancel. _cancellationToken.ThrowIfCancellationRequested(); - await testNodeInvokeAction(testNode, testExecutionContext); + await testNodeInvokeAction(testNode, testExecutionContext).ConfigureAwait(false); if (!platformTestNode.Properties.Any()) { @@ -245,7 +245,7 @@ private async Task InvokeTestNodeAndPublishResultAsync(TestNode testNode if (!skipPublishResult) { - await _publishDataAsync(new TestNodeUpdateMessage(_sessionUid, platformTestNode, parentTestNodeUid?.ToPlatformTestNodeUid())); + await _publishDataAsync(new TestNodeUpdateMessage(_sessionUid, platformTestNode, parentTestNodeUid?.ToPlatformTestNodeUid())).ConfigureAwait(false); } return Result.Ok(); diff --git a/src/Adapter/MSTest.Engine/TestFramework/TestFramework.cs b/src/Adapter/MSTest.Engine/TestFramework/TestFramework.cs index e43320b5bd..88e34f3fea 100644 --- a/src/Adapter/MSTest.Engine/TestFramework/TestFramework.cs +++ b/src/Adapter/MSTest.Engine/TestFramework/TestFramework.cs @@ -47,7 +47,7 @@ public TestFramework(TestFrameworkConfiguration testFrameworkConfiguration, ITes public string Description => _extension.Description; /// - public async Task IsEnabledAsync() => await _extension.IsEnabledAsync(); + public async Task IsEnabledAsync() => await _extension.IsEnabledAsync().ConfigureAwait(false); public Task CreateTestSessionAsync(CreateTestSessionContext context) { @@ -71,7 +71,7 @@ public async Task CloseTestSessionAsync(CloseTestSession { // Ensure we have finished processing all requests. _incomingRequestCounter.Signal(); - await _incomingRequestCounter.WaitAsync(context.CancellationToken); + await _incomingRequestCounter.WaitAsync(context.CancellationToken).ConfigureAwait(false); if (_sessionErrorMessages.Count > 0) { @@ -121,7 +121,7 @@ public async Task ExecuteRequestAsync(ExecuteRequestContext context) throw new InvalidOperationException($"Request type '{context.Request.GetType().FullName}' is not supported"); } - Result result = await _engine.ExecuteRequestAsync(testExecutionRequest, context.MessageBus, context.CancellationToken); + Result result = await _engine.ExecuteRequestAsync(testExecutionRequest, context.MessageBus, context.CancellationToken).ConfigureAwait(false); foreach (IReason reason in result.Reasons) { diff --git a/src/Adapter/MSTest.Engine/TestNodes/InternalUnsafeActionParameterizedTestNode.cs b/src/Adapter/MSTest.Engine/TestNodes/InternalUnsafeActionParameterizedTestNode.cs index 749b65b3a0..2f2f7ad49f 100644 --- a/src/Adapter/MSTest.Engine/TestNodes/InternalUnsafeActionParameterizedTestNode.cs +++ b/src/Adapter/MSTest.Engine/TestNodes/InternalUnsafeActionParameterizedTestNode.cs @@ -26,7 +26,7 @@ await safeInvoke(() => { Body(testExecutionContext, item); return Task.CompletedTask; - }); + }).ConfigureAwait(false); } } diff --git a/src/Adapter/MSTest.Engine/TestNodes/InternalUnsafeActionTaskParameterizedTestNode.cs b/src/Adapter/MSTest.Engine/TestNodes/InternalUnsafeActionTaskParameterizedTestNode.cs index 28dffaa306..b5a195628c 100644 --- a/src/Adapter/MSTest.Engine/TestNodes/InternalUnsafeActionTaskParameterizedTestNode.cs +++ b/src/Adapter/MSTest.Engine/TestNodes/InternalUnsafeActionTaskParameterizedTestNode.cs @@ -16,17 +16,17 @@ public sealed class InternalUnsafeActionTaskParameterizedTestNode public required Func>> GetArguments { get; init; } - Func> ITaskParameterizedTestNode.GetArguments => async () => await GetArguments(); + Func> ITaskParameterizedTestNode.GetArguments => async () => await GetArguments().ConfigureAwait(false); async Task IParameterizedAsyncActionTestNode.InvokeAsync(ITestExecutionContext testExecutionContext, Func, Task> safeInvoke) { - foreach (TData item in await GetArguments()) + foreach (TData item in await GetArguments().ConfigureAwait(false)) { await safeInvoke(() => { Body(testExecutionContext, item); return Task.CompletedTask; - }); + }).ConfigureAwait(false); } } diff --git a/src/Adapter/MSTest.Engine/TestNodes/InternalUnsafeAsyncActionParameterizedTestNode.cs b/src/Adapter/MSTest.Engine/TestNodes/InternalUnsafeAsyncActionParameterizedTestNode.cs index 3dbc8ace32..84a220e558 100644 --- a/src/Adapter/MSTest.Engine/TestNodes/InternalUnsafeAsyncActionParameterizedTestNode.cs +++ b/src/Adapter/MSTest.Engine/TestNodes/InternalUnsafeAsyncActionParameterizedTestNode.cs @@ -22,7 +22,7 @@ async Task IParameterizedAsyncActionTestNode.InvokeAsync(ITestExecutionContext t { foreach (TData item in GetArguments()) { - await safeInvoke(async () => await Body(testExecutionContext, item)); + await safeInvoke(async () => await Body(testExecutionContext, item).ConfigureAwait(false)).ConfigureAwait(false); } } diff --git a/src/Adapter/MSTest.Engine/TestNodes/InternalUnsafeAsyncActionTaskParameterizedTestNode.cs b/src/Adapter/MSTest.Engine/TestNodes/InternalUnsafeAsyncActionTaskParameterizedTestNode.cs index f27470ba19..1a56446928 100644 --- a/src/Adapter/MSTest.Engine/TestNodes/InternalUnsafeAsyncActionTaskParameterizedTestNode.cs +++ b/src/Adapter/MSTest.Engine/TestNodes/InternalUnsafeAsyncActionTaskParameterizedTestNode.cs @@ -16,13 +16,13 @@ public sealed class InternalUnsafeAsyncActionTaskParameterizedTestNode public required Func>> GetArguments { get; init; } - Func> ITaskParameterizedTestNode.GetArguments => async () => await GetArguments(); + Func> ITaskParameterizedTestNode.GetArguments => async () => await GetArguments().ConfigureAwait(false); async Task IParameterizedAsyncActionTestNode.InvokeAsync(ITestExecutionContext testExecutionContext, Func, Task> safeInvoke) { - foreach (TData item in await GetArguments()) + foreach (TData item in await GetArguments().ConfigureAwait(false)) { - await safeInvoke(async () => await Body(testExecutionContext, item)); + await safeInvoke(async () => await Body(testExecutionContext, item).ConfigureAwait(false)).ConfigureAwait(false); } } diff --git a/src/Adapter/MSTest.Engine/TestNodes/InternalUnsafeAsyncActionTestNode.cs b/src/Adapter/MSTest.Engine/TestNodes/InternalUnsafeAsyncActionTestNode.cs index 5d8a0aa48a..f6abe9f436 100644 --- a/src/Adapter/MSTest.Engine/TestNodes/InternalUnsafeAsyncActionTestNode.cs +++ b/src/Adapter/MSTest.Engine/TestNodes/InternalUnsafeAsyncActionTestNode.cs @@ -11,5 +11,5 @@ public sealed class InternalUnsafeAsyncActionTestNode : TestNode, IAsyncActionTe public required Func Body { get; init; } async Task IAsyncActionTestNode.InvokeAsync(ITestExecutionContext testExecutionContext) - => await Body(testExecutionContext); + => await Body(testExecutionContext).ConfigureAwait(false); } diff --git a/src/Adapter/MSTest.TestAdapter/TestingPlatformAdapter/MSTestBridgedTestFramework.cs b/src/Adapter/MSTest.TestAdapter/TestingPlatformAdapter/MSTestBridgedTestFramework.cs index e529cae9cb..d09665cf53 100644 --- a/src/Adapter/MSTest.TestAdapter/TestingPlatformAdapter/MSTestBridgedTestFramework.cs +++ b/src/Adapter/MSTest.TestAdapter/TestingPlatformAdapter/MSTestBridgedTestFramework.cs @@ -53,7 +53,7 @@ protected override async Task SynchronizedRunTestsAsync(VSTestRunTestExecutionRe PlatformServiceProvider.Instance.AdapterTraceLogger = new BridgedTraceLogger(_loggerFactory.CreateLogger("mstest-trace")); MSTestExecutor testExecutor = new(cancellationToken); - await testExecutor.RunTestsAsync(request.AssemblyPaths, request.RunContext, request.FrameworkHandle, _configuration); + await testExecutor.RunTestsAsync(request.AssemblyPaths, request.RunContext, request.FrameworkHandle, _configuration).ConfigureAwait(false); } } #endif diff --git a/src/Adapter/MSTest.TestAdapter/VSTestAdapter/MSTestExecutor.cs b/src/Adapter/MSTest.TestAdapter/VSTestAdapter/MSTestExecutor.cs index d8fbda9796..638e4507db 100644 --- a/src/Adapter/MSTest.TestAdapter/VSTestAdapter/MSTestExecutor.cs +++ b/src/Adapter/MSTest.TestAdapter/VSTestAdapter/MSTestExecutor.cs @@ -84,7 +84,7 @@ internal async Task RunTestsAsync(IEnumerable? tests, IRunContext? run return; } - await RunTestsFromRightContextAsync(frameworkHandle, async testRunToken => await TestExecutionManager.RunTestsAsync(tests, runContext, frameworkHandle, testRunToken)); + await RunTestsFromRightContextAsync(frameworkHandle, async testRunToken => await TestExecutionManager.RunTestsAsync(tests, runContext, frameworkHandle, testRunToken).ConfigureAwait(false)).ConfigureAwait(false); } internal async Task RunTestsAsync(IEnumerable? sources, IRunContext? runContext, IFrameworkHandle? frameworkHandle, IConfiguration? configuration) @@ -98,7 +98,7 @@ internal async Task RunTestsAsync(IEnumerable? sources, IRunContext? run } sources = PlatformServiceProvider.Instance.TestSource.GetTestSources(sources); - await RunTestsFromRightContextAsync(frameworkHandle, async testRunToken => await TestExecutionManager.RunTestsAsync(sources, runContext, frameworkHandle, testRunToken)); + await RunTestsFromRightContextAsync(frameworkHandle, async testRunToken => await TestExecutionManager.RunTestsAsync(sources, runContext, frameworkHandle, testRunToken).ConfigureAwait(false)).ConfigureAwait(false); } /// @@ -128,7 +128,7 @@ private async Task RunTestsFromRightContextAsync(IFrameworkHandle frameworkHandl try { var threadTask = Task.Run(entryPointThread.Join, _cancellationToken); - await threadTask; + await threadTask.ConfigureAwait(false); } catch (Exception ex) { @@ -144,7 +144,7 @@ private async Task RunTestsFromRightContextAsync(IFrameworkHandle frameworkHandl frameworkHandle.SendMessage(TestMessageLevel.Warning, Resource.STAIsOnlySupportedOnWindowsWarning); } - await DoRunTestsAsync(); + await DoRunTestsAsync().ConfigureAwait(false); } // Local functions @@ -155,7 +155,7 @@ async Task DoRunTestsAsync() try { _testRunCancellationToken = new TestRunCancellationToken(); - await runTestsAction(_testRunCancellationToken); + await runTestsAction(_testRunCancellationToken).ConfigureAwait(false); } finally { diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestExecutionManager.cs b/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestExecutionManager.cs index 4e8d7cd7a8..6185a94829 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestExecutionManager.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestExecutionManager.cs @@ -162,7 +162,7 @@ internal async Task RunTestsAsync(IEnumerable tests, IRunContext? runC CacheSessionParameters(runContext, frameworkHandle); // Execute the tests - await ExecuteTestsAsync(tests, runContext, frameworkHandle, isDeploymentDone); + await ExecuteTestsAsync(tests, runContext, frameworkHandle, isDeploymentDone).ConfigureAwait(false); if (!_hasAnyTestFailed) { @@ -248,7 +248,7 @@ internal async Task RunTestsAsync(IEnumerable sources, IRunContext? runC CacheSessionParameters(runContext, frameworkHandle); // Run tests. - await ExecuteTestsAsync(tests, runContext, frameworkHandle, isDeploymentDone); + await ExecuteTestsAsync(tests, runContext, frameworkHandle, isDeploymentDone).ConfigureAwait(false); if (!_hasAnyTestFailed) { @@ -272,7 +272,7 @@ group test by test.Source into testGroup foreach (var group in testsBySource) { _testRunCancellationToken?.ThrowIfCancellationRequested(); - await ExecuteTestsInSourceAsync(group.Tests, runContext, frameworkHandle, group.Source, isDeploymentDone); + await ExecuteTestsInSourceAsync(group.Tests, runContext, frameworkHandle, group.Source, isDeploymentDone).ConfigureAwait(false); } } @@ -460,7 +460,7 @@ private async Task ExecuteTestsInSourceAsync(IEnumerable tests, IRunCo if (queue.TryDequeue(out IEnumerable? testSet)) { - await ExecuteTestsWithTestRunnerAsync(testSet, frameworkHandle, source, sourceLevelParameters, testRunner, usesAppDomains); + await ExecuteTestsWithTestRunnerAsync(testSet, frameworkHandle, source, sourceLevelParameters, testRunner, usesAppDomains).ConfigureAwait(false); } } } @@ -472,7 +472,7 @@ private async Task ExecuteTestsInSourceAsync(IEnumerable tests, IRunCo try { - await Task.WhenAll(tasks); + await Task.WhenAll(tasks).ConfigureAwait(false); } catch (Exception ex) { @@ -486,12 +486,12 @@ private async Task ExecuteTestsInSourceAsync(IEnumerable tests, IRunCo // Queue the non parallel set if (nonParallelizableTestSet != null) { - await ExecuteTestsWithTestRunnerAsync(nonParallelizableTestSet, frameworkHandle, source, sourceLevelParameters, testRunner, usesAppDomains); + await ExecuteTestsWithTestRunnerAsync(nonParallelizableTestSet, frameworkHandle, source, sourceLevelParameters, testRunner, usesAppDomains).ConfigureAwait(false); } } else { - await ExecuteTestsWithTestRunnerAsync(testsToRun, frameworkHandle, source, sourceLevelParameters, testRunner, usesAppDomains); + await ExecuteTestsWithTestRunnerAsync(testsToRun, frameworkHandle, source, sourceLevelParameters, testRunner, usesAppDomains).ConfigureAwait(false); } if (PlatformServiceProvider.Instance.IsGracefulStopRequested) @@ -562,7 +562,7 @@ private async Task ExecuteTestsWithTestRunnerAsync( } else { - unitTestResult = await testRunner.RunSingleTestAsync(unitTestElement.TestMethod, testContextProperties, remotingMessageLogger); + unitTestResult = await testRunner.RunSingleTestAsync(unitTestElement.TestMethod, testContextProperties, remotingMessageLogger).ConfigureAwait(false); } PlatformServiceProvider.Instance.AdapterTraceLogger.LogInfo("Executed test {0}", unitTestElement.TestMethod.Name); diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestMethodInfo.cs b/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestMethodInfo.cs index 0a57430762..9543fd4950 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestMethodInfo.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestMethodInfo.cs @@ -161,8 +161,8 @@ public virtual async Task InvokeAsync(object?[]? arguments) listener = new LogMessageListener(MSTestSettings.CurrentSettings.CaptureDebugTraces); result = IsTimeoutSet - ? await ExecuteInternalWithTimeoutAsync(arguments) - : await ExecuteInternalAsync(arguments, null); + ? await ExecuteInternalWithTimeoutAsync(arguments).ConfigureAwait(false) + : await ExecuteInternalAsync(arguments, null).ConfigureAwait(false); } finally { @@ -420,7 +420,7 @@ private async Task ExecuteInternalAsync(object?[]? arguments, Cancel Task? invokeResult = TestMethod.GetInvokeResultAsync(_classInstance, arguments); if (invokeResult is not null) { - await invokeResult; + await invokeResult.ConfigureAwait(false); } } else @@ -435,7 +435,7 @@ private async Task ExecuteInternalAsync(object?[]? arguments, Cancel Task? invokeResult = TestMethod.GetInvokeResultAsync(_classInstance, arguments); if (invokeResult is not null) { - await invokeResult; + await invokeResult.ConfigureAwait(false); } } catch (Exception e) @@ -450,7 +450,7 @@ private async Task ExecuteInternalAsync(object?[]? arguments, Cancel }); #pragma warning restore VSTHRD101 // Avoid unsupported async delegates - await tcs.Task; + await tcs.Task.ConfigureAwait(false); if (updatedExecutionContext is not null) { @@ -1067,7 +1067,7 @@ private async Task ExecuteInternalWithTimeoutAsync(object?[]? argume try { - return await ExecuteInternalAsync(arguments, timeoutTokenSource); + return await ExecuteInternalAsync(arguments, timeoutTokenSource).ConfigureAwait(false); } catch (OperationCanceledException) { @@ -1115,7 +1115,7 @@ private async Task ExecuteInternalWithTimeoutAsync(object?[]? argume else { // Cancel the token source as test has timed out - await TestContext.Context.CancellationTokenSource.CancelAsync(); + await TestContext.Context.CancellationTokenSource.CancelAsync().ConfigureAwait(false); } TestResult timeoutResult = new() { Outcome = UTF.UnitTestOutcome.Timeout, TestFailureException = new TestFailedException(UTFUnitTestOutcome.Timeout, errorMessage) }; diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestMethodRunner.cs b/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestMethodRunner.cs index 5c82521885..3512e38437 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestMethodRunner.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestMethodRunner.cs @@ -105,7 +105,7 @@ internal async Task ExecuteAsync(string initializationLogs, string PlatformServiceProvider.Instance.AdapterTraceLogger.LogWarning(Resource.STAIsOnlySupportedOnWindowsWarning); } - return await SafeRunTestMethodAsync(initializationLogs, initializationErrorLogs, initializationTrace, initializationTestContextMessages); + return await SafeRunTestMethodAsync(initializationLogs, initializationErrorLogs, initializationTrace, initializationTestContextMessages).ConfigureAwait(false); } // Local functions @@ -115,7 +115,7 @@ async Task SafeRunTestMethodAsync(string initializationLogs, strin try { - result = await RunTestMethodAsync(); + result = await RunTestMethodAsync().ConfigureAwait(false); } catch (TestFailedException ex) { @@ -180,21 +180,21 @@ internal async Task RunTestMethodAsync() } object?[]? data = DataSerializationHelper.Deserialize(_test.SerializedData); - TestResult[] testResults = await ExecuteTestWithDataSourceAsync(null, data); + TestResult[] testResults = await ExecuteTestWithDataSourceAsync(null, data).ConfigureAwait(false); results.AddRange(testResults); } - else if (await TryExecuteDataSourceBasedTestsAsync(results)) + else if (await TryExecuteDataSourceBasedTestsAsync(results).ConfigureAwait(false)) { isDataDriven = true; } - else if (await TryExecuteFoldedDataDrivenTestsAsync(results)) + else if (await TryExecuteFoldedDataDrivenTestsAsync(results).ConfigureAwait(false)) { isDataDriven = true; } else { _testContext.SetDisplayName(_test.DisplayName); - TestResult[] testResults = await ExecuteTestAsync(_testMethodInfo); + TestResult[] testResults = await ExecuteTestAsync(_testMethodInfo).ConfigureAwait(false); foreach (TestResult testResult in testResults) { @@ -255,7 +255,7 @@ private async Task TryExecuteDataSourceBasedTestsAsync(List re DataSourceAttribute[] dataSourceAttribute = _testMethodInfo.GetAttributes(false); if (dataSourceAttribute is { Length: 1 }) { - await ExecuteTestFromDataSourceAttributeAsync(results); + await ExecuteTestFromDataSourceAttributeAsync(results).ConfigureAwait(false); return true; } @@ -303,7 +303,7 @@ private async Task TryExecuteFoldedDataDrivenTestsAsync(List r { try { - TestResult[] testResults = await ExecuteTestWithDataSourceAsync(testDataSource, data); + TestResult[] testResults = await ExecuteTestWithDataSourceAsync(testDataSource, data).ConfigureAwait(false); results.AddRange(testResults); } @@ -342,7 +342,7 @@ private async Task ExecuteTestFromDataSourceAttributeAsync(List resu foreach (object dataRow in dataRows) { - TestResult[] testResults = await ExecuteTestWithDataRowAsync(dataRow, rowIndex++); + TestResult[] testResults = await ExecuteTestWithDataRowAsync(dataRow, rowIndex++).ConfigureAwait(false); results.AddRange(testResults); } } @@ -411,7 +411,7 @@ private async Task ExecuteTestWithDataSourceAsync(UTF.ITestDataSou TestResult[] testResults = ignoreFromTestDataRow is not null ? [TestResult.CreateIgnoredResult(ignoreFromTestDataRow)] - : await ExecuteTestAsync(_testMethodInfo); + : await ExecuteTestAsync(_testMethodInfo).ConfigureAwait(false); stopwatch.Stop(); @@ -438,7 +438,7 @@ private async Task ExecuteTestWithDataRowAsync(object dataRow, int { stopwatch = Stopwatch.StartNew(); _testContext.SetDataRow(dataRow); - testResults = await ExecuteTestAsync(_testMethodInfo); + testResults = await ExecuteTestAsync(_testMethodInfo).ConfigureAwait(false); } finally { @@ -469,7 +469,7 @@ private async Task ExecuteTestAsync(TestMethodInfo testMethodInfo) { try { - tcs.SetResult(await _testMethodInfo.Executor.ExecuteAsync(testMethodInfo)); + tcs.SetResult(await _testMethodInfo.Executor.ExecuteAsync(testMethodInfo).ConfigureAwait(false)); } catch (Exception e) { @@ -477,7 +477,7 @@ private async Task ExecuteTestAsync(TestMethodInfo testMethodInfo) } }); #pragma warning restore VSTHRD101 // Avoid unsupported async delegates - return await tcs.Task; + return await tcs.Task.ConfigureAwait(false); } catch (Exception ex) { diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Execution/UnitTestRunner.cs b/src/Adapter/MSTestAdapter.PlatformServices/Execution/UnitTestRunner.cs index af20854ed8..e484c3368e 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Execution/UnitTestRunner.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Execution/UnitTestRunner.cs @@ -190,7 +190,7 @@ internal async Task RunSingleTestAsync(TestMethod testMethod, IDic testContextForTestExecution.SetOutcome(testContextForClassInit.Context.CurrentTestOutcome); RetryBaseAttribute? retryAttribute = testMethodInfo.RetryAttribute; var testMethodRunner = new TestMethodRunner(testMethodInfo, testMethod, testContextForTestExecution); - result = await testMethodRunner.ExecuteAsync(classInitializeResult.LogOutput!, classInitializeResult.LogError!, classInitializeResult.DebugTrace!, classInitializeResult.TestContextMessages!); + result = await testMethodRunner.ExecuteAsync(classInitializeResult.LogOutput!, classInitializeResult.LogError!, classInitializeResult.DebugTrace!, classInitializeResult.TestContextMessages!).ConfigureAwait(false); if (retryAttribute is not null && !RetryBaseAttribute.IsAcceptableResultForRetry(result)) { RetryResult retryResult = await retryAttribute.ExecuteAsync( @@ -199,7 +199,7 @@ internal async Task RunSingleTestAsync(TestMethod testMethod, IDic classInitializeResult.LogOutput!, classInitializeResult.LogError!, classInitializeResult.DebugTrace!, - classInitializeResult.TestContextMessages!), result)); + classInitializeResult.TestContextMessages!).ConfigureAwait(false), result)).ConfigureAwait(false); result = retryResult.TryGetLast() ?? throw ApplicationStateGuard.Unreachable(); } diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/AssertionArgsShouldAvoidConditionalAccessFixer.cs b/src/Analyzers/MSTest.Analyzers.CodeFixes/AssertionArgsShouldAvoidConditionalAccessFixer.cs index 830253f2e4..8e5eefd5e2 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/AssertionArgsShouldAvoidConditionalAccessFixer.cs +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/AssertionArgsShouldAvoidConditionalAccessFixer.cs @@ -40,7 +40,7 @@ private sealed class CustomFixAll : DocumentBasedFixAllProvider protected override async Task FixAllAsync(FixAllContext fixAllContext, Document document, ImmutableArray diagnostics) { SyntaxNode root = await document.GetRequiredSyntaxRootAsync(fixAllContext.CancellationToken).ConfigureAwait(false); - DocumentEditor editor = await DocumentEditor.CreateAsync(document, fixAllContext.CancellationToken); + DocumentEditor editor = await DocumentEditor.CreateAsync(document, fixAllContext.CancellationToken).ConfigureAwait(false); Document currentDocument = document; foreach (Diagnostic diagnostic in diagnostics) { diff --git a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/AzureDevOpsReporter.cs b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/AzureDevOpsReporter.cs index 580002941d..b41c26b3e2 100644 --- a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/AzureDevOpsReporter.cs +++ b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/AzureDevOpsReporter.cs @@ -124,16 +124,16 @@ public async Task ConsumeAsync(IDataProducer dataProducer, IData value, Cancella switch (nodeState) { case FailedTestNodeStateProperty failed: - await WriteExceptionAsync(failed.Explanation, failed.Exception); + await WriteExceptionAsync(failed.Explanation, failed.Exception).ConfigureAwait(false); break; case ErrorTestNodeStateProperty error: - await WriteExceptionAsync(error.Explanation, error.Exception); + await WriteExceptionAsync(error.Explanation, error.Exception).ConfigureAwait(false); break; case CancelledTestNodeStateProperty cancelled: - await WriteExceptionAsync(cancelled.Explanation, cancelled.Exception); + await WriteExceptionAsync(cancelled.Explanation, cancelled.Exception).ConfigureAwait(false); break; case TimeoutTestNodeStateProperty timeout: - await WriteExceptionAsync(timeout.Explanation, timeout.Exception); + await WriteExceptionAsync(timeout.Explanation, timeout.Exception).ConfigureAwait(false); break; } } @@ -161,7 +161,7 @@ private async Task WriteExceptionAsync(string? explanation, Exception? exception _logger.LogTrace($"Showing failure message '{line}'."); } - await _outputDisplay.DisplayAsync(this, new FormattedTextOutputDeviceData(line)); + await _outputDisplay.DisplayAsync(this, new FormattedTextOutputDeviceData(line)).ConfigureAwait(false); } internal static /* for testing */ string? GetErrorText(string? explanation, Exception? exception, string severity, IFileSystem fileSystem, ILogger logger) diff --git a/src/Platform/Microsoft.Testing.Extensions.CrashDump/CrashDumpProcessLifetimeHandler.cs b/src/Platform/Microsoft.Testing.Extensions.CrashDump/CrashDumpProcessLifetimeHandler.cs index ecec7a268e..005ccc1580 100644 --- a/src/Platform/Microsoft.Testing.Extensions.CrashDump/CrashDumpProcessLifetimeHandler.cs +++ b/src/Platform/Microsoft.Testing.Extensions.CrashDump/CrashDumpProcessLifetimeHandler.cs @@ -63,19 +63,19 @@ public async Task OnTestHostProcessExitedAsync(ITestHostProcessInformation testH } ApplicationStateGuard.Ensure(_netCoreCrashDumpGeneratorConfiguration.DumpFileNamePattern is not null); - await _outputDisplay.DisplayAsync(this, new ErrorMessageOutputDeviceData(string.Format(CultureInfo.InvariantCulture, CrashDumpResources.CrashDumpProcessCrashedDumpFileCreated, testHostProcessInformation.PID))); + await _outputDisplay.DisplayAsync(this, new ErrorMessageOutputDeviceData(string.Format(CultureInfo.InvariantCulture, CrashDumpResources.CrashDumpProcessCrashedDumpFileCreated, testHostProcessInformation.PID))).ConfigureAwait(false); string expectedDumpFile = _netCoreCrashDumpGeneratorConfiguration.DumpFileNamePattern.Replace("%p", testHostProcessInformation.PID.ToString(CultureInfo.InvariantCulture)); if (File.Exists(expectedDumpFile)) { - await _messageBus.PublishAsync(this, new FileArtifact(new FileInfo(expectedDumpFile), CrashDumpResources.CrashDumpArtifactDisplayName, CrashDumpResources.CrashDumpArtifactDescription)); + await _messageBus.PublishAsync(this, new FileArtifact(new FileInfo(expectedDumpFile), CrashDumpResources.CrashDumpArtifactDisplayName, CrashDumpResources.CrashDumpArtifactDescription)).ConfigureAwait(false); } else { - await _outputDisplay.DisplayAsync(this, new ErrorMessageOutputDeviceData(string.Format(CultureInfo.InvariantCulture, CrashDumpResources.CannotFindExpectedCrashDumpFile, expectedDumpFile))); + await _outputDisplay.DisplayAsync(this, new ErrorMessageOutputDeviceData(string.Format(CultureInfo.InvariantCulture, CrashDumpResources.CannotFindExpectedCrashDumpFile, expectedDumpFile))).ConfigureAwait(false); foreach (string dumpFile in Directory.GetFiles(Path.GetDirectoryName(expectedDumpFile)!, "*.dmp")) { - await _messageBus.PublishAsync(this, new FileArtifact(new FileInfo(dumpFile), CrashDumpResources.CrashDumpDisplayName, CrashDumpResources.CrashDumpArtifactDescription)); + await _messageBus.PublishAsync(this, new FileArtifact(new FileInfo(dumpFile), CrashDumpResources.CrashDumpDisplayName, CrashDumpResources.CrashDumpArtifactDescription)).ConfigureAwait(false); } } } diff --git a/src/Platform/Microsoft.Testing.Extensions.HangDump/HangDumpActivityIndicator.cs b/src/Platform/Microsoft.Testing.Extensions.HangDump/HangDumpActivityIndicator.cs index 7ca615581c..2c8d105a5b 100644 --- a/src/Platform/Microsoft.Testing.Extensions.HangDump/HangDumpActivityIndicator.cs +++ b/src/Platform/Microsoft.Testing.Extensions.HangDump/HangDumpActivityIndicator.cs @@ -90,7 +90,7 @@ public async Task OnTestSessionStartingAsync(SessionUid sessionUid, Cancellation { ApplicationStateGuard.Ensure(_namedPipeClient is not null); - if (!await IsEnabledAsync() || cancellationToken.IsCancellationRequested) + if (!await IsEnabledAsync().ConfigureAwait(false) || cancellationToken.IsCancellationRequested) { return; } @@ -98,20 +98,20 @@ public async Task OnTestSessionStartingAsync(SessionUid sessionUid, Cancellation try { // Connect to the named pipe server - await _logger.LogTraceAsync($"Connecting to the process lifetime handler {_namedPipeClient.PipeName}"); - await _namedPipeClient.ConnectAsync(cancellationToken).TimeoutAfterAsync(TimeoutHelper.DefaultHangTimeSpanTimeout, cancellationToken); - await _logger.LogTraceAsync("Connected to the process lifetime handler"); + await _logger.LogTraceAsync($"Connecting to the process lifetime handler {_namedPipeClient.PipeName}").ConfigureAwait(false); + await _namedPipeClient.ConnectAsync(cancellationToken).TimeoutAfterAsync(TimeoutHelper.DefaultHangTimeSpanTimeout, cancellationToken).ConfigureAwait(false); + await _logger.LogTraceAsync("Connected to the process lifetime handler").ConfigureAwait(false); _activityIndicatorMutex = new Mutex(true); _mutexName = $"{HangDumpConfiguration.MutexName}_{Guid.NewGuid():N}"; // Keep the custom thread to avoid to waste one from thread pool. _signalActivityIndicatorTask = _task.RunLongRunning(SignalActivityIndicatorAsync, "[HangDump] SignalActivityIndicatorAsync", cancellationToken); - await _logger.LogTraceAsync($"Wait for mutex '{_mutexName}' creation"); + await _logger.LogTraceAsync($"Wait for mutex '{_mutexName}' creation").ConfigureAwait(false); _mutexCreated.Wait(cancellationToken); - await _logger.LogTraceAsync($"Mutex '{_mutexName}' created"); + await _logger.LogTraceAsync($"Mutex '{_mutexName}' created").ConfigureAwait(false); await _namedPipeClient.RequestReplyAsync(new ActivityIndicatorMutexNameRequest(_mutexName), cancellationToken) - .TimeoutAfterAsync(TimeoutHelper.DefaultHangTimeSpanTimeout, cancellationToken); - await _logger.LogTraceAsync($"Mutex '{_mutexName}' sent to the process lifetime handler"); + .TimeoutAfterAsync(TimeoutHelper.DefaultHangTimeSpanTimeout, cancellationToken).ConfigureAwait(false); + await _logger.LogTraceAsync($"Mutex '{_mutexName}' sent to the process lifetime handler").ConfigureAwait(false); // Setup the server channel with the testhost controller _pipeNameDescription = NamedPipeServer.GetPipeName(Guid.NewGuid().ToString("N")); @@ -121,13 +121,13 @@ await _namedPipeClient.RequestReplyAsync(new ConsumerPipeNameRequest(_pipeNameDescription.Name), cancellationToken) - .TimeoutAfterAsync(TimeoutHelper.DefaultHangTimeSpanTimeout, cancellationToken); + .TimeoutAfterAsync(TimeoutHelper.DefaultHangTimeSpanTimeout, cancellationToken).ConfigureAwait(false); // Wait the connection from the testhost controller - await _singleConnectionNamedPipeServer.WaitConnectionAsync(cancellationToken).TimeoutAfterAsync(TimeoutHelper.DefaultHangTimeSpanTimeout, cancellationToken); - await _logger.LogTraceAsync("Test host controller connected"); + await _singleConnectionNamedPipeServer.WaitConnectionAsync(cancellationToken).TimeoutAfterAsync(TimeoutHelper.DefaultHangTimeSpanTimeout, cancellationToken).ConfigureAwait(false); + await _logger.LogTraceAsync("Test host controller connected").ConfigureAwait(false); } catch (OperationCanceledException ex) when (ex.CancellationToken == cancellationToken) { @@ -139,13 +139,13 @@ private async Task CallbackAsync(IRequest request) { if (request is GetInProgressTestsRequest) { - await _logger.LogDebugAsync($"Received '{nameof(GetInProgressTestsRequest)}'"); + await _logger.LogDebugAsync($"Received '{nameof(GetInProgressTestsRequest)}'").ConfigureAwait(false); return new GetInProgressTestsResponse([.. _testsCurrentExecutionState.Select(x => (x.Value.Name, (int)_clock.UtcNow.Subtract(x.Value.StartTime).TotalSeconds))]); } else if (request is ExitSignalActivityIndicatorTaskRequest) { - await _logger.LogDebugAsync($"Received '{nameof(ExitSignalActivityIndicatorTaskRequest)}'"); - await ExitSignalActivityIndicatorTaskAsync(); + await _logger.LogDebugAsync($"Received '{nameof(ExitSignalActivityIndicatorTaskRequest)}'").ConfigureAwait(false); + await ExitSignalActivityIndicatorTaskAsync().ConfigureAwait(false); return VoidResponse.CachedInstance; } else @@ -167,7 +167,7 @@ public async Task ConsumeAsync(IDataProducer dataProducer, IData value, Cancella { if (_traceLevelEnabled) { - await _logger.LogTraceAsync($"New in-progress test '{nodeChangedMessage.TestNode.DisplayName}'"); + await _logger.LogTraceAsync($"New in-progress test '{nodeChangedMessage.TestNode.DisplayName}'").ConfigureAwait(false); } _testsCurrentExecutionState.TryAdd(nodeChangedMessage.TestNode.Uid, (nodeChangedMessage.TestNode.DisplayName, typeof(InProgressTestNodeStateProperty), _clock.UtcNow)); @@ -177,7 +177,7 @@ or FailedTestNodeStateProperty or TimeoutTestNodeStateProperty or SkippedTestNod && _testsCurrentExecutionState.TryRemove(nodeChangedMessage.TestNode.Uid, out (string Name, Type Type, DateTimeOffset StartTime) record) && _traceLevelEnabled) { - await _logger.LogTraceAsync($"Test removed from in-progress list '{record.Name}' after '{_clock.UtcNow.Subtract(record.StartTime)}', total in-progress '{_testsCurrentExecutionState.Count}'"); + await _logger.LogTraceAsync($"Test removed from in-progress list '{record.Name}' after '{_clock.UtcNow.Subtract(record.StartTime)}', total in-progress '{_testsCurrentExecutionState.Count}'").ConfigureAwait(false); } // Optimization, we're interested in test progression and eventually in the discovery progression @@ -185,7 +185,7 @@ or FailedTestNodeStateProperty or TimeoutTestNodeStateProperty or SkippedTestNod { if (_traceLevelEnabled) { - await _logger.LogTraceAsync($"Signal for action node {nodeChangedMessage.TestNode.DisplayName} - '{state}'"); + await _logger.LogTraceAsync($"Signal for action node {nodeChangedMessage.TestNode.DisplayName} - '{state}'").ConfigureAwait(false); } // Signal the activity if it's not set @@ -234,18 +234,18 @@ public async Task OnTestSessionFinishingAsync(SessionUid sessionUid, Cancellatio ApplicationStateGuard.Ensure(_namedPipeClient is not null); ApplicationStateGuard.Ensure(_activityIndicatorMutex is not null); - if (!await IsEnabledAsync()) + if (!await IsEnabledAsync().ConfigureAwait(false)) { return; } await _namedPipeClient.RequestReplyAsync(new SessionEndSerializerRequest(), cancellationToken) - .TimeoutAfterAsync(TimeoutHelper.DefaultHangTimeSpanTimeout, cancellationToken); + .TimeoutAfterAsync(TimeoutHelper.DefaultHangTimeSpanTimeout, cancellationToken).ConfigureAwait(false); - await _logger.LogDebugAsync("Signal for test session end'"); - await ExitSignalActivityIndicatorTaskAsync(); + await _logger.LogDebugAsync("Signal for test session end'").ConfigureAwait(false); + await ExitSignalActivityIndicatorTaskAsync().ConfigureAwait(false); - await _logger.LogTraceAsync("Signaled by process for it's exit"); + await _logger.LogTraceAsync("Signaled by process for it's exit").ConfigureAwait(false); _sessionEndCalled = true; } @@ -259,20 +259,20 @@ private async Task ExitSignalActivityIndicatorTaskAsync() ApplicationStateGuard.Ensure(_signalActivityIndicatorTask is not null); _exitSignalActivityIndicatorAsync = true; _signalActivity.Set(); - await _signalActivityIndicatorTask.TimeoutAfterAsync(TimeoutHelper.DefaultHangTimeSpanTimeout); + await _signalActivityIndicatorTask.TimeoutAfterAsync(TimeoutHelper.DefaultHangTimeSpanTimeout).ConfigureAwait(false); } #if NETCOREAPP public async ValueTask DisposeAsync() { - await DisposeHelper.DisposeAsync(_namedPipeClient); + await DisposeHelper.DisposeAsync(_namedPipeClient).ConfigureAwait(false); // If the OnTestSessionFinishingAsync is not called means that something unhandled happened // and we didn't correctly coordinate the shutdown with the HangDumpProcessLifetimeHandler. // If we go do wait for the server we will hang. if (_sessionEndCalled) { - await DisposeHelper.DisposeAsync(_singleConnectionNamedPipeServer); + await DisposeHelper.DisposeAsync(_singleConnectionNamedPipeServer).ConfigureAwait(false); } _pipeNameDescription?.Dispose(); diff --git a/src/Platform/Microsoft.Testing.Extensions.HangDump/HangDumpProcessLifetimeHandler.cs b/src/Platform/Microsoft.Testing.Extensions.HangDump/HangDumpProcessLifetimeHandler.cs index 06f1fa1044..2f41e6fa6e 100644 --- a/src/Platform/Microsoft.Testing.Extensions.HangDump/HangDumpProcessLifetimeHandler.cs +++ b/src/Platform/Microsoft.Testing.Extensions.HangDump/HangDumpProcessLifetimeHandler.cs @@ -118,7 +118,7 @@ public async Task BeforeTestHostProcessStartAsync(CancellationToken cancellation _dumpFileNamePattern = fileName[0]; } - await _logger.LogInformationAsync($"Hang dump timeout setup {_activityTimerValue}."); + await _logger.LogInformationAsync($"Hang dump timeout setup {_activityTimerValue}.").ConfigureAwait(false); _waitConnectionTask = _task.Run( async () => @@ -128,8 +128,8 @@ public async Task BeforeTestHostProcessStartAsync(CancellationToken cancellation _singleConnectionNamedPipeServer.RegisterSerializer(new VoidResponseSerializer(), typeof(VoidResponse)); _singleConnectionNamedPipeServer.RegisterSerializer(new SessionEndSerializerRequestSerializer(), typeof(SessionEndSerializerRequest)); _singleConnectionNamedPipeServer.RegisterSerializer(new ConsumerPipeNameRequestSerializer(), typeof(ConsumerPipeNameRequest)); - await _logger.LogDebugAsync($"Waiting for connection to {_singleConnectionNamedPipeServer.PipeName.Name}"); - await _singleConnectionNamedPipeServer.WaitConnectionAsync(cancellationToken).TimeoutAfterAsync(TimeoutHelper.DefaultHangTimeSpanTimeout, cancellationToken); + await _logger.LogDebugAsync($"Waiting for connection to {_singleConnectionNamedPipeServer.PipeName.Name}").ConfigureAwait(false); + await _singleConnectionNamedPipeServer.WaitConnectionAsync(cancellationToken).TimeoutAfterAsync(TimeoutHelper.DefaultHangTimeSpanTimeout, cancellationToken).ConfigureAwait(false); }, cancellationToken); } @@ -137,19 +137,19 @@ private async Task CallbackAsync(IRequest request) { if (request is ActivityIndicatorMutexNameRequest activityIndicatorMutexNameRequest) { - await _logger.LogDebugAsync($"Mutex name received by the test host, '{activityIndicatorMutexNameRequest.MutexName}'"); + await _logger.LogDebugAsync($"Mutex name received by the test host, '{activityIndicatorMutexNameRequest.MutexName}'").ConfigureAwait(false); _activityTimerMutexName = activityIndicatorMutexNameRequest.MutexName; _mutexNameReceived.Set(); return VoidResponse.CachedInstance; } else if (request is SessionEndSerializerRequest) { - await _logger.LogDebugAsync("Session end received by the test host"); + await _logger.LogDebugAsync("Session end received by the test host").ConfigureAwait(false); _exitActivityIndicatorTask = true; #if NET if (_namedPipeClient is not null) { - await _namedPipeClient.DisposeAsync(); + await _namedPipeClient.DisposeAsync().ConfigureAwait(false); } #else _namedPipeClient?.Dispose(); @@ -158,7 +158,7 @@ private async Task CallbackAsync(IRequest request) } else if (request is ConsumerPipeNameRequest consumerPipeNameRequest) { - await _logger.LogDebugAsync($"Consumer pipe name received '{consumerPipeNameRequest.PipeName}'"); + await _logger.LogDebugAsync($"Consumer pipe name received '{consumerPipeNameRequest.PipeName}'").ConfigureAwait(false); _namedPipeClient = new NamedPipeClient(consumerPipeNameRequest.PipeName); _namedPipeClient.RegisterSerializer(new GetInProgressTestsResponseSerializer(), typeof(GetInProgressTestsResponse)); _namedPipeClient.RegisterSerializer(new GetInProgressTestsRequestSerializer(), typeof(GetInProgressTestsRequest)); @@ -181,14 +181,14 @@ public async Task OnTestHostProcessStartedAsync(ITestHostProcessInformation test { _testHostProcessInformation = testHostProcessInformation; - await _logger.LogDebugAsync($"Wait for test host connection to the server pipe '{_singleConnectionNamedPipeServer.PipeName.Name}'"); - await _waitConnectionTask.TimeoutAfterAsync(TimeoutHelper.DefaultHangTimeSpanTimeout); + await _logger.LogDebugAsync($"Wait for test host connection to the server pipe '{_singleConnectionNamedPipeServer.PipeName.Name}'").ConfigureAwait(false); + await _waitConnectionTask.TimeoutAfterAsync(TimeoutHelper.DefaultHangTimeSpanTimeout).ConfigureAwait(false); using CancellationTokenSource timeout = new(TimeoutHelper.DefaultHangTimeSpanTimeout); using var linkedCancellationToken = CancellationTokenSource.CreateLinkedTokenSource(cancellation, timeout.Token); _waitConsumerPipeName.Wait(linkedCancellationToken.Token); ApplicationStateGuard.Ensure(_namedPipeClient is not null); - await _namedPipeClient.ConnectAsync(cancellation).TimeoutAfterAsync(TimeoutHelper.DefaultHangTimeSpanTimeout); - await _logger.LogDebugAsync($"Connected to the test host server pipe '{_namedPipeClient.PipeName}'"); + await _namedPipeClient.ConnectAsync(cancellation).TimeoutAfterAsync(TimeoutHelper.DefaultHangTimeSpanTimeout).ConfigureAwait(false); + await _logger.LogDebugAsync($"Connected to the test host server pipe '{_namedPipeClient.PipeName}'").ConfigureAwait(false); // Keep the custom thread to avoid to waste one from thread pool. _activityIndicatorTask = _task.RunLongRunning( @@ -196,11 +196,11 @@ public async Task OnTestHostProcessStartedAsync(ITestHostProcessInformation test { try { - await ActivityTimerAsync(); + await ActivityTimerAsync().ConfigureAwait(false); } catch (Exception e) { - await _outputDisplay.DisplayAsync(this, new ErrorMessageOutputDeviceData(string.Format(CultureInfo.InvariantCulture, ExtensionResources.HangDumpFailed, e.ToString(), GetDiskInfo()))); + await _outputDisplay.DisplayAsync(this, new ErrorMessageOutputDeviceData(string.Format(CultureInfo.InvariantCulture, ExtensionResources.HangDumpFailed, e.ToString(), GetDiskInfo()))).ConfigureAwait(false); throw; } }, "[HangDump] ActivityTimerAsync", cancellation); @@ -244,7 +244,7 @@ public async Task OnTestHostProcessExitedAsync(ITestHostProcessInformation testH if (!RoslynString.IsNullOrEmpty(_dumpFileTaken)) { - await _messageBus.PublishAsync(this, new FileArtifact(new FileInfo(_dumpFileTaken), ExtensionResources.HangDumpArtifactDisplayName, ExtensionResources.HangDumpArtifactDescription)); + await _messageBus.PublishAsync(this, new FileArtifact(new FileInfo(_dumpFileTaken), ExtensionResources.HangDumpArtifactDisplayName, ExtensionResources.HangDumpArtifactDescription)).ConfigureAwait(false); } } @@ -340,7 +340,7 @@ private async Task ActivityTimerAsync() if (timeoutFired) { - await TakeDumpAsync(); + await TakeDumpAsync().ConfigureAwait(false); } } @@ -349,35 +349,35 @@ private async Task TakeDumpAsync() ApplicationStateGuard.Ensure(_testHostProcessInformation is not null); ApplicationStateGuard.Ensure(_dumpType is not null); - await _logger.LogInformationAsync($"Hang dump timeout({_activityTimerValue}) expired."); - await _outputDisplay.DisplayAsync(this, new ErrorMessageOutputDeviceData(string.Format(CultureInfo.InvariantCulture, ExtensionResources.HangDumpTimeoutExpired, _activityTimerValue))); + await _logger.LogInformationAsync($"Hang dump timeout({_activityTimerValue}) expired.").ConfigureAwait(false); + await _outputDisplay.DisplayAsync(this, new ErrorMessageOutputDeviceData(string.Format(CultureInfo.InvariantCulture, ExtensionResources.HangDumpTimeoutExpired, _activityTimerValue))).ConfigureAwait(false); string finalDumpFileName = _dumpFileNamePattern.Replace("%p", _testHostProcessInformation.PID.ToString(CultureInfo.InvariantCulture)); finalDumpFileName = Path.Combine(_configuration.GetTestResultDirectory(), finalDumpFileName); ApplicationStateGuard.Ensure(_namedPipeClient is not null); - GetInProgressTestsResponse tests = await _namedPipeClient.RequestReplyAsync(new GetInProgressTestsRequest(), _testApplicationCancellationTokenSource.CancellationToken); - await _namedPipeClient.RequestReplyAsync(new ExitSignalActivityIndicatorTaskRequest(), _testApplicationCancellationTokenSource.CancellationToken); + GetInProgressTestsResponse tests = await _namedPipeClient.RequestReplyAsync(new GetInProgressTestsRequest(), _testApplicationCancellationTokenSource.CancellationToken).ConfigureAwait(false); + await _namedPipeClient.RequestReplyAsync(new ExitSignalActivityIndicatorTaskRequest(), _testApplicationCancellationTokenSource.CancellationToken).ConfigureAwait(false); if (tests.Tests.Length > 0) { string hangTestsFileName = Path.Combine(_configuration.GetTestResultDirectory(), Path.ChangeExtension(Path.GetFileName(finalDumpFileName), ".log")); using (FileStream fs = File.OpenWrite(hangTestsFileName)) using (StreamWriter sw = new(fs)) { - await _outputDisplay.DisplayAsync(this, new ErrorMessageOutputDeviceData(ExtensionResources.RunningTestsWhileDumping)); + await _outputDisplay.DisplayAsync(this, new ErrorMessageOutputDeviceData(ExtensionResources.RunningTestsWhileDumping)).ConfigureAwait(false); foreach ((string testName, int seconds) in tests.Tests) { - await sw.WriteLineAsync($"[{TimeSpan.FromSeconds(seconds)}] {testName}"); - await _outputDisplay.DisplayAsync(this, new ErrorMessageOutputDeviceData($"[{TimeSpan.FromSeconds(seconds)}] {testName}")); + await sw.WriteLineAsync($"[{TimeSpan.FromSeconds(seconds)}] {testName}").ConfigureAwait(false); + await _outputDisplay.DisplayAsync(this, new ErrorMessageOutputDeviceData($"[{TimeSpan.FromSeconds(seconds)}] {testName}")).ConfigureAwait(false); } } - await _messageBus.PublishAsync(this, new FileArtifact(new FileInfo(hangTestsFileName), ExtensionResources.HangTestListArtifactDisplayName, ExtensionResources.HangTestListArtifactDescription)); + await _messageBus.PublishAsync(this, new FileArtifact(new FileInfo(hangTestsFileName), ExtensionResources.HangTestListArtifactDisplayName, ExtensionResources.HangTestListArtifactDescription)).ConfigureAwait(false); } - await _logger.LogInformationAsync($"Creating dump filename {finalDumpFileName}"); + await _logger.LogInformationAsync($"Creating dump filename {finalDumpFileName}").ConfigureAwait(false); - await _outputDisplay.DisplayAsync(this, new ErrorMessageOutputDeviceData(string.Format(CultureInfo.InvariantCulture, ExtensionResources.CreatingDumpFile, finalDumpFileName))); + await _outputDisplay.DisplayAsync(this, new ErrorMessageOutputDeviceData(string.Format(CultureInfo.InvariantCulture, ExtensionResources.CreatingDumpFile, finalDumpFileName))).ConfigureAwait(false); try { @@ -419,7 +419,7 @@ private async Task TakeDumpAsync() NotifyCrashDumpServiceIfEnabled(); using IProcess process = _processHandler.GetProcessById(_testHostProcessInformation.PID); process.Kill(); - await process.WaitForExitAsync(); + await process.WaitForExitAsync().ConfigureAwait(false); } } @@ -448,7 +448,7 @@ public async ValueTask DisposeAsync() { if (_activityIndicatorTask is not null) { - await _activityIndicatorTask.TimeoutAfterAsync(TimeoutHelper.DefaultHangTimeSpanTimeout); + await _activityIndicatorTask.TimeoutAfterAsync(TimeoutHelper.DefaultHangTimeSpanTimeout).ConfigureAwait(false); } _namedPipeClient?.Dispose(); diff --git a/src/Platform/Microsoft.Testing.Extensions.HotReload/HotReloadHandler.cs b/src/Platform/Microsoft.Testing.Extensions.HotReload/HotReloadHandler.cs index 281048572a..812d925074 100644 --- a/src/Platform/Microsoft.Testing.Extensions.HotReload/HotReloadHandler.cs +++ b/src/Platform/Microsoft.Testing.Extensions.HotReload/HotReloadHandler.cs @@ -84,13 +84,13 @@ public async Task ShouldRunAsync(Task? waitExecutionCompletion, Cancellati if (waitExecutionCompletion is not null) { - await waitExecutionCompletion; - await _outputDevice!.DisplayAsync(_outputDeviceDataProducer, new TextOutputDeviceData(ExtensionResources.HotReloadSessionCompleted)); + await waitExecutionCompletion.ConfigureAwait(false); + await _outputDevice!.DisplayAsync(_outputDeviceDataProducer, new TextOutputDeviceData(ExtensionResources.HotReloadSessionCompleted)).ConfigureAwait(false); } try { - await SemaphoreSlim.WaitAsync(cancellationToken); + await SemaphoreSlim.WaitAsync(cancellationToken).ConfigureAwait(false); } catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) { @@ -102,7 +102,7 @@ public async Task ShouldRunAsync(Task? waitExecutionCompletion, Cancellati _console!.Clear(); } - await _outputDevice.DisplayAsync(_outputDeviceDataProducer, new TextOutputDeviceData(ExtensionResources.HotReloadSessionStarted)); + await _outputDevice.DisplayAsync(_outputDeviceDataProducer, new TextOutputDeviceData(ExtensionResources.HotReloadSessionStarted)).ConfigureAwait(false); return !s_shutdownProcess; } diff --git a/src/Platform/Microsoft.Testing.Extensions.HotReload/HotReloadTestHostTestFrameworkInvoker.cs b/src/Platform/Microsoft.Testing.Extensions.HotReload/HotReloadTestHostTestFrameworkInvoker.cs index df6c08a9d4..72278a0a33 100644 --- a/src/Platform/Microsoft.Testing.Extensions.HotReload/HotReloadTestHostTestFrameworkInvoker.cs +++ b/src/Platform/Microsoft.Testing.Extensions.HotReload/HotReloadTestHostTestFrameworkInvoker.cs @@ -33,7 +33,7 @@ public override async Task ExecuteRequestAsync(ITestFramework testFrameworkAdapt { if (!_isHotReloadEnabled) { - await base.ExecuteRequestAsync(testFrameworkAdapter, request, messageBus, cancellationToken); + await base.ExecuteRequestAsync(testFrameworkAdapter, request, messageBus, cancellationToken).ConfigureAwait(false); return; } @@ -41,25 +41,25 @@ public override async Task ExecuteRequestAsync(ITestFramework testFrameworkAdapt IOutputDevice outputDevice = ServiceProvider.GetOutputDevice(); var hotReloadHandler = new HotReloadHandler(ServiceProvider.GetConsole(), outputDevice, this); TaskCompletionSource? executionCompleted = null; - while (await hotReloadHandler.ShouldRunAsync(executionCompleted?.Task, ServiceProvider.GetTestApplicationCancellationTokenSource().CancellationToken)) + while (await hotReloadHandler.ShouldRunAsync(executionCompleted?.Task, ServiceProvider.GetTestApplicationCancellationTokenSource().CancellationToken).ConfigureAwait(false)) { executionCompleted = new(); using SemaphoreSlim requestSemaphore = new(1); var hotReloadOutputDevice = ServiceProvider.GetPlatformOutputDevice() as IHotReloadPlatformOutputDevice; if (hotReloadOutputDevice is not null) { - await hotReloadOutputDevice.DisplayBeforeHotReloadSessionStartAsync(); + await hotReloadOutputDevice.DisplayBeforeHotReloadSessionStartAsync().ConfigureAwait(false); } #pragma warning disable TPEXP // Type is for evaluation purposes only and is subject to change or removal in future updates. Suppress this diagnostic to proceed. - await testFrameworkAdapter.ExecuteRequestAsync(new(request, messageBus, new SemaphoreSlimRequestCompleteNotifier(requestSemaphore), cancellationToken)); + await testFrameworkAdapter.ExecuteRequestAsync(new(request, messageBus, new SemaphoreSlimRequestCompleteNotifier(requestSemaphore), cancellationToken)).ConfigureAwait(false); #pragma warning restore TPEXP // Type is for evaluation purposes only and is subject to change or removal in future updates. Suppress this diagnostic to proceed. - await requestSemaphore.WaitAsync(cancellationToken); - await ServiceProvider.GetBaseMessageBus().DrainDataAsync(); + await requestSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false); + await ServiceProvider.GetBaseMessageBus().DrainDataAsync().ConfigureAwait(false); if (hotReloadOutputDevice is not null) { - await hotReloadOutputDevice.DisplayAfterHotReloadSessionEndAsync(); + await hotReloadOutputDevice.DisplayAfterHotReloadSessionEndAsync().ConfigureAwait(false); } executionCompleted.SetResult(0); diff --git a/src/Platform/Microsoft.Testing.Extensions.MSBuild/MSBuildConsumer.cs b/src/Platform/Microsoft.Testing.Extensions.MSBuild/MSBuildConsumer.cs index 124be7cbb5..9ce87925d1 100644 --- a/src/Platform/Microsoft.Testing.Extensions.MSBuild/MSBuildConsumer.cs +++ b/src/Platform/Microsoft.Testing.Extensions.MSBuild/MSBuildConsumer.cs @@ -94,7 +94,7 @@ await HandleFailuresAsync( actual: null, testFileLocationProperty?.FilePath, testFileLocationProperty?.LineSpan.Start.Line ?? 0, - cancellationToken); + cancellationToken).ConfigureAwait(false); break; case FailedTestNodeStateProperty failedState: @@ -108,7 +108,7 @@ await HandleFailuresAsync( actual: failedState.Exception?.Data["assert.actual"] as string, testFileLocationProperty?.FilePath, testFileLocationProperty?.LineSpan.Start.Line ?? 0, - cancellationToken); + cancellationToken).ConfigureAwait(false); break; case TimeoutTestNodeStateProperty timeoutState: @@ -122,7 +122,7 @@ await HandleFailuresAsync( actual: null, testFileLocationProperty?.FilePath, testFileLocationProperty?.LineSpan.Start.Line ?? 0, - cancellationToken); + cancellationToken).ConfigureAwait(false); break; case CancelledTestNodeStateProperty canceledState: @@ -136,7 +136,7 @@ await HandleFailuresAsync( actual: null, testFileLocationProperty?.FilePath, testFileLocationProperty?.LineSpan.Start.Line ?? 0, - cancellationToken); + cancellationToken).ConfigureAwait(false); break; case PassedTestNodeStateProperty: @@ -153,7 +153,7 @@ await HandleFailuresAsync( break; case TestRequestExecutionTimeInfo testRequestExecutionTimeInfo: - await HandleSummaryAsync(testRequestExecutionTimeInfo, cancellationToken); + await HandleSummaryAsync(testRequestExecutionTimeInfo, cancellationToken).ConfigureAwait(false); break; } @@ -166,7 +166,7 @@ private async Task HandleFailuresAsync(string testDisplayName, bool isCanceled, ApplicationStateGuard.Ensure(_msBuildTestApplicationLifecycleCallbacks != null); ApplicationStateGuard.Ensure(_msBuildTestApplicationLifecycleCallbacks.PipeClient != null); var failedTestInfoRequest = new FailedTestInfoRequest(testDisplayName, isCanceled, duration, errorMessage, errorStackTrace, expected, actual, codeFilePath, lineNumber); - await _msBuildTestApplicationLifecycleCallbacks.PipeClient.RequestReplyAsync(failedTestInfoRequest, cancellationToken); + await _msBuildTestApplicationLifecycleCallbacks.PipeClient.RequestReplyAsync(failedTestInfoRequest, cancellationToken).ConfigureAwait(false); } private async Task HandleSummaryAsync(TestRequestExecutionTimeInfo timeInfo, CancellationToken cancellationToken) @@ -176,7 +176,7 @@ private async Task HandleSummaryAsync(TestRequestExecutionTimeInfo timeInfo, Can ApplicationStateGuard.Ensure(_msBuildTestApplicationLifecycleCallbacks != null); ApplicationStateGuard.Ensure(_msBuildTestApplicationLifecycleCallbacks.PipeClient != null); var runSummaryInfoRequest = new RunSummaryInfoRequest(_totalTests, _totalFailedTests, _totalPassedTests, _totalSkippedTests, duration); - await _msBuildTestApplicationLifecycleCallbacks.PipeClient.RequestReplyAsync(runSummaryInfoRequest, cancellationToken); + await _msBuildTestApplicationLifecycleCallbacks.PipeClient.RequestReplyAsync(runSummaryInfoRequest, cancellationToken).ConfigureAwait(false); } private static string? ToHumanReadableDuration(double? durationInMs) diff --git a/src/Platform/Microsoft.Testing.Extensions.MSBuild/MSBuildTestApplicationLifecycleCallbacks.cs b/src/Platform/Microsoft.Testing.Extensions.MSBuild/MSBuildTestApplicationLifecycleCallbacks.cs index 7e830ab2b7..411274ac3c 100644 --- a/src/Platform/Microsoft.Testing.Extensions.MSBuild/MSBuildTestApplicationLifecycleCallbacks.cs +++ b/src/Platform/Microsoft.Testing.Extensions.MSBuild/MSBuildTestApplicationLifecycleCallbacks.cs @@ -61,13 +61,13 @@ public async Task BeforeRunAsync(CancellationToken cancellationToken) PipeClient.RegisterSerializer(new RunSummaryInfoRequestSerializer(), typeof(RunSummaryInfoRequest)); using var cancellationTokenSource = new CancellationTokenSource(TimeoutHelper.DefaultHangTimeSpanTimeout); using var linkedCancellationToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationTokenSource.Token, _testApplicationCancellationTokenSource.CancellationToken); - await PipeClient.ConnectAsync(linkedCancellationToken.Token); + await PipeClient.ConnectAsync(linkedCancellationToken.Token).ConfigureAwait(false); await PipeClient.RequestReplyAsync( new ModuleInfoRequest( RuntimeInformation.FrameworkDescription, RuntimeInformation.ProcessArchitecture.ToString().ToLowerInvariant(), _configuration.GetTestResultDirectory()), - _testApplicationCancellationTokenSource.CancellationToken); + _testApplicationCancellationTokenSource.CancellationToken).ConfigureAwait(false); } public void Dispose() diff --git a/src/Platform/Microsoft.Testing.Extensions.Retry/RetryDataConsumer.cs b/src/Platform/Microsoft.Testing.Extensions.Retry/RetryDataConsumer.cs index d81ebe0fb0..2c1b46b798 100644 --- a/src/Platform/Microsoft.Testing.Extensions.Retry/RetryDataConsumer.cs +++ b/src/Platform/Microsoft.Testing.Extensions.Retry/RetryDataConsumer.cs @@ -51,7 +51,7 @@ public async Task ConsumeAsync(IDataProducer dataProducer, IData value, Cancella { ApplicationStateGuard.Ensure(_retryFailedTestsLifecycleCallbacks is not null); ApplicationStateGuard.Ensure(_retryFailedTestsLifecycleCallbacks.Client is not null); - await _retryFailedTestsLifecycleCallbacks.Client.RequestReplyAsync(new FailedTestRequest(testNodeUpdateMessage.TestNode.Uid), cancellationToken); + await _retryFailedTestsLifecycleCallbacks.Client.RequestReplyAsync(new FailedTestRequest(testNodeUpdateMessage.TestNode.Uid), cancellationToken).ConfigureAwait(false); } if (Array.IndexOf(TestNodePropertiesCategories.WellKnownTestNodeTestRunOutcomeProperties, nodeState.GetType()) != -1) @@ -64,7 +64,7 @@ public async Task OnTestSessionFinishingAsync(SessionUid sessionUid, Cancellatio { ApplicationStateGuard.Ensure(_retryFailedTestsLifecycleCallbacks is not null); ApplicationStateGuard.Ensure(_retryFailedTestsLifecycleCallbacks.Client is not null); - await _retryFailedTestsLifecycleCallbacks.Client.RequestReplyAsync(new TotalTestsRunRequest(_totalTests), cancellationToken); + await _retryFailedTestsLifecycleCallbacks.Client.RequestReplyAsync(new TotalTestsRunRequest(_totalTests), cancellationToken).ConfigureAwait(false); } public Task OnTestSessionStartingAsync(SessionUid sessionUid, CancellationToken cancellationToken) @@ -76,7 +76,7 @@ public Task IsEnabledAsync() public async Task InitializeAsync() { - if (await IsEnabledAsync()) + if (await IsEnabledAsync().ConfigureAwait(false)) { _retryFailedTestsLifecycleCallbacks = _serviceProvider.GetRequiredService(); } diff --git a/src/Platform/Microsoft.Testing.Extensions.Retry/RetryExecutionFilterFactory.cs b/src/Platform/Microsoft.Testing.Extensions.Retry/RetryExecutionFilterFactory.cs index 0c28e544c0..c2b9b8c13a 100644 --- a/src/Platform/Microsoft.Testing.Extensions.Retry/RetryExecutionFilterFactory.cs +++ b/src/Platform/Microsoft.Testing.Extensions.Retry/RetryExecutionFilterFactory.cs @@ -43,7 +43,7 @@ public Task IsEnabledAsync() else { ConsoleTestExecutionFilterFactory consoleTestExecutionFilterFactory = new(_commandLineOptions); - return await consoleTestExecutionFilterFactory.TryCreateAsync(); + return await consoleTestExecutionFilterFactory.TryCreateAsync().ConfigureAwait(false); } } } diff --git a/src/Platform/Microsoft.Testing.Extensions.Retry/RetryLifecycleCallbacks.cs b/src/Platform/Microsoft.Testing.Extensions.Retry/RetryLifecycleCallbacks.cs index 6d019d9fd1..5bfdd7d039 100644 --- a/src/Platform/Microsoft.Testing.Extensions.Retry/RetryLifecycleCallbacks.cs +++ b/src/Platform/Microsoft.Testing.Extensions.Retry/RetryLifecycleCallbacks.cs @@ -63,9 +63,9 @@ public async Task BeforeRunAsync(CancellationToken cancellationToken) Client.RegisterSerializer(new GetListOfFailedTestsRequestSerializer(), typeof(GetListOfFailedTestsRequest)); Client.RegisterSerializer(new GetListOfFailedTestsResponseSerializer(), typeof(GetListOfFailedTestsResponse)); Client.RegisterSerializer(new TotalTestsRunRequestSerializer(), typeof(TotalTestsRunRequest)); - await Client.ConnectAsync(cancellationToken); + await Client.ConnectAsync(cancellationToken).ConfigureAwait(false); - GetListOfFailedTestsResponse result = await Client.RequestReplyAsync(new GetListOfFailedTestsRequest(), cancellationToken); + GetListOfFailedTestsResponse result = await Client.RequestReplyAsync(new GetListOfFailedTestsRequest(), cancellationToken).ConfigureAwait(false); FailedTestsIDToRetry = result.FailedTestIds; } @@ -80,7 +80,7 @@ public async ValueTask DisposeAsync() { if (Client is not null) { - await Client.DisposeAsync(); + await Client.DisposeAsync().ConfigureAwait(false); } } #else diff --git a/src/Platform/Microsoft.Testing.Extensions.Retry/RetryOrchestrator.cs b/src/Platform/Microsoft.Testing.Extensions.Retry/RetryOrchestrator.cs index 03cabcb6d7..fec544be04 100644 --- a/src/Platform/Microsoft.Testing.Extensions.Retry/RetryOrchestrator.cs +++ b/src/Platform/Microsoft.Testing.Extensions.Retry/RetryOrchestrator.cs @@ -182,7 +182,7 @@ public async Task OrchestrateTestHostExecutionAsync() #endif } - await logger.LogDebugAsync($"Starting test host process, attempt {attemptCount}/{userMaxRetryCount}"); + await logger.LogDebugAsync($"Starting test host process, attempt {attemptCount}/{userMaxRetryCount}").ConfigureAwait(false); IProcess testHostProcess = _serviceProvider.GetProcessHandler().Start(processStartInfo) ?? throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, ExtensionResources.RetryFailedTestsCannotStartProcessErrorMessage, processStartInfo.FileName)); @@ -198,39 +198,39 @@ public async Task OrchestrateTestHostExecutionAsync() using (var linkedToken = CancellationTokenSource.CreateLinkedTokenSource(timeout.Token, _serviceProvider.GetTestApplicationCancellationTokenSource().CancellationToken)) using (var linkedToken2 = CancellationTokenSource.CreateLinkedTokenSource(linkedToken.Token, processExitedCancellationToken.Token)) { - await logger.LogDebugAsync("Wait connection from the test host process"); + await logger.LogDebugAsync("Wait connection from the test host process").ConfigureAwait(false); try { #if NETCOREAPP - await retryFailedTestsPipeServer.WaitForConnectionAsync(linkedToken2.Token); + await retryFailedTestsPipeServer.WaitForConnectionAsync(linkedToken2.Token).ConfigureAwait(false); #else // We don't know why but if the cancellation is called quickly in line 171 for netfx we stuck sometime here, like if // the token we pass to the named pipe is not "correctly" verified inside the pipe implementation self. // We fallback with our custom agnostic cancellation mechanism in that case. // We see it happen only in .NET FX and not in .NET Core so for now we don't do it for core. - await retryFailedTestsPipeServer.WaitForConnectionAsync(linkedToken2.Token).WithCancellationAsync(linkedToken2.Token); + await retryFailedTestsPipeServer.WaitForConnectionAsync(linkedToken2.Token).WithCancellationAsync(linkedToken2.Token).ConfigureAwait(false); #endif } catch (OperationCanceledException) when (processExitedCancellationToken.IsCancellationRequested) { - await outputDevice.DisplayAsync(this, new ErrorMessageOutputDeviceData(string.Format(CultureInfo.InvariantCulture, ExtensionResources.TestHostProcessExitedBeforeRetryCouldConnect, testHostProcess.ExitCode))); + await outputDevice.DisplayAsync(this, new ErrorMessageOutputDeviceData(string.Format(CultureInfo.InvariantCulture, ExtensionResources.TestHostProcessExitedBeforeRetryCouldConnect, testHostProcess.ExitCode))).ConfigureAwait(false); return ExitCodes.GenericFailure; } } - await testHostProcess.WaitForExitAsync(); + await testHostProcess.WaitForExitAsync().ConfigureAwait(false); exitCodes.Add(testHostProcess.ExitCode); if (testHostProcess.ExitCode != ExitCodes.Success) { if (testHostProcess.ExitCode != ExitCodes.AtLeastOneTestFailed) { - await outputDevice.DisplayAsync(this, new WarningMessageOutputDeviceData(string.Format(CultureInfo.InvariantCulture, ExtensionResources.TestSuiteFailedWithWrongExitCode, testHostProcess.ExitCode))); + await outputDevice.DisplayAsync(this, new WarningMessageOutputDeviceData(string.Format(CultureInfo.InvariantCulture, ExtensionResources.TestSuiteFailedWithWrongExitCode, testHostProcess.ExitCode))).ConfigureAwait(false); retryInterrupted = true; break; } - await outputDevice.DisplayAsync(this, new WarningMessageOutputDeviceData(string.Format(CultureInfo.InvariantCulture, ExtensionResources.TestSuiteFailed, retryFailedTestsPipeServer.FailedUID?.Count ?? 0, testHostProcess.ExitCode, attemptCount, userMaxRetryCount + 1))); + await outputDevice.DisplayAsync(this, new WarningMessageOutputDeviceData(string.Format(CultureInfo.InvariantCulture, ExtensionResources.TestSuiteFailed, retryFailedTestsPipeServer.FailedUID?.Count ?? 0, testHostProcess.ExitCode, attemptCount, userMaxRetryCount + 1))).ConfigureAwait(false); // Check thresholds if (attemptCount == 1) @@ -269,7 +269,7 @@ public async Task OrchestrateTestHostExecutionAsync() explanation.AppendLine(string.Format(CultureInfo.InvariantCulture, ExtensionResources.FailureThresholdPolicyMaxCount, maxCount, retryFailedTestsPipeServer.FailedUID!.Count)); } - await outputDevice.DisplayAsync(this, new ErrorMessageOutputDeviceData(explanation.ToString())); + await outputDevice.DisplayAsync(this, new ErrorMessageOutputDeviceData(explanation.ToString())).ConfigureAwait(false); break; } } @@ -288,11 +288,11 @@ public async Task OrchestrateTestHostExecutionAsync() { if (exitCodes[^1] != ExitCodes.Success) { - await outputDevice.DisplayAsync(this, new ErrorMessageOutputDeviceData(string.Format(CultureInfo.InvariantCulture, ExtensionResources.TestSuiteFailedInAllAttempts, userMaxRetryCount + 1))); + await outputDevice.DisplayAsync(this, new ErrorMessageOutputDeviceData(string.Format(CultureInfo.InvariantCulture, ExtensionResources.TestSuiteFailedInAllAttempts, userMaxRetryCount + 1))).ConfigureAwait(false); } else { - await outputDevice.DisplayAsync(this, new FormattedTextOutputDeviceData(string.Format(CultureInfo.InvariantCulture, ExtensionResources.TestSuiteCompletedSuccessfully, attemptCount)) { ForegroundColor = new SystemConsoleColor { ConsoleColor = ConsoleColor.DarkGreen } }); + await outputDevice.DisplayAsync(this, new FormattedTextOutputDeviceData(string.Format(CultureInfo.InvariantCulture, ExtensionResources.TestSuiteCompletedSuccessfully, attemptCount)) { ForegroundColor = new SystemConsoleColor { ConsoleColor = ConsoleColor.DarkGreen } }).ConfigureAwait(false); } } @@ -301,7 +301,7 @@ public async Task OrchestrateTestHostExecutionAsync() string[] filesToMove = Directory.GetFiles(currentTryResultFolder, "*.*", SearchOption.AllDirectories); if (filesToMove.Length > 0) { - await outputDevice.DisplayAsync(this, new TextOutputDeviceData(ExtensionResources.MoveFiles)); + await outputDevice.DisplayAsync(this, new TextOutputDeviceData(ExtensionResources.MoveFiles)).ConfigureAwait(false); // Move last attempt assets foreach (string file in filesToMove) @@ -311,7 +311,7 @@ public async Task OrchestrateTestHostExecutionAsync() // Create the directory if missing Directory.CreateDirectory(Path.GetDirectoryName(finalFileLocation)!); - await outputDevice.DisplayAsync(this, new TextOutputDeviceData(string.Format(CultureInfo.InvariantCulture, ExtensionResources.MovingFileToLocation, file, finalFileLocation))); + await outputDevice.DisplayAsync(this, new TextOutputDeviceData(string.Format(CultureInfo.InvariantCulture, ExtensionResources.MovingFileToLocation, file, finalFileLocation))).ConfigureAwait(false); #if NETCOREAPP File.Move(file, finalFileLocation, overwrite: true); #else diff --git a/src/Platform/Microsoft.Testing.Extensions.Telemetry/AppInsightsProvider.cs b/src/Platform/Microsoft.Testing.Extensions.Telemetry/AppInsightsProvider.cs index 3eb596cfa9..fd9926502d 100644 --- a/src/Platform/Microsoft.Testing.Extensions.Telemetry/AppInsightsProvider.cs +++ b/src/Platform/Microsoft.Testing.Extensions.Telemetry/AppInsightsProvider.cs @@ -131,7 +131,7 @@ private async Task IngestLoopAsync() { _client = null; - await _logger.LogErrorAsync("Failed to initialize telemetry client", e); + await _logger.LogErrorAsync("Failed to initialize telemetry client", e).ConfigureAwait(false); return; } @@ -140,9 +140,9 @@ private async Task IngestLoopAsync() try { #if NETCOREAPP - while (await _payloads.Reader.WaitToReadAsync(_flushTimeoutOrStop.Token)) + while (await _payloads.Reader.WaitToReadAsync(_flushTimeoutOrStop.Token).ConfigureAwait(false)) { - (string eventName, IDictionary paramsMap) = await _payloads.Reader.ReadAsync(); + (string eventName, IDictionary paramsMap) = await _payloads.Reader.ReadAsync().ConfigureAwait(false); #else foreach ((string eventName, IDictionary paramsMap) in _payloads.GetConsumingEnumerable(_flushTimeoutOrStop.Token)) { @@ -205,7 +205,7 @@ private async Task IngestLoopAsync() builder.AppendLine(CultureInfo.InvariantCulture, $" {key}: {value.ToString("f", CultureInfo.InvariantCulture)}"); } - await _logger.LogTraceAsync(builder.ToString()); + await _logger.LogTraceAsync(builder.ToString()).ConfigureAwait(false); } try @@ -219,7 +219,7 @@ private async Task IngestLoopAsync() // We could do better back-pressure. if (_logger.IsEnabled(LogLevel.Error) && (!lastLoggedError.HasValue || (lastLoggedError.Value - _clock.UtcNow).TotalSeconds > 3)) { - await _logger.LogErrorAsync("Error during telemetry report.", ex); + await _logger.LogErrorAsync("Error during telemetry report.", ex).ConfigureAwait(false); lastLoggedError = _clock.UtcNow; } } @@ -275,7 +275,7 @@ private static Regex GetValidHashPattern() Task LogEventAsync(string eventName, IDictionary paramsMap) { #if NETCOREAPP - await _payloads.Writer.WriteAsync((eventName, paramsMap)); + await _payloads.Writer.WriteAsync((eventName, paramsMap)).ConfigureAwait(false); #else _payloads.Add((eventName, paramsMap)); return Task.CompletedTask; @@ -320,12 +320,12 @@ public async ValueTask DisposeAsync() int flushForSeconds = 3; try { - await _telemetryTask.TimeoutAfterAsync(TimeSpan.FromSeconds(flushForSeconds)); + await _telemetryTask.TimeoutAfterAsync(TimeSpan.FromSeconds(flushForSeconds)).ConfigureAwait(false); } catch (TimeoutException) { - await _flushTimeoutOrStop.CancelAsync(); - await _logger.LogWarningAsync($"Telemetry task didn't flush after '{flushForSeconds}', some payload could be lost"); + await _flushTimeoutOrStop.CancelAsync().ConfigureAwait(false); + await _logger.LogWarningAsync($"Telemetry task didn't flush after '{flushForSeconds}', some payload could be lost").ConfigureAwait(false); } _isDisposed = true; diff --git a/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxCompareTool.cs b/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxCompareTool.cs index 2373e481b5..17a95a5ea6 100644 --- a/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxCompareTool.cs +++ b/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxCompareTool.cs @@ -61,7 +61,7 @@ public async Task RunAsync() List comparedIssues = []; await _task.WhenAll( _task.Run(() => CollectEntriesAndErrors(baselineFilePaths[0], trxNamespace, baseLineResults, baseLineIssues)), - _task.Run(() => CollectEntriesAndErrors(comparedFilePaths[0], trxNamespace, comparedResults, comparedIssues))); + _task.Run(() => CollectEntriesAndErrors(comparedFilePaths[0], trxNamespace, comparedResults, comparedIssues))).ConfigureAwait(false); StringBuilder outputBuilder = new(); AppendResultsAndIssues("Baseline", baselineFilePaths[0], baseLineResults, baseLineIssues, outputBuilder); @@ -69,12 +69,12 @@ await _task.WhenAll( if (AreMatchingTrxFiles(baseLineResults, comparedResults, outputBuilder)) { - await _outputDisplay.DisplayAsync(this, new TextOutputDeviceData(outputBuilder.ToString())); + await _outputDisplay.DisplayAsync(this, new TextOutputDeviceData(outputBuilder.ToString())).ConfigureAwait(false); return ExitCodes.Success; } else { - await _outputDisplay.DisplayAsync(this, new TextOutputDeviceData(outputBuilder.ToString())); + await _outputDisplay.DisplayAsync(this, new TextOutputDeviceData(outputBuilder.ToString())).ConfigureAwait(false); return ExitCodes.GenericFailure; } } diff --git a/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxDataConsumer.cs b/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxDataConsumer.cs index 6157ecc217..5b146fe3c7 100644 --- a/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxDataConsumer.cs +++ b/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxDataConsumer.cs @@ -179,7 +179,7 @@ await _logger.LogDebugAsync($""" PlatformCommandLineProvider.ServerOption: {_commandLineOptionsService.IsOptionSet(PlatformCommandLineProvider.ServerOptionKey)} CrashDumpCommandLineOptions.CrashDumpOptionName: {_commandLineOptionsService.IsOptionSet(CrashDumpCommandLineOptions.CrashDumpOptionName)} TrxReportGeneratorCommandLine.IsTrxReportEnabled: {_commandLineOptionsService.IsOptionSet(TrxReportGeneratorCommandLine.TrxReportOptionName)} -"""); +""").ConfigureAwait(false); } if (!_commandLineOptionsService.IsOptionSet(PlatformCommandLineProvider.ServerOptionKey) && @@ -191,7 +191,7 @@ await _logger.LogDebugAsync($""" try { await _trxTestApplicationLifecycleCallbacks.NamedPipeClient.RequestReplyAsync(new TestAdapterInformationRequest(_testFramework.Uid, _testFramework.Version), cancellationToken) - .TimeoutAfterAsync(TimeoutHelper.DefaultHangTimeSpanTimeout, cancellationToken); + .TimeoutAfterAsync(TimeoutHelper.DefaultHangTimeSpanTimeout, cancellationToken).ConfigureAwait(false); } catch (OperationCanceledException ex) when (ex.CancellationToken == cancellationToken) { @@ -220,7 +220,7 @@ public async Task OnTestSessionFinishingAsync(SessionUid sessionUid, Cancellatio { if (!_adapterSupportTrxCapability) { - await _outputDisplay.DisplayAsync(this, new WarningMessageOutputDeviceData(string.Format(CultureInfo.InvariantCulture, ExtensionResources.TrxReportFrameworkDoesNotSupportTrxReportCapability, _testFramework.DisplayName, _testFramework.Uid))); + await _outputDisplay.DisplayAsync(this, new WarningMessageOutputDeviceData(string.Format(CultureInfo.InvariantCulture, ExtensionResources.TrxReportFrameworkDoesNotSupportTrxReportCapability, _testFramework.DisplayName, _testFramework.Uid))).ConfigureAwait(false); } ApplicationStateGuard.Ensure(_testStartTime is not null); @@ -229,10 +229,10 @@ public async Task OnTestSessionFinishingAsync(SessionUid sessionUid, Cancellatio TrxReportEngine trxReportGeneratorEngine = new(_testApplicationModuleInfo, _environment, _commandLineOptionsService, _configuration, _clock, [.. _tests], _failedTestsCount, _passedTestsCount, _notExecutedTestsCount, _timeoutTestsCount, _artifactsByExtension, _adapterSupportTrxCapability, _testFramework, _testStartTime.Value, exitCode, cancellationToken); - (string reportFileName, string? warning) = await trxReportGeneratorEngine.GenerateReportAsync(); + (string reportFileName, string? warning) = await trxReportGeneratorEngine.GenerateReportAsync().ConfigureAwait(false); if (warning is not null) { - await _outputDisplay.DisplayAsync(this, new WarningMessageOutputDeviceData(warning)); + await _outputDisplay.DisplayAsync(this, new WarningMessageOutputDeviceData(warning)).ConfigureAwait(false); } if ( @@ -242,13 +242,13 @@ public async Task OnTestSessionFinishingAsync(SessionUid sessionUid, Cancellatio !_commandLineOptionsService.IsOptionSet(CrashDumpCommandLineOptions.CrashDumpOptionName)) { // In server mode we report the trx in-process - await _messageBus.PublishAsync(this, new SessionFileArtifact(sessionUid, new FileInfo(reportFileName), ExtensionResources.TrxReportArtifactDisplayName, ExtensionResources.TrxReportArtifactDescription)); + await _messageBus.PublishAsync(this, new SessionFileArtifact(sessionUid, new FileInfo(reportFileName), ExtensionResources.TrxReportArtifactDisplayName, ExtensionResources.TrxReportArtifactDescription)).ConfigureAwait(false); } else { ApplicationStateGuard.Ensure(_trxTestApplicationLifecycleCallbacks is not null); ApplicationStateGuard.Ensure(_trxTestApplicationLifecycleCallbacks.NamedPipeClient is not null); - await _trxTestApplicationLifecycleCallbacks.NamedPipeClient.RequestReplyAsync(new ReportFileNameRequest(reportFileName), cancellationToken); + await _trxTestApplicationLifecycleCallbacks.NamedPipeClient.RequestReplyAsync(new ReportFileNameRequest(reportFileName), cancellationToken).ConfigureAwait(false); } } catch (OperationCanceledException ex) when (ex.CancellationToken == cancellationToken) diff --git a/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxProcessLifetimeHandler.cs b/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxProcessLifetimeHandler.cs index 9277a8b3ef..6242fd4664 100644 --- a/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxProcessLifetimeHandler.cs +++ b/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxProcessLifetimeHandler.cs @@ -109,7 +109,7 @@ public Task BeforeTestHostProcessStartAsync(CancellationToken cancellation) _singleConnectionNamedPipeServer.RegisterSerializer(new ReportFileNameRequestSerializer(), typeof(ReportFileNameRequest)); _singleConnectionNamedPipeServer.RegisterSerializer(new TestAdapterInformationRequestSerializer(), typeof(TestAdapterInformationRequest)); _singleConnectionNamedPipeServer.RegisterSerializer(new VoidResponseSerializer(), typeof(VoidResponse)); - await _singleConnectionNamedPipeServer.WaitConnectionAsync(cancellation).TimeoutAfterAsync(TimeoutHelper.DefaultHangTimeSpanTimeout, cancellation); + await _singleConnectionNamedPipeServer.WaitConnectionAsync(cancellation).TimeoutAfterAsync(TimeoutHelper.DefaultHangTimeSpanTimeout, cancellation).ConfigureAwait(false); }, cancellation); return Task.CompletedTask; @@ -122,7 +122,7 @@ public async Task OnTestHostProcessStartedAsync(ITestHostProcessInformation test throw new InvalidOperationException(ExtensionResources.TrxReportGeneratorBeforeTestHostProcessStartAsyncNotCalled); } - await _waitConnectionTask.TimeoutAfterAsync(TimeoutHelper.DefaultHangTimeSpanTimeout, cancellation); + await _waitConnectionTask.TimeoutAfterAsync(TimeoutHelper.DefaultHangTimeSpanTimeout, cancellation).ConfigureAwait(false); } public Task ConsumeAsync(IDataProducer dataProducer, IData value, CancellationToken cancellationToken) @@ -172,10 +172,10 @@ public async Task OnTestHostProcessExitedAsync(ITestHostProcessInformation testH (string fileName, string? warning) = await trxReportGeneratorEngine.GenerateReportAsync( isTestHostCrashed: true, - testHostCrashInfo: $"Test host process pid: {testHostProcessInformation.PID} crashed."); + testHostCrashInfo: $"Test host process pid: {testHostProcessInformation.PID} crashed.").ConfigureAwait(false); if (warning is not null) { - await _outputDevice.DisplayAsync(this, new WarningMessageOutputDeviceData(warning)); + await _outputDevice.DisplayAsync(this, new WarningMessageOutputDeviceData(warning)).ConfigureAwait(false); } await _messageBus.PublishAsync( @@ -183,7 +183,7 @@ await _messageBus.PublishAsync( new FileArtifact( new FileInfo(fileName), ExtensionResources.TrxReportArtifactDisplayName, - ExtensionResources.TrxReportArtifactDescription)); + ExtensionResources.TrxReportArtifactDescription)).ConfigureAwait(false); return; } @@ -206,10 +206,10 @@ await _messageBus.PublishAsync( testHostProcessInformation.ExitCode, cancellation); - await trxReportGeneratorEngine.AddArtifactsAsync(trxFile, artifacts); + await trxReportGeneratorEngine.AddArtifactsAsync(trxFile, artifacts).ConfigureAwait(false); } - await _messageBus.PublishAsync(this, new FileArtifact(trxFile, ExtensionResources.TrxReportArtifactDisplayName, ExtensionResources.TrxReportArtifactDescription)); + await _messageBus.PublishAsync(this, new FileArtifact(trxFile, ExtensionResources.TrxReportArtifactDisplayName, ExtensionResources.TrxReportArtifactDescription)).ConfigureAwait(false); } private Task CallbackAsync(IRequest request) @@ -233,7 +233,7 @@ private Task CallbackAsync(IRequest request) #if NETCOREAPP public async ValueTask DisposeAsync() { - await DisposeHelper.DisposeAsync(_singleConnectionNamedPipeServer); + await DisposeHelper.DisposeAsync(_singleConnectionNamedPipeServer).ConfigureAwait(false); // Dispose the pipe descriptor after the server to ensure the pipe is closed. _pipeNameDescription?.Dispose(); diff --git a/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxReportEngine.cs b/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxReportEngine.cs index bed4e9dc84..b739de4800 100644 --- a/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxReportEngine.cs +++ b/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxReportEngine.cs @@ -177,7 +177,7 @@ public TrxReportEngine(IFileSystem fileSystem, ITestApplicationModuleInfo testAp // NotExecuted is the status for the skipped test. resultSummaryOutcome = isTestHostCrashed || _exitCode != ExitCodes.Success ? "Failed" : resultSummaryOutcome is "Passed" or "NotExecuted" ? "Completed" : resultSummaryOutcome; - await AddResultSummaryAsync(testRun, resultSummaryOutcome, runDeploymentRoot, testHostCrashInfo, _exitCode, isTestHostCrashed); + await AddResultSummaryAsync(testRun, resultSummaryOutcome, runDeploymentRoot, testHostCrashInfo, _exitCode, isTestHostCrashed).ConfigureAwait(false); // will need catch Unauthorized access document.Add(testRun); @@ -203,11 +203,11 @@ public TrxReportEngine(IFileSystem fileSystem, ITestApplicationModuleInfo testAp // Note that we need to dispose the IFileStream, not the inner stream. // IFileStream implementations will be responsible to dispose their inner stream. using IFileStream stream = _fileSystem.NewFileStream(finalFileName, isFileNameExplicitlyProvided ? FileMode.Create : FileMode.CreateNew); - await document.SaveAsync(stream.Stream, SaveOptions.None, _cancellationToken); + await document.SaveAsync(stream.Stream, SaveOptions.None, _cancellationToken).ConfigureAwait(false); return isFileNameExplicitlyProvidedAndFileExists ? (finalFileName, string.Format(CultureInfo.InvariantCulture, ExtensionResources.TrxFileExistsAndWillBeOverwritten, finalFileName)) : (finalFileName, null); - }); + }).ConfigureAwait(false); private async Task<(string FileName, string? Warning)> RetryWhenIOExceptionAsync(Func> func) { @@ -217,7 +217,7 @@ public TrxReportEngine(IFileSystem fileSystem, ITestApplicationModuleInfo testAp { try { - return await func(); + return await func().ConfigureAwait(false); } catch (IOException) { @@ -254,10 +254,10 @@ public async Task AddArtifactsAsync(FileInfo trxFile, Dictionary> artifacts, XElement collectorDataEntries, string runDeploymentRoot) @@ -276,7 +276,7 @@ private async Task AddArtifactsToCollectionAsync(Dictionary CopyArtifactIntoTrxDirectoryAndReturnHrefValueAsync(FileInfo artifact, string runDeploymentRoot) @@ -368,7 +368,7 @@ private async Task CopyArtifactIntoTrxDirectoryAndReturnHrefValueAsync(F break; } - await CopyFileAsync(artifact, new FileInfo(destination)); + await CopyFileAsync(artifact, new FileInfo(destination)).ConfigureAwait(false); return Path.Combine(_environment.MachineName, Path.GetFileName(destination)); } @@ -393,7 +393,7 @@ private async Task CopyFileAsync(FileInfo origin, FileInfo destination) using FileStream fileStream = File.OpenRead(origin.FullName); using var destinationStream = new FileStream(destination.FullName, FileMode.Create); - await fileStream.CopyToAsync(destinationStream, _cancellationToken); + await fileStream.CopyToAsync(destinationStream, _cancellationToken).ConfigureAwait(false); } private static void AddTestLists(XElement testRun, string uncategorizedTestId) diff --git a/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxTestApplicationLifecycleCallbacks.cs b/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxTestApplicationLifecycleCallbacks.cs index 33e0e73cff..e48d67ca91 100644 --- a/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxTestApplicationLifecycleCallbacks.cs +++ b/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxTestApplicationLifecycleCallbacks.cs @@ -69,7 +69,7 @@ public async Task BeforeRunAsync(CancellationToken cancellationToken) NamedPipeClient.RegisterSerializer(new VoidResponseSerializer(), typeof(VoidResponse)); // Connect to the named pipe server - await NamedPipeClient.ConnectAsync(cancellationToken).TimeoutAfterAsync(TimeoutHelper.DefaultHangTimeSpanTimeout, cancellationToken); + await NamedPipeClient.ConnectAsync(cancellationToken).TimeoutAfterAsync(TimeoutHelper.DefaultHangTimeSpanTimeout, cancellationToken).ConfigureAwait(false); } } catch (OperationCanceledException ex) when (ex.CancellationToken == cancellationToken) diff --git a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/Configurations/RunSettingsConfigurationProvider.cs b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/Configurations/RunSettingsConfigurationProvider.cs index da7ff8d85c..297dd6e2b6 100644 --- a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/Configurations/RunSettingsConfigurationProvider.cs +++ b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/Configurations/RunSettingsConfigurationProvider.cs @@ -64,7 +64,7 @@ public async Task BuildAsync(CommandLineParseResult comm { if (_fileSystem.Exists(runSettingsFilePath[0])) { - _runSettingsFileContent = await _fileSystem.ReadAllTextAsync(runSettingsFilePath[0]); + _runSettingsFileContent = await _fileSystem.ReadAllTextAsync(runSettingsFilePath[0]).ConfigureAwait(false); } } diff --git a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/FrameworkHandlerAdapter.cs b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/FrameworkHandlerAdapter.cs index 65804c81be..d5406b4ed8 100644 --- a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/FrameworkHandlerAdapter.cs +++ b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/FrameworkHandlerAdapter.cs @@ -182,7 +182,7 @@ private async Task PublishTestSessionAttachmentsAsync(IEnumerable } var fileArtifact = new SessionFileArtifact(_session.SessionUid, new(attachment.Uri.LocalPath), attachmentSet.DisplayName, attachment.Description); - await _messageBus.PublishAsync(_adapterExtensionBase, fileArtifact); + await _messageBus.PublishAsync(_adapterExtensionBase, fileArtifact).ConfigureAwait(false); } } } diff --git a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/SynchronizedSingleSessionVSTestAndTestAnywhereAdapter.cs b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/SynchronizedSingleSessionVSTestAndTestAnywhereAdapter.cs index a9f70fbcdf..0789698909 100644 --- a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/SynchronizedSingleSessionVSTestAndTestAnywhereAdapter.cs +++ b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/SynchronizedSingleSessionVSTestAndTestAnywhereAdapter.cs @@ -52,7 +52,7 @@ protected SynchronizedSingleSessionVSTestBridgedTestFramework(IExtension extensi public sealed override string Version => _extension.Version; /// - public override async Task IsEnabledAsync() => await _extension.IsEnabledAsync(); + public override async Task IsEnabledAsync() => await _extension.IsEnabledAsync().ConfigureAwait(false); /// public sealed override Task CreateTestSessionAsync(CreateTestSessionContext context) @@ -75,7 +75,7 @@ public sealed override async Task CloseTestSessionAsync( _incomingRequestCounter.Signal(); // Wait for remaining request processing - await _incomingRequestCounter.WaitAsync(context.CancellationToken); + await _incomingRequestCounter.WaitAsync(context.CancellationToken).ConfigureAwait(false); _sessionUid = null; return new CloseTestSessionResult { IsSuccess = true }; } @@ -108,7 +108,7 @@ protected virtual void Dispose(bool disposing) /// The cancellation token. protected sealed override Task DiscoverTestsAsync(VSTestDiscoverTestExecutionRequest request, IMessageBus messageBus, CancellationToken cancellationToken) - => ExecuteRequestWithRequestCountGuardAsync(async () => await SynchronizedDiscoverTestsAsync(request, messageBus, cancellationToken)); + => ExecuteRequestWithRequestCountGuardAsync(async () => await SynchronizedDiscoverTestsAsync(request, messageBus, cancellationToken).ConfigureAwait(false)); /// /// Discovers tests asynchronously with handling of concurrency. @@ -127,7 +127,7 @@ protected abstract Task SynchronizedDiscoverTestsAsync(VSTestDiscoverTestExecuti /// The cancellation token. protected sealed override Task RunTestsAsync(VSTestRunTestExecutionRequest request, IMessageBus messageBus, CancellationToken cancellationToken) - => ExecuteRequestWithRequestCountGuardAsync(async () => await SynchronizedRunTestsAsync(request, messageBus, cancellationToken)); + => ExecuteRequestWithRequestCountGuardAsync(async () => await SynchronizedRunTestsAsync(request, messageBus, cancellationToken).ConfigureAwait(false)); /// /// Runs tests asynchronously with handling of concurrency. @@ -157,13 +157,13 @@ protected sealed override Task ExecuteRequestAsync(TestExecutionRequest request, case DiscoverTestExecutionRequest discoverRequest: VSTestDiscoverTestExecutionRequest vstestDiscoverRequest = VSTestDiscoverTestExecutionRequestFactory.CreateRequest(discoverRequest, this, testAssemblyPaths, cancellationToken); - await SynchronizedDiscoverTestsAsync(vstestDiscoverRequest, messageBus, cancellationToken); + await SynchronizedDiscoverTestsAsync(vstestDiscoverRequest, messageBus, cancellationToken).ConfigureAwait(false); break; case RunTestExecutionRequest runRequest: VSTestRunTestExecutionRequest vstestRunRequest = VSTestRunTestExecutionRequestFactory.CreateRequest(runRequest, this, testAssemblyPaths, cancellationToken); - await SynchronizedRunTestsAsync(vstestRunRequest, messageBus, cancellationToken); + await SynchronizedRunTestsAsync(vstestRunRequest, messageBus, cancellationToken).ConfigureAwait(false); break; default: @@ -185,7 +185,7 @@ private async Task ExecuteRequestWithRequestCountGuardAsync(Func asyncFunc try { - await asyncFunc(); + await asyncFunc().ConfigureAwait(false); } finally { diff --git a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/TestHostControllers/RunSettingsEnvironmentVariableProvider .cs b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/TestHostControllers/RunSettingsEnvironmentVariableProvider .cs index b1e9e21a15..a0d9366494 100644 --- a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/TestHostControllers/RunSettingsEnvironmentVariableProvider .cs +++ b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/TestHostControllers/RunSettingsEnvironmentVariableProvider .cs @@ -45,10 +45,10 @@ public async Task IsEnabledAsync() using IFileStream fileStream = _fileSystem.NewFileStream(runsettings[0], FileMode.Open, FileAccess.Read); #if NETCOREAPP - _runSettings = await XDocument.LoadAsync(fileStream.Stream, LoadOptions.None, CancellationToken.None); + _runSettings = await XDocument.LoadAsync(fileStream.Stream, LoadOptions.None, CancellationToken.None).ConfigureAwait(false); #else using StreamReader streamReader = new(fileStream.Stream); - _runSettings = XDocument.Parse(await streamReader.ReadToEndAsync()); + _runSettings = XDocument.Parse(await streamReader.ReadToEndAsync().ConfigureAwait(false)); #endif return _runSettings.Element("RunSettings")?.Element("RunConfiguration")?.Element("EnvironmentVariables") is not null; } diff --git a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/VSTestBridgedTestFrameworkBase.cs b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/VSTestBridgedTestFrameworkBase.cs index 516ce0c386..346c5d230e 100644 --- a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/VSTestBridgedTestFrameworkBase.cs +++ b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/VSTestBridgedTestFrameworkBase.cs @@ -92,7 +92,7 @@ public async Task ExecuteRequestAsync(ExecuteRequestContext context) _ => Task.CompletedTask, }; - await convertedRequest; + await convertedRequest.ConfigureAwait(false); } finally { diff --git a/src/Platform/Microsoft.Testing.Platform.MSBuild/Tasks/InvokeTestingPlatformTask.cs b/src/Platform/Microsoft.Testing.Platform.MSBuild/Tasks/InvokeTestingPlatformTask.cs index fd765fce0b..b5fcf97917 100644 --- a/src/Platform/Microsoft.Testing.Platform.MSBuild/Tasks/InvokeTestingPlatformTask.cs +++ b/src/Platform/Microsoft.Testing.Platform.MSBuild/Tasks/InvokeTestingPlatformTask.cs @@ -352,7 +352,7 @@ protected override void ProcessStarted() pipeServer.RegisterSerializer(new VoidResponseSerializer(), typeof(VoidResponse)); pipeServer.RegisterSerializer(new FailedTestInfoRequestSerializer(), typeof(FailedTestInfoRequest)); pipeServer.RegisterSerializer(new RunSummaryInfoRequestSerializer(), typeof(RunSummaryInfoRequest)); - await pipeServer.WaitConnectionAsync(_waitForConnections.Token); + await pipeServer.WaitConnectionAsync(_waitForConnections.Token).ConfigureAwait(false); _connections.Add(pipeServer); Log.LogMessage(MessageImportance.Low, $"Client connected to '{_pipeNameDescription.Name}'"); } diff --git a/src/Platform/Microsoft.Testing.Platform/Builder/TestApplication.cs b/src/Platform/Microsoft.Testing.Platform/Builder/TestApplication.cs index b5f7d81720..e28553653c 100644 --- a/src/Platform/Microsoft.Testing.Platform/Builder/TestApplication.cs +++ b/src/Platform/Microsoft.Testing.Platform/Builder/TestApplication.cs @@ -93,7 +93,7 @@ public static async Task CreateBuilderAsync(string[] ar { ILogger logger = loggingState.FileLoggerProvider.CreateLogger(typeof(TestApplication).ToString()); s_unhandledExceptionHandler.SetLogger(logger); - await LogInformationAsync(logger, testApplicationModuleInfo, testHostControllerInfo, systemProcess, systemEnvironment, createBuilderEntryTime, loggingState.IsSynchronousWrite, loggingState.LogLevel, args); + await LogInformationAsync(logger, testApplicationModuleInfo, testHostControllerInfo, systemProcess, systemEnvironment, createBuilderEntryTime, loggingState.IsSynchronousWrite, loggingState.LogLevel, args).ConfigureAwait(false); } // All checks are fine, create the TestApplication. @@ -115,25 +115,25 @@ private static async Task LogInformationAsync( AssemblyInformationalVersionAttribute? version = Assembly.GetExecutingAssembly().GetCustomAttribute(); if (version is not null) { - await logger.LogInformationAsync($"Version: {version.InformationalVersion}"); + await logger.LogInformationAsync($"Version: {version.InformationalVersion}").ConfigureAwait(false); } else { - await logger.LogInformationAsync("Version attribute not found"); + await logger.LogInformationAsync("Version attribute not found").ConfigureAwait(false); } - await logger.LogInformationAsync("Logging mode: " + (syncWrite ? "synchronous" : "asynchronous")); - await logger.LogInformationAsync($"Logging level: {loggerLevel}"); - await logger.LogInformationAsync($"CreateBuilderAsync entry time: {createBuilderEntryTime}"); + await logger.LogInformationAsync("Logging mode: " + (syncWrite ? "synchronous" : "asynchronous")).ConfigureAwait(false); + await logger.LogInformationAsync($"Logging level: {loggerLevel}").ConfigureAwait(false); + await logger.LogInformationAsync($"CreateBuilderAsync entry time: {createBuilderEntryTime}").ConfigureAwait(false); using IProcess currentProcess = processHandler.GetCurrentProcess(); - await logger.LogInformationAsync($"PID: {currentProcess.Id}"); + await logger.LogInformationAsync($"PID: {currentProcess.Id}").ConfigureAwait(false); #if NETCOREAPP string runtimeInformation = $"{RuntimeInformation.RuntimeIdentifier} - {RuntimeInformation.FrameworkDescription}"; #else string runtimeInformation = $"{RuntimeInformation.ProcessArchitecture} - {RuntimeInformation.FrameworkDescription}"; #endif - await logger.LogInformationAsync($"Runtime information: {runtimeInformation}"); + await logger.LogInformationAsync($"Runtime information: {runtimeInformation}").ConfigureAwait(false); #if NETCOREAPP if (RuntimeFeature.IsDynamicCodeSupported) @@ -143,11 +143,11 @@ private static async Task LogInformationAsync( #pragma warning restore IL3000 // Avoid accessing Assembly file path when publishing as a single file if (runtimeLocation is not null) { - await logger.LogInformationAsync($"Runtime location: {runtimeLocation}"); + await logger.LogInformationAsync($"Runtime location: {runtimeLocation}").ConfigureAwait(false); } else { - await logger.LogInformationAsync("Runtime location not found."); + await logger.LogInformationAsync("Runtime location not found.").ConfigureAwait(false); } } #else @@ -156,11 +156,11 @@ private static async Task LogInformationAsync( #pragma warning restore IL3000 // Avoid accessing Assembly file path when publishing as a single file if (runtimeLocation is not null) { - await logger.LogInformationAsync($"Runtime location: {runtimeLocation}"); + await logger.LogInformationAsync($"Runtime location: {runtimeLocation}").ConfigureAwait(false); } else { - await logger.LogInformationAsync($"Runtime location not found."); + await logger.LogInformationAsync($"Runtime location not found.").ConfigureAwait(false); } #endif @@ -168,11 +168,11 @@ private static async Task LogInformationAsync( #if NETCOREAPP isDynamicCodeSupported = RuntimeFeature.IsDynamicCodeSupported; #endif - await logger.LogInformationAsync($"IsDynamicCodeSupported: {isDynamicCodeSupported}"); + await logger.LogInformationAsync($"IsDynamicCodeSupported: {isDynamicCodeSupported}").ConfigureAwait(false); string moduleName = testApplicationModuleInfo.GetDisplayName(); - await logger.LogInformationAsync($"Test module: {moduleName}"); - await logger.LogInformationAsync($"Command line arguments: '{(args.Length == 0 ? string.Empty : args.Aggregate((a, b) => $"{a} {b}"))}'"); + await logger.LogInformationAsync($"Test module: {moduleName}").ConfigureAwait(false); + await logger.LogInformationAsync($"Command line arguments: '{(args.Length == 0 ? string.Empty : args.Aggregate((a, b) => $"{a} {b}"))}'").ConfigureAwait(false); StringBuilder machineInfo = new(); #pragma warning disable RS0030 // Do not use banned APIs @@ -184,15 +184,15 @@ private static async Task LogInformationAsync( #if NETCOREAPP machineInfo.AppendLine(CultureInfo.InvariantCulture, $"TotalAvailableMemoryBytes(GB): {GC.GetGCMemoryInfo().TotalAvailableMemoryBytes / 1_000_000_000}"); #endif - await logger.LogDebugAsync($"Machine info:\n{machineInfo}"); + await logger.LogDebugAsync($"Machine info:\n{machineInfo}").ConfigureAwait(false); if (testHostControllerInfo.HasTestHostController) { int? testHostControllerPID = testHostControllerInfo.GetTestHostControllerPID(); - await LogVariableAsync(EnvironmentVariableConstants.TESTINGPLATFORM_TESTHOSTCONTROLLER_CORRELATIONID); - await LogVariableAsync(EnvironmentVariableConstants.TESTINGPLATFORM_TESTHOSTCONTROLLER_PARENTPID); - await LogVariableAsync(EnvironmentVariableConstants.TESTINGPLATFORM_TESTHOSTCONTROLLER_TESTHOSTPROCESSSTARTTIME); + await LogVariableAsync(EnvironmentVariableConstants.TESTINGPLATFORM_TESTHOSTCONTROLLER_CORRELATIONID).ConfigureAwait(false); + await LogVariableAsync(EnvironmentVariableConstants.TESTINGPLATFORM_TESTHOSTCONTROLLER_PARENTPID).ConfigureAwait(false); + await LogVariableAsync(EnvironmentVariableConstants.TESTINGPLATFORM_TESTHOSTCONTROLLER_TESTHOSTPROCESSSTARTTIME).ConfigureAwait(false); async Task LogVariableAsync(string key) { @@ -200,12 +200,12 @@ async Task LogVariableAsync(string key) key = $"{key}_{testHostControllerPID}"; if ((value = environment.GetEnvironmentVariable(key)) is not null) { - await logger.LogDebugAsync($"{key} '{value}'"); + await logger.LogDebugAsync($"{key} '{value}'").ConfigureAwait(false); } } } - await logger.LogInformationAsync($"{EnvironmentVariableConstants.TESTINGPLATFORM_DEFAULT_HANG_TIMEOUT}: '{environment.GetEnvironmentVariable(EnvironmentVariableConstants.TESTINGPLATFORM_DEFAULT_HANG_TIMEOUT)}'"); + await logger.LogInformationAsync($"{EnvironmentVariableConstants.TESTINGPLATFORM_DEFAULT_HANG_TIMEOUT}: '{environment.GetEnvironmentVariable(EnvironmentVariableConstants.TESTINGPLATFORM_DEFAULT_HANG_TIMEOUT)}'").ConfigureAwait(false); } internal static void ReleaseBuilder() @@ -225,7 +225,7 @@ public ValueTask DisposeAsync() /// public async Task RunAsync() - => await _testHost.RunAsync(); + => await _testHost.RunAsync().ConfigureAwait(false); private static void AttachDebuggerIfNeeded(SystemEnvironment environment, SystemConsole console, SystemProcessHandler systemProcess) { diff --git a/src/Platform/Microsoft.Testing.Platform/Builder/TestApplicationBuilder.cs b/src/Platform/Microsoft.Testing.Platform/Builder/TestApplicationBuilder.cs index ce13d07d0b..3d046406cb 100644 --- a/src/Platform/Microsoft.Testing.Platform/Builder/TestApplicationBuilder.cs +++ b/src/Platform/Microsoft.Testing.Platform/Builder/TestApplicationBuilder.cs @@ -109,7 +109,7 @@ public async Task BuildAsync() throw new InvalidOperationException(PlatformResources.TestApplicationBuilderApplicationAlreadyRegistered); } - _testHost = await _testHostBuilder.BuildAsync(_loggingState, _testApplicationOptions, _unhandledExceptionsHandler, _createBuilderStart); + _testHost = await _testHostBuilder.BuildAsync(_loggingState, _testApplicationOptions, _unhandledExceptionsHandler, _createBuilderStart).ConfigureAwait(false); return new TestApplication(_testHost); } diff --git a/src/Platform/Microsoft.Testing.Platform/CommandLine/CommandLineHandler.cs b/src/Platform/Microsoft.Testing.Platform/CommandLine/CommandLineHandler.cs index ac42242e50..f4980eed01 100644 --- a/src/Platform/Microsoft.Testing.Platform/CommandLine/CommandLineHandler.cs +++ b/src/Platform/Microsoft.Testing.Platform/CommandLine/CommandLineHandler.cs @@ -49,10 +49,10 @@ public CommandLineHandler(CommandLineParseResult parseResult, IReadOnlyCollectio public async Task PrintInfoAsync(IOutputDevice outputDevice, IReadOnlyList? availableTools = null) { // /!\ Info should not be localized as it serves debugging purposes. - await DisplayPlatformInfoAsync(); - await outputDevice.DisplayAsync(this, EmptyText); - await DisplayBuiltInExtensionsInfoAsync(outputDevice); - await outputDevice.DisplayAsync(this, EmptyText); + await DisplayPlatformInfoAsync().ConfigureAwait(false); + await outputDevice.DisplayAsync(this, EmptyText).ConfigureAwait(false); + await DisplayBuiltInExtensionsInfoAsync(outputDevice).ConfigureAwait(false); + await outputDevice.DisplayAsync(this, EmptyText).ConfigureAwait(false); List toolExtensions = []; List nonToolExtensions = []; @@ -68,24 +68,24 @@ public async Task PrintInfoAsync(IOutputDevice outputDevice, IReadOnlyList(); string versionInfo = version?.InformationalVersion ?? "Not Available"; - await outputDevice.DisplayAsync(this, new TextOutputDeviceData($" Version: {versionInfo}")); + await outputDevice.DisplayAsync(this, new TextOutputDeviceData($" Version: {versionInfo}")).ConfigureAwait(false); - await outputDevice.DisplayAsync(this, new TextOutputDeviceData($" Dynamic Code Supported: {_runtimeFeature.IsDynamicCodeSupported}")); + await outputDevice.DisplayAsync(this, new TextOutputDeviceData($" Dynamic Code Supported: {_runtimeFeature.IsDynamicCodeSupported}")).ConfigureAwait(false); // TODO: Replace RuntimeInformation with IRuntimeInformation #if NETCOREAPP @@ -93,17 +93,17 @@ async Task DisplayPlatformInfoAsync() #else string runtimeInformation = $"{RuntimeInformation.FrameworkDescription}"; #endif - await outputDevice.DisplayAsync(this, new TextOutputDeviceData($" Runtime information: {runtimeInformation}")); + await outputDevice.DisplayAsync(this, new TextOutputDeviceData($" Runtime information: {runtimeInformation}")).ConfigureAwait(false); #if !NETCOREAPP #pragma warning disable IL3000 // Avoid accessing Assembly file path when publishing as a single file, this branch run only in .NET Framework string runtimeLocation = typeof(object).Assembly?.Location ?? "Not Found"; #pragma warning restore IL3000 // Avoid accessing Assembly file path when publishing as a single file - await outputDevice.DisplayAsync(this, new TextOutputDeviceData($" Runtime location: {runtimeLocation}")); + await outputDevice.DisplayAsync(this, new TextOutputDeviceData($" Runtime location: {runtimeLocation}")).ConfigureAwait(false); #endif string moduleName = _testApplicationModuleInfo.GetDisplayName(); - await outputDevice.DisplayAsync(this, new TextOutputDeviceData($" Test module: {moduleName}")); + await outputDevice.DisplayAsync(this, new TextOutputDeviceData($" Test module: {moduleName}")).ConfigureAwait(false); } async Task DisplayOptionsAsync(IOutputDevice outputDevice, IEnumerable options, int indentLevel) @@ -112,19 +112,19 @@ async Task DisplayOptionsAsync(IOutputDevice outputDevice, IEnumerable x.Name)) { - await outputDevice.DisplayAsync(this, new TextOutputDeviceData($"{optionNameIndent}--{option.Name}")); + await outputDevice.DisplayAsync(this, new TextOutputDeviceData($"{optionNameIndent}--{option.Name}")).ConfigureAwait(false); if (option.Arity.Min == option.Arity.Max) { - await outputDevice.DisplayAsync(this, new TextOutputDeviceData($"{optionInfoIndent}Arity: {option.Arity.Min}")); + await outputDevice.DisplayAsync(this, new TextOutputDeviceData($"{optionInfoIndent}Arity: {option.Arity.Min}")).ConfigureAwait(false); } else { string maxArityValue = option.Arity.Max == int.MaxValue ? "N" : $"{option.Arity.Max}"; - await outputDevice.DisplayAsync(this, new TextOutputDeviceData($"{optionInfoIndent}Arity: {option.Arity.Min}..{maxArityValue}")); + await outputDevice.DisplayAsync(this, new TextOutputDeviceData($"{optionInfoIndent}Arity: {option.Arity.Min}..{maxArityValue}")).ConfigureAwait(false); } - await outputDevice.DisplayAsync(this, new TextOutputDeviceData($"{optionInfoIndent}Hidden: {option.IsHidden}")); - await outputDevice.DisplayAsync(this, new FormattedTextOutputDeviceData($"Description: {option.Description}") { Padding = optionInfoIndent.Length }); + await outputDevice.DisplayAsync(this, new TextOutputDeviceData($"{optionInfoIndent}Hidden: {option.IsHidden}")).ConfigureAwait(false); + await outputDevice.DisplayAsync(this, new FormattedTextOutputDeviceData($"Description: {option.Description}") { Padding = optionInfoIndent.Length }).ConfigureAwait(false); } } @@ -140,69 +140,69 @@ async Task DisplayProvidersAsync(IOutputDevice outputDevice, IEnumerable nonToolExtensions) { - await outputDevice.DisplayAsync(this, new TextOutputDeviceData("Registered command line providers:")); + await outputDevice.DisplayAsync(this, new TextOutputDeviceData("Registered command line providers:")).ConfigureAwait(false); if (nonToolExtensions.Count == 0) { - await outputDevice.DisplayAsync(this, new TextOutputDeviceData(" There are no registered command line providers.")); + await outputDevice.DisplayAsync(this, new TextOutputDeviceData(" There are no registered command line providers.")).ConfigureAwait(false); } else { - await DisplayProvidersAsync(outputDevice, nonToolExtensions, 1); + await DisplayProvidersAsync(outputDevice, nonToolExtensions, 1).ConfigureAwait(false); } } async Task DisplayRegisteredToolsInfoAsync(IOutputDevice outputDevice, IReadOnlyList? availableTools, List toolExtensions) { - await outputDevice.DisplayAsync(this, new TextOutputDeviceData("Registered tools:")); + await outputDevice.DisplayAsync(this, new TextOutputDeviceData("Registered tools:")).ConfigureAwait(false); if (availableTools is null || availableTools.Count == 0) { - await outputDevice.DisplayAsync(this, new TextOutputDeviceData(" There are no registered tools.")); + await outputDevice.DisplayAsync(this, new TextOutputDeviceData(" There are no registered tools.")).ConfigureAwait(false); } else { var groupedToolExtensions = toolExtensions.GroupBy(x => x.ToolName).ToDictionary(x => x.Key, x => x.ToList()); foreach (ITool tool in availableTools.OrderBy(x => x.Uid)) { - await outputDevice.DisplayAsync(this, new TextOutputDeviceData($" {tool.Uid}")); - await outputDevice.DisplayAsync(this, new TextOutputDeviceData($" Command: {tool.Name}")); - await outputDevice.DisplayAsync(this, new TextOutputDeviceData($" Name: {tool.DisplayName}")); - await outputDevice.DisplayAsync(this, new TextOutputDeviceData($" Version: {tool.Version}")); - await outputDevice.DisplayAsync(this, new FormattedTextOutputDeviceData($"Description: {tool.Description}") { Padding = 4 }); - await outputDevice.DisplayAsync(this, new TextOutputDeviceData(" Tool command line providers:")); + await outputDevice.DisplayAsync(this, new TextOutputDeviceData($" {tool.Uid}")).ConfigureAwait(false); + await outputDevice.DisplayAsync(this, new TextOutputDeviceData($" Command: {tool.Name}")).ConfigureAwait(false); + await outputDevice.DisplayAsync(this, new TextOutputDeviceData($" Name: {tool.DisplayName}")).ConfigureAwait(false); + await outputDevice.DisplayAsync(this, new TextOutputDeviceData($" Version: {tool.Version}")).ConfigureAwait(false); + await outputDevice.DisplayAsync(this, new FormattedTextOutputDeviceData($"Description: {tool.Description}") { Padding = 4 }).ConfigureAwait(false); + await outputDevice.DisplayAsync(this, new TextOutputDeviceData(" Tool command line providers:")).ConfigureAwait(false); if (groupedToolExtensions.TryGetValue(tool.Name, out List? providers)) { - await DisplayProvidersAsync(outputDevice, providers, 3); + await DisplayProvidersAsync(outputDevice, providers, 3).ConfigureAwait(false); } else { - await outputDevice.DisplayAsync(this, new TextOutputDeviceData(" There are no registered command line providers.")); + await outputDevice.DisplayAsync(this, new TextOutputDeviceData(" There are no registered command line providers.")).ConfigureAwait(false); } } } @@ -231,11 +231,11 @@ public async Task PrintHelpAsync(IOutputDevice outputDevice, IReadOnlyList().Any(), "System command line options should not have any tool option registered."); - await outputDevice.DisplayAsync(this, new TextOutputDeviceData(PlatformResources.HelpOptions)); + await outputDevice.DisplayAsync(this, new TextOutputDeviceData(PlatformResources.HelpOptions)).ConfigureAwait(false); ICommandLineOptionsProvider[] nonToolsExtensionProviders = [.. ExtensionsCommandLineOptionsProviders.Where(provider => provider is not IToolCommandLineOptionsProvider)]; // By default, only system options are built-in but some extensions (e.g. retry) are considered as built-in too, // so we need to union the 2 collections before printing the options. - await PrintOptionsAsync(SystemCommandLineOptionsProviders.Union(nonToolsExtensionProviders), builtInOnly: true); - await outputDevice.DisplayAsync(this, EmptyText); + await PrintOptionsAsync(SystemCommandLineOptionsProviders.Union(nonToolsExtensionProviders), builtInOnly: true).ConfigureAwait(false); + await outputDevice.DisplayAsync(this, EmptyText).ConfigureAwait(false); - await outputDevice.DisplayAsync(this, new TextOutputDeviceData(PlatformResources.HelpExtensionOptions)); - if (!await PrintOptionsAsync(nonToolsExtensionProviders)) + await outputDevice.DisplayAsync(this, new TextOutputDeviceData(PlatformResources.HelpExtensionOptions)).ConfigureAwait(false); + if (!await PrintOptionsAsync(nonToolsExtensionProviders).ConfigureAwait(false)) { - await outputDevice.DisplayAsync(this, new TextOutputDeviceData(PlatformResources.HelpNoExtensionRegistered)); + await outputDevice.DisplayAsync(this, new TextOutputDeviceData(PlatformResources.HelpNoExtensionRegistered)).ConfigureAwait(false); } - await outputDevice.DisplayAsync(this, EmptyText); + await outputDevice.DisplayAsync(this, EmptyText).ConfigureAwait(false); } // Temporary disabled, we don't remove the code because could be useful in future. diff --git a/src/Platform/Microsoft.Testing.Platform/CommandLine/CommandLineManager.cs b/src/Platform/Microsoft.Testing.Platform/CommandLine/CommandLineManager.cs index 796a345413..d737a0ad5a 100644 --- a/src/Platform/Microsoft.Testing.Platform/CommandLine/CommandLineManager.cs +++ b/src/Platform/Microsoft.Testing.Platform/CommandLine/CommandLineManager.cs @@ -33,12 +33,12 @@ internal async Task BuildAsync(CommandLineParseResult parseR foreach (Func commandLineProviderFactory in _commandLineProviderFactory) { ICommandLineOptionsProvider commandLineOptionsProvider = commandLineProviderFactory(serviceProvider); - if (!await commandLineOptionsProvider.IsEnabledAsync()) + if (!await commandLineOptionsProvider.IsEnabledAsync().ConfigureAwait(false)) { continue; } - await commandLineOptionsProvider.TryInitializeAsync(); + await commandLineOptionsProvider.TryInitializeAsync().ConfigureAwait(false); commandLineOptionsProviders.Add( commandLineOptionsProvider is IToolCommandLineOptionsProvider toolCommandLineOptionsProvider diff --git a/src/Platform/Microsoft.Testing.Platform/CommandLine/CommandLineOptionsValidator.cs b/src/Platform/Microsoft.Testing.Platform/CommandLine/CommandLineOptionsValidator.cs index 9becb9e8c5..9ea02b9a03 100644 --- a/src/Platform/Microsoft.Testing.Platform/CommandLine/CommandLineOptionsValidator.cs +++ b/src/Platform/Microsoft.Testing.Platform/CommandLine/CommandLineOptionsValidator.cs @@ -59,13 +59,13 @@ public static async Task ValidateAsync( return result5; } - if (await ValidateOptionsArgumentsAsync(commandLineParseResult, providerAndOptionByOptionName) is { IsValid: false } result6) + if (await ValidateOptionsArgumentsAsync(commandLineParseResult, providerAndOptionByOptionName).ConfigureAwait(false) is { IsValid: false } result6) { return result6; } // Last validation step - return await ValidateConfigurationAsync(extensionOptionsByProvider.Keys, systemOptionsByProvider.Keys, commandLineOptions); + return await ValidateConfigurationAsync(extensionOptionsByProvider.Keys, systemOptionsByProvider.Keys, commandLineOptions).ConfigureAwait(false); } private static ValidationResult ValidateExtensionOptionsDoNotContainReservedPrefix( @@ -208,7 +208,7 @@ private static async Task ValidateOptionsArgumentsAsync( foreach (CommandLineParseOption optionRecord in parseResult.Options) { (ICommandLineOptionsProvider provider, CommandLineOption option) = providerAndOptionByOptionName[optionRecord.Name]; - ValidationResult result = await provider.ValidateOptionArgumentsAsync(option, optionRecord.Arguments); + ValidationResult result = await provider.ValidateOptionArgumentsAsync(option, optionRecord.Arguments).ConfigureAwait(false); if (!result.IsValid) { stringBuilder ??= new(); @@ -226,8 +226,8 @@ private static async Task ValidateConfigurationAsync( Dictionary>.KeyCollection systemProviders, ICommandLineOptions commandLineOptions) { - StringBuilder? stringBuilder = await ValidateConfigurationAsync(systemProviders, commandLineOptions, null); - stringBuilder = await ValidateConfigurationAsync(extensionsProviders, commandLineOptions, stringBuilder); + StringBuilder? stringBuilder = await ValidateConfigurationAsync(systemProviders, commandLineOptions, null).ConfigureAwait(false); + stringBuilder = await ValidateConfigurationAsync(extensionsProviders, commandLineOptions, stringBuilder).ConfigureAwait(false); return stringBuilder?.Length > 0 ? ValidationResult.Invalid(stringBuilder.ToTrimmedString()) @@ -241,7 +241,7 @@ private static async Task ValidateConfigurationAsync( { foreach (ICommandLineOptionsProvider commandLineOptionsProvider in providers) { - ValidationResult result = await commandLineOptionsProvider.ValidateCommandLineOptionsAsync(commandLineOptions); + ValidationResult result = await commandLineOptionsProvider.ValidateCommandLineOptionsAsync(commandLineOptions).ConfigureAwait(false); if (!result.IsValid) { stringBuilder ??= new(); diff --git a/src/Platform/Microsoft.Testing.Platform/CommandLine/InformativeCommandLineTestHost.cs b/src/Platform/Microsoft.Testing.Platform/CommandLine/InformativeCommandLineTestHost.cs index 05c78fc571..61983c398d 100644 --- a/src/Platform/Microsoft.Testing.Platform/CommandLine/InformativeCommandLineTestHost.cs +++ b/src/Platform/Microsoft.Testing.Platform/CommandLine/InformativeCommandLineTestHost.cs @@ -27,7 +27,7 @@ public async ValueTask DisposeAsync() { if (PushOnlyProtocol is not null) { - await PushOnlyProtocol.DisposeAsync(); + await PushOnlyProtocol.DisposeAsync().ConfigureAwait(false); } } #endif diff --git a/src/Platform/Microsoft.Testing.Platform/Configurations/AggregatedConfiguration.cs b/src/Platform/Microsoft.Testing.Platform/Configurations/AggregatedConfiguration.cs index 878a690d58..18ffa830a1 100644 --- a/src/Platform/Microsoft.Testing.Platform/Configurations/AggregatedConfiguration.cs +++ b/src/Platform/Microsoft.Testing.Platform/Configurations/AggregatedConfiguration.cs @@ -68,7 +68,7 @@ public async Task CheckTestResultsDirectoryOverrideAndCreateItAsync(IFileLoggerP // This behavior is non documented and we reserve the right to change it in the future. if (fileLoggerProvider is not null) { - await fileLoggerProvider.CheckLogFolderAndMoveToTheNewIfNeededAsync(_resultsDirectory); + await fileLoggerProvider.CheckLogFolderAndMoveToTheNewIfNeededAsync(_resultsDirectory).ConfigureAwait(false); } } diff --git a/src/Platform/Microsoft.Testing.Platform/Configurations/ConfigurationManager.cs b/src/Platform/Microsoft.Testing.Platform/Configurations/ConfigurationManager.cs index 4336f6c4e8..bf9b7a51e6 100644 --- a/src/Platform/Microsoft.Testing.Platform/Configurations/ConfigurationManager.cs +++ b/src/Platform/Microsoft.Testing.Platform/Configurations/ConfigurationManager.cs @@ -27,15 +27,15 @@ internal async Task BuildAsync(IFileLoggerProvider? syncFileLogg foreach (Func configurationSource in _configurationSources) { IConfigurationSource serviceInstance = configurationSource(); - if (!await serviceInstance.IsEnabledAsync()) + if (!await serviceInstance.IsEnabledAsync().ConfigureAwait(false)) { continue; } - await serviceInstance.TryInitializeAsync(); + await serviceInstance.TryInitializeAsync().ConfigureAwait(false); - IConfigurationProvider configurationProvider = await serviceInstance.BuildAsync(commandLineParseResult); - await configurationProvider.LoadAsync(); + IConfigurationProvider configurationProvider = await serviceInstance.BuildAsync(commandLineParseResult).ConfigureAwait(false); + await configurationProvider.LoadAsync().ConfigureAwait(false); if (configurationProvider is JsonConfigurationProvider configuration) { defaultJsonConfiguration = configuration; @@ -52,7 +52,7 @@ internal async Task BuildAsync(IFileLoggerProvider? syncFileLogg { using IFileStream configFileStream = _fileSystem.NewFileStream(defaultJsonConfiguration.ConfigurationFile, FileMode.Open, FileAccess.Read); StreamReader streamReader = new(configFileStream.Stream); - await logger.LogTraceAsync($"Configuration file ('{defaultJsonConfiguration.ConfigurationFile}') content:\n{await streamReader.ReadToEndAsync()}"); + await logger.LogTraceAsync($"Configuration file ('{defaultJsonConfiguration.ConfigurationFile}') content:\n{await streamReader.ReadToEndAsync().ConfigureAwait(false)}").ConfigureAwait(false); } } diff --git a/src/Platform/Microsoft.Testing.Platform/Configurations/JsonConfigurationProvider.cs b/src/Platform/Microsoft.Testing.Platform/Configurations/JsonConfigurationProvider.cs index e2f33baa04..e1b481d43b 100644 --- a/src/Platform/Microsoft.Testing.Platform/Configurations/JsonConfigurationProvider.cs +++ b/src/Platform/Microsoft.Testing.Platform/Configurations/JsonConfigurationProvider.cs @@ -30,7 +30,7 @@ private async Task LogInformationAsync(string message) { if (_logger is not null) { - await _logger.LogInformationAsync(message); + await _logger.LogInformationAsync(message).ConfigureAwait(false); } } @@ -69,7 +69,7 @@ public async Task LoadAsync() } } - await LogInformationAsync($"Config file '{configFileName}' loaded."); + await LogInformationAsync($"Config file '{configFileName}' loaded.").ConfigureAwait(false); ConfigurationFile = configFileName; diff --git a/src/Platform/Microsoft.Testing.Platform/Extensions/AbortForMaxFailedTestsExtension.cs b/src/Platform/Microsoft.Testing.Platform/Extensions/AbortForMaxFailedTestsExtension.cs index c35ed10c03..b6fd5e23ef 100644 --- a/src/Platform/Microsoft.Testing.Platform/Extensions/AbortForMaxFailedTestsExtension.cs +++ b/src/Platform/Microsoft.Testing.Platform/Extensions/AbortForMaxFailedTestsExtension.cs @@ -74,8 +74,8 @@ public async Task ConsumeAsync(IDataProducer dataProducer, IData value, Cancella // If already triggered, don't do it again. !_policiesService.IsMaxFailedTestsTriggered) { - await _capability.StopTestExecutionAsync(_testApplicationCancellationTokenSource.CancellationToken); - await _policiesService.ExecuteMaxFailedTestsCallbacksAsync(_maxFailedTests.Value, _testApplicationCancellationTokenSource.CancellationToken); + await _capability.StopTestExecutionAsync(_testApplicationCancellationTokenSource.CancellationToken).ConfigureAwait(false); + await _policiesService.ExecuteMaxFailedTestsCallbacksAsync(_maxFailedTests.Value, _testApplicationCancellationTokenSource.CancellationToken).ConfigureAwait(false); } } } diff --git a/src/Platform/Microsoft.Testing.Platform/Extensions/IAsyncInitializableExtension.cs b/src/Platform/Microsoft.Testing.Platform/Extensions/IAsyncInitializableExtension.cs index 8b79a2560d..87c0e8ad90 100644 --- a/src/Platform/Microsoft.Testing.Platform/Extensions/IAsyncInitializableExtension.cs +++ b/src/Platform/Microsoft.Testing.Platform/Extensions/IAsyncInitializableExtension.cs @@ -20,7 +20,7 @@ public static async Task TryInitializeAsync(this object target) { if (target is IAsyncInitializableExtension initializable) { - await initializable.InitializeAsync(); + await initializable.InitializeAsync().ConfigureAwait(false); } } } diff --git a/src/Platform/Microsoft.Testing.Platform/Helpers/CountDownEventExtensions.cs b/src/Platform/Microsoft.Testing.Platform/Helpers/CountDownEventExtensions.cs index ccf927e17e..5093cbe04e 100644 --- a/src/Platform/Microsoft.Testing.Platform/Helpers/CountDownEventExtensions.cs +++ b/src/Platform/Microsoft.Testing.Platform/Helpers/CountDownEventExtensions.cs @@ -6,10 +6,10 @@ namespace Microsoft.Testing.Platform.Helpers; internal static class CountDownEventExtensions { public static async Task WaitAsync(this CountdownEvent countdownEvent, CancellationToken cancellationToken) - => await countdownEvent.WaitAsync(uint.MaxValue, cancellationToken); + => await countdownEvent.WaitAsync(uint.MaxValue, cancellationToken).ConfigureAwait(false); public static async Task WaitAsync(this CountdownEvent countdownEvent, TimeSpan timeout, CancellationToken cancellationToken) - => await countdownEvent.WaitAsync((uint)timeout.TotalMilliseconds, cancellationToken); + => await countdownEvent.WaitAsync((uint)timeout.TotalMilliseconds, cancellationToken).ConfigureAwait(false); internal static async Task WaitAsync(this CountdownEvent countdownEvent, uint millisecondsTimeOutInterval, CancellationToken cancellationToken) { @@ -39,7 +39,7 @@ internal static async Task WaitAsync(this CountdownEvent countdownEvent, u // Register the cancellation callback tokenRegistration = cancellationToken.Register(state => ((TaskCompletionSource)state!).TrySetCanceled(), tcs); - return await tcs.Task; + return await tcs.Task.ConfigureAwait(false); } finally { @@ -50,7 +50,7 @@ internal static async Task WaitAsync(this CountdownEvent countdownEvent, u #pragma warning disable CA1416 // Validate platform compatibility registeredHandle?.Unregister(null); #pragma warning restore CA1416 - await DisposeHelper.DisposeAsync(tokenRegistration); + await DisposeHelper.DisposeAsync(tokenRegistration).ConfigureAwait(false); } } } diff --git a/src/Platform/Microsoft.Testing.Platform/Helpers/DisposeHelper.cs b/src/Platform/Microsoft.Testing.Platform/Helpers/DisposeHelper.cs index 5ff940fa0b..97f5e1ad40 100644 --- a/src/Platform/Microsoft.Testing.Platform/Helpers/DisposeHelper.cs +++ b/src/Platform/Microsoft.Testing.Platform/Helpers/DisposeHelper.cs @@ -16,13 +16,13 @@ public static async Task DisposeAsync(object? obj) if (obj is IAsyncCleanableExtension async) { - await async.CleanupAsync(); + await async.CleanupAsync().ConfigureAwait(false); } #if NETCOREAPP if (obj is IAsyncDisposable dcAsyncDisposable) { - await dcAsyncDisposable.DisposeAsync(); + await dcAsyncDisposable.DisposeAsync().ConfigureAwait(false); } else { diff --git a/src/Platform/Microsoft.Testing.Platform/Helpers/System/SystemAsyncMonitor.cs b/src/Platform/Microsoft.Testing.Platform/Helpers/System/SystemAsyncMonitor.cs index 4d563c4cd8..3e43741968 100644 --- a/src/Platform/Microsoft.Testing.Platform/Helpers/System/SystemAsyncMonitor.cs +++ b/src/Platform/Microsoft.Testing.Platform/Helpers/System/SystemAsyncMonitor.cs @@ -10,14 +10,14 @@ internal sealed class SystemAsyncMonitor : IAsyncMonitor, IDisposable public async Task LockAsync(TimeSpan timeout) { AsyncDisposableMonitor asyncDisposableMonitor = new(_semaphoreSlim); - await asyncDisposableMonitor.WaitAsync(timeout); + await asyncDisposableMonitor.WaitAsync(timeout).ConfigureAwait(false); return asyncDisposableMonitor; } public async Task LockAsync(CancellationToken cancellationToken) { AsyncDisposableMonitor asyncDisposableMonitor = new(_semaphoreSlim); - await asyncDisposableMonitor.WaitAsync(cancellationToken); + await asyncDisposableMonitor.WaitAsync(cancellationToken).ConfigureAwait(false); return asyncDisposableMonitor; } @@ -30,13 +30,13 @@ private readonly struct AsyncDisposableMonitor(SemaphoreSlim semaphoreSlim) : ID public async Task WaitAsync(TimeSpan timeout) { - if (!await _semaphoreSlim.WaitAsync(timeout)) + if (!await _semaphoreSlim.WaitAsync(timeout).ConfigureAwait(false)) { throw new InvalidOperationException($"Timeout of '{timeout}' while waiting for the semaphore"); } } - public async Task WaitAsync(CancellationToken cancellationToken) => await _semaphoreSlim.WaitAsync(cancellationToken); + public async Task WaitAsync(CancellationToken cancellationToken) => await _semaphoreSlim.WaitAsync(cancellationToken).ConfigureAwait(false); public void Dispose() => _semaphoreSlim.Release(); diff --git a/src/Platform/Microsoft.Testing.Platform/Helpers/System/SystemFileSystem.cs b/src/Platform/Microsoft.Testing.Platform/Helpers/System/SystemFileSystem.cs index c87970a522..564aaf3173 100644 --- a/src/Platform/Microsoft.Testing.Platform/Helpers/System/SystemFileSystem.cs +++ b/src/Platform/Microsoft.Testing.Platform/Helpers/System/SystemFileSystem.cs @@ -24,7 +24,7 @@ public async Task ReadAllTextAsync(string path) { using FileStream stream = new(path, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, FileOptions.Asynchronous | FileOptions.SequentialScan); using StreamReader reader = new(stream); - return await reader.ReadToEndAsync(); + return await reader.ReadToEndAsync().ConfigureAwait(false); } #endif } diff --git a/src/Platform/Microsoft.Testing.Platform/Helpers/TaskExtensions.cs b/src/Platform/Microsoft.Testing.Platform/Helpers/TaskExtensions.cs index e482f7ab42..ae1ac1c92c 100644 --- a/src/Platform/Microsoft.Testing.Platform/Helpers/TaskExtensions.cs +++ b/src/Platform/Microsoft.Testing.Platform/Helpers/TaskExtensions.cs @@ -16,7 +16,7 @@ public static async Task WithCancellationAsync(this Task task, Cancella { try { - await task; + await task.ConfigureAwait(false); } catch (Exception) { @@ -55,7 +55,7 @@ public static async Task WithCancellationAsync(this Task task, CancellationToken { try { - await task; + await task.ConfigureAwait(false); } catch (Exception) { @@ -86,7 +86,7 @@ public static async Task TimeoutAfterAsync(this Task task, TimeSpan timeout, boo { try { - await task; + await task.ConfigureAwait(false); } catch (Exception) { @@ -124,7 +124,7 @@ public static async Task TimeoutAfterAsync(this Task task, TimeSpan timeout, Can { try { - await task; + await task.ConfigureAwait(false); } catch (Exception) { diff --git a/src/Platform/Microsoft.Testing.Platform/Hosts/CommonTestHost.cs b/src/Platform/Microsoft.Testing.Platform/Hosts/CommonTestHost.cs index 0e146d7e9c..44c99a83b1 100644 --- a/src/Platform/Microsoft.Testing.Platform/Hosts/CommonTestHost.cs +++ b/src/Platform/Microsoft.Testing.Platform/Hosts/CommonTestHost.cs @@ -31,7 +31,7 @@ public async Task RunAsync() { if (PushOnlyProtocol is null || PushOnlyProtocol?.IsServerMode == false) { - exitCode = await RunTestAppAsync(testApplicationCancellationToken); + exitCode = await RunTestAppAsync(testApplicationCancellationToken).ConfigureAwait(false); if (testApplicationCancellationToken.IsCancellationRequested) { @@ -46,17 +46,17 @@ public async Task RunAsync() RoslynDebug.Assert(PushOnlyProtocol is not null); ITestApplicationModuleInfo testApplicationModuleInfo = serviceProvider.GetTestApplicationModuleInfo(); - bool isValidProtocol = await PushOnlyProtocol.IsCompatibleProtocolAsync(GetHostType()); + bool isValidProtocol = await PushOnlyProtocol.IsCompatibleProtocolAsync(GetHostType()).ConfigureAwait(false); exitCode = isValidProtocol - ? await RunTestAppAsync(testApplicationCancellationToken) + ? await RunTestAppAsync(testApplicationCancellationToken).ConfigureAwait(false) : ExitCodes.IncompatibleProtocolVersion; } finally { if (PushOnlyProtocol is not null) { - await PushOnlyProtocol.OnExitAsync(); + await PushOnlyProtocol.OnExitAsync().ConfigureAwait(false); } } } @@ -66,9 +66,9 @@ public async Task RunAsync() } finally { - await DisposeServiceProviderAsync(ServiceProvider, isProcessShutdown: true); - await DisposeHelper.DisposeAsync(ServiceProvider.GetService()); - await DisposeHelper.DisposeAsync(PushOnlyProtocol); + await DisposeServiceProviderAsync(ServiceProvider, isProcessShutdown: true).ConfigureAwait(false); + await DisposeHelper.DisposeAsync(ServiceProvider.GetService()).ConfigureAwait(false); + await DisposeHelper.DisposeAsync(PushOnlyProtocol).ConfigureAwait(false); // This is intentional that we are not disposing the CTS. // An unobserved task exception could be raised after the dispose, and we want to use OutputDevice there @@ -103,18 +103,18 @@ private async Task RunTestAppAsync(CancellationToken testApplicationCancell // Get the test application lifecycle callbacks to be able to call the before run foreach (ITestApplicationLifecycleCallbacks testApplicationLifecycleCallbacks in ServiceProvider.GetServicesInternal()) { - await testApplicationLifecycleCallbacks.BeforeRunAsync(testApplicationCancellationToken); + await testApplicationLifecycleCallbacks.BeforeRunAsync(testApplicationCancellationToken).ConfigureAwait(false); } } - int exitCode = await InternalRunAsync(); + int exitCode = await InternalRunAsync().ConfigureAwait(false); if (RunTestApplicationLifeCycleCallbacks) { foreach (ITestApplicationLifecycleCallbacks testApplicationLifecycleCallbacks in ServiceProvider.GetServicesInternal()) { - await testApplicationLifecycleCallbacks.AfterRunAsync(exitCode, testApplicationCancellationToken); - await DisposeHelper.DisposeAsync(testApplicationLifecycleCallbacks); + await testApplicationLifecycleCallbacks.AfterRunAsync(exitCode, testApplicationCancellationToken).ConfigureAwait(false); + await DisposeHelper.DisposeAsync(testApplicationLifecycleCallbacks).ConfigureAwait(false); } } @@ -128,13 +128,13 @@ protected static async Task ExecuteRequestAsync(ProxyOutputDevice outputDevice, { CancellationToken testSessionCancellationToken = serviceProvider.GetTestSessionContext().CancellationToken; - await DisplayBeforeSessionStartAsync(outputDevice, testSessionInfo, testSessionCancellationToken); + await DisplayBeforeSessionStartAsync(outputDevice, testSessionInfo, testSessionCancellationToken).ConfigureAwait(false); try { - await NotifyTestSessionStartAsync(testSessionInfo.SessionId, baseMessageBus, serviceProvider, testSessionCancellationToken); - await serviceProvider.GetTestAdapterInvoker().ExecuteAsync(testFramework, client, testSessionCancellationToken); - await NotifyTestSessionEndAsync(testSessionInfo.SessionId, baseMessageBus, serviceProvider, testSessionCancellationToken); + await NotifyTestSessionStartAsync(testSessionInfo.SessionId, baseMessageBus, serviceProvider, testSessionCancellationToken).ConfigureAwait(false); + await serviceProvider.GetTestAdapterInvoker().ExecuteAsync(testFramework, client, testSessionCancellationToken).ConfigureAwait(false); + await NotifyTestSessionEndAsync(testSessionInfo.SessionId, baseMessageBus, serviceProvider, testSessionCancellationToken).ConfigureAwait(false); } catch (OperationCanceledException) when (testSessionCancellationToken.IsCancellationRequested) { @@ -143,33 +143,33 @@ protected static async Task ExecuteRequestAsync(ProxyOutputDevice outputDevice, // We keep the display after session out of the OperationCanceledException catch because we want to notify the IPlatformOutputDevice // also in case of cancellation. Most likely it needs to notify users that the session was canceled. - await DisplayAfterSessionEndRunAsync(outputDevice, testSessionInfo, testSessionCancellationToken); + await DisplayAfterSessionEndRunAsync(outputDevice, testSessionInfo, testSessionCancellationToken).ConfigureAwait(false); } private static async Task DisplayBeforeSessionStartAsync(ProxyOutputDevice outputDevice, ITestSessionContext sessionInfo, CancellationToken cancellationToken) { // Display before session start - await outputDevice.DisplayBeforeSessionStartAsync(); + await outputDevice.DisplayBeforeSessionStartAsync().ConfigureAwait(false); if (outputDevice.OriginalOutputDevice is ITestSessionLifetimeHandler testSessionLifetimeHandler) { await testSessionLifetimeHandler.OnTestSessionStartingAsync( sessionInfo.SessionId, - cancellationToken); + cancellationToken).ConfigureAwait(false); } } private static async Task DisplayAfterSessionEndRunAsync(ProxyOutputDevice outputDevice, ITestSessionContext sessionInfo, CancellationToken cancellationToken) { // Display after session end - await outputDevice.DisplayAfterSessionEndRunAsync(); + await outputDevice.DisplayAfterSessionEndRunAsync().ConfigureAwait(false); // We want to ensure that the output service is the last one to run if (outputDevice.OriginalOutputDevice is ITestSessionLifetimeHandler testSessionLifetimeHandlerFinishing) { await testSessionLifetimeHandlerFinishing.OnTestSessionFinishingAsync( sessionInfo.SessionId, - cancellationToken); + cancellationToken).ConfigureAwait(false); } } @@ -183,17 +183,17 @@ private static async Task NotifyTestSessionStartAsync(SessionUid sessionUid, Bas foreach (ITestSessionLifetimeHandler testSessionLifetimeHandler in testSessionLifetimeHandlersContainer.TestSessionLifetimeHandlers) { - await testSessionLifetimeHandler.OnTestSessionStartingAsync(sessionUid, cancellationToken); + await testSessionLifetimeHandler.OnTestSessionStartingAsync(sessionUid, cancellationToken).ConfigureAwait(false); } // Drain messages generated by the session start notification before to start test execution. - await baseMessageBus.DrainDataAsync(); + await baseMessageBus.DrainDataAsync().ConfigureAwait(false); } private static async Task NotifyTestSessionEndAsync(SessionUid sessionUid, BaseMessageBus baseMessageBus, ServiceProvider serviceProvider, CancellationToken cancellationToken) { // Drain messages generated by the test session execution before to process the session end notification. - await baseMessageBus.DrainDataAsync(); + await baseMessageBus.DrainDataAsync().ConfigureAwait(false); TestSessionLifetimeHandlersContainer? testSessionLifetimeHandlersContainer = serviceProvider.GetService(); if (testSessionLifetimeHandlersContainer is null) @@ -203,15 +203,15 @@ private static async Task NotifyTestSessionEndAsync(SessionUid sessionUid, BaseM foreach (ITestSessionLifetimeHandler testSessionLifetimeHandler in serviceProvider.GetRequiredService().TestSessionLifetimeHandlers) { - await testSessionLifetimeHandler.OnTestSessionFinishingAsync(sessionUid, cancellationToken); + await testSessionLifetimeHandler.OnTestSessionFinishingAsync(sessionUid, cancellationToken).ConfigureAwait(false); // OnTestSessionFinishingAsync could produce information that needs to be handled by others. - await baseMessageBus.DrainDataAsync(); + await baseMessageBus.DrainDataAsync().ConfigureAwait(false); } // We disable after the drain because it's possible that the drain will produce more messages - await baseMessageBus.DrainDataAsync(); - await baseMessageBus.DisableAsync(); + await baseMessageBus.DrainDataAsync().ConfigureAwait(false); + await baseMessageBus.DisableAsync().ConfigureAwait(false); } protected static async Task DisposeServiceProviderAsync(ServiceProvider serviceProvider, Func? filter = null, List? alreadyDisposed = null, bool isProcessShutdown = false) @@ -249,7 +249,7 @@ ITestApplicationLifecycleCallbacks or if (!alreadyDisposed.Contains(service)) { - await DisposeHelper.DisposeAsync(service); + await DisposeHelper.DisposeAsync(service).ConfigureAwait(false); alreadyDisposed.Add(service); } @@ -264,7 +264,7 @@ ITestApplicationLifecycleCallbacks or if (!alreadyDisposed.Contains(dataConsumer)) { - await DisposeHelper.DisposeAsync(dataConsumer); + await DisposeHelper.DisposeAsync(dataConsumer).ConfigureAwait(false); alreadyDisposed.Add(service); } } diff --git a/src/Platform/Microsoft.Testing.Platform/Hosts/ConsoleTestHost.cs b/src/Platform/Microsoft.Testing.Platform/Hosts/ConsoleTestHost.cs index 026b1365d8..f5539c886b 100644 --- a/src/Platform/Microsoft.Testing.Platform/Hosts/ConsoleTestHost.cs +++ b/src/Platform/Microsoft.Testing.Platform/Hosts/ConsoleTestHost.cs @@ -65,13 +65,13 @@ protected override async Task InternalRunAsync() _testHostManager, new MessageBusProxy(), ServiceProvider.GetCommandLineOptions().IsOptionSet(PlatformCommandLineProvider.DiscoverTestsOptionKey), - false)); + false)).ConfigureAwait(false); ITelemetryCollector telemetry = ServiceProvider.GetTelemetryCollector(); ITelemetryInformation telemetryInformation = ServiceProvider.GetTelemetryInformation(); Statistics? statistics = null; string? extensionInformation = null; - await _logger.LogInformationAsync($"Starting test session '{ServiceProvider.GetTestSessionContext().SessionId}'"); + await _logger.LogInformationAsync($"Starting test session '{ServiceProvider.GetTestSessionContext().SessionId}'").ConfigureAwait(false); int exitCode; DateTimeOffset adapterLoadStop = _clock.UtcNow; DateTimeOffset requestExecuteStart = _clock.UtcNow; @@ -86,7 +86,7 @@ await ExecuteRequestAsync( ServiceProvider, ServiceProvider.GetBaseMessageBus(), testFramework, - ClientInfoHost); + ClientInfoHost).ConfigureAwait(false); requestExecuteStop = _clock.UtcNow; // Get the exit code service to be able to set the exit code @@ -94,12 +94,12 @@ await ExecuteRequestAsync( statistics = testApplicationResult.GetStatistics(); exitCode = testApplicationResult.GetProcessExitCode(); - await _logger.LogInformationAsync($"Test session '{ServiceProvider.GetTestSessionContext().SessionId}' ended with exit code '{exitCode}' in {consoleRunStarted.Elapsed}"); + await _logger.LogInformationAsync($"Test session '{ServiceProvider.GetTestSessionContext().SessionId}' ended with exit code '{exitCode}' in {consoleRunStarted.Elapsed}").ConfigureAwait(false); // We collect info about the extensions before the dispose to avoid possible issue with cleanup. if (telemetryInformation.IsEnabled) { - extensionInformation = await ExtensionInformationCollector.CollectAndSerializeToJsonAsync(ServiceProvider); + extensionInformation = await ExtensionInformationCollector.CollectAndSerializeToJsonAsync(ServiceProvider).ConfigureAwait(false); } } catch (OperationCanceledException oc) when (oc.CancellationToken == abortRun) @@ -107,12 +107,12 @@ await ExecuteRequestAsync( requestExecuteStop ??= _clock.UtcNow; exitCode = ExitCodes.TestSessionAborted; - await _logger.LogInformationAsync("Test session canceled."); + await _logger.LogInformationAsync("Test session canceled.").ConfigureAwait(false); } finally { // Cleanup all services - await DisposeServiceProviderAsync(ServiceProvider); + await DisposeServiceProviderAsync(ServiceProvider).ConfigureAwait(false); } if (telemetryInformation.IsEnabled) @@ -140,7 +140,7 @@ await ExecuteRequestAsync( metrics.Add(TelemetryProperties.HostProperties.ExtensionsPropertyName, extensionInformation); } - await telemetry.LogEventAsync(TelemetryEvents.ConsoleTestHostExitEventName, metrics); + await telemetry.LogEventAsync(TelemetryEvents.ConsoleTestHostExitEventName, metrics).ConfigureAwait(false); } return exitCode; diff --git a/src/Platform/Microsoft.Testing.Platform/Hosts/ServerTestHost.cs b/src/Platform/Microsoft.Testing.Platform/Hosts/ServerTestHost.cs index 1292534fa5..bc5168c5c5 100644 --- a/src/Platform/Microsoft.Testing.Platform/Hosts/ServerTestHost.cs +++ b/src/Platform/Microsoft.Testing.Platform/Hosts/ServerTestHost.cs @@ -137,10 +137,10 @@ protected override async Task InternalRunAsync() { try { - await _logger.LogDebugAsync("Starting server mode"); - _messageHandler = await _messageHandlerFactory.CreateMessageHandlerAsync(_testApplicationCancellationTokenSource.CancellationToken); + await _logger.LogDebugAsync("Starting server mode").ConfigureAwait(false); + _messageHandler = await _messageHandlerFactory.CreateMessageHandlerAsync(_testApplicationCancellationTokenSource.CancellationToken).ConfigureAwait(false); - await HandleMessagesAsync(); + await HandleMessagesAsync().ConfigureAwait(false); (_messageHandler as IDisposable)?.Dispose(); } @@ -156,7 +156,7 @@ protected override async Task InternalRunAsync() finally { // Cleanup all services but special one because in the per-call mode we needed to keep them alive for reuse - await DisposeServiceProviderAsync(ServiceProvider); + await DisposeServiceProviderAsync(ServiceProvider).ConfigureAwait(false); } // If the global cancellation is called together with the server closing one the server exited gracefully. @@ -178,7 +178,7 @@ private async Task HandleMessagesAsync() { try { - RpcMessage? message = await _messageHandler.ReadAsync(messageHandlerStopPlusGlobalToken); + RpcMessage? message = await _messageHandler.ReadAsync(messageHandlerStopPlusGlobalToken).ConfigureAwait(false); // In case of issue on underneath handler we expect a null rpc message to signal that we should close // because we're no more able to process things. @@ -195,8 +195,8 @@ private async Task HandleMessagesAsync() // Signal only one time if (!_serverClosingTokenSource.IsCancellationRequested) { - await _logger.LogDebugAsync("Server requested to shutdown"); - await _serverClosingTokenSource.CancelAsync(); + await _logger.LogDebugAsync("Server requested to shutdown").ConfigureAwait(false); + await _serverClosingTokenSource.CancelAsync().ConfigureAwait(false); } // Signal the exit call @@ -205,7 +205,7 @@ private async Task HandleMessagesAsync() // If there're no in-flight request we can close the server if (_clientToServerRequests.IsEmpty) { - await _stopMessageHandler.CancelAsync(); + await _stopMessageHandler.CancelAsync().ConfigureAwait(false); } continue; @@ -248,7 +248,7 @@ private async Task HandleMessagesAsync() _requestCounter.Signal(); // Wait to drain all in-flight requests HandleRequestCoreAsync/CompleteRequest - await _requestCounter.WaitAsync(TimeoutHelper.DefaultHangTimeSpanTimeout, CancellationToken.None); + await _requestCounter.WaitAsync(TimeoutHelper.DefaultHangTimeSpanTimeout, CancellationToken.None).ConfigureAwait(false); } private async Task HandleNotificationAsync(NotificationMessage message, CancellationToken serverClosing) @@ -285,11 +285,11 @@ private async Task HandleNotificationAsync(NotificationMessage message, Cancella // This is intentionally not using PlatformResources.ExceptionDuringCancellationWarningMessage // It's meant for troubleshooting and shouldn't be localized. // The localized message that is user-facing will be displayed in the DisplayAsync call next line. - await _logger.LogWarningAsync($"Exception during the cancellation of request id '{args.CancelRequestId}'"); + await _logger.LogWarningAsync($"Exception during the cancellation of request id '{args.CancelRequestId}'").ConfigureAwait(false); await ServiceProvider.GetOutputDevice().DisplayAsync( this, - new WarningMessageOutputDeviceData(string.Format(CultureInfo.InvariantCulture, PlatformResources.ExceptionDuringCancellationWarningMessage, args.CancelRequestId))); + new WarningMessageOutputDeviceData(string.Format(CultureInfo.InvariantCulture, PlatformResources.ExceptionDuringCancellationWarningMessage, args.CancelRequestId))).ConfigureAwait(false); } } @@ -310,7 +310,7 @@ private async Task HandleRequestAsync(RequestMessage request, CancellationToken { try { - await SendErrorAsync(reqId: request.Id, errorCode: ErrorCodes.InvalidRequest, message: "Server is closing", data: null, _testApplicationCancellationTokenSource.CancellationToken); + await SendErrorAsync(reqId: request.Id, errorCode: ErrorCodes.InvalidRequest, message: "Server is closing", data: null, _testApplicationCancellationTokenSource.CancellationToken).ConfigureAwait(false); } finally { @@ -330,8 +330,8 @@ private async Task HandleRequestAsync(RequestMessage request, CancellationToken try { - object response = await HandleRequestCoreAsync(request, rpcState); - await SendResponseAsync(reqId: request.Id, result: response, _testApplicationCancellationTokenSource.CancellationToken); + object response = await HandleRequestCoreAsync(request, rpcState).ConfigureAwait(false); + await SendResponseAsync(reqId: request.Id, result: response, _testApplicationCancellationTokenSource.CancellationToken).ConfigureAwait(false); CompleteRequest(ref _clientToServerRequests, request.Id, completion => completion.TrySetResult(response)); } catch (OperationCanceledException e) @@ -342,12 +342,12 @@ private async Task HandleRequestAsync(RequestMessage request, CancellationToken ? (string.Empty, ErrorCodes.RequestCanceled) : (e.ToString(), ErrorCodes.RequestCanceled); - await SendErrorAsync(reqId: request.Id, errorCode: errorCode, message: errorMessage, data: null, _testApplicationCancellationTokenSource.CancellationToken); + await SendErrorAsync(reqId: request.Id, errorCode: errorCode, message: errorMessage, data: null, _testApplicationCancellationTokenSource.CancellationToken).ConfigureAwait(false); CompleteRequest(ref _clientToServerRequests, request.Id, completion => completion.TrySetCanceled()); } catch (Exception e) { - await SendErrorAsync(reqId: request.Id, errorCode: 0, message: e.ToString(), data: null, _testApplicationCancellationTokenSource.CancellationToken); + await SendErrorAsync(reqId: request.Id, errorCode: 0, message: e.ToString(), data: null, _testApplicationCancellationTokenSource.CancellationToken).ConfigureAwait(false); CompleteRequest(ref _clientToServerRequests, request.Id, completion => completion.SetException(e)); } } @@ -393,7 +393,7 @@ private async Task HandleRequestCoreAsync(RequestMessage message, RpcInv AssertInitialized(); - await _logger.LogDebugAsync($"Received {message.Method} request"); + await _logger.LogDebugAsync($"Received {message.Method} request").ConfigureAwait(false); switch (message.Method, message.Params) { @@ -401,7 +401,7 @@ private async Task HandleRequestCoreAsync(RequestMessage message, RpcInv { _client = new(args.ClientInfo.Name, args.ClientInfo.Version); _clientInfoService = new ClientInfoService(args.ClientInfo.Name, args.ClientInfo.Version); - await _logger.LogDebugAsync($"Connection established with '{_client.Id}', protocol version {_client.Version}"); + await _logger.LogDebugAsync($"Connection established with '{_client.Id}', protocol version {_client.Version}").ConfigureAwait(false); INamedFeatureCapability? namedFeatureCapability = ServiceProvider.GetTestFrameworkCapabilities().GetCapability(); return new InitializeResponseArgs( @@ -419,12 +419,12 @@ private async Task HandleRequestCoreAsync(RequestMessage message, RpcInv case (JsonRpcMethods.TestingDiscoverTests, DiscoverRequestArgs args): { - return await ExecuteRequestAsync(args, JsonRpcMethods.TestingDiscoverTests, perRequestServiceProvider); + return await ExecuteRequestAsync(args, JsonRpcMethods.TestingDiscoverTests, perRequestServiceProvider).ConfigureAwait(false); } case (JsonRpcMethods.TestingRunTests, RunRequestArgs args): { - return await ExecuteRequestAsync(args, JsonRpcMethods.TestingRunTests, perRequestServiceProvider); + return await ExecuteRequestAsync(args, JsonRpcMethods.TestingRunTests, perRequestServiceProvider).ConfigureAwait(false); } default: @@ -472,7 +472,7 @@ private async Task ExecuteRequestAsync(RequestArgsBase args, s DateTimeOffset adapterLoadStart = _clock.UtcNow; ProxyOutputDevice outputDevice = ServiceProvider.GetRequiredService(); - await outputDevice.InitializeAsync(this); + await outputDevice.InitializeAsync(this).ConfigureAwait(false); // Build the per request adapter ITestFramework perRequestTestFramework = await _buildTestFrameworkAsync(new TestFrameworkBuilderData( @@ -486,7 +486,7 @@ private async Task ExecuteRequestAsync(RequestArgsBase args, s _testSessionManager, new MessageBusProxy(), method == JsonRpcMethods.TestingDiscoverTests, - true)); + true)).ConfigureAwait(false); DateTimeOffset adapterLoadStop = _clock.UtcNow; @@ -504,7 +504,7 @@ await ExecuteRequestAsync( perRequestServiceProvider, perRequestServiceProvider.GetBaseMessageBus(), perRequestTestFramework, - _client); + _client).ConfigureAwait(false); // Check if there was a test adapter testSession failure ITestApplicationProcessExitCode testApplicationResult = perRequestServiceProvider.GetTestApplicationProcessExitCode(); @@ -516,7 +516,7 @@ await ExecuteRequestAsync( // Verify request cancellation, above the chain the exception will be // catch and propagated as correct json rpc error perRequestTestSessionContext.CancellationToken.ThrowIfCancellationRequested(); - await SendTestUpdateCompleteAsync(args.RunId); + await SendTestUpdateCompleteAsync(args.RunId).ConfigureAwait(false); requestExecuteStop = _clock.UtcNow; } finally @@ -525,7 +525,7 @@ await ExecuteRequestAsync( // Cleanup all services // We skip all services that are "cloned" per call because are reused and will be disposed on shutdown. - await DisposeServiceProviderAsync(perRequestServiceProvider, obj => !ServiceProvider.Services.Contains(obj)); + await DisposeServiceProviderAsync(perRequestServiceProvider, obj => !ServiceProvider.Services.Contains(obj)).ConfigureAwait(false); // We need to dispose this service manually because the shared DisposeServiceProviderAsync skip some special service like the ITestApplicationCooperativeLifetimeService // that needs to be disposed at process exits. @@ -553,7 +553,7 @@ await ExecuteRequestAsync( testNodeUpdateProcessor.GetTestNodeStatistics().TotalDiscoveredTests) : throw new NotImplementedException($"Request not implemented '{method}'"); - await _telemetryService.LogEventAsync(TelemetryEvents.TestsRunEventName, metadata); + await _telemetryService.LogEventAsync(TelemetryEvents.TestsRunEventName, metadata).ConfigureAwait(false); return method == JsonRpcMethods.TestingRunTests ? new RunResponseArgs([.. testNodeUpdateProcessor.Artifacts]) @@ -604,9 +604,9 @@ private async Task SendErrorAsync(int reqId, int errorCode, string message, obje AssertInitialized(); ErrorMessage error = new(reqId, errorCode, message, data); - using (await _messageMonitor.LockAsync(cancellationToken)) + using (await _messageMonitor.LockAsync(cancellationToken).ConfigureAwait(false)) { - await _messageHandler.WriteRequestAsync(error, cancellationToken); + await _messageHandler.WriteRequestAsync(error, cancellationToken).ConfigureAwait(false); } } @@ -615,9 +615,9 @@ private async Task SendResponseAsync(int reqId, object result, CancellationToken AssertInitialized(); ResponseMessage response = new(reqId, result); - using (await _messageMonitor.LockAsync(cancellationToken)) + using (await _messageMonitor.LockAsync(cancellationToken).ConfigureAwait(false)) { - await _messageHandler.WriteRequestAsync(response, cancellationToken); + await _messageHandler.WriteRequestAsync(response, cancellationToken).ConfigureAwait(false); } } @@ -633,10 +633,10 @@ private async Task SendMessageAsync(string method, object? @params, Cancellation { NotificationMessage notification = new(method, @params); - using (await _messageMonitor.LockAsync(cancellationToken)) + using (await _messageMonitor.LockAsync(cancellationToken).ConfigureAwait(false)) { AssertInitialized(); - await _messageHandler.WriteRequestAsync(notification, cancellationToken); + await _messageHandler.WriteRequestAsync(notification, cancellationToken).ConfigureAwait(false); } } catch @@ -664,31 +664,31 @@ public void Dispose() } internal async Task SendTestUpdateCompleteAsync(Guid runId) - => await SendTestUpdateAsync(new TestNodeStateChangedEventArgs(runId, Changes: null)); + => await SendTestUpdateAsync(new TestNodeStateChangedEventArgs(runId, Changes: null)).ConfigureAwait(false); public async Task SendTestUpdateAsync(TestNodeStateChangedEventArgs update) => await SendMessageAsync( method: JsonRpcMethods.TestingTestUpdatesTests, @params: update, - _testApplicationCancellationTokenSource.CancellationToken); + _testApplicationCancellationTokenSource.CancellationToken).ConfigureAwait(false); public async Task SendTelemetryEventUpdateAsync(TelemetryEventArgs args) => await SendMessageAsync( method: JsonRpcMethods.TelemetryUpdate, @params: args, - _testApplicationCancellationTokenSource.CancellationToken); + _testApplicationCancellationTokenSource.CancellationToken).ConfigureAwait(false); public async Task SendClientLaunchDebuggerAsync(ProcessInfoArgs args) => await SendRequestAsync( method: JsonRpcMethods.ClientLaunchDebugger, @params: args, - _testApplicationCancellationTokenSource.CancellationToken); + _testApplicationCancellationTokenSource.CancellationToken).ConfigureAwait(false); public async Task SendClientAttachDebuggerAsync(AttachDebuggerInfoArgs args) => await SendRequestAsync( method: JsonRpcMethods.ClientAttachDebugger, @params: args, - _testApplicationCancellationTokenSource.CancellationToken); + _testApplicationCancellationTokenSource.CancellationToken).ConfigureAwait(false); private async Task SendRequestAsync(string method, object @params, CancellationToken cancellationToken) { @@ -701,14 +701,14 @@ private async Task SendRequestAsync(string method, object @params, CancellationT // Add the request to the counter _requestCounter.AddCount(); - await _messageHandler.WriteRequestAsync(request, cancellationToken); + await _messageHandler.WriteRequestAsync(request, cancellationToken).ConfigureAwait(false); using (cancellationToken.Register(() => _ = SendMessageAsync( JsonRpcMethods.CancelRequest, new CancelRequestArgs(requestId), cancellationToken))) { - await invocationState.CompletionSource.Task; + await invocationState.CompletionSource.Task.ConfigureAwait(false); } } @@ -724,7 +724,7 @@ await SendMessageAsync( // We could receive some log messages after the exit, a real sample is if telemetry provider is too slow and we log a warning. checkServerExit: true, - rethrowException: false); + rethrowException: false).ConfigureAwait(false); break; } } diff --git a/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostBuilder.cs b/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostBuilder.cs index bd38701961..8ace6b4971 100644 --- a/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostBuilder.cs +++ b/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostBuilder.cs @@ -115,7 +115,7 @@ public async Task BuildAsync( if (logger is not null) { - await logger.LogInformationAsync($"Setting RegisterEnvironmentVariablesConfigurationSource: '{testApplicationOptions.Configuration.ConfigurationSources.RegisterEnvironmentVariablesConfigurationSource}'"); + await logger.LogInformationAsync($"Setting RegisterEnvironmentVariablesConfigurationSource: '{testApplicationOptions.Configuration.ConfigurationSources.RegisterEnvironmentVariablesConfigurationSource}'").ConfigureAwait(false); } // By default the env var configuration source is enabled, check if we have to disable it. @@ -128,7 +128,7 @@ public async Task BuildAsync( Configuration.AddConfigurationSource(() => new JsonConfigurationSource(_testApplicationModuleInfo, _fileSystem, loggingState.FileLoggerProvider)); // Build the IConfiguration - we need special treatment because the configuration is needed by extensions. - var configuration = (AggregatedConfiguration)await ((ConfigurationManager)Configuration).BuildAsync(loggingState.FileLoggerProvider, loggingState.CommandLineParseResult); + var configuration = (AggregatedConfiguration)await ((ConfigurationManager)Configuration).BuildAsync(loggingState.FileLoggerProvider, loggingState.CommandLineParseResult).ConfigureAwait(false); serviceProvider.TryAddService(configuration); // Current test platform is picky on unhandled exception, we will tear down the process in that case. @@ -153,7 +153,7 @@ public async Task BuildAsync( if (logger is not null) { - await logger.LogInformationAsync($"Setting PlatformExitProcessOnUnhandledException: '{exitProcessOnUnhandledException}', config file: {isFileConfiguredToFailFast} environment variable: {isEnvConfiguredToFailFast}"); + await logger.LogInformationAsync($"Setting PlatformExitProcessOnUnhandledException: '{exitProcessOnUnhandledException}', config file: {isFileConfiguredToFailFast} environment variable: {isEnvConfiguredToFailFast}").ConfigureAwait(false); } if (exitProcessOnUnhandledException) @@ -183,7 +183,7 @@ public async Task BuildAsync( // Build the command line service - we need special treatment because is possible that an extension query it during the creation. // Add Retry default argument commandlines - CommandLineHandler commandLineHandler = await ((CommandLineManager)CommandLine).BuildAsync(loggingState.CommandLineParseResult, serviceProvider); + CommandLineHandler commandLineHandler = await ((CommandLineManager)CommandLine).BuildAsync(loggingState.CommandLineParseResult, serviceProvider).ConfigureAwait(false); // Set the concrete command line options to the proxy. commandLineOptionsProxy.SetCommandLineOptions(commandLineHandler); @@ -195,7 +195,7 @@ public async Task BuildAsync( bool hasServerFlag = commandLineHandler.TryGetOptionArgumentList(PlatformCommandLineProvider.ServerOptionKey, out string[]? protocolName); bool isJsonRpcProtocol = protocolName is null || protocolName.Length == 0 || protocolName[0].Equals(PlatformCommandLineProvider.JsonRpcProtocolName, StringComparison.OrdinalIgnoreCase); - ProxyOutputDevice proxyOutputDevice = await _outputDisplay.BuildAsync(serviceProvider, hasServerFlag && isJsonRpcProtocol); + ProxyOutputDevice proxyOutputDevice = await _outputDisplay.BuildAsync(serviceProvider, hasServerFlag && isJsonRpcProtocol).ConfigureAwait(false); // Add FileLoggerProvider if needed if (loggingState.FileLoggerProvider is not null) @@ -207,15 +207,15 @@ public async Task BuildAsync( ICommandLineOptions commandLineOptions = serviceProvider.GetCommandLineOptions(); // Build the logger factory. - ILoggerFactory loggerFactory = await ((LoggingManager)Logging).BuildAsync(serviceProvider, loggingState.LogLevel, systemMonitor); + ILoggerFactory loggerFactory = await ((LoggingManager)Logging).BuildAsync(serviceProvider, loggingState.LogLevel, systemMonitor).ConfigureAwait(false); // Set the concrete logger factory loggerFactoryProxy.SetLoggerFactory(loggerFactory); // Initialize the output device if needed. - if (await proxyOutputDevice.OriginalOutputDevice.IsEnabledAsync()) + if (await proxyOutputDevice.OriginalOutputDevice.IsEnabledAsync().ConfigureAwait(false)) { - await proxyOutputDevice.OriginalOutputDevice.TryInitializeAsync(); + await proxyOutputDevice.OriginalOutputDevice.TryInitializeAsync().ConfigureAwait(false); } // Add the platform output device to the service provider for both modes. @@ -226,7 +226,7 @@ public async Task BuildAsync( ITestFrameworkCapabilities testFrameworkCapabilities = TestFramework.TestFrameworkCapabilitiesFactory(serviceProvider); if (testFrameworkCapabilities is IAsyncInitializableExtension testFrameworkCapabilitiesAsyncInitializable) { - await testFrameworkCapabilitiesAsyncInitializable.InitializeAsync(); + await testFrameworkCapabilitiesAsyncInitializable.InitializeAsync().ConfigureAwait(false); } // Register the test framework capabilities to be used by services @@ -237,13 +237,13 @@ public async Task BuildAsync( loggingState.CommandLineParseResult, commandLineHandler.SystemCommandLineOptionsProviders, commandLineHandler.ExtensionsCommandLineOptionsProviders, - commandLineHandler); + commandLineHandler).ConfigureAwait(false); if (!loggingState.CommandLineParseResult.HasTool && !commandLineValidationResult.IsValid) { - await DisplayBannerIfEnabledAsync(loggingState, proxyOutputDevice, testFrameworkCapabilities); - await proxyOutputDevice.DisplayAsync(commandLineHandler, new ErrorMessageOutputDeviceData(commandLineValidationResult.ErrorMessage)); - await commandLineHandler.PrintHelpAsync(proxyOutputDevice); + await DisplayBannerIfEnabledAsync(loggingState, proxyOutputDevice, testFrameworkCapabilities).ConfigureAwait(false); + await proxyOutputDevice.DisplayAsync(commandLineHandler, new ErrorMessageOutputDeviceData(commandLineValidationResult.ErrorMessage)).ConfigureAwait(false); + await commandLineHandler.PrintHelpAsync(proxyOutputDevice).ConfigureAwait(false); return new InformativeCommandLineTestHost(ExitCodes.InvalidCommandLine, serviceProvider); } @@ -275,15 +275,15 @@ public async Task BuildAsync( // here we ensure to override the result directory if user passed the argument --results-directory in command line. // After this check users can get the result directory using IConfiguration["platformOptions:resultDirectory"] or the // extension method helper serviceProvider.GetConfiguration() - await configuration.CheckTestResultsDirectoryOverrideAndCreateItAsync(loggingState.FileLoggerProvider); + await configuration.CheckTestResultsDirectoryOverrideAndCreateItAsync(loggingState.FileLoggerProvider).ConfigureAwait(false); // Display banner now because we need capture the output in case of MSBuild integration and we want to forward // to file disc also the banner, so at this point we need to have all services and configuration(result directory) built. - await DisplayBannerIfEnabledAsync(loggingState, proxyOutputDevice, testFrameworkCapabilities); + await DisplayBannerIfEnabledAsync(loggingState, proxyOutputDevice, testFrameworkCapabilities).ConfigureAwait(false); // Add global telemetry service. // Add at this point or the telemetry banner appearance order will be wrong, we want the testing app banner before the telemetry banner. - ITelemetryCollector telemetryService = await ((TelemetryManager)Telemetry).BuildAsync(serviceProvider, loggerFactory, testApplicationOptions); + ITelemetryCollector telemetryService = await ((TelemetryManager)Telemetry).BuildAsync(serviceProvider, loggerFactory, testApplicationOptions).ConfigureAwait(false); serviceProvider.TryAddService(telemetryService); AddApplicationMetadata(serviceProvider, builderMetrics); @@ -312,7 +312,7 @@ public async Task BuildAsync( // Add the platform output device to the service provider. var toolsServiceProvider = (ServiceProvider)serviceProvider.Clone(); toolsServiceProvider.TryAddService(proxyOutputDevice); - IReadOnlyList toolsInformation = await ((ToolsManager)Tools).BuildAsync(toolsServiceProvider); + IReadOnlyList toolsInformation = await ((ToolsManager)Tools).BuildAsync(toolsServiceProvider).ConfigureAwait(false); if (loggingState.CommandLineParseResult.HasTool) { // Add the platform output device to the service provider. @@ -324,13 +324,13 @@ await LogTestHostCreatedAsync( serviceProvider, mode: TelemetryProperties.ApplicationMode.Tool, metrics: builderMetrics, - stop: systemClock.UtcNow); + stop: systemClock.UtcNow).ConfigureAwait(false); return toolsTestHost; } var pushOnlyProtocol = new DotnetTestConnection(commandLineHandler, processHandler, environment, _testApplicationModuleInfo, testApplicationCancellationTokenSource); - await pushOnlyProtocol.AfterCommonServiceSetupAsync(); + await pushOnlyProtocol.AfterCommonServiceSetupAsync().ConfigureAwait(false); if (pushOnlyProtocol.IsServerMode) { serviceProvider.AddService(pushOnlyProtocol); @@ -341,11 +341,11 @@ await LogTestHostCreatedAsync( { if (pushOnlyProtocol.IsServerMode) { - await pushOnlyProtocol.HelpInvokedAsync(); + await pushOnlyProtocol.HelpInvokedAsync().ConfigureAwait(false); } else { - await commandLineHandler.PrintHelpAsync(proxyOutputDevice, toolsInformation); + await commandLineHandler.PrintHelpAsync(proxyOutputDevice, toolsInformation).ConfigureAwait(false); } return new InformativeCommandLineTestHost(0, serviceProvider); @@ -354,16 +354,16 @@ await LogTestHostCreatedAsync( // If --info is invoked we return if (commandLineHandler.IsInfoInvoked()) { - await commandLineHandler.PrintInfoAsync(proxyOutputDevice, toolsInformation); + await commandLineHandler.PrintInfoAsync(proxyOutputDevice, toolsInformation).ConfigureAwait(false); return new InformativeCommandLineTestHost(0, serviceProvider); } // ======= TEST HOST ORCHESTRATOR ======== // - TestHostOrchestratorConfiguration testHostOrchestratorConfiguration = await TestHostOrchestratorManager.BuildAsync(serviceProvider); + TestHostOrchestratorConfiguration testHostOrchestratorConfiguration = await TestHostOrchestratorManager.BuildAsync(serviceProvider).ConfigureAwait(false); if (testHostOrchestratorConfiguration.TestHostOrchestrators.Length > 0 && !commandLineHandler.IsOptionSet(PlatformCommandLineProvider.DiscoverTestsOptionKey)) { policiesService.ProcessRole = TestProcessRole.TestHostOrchestrator; - await proxyOutputDevice.HandleProcessRoleAsync(TestProcessRole.TestHostOrchestrator); + await proxyOutputDevice.HandleProcessRoleAsync(TestProcessRole.TestHostOrchestrator).ConfigureAwait(false); return new TestHostOrchestratorHost(testHostOrchestratorConfiguration, serviceProvider); } @@ -395,19 +395,19 @@ await LogTestHostCreatedAsync( // Add the message bus proxy specific for the launchers. testHostControllersServiceProvider.TryAddService(new MessageBusProxy()); - TestHostControllerConfiguration testHostControllers = await ((TestHostControllersManager)TestHostControllers).BuildAsync(testHostControllersServiceProvider); + TestHostControllerConfiguration testHostControllers = await ((TestHostControllersManager)TestHostControllers).BuildAsync(testHostControllersServiceProvider).ConfigureAwait(false); if (testHostControllers.RequireProcessRestart) { testHostControllerInfo.IsCurrentProcessTestHostController = true; policiesService.ProcessRole = TestProcessRole.TestHostController; - await proxyOutputDevice.HandleProcessRoleAsync(TestProcessRole.TestHostController); + await proxyOutputDevice.HandleProcessRoleAsync(TestProcessRole.TestHostController).ConfigureAwait(false); TestHostControllersTestHost testHostControllersTestHost = new(testHostControllers, testHostControllersServiceProvider, passiveNode, systemEnvironment, loggerFactory, systemClock); await LogTestHostCreatedAsync( serviceProvider, mode: TelemetryProperties.ApplicationMode.TestHostControllers, metrics: builderMetrics, - stop: systemClock.UtcNow); + stop: systemClock.UtcNow).ConfigureAwait(false); return testHostControllersTestHost; } @@ -415,7 +415,7 @@ await LogTestHostCreatedAsync( // ======= TEST HOST MODE ======== // policiesService.ProcessRole = TestProcessRole.TestHost; - await proxyOutputDevice.HandleProcessRoleAsync(TestProcessRole.TestHost); + await proxyOutputDevice.HandleProcessRoleAsync(TestProcessRole.TestHost).ConfigureAwait(false); // Setup the test host working folder. // Out of the test host controller extension the current working directory is the test host working directory. @@ -432,11 +432,11 @@ await LogTestHostCreatedAsync( loggerFactory.CreateLogger(nameof(ConnectToTestHostProcessMonitorIfAvailableAsync)), testHostControllerInfo, configuration, - systemEnvironment); + systemEnvironment).ConfigureAwait(false); // Build and register the test application lifecycle callbacks. ITestApplicationLifecycleCallbacks[] testApplicationLifecycleCallback = - await ((TestHostManager)TestHost).BuildTestApplicationLifecycleCallbackAsync(serviceProvider); + await ((TestHostManager)TestHost).BuildTestApplicationLifecycleCallbackAsync(serviceProvider).ConfigureAwait(false); serviceProvider.AddServices(testApplicationLifecycleCallback); // ServerMode and Console mode uses different host @@ -461,21 +461,21 @@ await LogTestHostCreatedAsync( serviceProvider, mode: TelemetryProperties.ApplicationMode.Server, metrics: builderMetrics, - stop: systemClock.UtcNow); + stop: systemClock.UtcNow).ConfigureAwait(false); return actualTestHost; } else { // Add custom ITestExecutionFilterFactory to the service list if available - ActionResult testExecutionFilterFactoryResult = await ((TestHostManager)TestHost).TryBuildTestExecutionFilterFactoryAsync(serviceProvider); + ActionResult testExecutionFilterFactoryResult = await ((TestHostManager)TestHost).TryBuildTestExecutionFilterFactoryAsync(serviceProvider).ConfigureAwait(false); if (testExecutionFilterFactoryResult.IsSuccess) { serviceProvider.TryAddService(testExecutionFilterFactoryResult.Result); } // Add custom ITestExecutionFilterFactory to the service list if available - ActionResult testAdapterInvokerBuilderResult = await ((TestHostManager)TestHost).TryBuildTestAdapterInvokerAsync(serviceProvider); + ActionResult testAdapterInvokerBuilderResult = await ((TestHostManager)TestHost).TryBuildTestAdapterInvokerAsync(serviceProvider).ConfigureAwait(false); if (testAdapterInvokerBuilderResult.IsSuccess) { serviceProvider.TryAddService(testAdapterInvokerBuilderResult.Result); @@ -506,7 +506,7 @@ await LogTestHostCreatedAsync( serviceProvider, mode: TelemetryProperties.ApplicationMode.Console, metrics: builderMetrics, - stop: systemClock.UtcNow); + stop: systemClock.UtcNow).ConfigureAwait(false); #pragma warning restore SA1118 // Parameter should not span multiple lines return actualTestHost; @@ -537,21 +537,21 @@ await LogTestHostCreatedAsync( client.RegisterAllSerializers(); // Connect to the monitor - await logger.LogDebugAsync($"Connecting to named pipe '{pipeName}'"); + await logger.LogDebugAsync($"Connecting to named pipe '{pipeName}'").ConfigureAwait(false); string? seconds = configuration[PlatformConfigurationConstants.PlatformTestHostControllersManagerNamedPipeClientConnectTimeoutSeconds]; // Default timeout is 30 seconds int timeoutSeconds = seconds is null ? TimeoutHelper.DefaultHangTimeoutSeconds : int.Parse(seconds, CultureInfo.InvariantCulture); - await logger.LogDebugAsync($"Setting PlatformTestHostControllersManagerNamedPipeClientConnectTimeoutSeconds '{timeoutSeconds}'"); + await logger.LogDebugAsync($"Setting PlatformTestHostControllersManagerNamedPipeClientConnectTimeoutSeconds '{timeoutSeconds}'").ConfigureAwait(false); using CancellationTokenSource timeout = new(TimeSpan.FromSeconds(timeoutSeconds)); - await client.ConnectAsync(timeout.Token); - await logger.LogDebugAsync($"Connected to named pipe '{pipeName}'"); + await client.ConnectAsync(timeout.Token).ConfigureAwait(false); + await logger.LogDebugAsync($"Connected to named pipe '{pipeName}'").ConfigureAwait(false); // Send the PID using IProcess currentProcess = processHandler.GetCurrentProcess(); await client.RequestReplyAsync( new TestHostProcessPIDRequest(currentProcess.Id), - testApplicationCancellationTokenSource.CancellationToken); + testApplicationCancellationTokenSource.CancellationToken).ConfigureAwait(false); return client; } @@ -612,7 +612,7 @@ private static async Task LogTestHostCreatedAsync( [TelemetryProperties.HostProperties.BuildBuilderStop] = stop, [TelemetryProperties.HostProperties.CreateBuilderStop] = stop, }; - await telemetryService.LogEventAsync(TelemetryEvents.TestHostBuiltEventName, metricsObj); + await telemetryService.LogEventAsync(TelemetryEvents.TestHostBuiltEventName, metricsObj).ConfigureAwait(false); } } @@ -628,27 +628,27 @@ private static async Task BuildTestFrameworkAsync(TestFrameworkB if (pushOnlyProtocol?.IsServerMode == true) { - pushOnlyProtocolDataConsumer = await pushOnlyProtocol.GetDataConsumerAsync(); + pushOnlyProtocolDataConsumer = await pushOnlyProtocol.GetDataConsumerAsync().ConfigureAwait(false); } // Build and register "common non special" services - we need special treatment because extensions can start to log during the // creations and we could lose interesting diagnostic information. List dataConsumersBuilder = []; - await RegisterAsServiceOrConsumerOrBothAsync(testFrameworkBuilderData.PlatformOutputDisplayService, serviceProvider, dataConsumersBuilder); - await RegisterAsServiceOrConsumerOrBothAsync(testFrameworkBuilderData.TestExecutionRequestFactory, serviceProvider, dataConsumersBuilder); - await RegisterAsServiceOrConsumerOrBothAsync(testFrameworkBuilderData.TestExecutionRequestInvoker, serviceProvider, dataConsumersBuilder); - await RegisterAsServiceOrConsumerOrBothAsync(testFrameworkBuilderData.TestExecutionFilterFactory, serviceProvider, dataConsumersBuilder); + await RegisterAsServiceOrConsumerOrBothAsync(testFrameworkBuilderData.PlatformOutputDisplayService, serviceProvider, dataConsumersBuilder).ConfigureAwait(false); + await RegisterAsServiceOrConsumerOrBothAsync(testFrameworkBuilderData.TestExecutionRequestFactory, serviceProvider, dataConsumersBuilder).ConfigureAwait(false); + await RegisterAsServiceOrConsumerOrBothAsync(testFrameworkBuilderData.TestExecutionRequestInvoker, serviceProvider, dataConsumersBuilder).ConfigureAwait(false); + await RegisterAsServiceOrConsumerOrBothAsync(testFrameworkBuilderData.TestExecutionFilterFactory, serviceProvider, dataConsumersBuilder).ConfigureAwait(false); // Create the test framework adapter ITestFrameworkCapabilities testFrameworkCapabilities = serviceProvider.GetTestFrameworkCapabilities(); ITestFramework testFramework = testFrameworkBuilderData.TestFrameworkManager.TestFrameworkFactory(testFrameworkCapabilities, serviceProvider); - await testFramework.TryInitializeAsync(); + await testFramework.TryInitializeAsync().ConfigureAwait(false); serviceProvider.AllowTestAdapterFrameworkRegistration = true; try { - await RegisterAsServiceOrConsumerOrBothAsync(new TestFrameworkProxy(testFramework), serviceProvider, dataConsumersBuilder); + await RegisterAsServiceOrConsumerOrBothAsync(new TestFrameworkProxy(testFramework), serviceProvider, dataConsumersBuilder).ConfigureAwait(false); } finally { @@ -663,8 +663,8 @@ private static async Task BuildTestFrameworkAsync(TestFrameworkB { // We keep the bag of the already created composite service factory to reuse the instance. List newBuiltCompositeServices = []; - (IExtension Consumer, int RegistrationOrder)[] consumers = await testFrameworkBuilderData.TestSessionManager.BuildDataConsumersAsync(serviceProvider, newBuiltCompositeServices); - (IExtension TestSessionLifetimeHandler, int RegistrationOrder)[] sessionLifeTimeHandlers = await testFrameworkBuilderData.TestSessionManager.BuildTestSessionLifetimeHandleAsync(serviceProvider, newBuiltCompositeServices); + (IExtension Consumer, int RegistrationOrder)[] consumers = await testFrameworkBuilderData.TestSessionManager.BuildDataConsumersAsync(serviceProvider, newBuiltCompositeServices).ConfigureAwait(false); + (IExtension TestSessionLifetimeHandler, int RegistrationOrder)[] sessionLifeTimeHandlers = await testFrameworkBuilderData.TestSessionManager.BuildTestSessionLifetimeHandleAsync(serviceProvider, newBuiltCompositeServices).ConfigureAwait(false); // Register the test session lifetime handlers for the notifications testSessionLifetimeHandlers.AddRange(sessionLifeTimeHandlers.OrderBy(x => x.RegistrationOrder).Select(x => (ITestSessionLifetimeHandler)x.TestSessionLifetimeHandler)); @@ -674,11 +674,11 @@ private static async Task BuildTestFrameworkAsync(TestFrameworkB { if (testhostExtension.Extension is IDataConsumer) { - await RegisterAsServiceOrConsumerOrBothAsync(testhostExtension.Extension, serviceProvider, dataConsumersBuilder); + await RegisterAsServiceOrConsumerOrBothAsync(testhostExtension.Extension, serviceProvider, dataConsumersBuilder).ConfigureAwait(false); } else { - await AddServiceIfNotSkippedAsync(testhostExtension.Extension, serviceProvider); + await AddServiceIfNotSkippedAsync(testhostExtension.Extension, serviceProvider).ConfigureAwait(false); } } } @@ -692,7 +692,7 @@ private static async Task BuildTestFrameworkAsync(TestFrameworkB testSessionLifetimeHandlers.Add(handler); } - await RegisterAsServiceOrConsumerOrBothAsync(consumerService, serviceProvider, dataConsumersBuilder); + await RegisterAsServiceOrConsumerOrBothAsync(consumerService, serviceProvider, dataConsumersBuilder).ConfigureAwait(false); } // Register the test session lifetime handlers container @@ -708,7 +708,7 @@ private static async Task BuildTestFrameworkAsync(TestFrameworkB // Allow the ITestApplicationProcessExitCode to subscribe as IDataConsumer ITestApplicationProcessExitCode testApplicationResult = serviceProvider.GetRequiredService(); - await RegisterAsServiceOrConsumerOrBothAsync(testApplicationResult, serviceProvider, dataConsumersBuilder); + await RegisterAsServiceOrConsumerOrBothAsync(testApplicationResult, serviceProvider, dataConsumersBuilder).ConfigureAwait(false); // We register the data consumer handler if we're connected to the dotnet test pipe if (pushOnlyProtocolDataConsumer is not null) @@ -722,7 +722,7 @@ private static async Task BuildTestFrameworkAsync(TestFrameworkB serviceProvider.GetRequiredService(), serviceProvider.GetTestApplicationCancellationTokenSource()); - if (await abortForMaxFailedTestsExtension.IsEnabledAsync()) + if (await abortForMaxFailedTestsExtension.IsEnabledAsync().ConfigureAwait(false)) { dataConsumersBuilder.Add(abortForMaxFailedTestsExtension); } @@ -735,7 +735,7 @@ private static async Task BuildTestFrameworkAsync(TestFrameworkB serviceProvider.GetTask(), serviceProvider.GetLoggerFactory(), serviceProvider.GetEnvironment()); - await concreteMessageBusService.InitAsync(); + await concreteMessageBusService.InitAsync().ConfigureAwait(false); testFrameworkBuilderData.MessageBusProxy.SetBuiltMessageBus(concreteMessageBusService); return testFramework; @@ -752,7 +752,7 @@ private static async Task AddServiceIfNotSkippedAsync(object service, ServicePro { if (service is IExtension extension) { - if (await extension.IsEnabledAsync()) + if (await extension.IsEnabledAsync().ConfigureAwait(false)) { serviceProvider.TryAddService(service); } @@ -768,7 +768,7 @@ private static async Task RegisterAsServiceOrConsumerOrBothAsync(object service, { if (service is IDataConsumer dataConsumer) { - if (!await dataConsumer.IsEnabledAsync()) + if (!await dataConsumer.IsEnabledAsync().ConfigureAwait(false)) { return; } @@ -781,7 +781,7 @@ private static async Task RegisterAsServiceOrConsumerOrBothAsync(object service, return; } - await AddServiceIfNotSkippedAsync(service, serviceProvider); + await AddServiceIfNotSkippedAsync(service, serviceProvider).ConfigureAwait(false); } private async Task DisplayBannerIfEnabledAsync(ApplicationLoggingState loggingState, ProxyOutputDevice outputDevice, @@ -794,10 +794,10 @@ private async Task DisplayBannerIfEnabledAsync(ApplicationLoggingState loggingSt { IBannerMessageOwnerCapability? bannerMessageOwnerCapability = testFrameworkCapabilities.GetCapability(); string? bannerMessage = bannerMessageOwnerCapability is not null - ? await bannerMessageOwnerCapability.GetBannerMessageAsync() + ? await bannerMessageOwnerCapability.GetBannerMessageAsync().ConfigureAwait(false) : null; - await outputDevice.DisplayBannerAsync(bannerMessage); + await outputDevice.DisplayBannerAsync(bannerMessage).ConfigureAwait(false); } } } diff --git a/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostControlledHost.cs b/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostControlledHost.cs index 47aa9ec5ce..df4ef77d33 100644 --- a/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostControlledHost.cs +++ b/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostControlledHost.cs @@ -20,10 +20,10 @@ internal sealed class TestHostControlledHost(NamedPipeClient testHostControllerP public async Task RunAsync() { - int exitCode = await _innerTestHost.RunAsync(); + int exitCode = await _innerTestHost.RunAsync().ConfigureAwait(false); try { - await _namedPipeClient.RequestReplyAsync(new TestHostProcessExitRequest(exitCode), _cancellationToken); + await _namedPipeClient.RequestReplyAsync(new TestHostProcessExitRequest(exitCode), _cancellationToken).ConfigureAwait(false); } catch (OperationCanceledException oc) when (oc.CancellationToken == _cancellationToken) { @@ -31,7 +31,7 @@ public async Task RunAsync() } finally { - await DisposeHelper.DisposeAsync(_namedPipeClient); + await DisposeHelper.DisposeAsync(_namedPipeClient).ConfigureAwait(false); } return exitCode; @@ -46,8 +46,8 @@ public void Dispose() #if NETCOREAPP public async ValueTask DisposeAsync() { - await DisposeHelper.DisposeAsync(_innerTestHost); - await _namedPipeClient.DisposeAsync(); + await DisposeHelper.DisposeAsync(_innerTestHost).ConfigureAwait(false); + await _namedPipeClient.DisposeAsync().ConfigureAwait(false); } #endif } diff --git a/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostControllersTestHost.cs b/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostControllersTestHost.cs index 5fb3719f64..7508633fb4 100644 --- a/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostControllersTestHost.cs +++ b/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostControllersTestHost.cs @@ -81,7 +81,7 @@ protected override async Task InternalRunAsync() string processIdString = currentPID.ToString(CultureInfo.InvariantCulture); ExecutableInfo executableInfo = testApplicationModuleInfo.GetCurrentExecutableInfo(); - await _logger.LogDebugAsync($"Test host controller process info: {executableInfo}"); + await _logger.LogDebugAsync($"Test host controller process info: {executableInfo}").ConfigureAwait(false); List partialCommandLine = [ @@ -92,7 +92,7 @@ protected override async Task InternalRunAsync() // Prepare the environment variables used by the test host string processCorrelationId = Guid.NewGuid().ToString("N"); - await _logger.LogDebugAsync($"{EnvironmentVariableConstants.TESTINGPLATFORM_TESTHOSTCONTROLLER_CORRELATIONID}_{currentPID} '{processCorrelationId}'"); + await _logger.LogDebugAsync($"{EnvironmentVariableConstants.TESTINGPLATFORM_TESTHOSTCONTROLLER_CORRELATIONID}_{currentPID} '{processCorrelationId}'").ConfigureAwait(false); NamedPipeServer testHostControllerIpc = new( $"MONITORTOHOST_{Guid.NewGuid():N}", @@ -139,20 +139,20 @@ protected override async Task InternalRunAsync() IPushOnlyProtocol? pushOnlyProtocol = ServiceProvider.GetService(); if (pushOnlyProtocol?.IsServerMode == true) { - dataConsumersBuilder.Add(await pushOnlyProtocol.GetDataConsumerAsync()); + dataConsumersBuilder.Add(await pushOnlyProtocol.GetDataConsumerAsync().ConfigureAwait(false)); } // If we're in server mode jsonrpc we add as last consumer the PassiveNodeDataConsumer for the attachments. // Connect the passive node if it's available if (_passiveNode is not null) { - if (await _passiveNode.ConnectAsync()) + if (await _passiveNode.ConnectAsync().ConfigureAwait(false)) { dataConsumersBuilder.Add(new PassiveNodeDataConsumer(_passiveNode)); } else { - await _logger.LogWarningAsync("PassiveNode was expected to connect but failed"); + await _logger.LogWarningAsync("PassiveNode was expected to connect but failed").ConfigureAwait(false); } } @@ -162,7 +162,7 @@ protected override async Task InternalRunAsync() ServiceProvider.GetTask(), ServiceProvider.GetLoggerFactory(), ServiceProvider.GetEnvironment()); - await concreteMessageBusService.InitAsync(); + await concreteMessageBusService.InitAsync().ConfigureAwait(false); ((MessageBusProxy)ServiceProvider.GetMessageBus()).SetBuiltMessageBus(concreteMessageBusService); // Apply the ITestHostEnvironmentVariableProvider @@ -173,12 +173,12 @@ protected override async Task InternalRunAsync() { CurrentProvider = systemEnvironmentVariableProvider, }; - await systemEnvironmentVariableProvider.UpdateAsync(environmentVariables); + await systemEnvironmentVariableProvider.UpdateAsync(environmentVariables).ConfigureAwait(false); foreach (ITestHostEnvironmentVariableProvider environmentVariableProvider in _testHostsInformation.EnvironmentVariableProviders) { environmentVariables.CurrentProvider = environmentVariableProvider; - await environmentVariableProvider.UpdateAsync(environmentVariables); + await environmentVariableProvider.UpdateAsync(environmentVariables).ConfigureAwait(false); } environmentVariables.CurrentProvider = null; @@ -186,7 +186,7 @@ protected override async Task InternalRunAsync() List<(IExtension, string)> failedValidations = []; foreach (ITestHostEnvironmentVariableProvider hostEnvironmentVariableProvider in _testHostsInformation.EnvironmentVariableProviders) { - ValidationResult variableResult = await hostEnvironmentVariableProvider.ValidateTestHostEnvironmentVariablesAsync(environmentVariables); + ValidationResult variableResult = await hostEnvironmentVariableProvider.ValidateTestHostEnvironmentVariablesAsync(environmentVariables).ConfigureAwait(false); if (!variableResult.IsValid) { failedValidations.Add((hostEnvironmentVariableProvider, variableResult.ErrorMessage)); @@ -205,8 +205,8 @@ protected override async Task InternalRunAsync() displayErrorMessageBuilder.AppendLine(CultureInfo.InvariantCulture, $"Provider '{extension.DisplayName}' (UID: {extension.Uid}) failed with error: {errorMessage}"); } - await outputDevice.DisplayAsync(this, new ErrorMessageOutputDeviceData(displayErrorMessageBuilder.ToString())); - await _logger.LogErrorAsync(logErrorMessageBuilder.ToString()); + await outputDevice.DisplayAsync(this, new ErrorMessageOutputDeviceData(displayErrorMessageBuilder.ToString())).ConfigureAwait(false); + await _logger.LogErrorAsync(logErrorMessageBuilder.ToString()).ConfigureAwait(false); return ExitCodes.InvalidPlatformSetup; } @@ -223,7 +223,7 @@ protected override async Task InternalRunAsync() { foreach (ITestHostProcessLifetimeHandler lifetimeHandler in _testHostsInformation.LifetimeHandlers) { - await lifetimeHandler.BeforeTestHostProcessStartAsync(abortRun); + await lifetimeHandler.BeforeTestHostProcessStartAsync(abortRun).ConfigureAwait(false); } } @@ -232,9 +232,9 @@ protected override async Task InternalRunAsync() #pragma warning disable CA1416 // Validate platform compatibility processStartInfo.EnvironmentVariables.Add($"{EnvironmentVariableConstants.TESTINGPLATFORM_TESTHOSTCONTROLLER_TESTHOSTPROCESSSTARTTIME}_{currentPID}", testHostProcessStartupTime); #pragma warning restore CA1416 - await _logger.LogDebugAsync($"{EnvironmentVariableConstants.TESTINGPLATFORM_TESTHOSTCONTROLLER_TESTHOSTPROCESSSTARTTIME}_{currentPID} '{testHostProcessStartupTime}'"); + await _logger.LogDebugAsync($"{EnvironmentVariableConstants.TESTINGPLATFORM_TESTHOSTCONTROLLER_TESTHOSTPROCESSSTARTTIME}_{currentPID} '{testHostProcessStartupTime}'").ConfigureAwait(false); #pragma warning disable CA1416 // Validate platform compatibility - await _logger.LogDebugAsync($"Starting test host process '{processStartInfo.FileName}' with args '{processStartInfo.Arguments}'"); + await _logger.LogDebugAsync($"Starting test host process '{processStartInfo.FileName}' with args '{processStartInfo.Arguments}'").ConfigureAwait(false); #pragma warning restore CA1416 using IProcess testHostProcess = process.Start(processStartInfo); @@ -252,24 +252,24 @@ protected override async Task InternalRunAsync() testHostProcess.Exited += (_, _) => _logger.LogDebug($"Test host process exited, PID: '{testHostProcessId}'"); - await _logger.LogDebugAsync($"Started test host process '{testHostProcessId}' HasExited: {testHostProcess.HasExited}"); + await _logger.LogDebugAsync($"Started test host process '{testHostProcessId}' HasExited: {testHostProcess.HasExited}").ConfigureAwait(false); if (testHostProcess.HasExited || testHostProcessId is null) { - await _logger.LogDebugAsync("Test host process exited prematurely"); + await _logger.LogDebugAsync("Test host process exited prematurely").ConfigureAwait(false); } else { string? seconds = configuration[PlatformConfigurationConstants.PlatformTestHostControllersManagerSingleConnectionNamedPipeServerWaitConnectionTimeoutSeconds]; int timeoutSeconds = seconds is null ? TimeoutHelper.DefaultHangTimeoutSeconds : int.Parse(seconds, CultureInfo.InvariantCulture); - await _logger.LogDebugAsync($"Setting PlatformTestHostControllersManagerSingleConnectionNamedPipeServerWaitConnectionTimeoutSeconds '{timeoutSeconds}'"); + await _logger.LogDebugAsync($"Setting PlatformTestHostControllersManagerSingleConnectionNamedPipeServerWaitConnectionTimeoutSeconds '{timeoutSeconds}'").ConfigureAwait(false); // Wait for the test host controller to connect using (CancellationTokenSource timeout = new(TimeSpan.FromSeconds(timeoutSeconds))) using (var linkedToken = CancellationTokenSource.CreateLinkedTokenSource(timeout.Token, abortRun)) { - await _logger.LogDebugAsync("Wait connection from the test host process"); - await testHostControllerIpc.WaitConnectionAsync(linkedToken.Token); + await _logger.LogDebugAsync("Wait connection from the test host process").ConfigureAwait(false); + await testHostControllerIpc.WaitConnectionAsync(linkedToken.Token).ConfigureAwait(false); } // Wait for the test host controller to send the PID of the test host process @@ -280,7 +280,7 @@ protected override async Task InternalRunAsync() #pragma warning restore CA1416 } - await _logger.LogDebugAsync("Fire OnTestHostProcessStartedAsync"); + await _logger.LogDebugAsync("Fire OnTestHostProcessStartedAsync").ConfigureAwait(false); if (_testHostPID is null) { @@ -295,17 +295,17 @@ protected override async Task InternalRunAsync() TestHostProcessInformation testHostProcessInformation = new(_testHostPID.Value); foreach (ITestHostProcessLifetimeHandler lifetimeHandler in _testHostsInformation.LifetimeHandlers) { - await lifetimeHandler.OnTestHostProcessStartedAsync(testHostProcessInformation, abortRun); + await lifetimeHandler.OnTestHostProcessStartedAsync(testHostProcessInformation, abortRun).ConfigureAwait(false); } } - await _logger.LogDebugAsync("Wait for test host process exit"); - await testHostProcess.WaitForExitAsync(); + await _logger.LogDebugAsync("Wait for test host process exit").ConfigureAwait(false); + await testHostProcess.WaitForExitAsync().ConfigureAwait(false); } if (_testHostsInformation.LifetimeHandlers.Length > 0) { - await _logger.LogDebugAsync($"Fire OnTestHostProcessExitedAsync testHostGracefullyClosed: {_testHostGracefullyClosed}"); + await _logger.LogDebugAsync($"Fire OnTestHostProcessExitedAsync testHostGracefullyClosed: {_testHostGracefullyClosed}").ConfigureAwait(false); var messageBusProxy = (MessageBusProxy)ServiceProvider.GetMessageBus(); if (_testHostPID is not null) @@ -313,24 +313,24 @@ protected override async Task InternalRunAsync() TestHostProcessInformation testHostProcessInformation = new(_testHostPID.Value, testHostProcess.ExitCode, _testHostGracefullyClosed); foreach (ITestHostProcessLifetimeHandler lifetimeHandler in _testHostsInformation.LifetimeHandlers) { - await lifetimeHandler.OnTestHostProcessExitedAsync(testHostProcessInformation, abortRun); + await lifetimeHandler.OnTestHostProcessExitedAsync(testHostProcessInformation, abortRun).ConfigureAwait(false); // OnTestHostProcess could produce information that needs to be handled by others. - await messageBusProxy.DrainDataAsync(); + await messageBusProxy.DrainDataAsync().ConfigureAwait(false); } } // We disable after the drain because it's possible that the drain will produce more messages - await messageBusProxy.DrainDataAsync(); - await messageBusProxy.DisableAsync(); + await messageBusProxy.DrainDataAsync().ConfigureAwait(false); + await messageBusProxy.DisableAsync().ConfigureAwait(false); } - await outputDevice.DisplayAfterSessionEndRunAsync(); + await outputDevice.DisplayAfterSessionEndRunAsync().ConfigureAwait(false); // We collect info about the extensions before the dispose to avoid possible issue with cleanup. if (telemetryInformation.IsEnabled) { - extensionInformation = await ExtensionInformationCollector.CollectAndSerializeToJsonAsync(ServiceProvider); + extensionInformation = await ExtensionInformationCollector.CollectAndSerializeToJsonAsync(ServiceProvider).ConfigureAwait(false); } // If we have a process in the middle between the test host controller and the test host process we need to keep it into account. @@ -341,15 +341,15 @@ protected override async Task InternalRunAsync() if (!_testHostGracefullyClosed && !abortRun.IsCancellationRequested) { - await outputDevice.DisplayAsync(this, new ErrorMessageOutputDeviceData(string.Format(CultureInfo.InvariantCulture, PlatformResources.TestProcessDidNotExitGracefullyErrorMessage, exitCode))); + await outputDevice.DisplayAsync(this, new ErrorMessageOutputDeviceData(string.Format(CultureInfo.InvariantCulture, PlatformResources.TestProcessDidNotExitGracefullyErrorMessage, exitCode))).ConfigureAwait(false); } - await _logger.LogInformationAsync($"TestHostControllersTestHost ended with exit code '{exitCode}' (real test host exit code '{testHostProcess.ExitCode}')' in '{consoleRunStarted.Elapsed}'"); - await DisposeHelper.DisposeAsync(testHostControllerIpc); + await _logger.LogInformationAsync($"TestHostControllersTestHost ended with exit code '{exitCode}' (real test host exit code '{testHostProcess.ExitCode}')' in '{consoleRunStarted.Elapsed}'").ConfigureAwait(false); + await DisposeHelper.DisposeAsync(testHostControllerIpc).ConfigureAwait(false); } finally { - await DisposeServicesAsync(); + await DisposeServicesAsync().ConfigureAwait(false); } if (telemetryInformation.IsEnabled) @@ -363,7 +363,7 @@ protected override async Task InternalRunAsync() [TelemetryProperties.HostProperties.ExitCodePropertyName] = exitCode.ToString(CultureInfo.InvariantCulture), [TelemetryProperties.HostProperties.HasExitedGracefullyPropertyName] = _testHostGracefullyClosed.AsTelemetryBool(), [TelemetryProperties.HostProperties.ExtensionsPropertyName] = extensionInformation, - }); + }).ConfigureAwait(false); } return exitCode; @@ -378,17 +378,17 @@ private async Task DisposeServicesAsync() foreach (ITestHostProcessLifetimeHandler service in lifetimeHandlers) { - await DisposeHelper.DisposeAsync(service); + await DisposeHelper.DisposeAsync(service).ConfigureAwait(false); alreadyDisposed.Add(service); } foreach (ITestHostEnvironmentVariableProvider service in variableProviders) { - await DisposeHelper.DisposeAsync(service); + await DisposeHelper.DisposeAsync(service).ConfigureAwait(false); alreadyDisposed.Add(service); } - await DisposeServiceProviderAsync(ServiceProvider, alreadyDisposed: alreadyDisposed); + await DisposeServiceProviderAsync(ServiceProvider, alreadyDisposed: alreadyDisposed).ConfigureAwait(false); } private Task HandleRequestAsync(IRequest request) diff --git a/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostOchestratorHost.cs b/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostOchestratorHost.cs index 6eca7b889f..5889813f81 100644 --- a/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostOchestratorHost.cs +++ b/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostOchestratorHost.cs @@ -24,10 +24,10 @@ public async Task RunAsync() ITestHostOrchestrator testHostOrchestrator = _testHostOrchestratorConfiguration.TestHostOrchestrators[0]; ITestApplicationCancellationTokenSource applicationCancellationToken = _serviceProvider.GetTestApplicationCancellationTokenSource(); int exitCode; - await logger.LogInformationAsync($"Running test orchestrator '{testHostOrchestrator.Uid}'"); + await logger.LogInformationAsync($"Running test orchestrator '{testHostOrchestrator.Uid}'").ConfigureAwait(false); try { - exitCode = await testHostOrchestrator.OrchestrateTestHostExecutionAsync(); + exitCode = await testHostOrchestrator.OrchestrateTestHostExecutionAsync().ConfigureAwait(false); } catch (OperationCanceledException) when (applicationCancellationToken.CancellationToken.IsCancellationRequested) { diff --git a/src/Platform/Microsoft.Testing.Platform/Hosts/ToolsTestHost.cs b/src/Platform/Microsoft.Testing.Platform/Hosts/ToolsTestHost.cs index c4eb8aabb5..59f8cb908f 100644 --- a/src/Platform/Microsoft.Testing.Platform/Hosts/ToolsTestHost.cs +++ b/src/Platform/Microsoft.Testing.Platform/Hosts/ToolsTestHost.cs @@ -60,30 +60,30 @@ public async Task RunAsync() { if (UnknownOptions(out string? unknownOptionsError, tool)) { - await _outputDevice.DisplayAsync(this, new ErrorMessageOutputDeviceData(unknownOptionsError)); + await _outputDevice.DisplayAsync(this, new ErrorMessageOutputDeviceData(unknownOptionsError)).ConfigureAwait(false); console.WriteLine(); return ExitCodes.InvalidCommandLine; } if (ExtensionArgumentArityAreInvalid(out string? arityErrors, tool)) { - await _outputDevice.DisplayAsync(this, new ErrorMessageOutputDeviceData(arityErrors)); + await _outputDevice.DisplayAsync(this, new ErrorMessageOutputDeviceData(arityErrors)).ConfigureAwait(false); return ExitCodes.InvalidCommandLine; } - ValidationResult optionsArgumentsValidationResult = await ValidateOptionsArgumentsAsync(tool); + ValidationResult optionsArgumentsValidationResult = await ValidateOptionsArgumentsAsync(tool).ConfigureAwait(false); if (!optionsArgumentsValidationResult.IsValid) { - await _outputDevice.DisplayAsync(this, new ErrorMessageOutputDeviceData(optionsArgumentsValidationResult.ErrorMessage)); + await _outputDevice.DisplayAsync(this, new ErrorMessageOutputDeviceData(optionsArgumentsValidationResult.ErrorMessage)).ConfigureAwait(false); return ExitCodes.InvalidCommandLine; } - return await tool.RunAsync(); + return await tool.RunAsync().ConfigureAwait(false); } } - await _outputDevice.DisplayAsync(this, new ErrorMessageOutputDeviceData($"Tool '{toolNameToRun}' not found in the list of registered tools.")); - await _commandLineHandler.PrintHelpAsync(_outputDevice); + await _outputDevice.DisplayAsync(this, new ErrorMessageOutputDeviceData($"Tool '{toolNameToRun}' not found in the list of registered tools.")).ConfigureAwait(false); + await _commandLineHandler.PrintHelpAsync(_outputDevice).ConfigureAwait(false); return ExitCodes.InvalidCommandLine; } @@ -164,7 +164,7 @@ private async Task ValidateOptionsArgumentsAsync(ITool tool) foreach (CommandLineParseOption optionRecord in _commandLineHandler.ParseResult.Options) { ICommandLineOptionsProvider extension = GetAllCommandLineOptionsProviderByOptionName(optionRecord.Name).Single(); - ValidationResult result = await extension.ValidateOptionArgumentsAsync(extension.GetCommandLineOptions().Single(x => x.Name == optionRecord.Name), optionRecord.Arguments); + ValidationResult result = await extension.ValidateOptionArgumentsAsync(extension.GetCommandLineOptions().Single(x => x.Name == optionRecord.Name), optionRecord.Arguments).ConfigureAwait(false); if (!result.IsValid) { stringBuilder.AppendLine(CultureInfo.InvariantCulture, $"Invalid arguments for option '--{optionRecord.Name}': {result.ErrorMessage}, tool {tool.DisplayName}"); diff --git a/src/Platform/Microsoft.Testing.Platform/IPC/NamedPipeClient.cs b/src/Platform/Microsoft.Testing.Platform/IPC/NamedPipeClient.cs index 39613088cd..1ea5418212 100644 --- a/src/Platform/Microsoft.Testing.Platform/IPC/NamedPipeClient.cs +++ b/src/Platform/Microsoft.Testing.Platform/IPC/NamedPipeClient.cs @@ -39,13 +39,13 @@ public NamedPipeClient(string name) public bool IsConnected => _namedPipeClientStream.IsConnected; public async Task ConnectAsync(CancellationToken cancellationToken) - => await _namedPipeClientStream.ConnectAsync(cancellationToken); + => await _namedPipeClientStream.ConnectAsync(cancellationToken).ConfigureAwait(false); public async Task RequestReplyAsync(TRequest request, CancellationToken cancellationToken) where TRequest : IRequest where TResponse : IResponse { - await _lock.WaitAsync(cancellationToken); + await _lock.WaitAsync(cancellationToken).ConfigureAwait(false); try { INamedPipeSerializer requestNamedPipeSerializer = GetSerializer(typeof(TRequest)); @@ -70,14 +70,14 @@ public async Task RequestReplyAsync(TRequest req try { ApplicationStateGuard.Ensure(BitConverter.TryWriteBytes(bytes, sizeOfTheWholeMessage), PlatformResources.UnexpectedExceptionDuringByteConversionErrorMessage); - await _messageBuffer.WriteAsync(bytes.AsMemory(0, sizeof(int)), cancellationToken); + await _messageBuffer.WriteAsync(bytes.AsMemory(0, sizeof(int)), cancellationToken).ConfigureAwait(false); } finally { ArrayPool.Shared.Return(bytes); } #else - await _messageBuffer.WriteAsync(BitConverter.GetBytes(sizeOfTheWholeMessage), 0, sizeof(int), cancellationToken); + await _messageBuffer.WriteAsync(BitConverter.GetBytes(sizeOfTheWholeMessage), 0, sizeof(int), cancellationToken).ConfigureAwait(false); #endif // Write the serializer id @@ -86,23 +86,23 @@ public async Task RequestReplyAsync(TRequest req try { ApplicationStateGuard.Ensure(BitConverter.TryWriteBytes(bytes, requestNamedPipeSerializer.Id), PlatformResources.UnexpectedExceptionDuringByteConversionErrorMessage); - await _messageBuffer.WriteAsync(bytes.AsMemory(0, sizeof(int)), cancellationToken); + await _messageBuffer.WriteAsync(bytes.AsMemory(0, sizeof(int)), cancellationToken).ConfigureAwait(false); } finally { ArrayPool.Shared.Return(bytes); } #else - await _messageBuffer.WriteAsync(BitConverter.GetBytes(requestNamedPipeSerializer.Id), 0, sizeof(int), cancellationToken); + await _messageBuffer.WriteAsync(BitConverter.GetBytes(requestNamedPipeSerializer.Id), 0, sizeof(int), cancellationToken).ConfigureAwait(false); #endif try { // Write the message #if NETCOREAPP - await _messageBuffer.WriteAsync(_serializationBuffer.GetBuffer().AsMemory(0, (int)_serializationBuffer.Position), cancellationToken); + await _messageBuffer.WriteAsync(_serializationBuffer.GetBuffer().AsMemory(0, (int)_serializationBuffer.Position), cancellationToken).ConfigureAwait(false); #else - await _messageBuffer.WriteAsync(_serializationBuffer.GetBuffer(), 0, (int)_serializationBuffer.Position, cancellationToken); + await _messageBuffer.WriteAsync(_serializationBuffer.GetBuffer(), 0, (int)_serializationBuffer.Position, cancellationToken).ConfigureAwait(false); #endif } finally @@ -115,11 +115,11 @@ public async Task RequestReplyAsync(TRequest req try { #if NETCOREAPP - await _namedPipeClientStream.WriteAsync(_messageBuffer.GetBuffer().AsMemory(0, (int)_messageBuffer.Position), cancellationToken); + await _namedPipeClientStream.WriteAsync(_messageBuffer.GetBuffer().AsMemory(0, (int)_messageBuffer.Position), cancellationToken).ConfigureAwait(false); #else - await _namedPipeClientStream.WriteAsync(_messageBuffer.GetBuffer(), 0, (int)_messageBuffer.Position, cancellationToken); + await _namedPipeClientStream.WriteAsync(_messageBuffer.GetBuffer(), 0, (int)_messageBuffer.Position, cancellationToken).ConfigureAwait(false); #endif - await _namedPipeClientStream.FlushAsync(cancellationToken); + await _namedPipeClientStream.FlushAsync(cancellationToken).ConfigureAwait(false); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { _namedPipeClientStream.WaitForPipeDrain(); @@ -139,9 +139,9 @@ public async Task RequestReplyAsync(TRequest req { int currentReadIndex = 0; #if NETCOREAPP - int currentReadBytes = await _namedPipeClientStream.ReadAsync(_readBuffer.AsMemory(currentReadIndex, _readBuffer.Length), cancellationToken); + int currentReadBytes = await _namedPipeClientStream.ReadAsync(_readBuffer.AsMemory(currentReadIndex, _readBuffer.Length), cancellationToken).ConfigureAwait(false); #else - int currentReadBytes = await _namedPipeClientStream.ReadAsync(_readBuffer, currentReadIndex, _readBuffer.Length, cancellationToken); + int currentReadBytes = await _namedPipeClientStream.ReadAsync(_readBuffer, currentReadIndex, _readBuffer.Length, cancellationToken).ConfigureAwait(false); #endif // Reset the current chunk size @@ -161,9 +161,9 @@ public async Task RequestReplyAsync(TRequest req { // We need to read the rest of the message #if NETCOREAPP - await _messageBuffer.WriteAsync(_readBuffer.AsMemory(currentReadIndex, missingBytesToReadOfCurrentChunk), cancellationToken); + await _messageBuffer.WriteAsync(_readBuffer.AsMemory(currentReadIndex, missingBytesToReadOfCurrentChunk), cancellationToken).ConfigureAwait(false); #else - await _messageBuffer.WriteAsync(_readBuffer, currentReadIndex, missingBytesToReadOfCurrentChunk, cancellationToken); + await _messageBuffer.WriteAsync(_readBuffer, currentReadIndex, missingBytesToReadOfCurrentChunk, cancellationToken).ConfigureAwait(false); #endif missingBytesToReadOfWholeMessage -= missingBytesToReadOfCurrentChunk; } @@ -223,9 +223,9 @@ public async ValueTask DisposeAsync() } _lock.Dispose(); - await _serializationBuffer.DisposeAsync(); - await _messageBuffer.DisposeAsync(); - await _namedPipeClientStream.DisposeAsync(); + await _serializationBuffer.DisposeAsync().ConfigureAwait(false); + await _messageBuffer.DisposeAsync().ConfigureAwait(false); + await _namedPipeClientStream.DisposeAsync().ConfigureAwait(false); _disposed = true; } #endif diff --git a/src/Platform/Microsoft.Testing.Platform/IPC/NamedPipeServer.cs b/src/Platform/Microsoft.Testing.Platform/IPC/NamedPipeServer.cs index 8f59b1f817..3caf9be910 100644 --- a/src/Platform/Microsoft.Testing.Platform/IPC/NamedPipeServer.cs +++ b/src/Platform/Microsoft.Testing.Platform/IPC/NamedPipeServer.cs @@ -77,18 +77,18 @@ public NamedPipeServer( public async Task WaitConnectionAsync(CancellationToken cancellationToken) { - await _logger.LogDebugAsync($"Waiting for connection for the pipe name {PipeName.Name}"); + await _logger.LogDebugAsync($"Waiting for connection for the pipe name {PipeName.Name}").ConfigureAwait(false); #pragma warning disable CA1416 // Validate platform compatibility - await _namedPipeServerStream.WaitForConnectionAsync(cancellationToken); + await _namedPipeServerStream.WaitForConnectionAsync(cancellationToken).ConfigureAwait(false); #pragma warning restore CA1416 WasConnected = true; - await _logger.LogDebugAsync($"Client connected to {PipeName.Name}"); + await _logger.LogDebugAsync($"Client connected to {PipeName.Name}").ConfigureAwait(false); _loopTask = _task.Run( async () => { try { - await InternalLoopAsync(_cancellationToken); + await InternalLoopAsync(_cancellationToken).ConfigureAwait(false); } catch (OperationCanceledException ex) when (ex.CancellationToken == _cancellationToken) { @@ -96,7 +96,7 @@ public async Task WaitConnectionAsync(CancellationToken cancellationToken) } catch (Exception ex) { - await _logger.LogErrorAsync($"Exception on pipe: {PipeName.Name}", ex); + await _logger.LogErrorAsync($"Exception on pipe: {PipeName.Name}", ex).ConfigureAwait(false); _environment.FailFast($"[NamedPipeServer] Unhandled exception:{_environment.NewLine}{ex}", ex); } }, cancellationToken); @@ -117,10 +117,10 @@ private async Task InternalLoopAsync(CancellationToken cancellationToken) int currentReadIndex = 0; #if NET #pragma warning disable CA1416 // Validate platform compatibility - int currentReadBytes = await _namedPipeServerStream.ReadAsync(_readBuffer.AsMemory(currentReadIndex, _readBuffer.Length), cancellationToken); + int currentReadBytes = await _namedPipeServerStream.ReadAsync(_readBuffer.AsMemory(currentReadIndex, _readBuffer.Length), cancellationToken).ConfigureAwait(false); #pragma warning restore CA1416 #else - int currentReadBytes = await _namedPipeServerStream.ReadAsync(_readBuffer, currentReadIndex, _readBuffer.Length, cancellationToken); + int currentReadBytes = await _namedPipeServerStream.ReadAsync(_readBuffer, currentReadIndex, _readBuffer.Length, cancellationToken).ConfigureAwait(false); #endif if (currentReadBytes == 0) { @@ -145,9 +145,9 @@ private async Task InternalLoopAsync(CancellationToken cancellationToken) { // We need to read the rest of the message #if NET - await _messageBuffer.WriteAsync(_readBuffer.AsMemory(currentReadIndex, missingBytesToReadOfCurrentChunk), cancellationToken); + await _messageBuffer.WriteAsync(_readBuffer.AsMemory(currentReadIndex, missingBytesToReadOfCurrentChunk), cancellationToken).ConfigureAwait(false); #else - await _messageBuffer.WriteAsync(_readBuffer, currentReadIndex, missingBytesToReadOfCurrentChunk, cancellationToken); + await _messageBuffer.WriteAsync(_readBuffer, currentReadIndex, missingBytesToReadOfCurrentChunk, cancellationToken).ConfigureAwait(false); #endif missingBytesToReadOfWholeMessage -= missingBytesToReadOfCurrentChunk; } @@ -169,7 +169,7 @@ private async Task InternalLoopAsync(CancellationToken cancellationToken) var deserializedObject = (IRequest)requestNamedPipeSerializer.Deserialize(_messageBuffer); // Call the callback - IResponse response = await _callback(deserializedObject); + IResponse response = await _callback(deserializedObject).ConfigureAwait(false); // Write the message size _messageBuffer.Position = 0; @@ -194,14 +194,14 @@ private async Task InternalLoopAsync(CancellationToken cancellationToken) { ApplicationStateGuard.Ensure(BitConverter.TryWriteBytes(bytes, sizeOfTheWholeMessage), PlatformResources.UnexpectedExceptionDuringByteConversionErrorMessage); - await _messageBuffer.WriteAsync(bytes.AsMemory(0, sizeof(int)), cancellationToken); + await _messageBuffer.WriteAsync(bytes.AsMemory(0, sizeof(int)), cancellationToken).ConfigureAwait(false); } finally { ArrayPool.Shared.Return(bytes); } #else - await _messageBuffer.WriteAsync(BitConverter.GetBytes(sizeOfTheWholeMessage), 0, sizeof(int), cancellationToken); + await _messageBuffer.WriteAsync(BitConverter.GetBytes(sizeOfTheWholeMessage), 0, sizeof(int), cancellationToken).ConfigureAwait(false); #endif // Write the serializer id @@ -211,21 +211,21 @@ private async Task InternalLoopAsync(CancellationToken cancellationToken) { ApplicationStateGuard.Ensure(BitConverter.TryWriteBytes(bytes, responseNamedPipeSerializer.Id), PlatformResources.UnexpectedExceptionDuringByteConversionErrorMessage); - await _messageBuffer.WriteAsync(bytes.AsMemory(0, sizeof(int)), cancellationToken); + await _messageBuffer.WriteAsync(bytes.AsMemory(0, sizeof(int)), cancellationToken).ConfigureAwait(false); } finally { ArrayPool.Shared.Return(bytes); } #else - await _messageBuffer.WriteAsync(BitConverter.GetBytes(responseNamedPipeSerializer.Id), 0, sizeof(int), cancellationToken); + await _messageBuffer.WriteAsync(BitConverter.GetBytes(responseNamedPipeSerializer.Id), 0, sizeof(int), cancellationToken).ConfigureAwait(false); #endif // Write the message #if NET - await _messageBuffer.WriteAsync(_serializationBuffer.GetBuffer().AsMemory(0, (int)_serializationBuffer.Position), cancellationToken); + await _messageBuffer.WriteAsync(_serializationBuffer.GetBuffer().AsMemory(0, (int)_serializationBuffer.Position), cancellationToken).ConfigureAwait(false); #else - await _messageBuffer.WriteAsync(_serializationBuffer.GetBuffer(), 0, (int)_serializationBuffer.Position, cancellationToken); + await _messageBuffer.WriteAsync(_serializationBuffer.GetBuffer(), 0, (int)_serializationBuffer.Position, cancellationToken).ConfigureAwait(false); #endif // Send the message @@ -233,13 +233,13 @@ private async Task InternalLoopAsync(CancellationToken cancellationToken) { #if NET #pragma warning disable CA1416 // Validate platform compatibility - await _namedPipeServerStream.WriteAsync(_messageBuffer.GetBuffer().AsMemory(0, (int)_messageBuffer.Position), cancellationToken); + await _namedPipeServerStream.WriteAsync(_messageBuffer.GetBuffer().AsMemory(0, (int)_messageBuffer.Position), cancellationToken).ConfigureAwait(false); #pragma warning restore CA1416 #else - await _namedPipeServerStream.WriteAsync(_messageBuffer.GetBuffer(), 0, (int)_messageBuffer.Position, cancellationToken); + await _namedPipeServerStream.WriteAsync(_messageBuffer.GetBuffer(), 0, (int)_messageBuffer.Position, cancellationToken).ConfigureAwait(false); #endif #pragma warning disable CA1416 // Validate platform compatibility - await _namedPipeServerStream.FlushAsync(cancellationToken); + await _namedPipeServerStream.FlushAsync(cancellationToken).ConfigureAwait(false); #pragma warning restore CA1416 if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { @@ -332,7 +332,7 @@ public async ValueTask DisposeAsync() try { // To close gracefully we need to ensure that the client closed the stream line 103. - await _loopTask.WaitAsync(TimeoutHelper.DefaultHangTimeSpanTimeout, _cancellationToken); + await _loopTask.WaitAsync(TimeoutHelper.DefaultHangTimeSpanTimeout, _cancellationToken).ConfigureAwait(false); } catch (TimeoutException) { diff --git a/src/Platform/Microsoft.Testing.Platform/Logging/FileLogger.cs b/src/Platform/Microsoft.Testing.Platform/Logging/FileLogger.cs index eeec19e5f5..ba8d0da941 100644 --- a/src/Platform/Microsoft.Testing.Platform/Logging/FileLogger.cs +++ b/src/Platform/Microsoft.Testing.Platform/Logging/FileLogger.cs @@ -165,7 +165,7 @@ public async Task LogAsync(LogLevel logLevel, TState state, Exception? e { if (_options.SyncFlush) { - await InternalAsyncLogAsync(logLevel, state, exception, formatter, category); + await InternalAsyncLogAsync(logLevel, state, exception, formatter, category).ConfigureAwait(false); } else { @@ -180,14 +180,14 @@ private async Task InternalAsyncLogAsync(LogLevel logLevel, TState state return; } - if (!await _semaphore.WaitAsync(TimeoutHelper.DefaultHangTimeSpanTimeout)) + if (!await _semaphore.WaitAsync(TimeoutHelper.DefaultHangTimeSpanTimeout).ConfigureAwait(false)) { throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, PlatformResources.TimeoutAcquiringSemaphoreErrorMessage, TimeoutHelper.DefaultHangTimeoutSeconds)); } try { - await _writer.WriteLineAsync(BuildLogEntry(logLevel, state, exception, formatter, category)); + await _writer.WriteLineAsync(BuildLogEntry(logLevel, state, exception, formatter, category)).ConfigureAwait(false); } finally { @@ -232,16 +232,16 @@ private async Task WriteLogToFileAsync() { #if NETCOREAPP // We don't need cancellation token because the task will be stopped when the Channel is completed thanks to the call to Complete() inside the Dispose method. - while (await _channel.Reader.WaitToReadAsync()) + while (await _channel.Reader.WaitToReadAsync().ConfigureAwait(false)) { - await _writer.WriteLineAsync(await _channel.Reader.ReadAsync()); + await _writer.WriteLineAsync(await _channel.Reader.ReadAsync().ConfigureAwait(false)).ConfigureAwait(false); } #else // We don't need cancellation token because the task will be stopped when the BlockingCollection is completed thanks to the call to CompleteAdding() // inside the Dispose method. foreach (string message in _asyncLogs.GetConsumingEnumerable()) { - await _writer.WriteLineAsync(message); + await _writer.WriteLineAsync(message).ConfigureAwait(false); } #endif } @@ -312,13 +312,13 @@ public async ValueTask DisposeAsync() // Wait for all logs to be written _channel.Writer.TryComplete(); - await _logLoop.TimeoutAfterAsync(TimeoutHelper.DefaultHangTimeSpanTimeout); + await _logLoop.TimeoutAfterAsync(TimeoutHelper.DefaultHangTimeSpanTimeout).ConfigureAwait(false); } _semaphore.Dispose(); - await _writer.FlushAsync(); - await _writer.DisposeAsync(); - await _fileStream.DisposeAsync(); + await _writer.FlushAsync().ConfigureAwait(false); + await _writer.DisposeAsync().ConfigureAwait(false); + await _fileStream.DisposeAsync().ConfigureAwait(false); _disposed = true; } #endif diff --git a/src/Platform/Microsoft.Testing.Platform/Logging/FileLoggerCategory.cs b/src/Platform/Microsoft.Testing.Platform/Logging/FileLoggerCategory.cs index ea2c8f32b8..21b55b35b4 100644 --- a/src/Platform/Microsoft.Testing.Platform/Logging/FileLoggerCategory.cs +++ b/src/Platform/Microsoft.Testing.Platform/Logging/FileLoggerCategory.cs @@ -14,5 +14,5 @@ public void Log(LogLevel logLevel, TState state, Exception? exception, F => _fileLogger.Log(logLevel, state, exception, formatter, _category); public async Task LogAsync(LogLevel logLevel, TState state, Exception? exception, Func formatter) - => await _fileLogger.LogAsync(logLevel, state, exception, formatter, _category); + => await _fileLogger.LogAsync(logLevel, state, exception, formatter, _category).ConfigureAwait(false); } diff --git a/src/Platform/Microsoft.Testing.Platform/Logging/FileLoggerProvider.cs b/src/Platform/Microsoft.Testing.Platform/Logging/FileLoggerProvider.cs index cbb4477319..f6cabc8ffe 100644 --- a/src/Platform/Microsoft.Testing.Platform/Logging/FileLoggerProvider.cs +++ b/src/Platform/Microsoft.Testing.Platform/Logging/FileLoggerProvider.cs @@ -53,7 +53,7 @@ public async Task CheckLogFolderAndMoveToTheNewIfNeededAsync(string testResultDi } string fileName = Path.GetFileName(FileLogger.FileName); - await DisposeHelper.DisposeAsync(FileLogger); + await DisposeHelper.DisposeAsync(FileLogger).ConfigureAwait(false); // Move the log file to the new directory _fileSystem.Move(FileLogger.FileName, Path.Combine(testResultDirectory, fileName)); @@ -76,6 +76,6 @@ public void Dispose() #if NETCOREAPP public async ValueTask DisposeAsync() - => await FileLogger.DisposeAsync(); + => await FileLogger.DisposeAsync().ConfigureAwait(false); #endif } diff --git a/src/Platform/Microsoft.Testing.Platform/Logging/Logger.cs b/src/Platform/Microsoft.Testing.Platform/Logging/Logger.cs index 539dc9dfb9..f63efc4eaf 100644 --- a/src/Platform/Microsoft.Testing.Platform/Logging/Logger.cs +++ b/src/Platform/Microsoft.Testing.Platform/Logging/Logger.cs @@ -28,7 +28,7 @@ public async Task LogAsync(LogLevel logLevel, TState state, Exception? e { if (logger.IsEnabled(logLevel)) { - await logger.LogAsync(logLevel, state, exception, formatter); + await logger.LogAsync(logLevel, state, exception, formatter).ConfigureAwait(false); } } } diff --git a/src/Platform/Microsoft.Testing.Platform/Logging/LoggerFactory.cs b/src/Platform/Microsoft.Testing.Platform/Logging/LoggerFactory.cs index 796f009c74..c431ec4921 100644 --- a/src/Platform/Microsoft.Testing.Platform/Logging/LoggerFactory.cs +++ b/src/Platform/Microsoft.Testing.Platform/Logging/LoggerFactory.cs @@ -69,7 +69,7 @@ public async ValueTask DisposeAsync() continue; } - await asyncDisposable.DisposeAsync(); + await asyncDisposable.DisposeAsync().ConfigureAwait(false); } } #endif diff --git a/src/Platform/Microsoft.Testing.Platform/Logging/LoggingManager.cs b/src/Platform/Microsoft.Testing.Platform/Logging/LoggingManager.cs index 43c32ecbb2..390d1fd698 100644 --- a/src/Platform/Microsoft.Testing.Platform/Logging/LoggingManager.cs +++ b/src/Platform/Microsoft.Testing.Platform/Logging/LoggingManager.cs @@ -23,12 +23,12 @@ internal async Task BuildAsync(IServiceProvider serviceProvider, foreach (Func factory in _loggerProviderFullFactories) { ILoggerProvider serviceInstance = factory(logLevel, serviceProvider); - if (serviceInstance is IExtension extension && !await extension.IsEnabledAsync()) + if (serviceInstance is IExtension extension && !await extension.IsEnabledAsync().ConfigureAwait(false)) { continue; } - await serviceInstance.TryInitializeAsync(); + await serviceInstance.TryInitializeAsync().ConfigureAwait(false); loggerProviders.Add(serviceInstance); } diff --git a/src/Platform/Microsoft.Testing.Platform/Messages/AsynchronousMessageBus.cs b/src/Platform/Microsoft.Testing.Platform/Messages/AsynchronousMessageBus.cs index b473a41956..c51baaa3a1 100644 --- a/src/Platform/Microsoft.Testing.Platform/Messages/AsynchronousMessageBus.cs +++ b/src/Platform/Microsoft.Testing.Platform/Messages/AsynchronousMessageBus.cs @@ -42,13 +42,13 @@ public AsynchronousMessageBus( public override IDataConsumer[] DataConsumerServices => _dataConsumers; - public override async Task InitAsync() => await BuildConsumerProducersAsync(); + public override async Task InitAsync() => await BuildConsumerProducersAsync().ConfigureAwait(false); private async Task BuildConsumerProducersAsync() { foreach (IDataConsumer consumer in _dataConsumers) { - if (!await consumer.IsEnabledAsync()) + if (!await consumer.IsEnabledAsync().ConfigureAwait(false)) { throw new InvalidOperationException($"Unexpected disabled IDataConsumer '{consumer}'"); } @@ -96,7 +96,7 @@ public override async Task PublishAsync(IDataProducer dataProducer, IData data) if (_isTraceLoggingEnabled) { - await LogDataAsync(dataProducer, data); + await LogDataAsync(dataProducer, data).ConfigureAwait(false); } Type dataType = data.GetType(); @@ -112,7 +112,7 @@ public override async Task PublishAsync(IDataProducer dataProducer, IData data) for (int i = 0; i < values.Count; i++) { - await values[i].PublishAsync(dataProducer, data); + await values[i].PublishAsync(dataProducer, data).ConfigureAwait(false); } } @@ -124,7 +124,7 @@ private async Task LogDataAsync(IDataProducer dataProducer, IData data) $"The producer '{dataProducer.DisplayName}' (ID: {dataProducer.Uid}) pushed data:"); messageBuilder.AppendLine(data.ToString()); - await _logger.LogTraceAsync(messageBuilder.ToString()); + await _logger.LogTraceAsync(messageBuilder.ToString()).ConfigureAwait(false); } public override async Task DrainDataAsync() @@ -170,7 +170,7 @@ public override async Task DrainDataAsync() consumerToDrain.Add(asyncMultiProducerMultiConsumerDataProcessor, 0); } - long totalPayloadReceived = await asyncMultiProducerMultiConsumerDataProcessor.DrainDataAsync(); + long totalPayloadReceived = await asyncMultiProducerMultiConsumerDataProcessor.DrainDataAsync().ConfigureAwait(false); if (consumerToDrain[asyncMultiProducerMultiConsumerDataProcessor] != totalPayloadReceived) { consumerToDrain[asyncMultiProducerMultiConsumerDataProcessor] = totalPayloadReceived; @@ -194,7 +194,7 @@ public override async Task DisableAsync() { foreach (AsyncConsumerDataProcessor asyncMultiProducerMultiConsumerDataProcessor in dataProcessors) { - await asyncMultiProducerMultiConsumerDataProcessor.CompleteAddingAsync(); + await asyncMultiProducerMultiConsumerDataProcessor.CompleteAddingAsync().ConfigureAwait(false); } } } diff --git a/src/Platform/Microsoft.Testing.Platform/Messages/ChannelConsumerDataProcessor.cs b/src/Platform/Microsoft.Testing.Platform/Messages/ChannelConsumerDataProcessor.cs index 2982aeed35..1c568abd55 100644 --- a/src/Platform/Microsoft.Testing.Platform/Messages/ChannelConsumerDataProcessor.cs +++ b/src/Platform/Microsoft.Testing.Platform/Messages/ChannelConsumerDataProcessor.cs @@ -47,16 +47,16 @@ public AsyncConsumerDataProcessor(IDataConsumer consumer, ITask task, Cancellati public async Task PublishAsync(IDataProducer dataProducer, IData data) { Interlocked.Increment(ref _totalPayloadReceived); - await _channel.Writer.WriteAsync((dataProducer, data), _cancellationToken); + await _channel.Writer.WriteAsync((dataProducer, data), _cancellationToken).ConfigureAwait(false); } private async Task ConsumeAsync() { try { - while (await _channel.Reader.WaitToReadAsync(_cancellationToken)) + while (await _channel.Reader.WaitToReadAsync(_cancellationToken).ConfigureAwait(false)) { - (IDataProducer dataProducer, IData data) = await _channel.Reader.ReadAsync(_cancellationToken); + (IDataProducer dataProducer, IData data) = await _channel.Reader.ReadAsync(_cancellationToken).ConfigureAwait(false); try { @@ -70,7 +70,7 @@ private async Task ConsumeAsync() try { - await DataConsumer.ConsumeAsync(dataProducer, data, _cancellationToken); + await DataConsumer.ConsumeAsync(dataProducer, data, _cancellationToken).ConfigureAwait(false); } // We let the catch below to handle the graceful cancellation of the process @@ -118,7 +118,7 @@ public async Task CompleteAddingAsync() _channel.Writer.TryComplete(); // Wait for the consumer to complete - await _consumeTask; + await _consumeTask.ConfigureAwait(false); } public async Task DrainDataAsync() @@ -136,13 +136,13 @@ public async Task DrainDataAsync() break; } - await _task.Delay(currentDelayTimeMs); + await _task.Delay(currentDelayTimeMs).ConfigureAwait(false); currentDelayTimeMs = Math.Min(currentDelayTimeMs + minDelayTimeMs, 200); if (_consumerState.Task.IsFaulted) { // Rethrow the exception - await _consumerState.Task; + await _consumerState.Task.ConfigureAwait(false); } // Wait for the consumer to complete the current enqueued items @@ -154,7 +154,7 @@ public async Task DrainDataAsync() if (_consumerState.Task.IsFaulted) { // Rethrow the exception - await _consumerState.Task; + await _consumerState.Task.ConfigureAwait(false); } return _totalPayloadReceived; diff --git a/src/Platform/Microsoft.Testing.Platform/Messages/ConsumingEnumerableConsumerDataProcessor.cs b/src/Platform/Microsoft.Testing.Platform/Messages/ConsumingEnumerableConsumerDataProcessor.cs index fd0cf91171..f2cc853b00 100644 --- a/src/Platform/Microsoft.Testing.Platform/Messages/ConsumingEnumerableConsumerDataProcessor.cs +++ b/src/Platform/Microsoft.Testing.Platform/Messages/ConsumingEnumerableConsumerDataProcessor.cs @@ -59,7 +59,7 @@ private async Task ConsumeAsync() try { - await DataConsumer.ConsumeAsync(dataProducer, data, _cancellationToken); + await DataConsumer.ConsumeAsync(dataProducer, data, _cancellationToken).ConfigureAwait(false); } // We let the catch below to handle the graceful cancellation of the process @@ -125,13 +125,13 @@ public async Task DrainDataAsync() break; } - await _task.Delay(currentDelayTimeMs); + await _task.Delay(currentDelayTimeMs).ConfigureAwait(false); currentDelayTimeMs = Math.Min(currentDelayTimeMs + minDelayTimeMs, 200); if (_consumerState.Task.IsFaulted) { // Rethrow the exception - await _consumerState.Task; + await _consumerState.Task.ConfigureAwait(false); } // Wait for the consumer to complete the current enqueued items @@ -143,7 +143,7 @@ public async Task DrainDataAsync() if (_consumerState.Task.IsFaulted) { // Rethrow the exception - await _consumerState.Task; + await _consumerState.Task.ConfigureAwait(false); } return _totalPayloadReceived; @@ -155,7 +155,7 @@ public async Task CompleteAddingAsync() _payloads.CompleteAdding(); // Wait for the consumer to complete - await _consumeTask; + await _consumeTask.ConfigureAwait(false); } public void Dispose() diff --git a/src/Platform/Microsoft.Testing.Platform/Messages/MessageBusProxy.cs b/src/Platform/Microsoft.Testing.Platform/Messages/MessageBusProxy.cs index 20f550e813..bf1e01743f 100644 --- a/src/Platform/Microsoft.Testing.Platform/Messages/MessageBusProxy.cs +++ b/src/Platform/Microsoft.Testing.Platform/Messages/MessageBusProxy.cs @@ -16,7 +16,7 @@ public override IDataConsumer[] DataConsumerServices public override async Task InitAsync() { EnsureMessageBusAvailable(); - await _messageBus.InitAsync(); + await _messageBus.InitAsync().ConfigureAwait(false); } public void SetBuiltMessageBus(BaseMessageBus messageBus) @@ -28,19 +28,19 @@ public void SetBuiltMessageBus(BaseMessageBus messageBus) public override async Task PublishAsync(IDataProducer dataProducer, IData data) { EnsureMessageBusAvailable(); - await _messageBus.PublishAsync(dataProducer, data); + await _messageBus.PublishAsync(dataProducer, data).ConfigureAwait(false); } public override async Task DrainDataAsync() { EnsureMessageBusAvailable(); - await _messageBus.DrainDataAsync(); + await _messageBus.DrainDataAsync().ConfigureAwait(false); } public override async Task DisableAsync() { EnsureMessageBusAvailable(); - await _messageBus.DisableAsync(); + await _messageBus.DisableAsync().ConfigureAwait(false); } [MemberNotNull(nameof(_messageBus))] diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/BrowserOutputDevice.cs b/src/Platform/Microsoft.Testing.Platform/OutputDevice/BrowserOutputDevice.cs index e215879c04..97a63cf078 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/BrowserOutputDevice.cs +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/BrowserOutputDevice.cs @@ -93,7 +93,7 @@ public async Task InitializeAsync() { ConsoleLog(PlatformResources.CancellingTestSession); return Task.CompletedTask; - }); + }).ConfigureAwait(false); public Type[] DataTypesConsumed { get; } = [ @@ -119,7 +119,7 @@ public async Task InitializeAsync() public async Task DisplayBannerAsync(string? bannerMessage) { - using (await _asyncMonitor.LockAsync(TimeoutHelper.DefaultHangTimeSpanTimeout)) + using (await _asyncMonitor.LockAsync(TimeoutHelper.DefaultHangTimeSpanTimeout).ConfigureAwait(false)) { if (_bannerDisplayed) { @@ -202,7 +202,7 @@ private static void AppendAssemblyLinkTargetFrameworkAndArchitecture(IConsole co public async Task DisplayAfterSessionEndRunAsync() { - using (await _asyncMonitor.LockAsync(TimeoutHelper.DefaultHangTimeSpanTimeout)) + using (await _asyncMonitor.LockAsync(TimeoutHelper.DefaultHangTimeSpanTimeout).ConfigureAwait(false)) { if (_firstCallTo_OnSessionStartingAsync) { @@ -257,7 +257,7 @@ public Task OnTestSessionStartingAsync(SessionUid sessionUid, CancellationToken /// The data to be displayed. public async Task DisplayAsync(IOutputDeviceDataProducer producer, IOutputDeviceData data) { - using (await _asyncMonitor.LockAsync(TimeoutHelper.DefaultHangTimeSpanTimeout)) + using (await _asyncMonitor.LockAsync(TimeoutHelper.DefaultHangTimeSpanTimeout).ConfigureAwait(false)) { switch (data) { @@ -398,7 +398,7 @@ public async Task HandleProcessRoleAsync(TestProcessRole processRole) { await _policiesService.RegisterOnMaxFailedTestsCallbackAsync( async (maxFailedTests, _) => await DisplayAsync( - this, new TextOutputDeviceData(string.Format(CultureInfo.InvariantCulture, PlatformResources.ReachedMaxFailedTestsMessage, maxFailedTests)))); + this, new TextOutputDeviceData(string.Format(CultureInfo.InvariantCulture, PlatformResources.ReachedMaxFailedTestsMessage, maxFailedTests))).ConfigureAwait(false)).ConfigureAwait(false); } } } diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/OutputDeviceManager.cs b/src/Platform/Microsoft.Testing.Platform/OutputDevice/OutputDeviceManager.cs index 87ae5097ea..4248cc474e 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/OutputDeviceManager.cs +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/OutputDeviceManager.cs @@ -26,7 +26,7 @@ internal async Task BuildAsync(ServiceProvider serviceProvide : _platformOutputDeviceFactory(serviceProvider); // If the externally provided output device is not enabled, we opt-in the default terminal output device. - if (_platformOutputDeviceFactory is not null && !await nonServerOutputDevice.IsEnabledAsync()) + if (_platformOutputDeviceFactory is not null && !await nonServerOutputDevice.IsEnabledAsync().ConfigureAwait(false)) { nonServerOutputDevice = GetDefaultTerminalOutputDevice(serviceProvider); } diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/ProxyOutputDevice.cs b/src/Platform/Microsoft.Testing.Platform/OutputDevice/ProxyOutputDevice.cs index b2d0b2ed4c..4987ac93a8 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/ProxyOutputDevice.cs +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/ProxyOutputDevice.cs @@ -21,37 +21,37 @@ public ProxyOutputDevice(IPlatformOutputDevice originalOutputDevice, ServerModeP public async Task DisplayAsync(IOutputDeviceDataProducer producer, IOutputDeviceData data) { - await OriginalOutputDevice.DisplayAsync(producer, data); + await OriginalOutputDevice.DisplayAsync(producer, data).ConfigureAwait(false); if (_serverModeOutputDevice is not null) { - await _serverModeOutputDevice.DisplayAsync(producer, data); + await _serverModeOutputDevice.DisplayAsync(producer, data).ConfigureAwait(false); } } internal async Task DisplayBannerAsync(string? bannerMessage) { - await OriginalOutputDevice.DisplayBannerAsync(bannerMessage); + await OriginalOutputDevice.DisplayBannerAsync(bannerMessage).ConfigureAwait(false); if (_serverModeOutputDevice is not null) { - await _serverModeOutputDevice.DisplayBannerAsync(bannerMessage); + await _serverModeOutputDevice.DisplayBannerAsync(bannerMessage).ConfigureAwait(false); } } internal async Task DisplayBeforeSessionStartAsync() { - await OriginalOutputDevice.DisplayBeforeSessionStartAsync(); + await OriginalOutputDevice.DisplayBeforeSessionStartAsync().ConfigureAwait(false); if (_serverModeOutputDevice is not null) { - await _serverModeOutputDevice.DisplayBeforeSessionStartAsync(); + await _serverModeOutputDevice.DisplayBeforeSessionStartAsync().ConfigureAwait(false); } } internal async Task DisplayAfterSessionEndRunAsync() { - await OriginalOutputDevice.DisplayAfterSessionEndRunAsync(); + await OriginalOutputDevice.DisplayAfterSessionEndRunAsync().ConfigureAwait(false); if (_serverModeOutputDevice is not null) { - await _serverModeOutputDevice.DisplayAfterSessionEndRunAsync(); + await _serverModeOutputDevice.DisplayAfterSessionEndRunAsync().ConfigureAwait(false); } } @@ -59,16 +59,16 @@ internal async Task InitializeAsync(ServerTestHost serverTestHost) { if (_serverModeOutputDevice is not null) { - await _serverModeOutputDevice.InitializeAsync(serverTestHost); + await _serverModeOutputDevice.InitializeAsync(serverTestHost).ConfigureAwait(false); } } internal async Task HandleProcessRoleAsync(TestProcessRole processRole) { - await OriginalOutputDevice.HandleProcessRoleAsync(processRole); + await OriginalOutputDevice.HandleProcessRoleAsync(processRole).ConfigureAwait(false); if (_serverModeOutputDevice is not null) { - await _serverModeOutputDevice.HandleProcessRoleAsync(processRole); + await _serverModeOutputDevice.HandleProcessRoleAsync(processRole).ConfigureAwait(false); } } } diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/TerminalOutputDevice.cs b/src/Platform/Microsoft.Testing.Platform/OutputDevice/TerminalOutputDevice.cs index cfe454e7de..9a244d087b 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/TerminalOutputDevice.cs +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/TerminalOutputDevice.cs @@ -108,7 +108,7 @@ await _policiesService.RegisterOnAbortCallbackAsync( { _terminalTestReporter?.StartCancelling(); return Task.CompletedTask; - }); + }).ConfigureAwait(false); if (_fileLoggerInformation is not null) { @@ -195,7 +195,7 @@ private async Task LogDebugAsync(string message) { if (_logger is not null) { - await _logger.LogDebugAsync(message); + await _logger.LogDebugAsync(message).ConfigureAwait(false); } } @@ -203,7 +203,7 @@ public async Task DisplayBannerAsync(string? bannerMessage) { RoslynDebug.Assert(_terminalTestReporter is not null); - using (await _asyncMonitor.LockAsync(TimeoutHelper.DefaultHangTimeSpanTimeout)) + using (await _asyncMonitor.LockAsync(TimeoutHelper.DefaultHangTimeSpanTimeout).ConfigureAwait(false)) { if (!_bannerDisplayed) { @@ -263,7 +263,7 @@ public async Task DisplayBannerAsync(string? bannerMessage) } public async Task DisplayBeforeHotReloadSessionStartAsync() - => await DisplayBeforeSessionStartAsync(); + => await DisplayBeforeSessionStartAsync().ConfigureAwait(false); public async Task DisplayBeforeSessionStartAsync() { @@ -280,12 +280,12 @@ public async Task DisplayBeforeSessionStartAsync() _terminalTestReporter.AssemblyRunStarted(_assemblyName, _targetFramework, _shortArchitecture); if (_logger is not null && _logger.IsEnabled(LogLevel.Trace)) { - await _logger.LogTraceAsync("DisplayBeforeSessionStartAsync"); + await _logger.LogTraceAsync("DisplayBeforeSessionStartAsync").ConfigureAwait(false); } } public async Task DisplayAfterHotReloadSessionEndAsync() - => await DisplayAfterSessionEndRunInternalAsync(); + => await DisplayAfterSessionEndRunInternalAsync().ConfigureAwait(false); public async Task DisplayAfterSessionEndRunAsync() { @@ -301,14 +301,14 @@ public async Task DisplayAfterSessionEndRunAsync() return; } - await DisplayAfterSessionEndRunInternalAsync(); + await DisplayAfterSessionEndRunInternalAsync().ConfigureAwait(false); } private async Task DisplayAfterSessionEndRunInternalAsync() { RoslynDebug.Assert(_terminalTestReporter is not null); - using (await _asyncMonitor.LockAsync(TimeoutHelper.DefaultHangTimeSpanTimeout)) + using (await _asyncMonitor.LockAsync(TimeoutHelper.DefaultHangTimeSpanTimeout).ConfigureAwait(false)) { if (!_firstCallTo_OnSessionStartingAsync) { @@ -347,32 +347,32 @@ public async Task DisplayAsync(IOutputDeviceDataProducer producer, IOutputDevice { RoslynDebug.Assert(_terminalTestReporter is not null); - using (await _asyncMonitor.LockAsync(TimeoutHelper.DefaultHangTimeSpanTimeout)) + using (await _asyncMonitor.LockAsync(TimeoutHelper.DefaultHangTimeSpanTimeout).ConfigureAwait(false)) { switch (data) { case FormattedTextOutputDeviceData formattedTextData: - await LogDebugAsync(formattedTextData.Text); + await LogDebugAsync(formattedTextData.Text).ConfigureAwait(false); _terminalTestReporter.WriteMessage(formattedTextData.Text, formattedTextData.ForegroundColor as SystemConsoleColor, formattedTextData.Padding); break; case TextOutputDeviceData textData: - await LogDebugAsync(textData.Text); + await LogDebugAsync(textData.Text).ConfigureAwait(false); _terminalTestReporter.WriteMessage(textData.Text); break; case WarningMessageOutputDeviceData warningData: - await LogDebugAsync(warningData.Message); + await LogDebugAsync(warningData.Message).ConfigureAwait(false); _terminalTestReporter.WriteWarningMessage(_assemblyName, _targetFramework, _shortArchitecture, warningData.Message, null); break; case ErrorMessageOutputDeviceData errorData: - await LogDebugAsync(errorData.Message); + await LogDebugAsync(errorData.Message).ConfigureAwait(false); _terminalTestReporter.WriteErrorMessage(_assemblyName, _targetFramework, _shortArchitecture, errorData.Message, null); break; case ExceptionOutputDeviceData exceptionOutputDeviceData: - await LogDebugAsync(exceptionOutputDeviceData.Exception.ToString()); + await LogDebugAsync(exceptionOutputDeviceData.Exception.ToString()).ConfigureAwait(false); _terminalTestReporter.WriteErrorMessage(_assemblyName, _targetFramework, _shortArchitecture, exceptionOutputDeviceData.Exception); break; } @@ -579,7 +579,7 @@ public async Task HandleProcessRoleAsync(TestProcessRole processRole) { await _policiesService.RegisterOnMaxFailedTestsCallbackAsync( async (maxFailedTests, _) => await DisplayAsync( - this, new TextOutputDeviceData(string.Format(CultureInfo.InvariantCulture, PlatformResources.ReachedMaxFailedTestsMessage, maxFailedTests)))); + this, new TextOutputDeviceData(string.Format(CultureInfo.InvariantCulture, PlatformResources.ReachedMaxFailedTestsMessage, maxFailedTests))).ConfigureAwait(false)).ConfigureAwait(false); } } } diff --git a/src/Platform/Microsoft.Testing.Platform/Requests/ConsoleTestExecutionRequestFactory.cs b/src/Platform/Microsoft.Testing.Platform/Requests/ConsoleTestExecutionRequestFactory.cs index e4da6701f6..b31feb6d14 100644 --- a/src/Platform/Microsoft.Testing.Platform/Requests/ConsoleTestExecutionRequestFactory.cs +++ b/src/Platform/Microsoft.Testing.Platform/Requests/ConsoleTestExecutionRequestFactory.cs @@ -15,7 +15,7 @@ internal sealed class ConsoleTestExecutionRequestFactory(ICommandLineOptions com public async Task CreateRequestAsync(TestSessionContext session) { - (bool created, ITestExecutionFilter? testExecutionFilter) = await _testExecutionFilterFactory.TryCreateAsync(); + (bool created, ITestExecutionFilter? testExecutionFilter) = await _testExecutionFilterFactory.TryCreateAsync().ConfigureAwait(false); if (!created) { throw new InvalidOperationException(PlatformResources.CannotCreateTestExecutionFilterErrorMessage); diff --git a/src/Platform/Microsoft.Testing.Platform/Requests/TestHostTestFrameworkInvoker.cs b/src/Platform/Microsoft.Testing.Platform/Requests/TestHostTestFrameworkInvoker.cs index f44eb1e82b..0ba1974901 100644 --- a/src/Platform/Microsoft.Testing.Platform/Requests/TestHostTestFrameworkInvoker.cs +++ b/src/Platform/Microsoft.Testing.Platform/Requests/TestHostTestFrameworkInvoker.cs @@ -37,40 +37,40 @@ public async Task ExecuteAsync(ITestFramework testFramework, ClientInfo client, { ILogger logger = ServiceProvider.GetLoggerFactory().CreateLogger(); - await logger.LogInformationAsync($"Test framework UID: '{testFramework.Uid}' Version: '{testFramework.Version}' DisplayName: '{testFramework.DisplayName}' Description: '{testFramework.Description}'"); + await logger.LogInformationAsync($"Test framework UID: '{testFramework.Uid}' Version: '{testFramework.Version}' DisplayName: '{testFramework.DisplayName}' Description: '{testFramework.Description}'").ConfigureAwait(false); foreach (ICapability capability in ServiceProvider.GetTestFrameworkCapabilities().Capabilities) { if (capability is ITestNodesTreeFilterTestFrameworkCapability testNodesTreeFilterCapability) { - await logger.LogInformationAsync($"ITestNodesTreeFilterCapability.IsSupported: {testNodesTreeFilterCapability.IsSupported}"); + await logger.LogInformationAsync($"ITestNodesTreeFilterCapability.IsSupported: {testNodesTreeFilterCapability.IsSupported}").ConfigureAwait(false); } } DateTimeOffset startTime = DateTimeOffset.UtcNow; var stopwatch = Stopwatch.StartNew(); SessionUid sessionId = ServiceProvider.GetTestSessionContext().SessionId; - CreateTestSessionResult createTestSessionResult = await testFramework.CreateTestSessionAsync(new(sessionId, client, cancellationToken)); - await HandleTestSessionResultAsync(createTestSessionResult.IsSuccess, createTestSessionResult.WarningMessage, createTestSessionResult.ErrorMessage); + CreateTestSessionResult createTestSessionResult = await testFramework.CreateTestSessionAsync(new(sessionId, client, cancellationToken)).ConfigureAwait(false); + await HandleTestSessionResultAsync(createTestSessionResult.IsSuccess, createTestSessionResult.WarningMessage, createTestSessionResult.ErrorMessage).ConfigureAwait(false); ITestExecutionRequestFactory testExecutionRequestFactory = ServiceProvider.GetTestExecutionRequestFactory(); - TestExecutionRequest request = await testExecutionRequestFactory.CreateRequestAsync(new(sessionId, client)); + TestExecutionRequest request = await testExecutionRequestFactory.CreateRequestAsync(new(sessionId, client)).ConfigureAwait(false); IMessageBus messageBus = ServiceProvider.GetMessageBus(); // Execute the test request - await ExecuteRequestAsync(testFramework, request, messageBus, cancellationToken); + await ExecuteRequestAsync(testFramework, request, messageBus, cancellationToken).ConfigureAwait(false); - CloseTestSessionResult closeTestSessionResult = await testFramework.CloseTestSessionAsync(new(sessionId, client, cancellationToken)); - await HandleTestSessionResultAsync(closeTestSessionResult.IsSuccess, closeTestSessionResult.WarningMessage, closeTestSessionResult.ErrorMessage); + CloseTestSessionResult closeTestSessionResult = await testFramework.CloseTestSessionAsync(new(sessionId, client, cancellationToken)).ConfigureAwait(false); + await HandleTestSessionResultAsync(closeTestSessionResult.IsSuccess, closeTestSessionResult.WarningMessage, closeTestSessionResult.ErrorMessage).ConfigureAwait(false); DateTimeOffset endTime = DateTimeOffset.UtcNow; - await messageBus.PublishAsync(this, new TestRequestExecutionTimeInfo(new TimingInfo(startTime, endTime, stopwatch.Elapsed))); + await messageBus.PublishAsync(this, new TestRequestExecutionTimeInfo(new TimingInfo(startTime, endTime, stopwatch.Elapsed))).ConfigureAwait(false); } public virtual async Task ExecuteRequestAsync(ITestFramework testFramework, TestExecutionRequest request, IMessageBus messageBus, CancellationToken cancellationToken) { using SemaphoreSlim requestSemaphore = new(0, 1); - await testFramework.ExecuteRequestAsync(new(request, messageBus, new SemaphoreSlimRequestCompleteNotifier(requestSemaphore), cancellationToken)); - await requestSemaphore.WaitAsync(cancellationToken); + await testFramework.ExecuteRequestAsync(new(request, messageBus, new SemaphoreSlimRequestCompleteNotifier(requestSemaphore), cancellationToken)).ConfigureAwait(false); + await requestSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false); } private async Task HandleTestSessionResultAsync(bool isSuccess, string? warningMessage, string? errorMessage) @@ -78,14 +78,14 @@ private async Task HandleTestSessionResultAsync(bool isSuccess, string? warningM if (warningMessage is not null) { IOutputDevice outputDisplay = ServiceProvider.GetOutputDevice(); - await outputDisplay.DisplayAsync(this, new WarningMessageOutputDeviceData(warningMessage)); + await outputDisplay.DisplayAsync(this, new WarningMessageOutputDeviceData(warningMessage)).ConfigureAwait(false); } if (!isSuccess) { ITestApplicationProcessExitCode testApplicationProcessExitCode = ServiceProvider.GetTestApplicationProcessExitCode(); await testApplicationProcessExitCode.SetTestAdapterTestSessionFailureAsync(errorMessage - ?? PlatformResources.TestHostAdapterInvokerFailedTestSessionErrorMessage); + ?? PlatformResources.TestHostAdapterInvokerFailedTestSessionErrorMessage).ConfigureAwait(false); } } } diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/DotnetTestConnection.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/DotnetTestConnection.cs index b6cba24fa5..d69a7c0220 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/DotnetTestConnection.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/DotnetTestConnection.cs @@ -61,7 +61,7 @@ public async Task AfterCommonServiceSetupAsync() _dotnetTestPipeClient = new(arguments[0]); _dotnetTestPipeClient.RegisterAllSerializers(); - await _dotnetTestPipeClient.ConnectAsync(_cancellationTokenSource.CancellationToken); + await _dotnetTestPipeClient.ConnectAsync(_cancellationTokenSource.CancellationToken).ConfigureAwait(false); } } @@ -87,7 +87,7 @@ public async Task HelpInvokedAsync() } } - await _dotnetTestPipeClient.RequestReplyAsync(new CommandLineOptionMessages(_testApplicationModuleInfo.GetCurrentTestApplicationFullPath(), [.. commandLineHelpOptions.OrderBy(option => option.Name)]), _cancellationTokenSource.CancellationToken); + await _dotnetTestPipeClient.RequestReplyAsync(new CommandLineOptionMessages(_testApplicationModuleInfo.GetCurrentTestApplicationFullPath(), [.. commandLineHelpOptions.OrderBy(option => option.Name)]), _cancellationTokenSource.CancellationToken).ConfigureAwait(false); } public async Task IsCompatibleProtocolAsync(string hostType) @@ -108,7 +108,7 @@ public async Task IsCompatibleProtocolAsync(string hostType) { HandshakeMessagePropertyNames.InstanceId, InstanceId }, }); - HandshakeMessage response = await _dotnetTestPipeClient.RequestReplyAsync(handshakeMessage, _cancellationTokenSource.CancellationToken); + HandshakeMessage response = await _dotnetTestPipeClient.RequestReplyAsync(handshakeMessage, _cancellationTokenSource.CancellationToken).ConfigureAwait(false); return response.Properties?.TryGetValue(HandshakeMessagePropertyNames.SupportedProtocolVersions, out string? protocolVersion) == true && IsVersionCompatible(protocolVersion, supportedProtocolVersions); @@ -123,19 +123,19 @@ public async Task SendMessageAsync(IRequest message) switch (message) { case DiscoveredTestMessages discoveredTestMessages: - await _dotnetTestPipeClient.RequestReplyAsync(discoveredTestMessages, _cancellationTokenSource.CancellationToken); + await _dotnetTestPipeClient.RequestReplyAsync(discoveredTestMessages, _cancellationTokenSource.CancellationToken).ConfigureAwait(false); break; case TestResultMessages testResultMessages: - await _dotnetTestPipeClient.RequestReplyAsync(testResultMessages, _cancellationTokenSource.CancellationToken); + await _dotnetTestPipeClient.RequestReplyAsync(testResultMessages, _cancellationTokenSource.CancellationToken).ConfigureAwait(false); break; case FileArtifactMessages fileArtifactMessages: - await _dotnetTestPipeClient.RequestReplyAsync(fileArtifactMessages, _cancellationTokenSource.CancellationToken); + await _dotnetTestPipeClient.RequestReplyAsync(fileArtifactMessages, _cancellationTokenSource.CancellationToken).ConfigureAwait(false); break; case TestSessionEvent testSessionEvent: - await _dotnetTestPipeClient.RequestReplyAsync(testSessionEvent, _cancellationTokenSource.CancellationToken); + await _dotnetTestPipeClient.RequestReplyAsync(testSessionEvent, _cancellationTokenSource.CancellationToken).ConfigureAwait(false); break; } } @@ -149,7 +149,7 @@ public async ValueTask DisposeAsync() { if (_dotnetTestPipeClient is not null) { - await _dotnetTestPipeClient.DisposeAsync(); + await _dotnetTestPipeClient.DisposeAsync().ConfigureAwait(false); } } #endif diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/DotnetTestDataConsumer.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/DotnetTestDataConsumer.cs index 1c23eb623e..f15c188df0 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/DotnetTestDataConsumer.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/DotnetTestDataConsumer.cs @@ -65,7 +65,7 @@ public async Task ConsumeAsync(IDataProducer dataProducer, IData value, Cancella testNodeUpdateMessage.TestNode.DisplayName) ]); - await _dotnetTestConnection.SendMessageAsync(discoveredTestMessages); + await _dotnetTestConnection.SendMessageAsync(discoveredTestMessages).ConfigureAwait(false); break; case TestStates.Passed: @@ -86,7 +86,7 @@ public async Task ConsumeAsync(IDataProducer dataProducer, IData value, Cancella ], []); - await _dotnetTestConnection.SendMessageAsync(testResultMessages); + await _dotnetTestConnection.SendMessageAsync(testResultMessages).ConfigureAwait(false); break; case TestStates.Failed: @@ -110,7 +110,7 @@ public async Task ConsumeAsync(IDataProducer dataProducer, IData value, Cancella testNodeUpdateMessage.SessionUid.Value) ]); - await _dotnetTestConnection.SendMessageAsync(testResultMessages); + await _dotnetTestConnection.SendMessageAsync(testResultMessages).ConfigureAwait(false); break; } @@ -129,7 +129,7 @@ public async Task ConsumeAsync(IDataProducer dataProducer, IData value, Cancella testNodeUpdateMessage.SessionUid.Value) ]); - await _dotnetTestConnection.SendMessageAsync(testFileArtifactMessages); + await _dotnetTestConnection.SendMessageAsync(testFileArtifactMessages).ConfigureAwait(false); } break; @@ -148,7 +148,7 @@ public async Task ConsumeAsync(IDataProducer dataProducer, IData value, Cancella sessionFileArtifact.SessionUid.Value) ]); - await _dotnetTestConnection.SendMessageAsync(fileArtifactMessages); + await _dotnetTestConnection.SendMessageAsync(fileArtifactMessages).ConfigureAwait(false); break; case FileArtifact fileArtifact: @@ -165,7 +165,7 @@ public async Task ConsumeAsync(IDataProducer dataProducer, IData value, Cancella string.Empty) ]); - await _dotnetTestConnection.SendMessageAsync(fileArtifactMessages); + await _dotnetTestConnection.SendMessageAsync(fileArtifactMessages).ConfigureAwait(false); break; } } @@ -265,7 +265,7 @@ public async Task OnTestSessionStartingAsync(SessionUid sessionUid, Cancellation sessionUid.Value, ExecutionId); - await _dotnetTestConnection.SendMessageAsync(sessionStartEvent); + await _dotnetTestConnection.SendMessageAsync(sessionStartEvent).ConfigureAwait(false); } public async Task OnTestSessionFinishingAsync(SessionUid sessionUid, CancellationToken cancellationToken) @@ -277,6 +277,6 @@ public async Task OnTestSessionFinishingAsync(SessionUid sessionUid, Cancellatio sessionUid.Value, ExecutionId); - await _dotnetTestConnection.SendMessageAsync(sessionEndEvent); + await _dotnetTestConnection.SendMessageAsync(sessionEndEvent).ConfigureAwait(false); } } diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/Json/Json.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/Json/Json.cs index c6a35fe518..10d0771284 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/Json/Json.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/Json/Json.cs @@ -603,9 +603,11 @@ public async Task SerializeAsync(object obj) try { stream.Position = 0; +#pragma warning disable CA2007 // Consider calling ConfigureAwait on the awaited task await using Utf8JsonWriter writer = new(stream); - await SerializeAsync(obj, writer); - await writer.FlushAsync(); +#pragma warning restore CA2007 // Consider calling ConfigureAwait on the awaited task + await SerializeAsync(obj, writer).ConfigureAwait(false); + await writer.FlushAsync().ConfigureAwait(false); return Encoding.UTF8.GetString(stream.GetBuffer().AsMemory().Span[..(int)stream.Position]); } finally @@ -710,7 +712,7 @@ private async Task SerializeAsync(object? obj, Utf8JsonWriter writer) foreach ((string property, object? value) in properties) { writer.WritePropertyName(property); - await SerializeAsync(value, writer); + await SerializeAsync(value, writer).ConfigureAwait(false); } } @@ -737,7 +739,7 @@ private async Task SerializeAsync(object? obj, Utf8JsonWriter writer) } else { - await SerializeAsync(o, writer); + await SerializeAsync(o, writer).ConfigureAwait(false); } } diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/MessageHandlerFactory.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/MessageHandlerFactory.cs index 060a2a7562..3deba13219 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/MessageHandlerFactory.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/MessageHandlerFactory.cs @@ -42,14 +42,14 @@ public MessageHandlerFactory( #pragma warning disable CA1416 // Validate platform compatibility public async Task CreateMessageHandlerAsync(CancellationToken cancellationToken) { - await _outputDevice.DisplayAsync(this, new TextOutputDeviceData(string.Format(CultureInfo.InvariantCulture, PlatformResources.ConnectingToClientHost, _host, _port))); + await _outputDevice.DisplayAsync(this, new TextOutputDeviceData(string.Format(CultureInfo.InvariantCulture, PlatformResources.ConnectingToClientHost, _host, _port))).ConfigureAwait(false); TcpClient client = new(); #if NETCOREAPP - await client.ConnectAsync(host: _host, port: _port, cancellationToken); + await client.ConnectAsync(host: _host, port: _port, cancellationToken).ConfigureAwait(false); #else - await client.ConnectAsync(host: _host, port: _port).WithCancellationAsync(cancellationToken, observeException: true); + await client.ConnectAsync(host: _host, port: _port).WithCancellationAsync(cancellationToken, observeException: true).ConfigureAwait(false); #endif NetworkStream stream = client.GetStream(); return new TcpMessageHandler(client, clientToServerStream: stream, serverToClientStream: stream, FormatterUtilities.CreateFormatter()); diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/PassiveNode.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/PassiveNode.cs index 9ab9878ce0..9bd65b9908 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/PassiveNode.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/PassiveNode.cs @@ -42,12 +42,12 @@ public void AssertInitialized() public async Task ConnectAsync() { // Create message handler - await _logger.LogDebugAsync("Create message handler"); - _messageHandler = await _messageHandlerFactory.CreateMessageHandlerAsync(_testApplicationCancellationTokenSource.CancellationToken); + await _logger.LogDebugAsync("Create message handler").ConfigureAwait(false); + _messageHandler = await _messageHandlerFactory.CreateMessageHandlerAsync(_testApplicationCancellationTokenSource.CancellationToken).ConfigureAwait(false); // Wait the initial message - await _logger.LogDebugAsync("Wait the initial message"); - RpcMessage? message = await _messageHandler.ReadAsync(_testApplicationCancellationTokenSource.CancellationToken); + await _logger.LogDebugAsync("Wait the initial message").ConfigureAwait(false); + RpcMessage? message = await _messageHandler.ReadAsync(_testApplicationCancellationTokenSource.CancellationToken).ConfigureAwait(false); if (message is null) { return false; @@ -56,7 +56,7 @@ public async Task ConnectAsync() // Log the message if (_logger.IsEnabled(LogLevel.Trace)) { - await _logger.LogTraceAsync(message!.ToString()); + await _logger.LogTraceAsync(message!.ToString()).ConfigureAwait(false); } var requestMessage = (RequestMessage)message; @@ -73,7 +73,7 @@ public async Task ConnectAsync() // This means we're a push node MultiConnectionProvider: true))); - await SendResponseAsync(requestMessage.Id, responseObject, _testApplicationCancellationTokenSource.CancellationToken); + await SendResponseAsync(requestMessage.Id, responseObject, _testApplicationCancellationTokenSource.CancellationToken).ConfigureAwait(false); return true; } @@ -82,9 +82,9 @@ private async Task SendResponseAsync(int reqId, object result, CancellationToken AssertInitialized(); ResponseMessage response = new(reqId, result); - using (await _messageMonitor.LockAsync(cancellationToken)) + using (await _messageMonitor.LockAsync(cancellationToken).ConfigureAwait(false)) { - await _messageHandler.WriteRequestAsync(response, cancellationToken); + await _messageHandler.WriteRequestAsync(response, cancellationToken).ConfigureAwait(false); } } @@ -93,9 +93,9 @@ public async Task SendAttachmentsAsync(TestsAttachments testsAttachments, Cancel AssertInitialized(); NotificationMessage notification = new(JsonRpcMethods.TestingTestUpdatesAttachments, testsAttachments); - using (await _messageMonitor.LockAsync(cancellationToken)) + using (await _messageMonitor.LockAsync(cancellationToken).ConfigureAwait(false)) { - await _messageHandler.WriteRequestAsync(notification, cancellationToken); + await _messageHandler.WriteRequestAsync(notification, cancellationToken).ConfigureAwait(false); } } diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/PerRequestServerDataConsumerService.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/PerRequestServerDataConsumerService.cs index 30b26041f2..f61fad28a0 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/PerRequestServerDataConsumerService.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/PerRequestServerDataConsumerService.cs @@ -92,7 +92,7 @@ private async Task ProcessTestNodeUpdateAsync(TestNodeUpdateMessage update, Canc try { - await _nodeAggregatorSemaphore.WaitAsync(cancellationToken); + await _nodeAggregatorSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false); try { // Note: If there's no changes to aggregate kick off a background task, @@ -108,7 +108,7 @@ private async Task ProcessTestNodeUpdateAsync(TestNodeUpdateMessage update, Canc // Observe possible exceptions try { - await _idleUpdateTask.TimeoutAfterAsync(TimeoutHelper.DefaultHangTimeSpanTimeout, cancellationToken); + await _idleUpdateTask.TimeoutAfterAsync(TimeoutHelper.DefaultHangTimeSpanTimeout, cancellationToken).ConfigureAwait(false); } catch (OperationCanceledException) { @@ -144,14 +144,14 @@ private async Task SendTestNodeUpdatesOnIdleAsync(Guid runId) // When batch timer expire or we're at the end of the session we can unblock the message drain Guard.NotNull(_task); - await Task.WhenAny(_task.Delay(TimeSpan.FromMilliseconds(TestNodeUpdateDelayInMs), cancellationToken), _testSessionEnd.Task); + await Task.WhenAny(_task.Delay(TimeSpan.FromMilliseconds(TestNodeUpdateDelayInMs), cancellationToken), _testSessionEnd.Task).ConfigureAwait(false); if (cancellationToken.IsCancellationRequested) { return; } - await SendTestNodeUpdatesIfNecessaryAsync(runId, cancellationToken); + await SendTestNodeUpdatesIfNecessaryAsync(runId, cancellationToken).ConfigureAwait(false); } catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) { @@ -165,11 +165,11 @@ private async Task SendTestNodeUpdatesIfNecessaryAsync(Guid runId, CancellationT // and the Task completes, all of the pending updates have been sent. // We synchronize the aggregator access with a separate lock, so that sending // the update message will not block the producers. - await _nodeUpdateSemaphore.WaitAsync(cancellationToken); + await _nodeUpdateSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false); try { TestNodeStateChangedEventArgs? change = null; - await _nodeAggregatorSemaphore.WaitAsync(cancellationToken); + await _nodeAggregatorSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false); try { if (_nodeUpdatesAggregator.HasChanges) @@ -185,7 +185,7 @@ private async Task SendTestNodeUpdatesIfNecessaryAsync(Guid runId, CancellationT if (change is not null) { - await _serverTestHost.SendTestUpdateAsync(change); + await _serverTestHost.SendTestUpdateAsync(change).ConfigureAwait(false); } } finally @@ -200,7 +200,7 @@ public async Task OnTestSessionFinishingAsync(SessionUid sessionUid, Cancellatio { // We signal the test session end so we can complete the flush. _testSessionEnd.SetResult(true); - await GetIdleUpdateTaskAsync().TimeoutAfterAsync(TimeoutHelper.DefaultHangTimeSpanTimeout, cancellationToken); + await GetIdleUpdateTaskAsync().TimeoutAfterAsync(TimeoutHelper.DefaultHangTimeSpanTimeout, cancellationToken).ConfigureAwait(false); } catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) { @@ -218,7 +218,7 @@ public async Task ConsumeAsync(IDataProducer dataProducer, IData value, Cancella switch (value) { case TestNodeUpdateMessage update: - await ProcessTestNodeUpdateAsync(update, cancellationToken); + await ProcessTestNodeUpdateAsync(update, cancellationToken).ConfigureAwait(false); PopulateTestNodeStatistics(update); break; diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/ServerModePerCallOutputDevice.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/ServerModePerCallOutputDevice.cs index d15e47b46f..406f7419a4 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/ServerModePerCallOutputDevice.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/ServerModePerCallOutputDevice.cs @@ -41,7 +41,7 @@ internal async Task InitializeAsync(IServerTestHost serverTestHost) foreach (ServerLogMessage message in _messages) { - await LogAsync(message); + await LogAsync(message).ConfigureAwait(false); } _messages.Clear(); @@ -56,30 +56,30 @@ internal async Task InitializeAsync(IServerTestHost serverTestHost) public string Description => nameof(ServerModePerCallOutputDevice); public async Task DisplayAfterSessionEndRunAsync() - => await LogAsync(LogLevel.Trace, PlatformResources.FinishedTestSession, padding: null); + => await LogAsync(LogLevel.Trace, PlatformResources.FinishedTestSession, padding: null).ConfigureAwait(false); public async Task DisplayAsync(IOutputDeviceDataProducer producer, IOutputDeviceData data) { switch (data) { case FormattedTextOutputDeviceData formattedTextOutputDeviceData: - await LogAsync(LogLevel.Information, formattedTextOutputDeviceData.Text, formattedTextOutputDeviceData.Padding); + await LogAsync(LogLevel.Information, formattedTextOutputDeviceData.Text, formattedTextOutputDeviceData.Padding).ConfigureAwait(false); break; case TextOutputDeviceData textOutputDeviceData: - await LogAsync(LogLevel.Information, textOutputDeviceData.Text, padding: null); + await LogAsync(LogLevel.Information, textOutputDeviceData.Text, padding: null).ConfigureAwait(false); break; case WarningMessageOutputDeviceData warningData: - await LogAsync(LogLevel.Warning, warningData.Message, padding: null); + await LogAsync(LogLevel.Warning, warningData.Message, padding: null).ConfigureAwait(false); break; case ErrorMessageOutputDeviceData errorData: - await LogAsync(LogLevel.Error, errorData.Message, padding: null); + await LogAsync(LogLevel.Error, errorData.Message, padding: null).ConfigureAwait(false); break; case ExceptionOutputDeviceData exceptionOutputDeviceData: - await LogAsync(LogLevel.Error, exceptionOutputDeviceData.Exception.ToString(), padding: null); + await LogAsync(LogLevel.Error, exceptionOutputDeviceData.Exception.ToString(), padding: null).ConfigureAwait(false); break; } } @@ -88,7 +88,7 @@ public async Task DisplayBannerAsync(string? bannerMessage) { if (bannerMessage is not null) { - await LogAsync(LogLevel.Debug, bannerMessage, padding: null); + await LogAsync(LogLevel.Debug, bannerMessage, padding: null).ConfigureAwait(false); } } @@ -96,18 +96,18 @@ public async Task DisplayBeforeSessionStartAsync() { if (_fileLoggerProvider is { FileLogger.FileName: { } logFileName }) { - await LogAsync(LogLevel.Trace, string.Format(CultureInfo.InvariantCulture, PlatformResources.StartingTestSessionWithLogFilePath, logFileName), padding: null); + await LogAsync(LogLevel.Trace, string.Format(CultureInfo.InvariantCulture, PlatformResources.StartingTestSessionWithLogFilePath, logFileName), padding: null).ConfigureAwait(false); } else { - await LogAsync(LogLevel.Trace, PlatformResources.StartingTestSession, padding: null); + await LogAsync(LogLevel.Trace, PlatformResources.StartingTestSession, padding: null).ConfigureAwait(false); } } public Task IsEnabledAsync() => Task.FromResult(true); private async Task LogAsync(LogLevel logLevel, string message, int? padding) - => await LogAsync(GetServerLogMessage(logLevel, message, padding)); + => await LogAsync(GetServerLogMessage(logLevel, message, padding)).ConfigureAwait(false); private async Task LogAsync(ServerLogMessage message) { @@ -117,7 +117,7 @@ private async Task LogAsync(ServerLogMessage message) } else { - await _serverTestHost.PushDataAsync(message); + await _serverTestHost.PushDataAsync(message).ConfigureAwait(false); } } @@ -156,7 +156,7 @@ public async Task HandleProcessRoleAsync(TestProcessRole processRole) { await _policiesService.RegisterOnMaxFailedTestsCallbackAsync( async (maxFailedTests, _) => await DisplayAsync( - this, new TextOutputDeviceData(string.Format(CultureInfo.InvariantCulture, PlatformResources.ReachedMaxFailedTestsMessage, maxFailedTests)))); + this, new TextOutputDeviceData(string.Format(CultureInfo.InvariantCulture, PlatformResources.ReachedMaxFailedTestsMessage, maxFailedTests))).ConfigureAwait(false)).ConfigureAwait(false); } } } diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/StreamMessageHandler.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/StreamMessageHandler.cs index 474d8c1eb9..9efdf0535b 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/StreamMessageHandler.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/StreamMessageHandler.cs @@ -43,7 +43,7 @@ public StreamMessageHandler( // [content]\r\n while (true) { - int commandSize = await ReadHeadersAsync(cancellationToken); + int commandSize = await ReadHeadersAsync(cancellationToken).ConfigureAwait(false); // Most probably connection lost if (commandSize is -1) @@ -56,7 +56,7 @@ public StreamMessageHandler( try { Memory memoryBuffer = new(commandCharsBuffer, 0, commandSize); - await _reader.ReadBlockAsync(memoryBuffer, cancellationToken); + await _reader.ReadBlockAsync(memoryBuffer, cancellationToken).ConfigureAwait(false); return _formatter.Deserialize(memoryBuffer); } finally @@ -65,7 +65,7 @@ public StreamMessageHandler( } #else char[] commandChars = new char[commandSize]; - await _reader.ReadBlockAsync(commandChars, 0, commandSize).WithCancellationAsync(cancellationToken); + await _reader.ReadBlockAsync(commandChars, 0, commandSize).WithCancellationAsync(cancellationToken).ConfigureAwait(false); return _formatter.Deserialize(new string(commandChars, 0, commandSize)); #endif } @@ -78,11 +78,11 @@ private async Task ReadHeadersAsync(CancellationToken cancellationToken) while (true) { #if NET7_0_OR_GREATER - string? line = await _reader.ReadLineAsync(cancellationToken); + string? line = await _reader.ReadLineAsync(cancellationToken).ConfigureAwait(false); #elif NET6_0_OR_GREATER - string? line = await _reader.ReadLineAsync().WaitAsync(cancellationToken); + string? line = await _reader.ReadLineAsync().WaitAsync(cancellationToken).ConfigureAwait(false); #else - string? line = await _reader.ReadLineAsync().WithCancellationAsync(cancellationToken); + string? line = await _reader.ReadLineAsync().WithCancellationAsync(cancellationToken).ConfigureAwait(false); #endif if (line is null || (line.Length == 0 && contentSize != -1)) { @@ -106,12 +106,12 @@ private async Task ReadHeadersAsync(CancellationToken cancellationToken) public async Task WriteRequestAsync(RpcMessage message, CancellationToken cancellationToken) { - string messageStr = await _formatter.SerializeAsync(message); - await _writer.WriteLineAsync($"Content-Length: {Encoding.UTF8.GetByteCount(messageStr)}"); - await _writer.WriteLineAsync("Content-Type: application/testingplatform"); - await _writer.WriteLineAsync(); - await _writer.WriteAsync(messageStr); - await _writer.FlushAsync(cancellationToken); + string messageStr = await _formatter.SerializeAsync(message).ConfigureAwait(false); + await _writer.WriteLineAsync($"Content-Length: {Encoding.UTF8.GetByteCount(messageStr)}").ConfigureAwait(false); + await _writer.WriteLineAsync("Content-Type: application/testingplatform").ConfigureAwait(false); + await _writer.WriteLineAsync().ConfigureAwait(false); + await _writer.WriteAsync(messageStr).ConfigureAwait(false); + await _writer.FlushAsync(cancellationToken).ConfigureAwait(false); } protected virtual void Dispose(bool disposing) diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/TcpMessageHandler.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/TcpMessageHandler.cs index 1ea27abcde..e72aff6780 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/TcpMessageHandler.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/TcpMessageHandler.cs @@ -17,7 +17,7 @@ internal sealed class TcpMessageHandler( { try { - return await base.ReadAsync(cancellationToken); + return await base.ReadAsync(cancellationToken).ConfigureAwait(false); } // Client close the connection in an unexpected way diff --git a/src/Platform/Microsoft.Testing.Platform/Services/StopPoliciesService.cs b/src/Platform/Microsoft.Testing.Platform/Services/StopPoliciesService.cs index 79a71c1489..b9b2aed89b 100644 --- a/src/Platform/Microsoft.Testing.Platform/Services/StopPoliciesService.cs +++ b/src/Platform/Microsoft.Testing.Platform/Services/StopPoliciesService.cs @@ -19,7 +19,7 @@ public StopPoliciesService(ITestApplicationCancellationTokenSource testApplicati #pragma warning disable VSTHRD101 // Avoid unsupported async delegates // Note: If cancellation already requested, Register will still invoke the callback. - testApplicationCancellationTokenSource.CancellationToken.Register(async () => await ExecuteAbortCallbacksAsync()); + testApplicationCancellationTokenSource.CancellationToken.Register(async () => await ExecuteAbortCallbacksAsync().ConfigureAwait(false)); #pragma warning restore VSTHRD101 // Avoid unsupported async delegates } @@ -47,7 +47,7 @@ public async Task ExecuteMaxFailedTestsCallbacksAsync(int maxFailedTests, Cancel { // For now, we are fine if the callback crashed us. It shouldn't happen for our // current usage anyway and the APIs around this are all internal for now. - await callback.Invoke(maxFailedTests, cancellationToken); + await callback.Invoke(maxFailedTests, cancellationToken).ConfigureAwait(false); } } @@ -64,7 +64,7 @@ public async Task ExecuteAbortCallbacksAsync() { // For now, we are fine if the callback crashed us. It shouldn't happen for our // current usage anyway and the APIs around this are all internal for now. - await callback.Invoke(); + await callback.Invoke().ConfigureAwait(false); } } @@ -77,7 +77,7 @@ public async Task RegisterOnMaxFailedTestsCallbackAsync(Func callback) { if (IsAbortTriggered) { - await callback(); + await callback().ConfigureAwait(false); } RegisterCallback(ref _abortCallbacks, callback); diff --git a/src/Platform/Microsoft.Testing.Platform/Services/TestApplicationResult.cs b/src/Platform/Microsoft.Testing.Platform/Services/TestApplicationResult.cs index fd7ee1e415..4f2d9a7caf 100644 --- a/src/Platform/Microsoft.Testing.Platform/Services/TestApplicationResult.cs +++ b/src/Platform/Microsoft.Testing.Platform/Services/TestApplicationResult.cs @@ -125,7 +125,7 @@ public async Task SetTestAdapterTestSessionFailureAsync(string errorMessage) { TestAdapterTestSessionFailureErrorMessage = errorMessage; _testAdapterTestSessionFailure = true; - await _outputService.DisplayAsync(this, new ErrorMessageOutputDeviceData(errorMessage)); + await _outputService.DisplayAsync(this, new ErrorMessageOutputDeviceData(errorMessage)).ConfigureAwait(false); } public Statistics GetStatistics() diff --git a/src/Platform/Microsoft.Testing.Platform/Telemetry/ExtensionInformationCollector.cs b/src/Platform/Microsoft.Testing.Platform/Telemetry/ExtensionInformationCollector.cs index ff91fab992..dbff0964d6 100644 --- a/src/Platform/Microsoft.Testing.Platform/Telemetry/ExtensionInformationCollector.cs +++ b/src/Platform/Microsoft.Testing.Platform/Telemetry/ExtensionInformationCollector.cs @@ -25,7 +25,7 @@ public static async Task CollectAndSerializeToJsonAsync(ServiceProvider { if (service is IExtension extension) { - extensionsInformation.Add(new ExtensionInformation(Sha256Hasher.HashWithNormalizedCasing(extension.Uid), extension.Version, await extension.IsEnabledAsync())); + extensionsInformation.Add(new ExtensionInformation(Sha256Hasher.HashWithNormalizedCasing(extension.Uid), extension.Version, await extension.IsEnabledAsync().ConfigureAwait(false))); } if (service is MessageBusProxy messageBus) @@ -34,7 +34,7 @@ public static async Task CollectAndSerializeToJsonAsync(ServiceProvider { if (dataConsumer is IExtension extension1) { - extensionsInformation.Add(new ExtensionInformation(Sha256Hasher.HashWithNormalizedCasing(extension1.Uid), extension1.Version, await extension1.IsEnabledAsync())); + extensionsInformation.Add(new ExtensionInformation(Sha256Hasher.HashWithNormalizedCasing(extension1.Uid), extension1.Version, await extension1.IsEnabledAsync().ConfigureAwait(false))); } } } diff --git a/src/Platform/Microsoft.Testing.Platform/Telemetry/ServerTelemetry.cs b/src/Platform/Microsoft.Testing.Platform/Telemetry/ServerTelemetry.cs index 01646f0f4e..27a2b92a74 100644 --- a/src/Platform/Microsoft.Testing.Platform/Telemetry/ServerTelemetry.cs +++ b/src/Platform/Microsoft.Testing.Platform/Telemetry/ServerTelemetry.cs @@ -13,9 +13,9 @@ internal sealed class ServerTelemetry(IServerTestHost serverTestHost) : ITelemet public async Task LogEventAsync(string eventName, IDictionary paramsMap) { TelemetryEventArgs logMessage = new(eventName, paramsMap); - await PushTelemetryToServerTestHostAsync(logMessage); + await PushTelemetryToServerTestHostAsync(logMessage).ConfigureAwait(false); } private async Task PushTelemetryToServerTestHostAsync(TelemetryEventArgs telemetryEvent) - => await _serverTestHost.SendTelemetryEventUpdateAsync(telemetryEvent); + => await _serverTestHost.SendTelemetryEventUpdateAsync(telemetryEvent).ConfigureAwait(false); } diff --git a/src/Platform/Microsoft.Testing.Platform/Telemetry/TelemetryManager.cs b/src/Platform/Microsoft.Testing.Platform/Telemetry/TelemetryManager.cs index c96926d870..f2227455b4 100644 --- a/src/Platform/Microsoft.Testing.Platform/Telemetry/TelemetryManager.cs +++ b/src/Platform/Microsoft.Testing.Platform/Telemetry/TelemetryManager.cs @@ -35,23 +35,23 @@ public async Task BuildAsync(ServiceProvider serviceProvide bool isTelemetryOptedOut = !testApplicationOptions.EnableTelemetry; ILogger logger = loggerFactory.CreateLogger(); - await logger.LogDebugAsync($"TestApplicationOptions.EnableTelemetry: {testApplicationOptions.EnableTelemetry}"); + await logger.LogDebugAsync($"TestApplicationOptions.EnableTelemetry: {testApplicationOptions.EnableTelemetry}").ConfigureAwait(false); // If the environment variable is not set or is set to 0, telemetry is opted in. IEnvironment environment = serviceProvider.GetEnvironment(); string? telemetryOptOut = environment.GetEnvironmentVariable(EnvironmentVariableConstants.TESTINGPLATFORM_TELEMETRY_OPTOUT); - await logger.LogDebugAsync($"{EnvironmentVariableConstants.TESTINGPLATFORM_TELEMETRY_OPTOUT} environment variable: '{telemetryOptOut}'"); + await logger.LogDebugAsync($"{EnvironmentVariableConstants.TESTINGPLATFORM_TELEMETRY_OPTOUT} environment variable: '{telemetryOptOut}'").ConfigureAwait(false); isTelemetryOptedOut = (telemetryOptOut is "1" or "true") || isTelemetryOptedOut; string? cli_telemetryOptOut = environment.GetEnvironmentVariable(EnvironmentVariableConstants.DOTNET_CLI_TELEMETRY_OPTOUT); - await logger.LogDebugAsync($"{EnvironmentVariableConstants.DOTNET_CLI_TELEMETRY_OPTOUT} environment variable: '{cli_telemetryOptOut}'"); + await logger.LogDebugAsync($"{EnvironmentVariableConstants.DOTNET_CLI_TELEMETRY_OPTOUT} environment variable: '{cli_telemetryOptOut}'").ConfigureAwait(false); isTelemetryOptedOut = (cli_telemetryOptOut is "1" or "true") || isTelemetryOptedOut; - await logger.LogDebugAsync($"Telemetry is '{(!isTelemetryOptedOut ? "ENABLED" : "DISABLED")}'"); + await logger.LogDebugAsync($"Telemetry is '{(!isTelemetryOptedOut ? "ENABLED" : "DISABLED")}'").ConfigureAwait(false); if (!isTelemetryOptedOut && _telemetryFactory is not null) { - await ShowTelemetryBannerFirstNoticeAsync(serviceProvider, logger, environment); + await ShowTelemetryBannerFirstNoticeAsync(serviceProvider, logger, environment).ConfigureAwait(false); } serviceProvider.TryAddService(new TelemetryInformation(!isTelemetryOptedOut, TelemetryProperties.VersionValue)); @@ -62,7 +62,7 @@ public async Task BuildAsync(ServiceProvider serviceProvide if (!isTelemetryOptedOut) { - await logger.LogDebugAsync($"Telemetry collector provider: '{telemetryCollector.GetType()}'"); + await logger.LogDebugAsync($"Telemetry collector provider: '{telemetryCollector.GetType()}'").ConfigureAwait(false); } return telemetryCollector; @@ -75,11 +75,11 @@ private async Task ShowTelemetryBannerFirstNoticeAsync(ServiceProvider servicePr bool doNotShowLogo = commandLineOptions.IsOptionSet(PlatformCommandLineProvider.NoBannerOptionKey); string? noBannerEnvVar = environment.GetEnvironmentVariable(EnvironmentVariableConstants.TESTINGPLATFORM_NOBANNER); - await logger.LogDebugAsync($"{EnvironmentVariableConstants.TESTINGPLATFORM_NOBANNER} environment variable: '{noBannerEnvVar}'"); + await logger.LogDebugAsync($"{EnvironmentVariableConstants.TESTINGPLATFORM_NOBANNER} environment variable: '{noBannerEnvVar}'").ConfigureAwait(false); doNotShowLogo = (noBannerEnvVar is "1" or "true") || doNotShowLogo; string? dotnetNoLogoEnvVar = environment.GetEnvironmentVariable(EnvironmentVariableConstants.DOTNET_NOLOGO); - await logger.LogDebugAsync($"{EnvironmentVariableConstants.DOTNET_NOLOGO} environment variable: '{dotnetNoLogoEnvVar}'"); + await logger.LogDebugAsync($"{EnvironmentVariableConstants.DOTNET_NOLOGO} environment variable: '{dotnetNoLogoEnvVar}'").ConfigureAwait(false); doNotShowLogo = (dotnetNoLogoEnvVar is "1" or "true") || doNotShowLogo; if (doNotShowLogo) @@ -111,7 +111,7 @@ private async Task ShowTelemetryBannerFirstNoticeAsync(ServiceProvider servicePr } IOutputDevice outputDevice = serviceProvider.GetOutputDevice(); - await outputDevice.DisplayAsync(this, new TextOutputDeviceData(PlatformResources.TelemetryNotice)); + await outputDevice.DisplayAsync(this, new TextOutputDeviceData(PlatformResources.TelemetryNotice)).ConfigureAwait(false); string? path = null; try @@ -130,7 +130,7 @@ private async Task ShowTelemetryBannerFirstNoticeAsync(ServiceProvider servicePr } catch (Exception exception) when (exception is IOException or SystemException) { - await logger.LogErrorAsync($"Could not write sentinel file for telemetry to path,'{path ?? ""}'.", exception); + await logger.LogErrorAsync($"Could not write sentinel file for telemetry to path,'{path ?? ""}'.", exception).ConfigureAwait(false); } } diff --git a/src/Platform/Microsoft.Testing.Platform/TestHost/TestHostManager.cs b/src/Platform/Microsoft.Testing.Platform/TestHost/TestHostManager.cs index a9a6f7ce61..0e7aeed6ee 100644 --- a/src/Platform/Microsoft.Testing.Platform/TestHost/TestHostManager.cs +++ b/src/Platform/Microsoft.Testing.Platform/TestHost/TestHostManager.cs @@ -47,9 +47,9 @@ internal async Task> TryBuildTestAdapterInvo ITestFrameworkInvoker testAdapterInvoke = _testFrameworkInvokerFactory(serviceProvider); // We initialize only if enabled - if (await testAdapterInvoke.IsEnabledAsync()) + if (await testAdapterInvoke.IsEnabledAsync().ConfigureAwait(false)) { - await testAdapterInvoke.TryInitializeAsync(); + await testAdapterInvoke.TryInitializeAsync().ConfigureAwait(false); return ActionResult.Ok(testAdapterInvoke); } @@ -78,9 +78,9 @@ internal async Task> TryBuildTestExecu ITestExecutionFilterFactory testExecutionFilterFactory = _testExecutionFilterFactory(serviceProvider); // We initialize only if enabled - if (await testExecutionFilterFactory.IsEnabledAsync()) + if (await testExecutionFilterFactory.IsEnabledAsync().ConfigureAwait(false)) { - await testExecutionFilterFactory.TryInitializeAsync(); + await testExecutionFilterFactory.TryInitializeAsync().ConfigureAwait(false); return ActionResult.Ok(testExecutionFilterFactory); } @@ -109,9 +109,9 @@ internal async Task BuildTestApplicationLi } // We initialize only if enabled - if (await service.IsEnabledAsync()) + if (await service.IsEnabledAsync().ConfigureAwait(false)) { - await service.TryInitializeAsync(); + await service.TryInitializeAsync().ConfigureAwait(false); // Register the extension for usage testApplicationLifecycleCallbacks.Add(service); @@ -156,9 +156,9 @@ public void AddDataConsumer(CompositeExtensionFactory compositeServiceFact } // We initialize only if enabled - if (await service.IsEnabledAsync()) + if (await service.IsEnabledAsync().ConfigureAwait(false)) { - await service.TryInitializeAsync(); + await service.TryInitializeAsync().ConfigureAwait(false); // Register the extension for usage dataConsumers.Add((service, _factoryOrdering.IndexOf(dataConsumerFactory))); @@ -186,9 +186,9 @@ public void AddDataConsumer(CompositeExtensionFactory compositeServiceFact } // We initialize only if enabled - if (await instance.IsEnabledAsync()) + if (await instance.IsEnabledAsync().ConfigureAwait(false)) { - await instance.TryInitializeAsync(); + await instance.TryInitializeAsync().ConfigureAwait(false); } // Add to the list of shared singletons @@ -199,7 +199,7 @@ public void AddDataConsumer(CompositeExtensionFactory compositeServiceFact var extension = (IExtension)compositeFactoryInstance.GetInstance(); // We register the extension only if enabled - if (await extension.IsEnabledAsync()) + if (await extension.IsEnabledAsync().ConfigureAwait(false)) { if (extension is IDataConsumer consumer) { @@ -250,9 +250,9 @@ public void AddTestSessionLifetimeHandle(CompositeExtensionFactory composi } // We initialize only if enabled - if (await service.IsEnabledAsync()) + if (await service.IsEnabledAsync().ConfigureAwait(false)) { - await service.TryInitializeAsync(); + await service.TryInitializeAsync().ConfigureAwait(false); // Register the extension for usage testSessionLifetimeHandlers.Add((service, _factoryOrdering.IndexOf(testSessionLifetimeHandlerFactory))); @@ -280,9 +280,9 @@ public void AddTestSessionLifetimeHandle(CompositeExtensionFactory composi } // We initialize only if enabled - if (await instance.IsEnabledAsync()) + if (await instance.IsEnabledAsync().ConfigureAwait(false)) { - await instance.TryInitializeAsync(); + await instance.TryInitializeAsync().ConfigureAwait(false); } // Add to the list of shared singletons @@ -293,7 +293,7 @@ public void AddTestSessionLifetimeHandle(CompositeExtensionFactory composi var extension = (IExtension)compositeFactoryInstance.GetInstance(); // We register the extension only if enabled - if (await extension.IsEnabledAsync()) + if (await extension.IsEnabledAsync().ConfigureAwait(false)) { if (extension is ITestSessionLifetimeHandler testSessionLifetimeHandler) { diff --git a/src/Platform/Microsoft.Testing.Platform/TestHostControllers/PassiveNodeDataConsumer.cs b/src/Platform/Microsoft.Testing.Platform/TestHostControllers/PassiveNodeDataConsumer.cs index 9e4c2e5be8..31001ace26 100644 --- a/src/Platform/Microsoft.Testing.Platform/TestHostControllers/PassiveNodeDataConsumer.cs +++ b/src/Platform/Microsoft.Testing.Platform/TestHostControllers/PassiveNodeDataConsumer.cs @@ -46,14 +46,14 @@ public async Task ConsumeAsync(IDataProducer dataProducer, IData value, Cancella case SessionFileArtifact sessionFileArtifact: { RunTestAttachment runTestAttachment = new(sessionFileArtifact.FileInfo.FullName, dataProducer.Uid, FileType, sessionFileArtifact.DisplayName, sessionFileArtifact.Description); - await _passiveNode.SendAttachmentsAsync(new TestsAttachments([runTestAttachment]), cancellationToken); + await _passiveNode.SendAttachmentsAsync(new TestsAttachments([runTestAttachment]), cancellationToken).ConfigureAwait(false); break; } case FileArtifact fileArtifact: { RunTestAttachment runTestAttachment = new(fileArtifact.FileInfo.FullName, dataProducer.Uid, FileType, fileArtifact.DisplayName, fileArtifact.Description); - await _passiveNode.SendAttachmentsAsync(new TestsAttachments([runTestAttachment]), cancellationToken); + await _passiveNode.SendAttachmentsAsync(new TestsAttachments([runTestAttachment]), cancellationToken).ConfigureAwait(false); break; } diff --git a/src/Platform/Microsoft.Testing.Platform/TestHostControllers/SystemEnvironmentVariableProvider.cs b/src/Platform/Microsoft.Testing.Platform/TestHostControllers/SystemEnvironmentVariableProvider.cs index 6e4e6bac6e..00bed2b5a6 100644 --- a/src/Platform/Microsoft.Testing.Platform/TestHostControllers/SystemEnvironmentVariableProvider.cs +++ b/src/Platform/Microsoft.Testing.Platform/TestHostControllers/SystemEnvironmentVariableProvider.cs @@ -20,7 +20,7 @@ internal sealed class SystemEnvironmentVariableProvider(IEnvironment environment public string Description => _systemExtension.Description; - public async Task IsEnabledAsync() => await _systemExtension.IsEnabledAsync(); + public async Task IsEnabledAsync() => await _systemExtension.IsEnabledAsync().ConfigureAwait(false); public Task UpdateAsync(IEnvironmentVariables environmentVariables) { diff --git a/src/Platform/Microsoft.Testing.Platform/TestHostControllers/TestHostControllersManager.cs b/src/Platform/Microsoft.Testing.Platform/TestHostControllers/TestHostControllersManager.cs index 3422551b69..7fd09b3d23 100644 --- a/src/Platform/Microsoft.Testing.Platform/TestHostControllers/TestHostControllersManager.cs +++ b/src/Platform/Microsoft.Testing.Platform/TestHostControllers/TestHostControllersManager.cs @@ -99,9 +99,9 @@ internal async Task BuildAsync(ServiceProvider } // We initialize only if enabled - if (await envVarProvider.IsEnabledAsync()) + if (await envVarProvider.IsEnabledAsync().ConfigureAwait(false)) { - await envVarProvider.TryInitializeAsync(); + await envVarProvider.TryInitializeAsync().ConfigureAwait(false); // Register the extension for usage environmentVariableProviders.Add((envVarProvider, _factoryOrdering.IndexOf(environmentVariableProviderFactory))); @@ -113,7 +113,7 @@ internal async Task BuildAsync(ServiceProvider { // Get the singleton var extension = (IExtension)compositeServiceFactory.GetInstance(serviceProvider); - bool isEnabledAsync = await extension.IsEnabledAsync(); + bool isEnabledAsync = await extension.IsEnabledAsync().ConfigureAwait(false); // Check if we have already built the singleton for this composite factory if (!_alreadyBuiltServices.Contains(compositeServiceFactory)) @@ -128,7 +128,7 @@ internal async Task BuildAsync(ServiceProvider // We initialize only if enabled if (isEnabledAsync) { - await extension.TryInitializeAsync(); + await extension.TryInitializeAsync().ConfigureAwait(false); } // Add to the list of shared singletons @@ -164,9 +164,9 @@ internal async Task BuildAsync(ServiceProvider } // We initialize only if enabled - if (await lifetimeHandler.IsEnabledAsync()) + if (await lifetimeHandler.IsEnabledAsync().ConfigureAwait(false)) { - await lifetimeHandler.TryInitializeAsync(); + await lifetimeHandler.TryInitializeAsync().ConfigureAwait(false); // Register the extension for usage lifetimeHandlers.Add((lifetimeHandler, _factoryOrdering.IndexOf(lifetimeHandlerFactory))); @@ -178,7 +178,7 @@ internal async Task BuildAsync(ServiceProvider { // Get the singleton var extension = (IExtension)compositeServiceFactory.GetInstance(serviceProvider); - bool isEnabledAsync = await extension.IsEnabledAsync(); + bool isEnabledAsync = await extension.IsEnabledAsync().ConfigureAwait(false); // Check if we have already built the singleton for this composite factory if (!_alreadyBuiltServices.Contains(compositeServiceFactory)) @@ -192,7 +192,7 @@ internal async Task BuildAsync(ServiceProvider // We initialize only if enabled if (isEnabledAsync) { - await extension.TryInitializeAsync(); + await extension.TryInitializeAsync().ConfigureAwait(false); } // Add to the list of shared singletons @@ -228,9 +228,9 @@ internal async Task BuildAsync(ServiceProvider } // We initialize only if enabled - if (await service.IsEnabledAsync()) + if (await service.IsEnabledAsync().ConfigureAwait(false)) { - await service.TryInitializeAsync(); + await service.TryInitializeAsync().ConfigureAwait(false); // Register the extension for usage dataConsumers.Add((service, _factoryOrdering.IndexOf(dataConsumerFactory))); @@ -258,9 +258,9 @@ internal async Task BuildAsync(ServiceProvider } // We initialize only if enabled - if (await instance.IsEnabledAsync()) + if (await instance.IsEnabledAsync().ConfigureAwait(false)) { - await instance.TryInitializeAsync(); + await instance.TryInitializeAsync().ConfigureAwait(false); } // Add to the list of shared singletons @@ -271,7 +271,7 @@ internal async Task BuildAsync(ServiceProvider var extension = (IExtension)compositeFactoryInstance.GetInstance(); // We register the extension only if enabled - if (await extension.IsEnabledAsync()) + if (await extension.IsEnabledAsync().ConfigureAwait(false)) { if (extension is IDataConsumer consumer) { diff --git a/src/Platform/Microsoft.Testing.Platform/TestHostOrcherstrator/TestHostOrchestratorManager.cs b/src/Platform/Microsoft.Testing.Platform/TestHostOrcherstrator/TestHostOrchestratorManager.cs index a4015025af..a4483d6535 100644 --- a/src/Platform/Microsoft.Testing.Platform/TestHostOrcherstrator/TestHostOrchestratorManager.cs +++ b/src/Platform/Microsoft.Testing.Platform/TestHostOrcherstrator/TestHostOrchestratorManager.cs @@ -37,9 +37,9 @@ public async Task BuildAsync(ServiceProvider } // We initialize only if enabled - if (await orchestrator.IsEnabledAsync()) + if (await orchestrator.IsEnabledAsync().ConfigureAwait(false)) { - await orchestrator.TryInitializeAsync(); + await orchestrator.TryInitializeAsync().ConfigureAwait(false); // Register the extension for usage orchestrators.Add(orchestrator); diff --git a/src/Platform/Microsoft.Testing.Platform/Tools/ToolsManager.cs b/src/Platform/Microsoft.Testing.Platform/Tools/ToolsManager.cs index 869c60d440..69f2b595cf 100644 --- a/src/Platform/Microsoft.Testing.Platform/Tools/ToolsManager.cs +++ b/src/Platform/Microsoft.Testing.Platform/Tools/ToolsManager.cs @@ -21,12 +21,12 @@ internal async Task> BuildAsync(IServiceProvider servicePro foreach (Func toolFactory in _toolsFactories) { ITool tool = toolFactory(serviceProvider); - if (!await tool.IsEnabledAsync()) + if (!await tool.IsEnabledAsync().ConfigureAwait(false)) { continue; } - await tool.TryInitializeAsync(); + await tool.TryInitializeAsync().ConfigureAwait(false); tools.Add(tool); } diff --git a/src/TestFramework/TestFramework.Extensions/Attributes/UWP_UITestMethodAttribute.cs b/src/TestFramework/TestFramework.Extensions/Attributes/UWP_UITestMethodAttribute.cs index ab0577b601..59e96e8f1c 100644 --- a/src/TestFramework/TestFramework.Extensions/Attributes/UWP_UITestMethodAttribute.cs +++ b/src/TestFramework/TestFramework.Extensions/Attributes/UWP_UITestMethodAttribute.cs @@ -34,7 +34,7 @@ await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatch { try { - tcs.SetResult(await testMethod.InvokeAsync(null)); + tcs.SetResult(await testMethod.InvokeAsync(null).ConfigureAwait(false)); } catch (Exception ex) { @@ -43,7 +43,7 @@ await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatch }); #pragma warning restore VSTHRD101 // Avoid unsupported async delegates - return [await tcs.Task]; + return [await tcs.Task.ConfigureAwait(false)]; } } #endif diff --git a/src/TestFramework/TestFramework.Extensions/Attributes/WinUI_UITestMethodAttribute.cs b/src/TestFramework/TestFramework.Extensions/Attributes/WinUI_UITestMethodAttribute.cs index acec6a45d9..51eb1189ad 100644 --- a/src/TestFramework/TestFramework.Extensions/Attributes/WinUI_UITestMethodAttribute.cs +++ b/src/TestFramework/TestFramework.Extensions/Attributes/WinUI_UITestMethodAttribute.cs @@ -67,7 +67,7 @@ internal override async Task ExecuteAsync(ITestMethod testMethod) { try { - return [await testMethod.InvokeAsync(null)]; + return [await testMethod.InvokeAsync(null).ConfigureAwait(false)]; } catch (Exception e) { @@ -82,7 +82,7 @@ internal override async Task ExecuteAsync(ITestMethod testMethod) { try { - tcs.SetResult(await testMethod.InvokeAsync(null)); + tcs.SetResult(await testMethod.InvokeAsync(null).ConfigureAwait(false)); } catch (Exception e) { @@ -94,7 +94,7 @@ internal override async Task ExecuteAsync(ITestMethod testMethod) } #pragma warning restore VSTHRD101 // Avoid unsupported async delegates - return [await tcs.Task]; + return [await tcs.Task.ConfigureAwait(false)]; } private static Type? GetApplicationType(Assembly assembly) diff --git a/src/TestFramework/TestFramework/Attributes/TestMethod/RetryAttribute.cs b/src/TestFramework/TestFramework/Attributes/TestMethod/RetryAttribute.cs index 3cc9868be5..811a7b0e37 100644 --- a/src/TestFramework/TestFramework/Attributes/TestMethod/RetryAttribute.cs +++ b/src/TestFramework/TestFramework/Attributes/TestMethod/RetryAttribute.cs @@ -73,13 +73,13 @@ protected internal override async Task ExecuteAsync(RetryContext re for (int i = 0; i < MaxRetryAttempts; i++) { // The caller already executed the test once. So we need to do the delay here. - await Task.Delay(currentDelay); + await Task.Delay(currentDelay).ConfigureAwait(false); if (BackoffType == DelayBackoffType.Exponential) { currentDelay *= 2; } - TestResult[] testResults = await retryContext.ExecuteTaskGetter(); + TestResult[] testResults = await retryContext.ExecuteTaskGetter().ConfigureAwait(false); result.AddResult(testResults); if (IsAcceptableResultForRetry(testResults)) { diff --git a/src/TestFramework/TestFramework/Attributes/TestMethod/TestMethodAttribute.cs b/src/TestFramework/TestFramework/Attributes/TestMethod/TestMethodAttribute.cs index 6baf8e78fa..aa76cac719 100644 --- a/src/TestFramework/TestFramework/Attributes/TestMethod/TestMethodAttribute.cs +++ b/src/TestFramework/TestFramework/Attributes/TestMethod/TestMethodAttribute.cs @@ -69,6 +69,6 @@ public TestMethodAttribute(string? displayName) /// Extensions can override this method to customize running a TestMethod. internal virtual async Task ExecuteAsync(ITestMethod testMethod) => UseAsync - ? [await testMethod.InvokeAsync(null)] + ? [await testMethod.InvokeAsync(null).ConfigureAwait(false)] : Execute(testMethod); } diff --git a/test/.editorconfig b/test/.editorconfig index 4ffa71b86f..58ccc42e50 100644 --- a/test/.editorconfig +++ b/test/.editorconfig @@ -25,6 +25,10 @@ dotnet_diagnostic.CA1822.severity = none # CA1822: Mark members as st dotnet_diagnostic.CA1852.severity = none # CA1852: Type can be sealed dotnet_diagnostic.CA1859.severity = none # CA1859: Change return type to be more specific dotnet_diagnostic.CA1861.severity = none # CA1861: Avoid constant arrays as arguments + +# CA2007: Consider calling ConfigureAwait on the awaited task +dotnet_diagnostic.CA2007.severity = none + dotnet_diagnostic.CA2201.severity = none # CA2201: Do not raise reserved exception types dotnet_diagnostic.CA3075.severity = none # CA3075: Insecure DTD processing in XML From 751ba472cf9df16dc7adfa8405fbcd394be7e247 Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Thu, 12 Jun 2025 04:22:15 +0000 Subject: [PATCH 077/541] [main] Update dependencies from devdiv/DevDiv/vs-code-coverage, dotnet/arcade (#5740) [main] Update dependencies from devdiv/DevDiv/vs-code-coverage, dotnet/arcade --- eng/Version.Details.xml | 16 ++++++++-------- eng/Versions.props | 4 ++-- global.json | 2 +- 3 files changed, 11 insertions(+), 11 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index d3cc63ce58..45d397219b 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -1,21 +1,21 @@ - + https://github.com/dotnet/arcade - d237be4630776450573bc588eb995bb8f9ebc04f + 5ad76e326524772ed87487009987bf88264f0da2 - + https://github.com/dotnet/arcade - d237be4630776450573bc588eb995bb8f9ebc04f + 5ad76e326524772ed87487009987bf88264f0da2 - + https://github.com/dotnet/arcade - d237be4630776450573bc588eb995bb8f9ebc04f + 5ad76e326524772ed87487009987bf88264f0da2 - + https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage - 7d78c65400a20ab1c9be42104ae4f40568f6885a + 0df73e9ae14ec617262ca3f5aeec6c232a33e230 diff --git a/eng/Versions.props b/eng/Versions.props index b0b97903d9..45f7512972 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -7,7 +7,7 @@ preview - 10.0.0-beta.25310.2 - 17.15.0-preview.25310.3 + 10.0.0-beta.25311.1 + 17.15.0-preview.25311.1 diff --git a/global.json b/global.json index dd491d8f6c..7c8c12d6c8 100644 --- a/global.json +++ b/global.json @@ -28,7 +28,7 @@ "rollForward": "latestFeature" }, "msbuild-sdks": { - "Microsoft.DotNet.Arcade.Sdk": "10.0.0-beta.25310.2", + "Microsoft.DotNet.Arcade.Sdk": "10.0.0-beta.25311.1", "MSBuild.Sdk.Extras": "3.0.44" } } From b995d99f0e1ca10c33da803f9a3e51acffedff1c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Jare=C5=A1?= Date: Thu, 12 Jun 2025 09:49:22 +0200 Subject: [PATCH 078/541] Exclude folders (#5744) --- azure-pipelines.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/azure-pipelines.yml b/azure-pipelines.yml index 1a37097e89..874d113094 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -6,9 +6,9 @@ pr: - rel/* paths: exclude: - - .github/* - - .devcontainer/* - - docs/* + - .github/** + - .devcontainer/** + - docs/** - .markdownlint.json - .markdownlintignore - CODE_OF_CONDUCT.md From ec33a1e22fe9c22ce13956fb11e7fa94ae6ce68f Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Thu, 12 Jun 2025 10:15:47 +0200 Subject: [PATCH 079/541] Use local SDK in global.json (#5671) --- azure-pipelines.yml | 8 ++++---- global.json | 2 ++ 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/azure-pipelines.yml b/azure-pipelines.yml index 874d113094..55d5446dd8 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -98,7 +98,7 @@ stages: # Because the build step is using -ci flag, restore is done in a local .packages directory. # We need to pass NUGET_PACKAGES so that when dotnet test is doing evaluation phase on the projects, it can resolve .props/.targets from packages and import them. # Otherwise, props/targets are not imported. It's important that they are imported so that IsTestingPlatformApplication ends up being set. - - script: $(Build.SourcesDirectory)/.dotnet/dotnet test -c $(_BuildConfig) --no-build -bl:$(BUILD.SOURCESDIRECTORY)\artifacts\log\$(_BuildConfig)\TestStep.binlog + - script: dotnet test -c $(_BuildConfig) --no-build -bl:$(BUILD.SOURCESDIRECTORY)\artifacts\log\$(_BuildConfig)\TestStep.binlog name: Test displayName: Test env: @@ -131,7 +131,7 @@ stages: condition: always() # Upload code coverage to codecov.io - - script: $(Build.SourcesDirectory)/.dotnet/dotnet msbuild -restore + - script: dotnet msbuild -restore eng/CodeCoverage.proj /p:Configuration=$(_BuildConfig) /bl:$(BUILD.SOURCESDIRECTORY)\artifacts\log\$(_BuildConfig)\CodeCoverage.binlog @@ -162,7 +162,7 @@ stages: # Because the build step is using -ci flag, restore is done in a local .packages directory. # We need to pass NUGET_PACKAGES so that when dotnet test is doing evaluation phase on the projects, it can resolve .props/.targets from packages and import them. # Otherwise, props/targets are not imported. It's important that they are imported so that IsTestingPlatformApplication ends up being set. - - script: $(Build.SourcesDirectory)/.dotnet/dotnet test --solution NonWindowsTests.slnf -c $(_BuildConfig) --no-build -bl:$(BUILD.SOURCESDIRECTORY)\artifacts\log\$(_BuildConfig)\TestStep.binlog + - script: dotnet test --solution NonWindowsTests.slnf -c $(_BuildConfig) --no-build -bl:$(BUILD.SOURCESDIRECTORY)\artifacts\log\$(_BuildConfig)\TestStep.binlog name: Test displayName: Test env: @@ -219,7 +219,7 @@ stages: # Because the build step is using -ci flag, restore is done in a local .packages directory. # We need to pass NUGET_PACKAGES so that when dotnet test is doing evaluation phase on the projects, it can resolve .props/.targets from packages and import them. # Otherwise, props/targets are not imported. It's important that they are imported so that IsTestingPlatformApplication ends up being set. - - script: $(Build.SourcesDirectory)/.dotnet/dotnet test --solution NonWindowsTests.slnf -c $(_BuildConfig) --no-build -bl:$(BUILD.SOURCESDIRECTORY)\artifacts\log\$(_BuildConfig)\TestStep.binlog + - script: dotnet test --solution NonWindowsTests.slnf -c $(_BuildConfig) --no-build -bl:$(BUILD.SOURCESDIRECTORY)\artifacts\log\$(_BuildConfig)\TestStep.binlog name: Test displayName: Test env: diff --git a/global.json b/global.json index 7c8c12d6c8..7902c29958 100644 --- a/global.json +++ b/global.json @@ -24,6 +24,8 @@ }, "sdk": { "version": "10.0.100-preview.6.25309.101", + "paths": [ ".dotnet", "$host$" ], + "errorMessage": "The .NET SDK could not be found, please run ./build.cmd on Windows or ./build.sh on Linux and macOS.", "allowPrerelease": true, "rollForward": "latestFeature" }, From 3351ee40a1a2ca97aa0c5dff8b104664c8608f9c Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Thu, 12 Jun 2025 10:31:34 +0200 Subject: [PATCH 080/541] [VSTestBridge] Avoid creating Uri instance for every test case. (#5743) --- .../ObjectModel/ObjectModelConverters.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/ObjectModelConverters.cs b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/ObjectModelConverters.cs index 175dede801..02352b25bb 100644 --- a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/ObjectModelConverters.cs +++ b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/ObjectModelConverters.cs @@ -34,6 +34,8 @@ internal static class ObjectModelConverters valueType: typeof(string), owner: typeof(TestCase)); + private static readonly Uri ExecutorUri = new(Constants.ExecutorUri); + /// /// Converts a VSTest to a Microsoft Testing Platform . /// @@ -270,7 +272,7 @@ internal static void FixUpTestCase(this TestCase testCase, string? testAssemblyP testCase.SetPropertyValue(OriginalExecutorUriProperty, testCase.ExecutorUri); } - testCase.ExecutorUri = new(Constants.ExecutorUri); + testCase.ExecutorUri = ExecutorUri; } private static bool TryGetMethodIdentifierProperty(TestCase testCase, [NotNullWhen(true)] out TestMethodIdentifierProperty? methodIdentifierProperty) From 2d00b0c323717270c29764e4b40707c32e47d625 Mon Sep 17 00:00:00 2001 From: Copilot <198982749+Copilot@users.noreply.github.com> Date: Thu, 12 Jun 2025 10:38:57 +0200 Subject: [PATCH 081/541] Implement analyzer/codefix to move from DataTestMethodAttribute to TestMethodAttribute (#5706) Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: Youssef1313 <31348972+Youssef1313@users.noreply.github.com> Co-authored-by: Youssef1313 --- .../CodeFixResources.Designer.cs | 9 ++ .../CodeFixResources.resx | 5 +- ...PreferTestMethodOverDataTestMethodFixer.cs | 64 ++++++++ .../PublicAPI.Unshipped.txt | 5 + .../xlf/CodeFixResources.cs.xlf | 5 + .../xlf/CodeFixResources.de.xlf | 5 + .../xlf/CodeFixResources.es.xlf | 5 + .../xlf/CodeFixResources.fr.xlf | 5 + .../xlf/CodeFixResources.it.xlf | 5 + .../xlf/CodeFixResources.ja.xlf | 5 + .../xlf/CodeFixResources.ko.xlf | 5 + .../xlf/CodeFixResources.pl.xlf | 5 + .../xlf/CodeFixResources.pt-BR.xlf | 5 + .../xlf/CodeFixResources.ru.xlf | 5 + .../xlf/CodeFixResources.tr.xlf | 5 + .../xlf/CodeFixResources.zh-Hans.xlf | 5 + .../xlf/CodeFixResources.zh-Hant.xlf | 5 + .../AnalyzerReleases.Unshipped.md | 1 + .../MSTest.Analyzers/Helpers/DiagnosticIds.cs | 1 + .../Helpers/WellKnownTypeNames.cs | 1 + ...ferTestMethodOverDataTestMethodAnalyzer.cs | 79 ++++++++++ .../MSTest.Analyzers/PublicAPI.Unshipped.txt | 4 + .../MSTest.Analyzers/Resources.Designer.cs | 27 ++++ src/Analyzers/MSTest.Analyzers/Resources.resx | 11 +- .../MSTest.Analyzers/xlf/Resources.cs.xlf | 15 ++ .../MSTest.Analyzers/xlf/Resources.de.xlf | 15 ++ .../MSTest.Analyzers/xlf/Resources.es.xlf | 15 ++ .../MSTest.Analyzers/xlf/Resources.fr.xlf | 15 ++ .../MSTest.Analyzers/xlf/Resources.it.xlf | 15 ++ .../MSTest.Analyzers/xlf/Resources.ja.xlf | 15 ++ .../MSTest.Analyzers/xlf/Resources.ko.xlf | 15 ++ .../MSTest.Analyzers/xlf/Resources.pl.xlf | 15 ++ .../MSTest.Analyzers/xlf/Resources.pt-BR.xlf | 15 ++ .../MSTest.Analyzers/xlf/Resources.ru.xlf | 15 ++ .../MSTest.Analyzers/xlf/Resources.tr.xlf | 15 ++ .../xlf/Resources.zh-Hans.xlf | 15 ++ .../xlf/Resources.zh-Hant.xlf | 15 ++ ...stMethodOverDataTestMethodAnalyzerTests.cs | 142 ++++++++++++++++++ 38 files changed, 607 insertions(+), 2 deletions(-) create mode 100644 src/Analyzers/MSTest.Analyzers.CodeFixes/PreferTestMethodOverDataTestMethodFixer.cs create mode 100644 src/Analyzers/MSTest.Analyzers/PreferTestMethodOverDataTestMethodAnalyzer.cs create mode 100644 test/UnitTests/MSTest.Analyzers.UnitTests/PreferTestMethodOverDataTestMethodAnalyzerTests.cs diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/CodeFixResources.Designer.cs b/src/Analyzers/MSTest.Analyzers.CodeFixes/CodeFixResources.Designer.cs index 9cab8f2e12..93920133f3 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/CodeFixResources.Designer.cs +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/CodeFixResources.Designer.cs @@ -132,6 +132,15 @@ internal static string FixSignatureCodeFix { } } + /// + /// Looks up a localized string similar to Replace 'DataTestMethod' with 'TestMethod'. + /// + internal static string ReplaceDataTestMethodWithTestMethodTitle { + get { + return ResourceManager.GetString("ReplaceDataTestMethodWithTestMethodTitle", resourceCulture); + } + } + /// /// Looks up a localized string similar to Replace TestInitialize method with constructor. /// diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/CodeFixResources.resx b/src/Analyzers/MSTest.Analyzers.CodeFixes/CodeFixResources.resx index 27cd7731e9..0e215460ca 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/CodeFixResources.resx +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/CodeFixResources.resx @@ -177,4 +177,7 @@ Use '{0}' - \ No newline at end of file + + Replace 'DataTestMethod' with 'TestMethod' + + diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/PreferTestMethodOverDataTestMethodFixer.cs b/src/Analyzers/MSTest.Analyzers.CodeFixes/PreferTestMethodOverDataTestMethodFixer.cs new file mode 100644 index 0000000000..580a90cb3e --- /dev/null +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/PreferTestMethodOverDataTestMethodFixer.cs @@ -0,0 +1,64 @@ +// 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.Immutable; +using System.Composition; + +using Analyzer.Utilities; + +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CodeActions; +using Microsoft.CodeAnalysis.CodeFixes; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +using MSTest.Analyzers.Helpers; + +namespace MSTest.Analyzers; + +/// +/// Code fixer for . +/// +[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(PreferTestMethodOverDataTestMethodFixer))] +[Shared] +public sealed class PreferTestMethodOverDataTestMethodFixer : CodeFixProvider +{ + /// + public override ImmutableArray FixableDiagnosticIds { get; } + = ImmutableArray.Create(DiagnosticIds.PreferTestMethodOverDataTestMethodRuleId); + + /// + public override FixAllProvider GetFixAllProvider() + => WellKnownFixAllProviders.BatchFixer; + + /// + public override async Task RegisterCodeFixesAsync(CodeFixContext context) + { + SyntaxNode root = await context.Document.GetRequiredSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); + + foreach (Diagnostic diagnostic in context.Diagnostics) + { + SyntaxNode? diagnosticNode = root?.FindNode(diagnostic.Location.SourceSpan); + if (diagnosticNode is not AttributeSyntax attributeSyntax) + { + continue; + } + + // Replace DataTestMethod with TestMethod + var action = CodeAction.Create( + title: CodeFixResources.ReplaceDataTestMethodWithTestMethodTitle, + createChangedDocument: c => Task.FromResult(ReplaceDataTestMethod(context.Document, root!, attributeSyntax)), + equivalenceKey: nameof(PreferTestMethodOverDataTestMethodFixer)); + + context.RegisterCodeFix(action, diagnostic); + } + } + + private static Document ReplaceDataTestMethod(Document document, SyntaxNode root, AttributeSyntax attributeSyntax) + { + AttributeSyntax newAttribute = attributeSyntax.WithName(SyntaxFactory.IdentifierName("TestMethod")); + SyntaxNode newRoot = root.ReplaceNode(attributeSyntax, newAttribute); + + return document.WithSyntaxRoot(newRoot); + } +} diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/PublicAPI.Unshipped.txt b/src/Analyzers/MSTest.Analyzers.CodeFixes/PublicAPI.Unshipped.txt index 7dc5c58110..4af97d242d 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/PublicAPI.Unshipped.txt +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/PublicAPI.Unshipped.txt @@ -1 +1,6 @@ #nullable enable +MSTest.Analyzers.PreferTestMethodOverDataTestMethodFixer +MSTest.Analyzers.PreferTestMethodOverDataTestMethodFixer.PreferTestMethodOverDataTestMethodFixer() -> void +override MSTest.Analyzers.PreferTestMethodOverDataTestMethodFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray +override MSTest.Analyzers.PreferTestMethodOverDataTestMethodFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! +override MSTest.Analyzers.PreferTestMethodOverDataTestMethodFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.cs.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.cs.xlf index 5e01c72cca..72b8bcc71d 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.cs.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.cs.xlf @@ -42,6 +42,11 @@ Opravit podpis + + Replace 'DataTestMethod' with 'TestMethod' + Replace 'DataTestMethod' with 'TestMethod' + + Replace TestInitialize method with constructor Nahradit metodu TestInitialize konstruktorem diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.de.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.de.xlf index ecef33e935..52eae8f0fa 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.de.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.de.xlf @@ -42,6 +42,11 @@ Signatur korrigieren + + Replace 'DataTestMethod' with 'TestMethod' + Replace 'DataTestMethod' with 'TestMethod' + + Replace TestInitialize method with constructor TestInitialize-Methode durch Konstruktor ersetzen diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.es.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.es.xlf index 1edccf3e61..d51a97e215 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.es.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.es.xlf @@ -42,6 +42,11 @@ Corregir firma + + Replace 'DataTestMethod' with 'TestMethod' + Replace 'DataTestMethod' with 'TestMethod' + + Replace TestInitialize method with constructor Reemplazar el método TestInitialize por el constructor diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.fr.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.fr.xlf index ed28b55f45..498cfe7ea8 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.fr.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.fr.xlf @@ -42,6 +42,11 @@ Corriger la signature numérique + + Replace 'DataTestMethod' with 'TestMethod' + Replace 'DataTestMethod' with 'TestMethod' + + Replace TestInitialize method with constructor Remplacer la méthode TestInitialize par un constructeur diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.it.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.it.xlf index 10aafdcc89..383065c770 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.it.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.it.xlf @@ -42,6 +42,11 @@ Correggi firma + + Replace 'DataTestMethod' with 'TestMethod' + Replace 'DataTestMethod' with 'TestMethod' + + Replace TestInitialize method with constructor Sostituisci il metodo TestInitialize con il costruttore diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ja.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ja.xlf index ad8e53d586..109e333ead 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ja.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ja.xlf @@ -42,6 +42,11 @@ 署名の修正 + + Replace 'DataTestMethod' with 'TestMethod' + Replace 'DataTestMethod' with 'TestMethod' + + Replace TestInitialize method with constructor TestInitialize メソッドをコンストラクターに置き換える diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ko.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ko.xlf index 9d32dc54eb..35865aa78b 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ko.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ko.xlf @@ -42,6 +42,11 @@ 서명 수정 + + Replace 'DataTestMethod' with 'TestMethod' + Replace 'DataTestMethod' with 'TestMethod' + + Replace TestInitialize method with constructor TestInitialize 메서드를 생성자로 바꾸기 diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pl.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pl.xlf index d879b5a155..9bb87921b7 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pl.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pl.xlf @@ -42,6 +42,11 @@ Popraw podpis + + Replace 'DataTestMethod' with 'TestMethod' + Replace 'DataTestMethod' with 'TestMethod' + + Replace TestInitialize method with constructor Zastąp metodę TestInitialize konstruktorem diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pt-BR.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pt-BR.xlf index 646745d87a..196cffca2e 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pt-BR.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pt-BR.xlf @@ -42,6 +42,11 @@ Corrigir assinatura + + Replace 'DataTestMethod' with 'TestMethod' + Replace 'DataTestMethod' with 'TestMethod' + + Replace TestInitialize method with constructor Substituir o método TestInitialize pelo construtor. diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ru.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ru.xlf index d2e9dbd136..127258218a 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ru.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ru.xlf @@ -42,6 +42,11 @@ Исправить подпись + + Replace 'DataTestMethod' with 'TestMethod' + Replace 'DataTestMethod' with 'TestMethod' + + Replace TestInitialize method with constructor Заменить метод TestInitialize конструктором diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.tr.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.tr.xlf index 48e1032eb5..40263d1576 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.tr.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.tr.xlf @@ -42,6 +42,11 @@ İmzayı düzelt + + Replace 'DataTestMethod' with 'TestMethod' + Replace 'DataTestMethod' with 'TestMethod' + + Replace TestInitialize method with constructor TestInitialize yöntemini oluşturucuyla değiştir diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hans.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hans.xlf index 2f4b66073d..43c037cd5f 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hans.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hans.xlf @@ -42,6 +42,11 @@ 修复签名 + + Replace 'DataTestMethod' with 'TestMethod' + Replace 'DataTestMethod' with 'TestMethod' + + Replace TestInitialize method with constructor 将 TestInitialize 方法替换为构造函数 diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hant.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hant.xlf index 5c5ea7e81d..622334ef26 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hant.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hant.xlf @@ -42,6 +42,11 @@ 修正簽章 + + Replace 'DataTestMethod' with 'TestMethod' + Replace 'DataTestMethod' with 'TestMethod' + + Replace TestInitialize method with constructor 以建構函式取代 TestInitialize 方法 diff --git a/src/Analyzers/MSTest.Analyzers/AnalyzerReleases.Unshipped.md b/src/Analyzers/MSTest.Analyzers/AnalyzerReleases.Unshipped.md index 7b845f4860..ab12abf384 100644 --- a/src/Analyzers/MSTest.Analyzers/AnalyzerReleases.Unshipped.md +++ b/src/Analyzers/MSTest.Analyzers/AnalyzerReleases.Unshipped.md @@ -5,3 +5,4 @@ Rule ID | Category | Severity | Notes --------|----------|----------|------- +MSTEST0044 | Design | Info | PreferTestMethodOverDataTestMethodAnalyzer, [Documentation](https://learn.microsoft.com/dotnet/core/testing/mstest-analyzers/mstest0044) diff --git a/src/Analyzers/MSTest.Analyzers/Helpers/DiagnosticIds.cs b/src/Analyzers/MSTest.Analyzers/Helpers/DiagnosticIds.cs index 66be4e9c99..6c30e60f1b 100644 --- a/src/Analyzers/MSTest.Analyzers/Helpers/DiagnosticIds.cs +++ b/src/Analyzers/MSTest.Analyzers/Helpers/DiagnosticIds.cs @@ -48,4 +48,5 @@ internal static class DiagnosticIds public const string UseConditionBaseWithTestClassRuleId = "MSTEST0041"; public const string DuplicateDataRowRuleId = "MSTEST0042"; public const string UseRetryWithTestMethodRuleId = "MSTEST0043"; + public const string PreferTestMethodOverDataTestMethodRuleId = "MSTEST0044"; } diff --git a/src/Analyzers/MSTest.Analyzers/Helpers/WellKnownTypeNames.cs b/src/Analyzers/MSTest.Analyzers/Helpers/WellKnownTypeNames.cs index bb71ecd3a5..a56d8069a0 100644 --- a/src/Analyzers/MSTest.Analyzers/Helpers/WellKnownTypeNames.cs +++ b/src/Analyzers/MSTest.Analyzers/Helpers/WellKnownTypeNames.cs @@ -18,6 +18,7 @@ internal static class WellKnownTypeNames public const string MicrosoftVisualStudioTestToolsUnitTestingCssIterationAttribute = "Microsoft.VisualStudio.TestTools.UnitTesting.CssIterationAttribute"; public const string MicrosoftVisualStudioTestToolsUnitTestingCssProjectStructureAttribute = "Microsoft.VisualStudio.TestTools.UnitTesting.CssProjectStructureAttribute"; public const string MicrosoftVisualStudioTestToolsUnitTestingDataRowAttribute = "Microsoft.VisualStudio.TestTools.UnitTesting.DataRowAttribute"; + public const string MicrosoftVisualStudioTestToolsUnitTestingDataTestMethodAttribute = "Microsoft.VisualStudio.TestTools.UnitTesting.DataTestMethodAttribute"; public const string MicrosoftVisualStudioTestToolsUnitTestingDeploymentItemAttribute = "Microsoft.VisualStudio.TestTools.UnitTesting.DeploymentItemAttribute"; public const string MicrosoftVisualStudioTestToolsUnitTestingDescriptionAttribute = "Microsoft.VisualStudio.TestTools.UnitTesting.DescriptionAttribute"; public const string MicrosoftVisualStudioTestToolsUnitTestingDiscoverInternalsAttribute = "Microsoft.VisualStudio.TestTools.UnitTesting.DiscoverInternalsAttribute"; diff --git a/src/Analyzers/MSTest.Analyzers/PreferTestMethodOverDataTestMethodAnalyzer.cs b/src/Analyzers/MSTest.Analyzers/PreferTestMethodOverDataTestMethodAnalyzer.cs new file mode 100644 index 0000000000..22c9a51fee --- /dev/null +++ b/src/Analyzers/MSTest.Analyzers/PreferTestMethodOverDataTestMethodAnalyzer.cs @@ -0,0 +1,79 @@ +// 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.Immutable; + +using Analyzer.Utilities.Extensions; + +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Diagnostics; + +using MSTest.Analyzers.Helpers; + +namespace MSTest.Analyzers; + +/// +/// MSTEST0044: . +/// +[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] +public sealed class PreferTestMethodOverDataTestMethodAnalyzer : DiagnosticAnalyzer +{ + internal static readonly DiagnosticDescriptor PreferTestMethodOverDataTestMethodRule = DiagnosticDescriptorHelper.Create( + DiagnosticIds.PreferTestMethodOverDataTestMethodRuleId, + title: new LocalizableResourceString(nameof(Resources.PreferTestMethodOverDataTestMethodAnalyzerTitle), Resources.ResourceManager, typeof(Resources)), + messageFormat: new LocalizableResourceString(nameof(Resources.PreferTestMethodOverDataTestMethodAnalyzerMessageFormat), Resources.ResourceManager, typeof(Resources)), + description: new LocalizableResourceString(nameof(Resources.PreferTestMethodOverDataTestMethodAnalyzerDescription), Resources.ResourceManager, typeof(Resources)), + Category.Design, + DiagnosticSeverity.Info, + isEnabledByDefault: true); + + /// + public override ImmutableArray SupportedDiagnostics { get; } + = ImmutableArray.Create(PreferTestMethodOverDataTestMethodRule); + + /// + public override void Initialize(AnalysisContext context) + { + context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); + context.EnableConcurrentExecution(); + + context.RegisterCompilationStartAction(context => + { + if (!context.Compilation.TryGetOrCreateTypeByMetadataName(WellKnownTypeNames.MicrosoftVisualStudioTestToolsUnitTestingDataTestMethodAttribute, out INamedTypeSymbol? dataTestMethodAttributeSymbol)) + { + return; + } + + context.RegisterSymbolAction(context => AnalyzeMethod(context, dataTestMethodAttributeSymbol), SymbolKind.Method); + context.RegisterSymbolAction(context => AnalyzeNamedType(context, dataTestMethodAttributeSymbol), SymbolKind.NamedType); + }); + } + + private static void AnalyzeMethod(SymbolAnalysisContext context, INamedTypeSymbol dataTestMethodAttributeSymbol) + { + var methodSymbol = (IMethodSymbol)context.Symbol; + + foreach (AttributeData attribute in methodSymbol.GetAttributes()) + { + // Only report on direct application of DataTestMethodAttribute, not inherited ones + if (SymbolEqualityComparer.Default.Equals(attribute.AttributeClass, dataTestMethodAttributeSymbol)) + { + if (attribute.ApplicationSyntaxReference is { } syntaxRef) + { + context.ReportDiagnostic(syntaxRef.CreateDiagnostic(PreferTestMethodOverDataTestMethodRule, context.CancellationToken)); + } + } + } + } + + private static void AnalyzeNamedType(SymbolAnalysisContext context, INamedTypeSymbol dataTestMethodAttributeSymbol) + { + var namedTypeSymbol = (INamedTypeSymbol)context.Symbol; + + // Check if this type directly inherits from DataTestMethodAttribute + if (dataTestMethodAttributeSymbol.Equals(namedTypeSymbol.BaseType, SymbolEqualityComparer.Default)) + { + context.ReportDiagnostic(namedTypeSymbol.CreateDiagnostic(PreferTestMethodOverDataTestMethodRule)); + } + } +} diff --git a/src/Analyzers/MSTest.Analyzers/PublicAPI.Unshipped.txt b/src/Analyzers/MSTest.Analyzers/PublicAPI.Unshipped.txt index 7dc5c58110..04b7181a13 100644 --- a/src/Analyzers/MSTest.Analyzers/PublicAPI.Unshipped.txt +++ b/src/Analyzers/MSTest.Analyzers/PublicAPI.Unshipped.txt @@ -1 +1,5 @@ #nullable enable +MSTest.Analyzers.PreferTestMethodOverDataTestMethodAnalyzer +MSTest.Analyzers.PreferTestMethodOverDataTestMethodAnalyzer.PreferTestMethodOverDataTestMethodAnalyzer() -> void +override MSTest.Analyzers.PreferTestMethodOverDataTestMethodAnalyzer.Initialize(Microsoft.CodeAnalysis.Diagnostics.AnalysisContext! context) -> void +override MSTest.Analyzers.PreferTestMethodOverDataTestMethodAnalyzer.SupportedDiagnostics.get -> System.Collections.Immutable.ImmutableArray diff --git a/src/Analyzers/MSTest.Analyzers/Resources.Designer.cs b/src/Analyzers/MSTest.Analyzers/Resources.Designer.cs index 46445d28d4..0281966296 100644 --- a/src/Analyzers/MSTest.Analyzers/Resources.Designer.cs +++ b/src/Analyzers/MSTest.Analyzers/Resources.Designer.cs @@ -708,6 +708,33 @@ internal static string PreferTestInitializeOverConstructorTitle { } } + /// + /// Looks up a localized string similar to 'DataTestMethodAttribute' is obsolete and provides no additional functionality over 'TestMethodAttribute'. Use 'TestMethodAttribute' for all test methods, including parameterized tests.. + /// + internal static string PreferTestMethodOverDataTestMethodAnalyzerDescription { + get { + return ResourceManager.GetString("PreferTestMethodOverDataTestMethodAnalyzerDescription", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 'DataTestMethod' is obsolete. Use 'TestMethod' instead.. + /// + internal static string PreferTestMethodOverDataTestMethodAnalyzerMessageFormat { + get { + return ResourceManager.GetString("PreferTestMethodOverDataTestMethodAnalyzerMessageFormat", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Prefer 'TestMethod' over 'DataTestMethod'. + /// + internal static string PreferTestMethodOverDataTestMethodAnalyzerTitle { + get { + return ResourceManager.GetString("PreferTestMethodOverDataTestMethodAnalyzerTitle", resourceCulture); + } + } + /// /// Looks up a localized string similar to Public methods should be test methods (marked with `[TestMethod]`).. /// diff --git a/src/Analyzers/MSTest.Analyzers/Resources.resx b/src/Analyzers/MSTest.Analyzers/Resources.resx index 304dfec95d..3a14ec010c 100644 --- a/src/Analyzers/MSTest.Analyzers/Resources.resx +++ b/src/Analyzers/MSTest.Analyzers/Resources.resx @@ -585,4 +585,13 @@ The type declaring these methods should also respect the following rules: An attribute that derives from 'RetryBaseAttribute' can be specified only on a test method - \ No newline at end of file + + Prefer 'TestMethod' over 'DataTestMethod' + + + 'DataTestMethod' is obsolete. Use 'TestMethod' instead. + + + 'DataTestMethodAttribute' is obsolete and provides no additional functionality over 'TestMethodAttribute'. Use 'TestMethodAttribute' for all test methods, including parameterized tests. + + diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf index d40df19f9c..ac7ad3490f 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf @@ -437,6 +437,21 @@ Typ deklarující tyto metody by měl také respektovat následující pravidla: Místo trvalého neúspěšného vyhodnocovacího výrazu použijte „Assert.Fail“. + + 'DataTestMethodAttribute' is obsolete and provides no additional functionality over 'TestMethodAttribute'. Use 'TestMethodAttribute' for all test methods, including parameterized tests. + 'DataTestMethodAttribute' is obsolete and provides no additional functionality over 'TestMethodAttribute'. Use 'TestMethodAttribute' for all test methods, including parameterized tests. + + + + 'DataTestMethod' is obsolete. Use 'TestMethod' instead. + 'DataTestMethod' is obsolete. Use 'TestMethod' instead. + + + + Prefer 'TestMethod' over 'DataTestMethod' + Prefer 'TestMethod' over 'DataTestMethod' + + Review or remove the assertion as its condition is known to be always true Zkontrolujte nebo odeberte kontrolní výraz, protože jeho podmínka je vždy true. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf index ed0272a850..dfc9df7f99 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf @@ -438,6 +438,21 @@ Der Typ, der diese Methoden deklariert, sollte auch die folgenden Regeln beachte Verwenden Sie „Assert.Fail“ anstelle einer Assert-Anweisung, bei der immer ein Fehler auftritt. + + 'DataTestMethodAttribute' is obsolete and provides no additional functionality over 'TestMethodAttribute'. Use 'TestMethodAttribute' for all test methods, including parameterized tests. + 'DataTestMethodAttribute' is obsolete and provides no additional functionality over 'TestMethodAttribute'. Use 'TestMethodAttribute' for all test methods, including parameterized tests. + + + + 'DataTestMethod' is obsolete. Use 'TestMethod' instead. + 'DataTestMethod' is obsolete. Use 'TestMethod' instead. + + + + Prefer 'TestMethod' over 'DataTestMethod' + Prefer 'TestMethod' over 'DataTestMethod' + + Review or remove the assertion as its condition is known to be always true Überprüfen oder entfernen Sie die Assertion, weil ihre Bedingung bekanntermaßen immer TRUE ist. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf index 75d54fde75..232854564f 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf @@ -437,6 +437,21 @@ El tipo que declara estos métodos también debe respetar las reglas siguientes: Usar "Assert.Fail" en lugar de una aserción que siempre tiene errores + + 'DataTestMethodAttribute' is obsolete and provides no additional functionality over 'TestMethodAttribute'. Use 'TestMethodAttribute' for all test methods, including parameterized tests. + 'DataTestMethodAttribute' is obsolete and provides no additional functionality over 'TestMethodAttribute'. Use 'TestMethodAttribute' for all test methods, including parameterized tests. + + + + 'DataTestMethod' is obsolete. Use 'TestMethod' instead. + 'DataTestMethod' is obsolete. Use 'TestMethod' instead. + + + + Prefer 'TestMethod' over 'DataTestMethod' + Prefer 'TestMethod' over 'DataTestMethod' + + Review or remove the assertion as its condition is known to be always true Revise o quite la aserción porque se sabe que su condición siempre es true diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf index 8bdc50155d..726fde02fc 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf @@ -437,6 +437,21 @@ Le type doit être une classe Utilisez « Assert.Fail » à la place d’une assertion toujours en échec + + 'DataTestMethodAttribute' is obsolete and provides no additional functionality over 'TestMethodAttribute'. Use 'TestMethodAttribute' for all test methods, including parameterized tests. + 'DataTestMethodAttribute' is obsolete and provides no additional functionality over 'TestMethodAttribute'. Use 'TestMethodAttribute' for all test methods, including parameterized tests. + + + + 'DataTestMethod' is obsolete. Use 'TestMethod' instead. + 'DataTestMethod' is obsolete. Use 'TestMethod' instead. + + + + Prefer 'TestMethod' over 'DataTestMethod' + Prefer 'TestMethod' over 'DataTestMethod' + + Review or remove the assertion as its condition is known to be always true Vérifier ou supprimer l’assertion, car sa condition est connue pour être toujours vraie diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf index 3201a18d17..941bca4679 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf @@ -437,6 +437,21 @@ Anche il tipo che dichiara questi metodi deve rispettare le regole seguenti: Usare 'Assert.Fail' invece di un'asserzione che ha sempre esito negativo + + 'DataTestMethodAttribute' is obsolete and provides no additional functionality over 'TestMethodAttribute'. Use 'TestMethodAttribute' for all test methods, including parameterized tests. + 'DataTestMethodAttribute' is obsolete and provides no additional functionality over 'TestMethodAttribute'. Use 'TestMethodAttribute' for all test methods, including parameterized tests. + + + + 'DataTestMethod' is obsolete. Use 'TestMethod' instead. + 'DataTestMethod' is obsolete. Use 'TestMethod' instead. + + + + Prefer 'TestMethod' over 'DataTestMethod' + Prefer 'TestMethod' over 'DataTestMethod' + + Review or remove the assertion as its condition is known to be always true Rivedere o rimuovere l'asserzione perché la relativa condizione è sempre true diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf index 695f062ace..664263b7df 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf @@ -437,6 +437,21 @@ The type declaring these methods should also respect the following rules: 常に失敗しているアサートの代わりに 'Assert.Fail' を使用する + + 'DataTestMethodAttribute' is obsolete and provides no additional functionality over 'TestMethodAttribute'. Use 'TestMethodAttribute' for all test methods, including parameterized tests. + 'DataTestMethodAttribute' is obsolete and provides no additional functionality over 'TestMethodAttribute'. Use 'TestMethodAttribute' for all test methods, including parameterized tests. + + + + 'DataTestMethod' is obsolete. Use 'TestMethod' instead. + 'DataTestMethod' is obsolete. Use 'TestMethod' instead. + + + + Prefer 'TestMethod' over 'DataTestMethod' + Prefer 'TestMethod' over 'DataTestMethod' + + Review or remove the assertion as its condition is known to be always true アサーションの条件が常に TRUE であることが判明しているため、アサーションを確認または削除してください diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf index 1f862f2ac8..8b7e9cc65d 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf @@ -437,6 +437,21 @@ The type declaring these methods should also respect the following rules: 항상 실패하는 어설션 대신 'Assert.Fail' 사용 + + 'DataTestMethodAttribute' is obsolete and provides no additional functionality over 'TestMethodAttribute'. Use 'TestMethodAttribute' for all test methods, including parameterized tests. + 'DataTestMethodAttribute' is obsolete and provides no additional functionality over 'TestMethodAttribute'. Use 'TestMethodAttribute' for all test methods, including parameterized tests. + + + + 'DataTestMethod' is obsolete. Use 'TestMethod' instead. + 'DataTestMethod' is obsolete. Use 'TestMethod' instead. + + + + Prefer 'TestMethod' over 'DataTestMethod' + Prefer 'TestMethod' over 'DataTestMethod' + + Review or remove the assertion as its condition is known to be always true 조건이 항상 true인 것으로 알려진 어설션 검토 또는 제거 diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf index b82fdc2980..8181c95c2a 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf @@ -437,6 +437,21 @@ Typ deklarujący te metody powinien również przestrzegać następujących regu Użyj trybu „Assert.Fail” zamiast kończącej się zawsze niepowodzeniem instrukcji asercji + + 'DataTestMethodAttribute' is obsolete and provides no additional functionality over 'TestMethodAttribute'. Use 'TestMethodAttribute' for all test methods, including parameterized tests. + 'DataTestMethodAttribute' is obsolete and provides no additional functionality over 'TestMethodAttribute'. Use 'TestMethodAttribute' for all test methods, including parameterized tests. + + + + 'DataTestMethod' is obsolete. Use 'TestMethod' instead. + 'DataTestMethod' is obsolete. Use 'TestMethod' instead. + + + + Prefer 'TestMethod' over 'DataTestMethod' + Prefer 'TestMethod' over 'DataTestMethod' + + Review or remove the assertion as its condition is known to be always true Przejrzyj lub usuń asercję, ponieważ wiadomo, że jej warunek ma zawsze wartość true diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf index db27da787d..6272a68732 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf @@ -437,6 +437,21 @@ O tipo que declara esses métodos também deve respeitar as seguintes regras: Usar "Assert.Fail" em vez de uma asserção sempre com falha + + 'DataTestMethodAttribute' is obsolete and provides no additional functionality over 'TestMethodAttribute'. Use 'TestMethodAttribute' for all test methods, including parameterized tests. + 'DataTestMethodAttribute' is obsolete and provides no additional functionality over 'TestMethodAttribute'. Use 'TestMethodAttribute' for all test methods, including parameterized tests. + + + + 'DataTestMethod' is obsolete. Use 'TestMethod' instead. + 'DataTestMethod' is obsolete. Use 'TestMethod' instead. + + + + Prefer 'TestMethod' over 'DataTestMethod' + Prefer 'TestMethod' over 'DataTestMethod' + + Review or remove the assertion as its condition is known to be always true Examine ou remova a asserção, pois a sua condição é conhecida por ser sempre verdadeira diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf index f2770a865e..a0354e5f93 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf @@ -443,6 +443,21 @@ The type declaring these methods should also respect the following rules: Используйте "Assert.Fail" вместо утверждения с постоянным сбоем + + 'DataTestMethodAttribute' is obsolete and provides no additional functionality over 'TestMethodAttribute'. Use 'TestMethodAttribute' for all test methods, including parameterized tests. + 'DataTestMethodAttribute' is obsolete and provides no additional functionality over 'TestMethodAttribute'. Use 'TestMethodAttribute' for all test methods, including parameterized tests. + + + + 'DataTestMethod' is obsolete. Use 'TestMethod' instead. + 'DataTestMethod' is obsolete. Use 'TestMethod' instead. + + + + Prefer 'TestMethod' over 'DataTestMethod' + Prefer 'TestMethod' over 'DataTestMethod' + + Review or remove the assertion as its condition is known to be always true Проверьте или удалите утверждение, так как известно, что его условие всегда истинно. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf index 5e0f02d87f..8ab55f1ba0 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf @@ -437,6 +437,21 @@ Bu yöntemleri bildiren tipin ayrıca aşağıdaki kurallara uyması gerekir: Her zaman başarısız olan onaylama yerine 'Assert.Fail' seçeneğini kullanın + + 'DataTestMethodAttribute' is obsolete and provides no additional functionality over 'TestMethodAttribute'. Use 'TestMethodAttribute' for all test methods, including parameterized tests. + 'DataTestMethodAttribute' is obsolete and provides no additional functionality over 'TestMethodAttribute'. Use 'TestMethodAttribute' for all test methods, including parameterized tests. + + + + 'DataTestMethod' is obsolete. Use 'TestMethod' instead. + 'DataTestMethod' is obsolete. Use 'TestMethod' instead. + + + + Prefer 'TestMethod' over 'DataTestMethod' + Prefer 'TestMethod' over 'DataTestMethod' + + Review or remove the assertion as its condition is known to be always true Koşulu her zaman true olarak bilinen onaylamayı gözden geçirin veya kaldırın diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf index ff54e2c6e7..2be5ac4279 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf @@ -437,6 +437,21 @@ The type declaring these methods should also respect the following rules: 使用 “Assert.Fail” 而不是始终失败的断言 + + 'DataTestMethodAttribute' is obsolete and provides no additional functionality over 'TestMethodAttribute'. Use 'TestMethodAttribute' for all test methods, including parameterized tests. + 'DataTestMethodAttribute' is obsolete and provides no additional functionality over 'TestMethodAttribute'. Use 'TestMethodAttribute' for all test methods, including parameterized tests. + + + + 'DataTestMethod' is obsolete. Use 'TestMethod' instead. + 'DataTestMethod' is obsolete. Use 'TestMethod' instead. + + + + Prefer 'TestMethod' over 'DataTestMethod' + Prefer 'TestMethod' over 'DataTestMethod' + + Review or remove the assertion as its condition is known to be always true 查看或移除断言,因为已知其条件始终为 true diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf index dca44939e7..5dbdf5721f 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf @@ -437,6 +437,21 @@ The type declaring these methods should also respect the following rules: 使用 'Assert.Fail',而不是一直失敗的聲明 + + 'DataTestMethodAttribute' is obsolete and provides no additional functionality over 'TestMethodAttribute'. Use 'TestMethodAttribute' for all test methods, including parameterized tests. + 'DataTestMethodAttribute' is obsolete and provides no additional functionality over 'TestMethodAttribute'. Use 'TestMethodAttribute' for all test methods, including parameterized tests. + + + + 'DataTestMethod' is obsolete. Use 'TestMethod' instead. + 'DataTestMethod' is obsolete. Use 'TestMethod' instead. + + + + Prefer 'TestMethod' over 'DataTestMethod' + Prefer 'TestMethod' over 'DataTestMethod' + + Review or remove the assertion as its condition is known to be always true 檢閱或移除判斷提示,因為已知其條件一律為 True diff --git a/test/UnitTests/MSTest.Analyzers.UnitTests/PreferTestMethodOverDataTestMethodAnalyzerTests.cs b/test/UnitTests/MSTest.Analyzers.UnitTests/PreferTestMethodOverDataTestMethodAnalyzerTests.cs new file mode 100644 index 0000000000..b642a86ca7 --- /dev/null +++ b/test/UnitTests/MSTest.Analyzers.UnitTests/PreferTestMethodOverDataTestMethodAnalyzerTests.cs @@ -0,0 +1,142 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using VerifyCS = MSTest.Analyzers.Test.CSharpCodeFixVerifier< + MSTest.Analyzers.PreferTestMethodOverDataTestMethodAnalyzer, + MSTest.Analyzers.PreferTestMethodOverDataTestMethodFixer>; + +namespace MSTest.Analyzers.Test; + +[TestClass] +public sealed class PreferTestMethodOverDataTestMethodAnalyzerTests +{ + [TestMethod] + public async Task WhenUsingTestMethod_NoDiagnostic() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + } + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, code); + } + + [TestMethod] + public async Task WhenUsingDataTestMethod_Diagnostic() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [[|DataTestMethod|]] + public void MyTestMethod() + { + } + } + """; + + string fixedCode = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + } + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, fixedCode); + } + + [TestMethod] + public async Task WhenUsingDataTestMethodWithDisplayName_Diagnostic() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [[|DataTestMethod("Display Name")|]] + public void MyTestMethod() + { + } + } + """; + + string fixedCode = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod("Display Name")] + public void MyTestMethod() + { + } + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, fixedCode); + } + + [TestMethod] + public async Task WhenUsingDataTestMethodWithMultipleAttributesInSameList_Diagnostic() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [Ignore, [|DataTestMethod|]] + public void MyTestMethod() + { + } + } + """; + + string fixedCode = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [Ignore, TestMethod] + public void MyTestMethod() + { + } + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, fixedCode); + } + + [TestMethod] + public async Task WhenInheritingDataTestMethod_Diagnostic() + { + // TODO: Codefix doesn't handle this yet. So no codefix is offered. + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + internal sealed class [|MyDataTestMethodAttribute|] : DataTestMethodAttribute + { + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, code); + } +} From 0b16e9eaa43d721889cb1615734af9ec1fa789a3 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Thu, 12 Jun 2025 10:42:24 +0200 Subject: [PATCH 082/541] Add lifecycle callbacks to test host orchestrator (#5717) --- .../MSBuildExtensions.cs | 6 ++ .../MSBuildOrchestratorLifecycleCallbacks.cs | 70 +++++++++++++++++++ .../Tasks/InvokeTestingPlatformTask.cs | 4 ++ .../Hosts/TestHostBuilder.cs | 6 ++ .../Hosts/TestHostOchestratorHost.cs | 11 +++ .../ITestHostControllersExtension.cs | 9 +++ ...TestHostOrchestratorApplicationLifetime.cs | 25 +++++++ .../ITestHostOrchestratorManager.cs | 5 ++ .../TestHostOrchestratorManager.cs | 34 +++++++++ .../RetryFailedTestsTests.cs | 47 +++++++++++-- 10 files changed, 211 insertions(+), 6 deletions(-) create mode 100644 src/Platform/Microsoft.Testing.Extensions.MSBuild/MSBuildOrchestratorLifecycleCallbacks.cs create mode 100644 src/Platform/Microsoft.Testing.Platform/TestHostOrcherstrator/ITestHostControllersExtension.cs create mode 100644 src/Platform/Microsoft.Testing.Platform/TestHostOrcherstrator/ITestHostOrchestratorApplicationLifetime.cs diff --git a/src/Platform/Microsoft.Testing.Extensions.MSBuild/MSBuildExtensions.cs b/src/Platform/Microsoft.Testing.Extensions.MSBuild/MSBuildExtensions.cs index cbd3d784be..57b93bb738 100644 --- a/src/Platform/Microsoft.Testing.Extensions.MSBuild/MSBuildExtensions.cs +++ b/src/Platform/Microsoft.Testing.Extensions.MSBuild/MSBuildExtensions.cs @@ -26,6 +26,12 @@ public static void AddMSBuild(this ITestApplicationBuilder builder) serviceProvider.GetCommandLineOptions(), serviceProvider.GetTestApplicationCancellationTokenSource())); + ((TestApplicationBuilder)builder).TestHostOrchestrator.AddTestHostOrchestratorApplicationLifetime( + serviceProvider => new MSBuildOrchestratorLifetime( + serviceProvider.GetConfiguration(), + serviceProvider.GetCommandLineOptions(), + serviceProvider.GetTestApplicationCancellationTokenSource())); + CompositeExtensionFactory compositeExtensionFactory = new(serviceProvider => new MSBuildConsumer( serviceProvider, diff --git a/src/Platform/Microsoft.Testing.Extensions.MSBuild/MSBuildOrchestratorLifecycleCallbacks.cs b/src/Platform/Microsoft.Testing.Extensions.MSBuild/MSBuildOrchestratorLifecycleCallbacks.cs new file mode 100644 index 0000000000..b74ba02f2f --- /dev/null +++ b/src/Platform/Microsoft.Testing.Extensions.MSBuild/MSBuildOrchestratorLifecycleCallbacks.cs @@ -0,0 +1,70 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using Microsoft.Testing.Extensions.MSBuild.Serializers; +using Microsoft.Testing.Platform.CommandLine; +using Microsoft.Testing.Platform.Configurations; +using Microsoft.Testing.Platform.Extensions.TestHostOrchestrator; +using Microsoft.Testing.Platform.Helpers; +using Microsoft.Testing.Platform.IPC; +using Microsoft.Testing.Platform.IPC.Models; +using Microsoft.Testing.Platform.IPC.Serializers; +using Microsoft.Testing.Platform.Services; + +namespace Microsoft.Testing.Extensions.MSBuild; + +internal sealed class MSBuildOrchestratorLifetime : ITestHostOrchestratorApplicationLifetime +{ + private readonly IConfiguration _configuration; + private readonly ICommandLineOptions _commandLineOptions; + private readonly ITestApplicationCancellationTokenSource _testApplicationCancellationTokenSource; + + public MSBuildOrchestratorLifetime( + IConfiguration configuration, + ICommandLineOptions commandLineOptions, + ITestApplicationCancellationTokenSource testApplicationCancellationTokenSource) + { + _configuration = configuration; + _commandLineOptions = commandLineOptions; + _testApplicationCancellationTokenSource = testApplicationCancellationTokenSource; + } + + public string Uid => nameof(MSBuildOrchestratorLifetime); + + public string Version => AppVersion.DefaultSemVer; + + public string DisplayName => nameof(MSBuildOrchestratorLifetime); + + public string Description => Resources.ExtensionResources.MSBuildExtensionsDescription; + + public Task IsEnabledAsync() + => Task.FromResult(_commandLineOptions.IsOptionSet(MSBuildConstants.MSBuildNodeOptionKey)); + + public async Task BeforeRunAsync(CancellationToken cancellationToken) + { + if (!_commandLineOptions.TryGetOptionArgumentList(MSBuildConstants.MSBuildNodeOptionKey, out string[]? msbuildInfo)) + { + throw new InvalidOperationException($"MSBuild pipe name not found in the command line, missing {MSBuildConstants.MSBuildNodeOptionKey}"); + } + + if (msbuildInfo is null || msbuildInfo.Length != 1 || string.IsNullOrEmpty(msbuildInfo[0])) + { + throw new InvalidOperationException($"MSBuild pipe name not found in the command line, missing argument for {MSBuildConstants.MSBuildNodeOptionKey}"); + } + + using var pipeClient = new NamedPipeClient(msbuildInfo[0]); + pipeClient.RegisterSerializer(new ModuleInfoRequestSerializer(), typeof(ModuleInfoRequest)); + pipeClient.RegisterSerializer(new VoidResponseSerializer(), typeof(VoidResponse)); + using var cancellationTokenSource = new CancellationTokenSource(TimeoutHelper.DefaultHangTimeSpanTimeout); + using var linkedCancellationToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationTokenSource.Token, _testApplicationCancellationTokenSource.CancellationToken); + await pipeClient.ConnectAsync(linkedCancellationToken.Token).ConfigureAwait(false); + await pipeClient.RequestReplyAsync( + new ModuleInfoRequest( + RuntimeInformation.FrameworkDescription, + RuntimeInformation.ProcessArchitecture.ToString().ToLowerInvariant(), + _configuration.GetTestResultDirectory()), + _testApplicationCancellationTokenSource.CancellationToken).ConfigureAwait(false); + } + + public Task AfterRunAsync(int exitCode, CancellationToken cancellation) => Task.CompletedTask; +} diff --git a/src/Platform/Microsoft.Testing.Platform.MSBuild/Tasks/InvokeTestingPlatformTask.cs b/src/Platform/Microsoft.Testing.Platform.MSBuild/Tasks/InvokeTestingPlatformTask.cs index b5fcf97917..a10ac2eed5 100644 --- a/src/Platform/Microsoft.Testing.Platform.MSBuild/Tasks/InvokeTestingPlatformTask.cs +++ b/src/Platform/Microsoft.Testing.Platform.MSBuild/Tasks/InvokeTestingPlatformTask.cs @@ -433,6 +433,10 @@ protected override bool HandleTaskExecutionErrors() private Task HandleRequestAsync(IRequest request) { + // For the case, of orchestrator (e.g, Retry), we can get ModuleInfoRequest from the orchestrator itself. + // If there is no orchestrator or the orchestrator didn't send ModuleInfoRequest, we will get it from the first test host. + // For the case of retry, the request is different between the orchestrator and the test host. + // More specifically, the results directory is different (orchestrator points to original, while test host points to the specific retry results directory). if (request is ModuleInfoRequest moduleInfo) { if (_moduleInfo is null) diff --git a/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostBuilder.cs b/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostBuilder.cs index 8ace6b4971..90e9b551c1 100644 --- a/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostBuilder.cs +++ b/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostBuilder.cs @@ -364,6 +364,12 @@ await LogTestHostCreatedAsync( { policiesService.ProcessRole = TestProcessRole.TestHostOrchestrator; await proxyOutputDevice.HandleProcessRoleAsync(TestProcessRole.TestHostOrchestrator).ConfigureAwait(false); + + // Build and register the test application lifecycle callbacks. + ITestHostOrchestratorApplicationLifetime[] orchestratorLifetimes = + await ((TestHostOrchestratorManager)TestHostOrchestratorManager).BuildTestHostOrchestratorApplicationLifetimesAsync(serviceProvider).ConfigureAwait(false); + serviceProvider.AddServices(orchestratorLifetimes); + return new TestHostOrchestratorHost(testHostOrchestratorConfiguration, serviceProvider); } diff --git a/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostOchestratorHost.cs b/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostOchestratorHost.cs index 5889813f81..ebf0bc3a10 100644 --- a/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostOchestratorHost.cs +++ b/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostOchestratorHost.cs @@ -27,7 +27,18 @@ public async Task RunAsync() await logger.LogInformationAsync($"Running test orchestrator '{testHostOrchestrator.Uid}'").ConfigureAwait(false); try { + foreach (ITestHostOrchestratorApplicationLifetime orchestratorLifetime in _serviceProvider.GetServicesInternal()) + { + await orchestratorLifetime.BeforeRunAsync(applicationCancellationToken.CancellationToken).ConfigureAwait(false); + } + exitCode = await testHostOrchestrator.OrchestrateTestHostExecutionAsync().ConfigureAwait(false); + + foreach (ITestHostOrchestratorApplicationLifetime orchestratorLifetime in _serviceProvider.GetServicesInternal()) + { + await orchestratorLifetime.AfterRunAsync(exitCode, applicationCancellationToken.CancellationToken).ConfigureAwait(false); + await DisposeHelper.DisposeAsync(orchestratorLifetime).ConfigureAwait(false); + } } catch (OperationCanceledException) when (applicationCancellationToken.CancellationToken.IsCancellationRequested) { diff --git a/src/Platform/Microsoft.Testing.Platform/TestHostOrcherstrator/ITestHostControllersExtension.cs b/src/Platform/Microsoft.Testing.Platform/TestHostOrcherstrator/ITestHostControllersExtension.cs new file mode 100644 index 0000000000..02c81a5fee --- /dev/null +++ b/src/Platform/Microsoft.Testing.Platform/TestHostOrcherstrator/ITestHostControllersExtension.cs @@ -0,0 +1,9 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +namespace Microsoft.Testing.Platform.Extensions.TestHostOrchestrator; + +/// +/// Represents an extension for test host orchestrators. +/// +internal interface ITestHostOrchestratorExtension : IExtension; diff --git a/src/Platform/Microsoft.Testing.Platform/TestHostOrcherstrator/ITestHostOrchestratorApplicationLifetime.cs b/src/Platform/Microsoft.Testing.Platform/TestHostOrcherstrator/ITestHostOrchestratorApplicationLifetime.cs new file mode 100644 index 0000000000..93cb179eb8 --- /dev/null +++ b/src/Platform/Microsoft.Testing.Platform/TestHostOrcherstrator/ITestHostOrchestratorApplicationLifetime.cs @@ -0,0 +1,25 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +namespace Microsoft.Testing.Platform.Extensions.TestHostOrchestrator; + +// NOTE: The equivalent of this for "test host" is ITestApplicationLifecycleCallbacks, which is an unfortunate naming. +// If we ever open orchestration before MTP v2 (https://github.com/microsoft/testfx/issues/5733), we should +// consider if we are okay with this kinda inconsistent naming between test host and test host orchestrator. +internal interface ITestHostOrchestratorApplicationLifetime : ITestHostOrchestratorExtension +{ + /// + /// Executes before the orchestrator runs. + /// + /// The cancellation token. + /// A task representing the asynchronous operation. + Task BeforeRunAsync(CancellationToken cancellationToken); + + /// + /// Executes after the orchestrator runs. + /// + /// The exit code of the orchestrator. + /// The cancellation token. + /// A task representing the asynchronous operation. + Task AfterRunAsync(int exitCode, CancellationToken cancellation); +} diff --git a/src/Platform/Microsoft.Testing.Platform/TestHostOrcherstrator/ITestHostOrchestratorManager.cs b/src/Platform/Microsoft.Testing.Platform/TestHostOrcherstrator/ITestHostOrchestratorManager.cs index 3ad59955fb..7f4d5c0827 100644 --- a/src/Platform/Microsoft.Testing.Platform/TestHostOrcherstrator/ITestHostOrchestratorManager.cs +++ b/src/Platform/Microsoft.Testing.Platform/TestHostOrcherstrator/ITestHostOrchestratorManager.cs @@ -9,5 +9,10 @@ internal interface ITestHostOrchestratorManager { void AddTestHostOrchestrator(Func factory); + // NOTE: In ITestHostManager, we have AddTestApplicationLifecycleCallbacks, which is an unfortunate naming. + // If we ever open orchestration before MTP v2 (https://github.com/microsoft/testfx/issues/5733), we should + // consider if we are okay with this kinda inconsistent naming between test host and test host orchestrator. + void AddTestHostOrchestratorApplicationLifetime(Func testHostOrchestratorApplicationLifetimeFactory); + Task BuildAsync(ServiceProvider serviceProvider); } diff --git a/src/Platform/Microsoft.Testing.Platform/TestHostOrcherstrator/TestHostOrchestratorManager.cs b/src/Platform/Microsoft.Testing.Platform/TestHostOrcherstrator/TestHostOrchestratorManager.cs index a4483d6535..1997c40d08 100644 --- a/src/Platform/Microsoft.Testing.Platform/TestHostOrcherstrator/TestHostOrchestratorManager.cs +++ b/src/Platform/Microsoft.Testing.Platform/TestHostOrcherstrator/TestHostOrchestratorManager.cs @@ -8,6 +8,7 @@ namespace Microsoft.Testing.Platform.Extensions.TestHostOrchestrator; internal sealed class TestHostOrchestratorManager : ITestHostOrchestratorManager { + private readonly List> _testHostOrchestratorApplicationLifetimeFactories = []; private List>? _factories; public void AddTestHostOrchestrator(Func factory) @@ -48,4 +49,37 @@ public async Task BuildAsync(ServiceProvider return new TestHostOrchestratorConfiguration([.. orchestrators]); } + + public void AddTestHostOrchestratorApplicationLifetime(Func testHostOrchestratorApplicationLifetimeFactory) + { + Guard.NotNull(testHostOrchestratorApplicationLifetimeFactory); + _testHostOrchestratorApplicationLifetimeFactories.Add(testHostOrchestratorApplicationLifetimeFactory); + } + + internal async Task BuildTestHostOrchestratorApplicationLifetimesAsync(ServiceProvider serviceProvider) + { + List lifetimes = []; + foreach (Func testHostOrchestratorApplicationLifetimeFactory in _testHostOrchestratorApplicationLifetimeFactories) + { + ITestHostOrchestratorApplicationLifetime service = testHostOrchestratorApplicationLifetimeFactory(serviceProvider); + + // Check if we have already extensions of the same type with same id registered + if (lifetimes.Any(x => x.Uid == service.Uid)) + { + ITestHostOrchestratorApplicationLifetime currentRegisteredExtension = lifetimes.Single(x => x.Uid == service.Uid); + throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, PlatformResources.ExtensionWithSameUidAlreadyRegisteredErrorMessage, service.Uid, currentRegisteredExtension.GetType())); + } + + // We initialize only if enabled + if (await service.IsEnabledAsync().ConfigureAwait(false)) + { + await service.TryInitializeAsync().ConfigureAwait(false); + + // Register the extension for usage + lifetimes.Add(service); + } + } + + return [.. lifetimes]; + } } diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/RetryFailedTestsTests.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/RetryFailedTestsTests.cs index c4f229af9d..610162f739 100644 --- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/RetryFailedTestsTests.cs +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/RetryFailedTestsTests.cs @@ -178,6 +178,31 @@ await RetryHelper.RetryAsync( }, 3, TimeSpan.FromSeconds(5)); } + [TestMethod] + public async Task RetryFailedTests_PassingFromFirstTime_UsingOldDotnetTest_MoveFiles_Succeeds() + { + string resultDirectory = Path.Combine(AssetFixture.TargetAssetPath, Guid.NewGuid().ToString("N")); + + DotnetMuxerResult result = await DotnetCli.RunAsync( + $"test \"{AssetFixture.TargetAssetPath}\" -- --retry-failed-tests 1 --results-directory \"{resultDirectory}\"", + AcceptanceFixture.NuGetGlobalPackagesFolder.Path, + workingDirectory: AssetFixture.TargetAssetPath); + + Assert.AreEqual(ExitCodes.Success, result.ExitCode); + + // File names are on the form: RetryFailedTests_tfm_architecture.log + string[] logFilesFromInvokeTestingPlatformTask = Directory.GetFiles(resultDirectory, "RetryFailedTests_*_*.log"); + Assert.AreEqual(TargetFrameworks.All.Length, logFilesFromInvokeTestingPlatformTask.Length); + foreach (string logFile in logFilesFromInvokeTestingPlatformTask) + { + string logFileContents = File.ReadAllText(logFile); + Assert.Contains("Test run summary: Passed!", logFileContents); + Assert.Contains("total: 3", logFileContents); + Assert.Contains("succeeded: 3", logFileContents); + Assert.Contains("Tests suite completed successfully in 1 attempts", logFileContents); + } + } + public sealed class TestAssetFixture() : TestAssetFixtureBase(AcceptanceFixture.NuGetGlobalPackagesFolder) { public string TargetAssetPath => GetAssetPath(AssetName); @@ -200,14 +225,22 @@ public sealed class TestAssetFixture() : TestAssetFixtureBase(AcceptanceFixture. Exe true preview + false + true + false + +#file dotnet.config +[dotnet.test.runner] +name= "VSTest" + #file Program.cs using Microsoft.Testing.Extensions; using Microsoft.Testing.Extensions.TrxReport.Abstractions; @@ -215,6 +248,7 @@ public sealed class TestAssetFixture() : TestAssetFixtureBase(AcceptanceFixture. using Microsoft.Testing.Platform.Capabilities.TestFramework; using Microsoft.Testing.Platform.Extensions.Messages; using Microsoft.Testing.Platform.Extensions.TestFramework; +using Microsoft.Testing.Platform.MSBuild; using Microsoft.Testing.Platform.Services; public class Program @@ -228,6 +262,7 @@ public static async Task Main(string[] args) builder.AddCrashDumpProvider(); builder.AddTrxReportProvider(); builder.AddRetryProvider(); + builder.AddMSBuild(); using ITestApplication app = await builder.BuildAsync(); return await app.RunAsync(); } @@ -268,7 +303,7 @@ public async Task ExecuteRequestAsync(ExecuteRequestContext context) string resultDir = Environment.GetEnvironmentVariable("RESULTDIR")!; bool crash = Environment.GetEnvironmentVariable("CRASH") == "1"; - if (await TestMethod1(fail, resultDir, crash)) + if (TestMethod1(fail, resultDir, crash)) { await context.MessageBus.PublishAsync(this, new TestNodeUpdateMessage(context.Request.Session.SessionUid, new TestNode() { Uid = "1", DisplayName = "TestMethod1", Properties = new(PassedTestNodeStateProperty.CachedInstance) })); @@ -279,7 +314,7 @@ public async Task ExecuteRequestAsync(ExecuteRequestContext context) new TestNode() { Uid = "1", DisplayName = "TestMethod1", Properties = new(new FailedTestNodeStateProperty()) })); } - if (await TestMethod2(fail, resultDir)) + if (TestMethod2(fail, resultDir)) { await context.MessageBus.PublishAsync(this, new TestNodeUpdateMessage(context.Request.Session.SessionUid, new TestNode() { Uid = "2", DisplayName = "TestMethod2", Properties = new(PassedTestNodeStateProperty.CachedInstance) })); @@ -290,7 +325,7 @@ public async Task ExecuteRequestAsync(ExecuteRequestContext context) new TestNode() { Uid = "2", DisplayName = "TestMethod2", Properties = new(new FailedTestNodeStateProperty()) })); } - if (await TestMethod3(fail, resultDir)) + if (TestMethod3(fail, resultDir)) { await context.MessageBus.PublishAsync(this, new TestNodeUpdateMessage(context.Request.Session.SessionUid, new TestNode() { Uid = "3", DisplayName = "TestMethod3", Properties = new(PassedTestNodeStateProperty.CachedInstance) })); @@ -304,7 +339,7 @@ public async Task ExecuteRequestAsync(ExecuteRequestContext context) context.Complete(); } - private async Task TestMethod1(bool fail, string resultDir, bool crash) + private bool TestMethod1(bool fail, string resultDir, bool crash) { if (crash) { @@ -328,7 +363,7 @@ private async Task TestMethod1(bool fail, string resultDir, bool crash) return assert; } - private async Task TestMethod2(bool fail, string resultDir) + private bool TestMethod2(bool fail, string resultDir) { bool envVar = Environment.GetEnvironmentVariable("METHOD2") is null; System.Console.WriteLine("envVar " + envVar); @@ -348,7 +383,7 @@ private async Task TestMethod2(bool fail, string resultDir) return assert; } - private async Task TestMethod3(bool fail, string resultDir) + private bool TestMethod3(bool fail, string resultDir) { bool envVar = Environment.GetEnvironmentVariable("METHOD3") is null; From 7121ce9543814b0868b7bfdd4bd3dd63c7dd9b81 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Thu, 12 Jun 2025 17:56:31 +0200 Subject: [PATCH 083/541] Fix leak in TestRunCancellationToken (#5730) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Jakub Jareš --- .../VSTestAdapter/MSTestExecutor.cs | 2 +- .../Execution/ClassCleanupManager.cs | 2 +- .../Execution/TestRunCancellationToken.cs | 45 +++--- .../Execution/UnitTestRunner.cs | 24 +++- .../PlatformServiceProvider.cs | 5 +- .../PublicAPI/PublicAPI.Unshipped.txt | 2 + .../Services/TestContextImplementation.cs | 40 +++++- .../TestFramework.Extensions/TestContext.cs | 1 + .../LeakTests.cs | 133 ++++++++++++++++++ .../TestContextImplementationTests.cs | 2 +- .../TestablePlatformServiceProvider.cs | 2 +- 11 files changed, 218 insertions(+), 40 deletions(-) create mode 100644 test/IntegrationTests/MSTest.Acceptance.IntegrationTests/LeakTests.cs diff --git a/src/Adapter/MSTest.TestAdapter/VSTestAdapter/MSTestExecutor.cs b/src/Adapter/MSTest.TestAdapter/VSTestAdapter/MSTestExecutor.cs index 638e4507db..9bcc300321 100644 --- a/src/Adapter/MSTest.TestAdapter/VSTestAdapter/MSTestExecutor.cs +++ b/src/Adapter/MSTest.TestAdapter/VSTestAdapter/MSTestExecutor.cs @@ -154,7 +154,7 @@ async Task DoRunTestsAsync() { try { - _testRunCancellationToken = new TestRunCancellationToken(); + _testRunCancellationToken = new TestRunCancellationToken(_cancellationToken); await runTestsAction(_testRunCancellationToken).ConfigureAwait(false); } finally diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Execution/ClassCleanupManager.cs b/src/Adapter/MSTestAdapter.PlatformServices/Execution/ClassCleanupManager.cs index 43f89ad3c1..268fb8d2c7 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Execution/ClassCleanupManager.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Execution/ClassCleanupManager.cs @@ -66,7 +66,7 @@ public void MarkTestComplete(TestMethodInfo testMethodInfo, TestMethod testMetho internal static void ForceCleanup(TypeCache typeCache, IDictionary sourceLevelParameters, IMessageLogger logger) { using var writer = new ThreadSafeStringWriter(CultureInfo.InvariantCulture, "context"); - TestContext testContext = new TestContextImplementation(null, writer, sourceLevelParameters, logger); + TestContext testContext = new TestContextImplementation(null, writer, sourceLevelParameters, logger, testRunCancellationToken: null); IEnumerable classInfoCache = typeCache.ClassInfoListWithExecutableCleanupMethods; LogMessageListener? listener = null; foreach (TestClassInfo classInfo in classInfoCache) diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestRunCancellationToken.cs b/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestRunCancellationToken.cs index 607a553058..6a229f30cf 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestRunCancellationToken.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestRunCancellationToken.cs @@ -11,13 +11,22 @@ namespace Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter; #else [Obsolete(TestTools.UnitTesting.FrameworkConstants.PublicTypeObsoleteMessage)] #endif +#pragma warning disable CA1001 // Types that own disposable fields should be disposable public class TestRunCancellationToken +#pragma warning restore CA1001 // Types that own disposable fields should be disposable { + private readonly CancellationTokenSource _cancellationTokenSource = new(); + private readonly CancellationToken? _originalCancellationToken; + /// - /// Callbacks to be invoked when canceled. - /// Needs to be a concurrent collection, see https://github.com/microsoft/testfx/issues/3953. + /// Initializes a new instance of the class. /// - private readonly ConcurrentBag<(Action, object?)> _registeredCallbacks = []; + public TestRunCancellationToken() + { + } + + internal TestRunCancellationToken(CancellationToken originalCancellationToken) + => _originalCancellationToken = originalCancellationToken; /// /// Gets a value indicating whether the test run is canceled. @@ -32,10 +41,7 @@ private set if (!previousValue && value) { - foreach ((Action callBack, object? state) in _registeredCallbacks) - { - callBack.Invoke(state); - } + _cancellationTokenSource.Cancel(); } } } @@ -49,30 +55,21 @@ private set /// Registers a callback method to be invoked when canceled. /// /// Callback delegate for handling cancellation. - public void Register(Action callback) => _registeredCallbacks.Add((_ => callback(), null)); + public void Register(Action callback) => _cancellationTokenSource.Token.Register(_ => callback(), null); - internal void Register(Action callback, object? state) => _registeredCallbacks.Add((callback, state)); + internal CancellationTokenRegistration Register(Action callback, object? state) => _cancellationTokenSource.Token.Register(callback, state); /// - /// Unregister the callback method. + /// This method does nothing and is kept for binary compatibility. It should be removed in v4. + /// Note that the whole class is marked obsolete and will be made internal in v4. /// public void Unregister() -#if NETCOREAPP || WINDOWS_UWP - => _registeredCallbacks.Clear(); -#else { - while (!_registeredCallbacks.IsEmpty) - { - _ = _registeredCallbacks.TryTake(out _); - } } -#endif internal void ThrowIfCancellationRequested() - { - if (Canceled) - { - throw new OperationCanceledException(); - } - } + // If ThrowIfCancellationRequested is called from the main AppDomain where we have the original + // cancellation token, we should use that token. + // Otherwise, we have no choice other than using the cancellation token from the source created by TestRunCancellationToken. + => (_originalCancellationToken ?? _cancellationTokenSource.Token).ThrowIfCancellationRequested(); } diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Execution/UnitTestRunner.cs b/src/Adapter/MSTestAdapter.PlatformServices/Execution/UnitTestRunner.cs index e484c3368e..e0b25147eb 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Execution/UnitTestRunner.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Execution/UnitTestRunner.cs @@ -142,11 +142,17 @@ internal async Task RunSingleTestAsync(TestMethod testMethod, IDic { Guard.NotNull(testMethod); + ITestContext? testContextForTestExecution = null; + ITestContext? testContextForAssemblyInit = null; + ITestContext? testContextForClassInit = null; + ITestContext? testContextForClassCleanup = null; + ITestContext? testContextForAssemblyCleanup = null; + try { using var writer = new ThreadSafeStringWriter(CultureInfo.InvariantCulture, "context"); var properties = new Dictionary(testContextProperties); - ITestContext testContextForTestExecution = PlatformServiceProvider.Instance.GetTestContext(testMethod, writer, properties, messageLogger, UTF.UnitTestOutcome.InProgress); + testContextForTestExecution = PlatformServiceProvider.Instance.GetTestContext(testMethod, writer, properties, messageLogger, UTF.UnitTestOutcome.InProgress); // Get the testMethod TestMethodInfo? testMethodInfo = _typeCache.GetTestMethodInfo( @@ -166,7 +172,7 @@ internal async Task RunSingleTestAsync(TestMethod testMethod, IDic _assemblyFixtureTests.TryAdd(testMethod.AssemblyName, testMethodInfo.Parent.Parent); _classFixtureTests.TryAdd(testMethod.AssemblyName + testMethod.FullClassName, testMethodInfo.Parent); - ITestContext testContextForAssemblyInit = PlatformServiceProvider.Instance.GetTestContext(testMethod, writer, properties, messageLogger, testContextForTestExecution.Context.CurrentTestOutcome); + testContextForAssemblyInit = PlatformServiceProvider.Instance.GetTestContext(testMethod, writer, properties, messageLogger, testContextForTestExecution.Context.CurrentTestOutcome); TestResult assemblyInitializeResult = RunAssemblyInitializeIfNeeded(testMethodInfo, testContextForAssemblyInit); @@ -176,7 +182,7 @@ internal async Task RunSingleTestAsync(TestMethod testMethod, IDic } else { - ITestContext testContextForClassInit = PlatformServiceProvider.Instance.GetTestContext(testMethod, writer, properties, messageLogger, testContextForAssemblyInit.Context.CurrentTestOutcome); + testContextForClassInit = PlatformServiceProvider.Instance.GetTestContext(testMethod, writer, properties, messageLogger, testContextForAssemblyInit.Context.CurrentTestOutcome); TestResult classInitializeResult = testMethodInfo.Parent.GetResultOrRunClassInitialize(testContextForClassInit, assemblyInitializeResult.LogOutput!, assemblyInitializeResult.LogError!, assemblyInitializeResult.DebugTrace!, assemblyInitializeResult.TestContextMessages!); DebugEx.Assert(testMethodInfo.Parent.IsClassInitializeExecuted, "IsClassInitializeExecuted should be true after attempting to run it."); @@ -207,12 +213,12 @@ internal async Task RunSingleTestAsync(TestMethod testMethod, IDic } } - ITestContext testContextForClassCleanup = PlatformServiceProvider.Instance.GetTestContext(testMethod, writer, properties, messageLogger, testContextForTestExecution.Context.CurrentTestOutcome); + testContextForClassCleanup = PlatformServiceProvider.Instance.GetTestContext(testMethod, writer, properties, messageLogger, testContextForTestExecution.Context.CurrentTestOutcome); testMethodInfo?.Parent.RunClassCleanup(testContextForClassCleanup, _classCleanupManager, testMethodInfo, testMethod, result); if (testMethodInfo?.Parent.Parent.IsAssemblyInitializeExecuted == true) { - ITestContext testContextForAssemblyCleanup = PlatformServiceProvider.Instance.GetTestContext(testMethod, writer, properties, messageLogger, testContextForClassCleanup.Context.CurrentTestOutcome); + testContextForAssemblyCleanup = PlatformServiceProvider.Instance.GetTestContext(testMethod, writer, properties, messageLogger, testContextForClassCleanup.Context.CurrentTestOutcome); RunAssemblyCleanupIfNeeded(testContextForAssemblyCleanup, _classCleanupManager, _typeCache, result); } @@ -230,6 +236,14 @@ internal async Task RunSingleTestAsync(TestMethod testMethod, IDic } ]; } + finally + { + (testContextForTestExecution as IDisposable)?.Dispose(); + (testContextForAssemblyInit as IDisposable)?.Dispose(); + (testContextForClassInit as IDisposable)?.Dispose(); + (testContextForClassCleanup as IDisposable)?.Dispose(); + (testContextForAssemblyCleanup as IDisposable)?.Dispose(); + } } private static TestResult RunAssemblyInitializeIfNeeded(TestMethodInfo testMethodInfo, ITestContext testContext) diff --git a/src/Adapter/MSTestAdapter.PlatformServices/PlatformServiceProvider.cs b/src/Adapter/MSTestAdapter.PlatformServices/PlatformServiceProvider.cs index 21b7acea5b..eade6b5a1c 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/PlatformServiceProvider.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/PlatformServiceProvider.cs @@ -15,8 +15,6 @@ namespace Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter; /// internal sealed class PlatformServiceProvider : IPlatformServiceProvider { - private static readonly Action CancelDelegate = static state => ((TestContextImplementation)state!).Context.CancellationTokenSource.Cancel(); - /// /// Initializes a new instance of the class - a singleton. /// @@ -210,8 +208,7 @@ public ITestSourceHost CreateTestSourceHost( /// public ITestContext GetTestContext(ITestMethod testMethod, StringWriter writer, IDictionary properties, IMessageLogger messageLogger, UTF.UnitTestOutcome outcome) { - var testContextImplementation = new TestContextImplementation(testMethod, writer, properties, messageLogger); - TestRunCancellationToken?.Register(CancelDelegate, testContextImplementation); + var testContextImplementation = new TestContextImplementation(testMethod, writer, properties, messageLogger, TestRunCancellationToken); testContextImplementation.SetOutcome(outcome); return testContextImplementation; } diff --git a/src/Adapter/MSTestAdapter.PlatformServices/PublicAPI/PublicAPI.Unshipped.txt b/src/Adapter/MSTestAdapter.PlatformServices/PublicAPI/PublicAPI.Unshipped.txt index 7dc5c58110..043a57fc4f 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/PublicAPI/PublicAPI.Unshipped.txt +++ b/src/Adapter/MSTestAdapter.PlatformServices/PublicAPI/PublicAPI.Unshipped.txt @@ -1 +1,3 @@ #nullable enable +Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.TestContextImplementation.Dispose() -> void +virtual Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.TestContextImplementation.Dispose(bool disposing) -> void diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Services/TestContextImplementation.cs b/src/Adapter/MSTestAdapter.PlatformServices/Services/TestContextImplementation.cs index 46ceff8d42..23dc365800 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Services/TestContextImplementation.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Services/TestContextImplementation.cs @@ -6,6 +6,7 @@ using System.Data.Common; #endif +using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter; using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Interface; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging; using Microsoft.VisualStudio.TestTools.UnitTesting; @@ -24,7 +25,7 @@ namespace Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; #else [Obsolete(FrameworkConstants.PublicTypeObsoleteMessage)] #endif -public class TestContextImplementation : TestContext, ITestContext +public class TestContextImplementation : TestContext, ITestContext, IDisposable { /// /// List of result files associated with the test. @@ -42,12 +43,15 @@ public class TestContextImplementation : TestContext, ITestContext /// private readonly Dictionary _properties; private readonly IMessageLogger? _messageLogger; + private readonly CancellationTokenRegistration? _cancellationTokenRegistration; /// /// Specifies whether the writer is disposed or not. /// private bool _stringWriterDisposed; + private bool _isDisposed; + /// /// Unit test outcome. /// @@ -65,6 +69,8 @@ public class TestContextImplementation : TestContext, ITestContext private DataRow? _dataRow; #endif + private static readonly Action CancelDelegate = static state => ((TestContextImplementation)state!).Context.CancellationTokenSource.Cancel(); + /// /// Initializes a new instance of the class. /// @@ -72,9 +78,13 @@ public class TestContextImplementation : TestContext, ITestContext /// The writer where diagnostic messages are written to. /// Properties/configuration passed in. /// The message logger to use. - internal TestContextImplementation(ITestMethod? testMethod, StringWriter stringWriter, IDictionary properties, IMessageLogger messageLogger) + /// The global test run cancellation token. + internal TestContextImplementation(ITestMethod? testMethod, StringWriter stringWriter, IDictionary properties, IMessageLogger messageLogger, TestRunCancellationToken? testRunCancellationToken) : this(testMethod, stringWriter, properties) - => _messageLogger = messageLogger; + { + _messageLogger = messageLogger; + _cancellationTokenRegistration = testRunCancellationToken?.Register(CancelDelegate, this); + } /// /// Initializes a new instance of the class. @@ -370,4 +380,28 @@ public void SetDisplayName(string? displayName) public override void DisplayMessage(MessageLevel messageLevel, string message) => _messageLogger?.SendMessage(messageLevel.ToTestMessageLevel(), message); #endregion + + /// + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } + + /// + /// The dispose pattern. + /// + /// Whether to dispose managed state. + protected virtual void Dispose(bool disposing) + { + if (!_isDisposed) + { + _isDisposed = true; + + if (disposing) + { + _cancellationTokenRegistration?.Dispose(); + } + } + } } diff --git a/src/TestFramework/TestFramework.Extensions/TestContext.cs b/src/TestFramework/TestFramework.Extensions/TestContext.cs index ccbb8a68ea..ce78b1a0c1 100644 --- a/src/TestFramework/TestFramework.Extensions/TestContext.cs +++ b/src/TestFramework/TestFramework.Extensions/TestContext.cs @@ -48,6 +48,7 @@ public abstract class TestContext /// /// Gets or sets the cancellation token source. This token source is canceled when test times out. Also when explicitly canceled the test will be aborted. /// + // Disposing isn't important per https://github.com/dotnet/runtime/issues/29970#issuecomment-717840778 public virtual CancellationTokenSource CancellationTokenSource { get; protected internal set; } = new(); /// diff --git a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/LeakTests.cs b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/LeakTests.cs new file mode 100644 index 0000000000..fff4190e48 --- /dev/null +++ b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/LeakTests.cs @@ -0,0 +1,133 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using Microsoft.Testing.Platform.Acceptance.IntegrationTests; +using Microsoft.Testing.Platform.Acceptance.IntegrationTests.Helpers; + +namespace MSTest.Acceptance.IntegrationTests; + +[TestClass] +public sealed class LeakTests : AcceptanceTestBase +{ + [TestMethod] + [DynamicData(nameof(TargetFrameworks.AllForDynamicData), typeof(TargetFrameworks))] + public async Task TestContextInstancesShouldNotLeak(string tfm) + { + var testHost = TestHost.LocateFrom(AssetFixture.ProjectPath, TestAssetFixture.ProjectName, tfm); + TestHostResult testHostResult = await testHost.ExecuteAsync(); + + testHostResult.AssertExitCodeIs(0); + testHostResult.AssertOutputContainsSummary(failed: 0, passed: 100, skipped: 0); + } + + public sealed class TestAssetFixture() : TestAssetFixtureBase(AcceptanceFixture.NuGetGlobalPackagesFolder) + { + public const string ProjectName = "LeakTests"; + + public string ProjectPath => GetAssetPath(ProjectName); + + public override IEnumerable<(string ID, string Name, string Code)> GetAssetsToGenerate() + { + yield return (ProjectName, ProjectName, + SourceCode + .PatchTargetFrameworks(TargetFrameworks.All) + .PatchCodeWithReplace("$MSTestVersion$", MSTestVersion)); + } + + private const string SourceCode = """ +#file LeakTests.csproj + + + + Exe + true + $TargetFrameworks$ + preview + + + true + + + + + + + + +#file UnitTest1.cs +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using Microsoft.VisualStudio.TestTools.UnitTesting; + + +[TestClass] +public class TestClass +{ + private static ConcurrentBag> _testContexts = new(); + + [AssemblyInitialize] + public static void AssemblyInitialize(TestContext context) + => _testContexts.Add(new WeakReference(context)); + + [ClassInitialize] + public static void ClassInitialize(TestContext context) + => _testContexts.Add(new WeakReference(context)); + + public TestContext TestContext { get; set; } + + [TestMethod] + [DynamicData(nameof(Data))] + public void Test3(int a) + => _testContexts.Add(new WeakReference(TestContext)); + + [ClassCleanup] + public static void ClassCleanup(TestContext testContext) + => _testContexts.Add(new WeakReference(testContext)); + + [AssemblyCleanup] + public static void AssemblyCleanup() + { + for (int i = 0; i < 3; i++) + { + GC.Collect(); + GC.WaitForPendingFinalizers(); + } + + // Assembly init, class init, 100 tests, and class cleanup. (total 103). + Assert.AreEqual(103, _testContexts.Count); + + var alive = 0; + foreach (var weakReference in _testContexts) + { + if (weakReference.TryGetTarget(out _)) + { + alive++; + } + } + + // AssemblyCleanup is executed along with the last test. + // So, we are still holding 2 references to the TestContext. The one for the execution of last test, as well as the one for ClassCleanup. + // Holding into these two references is okay. + Assert.AreEqual(2, alive); + } + + public static IEnumerable Data + { + get + { + for (int i = 0; i < 100; i++) + { + yield return i; + } + } + } +} + +"""; + } +} diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/TestContextImplementationTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/TestContextImplementationTests.cs index fdcfe307d2..4e74bc80f3 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/TestContextImplementationTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/TestContextImplementationTests.cs @@ -398,7 +398,7 @@ public void DisplayMessageShouldForwardToIMessageLogger() messageLoggerMock .Setup(l => l.SendMessage(It.IsAny(), It.IsAny())); - _testContextImplementation = new TestContextImplementation(_testMethod.Object, new ThreadSafeStringWriter(null!, "test"), _properties, messageLoggerMock.Object); + _testContextImplementation = new TestContextImplementation(_testMethod.Object, new ThreadSafeStringWriter(null!, "test"), _properties, messageLoggerMock.Object, testRunCancellationToken: null); _testContextImplementation.DisplayMessage(MessageLevel.Informational, "InfoMessage"); _testContextImplementation.DisplayMessage(MessageLevel.Warning, "WarningMessage"); _testContextImplementation.DisplayMessage(MessageLevel.Error, "ErrorMessage"); diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/TestableImplementations/TestablePlatformServiceProvider.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/TestableImplementations/TestablePlatformServiceProvider.cs index 42019d64fc..375a4d7fc2 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/TestableImplementations/TestablePlatformServiceProvider.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/TestableImplementations/TestablePlatformServiceProvider.cs @@ -71,7 +71,7 @@ public IReflectionOperations2 ReflectionOperations public ITestContext GetTestContext(ITestMethod testMethod, StringWriter writer, IDictionary properties, IMessageLogger messageLogger, UnitTestOutcome outcome) { - var testContextImpl = new TestContextImplementation(testMethod, writer, properties, messageLogger); + var testContextImpl = new TestContextImplementation(testMethod, writer, properties, messageLogger, testRunCancellationToken: null); testContextImpl.SetOutcome(outcome); return testContextImpl; } From b7c0d0a3b20009dbfd0a998e3e05084a81125543 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Thu, 12 Jun 2025 18:44:40 +0200 Subject: [PATCH 084/541] Error if framework/adapter versions are mismatched at runtime (#5703) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Jakub Jareš --- .../VSTestAdapter/MSTestExecutor.cs | 14 ++++++++++++++ .../Resources/Resource.Designer.cs | 9 +++++++++ .../Resources/Resource.resx | 3 +++ .../Resources/xlf/Resource.cs.xlf | 5 +++++ .../Resources/xlf/Resource.de.xlf | 5 +++++ .../Resources/xlf/Resource.es.xlf | 5 +++++ .../Resources/xlf/Resource.fr.xlf | 5 +++++ .../Resources/xlf/Resource.it.xlf | 5 +++++ .../Resources/xlf/Resource.ja.xlf | 5 +++++ .../Resources/xlf/Resource.ko.xlf | 5 +++++ .../Resources/xlf/Resource.pl.xlf | 5 +++++ .../Resources/xlf/Resource.pt-BR.xlf | 5 +++++ .../Resources/xlf/Resource.ru.xlf | 5 +++++ .../Resources/xlf/Resource.tr.xlf | 5 +++++ .../Resources/xlf/Resource.zh-Hans.xlf | 5 +++++ .../Resources/xlf/Resource.zh-Hant.xlf | 5 +++++ 16 files changed, 91 insertions(+) diff --git a/src/Adapter/MSTest.TestAdapter/VSTestAdapter/MSTestExecutor.cs b/src/Adapter/MSTest.TestAdapter/VSTestAdapter/MSTestExecutor.cs index 9bcc300321..82b316d549 100644 --- a/src/Adapter/MSTest.TestAdapter/VSTestAdapter/MSTestExecutor.cs +++ b/src/Adapter/MSTest.TestAdapter/VSTestAdapter/MSTestExecutor.cs @@ -49,6 +49,20 @@ internal MSTestExecutor(CancellationToken cancellationToken) /// public TestExecutionManager TestExecutionManager { get; protected set; } +#pragma warning disable CA2255 // The 'ModuleInitializer' attribute should not be used in libraries + [ModuleInitializer] +#pragma warning restore CA2255 // The 'ModuleInitializer' attribute should not be used in libraries + internal static void EnsureAdapterAndFrameworkVersions() + { + string? adapterVersion = typeof(MSTestExecutor).Assembly.GetCustomAttribute()?.InformationalVersion; + string? frameworkVersion = typeof(TestMethodAttribute).Assembly.GetCustomAttribute()?.InformationalVersion; + if (adapterVersion is not null && frameworkVersion is not null + && adapterVersion != frameworkVersion) + { + throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, Resource.VersionMismatchBetweenAdapterAndFramework, adapterVersion, frameworkVersion)); + } + } + /// /// Runs the tests. /// diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/Resource.Designer.cs b/src/Adapter/MSTestAdapter.PlatformServices/Resources/Resource.Designer.cs index 7a588aa40b..b934d1b01d 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/Resource.Designer.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/Resource.Designer.cs @@ -1084,6 +1084,15 @@ internal static string UTF_FailedToGetExceptionMessage { } } + /// + /// Looks up a localized string similar to 'MSTest.TestAdapter' and 'MSTest.TestFramework' must have the same version. Found 'MSTest.TestAdapter' version '{0}' and 'MSTest.TestFramework' version '{1}'.. + /// + internal static string VersionMismatchBetweenAdapterAndFramework { + get { + return ResourceManager.GetString("VersionMismatchBetweenAdapterAndFramework", resourceCulture); + } + } + /// /// Looks up a localized string similar to Wrong number of objects for permutation. Should be greater than zero.. /// diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/Resource.resx b/src/Adapter/MSTestAdapter.PlatformServices/Resources/Resource.resx index fa7e9078aa..473060ad60 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/Resource.resx +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/Resource.resx @@ -484,4 +484,7 @@ Error: {1} Runsettings entry '<ExecutionApartmentState>STA</ExecutionApartmentState>' is not supported on non-Windows OSes. + + 'MSTest.TestAdapter' and 'MSTest.TestFramework' must have the same version. Found 'MSTest.TestAdapter' version '{0}' and 'MSTest.TestFramework' version '{1}'. Please make sure that the versions of 'MSTest.TestAdapter' and 'MSTest.TestFramework' NuGet packages have the same version. + \ No newline at end of file diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.cs.xlf b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.cs.xlf index 19a49ea75c..c9fc0910c0 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.cs.xlf +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.cs.xlf @@ -587,6 +587,11 @@ Error: {1} (Failed to get the message for an exception of type {0} due to an exception.) + + 'MSTest.TestAdapter' and 'MSTest.TestFramework' must have the same version. Found 'MSTest.TestAdapter' version '{0}' and 'MSTest.TestFramework' version '{1}'. Please make sure that the versions of 'MSTest.TestAdapter' and 'MSTest.TestFramework' NuGet packages have the same version. + 'MSTest.TestAdapter' and 'MSTest.TestFramework' must have the same version. Found 'MSTest.TestAdapter' version '{0}' and 'MSTest.TestFramework' version '{1}'. Please make sure that the versions of 'MSTest.TestAdapter' and 'MSTest.TestFramework' NuGet packages have the same version. + + Wrong number of objects for permutation. Should be greater than zero. Chybný počet objektů pro permutaci. Počet musí být větší než nula. diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.de.xlf b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.de.xlf index 620d697dde..283233a4b5 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.de.xlf +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.de.xlf @@ -587,6 +587,11 @@ Error: {1} (Failed to get the message for an exception of type {0} due to an exception.) + + 'MSTest.TestAdapter' and 'MSTest.TestFramework' must have the same version. Found 'MSTest.TestAdapter' version '{0}' and 'MSTest.TestFramework' version '{1}'. Please make sure that the versions of 'MSTest.TestAdapter' and 'MSTest.TestFramework' NuGet packages have the same version. + 'MSTest.TestAdapter' and 'MSTest.TestFramework' must have the same version. Found 'MSTest.TestAdapter' version '{0}' and 'MSTest.TestFramework' version '{1}'. Please make sure that the versions of 'MSTest.TestAdapter' and 'MSTest.TestFramework' NuGet packages have the same version. + + Wrong number of objects for permutation. Should be greater than zero. Falsche Anzahl von Objekten für die Permutation. Die Anzahl muss größer als NULL sein. diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.es.xlf b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.es.xlf index ebee59c379..765120c3b9 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.es.xlf +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.es.xlf @@ -587,6 +587,11 @@ Error: {1} (Failed to get the message for an exception of type {0} due to an exception.) + + 'MSTest.TestAdapter' and 'MSTest.TestFramework' must have the same version. Found 'MSTest.TestAdapter' version '{0}' and 'MSTest.TestFramework' version '{1}'. Please make sure that the versions of 'MSTest.TestAdapter' and 'MSTest.TestFramework' NuGet packages have the same version. + 'MSTest.TestAdapter' and 'MSTest.TestFramework' must have the same version. Found 'MSTest.TestAdapter' version '{0}' and 'MSTest.TestFramework' version '{1}'. Please make sure that the versions of 'MSTest.TestAdapter' and 'MSTest.TestFramework' NuGet packages have the same version. + + Wrong number of objects for permutation. Should be greater than zero. Número incorrecto de objetos para permutación. Debe ser una cantidad mayor que cero. diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.fr.xlf b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.fr.xlf index 8782a77f73..d8ac2d32aa 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.fr.xlf +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.fr.xlf @@ -587,6 +587,11 @@ Error: {1} (Failed to get the message for an exception of type {0} due to an exception.) + + 'MSTest.TestAdapter' and 'MSTest.TestFramework' must have the same version. Found 'MSTest.TestAdapter' version '{0}' and 'MSTest.TestFramework' version '{1}'. Please make sure that the versions of 'MSTest.TestAdapter' and 'MSTest.TestFramework' NuGet packages have the same version. + 'MSTest.TestAdapter' and 'MSTest.TestFramework' must have the same version. Found 'MSTest.TestAdapter' version '{0}' and 'MSTest.TestFramework' version '{1}'. Please make sure that the versions of 'MSTest.TestAdapter' and 'MSTest.TestFramework' NuGet packages have the same version. + + Wrong number of objects for permutation. Should be greater than zero. Nombre d'objets erroné pour la permutation. Il doit être supérieur à zéro. diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.it.xlf b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.it.xlf index 04e9f2a74c..891ff8ed7d 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.it.xlf +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.it.xlf @@ -587,6 +587,11 @@ Error: {1} (Failed to get the message for an exception of type {0} due to an exception.) + + 'MSTest.TestAdapter' and 'MSTest.TestFramework' must have the same version. Found 'MSTest.TestAdapter' version '{0}' and 'MSTest.TestFramework' version '{1}'. Please make sure that the versions of 'MSTest.TestAdapter' and 'MSTest.TestFramework' NuGet packages have the same version. + 'MSTest.TestAdapter' and 'MSTest.TestFramework' must have the same version. Found 'MSTest.TestAdapter' version '{0}' and 'MSTest.TestFramework' version '{1}'. Please make sure that the versions of 'MSTest.TestAdapter' and 'MSTest.TestFramework' NuGet packages have the same version. + + Wrong number of objects for permutation. Should be greater than zero. Il numero di oggetti non è corretto per la permutazione. Deve essere maggiore di zero. diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.ja.xlf b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.ja.xlf index f77c60ebb2..4172147805 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.ja.xlf +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.ja.xlf @@ -587,6 +587,11 @@ Error: {1} (Failed to get the message for an exception of type {0} due to an exception.) + + 'MSTest.TestAdapter' and 'MSTest.TestFramework' must have the same version. Found 'MSTest.TestAdapter' version '{0}' and 'MSTest.TestFramework' version '{1}'. Please make sure that the versions of 'MSTest.TestAdapter' and 'MSTest.TestFramework' NuGet packages have the same version. + 'MSTest.TestAdapter' and 'MSTest.TestFramework' must have the same version. Found 'MSTest.TestAdapter' version '{0}' and 'MSTest.TestFramework' version '{1}'. Please make sure that the versions of 'MSTest.TestAdapter' and 'MSTest.TestFramework' NuGet packages have the same version. + + Wrong number of objects for permutation. Should be greater than zero. 順列のオブジェクト数が正しくありません。ゼロより大きくなければなりません。 diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.ko.xlf b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.ko.xlf index f5f89ac3d6..fece671f18 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.ko.xlf +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.ko.xlf @@ -587,6 +587,11 @@ Error: {1} (Failed to get the message for an exception of type {0} due to an exception.) + + 'MSTest.TestAdapter' and 'MSTest.TestFramework' must have the same version. Found 'MSTest.TestAdapter' version '{0}' and 'MSTest.TestFramework' version '{1}'. Please make sure that the versions of 'MSTest.TestAdapter' and 'MSTest.TestFramework' NuGet packages have the same version. + 'MSTest.TestAdapter' and 'MSTest.TestFramework' must have the same version. Found 'MSTest.TestAdapter' version '{0}' and 'MSTest.TestFramework' version '{1}'. Please make sure that the versions of 'MSTest.TestAdapter' and 'MSTest.TestFramework' NuGet packages have the same version. + + Wrong number of objects for permutation. Should be greater than zero. 순열의 개체 수가 잘못되었습니다. 개체 수는 0보다 커야 합니다. diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.pl.xlf b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.pl.xlf index 2b3586b4f4..832339a682 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.pl.xlf +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.pl.xlf @@ -587,6 +587,11 @@ Error: {1} (Failed to get the message for an exception of type {0} due to an exception.) + + 'MSTest.TestAdapter' and 'MSTest.TestFramework' must have the same version. Found 'MSTest.TestAdapter' version '{0}' and 'MSTest.TestFramework' version '{1}'. Please make sure that the versions of 'MSTest.TestAdapter' and 'MSTest.TestFramework' NuGet packages have the same version. + 'MSTest.TestAdapter' and 'MSTest.TestFramework' must have the same version. Found 'MSTest.TestAdapter' version '{0}' and 'MSTest.TestFramework' version '{1}'. Please make sure that the versions of 'MSTest.TestAdapter' and 'MSTest.TestFramework' NuGet packages have the same version. + + Wrong number of objects for permutation. Should be greater than zero. Nieprawidłowa liczba obiektów permutacji. Ta liczba powinna być większa od zera. diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.pt-BR.xlf b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.pt-BR.xlf index e3ccfc9b90..05a30643ab 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.pt-BR.xlf +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.pt-BR.xlf @@ -587,6 +587,11 @@ Error: {1} (Failed to get the message for an exception of type {0} due to an exception.) + + 'MSTest.TestAdapter' and 'MSTest.TestFramework' must have the same version. Found 'MSTest.TestAdapter' version '{0}' and 'MSTest.TestFramework' version '{1}'. Please make sure that the versions of 'MSTest.TestAdapter' and 'MSTest.TestFramework' NuGet packages have the same version. + 'MSTest.TestAdapter' and 'MSTest.TestFramework' must have the same version. Found 'MSTest.TestAdapter' version '{0}' and 'MSTest.TestFramework' version '{1}'. Please make sure that the versions of 'MSTest.TestAdapter' and 'MSTest.TestFramework' NuGet packages have the same version. + + Wrong number of objects for permutation. Should be greater than zero. Número incorreto de objetos para permutação. Deve ser maior que zero. diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.ru.xlf b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.ru.xlf index bb50ff73ac..e587b45d5b 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.ru.xlf +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.ru.xlf @@ -587,6 +587,11 @@ Error: {1} (Failed to get the message for an exception of type {0} due to an exception.) + + 'MSTest.TestAdapter' and 'MSTest.TestFramework' must have the same version. Found 'MSTest.TestAdapter' version '{0}' and 'MSTest.TestFramework' version '{1}'. Please make sure that the versions of 'MSTest.TestAdapter' and 'MSTest.TestFramework' NuGet packages have the same version. + 'MSTest.TestAdapter' and 'MSTest.TestFramework' must have the same version. Found 'MSTest.TestAdapter' version '{0}' and 'MSTest.TestFramework' version '{1}'. Please make sure that the versions of 'MSTest.TestAdapter' and 'MSTest.TestFramework' NuGet packages have the same version. + + Wrong number of objects for permutation. Should be greater than zero. Неправильное число объектов для перестановки. Оно должно быть больше нуля. diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.tr.xlf b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.tr.xlf index e63490a10a..b7c43c2674 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.tr.xlf +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.tr.xlf @@ -587,6 +587,11 @@ Error: {1} (Failed to get the message for an exception of type {0} due to an exception.) + + 'MSTest.TestAdapter' and 'MSTest.TestFramework' must have the same version. Found 'MSTest.TestAdapter' version '{0}' and 'MSTest.TestFramework' version '{1}'. Please make sure that the versions of 'MSTest.TestAdapter' and 'MSTest.TestFramework' NuGet packages have the same version. + 'MSTest.TestAdapter' and 'MSTest.TestFramework' must have the same version. Found 'MSTest.TestAdapter' version '{0}' and 'MSTest.TestFramework' version '{1}'. Please make sure that the versions of 'MSTest.TestAdapter' and 'MSTest.TestFramework' NuGet packages have the same version. + + Wrong number of objects for permutation. Should be greater than zero. Permütasyon için nesne sayısı yanlış. Değer, sıfırdan büyük olmalıdır. diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.zh-Hans.xlf b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.zh-Hans.xlf index c81aa4644c..9538daa867 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.zh-Hans.xlf +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.zh-Hans.xlf @@ -587,6 +587,11 @@ Error: {1} (Failed to get the message for an exception of type {0} due to an exception.) + + 'MSTest.TestAdapter' and 'MSTest.TestFramework' must have the same version. Found 'MSTest.TestAdapter' version '{0}' and 'MSTest.TestFramework' version '{1}'. Please make sure that the versions of 'MSTest.TestAdapter' and 'MSTest.TestFramework' NuGet packages have the same version. + 'MSTest.TestAdapter' and 'MSTest.TestFramework' must have the same version. Found 'MSTest.TestAdapter' version '{0}' and 'MSTest.TestFramework' version '{1}'. Please make sure that the versions of 'MSTest.TestAdapter' and 'MSTest.TestFramework' NuGet packages have the same version. + + Wrong number of objects for permutation. Should be greater than zero. 排列的对象数不正确。应大于零。 diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.zh-Hant.xlf b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.zh-Hant.xlf index 70e0deb2f4..2ff7a526fb 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.zh-Hant.xlf +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.zh-Hant.xlf @@ -587,6 +587,11 @@ Error: {1} (Failed to get the message for an exception of type {0} due to an exception.) + + 'MSTest.TestAdapter' and 'MSTest.TestFramework' must have the same version. Found 'MSTest.TestAdapter' version '{0}' and 'MSTest.TestFramework' version '{1}'. Please make sure that the versions of 'MSTest.TestAdapter' and 'MSTest.TestFramework' NuGet packages have the same version. + 'MSTest.TestAdapter' and 'MSTest.TestFramework' must have the same version. Found 'MSTest.TestAdapter' version '{0}' and 'MSTest.TestFramework' version '{1}'. Please make sure that the versions of 'MSTest.TestAdapter' and 'MSTest.TestFramework' NuGet packages have the same version. + + Wrong number of objects for permutation. Should be greater than zero. 排列的物件數目錯誤。應大於零。 From 6db49e7b670782671d0ac2e9bf14dc8381d77488 Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Fri, 13 Jun 2025 06:30:49 +0000 Subject: [PATCH 085/541] [main] Update dependencies from devdiv/DevDiv/vs-code-coverage, dotnet/arcade (#5763) [main] Update dependencies from devdiv/DevDiv/vs-code-coverage, dotnet/arcade --- eng/Version.Details.xml | 16 ++++++++-------- eng/Versions.props | 4 ++-- eng/common/dotnet.cmd | 7 +++++++ eng/common/dotnet.ps1 | 11 +++++++++++ eng/common/dotnet.sh | 26 ++++++++++++++++++++++++++ eng/common/templates/vmr-build-pr.yml | 11 +---------- eng/common/tools.ps1 | 23 ++++------------------- eng/common/tools.sh | 22 ++++------------------ global.json | 7 +++++-- 9 files changed, 68 insertions(+), 59 deletions(-) create mode 100644 eng/common/dotnet.cmd create mode 100644 eng/common/dotnet.ps1 create mode 100644 eng/common/dotnet.sh diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index 45d397219b..e1d5e59fa5 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -1,21 +1,21 @@ - + https://github.com/dotnet/arcade - 5ad76e326524772ed87487009987bf88264f0da2 + 186172916558a2e41c87c1ca4e02850e9bba5f53 - + https://github.com/dotnet/arcade - 5ad76e326524772ed87487009987bf88264f0da2 + 186172916558a2e41c87c1ca4e02850e9bba5f53 - + https://github.com/dotnet/arcade - 5ad76e326524772ed87487009987bf88264f0da2 + 186172916558a2e41c87c1ca4e02850e9bba5f53 - + https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage - 0df73e9ae14ec617262ca3f5aeec6c232a33e230 + 899af124a773e3eed658a50d5d2171a4213cb8f8 diff --git a/eng/Versions.props b/eng/Versions.props index 45f7512972..a333943c9c 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -7,7 +7,7 @@ preview - 10.0.0-beta.25311.1 - 17.15.0-preview.25311.1 + 10.0.0-beta.25312.3 + 17.15.0-preview.25312.3 diff --git a/eng/common/dotnet.cmd b/eng/common/dotnet.cmd new file mode 100644 index 0000000000..527fa4bb38 --- /dev/null +++ b/eng/common/dotnet.cmd @@ -0,0 +1,7 @@ +@echo off + +:: This script is used to install the .NET SDK. +:: It will also invoke the SDK with any provided arguments. + +powershell -ExecutionPolicy ByPass -NoProfile -command "& """%~dp0dotnet.ps1""" %*" +exit /b %ErrorLevel% diff --git a/eng/common/dotnet.ps1 b/eng/common/dotnet.ps1 new file mode 100644 index 0000000000..45e5676c9e --- /dev/null +++ b/eng/common/dotnet.ps1 @@ -0,0 +1,11 @@ +# This script is used to install the .NET SDK. +# It will also invoke the SDK with any provided arguments. + +. $PSScriptRoot\tools.ps1 +$dotnetRoot = InitializeDotNetCli -install:$true + +# Invoke acquired SDK with args if they are provided +if ($args.count -gt 0) { + $env:DOTNET_NOLOGO=1 + & "$dotnetRoot\dotnet.exe" $args +} diff --git a/eng/common/dotnet.sh b/eng/common/dotnet.sh new file mode 100644 index 0000000000..2ef6823567 --- /dev/null +++ b/eng/common/dotnet.sh @@ -0,0 +1,26 @@ +#!/usr/bin/env bash + +# This script is used to install the .NET SDK. +# It will also invoke the SDK with any provided arguments. + +source="${BASH_SOURCE[0]}" +# resolve $SOURCE until the file is no longer a symlink +while [[ -h $source ]]; do + scriptroot="$( cd -P "$( dirname "$source" )" && pwd )" + source="$(readlink "$source")" + + # if $source was a relative symlink, we need to resolve it relative to the path where the + # symlink file was located + [[ $source != /* ]] && source="$scriptroot/$source" +done +scriptroot="$( cd -P "$( dirname "$source" )" && pwd )" + +source $scriptroot/tools.sh +InitializeDotNetCli true # install + +# Invoke acquired SDK with args if they are provided +if [[ $# > 0 ]]; then + __dotnetDir=${_InitializeDotNetCli} + dotnetPath=${__dotnetDir}/dotnet + ${dotnetPath} "$@" +fi diff --git a/eng/common/templates/vmr-build-pr.yml b/eng/common/templates/vmr-build-pr.yml index 670cf32c3b..c1b6fec458 100644 --- a/eng/common/templates/vmr-build-pr.yml +++ b/eng/common/templates/vmr-build-pr.yml @@ -1,14 +1,5 @@ trigger: none -pr: - branches: - include: - - main - - release/* - paths: - exclude: - - documentation/* - - README.md - - CODEOWNERS +pr: none variables: - template: /eng/common/templates/variables/pool-providers.yml@self diff --git a/eng/common/tools.ps1 b/eng/common/tools.ps1 index c9e39595b5..40f0aa8612 100644 --- a/eng/common/tools.ps1 +++ b/eng/common/tools.ps1 @@ -765,28 +765,13 @@ function MSBuild() { $toolsetBuildProject = InitializeToolset $basePath = Split-Path -parent $toolsetBuildProject - $possiblePaths = @( - # new scripts need to work with old packages, so we need to look for the old names/versions - (Join-Path $basePath (Join-Path $buildTool.Framework 'Microsoft.DotNet.ArcadeLogging.dll')), - (Join-Path $basePath (Join-Path $buildTool.Framework 'Microsoft.DotNet.Arcade.Sdk.dll')), - - # This list doesn't need to be updated anymore and can eventually be removed. - (Join-Path $basePath (Join-Path net9.0 'Microsoft.DotNet.ArcadeLogging.dll')), - (Join-Path $basePath (Join-Path net9.0 'Microsoft.DotNet.Arcade.Sdk.dll')), - (Join-Path $basePath (Join-Path net8.0 'Microsoft.DotNet.ArcadeLogging.dll')), - (Join-Path $basePath (Join-Path net8.0 'Microsoft.DotNet.Arcade.Sdk.dll')) - ) - $selectedPath = $null - foreach ($path in $possiblePaths) { - if (Test-Path $path -PathType Leaf) { - $selectedPath = $path - break - } - } + $selectedPath = Join-Path $basePath (Join-Path $buildTool.Framework 'Microsoft.DotNet.ArcadeLogging.dll') + if (-not $selectedPath) { - Write-PipelineTelemetryError -Category 'Build' -Message 'Unable to find arcade sdk logger assembly.' + Write-PipelineTelemetryError -Category 'Build' -Message "Unable to find arcade sdk logger assembly: $selectedPath" ExitWithExitCode 1 } + $args += "/logger:$selectedPath" } diff --git a/eng/common/tools.sh b/eng/common/tools.sh index a7e8493151..3def02a638 100644 --- a/eng/common/tools.sh +++ b/eng/common/tools.sh @@ -447,27 +447,13 @@ function MSBuild { fi local toolset_dir="${_InitializeToolset%/*}" - # new scripts need to work with old packages, so we need to look for the old names/versions - local selectedPath= - local possiblePaths=() - possiblePaths+=( "$toolset_dir/net/Microsoft.DotNet.ArcadeLogging.dll" ) - possiblePaths+=( "$toolset_dir/net/Microsoft.DotNet.Arcade.Sdk.dll" ) - - # This list doesn't need to be updated anymore and can eventually be removed. - possiblePaths+=( "$toolset_dir/net9.0/Microsoft.DotNet.ArcadeLogging.dll" ) - possiblePaths+=( "$toolset_dir/net9.0/Microsoft.DotNet.Arcade.Sdk.dll" ) - possiblePaths+=( "$toolset_dir/net8.0/Microsoft.DotNet.ArcadeLogging.dll" ) - possiblePaths+=( "$toolset_dir/net8.0/Microsoft.DotNet.Arcade.Sdk.dll" ) - for path in "${possiblePaths[@]}"; do - if [[ -f $path ]]; then - selectedPath=$path - break - fi - done + local selectedPath="$toolset_dir/net/Microsoft.DotNet.ArcadeLogging.dll" + if [[ -z "$selectedPath" ]]; then - Write-PipelineTelemetryError -category 'Build' "Unable to find arcade sdk logger assembly." + Write-PipelineTelemetryError -category 'Build' "Unable to find arcade sdk logger assembly: $selectedPath" ExitWithExitCode 1 fi + args+=( "-logger:$selectedPath" ) fi diff --git a/global.json b/global.json index 7902c29958..da30ccee88 100644 --- a/global.json +++ b/global.json @@ -24,13 +24,16 @@ }, "sdk": { "version": "10.0.100-preview.6.25309.101", - "paths": [ ".dotnet", "$host$" ], + "paths": [ + ".dotnet", + "$host$" + ], "errorMessage": "The .NET SDK could not be found, please run ./build.cmd on Windows or ./build.sh on Linux and macOS.", "allowPrerelease": true, "rollForward": "latestFeature" }, "msbuild-sdks": { - "Microsoft.DotNet.Arcade.Sdk": "10.0.0-beta.25311.1", + "Microsoft.DotNet.Arcade.Sdk": "10.0.0-beta.25312.3", "MSBuild.Sdk.Extras": "3.0.44" } } From fc5d76296d2e70b921e902ede44d2514c53383cb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Jare=C5=A1?= Date: Fri, 13 Jun 2025 14:00:11 +0200 Subject: [PATCH 086/541] Revert "Exclude folders" (#5747) --- azure-pipelines.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/azure-pipelines.yml b/azure-pipelines.yml index 55d5446dd8..612e8fdd38 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -6,9 +6,9 @@ pr: - rel/* paths: exclude: - - .github/** - - .devcontainer/** - - docs/** + - .github/* + - .devcontainer/* + - docs/* - .markdownlint.json - .markdownlintignore - CODE_OF_CONDUCT.md From 5d134148621d9a46c73d16d3f26e9a84a6b0cdca Mon Sep 17 00:00:00 2001 From: dotnet bot Date: Fri, 13 Jun 2025 05:11:46 -0700 Subject: [PATCH 087/541] Localized file check-in by OneLocBuild Task: Build definition ID 1218: Build ID 2729568 --- .../Resources/xlf/Resource.cs.xlf | 170 ++++++++-------- .../Resources/xlf/Resource.de.xlf | 170 ++++++++-------- .../Resources/xlf/Resource.es.xlf | 186 ++++++++--------- .../Resources/xlf/Resource.fr.xlf | 162 +++++++-------- .../Resources/xlf/Resource.it.xlf | 170 ++++++++-------- .../Resources/xlf/Resource.ja.xlf | 170 ++++++++-------- .../Resources/xlf/Resource.ko.xlf | 170 ++++++++-------- .../Resources/xlf/Resource.pl.xlf | 168 ++++++++-------- .../Resources/xlf/Resource.pt-BR.xlf | 168 ++++++++-------- .../Resources/xlf/Resource.ru.xlf | 190 +++++++++--------- .../Resources/xlf/Resource.tr.xlf | 170 ++++++++-------- .../Resources/xlf/Resource.zh-Hans.xlf | 188 ++++++++--------- .../Resources/xlf/Resource.zh-Hant.xlf | 170 ++++++++-------- .../xlf/CodeFixResources.cs.xlf | 2 +- .../xlf/CodeFixResources.ja.xlf | 2 +- .../xlf/CodeFixResources.pt-BR.xlf | 2 +- .../xlf/CodeFixResources.zh-Hans.xlf | 2 +- .../MSTest.Analyzers/xlf/Resources.cs.xlf | 6 +- .../MSTest.Analyzers/xlf/Resources.pt-BR.xlf | 6 +- .../MSTest.Analyzers/xlf/Resources.ru.xlf | 6 +- .../xlf/Resources.zh-Hans.xlf | 6 +- 21 files changed, 1142 insertions(+), 1142 deletions(-) diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.cs.xlf b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.cs.xlf index c9fc0910c0..a68b985ad9 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.cs.xlf +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.cs.xlf @@ -4,52 +4,52 @@ Assembly cleanup method '{0}.{1}' timed out after {2}ms - Assembly cleanup method '{0}.{1}' timed out after {2}ms + Po {2} ms vypršel časový limit metody čištění sestavení {0}.{1}. Assembly cleanup method '{0}.{1}' was canceled - Assembly cleanup method '{0}.{1}' was canceled + Metoda čištění sestavení {0}.{1} byla zrušena. Assembly initialize method '{0}.{1}' timed out after {2}ms - Assembly initialize method '{0}.{1}' timed out after {2}ms + Po {2} ms vypršel časový limit metody inicializace sestavení {0}.{1}. Assembly initialize method '{0}.{1}' was canceled - Assembly initialize method '{0}.{1}' was canceled + Metoda inicializace sestavení {0}.{1} byla zrušena. MSTestAdapterV2 - MSTestAdapterV2 + MSTestAdapterV2 Exception occurred while enumerating IDataSource attribute on "{0}.{1}": {2} - Exception occurred while enumerating IDataSource attribute on "{0}.{1}": {2} + Při vytváření výčtu atributu IDataSource došlo k výjimce. „{0}.{1}“: {2} {0}: TypeName with namespace, {1}: Method name, {2}: Exception details Exception occurred while expanding IDataSource rows from attribute on "{0}.{1}": {2} - Exception occurred while expanding IDataSource rows from attribute on "{0}.{1}": {2} + Došlo k výjimce při rozbalování řádků IDataSource z atributu na „{0}.{1}“: {2} {0}: TypeName with namespace, {1}: Method name, {2}: CannotExpandIDataSourceAttribute_DuplicateDisplayName or CannotExpandIDataSourceAttribute_CannotSerialize Data on index {0} for "{1}" cannot be serialized. All data provided through "IDataSource" should be serializable. If you need to test non-serializable data sources, please make sure you add "TestDataSourceDiscovery" attribute on your test assembly and set the discovery option to "DuringExecution". - Data on index {0} for "{1}" cannot be serialized. All data provided through "IDataSource" should be serializable. If you need to test non-serializable data sources, please make sure you add "TestDataSourceDiscovery" attribute on your test assembly and set the discovery option to "DuringExecution". + Data v {0} indexu pro „{1}“ nelze serializovat. Všechna data poskytnutá prostřednictvím „IDataSource“ by měla být serializovatelná. Pokud potřebujete testovat neserializovatelné zdroje dat, nezapomeňte do testovacího sestavení přidat atribut TestDataSourceDiscovery a nastavit možnost zjišťování na „DuringExecution“. {0}: Zero based index if an element inside of an array, {1}: Test name Display name "{2}" on indexes {0} and {1} are duplicate. Display names should be unique. - Display name "{2}" on indexes {0} and {1} are duplicate. Display names should be unique. + Zobrazovaný název „{2}“ u indexů {0} a {1} je duplicitní. Zobrazované názvy by měly být jedinečné. {0}, {1}: Zero based index if an element inside of an array {2}: Test display name. @@ -69,27 +69,27 @@ but received {4} argument(s), with types '{5}'. Cannot run test method '{0}.{1}': Method has parameters, but does not define any test source. Use '[DataRow]', '[DynamicData]', or a custom 'ITestDataSource' data source to provide test data. - Cannot run test method '{0}.{1}': Method has parameters, but does not define any test source. Use '[DataRow]', '[DynamicData]', or a custom 'ITestDataSource' data source to provide test data. + Nelze spustit testovací metodu {0}.{1}: Metoda má parametry, ale nedefinuje žádný zdroj testu. K poskytování testovacích dat použijte zdroj dat [DataRow] nebo [DynamicData], případně vlastní zdroj dat ITestDataSource. Class cleanup method '{0}.{1}' timed out after {2}ms - Class cleanup method '{0}.{1}' timed out after {2}ms + Po {2} ms vypršel časový limit metody čištění třídy {0}.{1}. Class cleanup method '{0}.{1}' was canceled - Class cleanup method '{0}.{1}' was canceled + Metoda čištění třídy {0}.{1} byla zrušena. Class initialize method '{0}.{1}' timed out after {2}ms - Class initialize method '{0}.{1}' timed out after {2}ms + Po {2} ms vypršel časový limit metody inicializace třídy {0}.{1}. Class initialize method '{0}.{1}' was canceled - Class initialize method '{0}.{1}' was canceled + Metoda inicializace třídy {0}.{1} byla zrušena. @@ -99,17 +99,17 @@ but received {4} argument(s), with types '{5}'. MSTestAdapter failed to discover tests in class '{0}' of assembly '{1}' because {2}. - MSTestAdapter failed to discover tests in class '{0}' of assembly '{1}' because {2}. + MSTestAdapter nezjistil v třídě {0} sestavení {1} žádný test, protože: {2}. {0} (Data Row {1}) - {0} (Data Row {1}) + {0} (datový řádek {1}) Debug Trace: - Debug Trace: + Trasování ladění: @@ -179,28 +179,28 @@ but received {4} argument(s), with types '{5}'. [MSTest][Discovery][{0}] {1} - [MSTest][Discovery][{0}] {1} + [MSTest][Discovery][{0}] {1} Both '.runsettings' and '.testconfig.json' files have been detected. Please select only one of these test configuration files. - Both '.runsettings' and '.testconfig.json' files have been detected. Please select only one of these test configuration files. + Byly zjištěny soubory .runsettings i .testconfig.json. Vyberte prosím jenom jeden z těchto souborů konfigurace testu. {0}: {1} - {0}: {1} + {0}: {1} "{0}": (Failed to get exception description due to an exception of type "{1}". - "{0}": (Failed to get exception description due to an exception of type "{1}". + „{0}“: (Nepodařilo se získat popis výjimky z důvodu výjimky typu „{1}“. {0}: Type of the original exception that we're trying to get the description of. {1}: Thrown exception Exceptions thrown: - Exceptions thrown: + Vyvolané výjimky: This is usually precedes by TestAssembly_AssemblyDiscoveryFailure message, and preceded by list of exceptions thrown in a test discovery session. @@ -215,7 +215,7 @@ but received {4} argument(s), with types '{5}'. Getting custom attributes for type {0} threw exception (will ignore and use the reflection way): {1} - Getting custom attributes for type {0} threw exception (will ignore and use the reflection way): {1} + Získání vlastních atributů pro typ {0} vyvolalo výjimku (bude ignorovat a používat způsob reflexe): {1} {0}: Attribute full type name. {1}: Exception description @@ -236,22 +236,22 @@ but received {4} argument(s), with types '{5}'. Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. - Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. + Pro classCleanupLifecycle byla zadána neplatná hodnota {0}. Podporované obory jsou {1}. 'ClassCleanupLifecycle' is a setting name that shouldn't be localized. Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. - Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. + Pro Obor je zadaná neplatná hodnota {0}. Podporované obory jsou {1}. 'Scope' is a setting name that shouldn't be localized. Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. - Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. + Pro Pracovní procesy je zadaná neplatná hodnota {0}. Hodnota by měla být nezáporné celé číslo. `Workers` is a setting name that shouldn't be localized. Invalid settings '{0}'. Unexpected XmlAttribute: '{1}'. - Invalid settings '{0}'. Unexpected XmlAttribute: '{1}'. + Neplatné nastavení {0}. Neočekávaný XmlAttribute: {1}. @@ -261,7 +261,7 @@ but received {4} argument(s), with types '{5}'. Invalid settings '{0}'. Unexpected XmlElement: '{1}'. - Invalid settings '{0}'. Unexpected XmlElement: '{1}'. + Neplatné nastavení {0}. Neočekávaný XmlElement: {1}. @@ -271,12 +271,12 @@ but received {4} argument(s), with types '{5}'. Invalid value '{0}' for runsettings entry '{1}', setting will be ignored. - Invalid value '{0}' for runsettings entry '{1}', setting will be ignored. + Neplatná hodnota {0} pro položku runsettings {1}. Nastavení bude ignorováno. Warning : A testsettings file or a vsmdi file is not supported with the MSTest V2 Adapter. - Warning : A testsettings file or a vsmdi file is not supported with the MSTest V2 Adapter. + Upozornění: Adaptér MSTest V2 nepodporuje soubor testsettings ani vsmdi. @@ -291,67 +291,67 @@ but received {4} argument(s), with types '{5}'. An older version of MSTestV2 package is loaded in assembly, test discovery might fail to discover all data tests if they depend on `.runsettings` file. - An older version of MSTestV2 package is loaded in assembly, test discovery might fail to discover all data tests if they depend on `.runsettings` file. + V sestavení je načtena starší verze balíčku MSTestV2. Zjišťování testů může selhat při zjišťování všech testů dat, pokud jsou závislé na souboru .runsettings. Runsettings entry '<ExecutionApartmentState>STA</ExecutionApartmentState>' is not supported on non-Windows OSes. - Runsettings entry '<ExecutionApartmentState>STA</ExecutionApartmentState>' is not supported on non-Windows OSes. + Položka runsettings <ExecutionApartmentState>STA</ExecutionApartmentState> se v operačních systémech jiných než Windows nepodporuje. Running tests in any of the provided sources is not supported for the selected platform - Running tests in any of the provided sources is not supported for the selected platform + Spouštění testů v některém z uvedených zdrojů se pro vybranou platformu nepodporuje. Failed to discover tests from assembly {0}. Reason:{1} - Failed to discover tests from assembly {0}. Reason:{1} + Nepovedlo se zjistit testy ze sestavení {0}. Důvod:{1} File does not exist: {0} - File does not exist: {0} + Neexistující soubor: {0} Test cleanup method '{0}.{1}' timed out after {2}ms - Test cleanup method '{0}.{1}' timed out after {2}ms + Po {2} ms vypršel časový limit metody čištění testu {0}.{1}. Test cleanup method '{0}.{1}' was canceled - Test cleanup method '{0}.{1}' was canceled + Metoda čištění testu {0}.{1} byla zrušena. TestContext cannot be Null. - TestContext cannot be Null. + TestContext nemůže být Null. TestContext Messages: - TestContext Messages: + Zprávy pro TestContext: Test initialize method '{0}.{1}' timed out after {2}ms - Test initialize method '{0}.{1}' timed out after {2}ms + Po {2} ms vypršel časový limit metody inicializace testu {0}.{1}. Test initialize method '{0}.{1}' was canceled - Test initialize method '{0}.{1}' was canceled + Metoda inicializace testu {0}.{1} byla zrušena. Test method {0} was not found. - Test method {0} was not found. + Testovací metoda {0} se nenašla. Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) - Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) + Je povolená paralelizace testu pro {0} (pracovní procesy: {1}, obor: {2}). `Workers` is a setting name that shouldn't be localized. 'Scope' is a setting name that shouldn't be localized. @@ -362,53 +362,53 @@ but received {4} argument(s), with types '{5}'. Unable to load types from the test source '{0}'. Some or all of the tests in this source may not be discovered. Error: {1} - Unable to load types from the test source '{0}'. Some or all of the tests in this source may not be discovered. -Error: {1} + Nepovedlo se načíst typy ze zdroje testu {0}. Je možné, že se některé nebo všechny testy v tomto zdroji nezjistily. +Chyba: {1} Assembly Cleanup method {0}.{1} failed. Error Message: {2}. StackTrace: {3} - Assembly Cleanup method {0}.{1} failed. Error Message: {2}. StackTrace: {3} + Čisticí metoda sestavení {0}.{1} selhala. Chybová zpráva: {2}. Trasování zásobníku: {3} Assembly Initialization method {0}.{1} threw exception. {2}: {3}. Aborting test execution. - Assembly Initialization method {0}.{1} threw exception. {2}: {3}. Aborting test execution. + Inicializační metoda sestavení {0}.{1} vyvolala výjimku. {2}: {3}. Přerušuje se provádění testu. Class Cleanup method {0}.{1} failed. Error Message: {2}. Stack Trace: {3} - Class Cleanup method {0}.{1} failed. Error Message: {2}. Stack Trace: {3} + Čisticí metoda třídy {0}.{1} selhala. Chybová zpráva: {2}. Trasování zásobníku: {3} Class Initialization method {0}.{1} threw exception. {2}: {3}. - Class Initialization method {0}.{1} threw exception. {2}: {3}. + Inicializační metoda třídy {0}.{1} vyvolala výjimku. {2}: {3}. Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. - Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + Metoda {0}.{1} má špatný podpis. Metoda musí být static nebo public, nevrací hodnotu a nesmí přijímat žádný parametr. Pokud navíc v metodě používáte operátor async-await, musí být návratový typ Task nebo ValueTask. Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should take a single parameter of type TestContext. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. - Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should take a single parameter of type TestContext. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + Metoda {0}.{1} má špatný podpis. Metoda musí být static nebo public, nevrací hodnotu a musí přijímat jeden parametr typu TestContext. Pokud navíc v metodě používáte operátor async-await, musí být návratový typ Task nebo ValueTask. TestCleanup method {0}.{1} threw exception. {2}. - TestCleanup method {0}.{1} threw exception. {2}. + Metoda TestCleanup {0}.{1} vyvolala výjimku. {2}. Error calling Test Cleanup method for test class {0}: {1} - Error calling Test Cleanup method for test class {0}: {1} + Při volání čisticí metody testu pro třídu {0} došlo k chybě: {1} TestCleanup Stack Trace - TestCleanup Stack Trace + Trasování zásobníku čištění testu @@ -418,7 +418,7 @@ Error: {1} --- End of inner exception stack trace --- - --- End of inner exception stack trace --- + --- Konec trasování zásobníku pro vnitřní výjimku --- @@ -428,67 +428,67 @@ Error: {1} UTA031: class {0} does not have valid TestContext property. TestContext must be of type TestContext, must be non-static, and must be public. For example: public TestContext TestContext. - UTA031: class {0} does not have valid TestContext property. TestContext must be of type TestContext, must be non-static, and must be public. For example: public TestContext TestContext. + UTA031: Třída {0} nemá platnou vlastnost TestContext. Vlastnost TestContext musí být typu TestContext, musí být nestatická a musí být veřejná. Například: public TestContext TestContext UTA007: Method {1} defined in class {0} does not have correct signature. Test method marked with the [TestMethod] attribute must be non-static, public, return-type as void and should not take any parameter. Example: public void Test.Class1.Test(). Additionally, if you are using async-await in test method then return-type must be 'Task' or 'ValueTask'. Example: public async Task Test.Class1.Test2() - UTA007: Method {1} defined in class {0} does not have correct signature. Test method marked with the [TestMethod] attribute must be non-static, public, return-type as void and should not take any parameter. Example: public void Test.Class1.Test(). Additionally, if you are using async-await in test method then return-type must be 'Task' or 'ValueTask'. Example: public async Task Test.Class1.Test2() + UTA007: Metoda {1} definovaná ve třídě {0} nemá správný podpis. Testovací metoda označená atributem [TestMethod] nesmí být static ani public, musí mít návratový typ void a nesmí přijímat žádný parametr. Například: public void Test.Class1.Test(). Pokud navíc v testovací metodě používáte operátor async-await, musí být návratový typ Task nebo ValueTask. Například: public async Task Test.Class1.Test2() UTA054: {0}.{1} has invalid Timeout attribute. The timeout must be an integer value greater than 0. - UTA054: {0}.{1} has invalid Timeout attribute. The timeout must be an integer value greater than 0. + UTA054: {0}.{1} má neplatný atribut Timeout. Hodnota timeline musí být celé číslo větší než 0. UTA014: {0}: Cannot define more than one method with the AssemblyCleanup attribute inside an assembly. - UTA014: {0}: Cannot define more than one method with the AssemblyCleanup attribute inside an assembly. + UTA014: {0}: V jednom sestavení nejde definovat více jak jednu metodu s atributem AssemblyCleanup. UTA013: {0}: Cannot define more than one method with the AssemblyInitialize attribute inside an assembly. - UTA013: {0}: Cannot define more than one method with the AssemblyInitialize attribute inside an assembly. + UTA013: {0}: V jednom sestavení nejde definovat více jak jednu metodu s atributem AssemblyInitialize. UTA026: {0}: Cannot define more than one method with the ClassCleanup attribute inside a class. - UTA026: {0}: Cannot define more than one method with the ClassCleanup attribute inside a class. + UTA026: {0}: Uvnitř třídy nejde definovat více jak jednu metodu s atributem ClassCleanup. UTA025: {0}: Cannot define more than one method with the ClassInitialize attribute inside a class. - UTA025: {0}: Cannot define more than one method with the ClassInitialize attribute inside a class. + UTA025: {0}: Uvnitř třídy nejde definovat více jak jednu metodu s atributem ClassInitialize. UTA024: {0}: Cannot define more than one method with the TestCleanup attribute. - UTA024: {0}: Cannot define more than one method with the TestCleanup attribute. + UTA024: {0}: Nejde definovat více jak jednu metodu s atributem TestCleanup. UTA018: {0}: Cannot define more than one method with the TestInitialize attribute. - UTA018: {0}: Cannot define more than one method with the TestInitialize attribute. + UTA018: {0}: Nejde definovat více jak jednu metodu s atributem TestInitialize. UTA001: TestClass attribute defined on non-public class {0} - UTA001: TestClass attribute defined on non-public class {0} + UTA001: Atribut TestClass se definoval v neveřejné třídě {0}. UTA023: {0}: Cannot define predefined property {2} on method {1}. - UTA023: {0}: Cannot define predefined property {2} on method {1}. + UTA023: {0}: V metodě {1} nejde definovat předdefinovanou vlastnost {2}. TestClass attribute defined on generic non-abstract class {0} - TestClass attribute defined on generic non-abstract class {0} + Atribut TestClass definovaný u obecné neabstraktní třídy {0} UTA021: {0}: Null or empty custom property defined on method {1}. The custom property must have a valid name. - UTA021: {0}: Null or empty custom property defined on method {1}. The custom property must have a valid name. + UTA021: {0}: V metodě {1} je definovaná vlastní vlastnost, která je null nebo je prázdná. Vlastní vlastnost musí mít platný název. @@ -501,90 +501,90 @@ Error: {1} The ExpectedException attribute defined on test method {0}.{1} threw an exception during construction. {2} - The ExpectedException attribute defined on test method {0}.{1} threw an exception during construction. + Atribut ExpectedException definovaný u testovací metody {0}.{1} vyvolal během vytváření výjimku. {2} Failed to obtain the exception thrown by test method {0}.{1}. - Failed to obtain the exception thrown by test method {0}.{1}. + Nepovedlo se získat výjimku vyvolanou testovací metodou {0}.{1}. Initialization method {0}.{1} threw exception. {2}. - Initialization method {0}.{1} threw exception. {2}. + Inicializační metoda {0}.{1} způsobila výjimku. {2}. Unable to create instance of class {0}. Error: {1}. - Unable to create instance of class {0}. Error: {1}. + Nepodařilo se vytvořit instanci třídy {0}. Chyba: {1}. Method {0}.{1} does not exist. - Method {0}.{1} does not exist. + Metoda {0}.{1} neexistuje. The test method '{0}.{1}' has multiple attributes derived from '{2}' defined on it. Only one such attribute is allowed. - The test method '{0}.{1}' has multiple attributes derived from '{2}' defined on it. Only one such attribute is allowed. + Testovací metoda {0}.{1} má definovaných více atributů odvozených od atributu {2}. Povolený je jenom jeden takový atribut. Error in executing test. No result returned by extension. If using extension of TestMethodAttribute then please contact vendor. - Error in executing test. No result returned by extension. If using extension of TestMethodAttribute then please contact vendor. + Při provádění testu došlo k chybě. Rozšíření nevrátilo žádný výsledek. Pokud používáte rozšíření třídy TestMethodAttribute, obraťte se na dodavatele. Cannot find a valid constructor for test class '{0}'. Valid constructors are 'public' and either parameterless or with one parameter of type 'TestContext'. - Cannot find a valid constructor for test class '{0}'. Valid constructors are 'public' and either parameterless or with one parameter of type 'TestContext'. + Nelze najít platný konstruktor pro testovací třídu {0}. Platné konstruktory jsou public a buď bez parametrů, nebo s jedním parametrem typu TestContext. Unable to find property {0}.TestContext. Error:{1}. - Unable to find property {0}.TestContext. Error:{1}. + Nepodařilo se najít vlastnost {0}.TestContext. Chyba:{1}. Unable to set TestContext property for the class {0}. Error: {1}. - Unable to set TestContext property for the class {0}. Error: {1}. + Pro třídu {0} se nepodařilo nastavit vlastnost TestContext. Chyba: {1}. The {0}.TestContext has incorrect type. - The {0}.TestContext has incorrect type. + {0}.TestContext má nesprávný typ. Method {0}.{1} has wrong signature. The method must be non-static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. - Method {0}.{1} has wrong signature. The method must be non-static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + Metoda {0}.{1} má špatný podpis. Metoda nesmí být static nebo public, nevrací hodnotu a nesmí přijímat žádný parametr. Pokud navíc v metodě používáte operátor async-await, musí být návratový typ Task nebo ValueTask. Test method {0}.{1} threw exception: {2} - Test method {0}.{1} threw exception: + V testovací metodě {0}.{1} došlo k výjimce: {2} Unable to get type {0}. Error: {1}. - Unable to get type {0}. Error: {1}. + Nepodařilo se získat typ {0}. Chyba: {1}. The called code threw an exception that was caught, but the exception value was null - The called code threw an exception that was caught, but the exception value was null + Volaný kód vyvolal výjimku, která byla zachycena, ale její hodnota byla null. {0} For UWP projects, if you are using UI objects in test consider using [UITestMethod] attribute instead of [TestMethod] to execute test in UI thread. - {0} For UWP projects, if you are using UI objects in test consider using [UITestMethod] attribute instead of [TestMethod] to execute test in UI thread. + {0}. Pokud v testu používáte objekty uživatelského rozhraní, zvažte u projektů pro platformu UPW použití atributu [UITestMethod] místo atributu [TestMethod], aby se test provedl ve vlákně uživatelského rozhraní. (Failed to get the message for an exception of type {0} due to an exception.) - (Failed to get the message for an exception of type {0} due to an exception.) + (Z důvodu výjimky se nepodařilo získat zprávu o výjimce typu {0}.) diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.de.xlf b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.de.xlf index 283233a4b5..8890afe3e0 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.de.xlf +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.de.xlf @@ -4,52 +4,52 @@ Assembly cleanup method '{0}.{1}' timed out after {2}ms - Assembly cleanup method '{0}.{1}' timed out after {2}ms + Timeout der Assemblybereinigungsmethode "{0}.{1}" nach {2} ms Assembly cleanup method '{0}.{1}' was canceled - Assembly cleanup method '{0}.{1}' was canceled + Die Assemblybereinigungsmethode "{0}.{1}" wurde abgebrochen Assembly initialize method '{0}.{1}' timed out after {2}ms - Assembly initialize method '{0}.{1}' timed out after {2}ms + Timeout der Assemblyinitialisierungsmethode "{0}.{1}" nach {2} ms Assembly initialize method '{0}.{1}' was canceled - Assembly initialize method '{0}.{1}' was canceled + Die Assemblyinitialisierungsmethode "{0}.{1}" wurde abgebrochen MSTestAdapterV2 - MSTestAdapterV2 + MSTestAdapterV2 Exception occurred while enumerating IDataSource attribute on "{0}.{1}": {2} - Exception occurred while enumerating IDataSource attribute on "{0}.{1}": {2} + Ausnahme beim Auflisten des IDataSource-Attributs für "{0}.{1}": {2} {0}: TypeName with namespace, {1}: Method name, {2}: Exception details Exception occurred while expanding IDataSource rows from attribute on "{0}.{1}": {2} - Exception occurred while expanding IDataSource rows from attribute on "{0}.{1}": {2} + Ausnahme beim Erweitern von IDataSource-Zeilen aus dem Attribut auf "{0}.{1}": {2} {0}: TypeName with namespace, {1}: Method name, {2}: CannotExpandIDataSourceAttribute_DuplicateDisplayName or CannotExpandIDataSourceAttribute_CannotSerialize Data on index {0} for "{1}" cannot be serialized. All data provided through "IDataSource" should be serializable. If you need to test non-serializable data sources, please make sure you add "TestDataSourceDiscovery" attribute on your test assembly and set the discovery option to "DuringExecution". - Data on index {0} for "{1}" cannot be serialized. All data provided through "IDataSource" should be serializable. If you need to test non-serializable data sources, please make sure you add "TestDataSourceDiscovery" attribute on your test assembly and set the discovery option to "DuringExecution". + Daten im Index {0} für "{1}" können nicht serialisiert werden. Alle über "IDataSource" bereitgestellten Daten sollten serialisierbar sein. Wenn Sie nicht serialisierbare Datenquellen testen müssen, stellen Sie sicher, dass Sie der Testassembly das Attribut "TestDataSourceDiscovery" hinzufügen und die Ermittlungsoption auf "DuringExecution" festlegen. {0}: Zero based index if an element inside of an array, {1}: Test name Display name "{2}" on indexes {0} and {1} are duplicate. Display names should be unique. - Display name "{2}" on indexes {0} and {1} are duplicate. Display names should be unique. + Der Anzeigename "{2}" für Indizes {0} und {1} ist doppelt vorhanden. Anzeigenamen sollten eindeutig sein. {0}, {1}: Zero based index if an element inside of an array {2}: Test display name. @@ -69,27 +69,27 @@ but received {4} argument(s), with types '{5}'. Cannot run test method '{0}.{1}': Method has parameters, but does not define any test source. Use '[DataRow]', '[DynamicData]', or a custom 'ITestDataSource' data source to provide test data. - Cannot run test method '{0}.{1}': Method has parameters, but does not define any test source. Use '[DataRow]', '[DynamicData]', or a custom 'ITestDataSource' data source to provide test data. + Die Testmethode „{0}.{1}“ kann nicht ausgeführt werden: Die Methode verfügt über Parameter, definiert jedoch keine Testquelle. Verwenden Sie „[DataRow]“, „[DynamicData]“ oder eine benutzerdefinierte „ITestDataSource-Datenquelle“, um Testdaten bereitzustellen. Class cleanup method '{0}.{1}' timed out after {2}ms - Class cleanup method '{0}.{1}' timed out after {2}ms + Timeout der Klassenbereinigungsmethode "{0}.{1}" nach {2} ms Class cleanup method '{0}.{1}' was canceled - Class cleanup method '{0}.{1}' was canceled + Die Klassenbereinigungsmethode "{0}.{1}" wurde abgebrochen Class initialize method '{0}.{1}' timed out after {2}ms - Class initialize method '{0}.{1}' timed out after {2}ms + Timeout der Klasseninitialisierungsmethode "{0}.{1}" nach {2} ms Class initialize method '{0}.{1}' was canceled - Class initialize method '{0}.{1}' was canceled + Die Initialisierungsmethode "{0}.{1}" der Klasse wurde abgebrochen @@ -99,17 +99,17 @@ but received {4} argument(s), with types '{5}'. MSTestAdapter failed to discover tests in class '{0}' of assembly '{1}' because {2}. - MSTestAdapter failed to discover tests in class '{0}' of assembly '{1}' because {2}. + Fehler von 'MSTestAdapter' beim Ermitteln von Tests in der Klasse "{0}" der Assembly "{1}". Ursache: {2}. {0} (Data Row {1}) - {0} (Data Row {1}) + {0} (Datenzeile {1}) Debug Trace: - Debug Trace: + Debugablaufverfolgung: @@ -179,28 +179,28 @@ but received {4} argument(s), with types '{5}'. [MSTest][Discovery][{0}] {1} - [MSTest][Discovery][{0}] {1} + [MSTest][Discovery][{0}] {1} Both '.runsettings' and '.testconfig.json' files have been detected. Please select only one of these test configuration files. - Both '.runsettings' and '.testconfig.json' files have been detected. Please select only one of these test configuration files. + Es wurden sowohl die Dateien „.runsettings“ als auch „.testconfig.json“ erkannt. Wählen Sie nur eine dieser Testkonfigurationsdateien aus. {0}: {1} - {0}: {1} + {0}: {1} "{0}": (Failed to get exception description due to an exception of type "{1}". - "{0}": (Failed to get exception description due to an exception of type "{1}". + "{0}": (Fehler beim Abrufen der Ausnahmebeschreibung aufgrund einer Ausnahme vom Typ "{1}". {0}: Type of the original exception that we're trying to get the description of. {1}: Thrown exception Exceptions thrown: - Exceptions thrown: + Ausgelöste Ausnahmen: This is usually precedes by TestAssembly_AssemblyDiscoveryFailure message, and preceded by list of exceptions thrown in a test discovery session. @@ -215,7 +215,7 @@ but received {4} argument(s), with types '{5}'. Getting custom attributes for type {0} threw exception (will ignore and use the reflection way): {1} - Getting custom attributes for type {0} threw exception (will ignore and use the reflection way): {1} + Beim Abrufen von benutzerdefinierten Attributen für den Typ {0} wurde Ausnahme ausgelöst (wird ignoriert und die Reflektionsart verwendet): {1} {0}: Attribute full type name. {1}: Exception description @@ -236,22 +236,22 @@ but received {4} argument(s), with types '{5}'. Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. - Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. + Für "ClassCleanupLifecycle" wurde ein ungültiger Wert "{0}" angegeben. Unterstützte Bereiche sind {1}. 'ClassCleanupLifecycle' is a setting name that shouldn't be localized. Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. - Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. + Ungültiger Wert "{0}" für "Scope" angegeben. Unterstützte Bereiche: {1}. 'Scope' is a setting name that shouldn't be localized. Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. - Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. + Ungültiger Wert "{0}" für "Workers" angegeben. Der Wert muss eine nicht negative Ganzzahl sein. `Workers` is a setting name that shouldn't be localized. Invalid settings '{0}'. Unexpected XmlAttribute: '{1}'. - Invalid settings '{0}'. Unexpected XmlAttribute: '{1}'. + Ungültige Einstellungen "{0}". Unerwartetes XmlAttribute: "{1}". @@ -261,7 +261,7 @@ but received {4} argument(s), with types '{5}'. Invalid settings '{0}'. Unexpected XmlElement: '{1}'. - Invalid settings '{0}'. Unexpected XmlElement: '{1}'. + Ungültige Einstellungen "{0}". Unerwartetes XmlElement: "{1}". @@ -271,12 +271,12 @@ but received {4} argument(s), with types '{5}'. Invalid value '{0}' for runsettings entry '{1}', setting will be ignored. - Invalid value '{0}' for runsettings entry '{1}', setting will be ignored. + Ungültiger Wert "{0}" für runsettings-Eintrag "{1}". Die Einstellung wird ignoriert. Warning : A testsettings file or a vsmdi file is not supported with the MSTest V2 Adapter. - Warning : A testsettings file or a vsmdi file is not supported with the MSTest V2 Adapter. + Warnung: Eine TESTSETTINGS-Datei oder eine VSMDI-Datei wird vom MSTest-V2-Adapter nicht unterstützt. @@ -291,67 +291,67 @@ but received {4} argument(s), with types '{5}'. An older version of MSTestV2 package is loaded in assembly, test discovery might fail to discover all data tests if they depend on `.runsettings` file. - An older version of MSTestV2 package is loaded in assembly, test discovery might fail to discover all data tests if they depend on `.runsettings` file. + Eine ältere Version des MSTestV2-Pakets wird in die Assembly geladen. Bei der Testermittlung werden möglicherweise nicht alle Datentests ermittelt, wenn sie von der Datei ".runsettings" abhängen. Runsettings entry '<ExecutionApartmentState>STA</ExecutionApartmentState>' is not supported on non-Windows OSes. - Runsettings entry '<ExecutionApartmentState>STA</ExecutionApartmentState>' is not supported on non-Windows OSes. + Der Eintrag "<ExecutionApartmentState>STA</ExecutionApartmentState>" der Ausführungseinstellungen wird auf Nicht-Windows-Betriebssystemen nicht unterstützt. Running tests in any of the provided sources is not supported for the selected platform - Running tests in any of the provided sources is not supported for the selected platform + Das Ausführen von Tests in einer der angegebenen Quellen wird für die ausgewählte Plattform nicht unterstützt. Failed to discover tests from assembly {0}. Reason:{1} - Failed to discover tests from assembly {0}. Reason:{1} + Fehler beim Ermitteln von Tests aus der Assembly "{0}". Ursache:{1} File does not exist: {0} - File does not exist: {0} + Die Datei ist nicht vorhanden: {0} Test cleanup method '{0}.{1}' timed out after {2}ms - Test cleanup method '{0}.{1}' timed out after {2}ms + Timeout der Testbereinigungsmethode "{0}.{1}" nach {2} ms Test cleanup method '{0}.{1}' was canceled - Test cleanup method '{0}.{1}' was canceled + Die Testbereinigungsmethode "{0}.{1}" wurde abgebrochen TestContext cannot be Null. - TestContext cannot be Null. + "TestContext" darf nicht NULL sein. TestContext Messages: - TestContext Messages: + TestContext-Meldungen: Test initialize method '{0}.{1}' timed out after {2}ms - Test initialize method '{0}.{1}' timed out after {2}ms + Timeout der Testinitialisierungsmethode "{0}.{1}" nach {2} ms Test initialize method '{0}.{1}' was canceled - Test initialize method '{0}.{1}' was canceled + Die Testinitialisierungsmethode "{0}.{1}" wurde abgebrochen Test method {0} was not found. - Test method {0} was not found. + Die Testmethode "{0}" wurde nicht gefunden. Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) - Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) + Testparallelisierung aktiviert für {0} (Worker: {1}, Bereich: {2}) `Workers` is a setting name that shouldn't be localized. 'Scope' is a setting name that shouldn't be localized. @@ -362,53 +362,53 @@ but received {4} argument(s), with types '{5}'. Unable to load types from the test source '{0}'. Some or all of the tests in this source may not be discovered. Error: {1} - Unable to load types from the test source '{0}'. Some or all of the tests in this source may not be discovered. -Error: {1} + Fehler beim Laden von Typen aus der Testquelle "{0}". Möglicherweise werden einige oder alle Tests in dieser Quelle nicht ermittelt. +Fehler: {1} Assembly Cleanup method {0}.{1} failed. Error Message: {2}. StackTrace: {3} - Assembly Cleanup method {0}.{1} failed. Error Message: {2}. StackTrace: {3} + Fehler bei der Methode "{0}.{1}" für die Assemblybereinigung. Fehlermeldung: {2}. "StackTrace": {3} Assembly Initialization method {0}.{1} threw exception. {2}: {3}. Aborting test execution. - Assembly Initialization method {0}.{1} threw exception. {2}: {3}. Aborting test execution. + Die Methode "{0}.{1}" für die Assemblyinitialisierung hat eine Ausnahme ausgelöst. {2}: {3}. Die Ausführung des Tests wird abgebrochen. Class Cleanup method {0}.{1} failed. Error Message: {2}. Stack Trace: {3} - Class Cleanup method {0}.{1} failed. Error Message: {2}. Stack Trace: {3} + Fehler bei der Methode "{0}.{1}" für die Klassenbereinigung. Fehlermeldung: {2}. Stapelüberwachung: {3} Class Initialization method {0}.{1} threw exception. {2}: {3}. - Class Initialization method {0}.{1} threw exception. {2}: {3}. + Die Methode "{0}.{1}" für die Klasseninitialisierung hat eine Ausnahme ausgelöst. {2}: {3}. Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. - Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + Die Methode „{0}.{1}“ weist eine falsche Signatur auf. Die Methode muss statisch und öffentlich sein. Sie darf keinen Wert zurückgeben und keinen Parameter annehmen. Wenn Sie außerdem in der Methode „async-await“ verwenden, muss der Rückgabetyp „Task“ oder „ValueTask“ sein. Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should take a single parameter of type TestContext. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. - Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should take a single parameter of type TestContext. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + Die Methode „{0}.{1}“ weist eine falsche Signatur auf. Die Methode muss statisch und öffentlich sein. Sie darf keinen Wert zurückgeben und muss einen einzigen Parameter des Typs TestContext annehmen. Wenn Sie außerdem in der Methode „async-await“ verwenden, muss der Rückgabetyp „Task“ oder „ValueTask“ sein. TestCleanup method {0}.{1} threw exception. {2}. - TestCleanup method {0}.{1} threw exception. {2}. + Die TestCleanup-Methode "{0}.{1}" hat eine Ausnahme ausgelöst. {2}. Error calling Test Cleanup method for test class {0}: {1} - Error calling Test Cleanup method for test class {0}: {1} + Fehler beim Aufruf der Testbereinigungsmethode für die Testklasse "{0}": {1} TestCleanup Stack Trace - TestCleanup Stack Trace + TestCleanup-Stapelüberwachung @@ -418,7 +418,7 @@ Error: {1} --- End of inner exception stack trace --- - --- End of inner exception stack trace --- + --- Ende der internen Ausnahmestapelüberwachung --- @@ -428,67 +428,67 @@ Error: {1} UTA031: class {0} does not have valid TestContext property. TestContext must be of type TestContext, must be non-static, and must be public. For example: public TestContext TestContext. - UTA031: class {0} does not have valid TestContext property. TestContext must be of type TestContext, must be non-static, and must be public. For example: public TestContext TestContext. + UTA031: Die Klasse {0} weist keine gültige Eigenschaft TestContext auf. TestContext muss vom Typ TestContext sein, muss nicht statisch und öffentlich sein. Beispiel: 'public TestContext TestContext'. UTA007: Method {1} defined in class {0} does not have correct signature. Test method marked with the [TestMethod] attribute must be non-static, public, return-type as void and should not take any parameter. Example: public void Test.Class1.Test(). Additionally, if you are using async-await in test method then return-type must be 'Task' or 'ValueTask'. Example: public async Task Test.Class1.Test2() - UTA007: Method {1} defined in class {0} does not have correct signature. Test method marked with the [TestMethod] attribute must be non-static, public, return-type as void and should not take any parameter. Example: public void Test.Class1.Test(). Additionally, if you are using async-await in test method then return-type must be 'Task' or 'ValueTask'. Example: public async Task Test.Class1.Test2() + UTA007: Die in der Klasse {0} definierte Methode {1} weist nicht die richtige Signatur auf. Die mit dem [TestMethod]-Attribut markierte Testmethode muss nicht statisch und öffentlich sein, muss den Rückgabetyp „void“ aufweisen und darf keine Parameter annehmen. Beispiel: public void Test.Class1.Test(). Wenn Sie außerdem in der Testmethode „async-await“ verwenden, muss der Rückgabetyp „Task“ oder „ValueTask“ sein. Beispiel: public async Task Test.Class1.Test2() UTA054: {0}.{1} has invalid Timeout attribute. The timeout must be an integer value greater than 0. - UTA054: {0}.{1} has invalid Timeout attribute. The timeout must be an integer value greater than 0. + UTA054: {0}.{1} weist ein ungültiges Attribut „Timeout“ auf. Timeout muss eine ganze Zahl größer als 0 sein. UTA014: {0}: Cannot define more than one method with the AssemblyCleanup attribute inside an assembly. - UTA014: {0}: Cannot define more than one method with the AssemblyCleanup attribute inside an assembly. + UTA014: {0}: Es darf nur eine Methode mit dem Attribut 'AssemblyCleanup' innerhalb einer Assembly definiert werden. UTA013: {0}: Cannot define more than one method with the AssemblyInitialize attribute inside an assembly. - UTA013: {0}: Cannot define more than one method with the AssemblyInitialize attribute inside an assembly. + UTA013: {0}: Es darf nur eine Methode mit dem Attribut 'AssemblyInitialize' innerhalb einer Assembly definiert werden. UTA026: {0}: Cannot define more than one method with the ClassCleanup attribute inside a class. - UTA026: {0}: Cannot define more than one method with the ClassCleanup attribute inside a class. + UTA026: {0}: Es darf nur eine Methode mit dem Attribut 'ClassCleanup' innerhalb einer Klasse definiert werden. UTA025: {0}: Cannot define more than one method with the ClassInitialize attribute inside a class. - UTA025: {0}: Cannot define more than one method with the ClassInitialize attribute inside a class. + UTA025: {0}: Es darf nur eine Methode mit dem Attribut 'ClassInitialize' innerhalb einer Klasse definiert werden. UTA024: {0}: Cannot define more than one method with the TestCleanup attribute. - UTA024: {0}: Cannot define more than one method with the TestCleanup attribute. + UTA024: {0}: Es darf nur eine Methode mit dem Attribut 'TestCleanup' definiert werden. UTA018: {0}: Cannot define more than one method with the TestInitialize attribute. - UTA018: {0}: Cannot define more than one method with the TestInitialize attribute. + UTA018: {0}: Es darf nur eine Methode mit dem Attribut 'TestInitialize' definiert werden. UTA001: TestClass attribute defined on non-public class {0} - UTA001: TestClass attribute defined on non-public class {0} + UTA001: Für die nicht öffentliche Klasse '{0}' definiertes Attribut 'TestClass'. UTA023: {0}: Cannot define predefined property {2} on method {1}. - UTA023: {0}: Cannot define predefined property {2} on method {1}. + UTA023: {0}: Die vordefinierte Eigenschaft "{2}" kann nicht für die Methode "{1}" definiert werden. TestClass attribute defined on generic non-abstract class {0} - TestClass attribute defined on generic non-abstract class {0} + TestClass-Attribut für generische nicht abstrakte Klasse {0} definiert UTA021: {0}: Null or empty custom property defined on method {1}. The custom property must have a valid name. - UTA021: {0}: Null or empty custom property defined on method {1}. The custom property must have a valid name. + UTA021: {0}: Für die Methode "{1}" wurde eine benutzerdefinierte Eigenschaft mit dem Wert NULL oder eine benutzerdefinierte leere Eigenschaft definiert. Die benutzerdefinierte Eigenschaft muss einen gültigen Namen aufweisen. @@ -501,90 +501,90 @@ Error: {1} The ExpectedException attribute defined on test method {0}.{1} threw an exception during construction. {2} - The ExpectedException attribute defined on test method {0}.{1} threw an exception during construction. + Das für die Testmethode "{0}.{1}" definierte ExpectedException-Attribut hat während der Konstruktion eine Ausnahme ausgelöst. {2} Failed to obtain the exception thrown by test method {0}.{1}. - Failed to obtain the exception thrown by test method {0}.{1}. + Fehler beim Abrufen der von der Testmethode "{0}.{1}" ausgelösten Ausnahme. Initialization method {0}.{1} threw exception. {2}. - Initialization method {0}.{1} threw exception. {2}. + Die Initialisierungsmethode '{0}.{1}' hat eine Ausnahme ausgelöst. {2}. Unable to create instance of class {0}. Error: {1}. - Unable to create instance of class {0}. Error: {1}. + Es kann keine Instanz der Klasse '{0}' erstellt werden. Fehler: {1}. Method {0}.{1} does not exist. - Method {0}.{1} does not exist. + Die Methode "{0}.{1}" ist nicht vorhanden. The test method '{0}.{1}' has multiple attributes derived from '{2}' defined on it. Only one such attribute is allowed. - The test method '{0}.{1}' has multiple attributes derived from '{2}' defined on it. Only one such attribute is allowed. + Für die Testmethode „{0}.{1}“ sind mehrere Attribute definiert, die von „{2}“ abgeleitet sind. Nur ein einziges solches Attribut ist zulässig. Error in executing test. No result returned by extension. If using extension of TestMethodAttribute then please contact vendor. - Error in executing test. No result returned by extension. If using extension of TestMethodAttribute then please contact vendor. + Fehler beim Ausführen des Tests. Von der Extension wurde kein Ergebnis zurückgegeben. Wenn Sie eine Extension von "TestMethodAttribute" verwenden, wenden Sie sich bitte an den Anbieter. Cannot find a valid constructor for test class '{0}'. Valid constructors are 'public' and either parameterless or with one parameter of type 'TestContext'. - Cannot find a valid constructor for test class '{0}'. Valid constructors are 'public' and either parameterless or with one parameter of type 'TestContext'. + Es wurde kein gültiger Konstruktor für die Testklasse "{0}" gefunden. Gültige Konstruktoren sind "public" und entweder parameterlos oder mit einem Parameter vom Typ "TestContext". Unable to find property {0}.TestContext. Error:{1}. - Unable to find property {0}.TestContext. Error:{1}. + Die Eigenschaft "{0}.TestContext" wurde nicht gefunden. Fehler: {1}. Unable to set TestContext property for the class {0}. Error: {1}. - Unable to set TestContext property for the class {0}. Error: {1}. + Die Eigenschaft 'TestContext' für die Klasse '{0}' kann nicht festgelegt werden. Fehler: {1}. The {0}.TestContext has incorrect type. - The {0}.TestContext has incorrect type. + "{0}.TestContext" weist einen falschen Typ auf. Method {0}.{1} has wrong signature. The method must be non-static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. - Method {0}.{1} has wrong signature. The method must be non-static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + Die Methode „{0}.{1}“ weist eine falsche Signatur auf. Die Methode muss nicht statisch und öffentlich sein, und sie darf keinen Wert zurückgeben und keinen Parameter annehmen. Wenn Sie außerdem in der Methode „async-await“ verwenden, muss der Rückgabetyp „Task“ oder „ValueTask“ sein. Test method {0}.{1} threw exception: {2} - Test method {0}.{1} threw exception: + Die Testmethode "{0}.{1}" hat eine Ausnahme ausgelöst: {2} Unable to get type {0}. Error: {1}. - Unable to get type {0}. Error: {1}. + Der Typ "{0}" kann nicht abgerufen werden. Fehler: {1}. The called code threw an exception that was caught, but the exception value was null - The called code threw an exception that was caught, but the exception value was null + Der aufgerufene Code hat eine Ausnahme ausgelöst, die abgefangen wurde, aber der Ausnahmewert war NULL. {0} For UWP projects, if you are using UI objects in test consider using [UITestMethod] attribute instead of [TestMethod] to execute test in UI thread. - {0} For UWP projects, if you are using UI objects in test consider using [UITestMethod] attribute instead of [TestMethod] to execute test in UI thread. + {0}: Erwägen Sie für UWP-Projekte bei Einsatz von UI-Objekten im Test die Verwendung des [UITestMethod]-Attributs anstelle von "[TestMethod]", um den Test im UI-Thread auszuführen. (Failed to get the message for an exception of type {0} due to an exception.) - (Failed to get the message for an exception of type {0} due to an exception.) + (Fehler beim Abrufen der Meldung für eine Ausnahme vom Typ "{0}" aufgrund einer Ausnahme.) diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.es.xlf b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.es.xlf index 765120c3b9..3d8036ba23 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.es.xlf +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.es.xlf @@ -4,52 +4,52 @@ Assembly cleanup method '{0}.{1}' timed out after {2}ms - Assembly cleanup method '{0}.{1}' timed out after {2}ms + Método de limpieza de ensamblado '{0}.{1}' se agotó el tiempo de espera después de {2}ms Assembly cleanup method '{0}.{1}' was canceled - Assembly cleanup method '{0}.{1}' was canceled + Método de limpieza de ensamblado "{0}.{1}" se canceló Assembly initialize method '{0}.{1}' timed out after {2}ms - Assembly initialize method '{0}.{1}' timed out after {2}ms + Método de inicialización de ensamblado '{0}.{1}' se agotó el tiempo de espera de después de {2}ms Assembly initialize method '{0}.{1}' was canceled - Assembly initialize method '{0}.{1}' was canceled + Método de inicialización de ensamblado "{0}.{1}" se canceló MSTestAdapterV2 - MSTestAdapterV2 + MSTestAdapterV2 Exception occurred while enumerating IDataSource attribute on "{0}.{1}": {2} - Exception occurred while enumerating IDataSource attribute on "{0}.{1}": {2} + Excepción al enumerar el atributo IDataSource en "{0}.{1}": {2} {0}: TypeName with namespace, {1}: Method name, {2}: Exception details Exception occurred while expanding IDataSource rows from attribute on "{0}.{1}": {2} - Exception occurred while expanding IDataSource rows from attribute on "{0}.{1}": {2} + Se produjo una excepción al expandir las filas de IDataSource del atributo en "{0}.{1}": {2} {0}: TypeName with namespace, {1}: Method name, {2}: CannotExpandIDataSourceAttribute_DuplicateDisplayName or CannotExpandIDataSourceAttribute_CannotSerialize Data on index {0} for "{1}" cannot be serialized. All data provided through "IDataSource" should be serializable. If you need to test non-serializable data sources, please make sure you add "TestDataSourceDiscovery" attribute on your test assembly and set the discovery option to "DuringExecution". - Data on index {0} for "{1}" cannot be serialized. All data provided through "IDataSource" should be serializable. If you need to test non-serializable data sources, please make sure you add "TestDataSourceDiscovery" attribute on your test assembly and set the discovery option to "DuringExecution". + No se pueden serializar los datos del {0} de índice para "{1}". Todos los datos proporcionados a través de "IDataSource" deben ser serializables. Si necesita probar orígenes de datos no serializables, asegúrese de agregar el atributo "TestDataSourceDiscovery" en el ensamblado de prueba y establezca la opción de detección en "DuringExecution". {0}: Zero based index if an element inside of an array, {1}: Test name Display name "{2}" on indexes {0} and {1} are duplicate. Display names should be unique. - Display name "{2}" on indexes {0} and {1} are duplicate. Display names should be unique. + El nombre para mostrar "{2}" en los índices {0} y {1} están duplicados. Los nombres para mostrar deben ser únicos. {0}, {1}: Zero based index if an element inside of an array {2}: Test display name. @@ -62,34 +62,34 @@ Cannot run test method '{0}.{1}': Test data doesn't match method parameters. Either the count or types are different. Test expected {2} parameter(s), with types '{3}', but received {4} argument(s), with types '{5}'. - Cannot run test method '{0}.{1}': Test data doesn't match method parameters. Either the count or types are different. -Test expected {2} parameter(s), with types '{3}', -but received {4} argument(s), with types '{5}'. + No se puede ejecutar el método de prueba '{0}.{1}': Los datos de prueba no coinciden con los parámetros del método. El recuento o los tipos son diferentes. +Probar los parámetros de {2} esperados, con los tipos '{3}', +pero recibió {4} argumentos, con los tipos '{5}'. Cannot run test method '{0}.{1}': Method has parameters, but does not define any test source. Use '[DataRow]', '[DynamicData]', or a custom 'ITestDataSource' data source to provide test data. - Cannot run test method '{0}.{1}': Method has parameters, but does not define any test source. Use '[DataRow]', '[DynamicData]', or a custom 'ITestDataSource' data source to provide test data. + No se puede ejecutar el método de prueba "{0}.{1}": el método tiene parámetros, pero no define ningún origen de prueba. Use "[DataRow]", "[DynamicData]" o un origen de datos "ITestDataSource" personalizado para proporcionar datos de prueba. Class cleanup method '{0}.{1}' timed out after {2}ms - Class cleanup method '{0}.{1}' timed out after {2}ms + Método de limpieza de clases '{0}.{1}' se agotó el tiempo de espera después de {2}ms Class cleanup method '{0}.{1}' was canceled - Class cleanup method '{0}.{1}' was canceled + Método de limpieza de clases "{0}.{1}" se canceló Class initialize method '{0}.{1}' timed out after {2}ms - Class initialize method '{0}.{1}' timed out after {2}ms + Método de inicialización de clase '{0}.{1}' se agotó el tiempo de espera después de {2}ms Class initialize method '{0}.{1}' was canceled - Class initialize method '{0}.{1}' was canceled + Método de inicialización de clase "{0}.{1}" se canceló @@ -99,17 +99,17 @@ but received {4} argument(s), with types '{5}'. MSTestAdapter failed to discover tests in class '{0}' of assembly '{1}' because {2}. - MSTestAdapter failed to discover tests in class '{0}' of assembly '{1}' because {2}. + MSTestAdapter no detectó pruebas en la clase '{0}' del ensamblado '{1}' porque {2}. {0} (Data Row {1}) - {0} (Data Row {1}) + {0} (Fila de datos {1}) Debug Trace: - Debug Trace: + Seguimiento de depuración: @@ -179,79 +179,79 @@ but received {4} argument(s), with types '{5}'. [MSTest][Discovery][{0}] {1} - [MSTest][Discovery][{0}] {1} + [MSTest][Discovery][{0}] {1} Both '.runsettings' and '.testconfig.json' files have been detected. Please select only one of these test configuration files. - Both '.runsettings' and '.testconfig.json' files have been detected. Please select only one of these test configuration files. + Se han detectado los archivos ".runsettings" y ".testconfig.json". Seleccione solo uno de estos archivos de configuración de prueba. {0}: {1} - {0}: {1} + {0}: {1} "{0}": (Failed to get exception description due to an exception of type "{1}". - "{0}": (Failed to get exception description due to an exception of type "{1}". + "{0}": (No se pudo obtener la descripción de la excepción debido a una excepción de tipo "{1}". {0}: Type of the original exception that we're trying to get the description of. {1}: Thrown exception Exceptions thrown: - Exceptions thrown: + Excepciones devueltas: This is usually precedes by TestAssembly_AssemblyDiscoveryFailure message, and preceded by list of exceptions thrown in a test discovery session. Test '{0}' was canceled - Test '{0}' was canceled + Se canceló la prueba '{0}' Test '{0}' timed out after {1}ms - Test '{0}' timed out after {1}ms + La prueba '{0}' agotó el tiempo de espera después de {1} ms Getting custom attributes for type {0} threw exception (will ignore and use the reflection way): {1} - Getting custom attributes for type {0} threw exception (will ignore and use the reflection way): {1} + Al obtener atributos personalizados para el tipo {0} se produjo una excepción (se omitirá y se usará la forma de reflexión): {1} {0}: Attribute full type name. {1}: Exception description The type of the generic parameter '{0}' could not be inferred. - The type of the generic parameter '{0}' could not be inferred. + No se pudo inferir el tipo del parámetro genérico '{0}'. The generic test method '{0}' doesn't have arguments, so the generic parameter cannot be inferred. - The generic test method '{0}' doesn't have arguments, so the generic parameter cannot be inferred. + El método de prueba genérico '{0}' no tiene argumentos, por lo que no se puede inferir el parámetro genérico. Found two conflicting types for generic parameter '{0}'. The conflicting types are '{1}' and '{2}'. - Found two conflicting types for generic parameter '{0}'. The conflicting types are '{1}' and '{2}'. + Se encontraron dos tipos en conflicto para el parámetro genérico '{0}'. Los tipos en conflicto son '{1}' y ''{2}. Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. - Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. + Valor no válido "{0}" especificado para "ClassCleanupLifecycle". Los ámbitos admitidos son {1}. 'ClassCleanupLifecycle' is a setting name that shouldn't be localized. Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. - Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. + Valor no válido "{0}" especificado para "Ámbito". Los ámbitos admitidos son {1}. 'Scope' is a setting name that shouldn't be localized. Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. - Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. + Valor no válido "{0}" especificado para "Trabajadores". El valor debe ser un entero no negativo. `Workers` is a setting name that shouldn't be localized. Invalid settings '{0}'. Unexpected XmlAttribute: '{1}'. - Invalid settings '{0}'. Unexpected XmlAttribute: '{1}'. + Valor no válido '{0}'. XmlAttribute no esperado: '{1}'. @@ -261,7 +261,7 @@ but received {4} argument(s), with types '{5}'. Invalid settings '{0}'. Unexpected XmlElement: '{1}'. - Invalid settings '{0}'. Unexpected XmlElement: '{1}'. + Valor no válido '{0}'. XmlElement no esperado: '{1}'. @@ -271,12 +271,12 @@ but received {4} argument(s), with types '{5}'. Invalid value '{0}' for runsettings entry '{1}', setting will be ignored. - Invalid value '{0}' for runsettings entry '{1}', setting will be ignored. + Valor ''{0}'' no válido para la entrada runsettings ''{1}'', se omitirá la configuración. Warning : A testsettings file or a vsmdi file is not supported with the MSTest V2 Adapter. - Warning : A testsettings file or a vsmdi file is not supported with the MSTest V2 Adapter. + Advertencia: No se admite un archivo testsettings o vsmdi con el adaptador de MSTest V2. @@ -291,67 +291,67 @@ but received {4} argument(s), with types '{5}'. An older version of MSTestV2 package is loaded in assembly, test discovery might fail to discover all data tests if they depend on `.runsettings` file. - An older version of MSTestV2 package is loaded in assembly, test discovery might fail to discover all data tests if they depend on `.runsettings` file. + Hay una versión anterior del paquete MSTestV2 cargada en el ensamblado. Es posible que la detección de pruebas no detecte todas las pruebas de datos si dependen del archivo ".runsettings". Runsettings entry '<ExecutionApartmentState>STA</ExecutionApartmentState>' is not supported on non-Windows OSes. - Runsettings entry '<ExecutionApartmentState>STA</ExecutionApartmentState>' is not supported on non-Windows OSes. + La entrada runsettings "<ExecutionApartmentState>STA</ExecutionApartmentState>" no se admite en sistemas operativos que no son de Windows. Running tests in any of the provided sources is not supported for the selected platform - Running tests in any of the provided sources is not supported for the selected platform + La ejecución de pruebas en las fuentes proporcionadas no se admite para la plataforma seleccionada Failed to discover tests from assembly {0}. Reason:{1} - Failed to discover tests from assembly {0}. Reason:{1} + No se pudieron detectar pruebas desde el ensamblado {0}. Motivo:{1} File does not exist: {0} - File does not exist: {0} + El archivo no existe: {0} Test cleanup method '{0}.{1}' timed out after {2}ms - Test cleanup method '{0}.{1}' timed out after {2}ms + Método de limpieza de pruebas '{0}.{1}' se agotó el tiempo de espera después de {2}ms Test cleanup method '{0}.{1}' was canceled - Test cleanup method '{0}.{1}' was canceled + Método de limpieza de pruebas "{0}.{1}" se canceló TestContext cannot be Null. - TestContext cannot be Null. + TestContext no será null. TestContext Messages: - TestContext Messages: + Mensajes de TestContext: Test initialize method '{0}.{1}' timed out after {2}ms - Test initialize method '{0}.{1}' timed out after {2}ms + Método de inicialización de prueba '{0}.{1}' se agotó el tiempo de espera después de {2}ms Test initialize method '{0}.{1}' was canceled - Test initialize method '{0}.{1}' was canceled + Método de inicialización de prueba "{0}.{1}" se canceló Test method {0} was not found. - Test method {0} was not found. + No encontrado método prueba {0}. Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) - Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) + Probar paralelización habilitada para {0} (Trabajos: {1}, Ámbito: {2}) `Workers` is a setting name that shouldn't be localized. 'Scope' is a setting name that shouldn't be localized. @@ -362,53 +362,53 @@ but received {4} argument(s), with types '{5}'. Unable to load types from the test source '{0}'. Some or all of the tests in this source may not be discovered. Error: {1} - Unable to load types from the test source '{0}'. Some or all of the tests in this source may not be discovered. + No se pueden cargar tipos del origen de prueba "{0}". Puede que no se detecten algunas o ninguna de las pruebas de este origen. Error: {1} Assembly Cleanup method {0}.{1} failed. Error Message: {2}. StackTrace: {3} - Assembly Cleanup method {0}.{1} failed. Error Message: {2}. StackTrace: {3} + Error de método Cleanup de ensamblado {0}.{1}. Mensaje de error: {2}. StackTrace: {3} Assembly Initialization method {0}.{1} threw exception. {2}: {3}. Aborting test execution. - Assembly Initialization method {0}.{1} threw exception. {2}: {3}. Aborting test execution. + Excepción método inicialización ensamblado {0}.{1}. {2}: {3}. Anulada ejecución de prueba. Class Cleanup method {0}.{1} failed. Error Message: {2}. Stack Trace: {3} - Class Cleanup method {0}.{1} failed. Error Message: {2}. Stack Trace: {3} + Error de método Cleanup de clase {0}.{1}. Mensaje error: {2}. Seguimiento de pila: {3} Class Initialization method {0}.{1} threw exception. {2}: {3}. - Class Initialization method {0}.{1} threw exception. {2}: {3}. + Excepción del método inicialización clase {0}. {1}. {2}: {3}. Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. - Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + El método {0}.{1} tiene una firma incorrecta. El método debe ser estático, público, no devolver un valor y no aceptar ningún parámetro. Además, si está usando async-await en el método entonces el tipo de valor devuelto debe ser 'Task' o 'ValueTask'. Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should take a single parameter of type TestContext. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. - Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should take a single parameter of type TestContext. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + El método {0}.{1} tiene una firma incorrecta. El método debe ser estático, público, no devolver ningún valor y debe tomar un único parámetro de tipo TestContext. Además, si está usando async-await en el método entonces el tipo de valor devuelto debe ser 'Task' o 'ValueTask'. TestCleanup method {0}.{1} threw exception. {2}. - TestCleanup method {0}.{1} threw exception. {2}. + El método TestCleanup {0}.{1} devolvió una excepción. {2}. Error calling Test Cleanup method for test class {0}: {1} - Error calling Test Cleanup method for test class {0}: {1} + Error al llamar al método Test Cleanup para la clase de prueba {0}: {1} TestCleanup Stack Trace - TestCleanup Stack Trace + Seguimiento de pila de TestCleanup @@ -418,7 +418,7 @@ Error: {1} --- End of inner exception stack trace --- - --- End of inner exception stack trace --- + --- Fin del seguimiento de la pila de excepción interna --- @@ -428,163 +428,163 @@ Error: {1} UTA031: class {0} does not have valid TestContext property. TestContext must be of type TestContext, must be non-static, and must be public. For example: public TestContext TestContext. - UTA031: class {0} does not have valid TestContext property. TestContext must be of type TestContext, must be non-static, and must be public. For example: public TestContext TestContext. + UTA031: la clase {0}no tiene la propiedad TestContext válida. TestContext debe ser de tipo TestContext, debe ser no estática y debe ser pública. Por ejemplo: public TestContext TestContext. UTA007: Method {1} defined in class {0} does not have correct signature. Test method marked with the [TestMethod] attribute must be non-static, public, return-type as void and should not take any parameter. Example: public void Test.Class1.Test(). Additionally, if you are using async-await in test method then return-type must be 'Task' or 'ValueTask'. Example: public async Task Test.Class1.Test2() - UTA007: Method {1} defined in class {0} does not have correct signature. Test method marked with the [TestMethod] attribute must be non-static, public, return-type as void and should not take any parameter. Example: public void Test.Class1.Test(). Additionally, if you are using async-await in test method then return-type must be 'Task' or 'ValueTask'. Example: public async Task Test.Class1.Test2() + UTA007: El método {1} definido en la clase {0} no tiene la firma correcta. El método de prueba marcado con el atributo [TestMethod] debe ser no estático, público, con el tipo devuelto void y no debe tomar ningún parámetro. Ejemplo: public void Test.Class1.Test(). Además, si está usando async-await en el método de prueba, entonces el tipo de valor devuelto debe ser 'Task' o 'ValueTask'. Ejemplo: public async Task Test.Class1.Test2() UTA054: {0}.{1} has invalid Timeout attribute. The timeout must be an integer value greater than 0. - UTA054: {0}.{1} has invalid Timeout attribute. The timeout must be an integer value greater than 0. + UTA054: {0}.{1} tiene un atributo Timeout no válido. El tiempo de espera debe ser un valor entero mayor que 0. UTA014: {0}: Cannot define more than one method with the AssemblyCleanup attribute inside an assembly. - UTA014: {0}: Cannot define more than one method with the AssemblyCleanup attribute inside an assembly. + UTA014: {0}: No se puede definir más de un método con el atributo AssemblyCleanup dentro de un ensamblado. UTA013: {0}: Cannot define more than one method with the AssemblyInitialize attribute inside an assembly. - UTA013: {0}: Cannot define more than one method with the AssemblyInitialize attribute inside an assembly. + UTA013: {0}: No se puede definir más de un método con el atributo AssemblyInitialize dentro de un ensamblado. UTA026: {0}: Cannot define more than one method with the ClassCleanup attribute inside a class. - UTA026: {0}: Cannot define more than one method with the ClassCleanup attribute inside a class. + UTA026: {0}: No se puede definir más de un método con el atributo ClassCleanup dentro de una clase. UTA025: {0}: Cannot define more than one method with the ClassInitialize attribute inside a class. - UTA025: {0}: Cannot define more than one method with the ClassInitialize attribute inside a class. + UTA025: {0}: No se puede definir más de un método con el atributo ClassInitialize dentro de una clase. UTA024: {0}: Cannot define more than one method with the TestCleanup attribute. - UTA024: {0}: Cannot define more than one method with the TestCleanup attribute. + UTA024: {0}: No se puede definir más de un método con el atributo TestCleanup. UTA018: {0}: Cannot define more than one method with the TestInitialize attribute. - UTA018: {0}: Cannot define more than one method with the TestInitialize attribute. + UTA018: {0}: No se puede definir más de un método con el atributo TestInitialize. UTA001: TestClass attribute defined on non-public class {0} - UTA001: TestClass attribute defined on non-public class {0} + UTA001: se ha definido el atributo TestClass en la clase no pública {0} UTA023: {0}: Cannot define predefined property {2} on method {1}. - UTA023: {0}: Cannot define predefined property {2} on method {1}. + UTA023: {0}: no se puede definir la propiedad predefinida {2} en el método {1}. TestClass attribute defined on generic non-abstract class {0} - TestClass attribute defined on generic non-abstract class {0} + Atributo TestClass definido en una clase genérica no abstracta {0} UTA021: {0}: Null or empty custom property defined on method {1}. The custom property must have a valid name. - UTA021: {0}: Null or empty custom property defined on method {1}. The custom property must have a valid name. + UTA021: {0}: se ha definido una propiedad personalizada nula o vacía en el método {1}. La propiedad personalizada debe tener un nombre válido. An unhandled exception was thrown by the 'Execute' method. Please report this error to the author of the attribute '{0}'. {1} - An unhandled exception was thrown by the 'Execute' method. Please report this error to the author of the attribute '{0}'. + El método 'Execute' produjo una excepción no controlada. Notifique este error al autor del atributo ''{0}. {1} The ExpectedException attribute defined on test method {0}.{1} threw an exception during construction. {2} - The ExpectedException attribute defined on test method {0}.{1} threw an exception during construction. + El atributo ExpectedException definido en el método de prueba {0}.{1} inició una excepción durante la construcción. {2} Failed to obtain the exception thrown by test method {0}.{1}. - Failed to obtain the exception thrown by test method {0}.{1}. + No se pudo obtener la excepción iniciada por el método de prueba {0}.{1}. Initialization method {0}.{1} threw exception. {2}. - Initialization method {0}.{1} threw exception. {2}. + El método de inicialización {0}.{1} devolvió una excepción. {2}. Unable to create instance of class {0}. Error: {1}. - Unable to create instance of class {0}. Error: {1}. + No se puede crear una instancia de la clase {0}. Error: {1}. Method {0}.{1} does not exist. - Method {0}.{1} does not exist. + El método {0}.{1} no existe. The test method '{0}.{1}' has multiple attributes derived from '{2}' defined on it. Only one such attribute is allowed. - The test method '{0}.{1}' has multiple attributes derived from '{2}' defined on it. Only one such attribute is allowed. + El método de prueba '{0}.{1}' tiene varios atributos derivados de '{2}' definidos en él. Solo se permite un atributo de este tipo. Error in executing test. No result returned by extension. If using extension of TestMethodAttribute then please contact vendor. - Error in executing test. No result returned by extension. If using extension of TestMethodAttribute then please contact vendor. + No se pudo ejecutar prueba. Extensión no devolvió resultados. Si usa extensión TestMethodAttribute, contacte con el proveedor. Cannot find a valid constructor for test class '{0}'. Valid constructors are 'public' and either parameterless or with one parameter of type 'TestContext'. - Cannot find a valid constructor for test class '{0}'. Valid constructors are 'public' and either parameterless or with one parameter of type 'TestContext'. + No se encuentra un constructor válido para la clase de prueba '{0}'. Los constructores válidos son 'public' y sin parámetros o con un parámetro de tipo 'TestContext'. Unable to find property {0}.TestContext. Error:{1}. - Unable to find property {0}.TestContext. Error:{1}. + No se puede encontrar la propiedad {0}.TestContext. Error:{1}. Unable to set TestContext property for the class {0}. Error: {1}. - Unable to set TestContext property for the class {0}. Error: {1}. + No se puede establecer la propiedad TestContext para la clase {0}. Error: {1}. The {0}.TestContext has incorrect type. - The {0}.TestContext has incorrect type. + Tipo {0}.TestContext no es correcto. Method {0}.{1} has wrong signature. The method must be non-static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. - Method {0}.{1} has wrong signature. The method must be non-static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + El método {0}.{1} tiene una firma incorrecta. Debe ser un método no estático, público, no devolver ningún valor y no debe aceptar parámetros. Además, si está usando async-await en el método entonces el tipo de valor devuelto debe ser 'Task' o 'ValueTask'. Test method {0}.{1} threw exception: {2} - Test method {0}.{1} threw exception: + Excepción método de prueba {0}.{1}: {2} Unable to get type {0}. Error: {1}. - Unable to get type {0}. Error: {1}. + No se puede obtener el tipo {0}. Error: {1}. The called code threw an exception that was caught, but the exception value was null - The called code threw an exception that was caught, but the exception value was null + El código llamado produjo una excepción que se detectó, pero el valor de la excepción era null {0} For UWP projects, if you are using UI objects in test consider using [UITestMethod] attribute instead of [TestMethod] to execute test in UI thread. - {0} For UWP projects, if you are using UI objects in test consider using [UITestMethod] attribute instead of [TestMethod] to execute test in UI thread. + {0}. En proyectos de UWP, si usa objetos de interfaz de usuario en la prueba, podría usar el atributo [UITestMethod] en lugar de [TestMethod] para ejecutar la prueba en el subproceso de interfaz de usuario. (Failed to get the message for an exception of type {0} due to an exception.) - (Failed to get the message for an exception of type {0} due to an exception.) + (No se pudo obtener el mensaje para una excepción del tipo {0} debido a una excepción.) diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.fr.xlf b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.fr.xlf index d8ac2d32aa..d31b404ee2 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.fr.xlf +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.fr.xlf @@ -4,52 +4,52 @@ Assembly cleanup method '{0}.{1}' timed out after {2}ms - Assembly cleanup method '{0}.{1}' timed out after {2}ms + La méthode de nettoyage d’assembly « {0}.{1} » a expiré après {2}ms Assembly cleanup method '{0}.{1}' was canceled - Assembly cleanup method '{0}.{1}' was canceled + La méthode de nettoyage de l’assembly « {0}.{1} » a été annulée Assembly initialize method '{0}.{1}' timed out after {2}ms - Assembly initialize method '{0}.{1}' timed out after {2}ms + La méthode d'initialisation de l’assembly « {0}.{1} » a expiré après {2}ms Assembly initialize method '{0}.{1}' was canceled - Assembly initialize method '{0}.{1}' was canceled + La méthode d’initialisation de l’assembly « {0}.{1} » a été annulée MSTestAdapterV2 - MSTestAdapterV2 + MSTestAdapterV2 Exception occurred while enumerating IDataSource attribute on "{0}.{1}": {2} - Exception occurred while enumerating IDataSource attribute on "{0}.{1}": {2} + Une exception s’est produite lors de l’énumération de l’attribut IDataSource sur « {0}.{1} » : {2} {0}: TypeName with namespace, {1}: Method name, {2}: Exception details Exception occurred while expanding IDataSource rows from attribute on "{0}.{1}": {2} - Exception occurred while expanding IDataSource rows from attribute on "{0}.{1}": {2} + Une exception s’est produite lors du développement des lignes IDataSource à partir de l’attribut sur « {0}.{1} » : {2} {0}: TypeName with namespace, {1}: Method name, {2}: CannotExpandIDataSourceAttribute_DuplicateDisplayName or CannotExpandIDataSourceAttribute_CannotSerialize Data on index {0} for "{1}" cannot be serialized. All data provided through "IDataSource" should be serializable. If you need to test non-serializable data sources, please make sure you add "TestDataSourceDiscovery" attribute on your test assembly and set the discovery option to "DuringExecution". - Data on index {0} for "{1}" cannot be serialized. All data provided through "IDataSource" should be serializable. If you need to test non-serializable data sources, please make sure you add "TestDataSourceDiscovery" attribute on your test assembly and set the discovery option to "DuringExecution". + Impossible de sérialiser les données de l’index {0} pour « {1} ». Toutes les données fournies via « IDataSource » doivent être sérialisables. Si vous devez tester des sources de données non sérialisables, veillez à ajouter l’attribut « TestDataSourceDiscovery » à votre assembly de test et définissez l’option de découverte sur « DuringExecution ». {0}: Zero based index if an element inside of an array, {1}: Test name Display name "{2}" on indexes {0} and {1} are duplicate. Display names should be unique. - Display name "{2}" on indexes {0} and {1} are duplicate. Display names should be unique. + Le nom d’affichage « {2} » sur les index {0} et {1} est dupliqué. Les noms d’affichage doivent être uniques. {0}, {1}: Zero based index if an element inside of an array {2}: Test display name. @@ -69,27 +69,27 @@ but received {4} argument(s), with types '{5}'. Cannot run test method '{0}.{1}': Method has parameters, but does not define any test source. Use '[DataRow]', '[DynamicData]', or a custom 'ITestDataSource' data source to provide test data. - Cannot run test method '{0}.{1}': Method has parameters, but does not define any test source. Use '[DataRow]', '[DynamicData]', or a custom 'ITestDataSource' data source to provide test data. + Impossible d’exécuter la méthode de test « {0}.{1} » : la méthode a des paramètres, mais ne définit aucune source de test. Utilisez « [DataRow] », « [DynamicData] » ou une source de données « ITestDataSource » personnalisée pour fournir des données de test. Class cleanup method '{0}.{1}' timed out after {2}ms - Class cleanup method '{0}.{1}' timed out after {2}ms + La méthode de nettoyage de classe « {0}.{1} » a expiré après {2}ms Class cleanup method '{0}.{1}' was canceled - Class cleanup method '{0}.{1}' was canceled + La méthode de nettoyage de la classe « {0}.{1} » a été annulée Class initialize method '{0}.{1}' timed out after {2}ms - Class initialize method '{0}.{1}' timed out after {2}ms + La méthode d'initialisation de la classe « {0}.{1} » a expiré après {2}ms Class initialize method '{0}.{1}' was canceled - Class initialize method '{0}.{1}' was canceled + La méthode d’initialisation de la classe « {0}.{1} » a été annulée @@ -99,17 +99,17 @@ but received {4} argument(s), with types '{5}'. MSTestAdapter failed to discover tests in class '{0}' of assembly '{1}' because {2}. - MSTestAdapter failed to discover tests in class '{0}' of assembly '{1}' because {2}. + MSTestAdapter n'a pas découvert de tests dans la classe '{0}' de l'assembly '{1}', car {2}. {0} (Data Row {1}) - {0} (Data Row {1}) + {0} (ligne de données {1}) Debug Trace: - Debug Trace: + Trace du débogage : @@ -179,28 +179,28 @@ but received {4} argument(s), with types '{5}'. [MSTest][Discovery][{0}] {1} - [MSTest][Discovery][{0}] {1} + [MSTest][Discovery][{0}] {1} Both '.runsettings' and '.testconfig.json' files have been detected. Please select only one of these test configuration files. - Both '.runsettings' and '.testconfig.json' files have been detected. Please select only one of these test configuration files. + Les fichiers « .runsettings » et « .testconfig.json » ont été détectés. Veuillez sélectionner un seul de ces fichiers de configuration de test. {0}: {1} - {0}: {1} + {0} : {1} "{0}": (Failed to get exception description due to an exception of type "{1}". - "{0}": (Failed to get exception description due to an exception of type "{1}". + « {0} » : (Échec de l’obtention de la description de l’exception en raison d’une exception de type « {1} ». {0}: Type of the original exception that we're trying to get the description of. {1}: Thrown exception Exceptions thrown: - Exceptions thrown: + Exceptions levées/s : This is usually precedes by TestAssembly_AssemblyDiscoveryFailure message, and preceded by list of exceptions thrown in a test discovery session. @@ -215,7 +215,7 @@ but received {4} argument(s), with types '{5}'. Getting custom attributes for type {0} threw exception (will ignore and use the reflection way): {1} - Getting custom attributes for type {0} threw exception (will ignore and use the reflection way): {1} + L’obtention d’attributs personnalisés pour le type {0} a levé une exception (ignorera et utilisera la méthode de réflexion) : {1} {0}: Attribute full type name. {1}: Exception description @@ -236,22 +236,22 @@ but received {4} argument(s), with types '{5}'. Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. - Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. + Valeur non valide '{0}' spécifiée pour la 'ClassCleanupLifecycle'. Les portées prises en charge sont {1}. 'ClassCleanupLifecycle' is a setting name that shouldn't be localized. Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. - Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. + Valeur non valide '{0}' spécifiée pour la 'Portée'. Les portées prises en charge sont {1}. 'Scope' is a setting name that shouldn't be localized. Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. - Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. + Valeur non valide '{0}' spécifiée pour 'Workers'. La valeur doit être un entier non négatif. `Workers` is a setting name that shouldn't be localized. Invalid settings '{0}'. Unexpected XmlAttribute: '{1}'. - Invalid settings '{0}'. Unexpected XmlAttribute: '{1}'. + Paramètres non valides '{0}'. XmlAttribute inattendu : '{1}'. @@ -261,7 +261,7 @@ but received {4} argument(s), with types '{5}'. Invalid settings '{0}'. Unexpected XmlElement: '{1}'. - Invalid settings '{0}'. Unexpected XmlElement: '{1}'. + Paramètres non valides '{0}'. XmlElement inattendu : '{1}'. @@ -271,12 +271,12 @@ but received {4} argument(s), with types '{5}'. Invalid value '{0}' for runsettings entry '{1}', setting will be ignored. - Invalid value '{0}' for runsettings entry '{1}', setting will be ignored. + Valeur non valide '{0}' pour l’entrée runsettings '{1}', le paramètre sera ignoré. Warning : A testsettings file or a vsmdi file is not supported with the MSTest V2 Adapter. - Warning : A testsettings file or a vsmdi file is not supported with the MSTest V2 Adapter. + Avertissement : L'adaptateur MSTest V2 ne prend pas en charge les fichiers testsettings ou vsmdi. @@ -291,67 +291,67 @@ but received {4} argument(s), with types '{5}'. An older version of MSTestV2 package is loaded in assembly, test discovery might fail to discover all data tests if they depend on `.runsettings` file. - An older version of MSTestV2 package is loaded in assembly, test discovery might fail to discover all data tests if they depend on `.runsettings` file. + Une version antérieure du package MSTestV2 est chargée dans l’assembly. La découverte de tests risque de ne pas découvrir tous les tests de données s’ils dépendent du fichier '.runsettings'. Runsettings entry '<ExecutionApartmentState>STA</ExecutionApartmentState>' is not supported on non-Windows OSes. - Runsettings entry '<ExecutionApartmentState>STA</ExecutionApartmentState>' is not supported on non-Windows OSes. + L’entrée Runsettings « <ExecutionApartmentState>STA</ExecutionApartmentState> » n’est pas prise en charge sur les systèmes d’exploitation non Windows. Running tests in any of the provided sources is not supported for the selected platform - Running tests in any of the provided sources is not supported for the selected platform + L'exécution de tests dans l'une des sources fournies n'est pas prise en charge pour la plateforme sélectionnée Failed to discover tests from assembly {0}. Reason:{1} - Failed to discover tests from assembly {0}. Reason:{1} + Échec de la découverte de tests à partir de l'assembly {0}. Raison :{1} File does not exist: {0} - File does not exist: {0} + Fichier inexistant : {0} Test cleanup method '{0}.{1}' timed out after {2}ms - Test cleanup method '{0}.{1}' timed out after {2}ms + La méthode de nettoyage de test « {0}.{1} » a expiré après {2}ms Test cleanup method '{0}.{1}' was canceled - Test cleanup method '{0}.{1}' was canceled + La méthode de nettoyage du test « {0}.{1} » a été annulée TestContext cannot be Null. - TestContext cannot be Null. + TestContext ne peut pas être null. TestContext Messages: - TestContext Messages: + Messages TestContext : Test initialize method '{0}.{1}' timed out after {2}ms - Test initialize method '{0}.{1}' timed out after {2}ms + La méthode d’initialisation de test « {0}.{1} » a expiré après {2}ms Test initialize method '{0}.{1}' was canceled - Test initialize method '{0}.{1}' was canceled + La méthode d’initialisation du test « {0}.{1} » a été annulée Test method {0} was not found. - Test method {0} was not found. + Méthode de test {0} introuvable. Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) - Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) + Parallélisation des tests activée pour {0} (Workers : {1}, Étendue : {2}). `Workers` is a setting name that shouldn't be localized. 'Scope' is a setting name that shouldn't be localized. @@ -362,28 +362,28 @@ but received {4} argument(s), with types '{5}'. Unable to load types from the test source '{0}'. Some or all of the tests in this source may not be discovered. Error: {1} - Unable to load types from the test source '{0}'. Some or all of the tests in this source may not be discovered. -Error: {1} + Impossible de charger les types à partir de la source de tests '{0}'. Une partie ou l'ensemble des tests de cette source ne peuvent pas être découverts. +Erreur : {1} Assembly Cleanup method {0}.{1} failed. Error Message: {2}. StackTrace: {3} - Assembly Cleanup method {0}.{1} failed. Error Message: {2}. StackTrace: {3} + La méthode Cleanup d'assembly {0}.{1} a échoué. Message d'erreur : {2}. StackTrace : {3} Assembly Initialization method {0}.{1} threw exception. {2}: {3}. Aborting test execution. - Assembly Initialization method {0}.{1} threw exception. {2}: {3}. Aborting test execution. + La méthode d'assembly Initialization {0}.{1} a levé une exception. {2} : {3}. Abandon de l'exécution de tests. Class Cleanup method {0}.{1} failed. Error Message: {2}. Stack Trace: {3} - Class Cleanup method {0}.{1} failed. Error Message: {2}. Stack Trace: {3} + La méthode de classe Cleanup {0}.{1} a échoué. Message d'erreur : {2}. Trace de la pile : {3} Class Initialization method {0}.{1} threw exception. {2}: {3}. - Class Initialization method {0}.{1} threw exception. {2}: {3}. + La méthode de classe Initialization {0}.{1} a levé une exception. {2} : {3}. @@ -398,17 +398,17 @@ Error: {1} TestCleanup method {0}.{1} threw exception. {2}. - TestCleanup method {0}.{1} threw exception. {2}. + La méthode TestCleanup {0}.{1} a levé une exception. {2}. Error calling Test Cleanup method for test class {0}: {1} - Error calling Test Cleanup method for test class {0}: {1} + Erreur lors de l'appel de la méthode Test Cleanup pour la classe de test {0} : {1} TestCleanup Stack Trace - TestCleanup Stack Trace + Trace de la pile TestCleanup @@ -418,7 +418,7 @@ Error: {1} --- End of inner exception stack trace --- - --- End of inner exception stack trace --- + --- Fin de la trace de la pile d'exception interne --- @@ -428,7 +428,7 @@ Error: {1} UTA031: class {0} does not have valid TestContext property. TestContext must be of type TestContext, must be non-static, and must be public. For example: public TestContext TestContext. - UTA031: class {0} does not have valid TestContext property. TestContext must be of type TestContext, must be non-static, and must be public. For example: public TestContext TestContext. + UTA031 : la classe {0} n'a pas de propriété TestContext valide. TestContext doit être de type TestContext, doit être non statique et doit être public. Par exemple : public TestContext TestContext. @@ -438,57 +438,57 @@ Error: {1} UTA054: {0}.{1} has invalid Timeout attribute. The timeout must be an integer value greater than 0. - UTA054: {0}.{1} has invalid Timeout attribute. The timeout must be an integer value greater than 0. + UTA054 : {0}.{1}possède un attribut de délai d’expiration non valide. Le délai d’expiration doit être un nombre entier supérieur à 0. UTA014: {0}: Cannot define more than one method with the AssemblyCleanup attribute inside an assembly. - UTA014: {0}: Cannot define more than one method with the AssemblyCleanup attribute inside an assembly. + UTA014 : {0} : impossible de définir plus d'une méthode avec l'attribut AssemblyCleanup à l'intérieur d'un assembly. UTA013: {0}: Cannot define more than one method with the AssemblyInitialize attribute inside an assembly. - UTA013: {0}: Cannot define more than one method with the AssemblyInitialize attribute inside an assembly. + UTA013 : {0} : impossible de définir plus d'une méthode avec l'attribut AssemblyInitialize à l'intérieur d'un assembly. UTA026: {0}: Cannot define more than one method with the ClassCleanup attribute inside a class. - UTA026: {0}: Cannot define more than one method with the ClassCleanup attribute inside a class. + UTA026 : {0} : impossible de définir plus d'une méthode avec l'attribut ClassCleanup à l'intérieur d'une classe. UTA025: {0}: Cannot define more than one method with the ClassInitialize attribute inside a class. - UTA025: {0}: Cannot define more than one method with the ClassInitialize attribute inside a class. + UTA025 : {0} : impossible de définir plus d'une méthode avec l'attribut ClassInitialize à l'intérieur d'une classe. UTA024: {0}: Cannot define more than one method with the TestCleanup attribute. - UTA024: {0}: Cannot define more than one method with the TestCleanup attribute. + UTA024 : {0} : impossible de définir plus d'une méthode avec l'attribut TestCleanup. UTA018: {0}: Cannot define more than one method with the TestInitialize attribute. - UTA018: {0}: Cannot define more than one method with the TestInitialize attribute. + UTA018 : {0} : impossible de définir plus d'une méthode avec l'attribut TestInitialize. UTA001: TestClass attribute defined on non-public class {0} - UTA001: TestClass attribute defined on non-public class {0} + UTA001 : attribut TestClass défini sur la classe non publique {0} UTA023: {0}: Cannot define predefined property {2} on method {1}. - UTA023: {0}: Cannot define predefined property {2} on method {1}. + UTA023 : {0} : Impossible de définir la propriété prédéfinie {2} sur la méthode {1}. TestClass attribute defined on generic non-abstract class {0} - TestClass attribute defined on generic non-abstract class {0} + Attribut TestClass défini sur une classe non abstraite générique {0} UTA021: {0}: Null or empty custom property defined on method {1}. The custom property must have a valid name. - UTA021: {0}: Null or empty custom property defined on method {1}. The custom property must have a valid name. + UTA021 : {0} : Une propriété null ou vide personnalisée est définie sur la méthode {1}. La propriété personnalisée doit posséder un nom valide. @@ -501,58 +501,58 @@ Error: {1} The ExpectedException attribute defined on test method {0}.{1} threw an exception during construction. {2} - The ExpectedException attribute defined on test method {0}.{1} threw an exception during construction. + L'attribut ExpectedException défini dans la méthode de test {0}.{1} a levé une exception durant la construction. {2} Failed to obtain the exception thrown by test method {0}.{1}. - Failed to obtain the exception thrown by test method {0}.{1}. + Échec de l'obtention de l'exception levée par la méthode de test {0}.{1}. Initialization method {0}.{1} threw exception. {2}. - Initialization method {0}.{1} threw exception. {2}. + La méthode Initialization {0}.{1} a levé une exception. {2}. Unable to create instance of class {0}. Error: {1}. - Unable to create instance of class {0}. Error: {1}. + Impossible de créer une instance de la classe {0}. Erreur : {1}. Method {0}.{1} does not exist. - Method {0}.{1} does not exist. + La méthode {0}.{1} n'existe pas. The test method '{0}.{1}' has multiple attributes derived from '{2}' defined on it. Only one such attribute is allowed. - The test method '{0}.{1}' has multiple attributes derived from '{2}' defined on it. Only one such attribute is allowed. + La méthode de test « {0}.{1} » possède plusieurs attributs dérivés de « {2} » qui lui sont définis. Un seul attribut de ce type est autorisé. Error in executing test. No result returned by extension. If using extension of TestMethodAttribute then please contact vendor. - Error in executing test. No result returned by extension. If using extension of TestMethodAttribute then please contact vendor. + Erreur lors de l'exécution du test. L'extension n'a retourné aucun résultat. Si vous utilisez l'extension de TestMethodAttribute, contactez le fournisseur. Cannot find a valid constructor for test class '{0}'. Valid constructors are 'public' and either parameterless or with one parameter of type 'TestContext'. - Cannot find a valid constructor for test class '{0}'. Valid constructors are 'public' and either parameterless or with one parameter of type 'TestContext'. + Impossible de trouver un constructeur valide pour la classe de test « {0} ». Les constructeurs valides sont « publics » et sans paramètre ou avec un paramètre de type « TestContext ». Unable to find property {0}.TestContext. Error:{1}. - Unable to find property {0}.TestContext. Error:{1}. + Propriété {0}.TestContext introuvable. Erreur :{1}. Unable to set TestContext property for the class {0}. Error: {1}. - Unable to set TestContext property for the class {0}. Error: {1}. + Impossible de définir la propriété TestContext pour la classe {0}. Erreur : {1}. The {0}.TestContext has incorrect type. - The {0}.TestContext has incorrect type. + {0}.TestContext possède un type incorrect. @@ -563,28 +563,28 @@ Error: {1} Test method {0}.{1} threw exception: {2} - Test method {0}.{1} threw exception: + La méthode de test {0}.{1} a levé une exception : {2} Unable to get type {0}. Error: {1}. - Unable to get type {0}. Error: {1}. + Impossible d'obtenir le type {0}. Erreur : {1}. The called code threw an exception that was caught, but the exception value was null - The called code threw an exception that was caught, but the exception value was null + Le code appelé a levé une exception qui a été interceptée, mais la valeur de l’exception était nul {0} For UWP projects, if you are using UI objects in test consider using [UITestMethod] attribute instead of [TestMethod] to execute test in UI thread. - {0} For UWP projects, if you are using UI objects in test consider using [UITestMethod] attribute instead of [TestMethod] to execute test in UI thread. + {0} Pour les projets UWP, si vous utilisez des objets d'IU dans un test, utilisez l'attribut [UITestMethod] à la place de [TestMethod] pour exécuter le test dans le thread d'interface utilisateur. (Failed to get the message for an exception of type {0} due to an exception.) - (Failed to get the message for an exception of type {0} due to an exception.) + (Échec de la réception du message pour une exception de type {0} en raison d'une exception.) diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.it.xlf b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.it.xlf index 891ff8ed7d..dbe79e38f9 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.it.xlf +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.it.xlf @@ -4,52 +4,52 @@ Assembly cleanup method '{0}.{1}' timed out after {2}ms - Assembly cleanup method '{0}.{1}' timed out after {2}ms + Metodo di pulizia dell’assembly '{0}. Time out di {1}' dopo {2} ms Assembly cleanup method '{0}.{1}' was canceled - Assembly cleanup method '{0}.{1}' was canceled + Il metodo di pulizia dell'assembly "{0}.{1}" è stato annullato Assembly initialize method '{0}.{1}' timed out after {2}ms - Assembly initialize method '{0}.{1}' timed out after {2}ms + Metodo di inizializzazione dell'assembly '{0}. Timeout di {1}' dopo {2} ms Assembly initialize method '{0}.{1}' was canceled - Assembly initialize method '{0}.{1}' was canceled + Il metodo di inizializzazione dell'assembly "{0}.{1}" è stato annullato MSTestAdapterV2 - MSTestAdapterV2 + MSTestAdapterV2 Exception occurred while enumerating IDataSource attribute on "{0}.{1}": {2} - Exception occurred while enumerating IDataSource attribute on "{0}.{1}": {2} + Si è verificata un'eccezione durante l'enumerazione dell'attributo IDataSource in "{0}.{1}": {2} {0}: TypeName with namespace, {1}: Method name, {2}: Exception details Exception occurred while expanding IDataSource rows from attribute on "{0}.{1}": {2} - Exception occurred while expanding IDataSource rows from attribute on "{0}.{1}": {2} + Si è verificata un'eccezione durante l'espansione delle righe IDataSource dall'attributo in "{0}.{1}": {2} {0}: TypeName with namespace, {1}: Method name, {2}: CannotExpandIDataSourceAttribute_DuplicateDisplayName or CannotExpandIDataSourceAttribute_CannotSerialize Data on index {0} for "{1}" cannot be serialized. All data provided through "IDataSource" should be serializable. If you need to test non-serializable data sources, please make sure you add "TestDataSourceDiscovery" attribute on your test assembly and set the discovery option to "DuringExecution". - Data on index {0} for "{1}" cannot be serialized. All data provided through "IDataSource" should be serializable. If you need to test non-serializable data sources, please make sure you add "TestDataSourceDiscovery" attribute on your test assembly and set the discovery option to "DuringExecution". + Non è possibile serializzare i dati nell'indice {0} per "{1}". Tutti i dati forniti tramite "IDataSource" devono essere serializzabili. Se è necessario testare origini dati non serializzabili, assicurarsi di aggiungere l'attributo "TestDataSourceDiscovery" nell'assembly di test e impostare l'opzione di individuazione su "DuringExecution". {0}: Zero based index if an element inside of an array, {1}: Test name Display name "{2}" on indexes {0} and {1} are duplicate. Display names should be unique. - Display name "{2}" on indexes {0} and {1} are duplicate. Display names should be unique. + Il nome visualizzato "{2}" negli indici {0} e {1} è duplicato. I nomi visualizzati devono essere univoci. {0}, {1}: Zero based index if an element inside of an array {2}: Test display name. @@ -69,27 +69,27 @@ but received {4} argument(s), with types '{5}'. Cannot run test method '{0}.{1}': Method has parameters, but does not define any test source. Use '[DataRow]', '[DynamicData]', or a custom 'ITestDataSource' data source to provide test data. - Cannot run test method '{0}.{1}': Method has parameters, but does not define any test source. Use '[DataRow]', '[DynamicData]', or a custom 'ITestDataSource' data source to provide test data. + Impossibile eseguire il metodo di test "{0}.{1}": il metodo contiene parametri, ma non definisce alcuna origine test. Usare "[DataRow]", "[DynamicData]" o un'origine dati "ITestDataSource" personalizzata per fornire i dati del test. Class cleanup method '{0}.{1}' timed out after {2}ms - Class cleanup method '{0}.{1}' timed out after {2}ms + Time out del metodo di pulizia della classe '{0}. Time out di {1}' dopo {2} ms Class cleanup method '{0}.{1}' was canceled - Class cleanup method '{0}.{1}' was canceled + Il metodo di pulizia della classe "{0}.{1}" è stato annullato Class initialize method '{0}.{1}' timed out after {2}ms - Class initialize method '{0}.{1}' timed out after {2}ms + Metodo di inizializzazione della classe '{0}. Timeout di {1}' dopo {2} ms Class initialize method '{0}.{1}' was canceled - Class initialize method '{0}.{1}' was canceled + Il metodo di inizializzazione della classe "{0}.{1}" è stato annullato @@ -99,17 +99,17 @@ but received {4} argument(s), with types '{5}'. MSTestAdapter failed to discover tests in class '{0}' of assembly '{1}' because {2}. - MSTestAdapter failed to discover tests in class '{0}' of assembly '{1}' because {2}. + MSTestAdapter non è riuscito a individuare test nella classe '{0}' dell'assembly '{1}' perché {2}. {0} (Data Row {1}) - {0} (Data Row {1}) + {0} (riga dati {1}) Debug Trace: - Debug Trace: + Traccia di debug: @@ -179,28 +179,28 @@ but received {4} argument(s), with types '{5}'. [MSTest][Discovery][{0}] {1} - [MSTest][Discovery][{0}] {1} + [MSTest][Individuazione][{0}] {1} Both '.runsettings' and '.testconfig.json' files have been detected. Please select only one of these test configuration files. - Both '.runsettings' and '.testconfig.json' files have been detected. Please select only one of these test configuration files. + Sono stati rilevati sia i file '.runsettings' sia '.testconfig.json'. Selezionare solo uno di questi file di configurazione di test. {0}: {1} - {0}: {1} + {0}: {1} "{0}": (Failed to get exception description due to an exception of type "{1}". - "{0}": (Failed to get exception description due to an exception of type "{1}". + "{0}": (non è stato possibile ottenere la descrizione dell'eccezione a causa di un'eccezione di tipo "{1}". {0}: Type of the original exception that we're trying to get the description of. {1}: Thrown exception Exceptions thrown: - Exceptions thrown: + Eccezioni generate: This is usually precedes by TestAssembly_AssemblyDiscoveryFailure message, and preceded by list of exceptions thrown in a test discovery session. @@ -215,7 +215,7 @@ but received {4} argument(s), with types '{5}'. Getting custom attributes for type {0} threw exception (will ignore and use the reflection way): {1} - Getting custom attributes for type {0} threw exception (will ignore and use the reflection way): {1} + Il recupero degli attributi personalizzati per il tipo {0} ha generato un'eccezione (verrà ignorata e verrà usata la modalità reflection): {1} {0}: Attribute full type name. {1}: Exception description @@ -236,22 +236,22 @@ but received {4} argument(s), with types '{5}'. Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. - Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. + Il valore '{0}', specificato per 'ClassCleanupLifecycle', non è valido. I valori supportati per Scope sono {1}. 'ClassCleanupLifecycle' is a setting name that shouldn't be localized. Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. - Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. + Il valore '{0}', specificato per 'Scope', non è valido. I valori supportati per Scope sono {1}. 'Scope' is a setting name that shouldn't be localized. Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. - Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. + Il valore '{0}', specificato per 'Workers', non è valido. Il valore deve essere un numero intero non negativo. `Workers` is a setting name that shouldn't be localized. Invalid settings '{0}'. Unexpected XmlAttribute: '{1}'. - Invalid settings '{0}'. Unexpected XmlAttribute: '{1}'. + Le impostazioni '{0}' non sono valide. Elemento XmlAttribute imprevisto: '{1}'. @@ -261,7 +261,7 @@ but received {4} argument(s), with types '{5}'. Invalid settings '{0}'. Unexpected XmlElement: '{1}'. - Invalid settings '{0}'. Unexpected XmlElement: '{1}'. + Le impostazioni '{0}' non sono valide. Elemento XmlElement imprevisto: '{1}'. @@ -271,12 +271,12 @@ but received {4} argument(s), with types '{5}'. Invalid value '{0}' for runsettings entry '{1}', setting will be ignored. - Invalid value '{0}' for runsettings entry '{1}', setting will be ignored. + Valore non valido '{0}' per la voce runsettings '{1}'. L'impostazione verrà ignorata. Warning : A testsettings file or a vsmdi file is not supported with the MSTest V2 Adapter. - Warning : A testsettings file or a vsmdi file is not supported with the MSTest V2 Adapter. + Avviso: con l'adattatore MSTest V2 non è possibile usare un file testsettings o un file vsmdi. @@ -291,67 +291,67 @@ but received {4} argument(s), with types '{5}'. An older version of MSTestV2 package is loaded in assembly, test discovery might fail to discover all data tests if they depend on `.runsettings` file. - An older version of MSTestV2 package is loaded in assembly, test discovery might fail to discover all data tests if they depend on `.runsettings` file. + Nell'assembly è caricata una versione precedente del pacchetto MSTestV2. L'individuazione dei test potrebbe non riuscire a individuare tutti i test dei dati se dipendono dal file '.runsettings'. Runsettings entry '<ExecutionApartmentState>STA</ExecutionApartmentState>' is not supported on non-Windows OSes. - Runsettings entry '<ExecutionApartmentState>STA</ExecutionApartmentState>' is not supported on non-Windows OSes. + La voce Runsettings '<ExecutionApartmentState>STA</ExecutionApartmentState>' non è supportata nei sistemi operativi non Windows. Running tests in any of the provided sources is not supported for the selected platform - Running tests in any of the provided sources is not supported for the selected platform + L'esecuzione di test in una delle origini specificate non è supportata per la piattaforma selezionata Failed to discover tests from assembly {0}. Reason:{1} - Failed to discover tests from assembly {0}. Reason:{1} + Non è stato possibile individuare i test dall'assembly {0}. Motivo: {1} File does not exist: {0} - File does not exist: {0} + Il file {0} non esiste Test cleanup method '{0}.{1}' timed out after {2}ms - Test cleanup method '{0}.{1}' timed out after {2}ms + Time out del metodo di pulizia della classe dei test '{0}. Time out di {1}' dopo {2} ms Test cleanup method '{0}.{1}' was canceled - Test cleanup method '{0}.{1}' was canceled + Il metodo di pulizia del test "{0}.{1}" è stato annullato TestContext cannot be Null. - TestContext cannot be Null. + TestContext non può essere Null. TestContext Messages: - TestContext Messages: + Messaggi di TestContext: Test initialize method '{0}.{1}' timed out after {2}ms - Test initialize method '{0}.{1}' timed out after {2}ms + Metodo di inizializzazione del test '{0}. Timeout di {1}' dopo {2} ms Test initialize method '{0}.{1}' was canceled - Test initialize method '{0}.{1}' was canceled + Il metodo di inizializzazione del test "{0}.{1}" è stato annullato Test method {0} was not found. - Test method {0} was not found. + Il metodo di test {0} non è stato trovato. Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) - Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) + Parallelizzazione test abilitata per {0} (Processi di lavoro: {1}. Ambito: {2}). `Workers` is a setting name that shouldn't be localized. 'Scope' is a setting name that shouldn't be localized. @@ -362,53 +362,53 @@ but received {4} argument(s), with types '{5}'. Unable to load types from the test source '{0}'. Some or all of the tests in this source may not be discovered. Error: {1} - Unable to load types from the test source '{0}'. Some or all of the tests in this source may not be discovered. -Error: {1} + Non è possibile caricare i tipi dall'origine test '{0}'. È possibile che alcuni o tutti i test non siano stati individuati in questa origine. +Errore: {1} Assembly Cleanup method {0}.{1} failed. Error Message: {2}. StackTrace: {3} - Assembly Cleanup method {0}.{1} failed. Error Message: {2}. StackTrace: {3} + Il metodo di pulizia assembly {0}.{1} non è riuscito. Messaggio di errore: {2}. Analisi dello stack: {3} Assembly Initialization method {0}.{1} threw exception. {2}: {3}. Aborting test execution. - Assembly Initialization method {0}.{1} threw exception. {2}: {3}. Aborting test execution. + Il metodo di inizializzazione assembly {0}.{1} ha generato un'eccezione. {2}: {3}. L'esecuzione del test verrà interrotta. Class Cleanup method {0}.{1} failed. Error Message: {2}. Stack Trace: {3} - Class Cleanup method {0}.{1} failed. Error Message: {2}. Stack Trace: {3} + Il metodo di pulizia classi {0}.{1} non è riuscito. Messaggio di errore: {2}. Analisi dello stack: {3} Class Initialization method {0}.{1} threw exception. {2}: {3}. - Class Initialization method {0}.{1} threw exception. {2}: {3}. + Il metodo di inizializzazione classi {0}.{1} ha generato un'eccezione. {2}: {3}. Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. - Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + La firma del metodo {0}.{1}non è corretta. Il metodo deve essere statico e pubblico, non deve restituire un valore né accettare parametri. Se inoltre si usa async-await nel metodo di test, il tipo restituito deve essere 'Task' o 'ValueTask'. Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should take a single parameter of type TestContext. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. - Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should take a single parameter of type TestContext. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + La firma del metodo {0}.{1}non è corretta. Il metodo deve essere statico e pubblico, non deve restituire un valore e deve accettare un singolo parametro di tipo TestContext. Se inoltre si usa async-await nel metodo di test, il tipo restituito deve essere 'Task' o 'ValueTask'. TestCleanup method {0}.{1} threw exception. {2}. - TestCleanup method {0}.{1} threw exception. {2}. + Il metodo TestCleanup {0}.{1} ha generato un'eccezione. {2}. Error calling Test Cleanup method for test class {0}: {1} - Error calling Test Cleanup method for test class {0}: {1} + Si è verificato un errore durante la chiamata del metodo TestCleanup per la classe di test {0}: {1} TestCleanup Stack Trace - TestCleanup Stack Trace + Analisi dello stato di TestCleanup @@ -418,7 +418,7 @@ Error: {1} --- End of inner exception stack trace --- - --- End of inner exception stack trace --- + --- Fine dell'analisi dello stack dell'eccezione interna --- @@ -428,67 +428,67 @@ Error: {1} UTA031: class {0} does not have valid TestContext property. TestContext must be of type TestContext, must be non-static, and must be public. For example: public TestContext TestContext. - UTA031: class {0} does not have valid TestContext property. TestContext must be of type TestContext, must be non-static, and must be public. For example: public TestContext TestContext. + UTA031: la classe {0} non dispone di una proprietà TestContext valida. La proprietà TestContext deve essere di tipo TestContext, non deve essere statica e deve essere pubblica. Ad esempio: public TestContext TestContext. UTA007: Method {1} defined in class {0} does not have correct signature. Test method marked with the [TestMethod] attribute must be non-static, public, return-type as void and should not take any parameter. Example: public void Test.Class1.Test(). Additionally, if you are using async-await in test method then return-type must be 'Task' or 'ValueTask'. Example: public async Task Test.Class1.Test2() - UTA007: Method {1} defined in class {0} does not have correct signature. Test method marked with the [TestMethod] attribute must be non-static, public, return-type as void and should not take any parameter. Example: public void Test.Class1.Test(). Additionally, if you are using async-await in test method then return-type must be 'Task' or 'ValueTask'. Example: public async Task Test.Class1.Test2() + UTA007: la firma del metodo {1} definito nella classe {0} non è corretta. Il metodo di test contrassegnato con l'attributo [TestMethod] deve essere pubblico e non statico, non deve accettare parametri e deve includere un tipo restituito void. Esempio: public void Test.Class1.Test(). Se inoltre nel metodo di test si usa async-await, il tipo restituito deve essere 'Task' o 'ValueTask'. Esempio: public async Task Test.Class1.Test2() UTA054: {0}.{1} has invalid Timeout attribute. The timeout must be an integer value greater than 0. - UTA054: {0}.{1} has invalid Timeout attribute. The timeout must be an integer value greater than 0. + UTA054: {0}.{1} ha un attributo Timeout non valido. Il timeout deve essere un valore intero maggiore di 0. UTA014: {0}: Cannot define more than one method with the AssemblyCleanup attribute inside an assembly. - UTA014: {0}: Cannot define more than one method with the AssemblyCleanup attribute inside an assembly. + UTA014: {0}: non è possibile definire più di un metodo con l'attributo AssemblyCleanup all'interno di un assembly. UTA013: {0}: Cannot define more than one method with the AssemblyInitialize attribute inside an assembly. - UTA013: {0}: Cannot define more than one method with the AssemblyInitialize attribute inside an assembly. + UTA013: {0}: non è possibile definire più di un metodo con l'attributo AssemblyInitialize all'interno di un assembly. UTA026: {0}: Cannot define more than one method with the ClassCleanup attribute inside a class. - UTA026: {0}: Cannot define more than one method with the ClassCleanup attribute inside a class. + UTA026: {0}: non è possibile definire più di un metodo con l'attributo ClassCleanup all'interno di una classe. UTA025: {0}: Cannot define more than one method with the ClassInitialize attribute inside a class. - UTA025: {0}: Cannot define more than one method with the ClassInitialize attribute inside a class. + UTA025: {0}: non è possibile definire più di un metodo con l'attributo ClassInitialize all'interno di una classe. UTA024: {0}: Cannot define more than one method with the TestCleanup attribute. - UTA024: {0}: Cannot define more than one method with the TestCleanup attribute. + UTA024: {0}: non è possibile definire più di un metodo con l'attributo TestCleanup. UTA018: {0}: Cannot define more than one method with the TestInitialize attribute. - UTA018: {0}: Cannot define more than one method with the TestInitialize attribute. + UTA018: {0}: non è possibile definire più di un metodo con l'attributo TestInitialize. UTA001: TestClass attribute defined on non-public class {0} - UTA001: TestClass attribute defined on non-public class {0} + UTA001: è stato definito l'attributo TestClass per la classe non pubblica {0} UTA023: {0}: Cannot define predefined property {2} on method {1}. - UTA023: {0}: Cannot define predefined property {2} on method {1}. + UTA023: {0}: non è possibile definire la proprietà predefinita {2} per il metodo {1}. TestClass attribute defined on generic non-abstract class {0} - TestClass attribute defined on generic non-abstract class {0} + Attributo TestClass definito nella classe generica non astratta {0} UTA021: {0}: Null or empty custom property defined on method {1}. The custom property must have a valid name. - UTA021: {0}: Null or empty custom property defined on method {1}. The custom property must have a valid name. + UTA021: {0}: per il metodo {1} è stata definita una proprietà personalizzata Null o vuota. Specificare un nome valido per la proprietà personalizzata. @@ -501,90 +501,90 @@ Error: {1} The ExpectedException attribute defined on test method {0}.{1} threw an exception during construction. {2} - The ExpectedException attribute defined on test method {0}.{1} threw an exception during construction. + L'attributo ExpectedException definito nel metodo di test {0}.{1} ha generato un'eccezione durante la costruzione. {2} Failed to obtain the exception thrown by test method {0}.{1}. - Failed to obtain the exception thrown by test method {0}.{1}. + Non è stato possibile ottenere l'eccezione generata dal metodo di test {0}.{1}. Initialization method {0}.{1} threw exception. {2}. - Initialization method {0}.{1} threw exception. {2}. + Il metodo di inizializzazione {0}.{1} ha generato un'eccezione. {2}. Unable to create instance of class {0}. Error: {1}. - Unable to create instance of class {0}. Error: {1}. + Non è possibile creare un'istanza della classe {0}. Errore: {1}. Method {0}.{1} does not exist. - Method {0}.{1} does not exist. + Il metodo {0}.{1} non esiste. The test method '{0}.{1}' has multiple attributes derived from '{2}' defined on it. Only one such attribute is allowed. - The test method '{0}.{1}' has multiple attributes derived from '{2}' defined on it. Only one such attribute is allowed. + Il metodo di test '{0}.{1}' contiene più attributi derivati da '{2}' definito in esso. È consentito solo uno di tali attributi. Error in executing test. No result returned by extension. If using extension of TestMethodAttribute then please contact vendor. - Error in executing test. No result returned by extension. If using extension of TestMethodAttribute then please contact vendor. + Si è verificato un errore durante l'esecuzione del test. L'estensione non ha restituito alcun risultato. Se si usa l'estensione di TestMethodAttribute, contattare il fornitore. Cannot find a valid constructor for test class '{0}'. Valid constructors are 'public' and either parameterless or with one parameter of type 'TestContext'. - Cannot find a valid constructor for test class '{0}'. Valid constructors are 'public' and either parameterless or with one parameter of type 'TestContext'. + Impossibile trovare un costruttore valido per la classe di test '{0}'. I costruttori validi sono 'public' e senza parametri o con un parametro di tipo 'TestContext'. Unable to find property {0}.TestContext. Error:{1}. - Unable to find property {0}.TestContext. Error:{1}. + La proprietà {0}.TestContext non è stata trovata. Errore: {1}. Unable to set TestContext property for the class {0}. Error: {1}. - Unable to set TestContext property for the class {0}. Error: {1}. + Non è possibile impostare la proprietà TestContext per la classe {0}. Errore: {1}. The {0}.TestContext has incorrect type. - The {0}.TestContext has incorrect type. + Il tipo di {0}.TestContext non è corretto. Method {0}.{1} has wrong signature. The method must be non-static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. - Method {0}.{1} has wrong signature. The method must be non-static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + La firma del metodo {0}.{1}non è corretta. Il metodo deve essere non statico e pubblico, non deve restituire un valore né accettare parametri. Se inoltre si usa async-await nel metodo di test, il tipo restituito deve essere 'Task' o 'ValueTask'. Test method {0}.{1} threw exception: {2} - Test method {0}.{1} threw exception: + Il metodo di test {0}.{1} ha generato un'eccezione: {2} Unable to get type {0}. Error: {1}. - Unable to get type {0}. Error: {1}. + Non è possibile ottenere il tipo {0}. Errore: {1}. The called code threw an exception that was caught, but the exception value was null - The called code threw an exception that was caught, but the exception value was null + Il codice chiamato ha generato un'eccezione che è stata rilevata, ma il valore dell'eccezione è Null {0} For UWP projects, if you are using UI objects in test consider using [UITestMethod] attribute instead of [TestMethod] to execute test in UI thread. - {0} For UWP projects, if you are using UI objects in test consider using [UITestMethod] attribute instead of [TestMethod] to execute test in UI thread. + {0}. Se, per i progetti della piattaforma UWP, nel test si usano oggetti dell'interfaccia utente, provare a specificare l'attributo [UITestMethod] invece di [TestMethod] per eseguire il test nel thread di UI. (Failed to get the message for an exception of type {0} due to an exception.) - (Failed to get the message for an exception of type {0} due to an exception.) + Non è stato possibile ottenere il messaggio per un'eccezione di tipo {0} a causa di un'eccezione. diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.ja.xlf b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.ja.xlf index 4172147805..c1cf893a9f 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.ja.xlf +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.ja.xlf @@ -4,52 +4,52 @@ Assembly cleanup method '{0}.{1}' timed out after {2}ms - Assembly cleanup method '{0}.{1}' timed out after {2}ms + アセンブリ クリーンアップ メソッド '{0}.{1}' が {2}ms 後にタイムアウトしました Assembly cleanup method '{0}.{1}' was canceled - Assembly cleanup method '{0}.{1}' was canceled + アセンブリ クリーンアップ メソッド '{0}.{1}' が取り消されました Assembly initialize method '{0}.{1}' timed out after {2}ms - Assembly initialize method '{0}.{1}' timed out after {2}ms + アセンブリ初期化メソッド '{0}.{1}' が {2}ms 後にタイムアウトになりました Assembly initialize method '{0}.{1}' was canceled - Assembly initialize method '{0}.{1}' was canceled + アセンブリ初期化メソッド '{0}.{1}' が取り消されました MSTestAdapterV2 - MSTestAdapterV2 + MSTestAdapterV2 Exception occurred while enumerating IDataSource attribute on "{0}.{1}": {2} - Exception occurred while enumerating IDataSource attribute on "{0}.{1}": {2} + "{0}.{1}" で IDataSource 属性を列挙中に例外が発生しました: {2} {0}: TypeName with namespace, {1}: Method name, {2}: Exception details Exception occurred while expanding IDataSource rows from attribute on "{0}.{1}": {2} - Exception occurred while expanding IDataSource rows from attribute on "{0}.{1}": {2} + "{0}.{1}" の属性から IDataSource 行を展開中に例外が発生しました: {2} {0}: TypeName with namespace, {1}: Method name, {2}: CannotExpandIDataSourceAttribute_DuplicateDisplayName or CannotExpandIDataSourceAttribute_CannotSerialize Data on index {0} for "{1}" cannot be serialized. All data provided through "IDataSource" should be serializable. If you need to test non-serializable data sources, please make sure you add "TestDataSourceDiscovery" attribute on your test assembly and set the discovery option to "DuringExecution". - Data on index {0} for "{1}" cannot be serialized. All data provided through "IDataSource" should be serializable. If you need to test non-serializable data sources, please make sure you add "TestDataSourceDiscovery" attribute on your test assembly and set the discovery option to "DuringExecution". + "{1}" のインデックス {0} のデータをシリアル化できません。"IDataSource" を介して提供されるすべてのデータはシリアル化可能である必要があります。シリアル化できないデータ ソースをテストする必要がある場合は、テスト アセンブリに "TestDataSourceDiscovery" 属性を追加し、検出オプションを "DuringExecution" に設定してください。 {0}: Zero based index if an element inside of an array, {1}: Test name Display name "{2}" on indexes {0} and {1} are duplicate. Display names should be unique. - Display name "{2}" on indexes {0} and {1} are duplicate. Display names should be unique. + インデックス {0} と {1} の表示名 "{2}" が重複しています。表示名は一意である必要があります。 {0}, {1}: Zero based index if an element inside of an array {2}: Test display name. @@ -69,27 +69,27 @@ but received {4} argument(s), with types '{5}'. Cannot run test method '{0}.{1}': Method has parameters, but does not define any test source. Use '[DataRow]', '[DynamicData]', or a custom 'ITestDataSource' data source to provide test data. - Cannot run test method '{0}.{1}': Method has parameters, but does not define any test source. Use '[DataRow]', '[DynamicData]', or a custom 'ITestDataSource' data source to provide test data. + テスト メソッド '{0} を実行できません。{1}': メソッドにはパラメーターがありますが、テスト ソースは定義されていません。'[DataRow]'、'[DynamicData]'、カスタムの 'ITestDataSource' データ ソースを使用して、テスト データを提供します。 Class cleanup method '{0}.{1}' timed out after {2}ms - Class cleanup method '{0}.{1}' timed out after {2}ms + クラス クリーンアップ メソッド '{0}.{1}' が {2}ms 後にタイムアウトしました Class cleanup method '{0}.{1}' was canceled - Class cleanup method '{0}.{1}' was canceled + クラス クリーンアップ メソッド '{0}.{1}' が取り消されました Class initialize method '{0}.{1}' timed out after {2}ms - Class initialize method '{0}.{1}' timed out after {2}ms + クラス初期化メソッド '{0}.{1}' が {2}ms 後にタイムアウトになりました Class initialize method '{0}.{1}' was canceled - Class initialize method '{0}.{1}' was canceled + クラス初期化メソッド '{0}.{1}' が取り消されました @@ -99,17 +99,17 @@ but received {4} argument(s), with types '{5}'. MSTestAdapter failed to discover tests in class '{0}' of assembly '{1}' because {2}. - MSTestAdapter failed to discover tests in class '{0}' of assembly '{1}' because {2}. + MSTestAdapter でアセンブリ '{1}' のクラス '{0}' にテストが見つかりませんでした。理由 {2}。 {0} (Data Row {1}) - {0} (Data Row {1}) + {0} (データ行 {1}) Debug Trace: - Debug Trace: + デバッグ トレース: @@ -179,28 +179,28 @@ but received {4} argument(s), with types '{5}'. [MSTest][Discovery][{0}] {1} - [MSTest][Discovery][{0}] {1} + [MSTest][Discovery][{0}] {1} Both '.runsettings' and '.testconfig.json' files have been detected. Please select only one of these test configuration files. - Both '.runsettings' and '.testconfig.json' files have been detected. Please select only one of these test configuration files. + '.runsettings' ファイルと '.testconfig.json' ファイルの両方が検出されました。これらのテスト構成ファイルのいずれか 1 つだけを選択してください。 {0}: {1} - {0}: {1} + {0}: {1} "{0}": (Failed to get exception description due to an exception of type "{1}". - "{0}": (Failed to get exception description due to an exception of type "{1}". + "{0}": (種類が "{1}"の例外のため、例外の説明を取得できませんでした。 {0}: Type of the original exception that we're trying to get the description of. {1}: Thrown exception Exceptions thrown: - Exceptions thrown: + スローされた例外: This is usually precedes by TestAssembly_AssemblyDiscoveryFailure message, and preceded by list of exceptions thrown in a test discovery session. @@ -215,7 +215,7 @@ but received {4} argument(s), with types '{5}'. Getting custom attributes for type {0} threw exception (will ignore and use the reflection way): {1} - Getting custom attributes for type {0} threw exception (will ignore and use the reflection way): {1} + 型 {0} のカスタム属性を取得中に例外がスローされました (無視してリフレクションの方法を使用します): {1} {0}: Attribute full type name. {1}: Exception description @@ -236,22 +236,22 @@ but received {4} argument(s), with types '{5}'. Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. - Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. + 'ClassCleanupLifecycle' に無効な値 '{0}' が指定されました。サポートされているスコープは {1} です。 'ClassCleanupLifecycle' is a setting name that shouldn't be localized. Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. - Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. + 無効な値 '{0}' が 'Scope' に指定されました。サポートされているスコープは {1} です。 'Scope' is a setting name that shouldn't be localized. Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. - Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. + 無効な値 '{0}' が 'Workers' に指定されました。値は負ではない整数である必要があります。 `Workers` is a setting name that shouldn't be localized. Invalid settings '{0}'. Unexpected XmlAttribute: '{1}'. - Invalid settings '{0}'. Unexpected XmlAttribute: '{1}'. + 設定 '{0}' は無効です。予期しない XmlAttribute: '{1}'。 @@ -261,7 +261,7 @@ but received {4} argument(s), with types '{5}'. Invalid settings '{0}'. Unexpected XmlElement: '{1}'. - Invalid settings '{0}'. Unexpected XmlElement: '{1}'. + 設定 '{0}' は無効です。予期しない XmlElement: '{1}'。 @@ -271,12 +271,12 @@ but received {4} argument(s), with types '{5}'. Invalid value '{0}' for runsettings entry '{1}', setting will be ignored. - Invalid value '{0}' for runsettings entry '{1}', setting will be ignored. + runsettings エントリ '{1}' の値 '{0}' は無効です。設定は無視されます。 Warning : A testsettings file or a vsmdi file is not supported with the MSTest V2 Adapter. - Warning : A testsettings file or a vsmdi file is not supported with the MSTest V2 Adapter. + 警告: testsettings ファイル、vsmdi ファイルは MSTest V2 アダプターではサポートされていません。 @@ -291,67 +291,67 @@ but received {4} argument(s), with types '{5}'. An older version of MSTestV2 package is loaded in assembly, test discovery might fail to discover all data tests if they depend on `.runsettings` file. - An older version of MSTestV2 package is loaded in assembly, test discovery might fail to discover all data tests if they depend on `.runsettings` file. + 古いバージョンの MSTestV2 パッケージがアセンブリに読み込まれています。`.runsettings` ファイルに依存している場合、テスト検出ですべてのデータ テストを検出できない可能性があります。 Runsettings entry '<ExecutionApartmentState>STA</ExecutionApartmentState>' is not supported on non-Windows OSes. - Runsettings entry '<ExecutionApartmentState>STA</ExecutionApartmentState>' is not supported on non-Windows OSes. + Runsettings エントリ '<ExecutionApartmentState>STA</ExecutionApartmentState>' は、Windows OS 以外ではサポートされていません。 Running tests in any of the provided sources is not supported for the selected platform - Running tests in any of the provided sources is not supported for the selected platform + 指定されたソースのいずれかでのテストの実行は、選択されたプラットフォームでサポートされていません Failed to discover tests from assembly {0}. Reason:{1} - Failed to discover tests from assembly {0}. Reason:{1} + アセンブリ {0} からテストを検出できませんでした。理由:{1} File does not exist: {0} - File does not exist: {0} + ファイルが存在しません: {0} Test cleanup method '{0}.{1}' timed out after {2}ms - Test cleanup method '{0}.{1}' timed out after {2}ms + テスト クリーンアップ メソッド '{0}.{1}' が {2}ms 後にタイムアウトしました Test cleanup method '{0}.{1}' was canceled - Test cleanup method '{0}.{1}' was canceled + テスト クリーンアップ メソッド '{0}.{1}' が取り消されました TestContext cannot be Null. - TestContext cannot be Null. + TestContext を Null にすることはできません。 TestContext Messages: - TestContext Messages: + TestContext メッセージ: Test initialize method '{0}.{1}' timed out after {2}ms - Test initialize method '{0}.{1}' timed out after {2}ms + テスト初期化メソッド '{0}.{1}' が {2}ms 後にタイムアウトになりました Test initialize method '{0}.{1}' was canceled - Test initialize method '{0}.{1}' was canceled + テスト初期化メソッド '{0}.{1}' が取り消されました Test method {0} was not found. - Test method {0} was not found. + テスト メソッド {0} が見つかりませんでした。 Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) - Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) + {0} でテスト並列処理が有効にされています (Workers: {1}、Scope: {2})。 `Workers` is a setting name that shouldn't be localized. 'Scope' is a setting name that shouldn't be localized. @@ -362,53 +362,53 @@ but received {4} argument(s), with types '{5}'. Unable to load types from the test source '{0}'. Some or all of the tests in this source may not be discovered. Error: {1} - Unable to load types from the test source '{0}'. Some or all of the tests in this source may not be discovered. -Error: {1} + テスト ソース '{0}' から型を読み込むことができません。このソース内の一部またはすべてのテストが見つからない可能性があります。 +エラー: {1} Assembly Cleanup method {0}.{1} failed. Error Message: {2}. StackTrace: {3} - Assembly Cleanup method {0}.{1} failed. Error Message: {2}. StackTrace: {3} + アセンブリ クリーンアップ メソッド {0}.{1} に失敗しました。エラー メッセージ: {2}。スタック トレース: {3} Assembly Initialization method {0}.{1} threw exception. {2}: {3}. Aborting test execution. - Assembly Initialization method {0}.{1} threw exception. {2}: {3}. Aborting test execution. + アセンブリ初期化メソッド {0}.{1} は例外をスローしました。{2}: {3}。テストの実行を中止しています。 Class Cleanup method {0}.{1} failed. Error Message: {2}. Stack Trace: {3} - Class Cleanup method {0}.{1} failed. Error Message: {2}. Stack Trace: {3} + クラス クリーンアップ メソッド {0}.{1} に失敗しました。エラー メッセージ: {2}。スタック トレース: {3} Class Initialization method {0}.{1} threw exception. {2}: {3}. - Class Initialization method {0}.{1} threw exception. {2}: {3}. + クラス初期化メソッド {0}.{1} は例外をスローしました。{2}: {3}。 Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. - Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + メソッド {0}。{1} は不適切なシグネチャを含んでいます。メソッドは static および public である必要があり、値を返しません。また、パラメーターを受け取ることはできません。また、メソッドで async-await を使用している場合、戻り値の型は 'Task' または 'ValueTask' である必要があります。 Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should take a single parameter of type TestContext. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. - Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should take a single parameter of type TestContext. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + メソッド {0}。{1} は不適切なシグネチャを含んでいます。メソッドは static および public である必要があり、値を返しません。また、TestContext 型の 1 つのパラメーターを受け取る必要があります。また、メソッドで async-await を使用している場合、戻り値の型は 'Task' または 'ValueTask' である必要があります。 TestCleanup method {0}.{1} threw exception. {2}. - TestCleanup method {0}.{1} threw exception. {2}. + TestCleanup メソッド {0}.{1} は例外をスローしました。{2}。 Error calling Test Cleanup method for test class {0}: {1} - Error calling Test Cleanup method for test class {0}: {1} + テスト クラス {0} のテスト クリーンアップ メソッドの呼び出しでエラーが発生しました: {1} TestCleanup Stack Trace - TestCleanup Stack Trace + TestCleanup スタック トレース @@ -418,7 +418,7 @@ Error: {1} --- End of inner exception stack trace --- - --- End of inner exception stack trace --- + --- 内部例外スタック トレースの終わり --- @@ -428,67 +428,67 @@ Error: {1} UTA031: class {0} does not have valid TestContext property. TestContext must be of type TestContext, must be non-static, and must be public. For example: public TestContext TestContext. - UTA031: class {0} does not have valid TestContext property. TestContext must be of type TestContext, must be non-static, and must be public. For example: public TestContext TestContext. + UTA031: クラス {0} に有効な TestContext プロパティがありません。TestContext は TestContext 型で、非静的である必要があり、public である必要があります。たとえば、public TestContext TestContext です。 UTA007: Method {1} defined in class {0} does not have correct signature. Test method marked with the [TestMethod] attribute must be non-static, public, return-type as void and should not take any parameter. Example: public void Test.Class1.Test(). Additionally, if you are using async-await in test method then return-type must be 'Task' or 'ValueTask'. Example: public async Task Test.Class1.Test2() - UTA007: Method {1} defined in class {0} does not have correct signature. Test method marked with the [TestMethod] attribute must be non-static, public, return-type as void and should not take any parameter. Example: public void Test.Class1.Test(). Additionally, if you are using async-await in test method then return-type must be 'Task' or 'ValueTask'. Example: public async Task Test.Class1.Test2() + UTA007: クラス {0} で定義されているメソッド {1} に適切なシグネチャが含まれていません。[TestMethod] 属性でマークされたテスト メソッドは、non-static および public である必要があり、戻り値の型は void である必要があります。また、パラメーターを受け取ることはできません。例: public void Test.Class1.Test()。また、テスト メソッドで async-await を使用している場合、戻り値の型は 'Task' または 'ValueTask' である必要があります。例: public async Task Test.Class1.Test2() UTA054: {0}.{1} has invalid Timeout attribute. The timeout must be an integer value greater than 0. - UTA054: {0}.{1} has invalid Timeout attribute. The timeout must be an integer value greater than 0. + UTA054: {0}。{1} に無効な Timeout 属性があります。タイムアウトには、0 より大きい整数値を指定する必要があります。 UTA014: {0}: Cannot define more than one method with the AssemblyCleanup attribute inside an assembly. - UTA014: {0}: Cannot define more than one method with the AssemblyCleanup attribute inside an assembly. + UTA014: {0}: 1 つのアセンブリ内で、AssemblyCleanup 属性を伴う 2 つ以上のメソッドを定義することはできません。 UTA013: {0}: Cannot define more than one method with the AssemblyInitialize attribute inside an assembly. - UTA013: {0}: Cannot define more than one method with the AssemblyInitialize attribute inside an assembly. + UTA013: {0}: 1 つのアセンブリ内で、AssemblyInitialize 属性を伴う 2 つ以上のメソッドを定義することはできません。 UTA026: {0}: Cannot define more than one method with the ClassCleanup attribute inside a class. - UTA026: {0}: Cannot define more than one method with the ClassCleanup attribute inside a class. + UTA026: {0}: 1 つのクラス内で、ClassCleanup 属性を伴う 2 つ以上のメソッドを定義することはできません。 UTA025: {0}: Cannot define more than one method with the ClassInitialize attribute inside a class. - UTA025: {0}: Cannot define more than one method with the ClassInitialize attribute inside a class. + UTA025: {0}: 1 つのクラス内で、ClassInitialize 属性を伴う 2 つ以上のメソッドを定義することはできません。 UTA024: {0}: Cannot define more than one method with the TestCleanup attribute. - UTA024: {0}: Cannot define more than one method with the TestCleanup attribute. + UTA024: {0}: TestCleanup 属性を伴う 2 つ以上のメソッドを定義することはできません。 UTA018: {0}: Cannot define more than one method with the TestInitialize attribute. - UTA018: {0}: Cannot define more than one method with the TestInitialize attribute. + UTA018: {0}: TestInitialize 属性を伴う 2 つ以上のメソッドを定義することはできません。 UTA001: TestClass attribute defined on non-public class {0} - UTA001: TestClass attribute defined on non-public class {0} + UTA001: TestClass 属性がパブリックでないクラス {0} で定義されています UTA023: {0}: Cannot define predefined property {2} on method {1}. - UTA023: {0}: Cannot define predefined property {2} on method {1}. + UTA023: {0}: メソッド {1} 上の以前に定義されたプロパティ {2} を定義することはできません。 TestClass attribute defined on generic non-abstract class {0} - TestClass attribute defined on generic non-abstract class {0} + 汎用の非抽象クラス {0}で定義された TestClass 属性 UTA021: {0}: Null or empty custom property defined on method {1}. The custom property must have a valid name. - UTA021: {0}: Null or empty custom property defined on method {1}. The custom property must have a valid name. + UTA021: {0}: Null または空のカスタム プロパティが、メソッド {1} で定義されています。カスタム プロパティには有効な名前を指定しなければなりません。 @@ -501,90 +501,90 @@ Error: {1} The ExpectedException attribute defined on test method {0}.{1} threw an exception during construction. {2} - The ExpectedException attribute defined on test method {0}.{1} threw an exception during construction. + テスト メソッド {0}.{1} に定義されている ExpectedException 属性が、作成中に例外をスローしました。 {2} Failed to obtain the exception thrown by test method {0}.{1}. - Failed to obtain the exception thrown by test method {0}.{1}. + テスト メソッド {0}.{1} によってスローされた例外を取得できませんでした。 Initialization method {0}.{1} threw exception. {2}. - Initialization method {0}.{1} threw exception. {2}. + 初期化メソッド {0}.{1} は例外をスローしました。{2}。 Unable to create instance of class {0}. Error: {1}. - Unable to create instance of class {0}. Error: {1}. + クラス {0} のインスタンスを作成できません。エラー: {1}。 Method {0}.{1} does not exist. - Method {0}.{1} does not exist. + メソッド {0}.{1} は存在しません。 The test method '{0}.{1}' has multiple attributes derived from '{2}' defined on it. Only one such attribute is allowed. - The test method '{0}.{1}' has multiple attributes derived from '{2}' defined on it. Only one such attribute is allowed. + テスト メソッド '{0}.{1}' には、 '{2}' から派生した属性が複数定義されています。このような属性は 1 つしか許可されません。 Error in executing test. No result returned by extension. If using extension of TestMethodAttribute then please contact vendor. - Error in executing test. No result returned by extension. If using extension of TestMethodAttribute then please contact vendor. + テストの実行中にエラーが発生しました。拡張から結果が返されませんでした。TestMethodAttribute の拡張クラスを使用している場合は、ベンダーに連絡してください。 Cannot find a valid constructor for test class '{0}'. Valid constructors are 'public' and either parameterless or with one parameter of type 'TestContext'. - Cannot find a valid constructor for test class '{0}'. Valid constructors are 'public' and either parameterless or with one parameter of type 'TestContext'. + テスト クラス '{0}' の有効なコンストラクターが見つかりません。有効なコンストラクターは、'public' で、パラメーターがないもの、または 'TestContext' 型のパラメーター 1 個を取るものです。 Unable to find property {0}.TestContext. Error:{1}. - Unable to find property {0}.TestContext. Error:{1}. + プロパティ {0}.TestContext が見つかりません。エラー: {1}。 Unable to set TestContext property for the class {0}. Error: {1}. - Unable to set TestContext property for the class {0}. Error: {1}. + クラス {0} の TestContext プロパティを設定できません。エラー: {1}。 The {0}.TestContext has incorrect type. - The {0}.TestContext has incorrect type. + {0}.TestContext は不適切な型を含んでいます。 Method {0}.{1} has wrong signature. The method must be non-static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. - Method {0}.{1} has wrong signature. The method must be non-static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + メソッド {0}。{1} は不適切なシグネチャを含んでいます。メソッドは non-static および public である必要があり、値を返しません。また、パラメーターを受け取ることはできません。また、メソッドで async-await を使用している場合、戻り値の型は 'Task' または 'ValueTask' である必要があります。 Test method {0}.{1} threw exception: {2} - Test method {0}.{1} threw exception: + テスト メソッド {0}.{1} が例外をスローしました: {2} Unable to get type {0}. Error: {1}. - Unable to get type {0}. Error: {1}. + 型 {0} を取得できません。エラー: {1}。 The called code threw an exception that was caught, but the exception value was null - The called code threw an exception that was caught, but the exception value was null + 呼び出されたコードはキャッチされた例外をスローしましたが、例外値が null でした {0} For UWP projects, if you are using UI objects in test consider using [UITestMethod] attribute instead of [TestMethod] to execute test in UI thread. - {0} For UWP projects, if you are using UI objects in test consider using [UITestMethod] attribute instead of [TestMethod] to execute test in UI thread. + {0} UWP プロジェクトについて、テスト内で UI オブジェクトを使用している場合は、[TestMethod] の代わりに [UITestMethod] 属性を使用して UI スレッド内でテストを実行することを検討してください。 (Failed to get the message for an exception of type {0} due to an exception.) - (Failed to get the message for an exception of type {0} due to an exception.) + (例外が発生したため、型 {0} の例外のメッセージを取得できませんでした。) diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.ko.xlf b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.ko.xlf index fece671f18..8a68f5f803 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.ko.xlf +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.ko.xlf @@ -4,52 +4,52 @@ Assembly cleanup method '{0}.{1}' timed out after {2}ms - Assembly cleanup method '{0}.{1}' timed out after {2}ms + {2}밀리초 후 어셈블리 정리 메서드 '{0}.{1}'이(가) 시간 초과되었습니다. Assembly cleanup method '{0}.{1}' was canceled - Assembly cleanup method '{0}.{1}' was canceled + 어셈블리 정리 메서드 '{0}.{1}'이(가) 취소되었습니다. Assembly initialize method '{0}.{1}' timed out after {2}ms - Assembly initialize method '{0}.{1}' timed out after {2}ms + {2}밀리초 후 '{0}.{1}' 어셈블리 초기화 메서드의 시간이 초과되었습니다. Assembly initialize method '{0}.{1}' was canceled - Assembly initialize method '{0}.{1}' was canceled + 어셈블리 초기화 메서드 '{0}.{1}'(이)가 취소되었습니다. MSTestAdapterV2 - MSTestAdapterV2 + MSTestAdapterV2 Exception occurred while enumerating IDataSource attribute on "{0}.{1}": {2} - Exception occurred while enumerating IDataSource attribute on "{0}.{1}": {2} + "{0}.{1}"에서 IDataSource 특성을 열거하는 동안 예외가 발생했습니다. {2} {0}: TypeName with namespace, {1}: Method name, {2}: Exception details Exception occurred while expanding IDataSource rows from attribute on "{0}.{1}": {2} - Exception occurred while expanding IDataSource rows from attribute on "{0}.{1}": {2} + "{0}.{1}"의 특성에서 IDataSource 행을 확장하는 동안 예외가 발생했습니다. {2} {0}: TypeName with namespace, {1}: Method name, {2}: CannotExpandIDataSourceAttribute_DuplicateDisplayName or CannotExpandIDataSourceAttribute_CannotSerialize Data on index {0} for "{1}" cannot be serialized. All data provided through "IDataSource" should be serializable. If you need to test non-serializable data sources, please make sure you add "TestDataSourceDiscovery" attribute on your test assembly and set the discovery option to "DuringExecution". - Data on index {0} for "{1}" cannot be serialized. All data provided through "IDataSource" should be serializable. If you need to test non-serializable data sources, please make sure you add "TestDataSourceDiscovery" attribute on your test assembly and set the discovery option to "DuringExecution". + "{1}"에 대한 {0} 인덱스의 데이터를 직렬화할 수 없습니다. "IDataSource"를 통해 제공된 모든 데이터를 직렬화할 수 있어야 합니다. 직렬화할 수 없는 데이터 원본을 테스트해야 하는 경우 테스트 어셈블리에 "TestDataSourceDiscovery" 특성을 추가하고 검색 옵션을 "DuringExecution"으로 설정하세요. {0}: Zero based index if an element inside of an array, {1}: Test name Display name "{2}" on indexes {0} and {1} are duplicate. Display names should be unique. - Display name "{2}" on indexes {0} and {1} are duplicate. Display names should be unique. + {0} 및 {1} 인덱스의 "{2}" 표시 이름이 중복됩니다. 표시 이름은 고유해야 합니다. {0}, {1}: Zero based index if an element inside of an array {2}: Test display name. @@ -69,27 +69,27 @@ but received {4} argument(s), with types '{5}'. Cannot run test method '{0}.{1}': Method has parameters, but does not define any test source. Use '[DataRow]', '[DynamicData]', or a custom 'ITestDataSource' data source to provide test data. - Cannot run test method '{0}.{1}': Method has parameters, but does not define any test source. Use '[DataRow]', '[DynamicData]', or a custom 'ITestDataSource' data source to provide test data. + 테스트 메서드 '{0}{1}'을(를) 실행할 수 없음: 메서드에 매개 변수가 있지만 테스트 원본을 정의하지 않습니다. '[DataRow]', '[DynamicData]' 또는 사용자 지정 'ITestDataSource' 데이터 원본을 사용하여 테스트 데이터를 제공합니다. Class cleanup method '{0}.{1}' timed out after {2}ms - Class cleanup method '{0}.{1}' timed out after {2}ms + {2}밀리초 후 클래스 정리 메서드 '{0}.{1}'이(가) 시간 초과되었습니다. Class cleanup method '{0}.{1}' was canceled - Class cleanup method '{0}.{1}' was canceled + 클래스 정리 메서드 '{0}.{1}'이(가) 취소되었습니다. Class initialize method '{0}.{1}' timed out after {2}ms - Class initialize method '{0}.{1}' timed out after {2}ms + {2}밀리초 후 '{0}.{1}' 클래스 초기화 메서드의 시간이 초과되었습니다. Class initialize method '{0}.{1}' was canceled - Class initialize method '{0}.{1}' was canceled + '클래스 초기화 메서드 '{0}.{1}'이(가) 취소되었습니다. @@ -99,17 +99,17 @@ but received {4} argument(s), with types '{5}'. MSTestAdapter failed to discover tests in class '{0}' of assembly '{1}' because {2}. - MSTestAdapter failed to discover tests in class '{0}' of assembly '{1}' because {2}. + MSTestAdapter가 {2} 때문에 어셈블리 '{1}'의 클래스 '{0}'에서 테스트를 검색하지 못했습니다. {0} (Data Row {1}) - {0} (Data Row {1}) + {0}(데이터 행 {1}) Debug Trace: - Debug Trace: + 디버그 추적: @@ -179,28 +179,28 @@ but received {4} argument(s), with types '{5}'. [MSTest][Discovery][{0}] {1} - [MSTest][Discovery][{0}] {1} + [MSTest][검색][{0}] {1} Both '.runsettings' and '.testconfig.json' files have been detected. Please select only one of these test configuration files. - Both '.runsettings' and '.testconfig.json' files have been detected. Please select only one of these test configuration files. + '.runsettings' 및 '.testconfig.json' 파일이 모두 검색되었습니다. 이러한 테스트 구성 파일 중 하나만 선택하세요. {0}: {1} - {0}: {1} + {0}: {1} "{0}": (Failed to get exception description due to an exception of type "{1}". - "{0}": (Failed to get exception description due to an exception of type "{1}". + "{0}": ("{1}" 형식의 예외로 인해 예외 설명을 가져오지 못했습니다. {0}: Type of the original exception that we're trying to get the description of. {1}: Thrown exception Exceptions thrown: - Exceptions thrown: + 예외 발생: This is usually precedes by TestAssembly_AssemblyDiscoveryFailure message, and preceded by list of exceptions thrown in a test discovery session. @@ -215,7 +215,7 @@ but received {4} argument(s), with types '{5}'. Getting custom attributes for type {0} threw exception (will ignore and use the reflection way): {1} - Getting custom attributes for type {0} threw exception (will ignore and use the reflection way): {1} + {0} 형식에 대한 사용자 지정 특성을 가져오는 데 예외가 발생했습니다(무시하고 리플렉션 방법 사용). {1} {0}: Attribute full type name. {1}: Exception description @@ -236,22 +236,22 @@ but received {4} argument(s), with types '{5}'. Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. - Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. + 'ClassCleanupLifecycle'에 대해 '{0}' 잘못된 값이 지정되었습니다. 지원되는 범위는 {1}입니다. 'ClassCleanupLifecycle' is a setting name that shouldn't be localized. Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. - Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. + 'Scope'에 대해 잘못된 값 '{0}'이(가) 지정되었습니다. 지원되는 범위는 {1}입니다. 'Scope' is a setting name that shouldn't be localized. Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. - Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. + 'Workers'에 대해 잘못된 값 '{0}'이(가) 지정되었습니다. 이 값은 음수가 아닌 정수여야 합니다. `Workers` is a setting name that shouldn't be localized. Invalid settings '{0}'. Unexpected XmlAttribute: '{1}'. - Invalid settings '{0}'. Unexpected XmlAttribute: '{1}'. + '{0}' 설정이 잘못되었습니다. 예기치 않은 XmlAttribute '{1}'이(가) 있습니다. @@ -261,7 +261,7 @@ but received {4} argument(s), with types '{5}'. Invalid settings '{0}'. Unexpected XmlElement: '{1}'. - Invalid settings '{0}'. Unexpected XmlElement: '{1}'. + '{0}' 설정이 잘못되었습니다. 예기치 않은 XmlElement '{1}'이(가) 있습니다. @@ -271,12 +271,12 @@ but received {4} argument(s), with types '{5}'. Invalid value '{0}' for runsettings entry '{1}', setting will be ignored. - Invalid value '{0}' for runsettings entry '{1}', setting will be ignored. + runsettings 항목 '{1}'에 대해 '{0}' 값이 잘못되었습니다. 설정은 무시됩니다. Warning : A testsettings file or a vsmdi file is not supported with the MSTest V2 Adapter. - Warning : A testsettings file or a vsmdi file is not supported with the MSTest V2 Adapter. + 경고: MSTest V2 어댑터에서는 testsettings 파일 또는 vsmdi 파일이 지원되지 않습니다. @@ -291,67 +291,67 @@ but received {4} argument(s), with types '{5}'. An older version of MSTestV2 package is loaded in assembly, test discovery might fail to discover all data tests if they depend on `.runsettings` file. - An older version of MSTestV2 package is loaded in assembly, test discovery might fail to discover all data tests if they depend on `.runsettings` file. + 이전 버전 MSTestV2 패키지가 어셈블리에 로드되어 테스트 검색이 '.runsettings' 파일에 종속된 경우 모든 데이터 테스트를 검색하지 못할 수 있습니다. Runsettings entry '<ExecutionApartmentState>STA</ExecutionApartmentState>' is not supported on non-Windows OSes. - Runsettings entry '<ExecutionApartmentState>STA</ExecutionApartmentState>' is not supported on non-Windows OSes. + Runsettings 항목 '<ExecutionApartmentState>STA</ExecutionApartmentState>'는 Windows 이외의 OS에서는 지원되지 않습니다. Running tests in any of the provided sources is not supported for the selected platform - Running tests in any of the provided sources is not supported for the selected platform + 선택된 플랫폼의 경우 제공된 소스에서 테스트를 실행할 수 없습니다. Failed to discover tests from assembly {0}. Reason:{1} - Failed to discover tests from assembly {0}. Reason:{1} + 어셈블리 {0}에서 테스트를 검색하지 못했습니다. 이유:{1} File does not exist: {0} - File does not exist: {0} + 파일이 없습니다. {0} Test cleanup method '{0}.{1}' timed out after {2}ms - Test cleanup method '{0}.{1}' timed out after {2}ms + {2}밀리초 후 테스트 정리 메서드 '{0}.{1}'이(가) 시간 초과되었습니다. Test cleanup method '{0}.{1}' was canceled - Test cleanup method '{0}.{1}' was canceled + 테스트 정리 메서드 '{0}.{1}'이(가) 취소되었습니다. TestContext cannot be Null. - TestContext cannot be Null. + TestContext는 null일 수 없습니다. TestContext Messages: - TestContext Messages: + TestContext 메시지: Test initialize method '{0}.{1}' timed out after {2}ms - Test initialize method '{0}.{1}' timed out after {2}ms + {2}밀리초 후 '{0}.{1}' 테스트 초기화 메서드의 시간이 초과되었습니다. Test initialize method '{0}.{1}' was canceled - Test initialize method '{0}.{1}' was canceled + 테스트 초기화 메서드 '{0}.{1}'이(가) 취소되었습니다. Test method {0} was not found. - Test method {0} was not found. + {0} 테스트 메서드를 찾을 수 없습니다. Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) - Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) + {0}에 대해 테스트 병렬 처리를 사용합니다(Workers: {1}, Scope: {2}). `Workers` is a setting name that shouldn't be localized. 'Scope' is a setting name that shouldn't be localized. @@ -362,53 +362,53 @@ but received {4} argument(s), with types '{5}'. Unable to load types from the test source '{0}'. Some or all of the tests in this source may not be discovered. Error: {1} - Unable to load types from the test source '{0}'. Some or all of the tests in this source may not be discovered. -Error: {1} + 테스트 소스 '{0}'에서 형식을 로드할 수 없습니다. 이 소스의 일부 또는 모든 테스트를 검색할 수 없습니다. +오류: {1} Assembly Cleanup method {0}.{1} failed. Error Message: {2}. StackTrace: {3} - Assembly Cleanup method {0}.{1} failed. Error Message: {2}. StackTrace: {3} + 어셈블리 정리 메서드 {0}.{1}이(가) 실패했습니다. 오류 메시지: {2}. StackTrace: {3} Assembly Initialization method {0}.{1} threw exception. {2}: {3}. Aborting test execution. - Assembly Initialization method {0}.{1} threw exception. {2}: {3}. Aborting test execution. + 어셈블리 초기화 메서드 {0}.{1}에서 예외를 throw했습니다. {2}: {3}. 테스트 실행을 중단합니다. Class Cleanup method {0}.{1} failed. Error Message: {2}. Stack Trace: {3} - Class Cleanup method {0}.{1} failed. Error Message: {2}. Stack Trace: {3} + 클래스 정리 메서드 {0}.{1}이(가) 실패했습니다. 오류 메시지: {2}. 스택 추적: {3} Class Initialization method {0}.{1} threw exception. {2}: {3}. - Class Initialization method {0}.{1} threw exception. {2}: {3}. + 클래스 초기화 메서드 {0}.{1}에서 예외를 throw했습니다. {2}: {3} Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. - Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + {0}.{1} 메서드의 서명이 잘못되었습니다. 메서드는 정적이고 공용이어야 하며, 값을 반환하거나 매개 변수를 취하지 않습니다. 또한 메서드에서 비동기 대기를 사용하는 경우 반환 형식은 'Task' 또는 'ValueTask'여야 합니다. Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should take a single parameter of type TestContext. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. - Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should take a single parameter of type TestContext. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + {0}.{1} 메서드의 서명이 잘못되었습니다. 메서드는 static, public이어야 하고, 값을 반환하지 않으며, TestContext 형식의 단일 매개 변수를 사용해야 합니다. 또한 메서드에서 비동기 대기를 사용하는 경우 반환 형식은 'Task' 또는 'ValueTask'여야 합니다. TestCleanup method {0}.{1} threw exception. {2}. - TestCleanup method {0}.{1} threw exception. {2}. + TestCleanup 메서드 {0}.{1}에서 예외가 발생했습니다. {2}. Error calling Test Cleanup method for test class {0}: {1} - Error calling Test Cleanup method for test class {0}: {1} + 테스트 클래스 {0}에 대한 테스트 정리 메서드를 호출하는 오류: {1} TestCleanup Stack Trace - TestCleanup Stack Trace + TestCleanup 스택 추적 @@ -418,7 +418,7 @@ Error: {1} --- End of inner exception stack trace --- - --- End of inner exception stack trace --- + --- 내부 예외 스택 추적의 끝 --- @@ -428,67 +428,67 @@ Error: {1} UTA031: class {0} does not have valid TestContext property. TestContext must be of type TestContext, must be non-static, and must be public. For example: public TestContext TestContext. - UTA031: class {0} does not have valid TestContext property. TestContext must be of type TestContext, must be non-static, and must be public. For example: public TestContext TestContext. + UTA031: {0} 클래스에 유효한 TestContext 속성이 없습니다. TestContext는 TestContext 유형이어야 하고, 정적이 아니어야 하며, 일반적이어야 합니다. 예: public TestContext TestContext. UTA007: Method {1} defined in class {0} does not have correct signature. Test method marked with the [TestMethod] attribute must be non-static, public, return-type as void and should not take any parameter. Example: public void Test.Class1.Test(). Additionally, if you are using async-await in test method then return-type must be 'Task' or 'ValueTask'. Example: public async Task Test.Class1.Test2() - UTA007: Method {1} defined in class {0} does not have correct signature. Test method marked with the [TestMethod] attribute must be non-static, public, return-type as void and should not take any parameter. Example: public void Test.Class1.Test(). Additionally, if you are using async-await in test method then return-type must be 'Task' or 'ValueTask'. Example: public async Task Test.Class1.Test2() + UTA007: 클래스 {0}에 정의된 메서드 {1}에 올바른 서명이 없습니다. [TestMethod] 특성으로 표시된 테스트 메서드는 non-static, public, return-type이 void여야 하며 매개 변수를 사용하지 않아야 합니다. 예: public void Test.Class1.Test(). 또한 테스트 메서드에서 비동기 대기를 사용하는 경우 반환 형식은 Task여야 합니다. 예: public async Task Test.Class1.Test2() UTA054: {0}.{1} has invalid Timeout attribute. The timeout must be an integer value greater than 0. - UTA054: {0}.{1} has invalid Timeout attribute. The timeout must be an integer value greater than 0. + UTA054: {0}.{1}에 잘못된 Timeout 특성이 있습니다. 시간 제한 값은 0보다 큰 정수여야 합니다. UTA014: {0}: Cannot define more than one method with the AssemblyCleanup attribute inside an assembly. - UTA014: {0}: Cannot define more than one method with the AssemblyCleanup attribute inside an assembly. + UTA014: {0}: 어셈블리 내부에서 AssemblyCleanup 특성을 사용하는 메서드를 여러 개 정의할 수 없습니다. UTA013: {0}: Cannot define more than one method with the AssemblyInitialize attribute inside an assembly. - UTA013: {0}: Cannot define more than one method with the AssemblyInitialize attribute inside an assembly. + UTA013: {0}: 어셈블리 내부에서 AssemblyInitialize 특성을 사용하는 메서드를 여러 개 정의할 수 없습니다. UTA026: {0}: Cannot define more than one method with the ClassCleanup attribute inside a class. - UTA026: {0}: Cannot define more than one method with the ClassCleanup attribute inside a class. + UTA026: {0}: 클래스 내부에서 ClassCleanup 특성을 사용하는 메서드를 여러 개 정의할 수 없습니다. UTA025: {0}: Cannot define more than one method with the ClassInitialize attribute inside a class. - UTA025: {0}: Cannot define more than one method with the ClassInitialize attribute inside a class. + UTA025: {0}: 클래스 내부에서 ClassInitialize 특성을 사용하는 메서드를 여러 개 정의할 수 없습니다. UTA024: {0}: Cannot define more than one method with the TestCleanup attribute. - UTA024: {0}: Cannot define more than one method with the TestCleanup attribute. + UTA024: {0}: TestCleanup 특성을 사용하는 메서드를 여러 개 정의할 수 없습니다. UTA018: {0}: Cannot define more than one method with the TestInitialize attribute. - UTA018: {0}: Cannot define more than one method with the TestInitialize attribute. + UTA018: {0}: TestInitialize 특성을 사용하는 메서드를 여러 개 정의할 수 없습니다. UTA001: TestClass attribute defined on non-public class {0} - UTA001: TestClass attribute defined on non-public class {0} + UTA001: public이 아닌 클래스 {0}에서 TestClass 특성을 정의했습니다. UTA023: {0}: Cannot define predefined property {2} on method {1}. - UTA023: {0}: Cannot define predefined property {2} on method {1}. + UTA023: {0}: {1} 메서드에서 미리 정의된 속성 {2}을(를) 정의할 수 없습니다. TestClass attribute defined on generic non-abstract class {0} - TestClass attribute defined on generic non-abstract class {0} + 일반 비추상 클래스 {0}에 정의된 TestClass 속성 UTA021: {0}: Null or empty custom property defined on method {1}. The custom property must have a valid name. - UTA021: {0}: Null or empty custom property defined on method {1}. The custom property must have a valid name. + UTA021: {0}: {1} 메서드에서 Null 또는 빈 사용자 지정 속성을 정의했습니다. 사용자 지정 속성에는 올바른 이름이 지정되어 있어야 합니다. @@ -501,90 +501,90 @@ Error: {1} The ExpectedException attribute defined on test method {0}.{1} threw an exception during construction. {2} - The ExpectedException attribute defined on test method {0}.{1} threw an exception during construction. + 테스트 메서드 {0}.{1}에 정의된 ExpectedException 특성이 생성하는 동안 예외를 throw했습니다. {2} Failed to obtain the exception thrown by test method {0}.{1}. - Failed to obtain the exception thrown by test method {0}.{1}. + 테스트 메서드 {0}.{1}에서 throw한 예외를 가져오지 못했습니다. Initialization method {0}.{1} threw exception. {2}. - Initialization method {0}.{1} threw exception. {2}. + 초기화 메서드 {0}.{1}에서 예외를 throw했습니다. {2}. Unable to create instance of class {0}. Error: {1}. - Unable to create instance of class {0}. Error: {1}. + {0} 클래스의 인스턴스를 만들 수 없습니다. 오류: {1} Method {0}.{1} does not exist. - Method {0}.{1} does not exist. + {0}.{1} 메서드가 없습니다. The test method '{0}.{1}' has multiple attributes derived from '{2}' defined on it. Only one such attribute is allowed. - The test method '{0}.{1}' has multiple attributes derived from '{2}' defined on it. Only one such attribute is allowed. + 테스트 메서드 '{0}.{1}'에 {2}에서 파생된 여러 특성이 정의되어 있습니다. 이러한 특성은 하나만 허용됩니다. Error in executing test. No result returned by extension. If using extension of TestMethodAttribute then please contact vendor. - Error in executing test. No result returned by extension. If using extension of TestMethodAttribute then please contact vendor. + 테스트를 실행하는 중에 오류가 발생했습니다. 확장에서 결과가 반환되지 않았습니다. TestMethodAttribute 확장을 사용하는 경우 공급업체에 문의하세요. Cannot find a valid constructor for test class '{0}'. Valid constructors are 'public' and either parameterless or with one parameter of type 'TestContext'. - Cannot find a valid constructor for test class '{0}'. Valid constructors are 'public' and either parameterless or with one parameter of type 'TestContext'. + 테스트 클래스 '{0}'에 대한 유효한 생성자를 찾을 수 없습니다. 유효한 생성자는 'public'이며 매개 변수가 없거나 'TestContext' 유형의 매개 변수가 하나 있습니다. Unable to find property {0}.TestContext. Error:{1}. - Unable to find property {0}.TestContext. Error:{1}. + {0}.TestContext 속성을 찾을 수 없습니다. 오류: {1} Unable to set TestContext property for the class {0}. Error: {1}. - Unable to set TestContext property for the class {0}. Error: {1}. + {0} 클래스에 대해 TestContext 속성을 설정할 수 없습니다. 오류: {1} The {0}.TestContext has incorrect type. - The {0}.TestContext has incorrect type. + {0}.TestContext의 형식이 잘못되었습니다. Method {0}.{1} has wrong signature. The method must be non-static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. - Method {0}.{1} has wrong signature. The method must be non-static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + {0}.{1} 메서드의 서명이 잘못되었습니다. 메서드는 정적이 아니고 공용이어야 하며, 값을 반환하거나 매개 변수를 사용할 수 없습니다. 또한 메서드에서 비동기 대기를 사용하는 경우 반환 형식은 'Task' 또는 'ValueTask'여야 합니다. Test method {0}.{1} threw exception: {2} - Test method {0}.{1} threw exception: + 테스트 메서드 {0}.{1}에서 예외를 throw했습니다. {2} Unable to get type {0}. Error: {1}. - Unable to get type {0}. Error: {1}. + {0} 형식을 가져올 수 없습니다. 오류: {1} The called code threw an exception that was caught, but the exception value was null - The called code threw an exception that was caught, but the exception value was null + 호출된 코드에서 확인된 예외가 발생했지만 예외 값이 null입니다. {0} For UWP projects, if you are using UI objects in test consider using [UITestMethod] attribute instead of [TestMethod] to execute test in UI thread. - {0} For UWP projects, if you are using UI objects in test consider using [UITestMethod] attribute instead of [TestMethod] to execute test in UI thread. + {0} UWP 프로젝트의 경우 테스트에서 UI 개체를 사용 중이면 [TestMethod] 대신 [UITestMethod] 특성을 사용하여 UI 스레드에서 테스트를 실행하세요. (Failed to get the message for an exception of type {0} due to an exception.) - (Failed to get the message for an exception of type {0} due to an exception.) + (예외로 인해 {0} 형식의 예외에 대한 메시지를 가져오지 못했습니다.) diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.pl.xlf b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.pl.xlf index 832339a682..de9cf91dd6 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.pl.xlf +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.pl.xlf @@ -4,52 +4,52 @@ Assembly cleanup method '{0}.{1}' timed out after {2}ms - Assembly cleanup method '{0}.{1}' timed out after {2}ms + Metoda oczyszczania zestawu „{0}.{1}” przekroczyła limit czasu po {2}ms Assembly cleanup method '{0}.{1}' was canceled - Assembly cleanup method '{0}.{1}' was canceled + Anulowano metodę oczyszczania zestawu „{0}.{1}” Assembly initialize method '{0}.{1}' timed out after {2}ms - Assembly initialize method '{0}.{1}' timed out after {2}ms + Metoda inicjalizacji zestawu „{0}.{1}” przekroczyła limit czasu po {2}ms Assembly initialize method '{0}.{1}' was canceled - Assembly initialize method '{0}.{1}' was canceled + Anulowano metodę inicjowania zestawu „{0}.{1}” MSTestAdapterV2 - MSTestAdapterV2 + MSTestAdapterV2 Exception occurred while enumerating IDataSource attribute on "{0}.{1}": {2} - Exception occurred while enumerating IDataSource attribute on "{0}.{1}": {2} + Wystąpił wyjątek podczas wyliczania atrybutu IDataSource w przestrzeni nazwy „{0}.{1}”: {2} {0}: TypeName with namespace, {1}: Method name, {2}: Exception details Exception occurred while expanding IDataSource rows from attribute on "{0}.{1}": {2} - Exception occurred while expanding IDataSource rows from attribute on "{0}.{1}": {2} + Wystąpił wyjątek podczas rozwijania wierszy IDataSource z atrybutu w przestrzeni nazw „{0}.{1}”: {2} {0}: TypeName with namespace, {1}: Method name, {2}: CannotExpandIDataSourceAttribute_DuplicateDisplayName or CannotExpandIDataSourceAttribute_CannotSerialize Data on index {0} for "{1}" cannot be serialized. All data provided through "IDataSource" should be serializable. If you need to test non-serializable data sources, please make sure you add "TestDataSourceDiscovery" attribute on your test assembly and set the discovery option to "DuringExecution". - Data on index {0} for "{1}" cannot be serialized. All data provided through "IDataSource" should be serializable. If you need to test non-serializable data sources, please make sure you add "TestDataSourceDiscovery" attribute on your test assembly and set the discovery option to "DuringExecution". + Nie można serializować danych w indeksie {0} dla „{1}”. Wszystkie dane dostarczane za pomocą źródła „IDataSource” powinny być możliwe do serializacji. Jeśli chcesz przetestować nieserializowalne źródła danych, upewnij się, że dodasz atrybut „ TestDataSourceDiscovery” w zestawie testowym i ustaw opcję odnajdywania na wartość „DuringExecution”. {0}: Zero based index if an element inside of an array, {1}: Test name Display name "{2}" on indexes {0} and {1} are duplicate. Display names should be unique. - Display name "{2}" on indexes {0} and {1} are duplicate. Display names should be unique. + Nazwa wyświetlana „{2}” w indeksach {0} i {1} jest duplikatem. Nazwy wyświetlane powinny być unikatowe. {0}, {1}: Zero based index if an element inside of an array {2}: Test display name. @@ -74,22 +74,22 @@ but received {4} argument(s), with types '{5}'. Class cleanup method '{0}.{1}' timed out after {2}ms - Class cleanup method '{0}.{1}' timed out after {2}ms + Metoda oczyszczania klasy „{0}.{1}” przekroczyła limit czasu po {2}ms Class cleanup method '{0}.{1}' was canceled - Class cleanup method '{0}.{1}' was canceled + Anulowano metodę oczyszczania klasy „{0}.{1}” Class initialize method '{0}.{1}' timed out after {2}ms - Class initialize method '{0}.{1}' timed out after {2}ms + Metoda inicjalizacji klasy „{0}.{1}” przekroczyła limit czasu po {2}ms Class initialize method '{0}.{1}' was canceled - Class initialize method '{0}.{1}' was canceled + Anulowano metodę inicjowania klasy „{0}.{1}” @@ -99,17 +99,17 @@ but received {4} argument(s), with types '{5}'. MSTestAdapter failed to discover tests in class '{0}' of assembly '{1}' because {2}. - MSTestAdapter failed to discover tests in class '{0}' of assembly '{1}' because {2}. + Adapter MSTestAdapter nie mógł odnaleźć testów w klasie „{0}” zestawu „{1}”, przyczyna: {2}. {0} (Data Row {1}) - {0} (Data Row {1}) + {0} (wiersz danych {1}) Debug Trace: - Debug Trace: + Ślad debugowania: @@ -179,28 +179,28 @@ but received {4} argument(s), with types '{5}'. [MSTest][Discovery][{0}] {1} - [MSTest][Discovery][{0}] {1} + [MSTest][Discovery][{0}] {1} Both '.runsettings' and '.testconfig.json' files have been detected. Please select only one of these test configuration files. - Both '.runsettings' and '.testconfig.json' files have been detected. Please select only one of these test configuration files. + Wykryto zarówno pliki „.runsettings”, jak i „.testconfig.json”. Wybierz tylko jeden z tych plików konfiguracji testu. {0}: {1} - {0}: {1} + {0}: {1} "{0}": (Failed to get exception description due to an exception of type "{1}". - "{0}": (Failed to get exception description due to an exception of type "{1}". + „{0}”: (Nie można uzyskać opisu wyjątku z powodu wyjątku typu „{1}”. {0}: Type of the original exception that we're trying to get the description of. {1}: Thrown exception Exceptions thrown: - Exceptions thrown: + Zgłoszone wyjątki: This is usually precedes by TestAssembly_AssemblyDiscoveryFailure message, and preceded by list of exceptions thrown in a test discovery session. @@ -215,7 +215,7 @@ but received {4} argument(s), with types '{5}'. Getting custom attributes for type {0} threw exception (will ignore and use the reflection way): {1} - Getting custom attributes for type {0} threw exception (will ignore and use the reflection way): {1} + Pobieranie atrybutów niestandardowych dla typu {0} zgłosiło wyjątek (zignoruje i użyje sposobu odbicia): {1} {0}: Attribute full type name. {1}: Exception description @@ -236,22 +236,22 @@ but received {4} argument(s), with types '{5}'. Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. - Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. + Dla ustawienia „ClassCleanupLifecycle” określono nieprawidłową wartość „{0}”. Obsługiwane zakresy to {1}. 'ClassCleanupLifecycle' is a setting name that shouldn't be localized. Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. - Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. + Określono nieprawidłową wartość „{0}” dla właściwości „Scope”. Obsługiwane zakresy to {1}. 'Scope' is a setting name that shouldn't be localized. Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. - Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. + Określono nieprawidłową wartość „{0}” dla właściwości „Workers”. Wartość musi być nieujemną liczbą całkowitą. `Workers` is a setting name that shouldn't be localized. Invalid settings '{0}'. Unexpected XmlAttribute: '{1}'. - Invalid settings '{0}'. Unexpected XmlAttribute: '{1}'. + Nieprawidłowe ustawienia „{0}”. Nieoczekiwany atrybut XmlAttribute: „{1}”. @@ -261,7 +261,7 @@ but received {4} argument(s), with types '{5}'. Invalid settings '{0}'. Unexpected XmlElement: '{1}'. - Invalid settings '{0}'. Unexpected XmlElement: '{1}'. + Nieprawidłowe ustawienia „{0}”. Nieoczekiwany atrybut XmlElement: „{1}”. @@ -271,12 +271,12 @@ but received {4} argument(s), with types '{5}'. Invalid value '{0}' for runsettings entry '{1}', setting will be ignored. - Invalid value '{0}' for runsettings entry '{1}', setting will be ignored. + Nieprawidłowa wartość „{0}” dla wpisu runsettings „{1}”. Ustawienie zostanie zignorowane. Warning : A testsettings file or a vsmdi file is not supported with the MSTest V2 Adapter. - Warning : A testsettings file or a vsmdi file is not supported with the MSTest V2 Adapter. + Ostrzeżenie: Plik testsettings lub plik vsmdi nie jest obsługiwany przez adapter MSTest w wersji 2. @@ -291,67 +291,67 @@ but received {4} argument(s), with types '{5}'. An older version of MSTestV2 package is loaded in assembly, test discovery might fail to discover all data tests if they depend on `.runsettings` file. - An older version of MSTestV2 package is loaded in assembly, test discovery might fail to discover all data tests if they depend on `.runsettings` file. + Starsza wersja pakietu MSTestV2 jest załadowana do zestawu. Odnajdywanie testów może nie odnaleźć wszystkich testów danych, jeśli zależą od pliku „.runsettings”. Runsettings entry '<ExecutionApartmentState>STA</ExecutionApartmentState>' is not supported on non-Windows OSes. - Runsettings entry '<ExecutionApartmentState>STA</ExecutionApartmentState>' is not supported on non-Windows OSes. + Wpis runsettings „<ExecutionApartmentState>STA</ExecutionApartmentState>” nie jest obsługiwany w systemach operacyjnych innych niż Windows. Running tests in any of the provided sources is not supported for the selected platform - Running tests in any of the provided sources is not supported for the selected platform + Uruchamianie testów w żadnym z podanych źródeł nie jest obsługiwane dla wybranej platformy Failed to discover tests from assembly {0}. Reason:{1} - Failed to discover tests from assembly {0}. Reason:{1} + Nie można odnaleźć testów z zestawu {0}. Przyczyna:{1} File does not exist: {0} - File does not exist: {0} + Plik nie istnieje: {0} Test cleanup method '{0}.{1}' timed out after {2}ms - Test cleanup method '{0}.{1}' timed out after {2}ms + Metoda oczyszczania testu „{0}.{1}” przekroczyła limit czasu po {2}ms Test cleanup method '{0}.{1}' was canceled - Test cleanup method '{0}.{1}' was canceled + Anulowano metodę oczyszczania testu „{0}.{1}” TestContext cannot be Null. - TestContext cannot be Null. + Wartość TestContext nie może być równa null. TestContext Messages: - TestContext Messages: + Komunikaty TestContext: Test initialize method '{0}.{1}' timed out after {2}ms - Test initialize method '{0}.{1}' timed out after {2}ms + Metoda inicjalizacji testu „{0}.{1}” przekroczyła limit czasu po {2}ms Test initialize method '{0}.{1}' was canceled - Test initialize method '{0}.{1}' was canceled + Anulowano metodę inicjowania testu „{0}.{1}” Test method {0} was not found. - Test method {0} was not found. + Nie znaleziono metody testowej {0}. Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) - Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) + Przetwarzanie równoległe testów włączono dla {0} (procesy robocze: {1}, zakres: {2}) `Workers` is a setting name that shouldn't be localized. 'Scope' is a setting name that shouldn't be localized. @@ -362,53 +362,53 @@ but received {4} argument(s), with types '{5}'. Unable to load types from the test source '{0}'. Some or all of the tests in this source may not be discovered. Error: {1} - Unable to load types from the test source '{0}'. Some or all of the tests in this source may not be discovered. -Error: {1} + Nie można załadować typów ze źródła testów „{0}”. Niektóre lub wszystkie testy w tym źródle mogły nie zostać odnalezione. +Błąd: {1} Assembly Cleanup method {0}.{1} failed. Error Message: {2}. StackTrace: {3} - Assembly Cleanup method {0}.{1} failed. Error Message: {2}. StackTrace: {3} + Metoda czyszczenia zestawu {0}.{1} nie powiodła się. Komunikat o błędzie: {2}. Ślad stosu: {3} Assembly Initialization method {0}.{1} threw exception. {2}: {3}. Aborting test execution. - Assembly Initialization method {0}.{1} threw exception. {2}: {3}. Aborting test execution. + Metoda inicjująca zestaw {0}.{1} nie powiodła się. {2}: {3}. Przerywanie wykonywania testu. Class Cleanup method {0}.{1} failed. Error Message: {2}. Stack Trace: {3} - Class Cleanup method {0}.{1} failed. Error Message: {2}. Stack Trace: {3} + Metoda czyszczenia klasy {0}.{1} nie powiodła się. Komunikat o błędzie: {2}. Ślad stosu: {3} Class Initialization method {0}.{1} threw exception. {2}: {3}. - Class Initialization method {0}.{1} threw exception. {2}: {3}. + Metoda inicjowania klasy {0}.{1} zgłosiła wyjątek. {2}: {3}. Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. - Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + Metoda {0}.{1}ma nieprawidłową sygnaturę. Metoda musi być statyczna, publiczna, nie może zwracać wartości i nie powinna przyjmować żadnego parametru. Ponadto jeśli w metodzie jest używane oczekiwanie asynchroniczne, wtedy zwracanym typem musi być typ „Task” lub „ValueTask”. Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should take a single parameter of type TestContext. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. - Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should take a single parameter of type TestContext. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + Metoda {0}.{1}ma nieprawidłową sygnaturę. Metoda musi być statyczna, publiczna, nie może zwracać wartości i powinna mieć jeden parametr typu TestContext. Ponadto jeśli w metodzie jest używane oczekiwanie asynchroniczne, wtedy zwracanym typem musi być typ „Task” lub „ValueTask”. TestCleanup method {0}.{1} threw exception. {2}. - TestCleanup method {0}.{1} threw exception. {2}. + Metoda TestCleanup {0}.{1} zgłosiła wyjątek {2}. Error calling Test Cleanup method for test class {0}: {1} - Error calling Test Cleanup method for test class {0}: {1} + Błąd podczas wywoływania metody czyszczącej testu dla klasy testowej {0}: {1} TestCleanup Stack Trace - TestCleanup Stack Trace + Ślad stosu dla TestCleanup @@ -418,7 +418,7 @@ Error: {1} --- End of inner exception stack trace --- - --- End of inner exception stack trace --- + --- Koniec śledzenia stosu wyjątku wewnętrznego --- @@ -428,67 +428,67 @@ Error: {1} UTA031: class {0} does not have valid TestContext property. TestContext must be of type TestContext, must be non-static, and must be public. For example: public TestContext TestContext. - UTA031: class {0} does not have valid TestContext property. TestContext must be of type TestContext, must be non-static, and must be public. For example: public TestContext TestContext. + UTA031: Klasa {0}nie ma prawidłowej właściwości TestContext. Element TestContext musi być typu TestContext, musi być niestatyczny i musi być publiczny. Na przykład : public TestContext TestContext. UTA007: Method {1} defined in class {0} does not have correct signature. Test method marked with the [TestMethod] attribute must be non-static, public, return-type as void and should not take any parameter. Example: public void Test.Class1.Test(). Additionally, if you are using async-await in test method then return-type must be 'Task' or 'ValueTask'. Example: public async Task Test.Class1.Test2() - UTA007: Method {1} defined in class {0} does not have correct signature. Test method marked with the [TestMethod] attribute must be non-static, public, return-type as void and should not take any parameter. Example: public void Test.Class1.Test(). Additionally, if you are using async-await in test method then return-type must be 'Task' or 'ValueTask'. Example: public async Task Test.Class1.Test2() + UTA007: metoda {1} zdefiniowana w klasie {0}nie ma poprawnej sygnatury. Metoda testowa oznaczona przez atrybut [TestMethod] musi być niestatyczna, publiczna, zwracać wartość typu void i nie powinna przyjmować żadnego parametru. Przykład: public void Test.Class1.Test(). Ponadto, jeśli używasz oczekiwanie asynchroniczne w metodzie testowej, wtedy zwracanym typem musi być „Task” lub „ValueTask”. Przykład: public async Task Test.Class1.Test2() UTA054: {0}.{1} has invalid Timeout attribute. The timeout must be an integer value greater than 0. - UTA054: {0}.{1} has invalid Timeout attribute. The timeout must be an integer value greater than 0. + UTA054: {0}.{1} ma nieprawidłowy atrybut Timeout. Limit czasu musi być liczbą całkowitą większą niż 0. UTA014: {0}: Cannot define more than one method with the AssemblyCleanup attribute inside an assembly. - UTA014: {0}: Cannot define more than one method with the AssemblyCleanup attribute inside an assembly. + UTA014: {0}: W zestawie nie można zdefiniować więcej niż jednej metody z atrybutem AssemblyCleanup. UTA013: {0}: Cannot define more than one method with the AssemblyInitialize attribute inside an assembly. - UTA013: {0}: Cannot define more than one method with the AssemblyInitialize attribute inside an assembly. + UTA013: {0}: W zestawie nie można zdefiniować więcej niż jednej metody z atrybutem AssemblyInitialize. UTA026: {0}: Cannot define more than one method with the ClassCleanup attribute inside a class. - UTA026: {0}: Cannot define more than one method with the ClassCleanup attribute inside a class. + UTA026: {0}: W klasie nie można zdefiniować więcej niż jednej metody z atrybutem ClassCleanup. UTA025: {0}: Cannot define more than one method with the ClassInitialize attribute inside a class. - UTA025: {0}: Cannot define more than one method with the ClassInitialize attribute inside a class. + UTA025: {0}: W klasie nie można zdefiniować więcej niż jednej metody z atrybutem ClassInitialize. UTA024: {0}: Cannot define more than one method with the TestCleanup attribute. - UTA024: {0}: Cannot define more than one method with the TestCleanup attribute. + UTA024: {0}: Nie można zdefiniować więcej niż jednej metody z atrybutem TestCleanup. UTA018: {0}: Cannot define more than one method with the TestInitialize attribute. - UTA018: {0}: Cannot define more than one method with the TestInitialize attribute. + UTA018: {0}: Nie można zdefiniować więcej niż jednej metody z atrybutem TestInitialize. UTA001: TestClass attribute defined on non-public class {0} - UTA001: TestClass attribute defined on non-public class {0} + UTA001: Atrybut TestClass zdefiniowany dla niepublicznej klasy {0} UTA023: {0}: Cannot define predefined property {2} on method {1}. - UTA023: {0}: Cannot define predefined property {2} on method {1}. + UTA023: {0}: Nie można zdefiniować wstępnie zdefiniowanej właściwości {2} dla metody {1}. TestClass attribute defined on generic non-abstract class {0} - TestClass attribute defined on generic non-abstract class {0} + Atrybut TestClass zdefiniowany w ogólnej klasie nieabstrakcyjnej {0} UTA021: {0}: Null or empty custom property defined on method {1}. The custom property must have a valid name. - UTA021: {0}: Null or empty custom property defined on method {1}. The custom property must have a valid name. + UTA021: {0}: Zerowa lub pusta niestandardowa właściwość została zdefiniowana dla metody {1}. Niestandardowa właściwość musi mieć prawidłową nazwę. @@ -501,90 +501,90 @@ Error: {1} The ExpectedException attribute defined on test method {0}.{1} threw an exception during construction. {2} - The ExpectedException attribute defined on test method {0}.{1} threw an exception during construction. + Atrybut ExpectedException zdefiniowany dla metody testowej {0}.{1} zgłosił wyjątek w trakcie konstruowania. {2} Failed to obtain the exception thrown by test method {0}.{1}. - Failed to obtain the exception thrown by test method {0}.{1}. + Nie powiodło się uzyskanie wyjątku zgłoszonego przez metodę testową {0}.{1}. Initialization method {0}.{1} threw exception. {2}. - Initialization method {0}.{1} threw exception. {2}. + Metoda inicjowania {0}.{1} zgłosiła wyjątek. {2}. Unable to create instance of class {0}. Error: {1}. - Unable to create instance of class {0}. Error: {1}. + Nie można utworzyć wystąpienia klasy {0}. Błąd: {1}. Method {0}.{1} does not exist. - Method {0}.{1} does not exist. + Metoda {0}.{1} nie istnieje. The test method '{0}.{1}' has multiple attributes derived from '{2}' defined on it. Only one such attribute is allowed. - The test method '{0}.{1}' has multiple attributes derived from '{2}' defined on it. Only one such attribute is allowed. + Metoda testowa "{0}.{1}” ma zdefiniowanych wiele atrybutów pochodzących z „{2}”. Dozwolony jest tylko jeden taki atrybut. Error in executing test. No result returned by extension. If using extension of TestMethodAttribute then please contact vendor. - Error in executing test. No result returned by extension. If using extension of TestMethodAttribute then please contact vendor. + Błąd podczas wykonywania testu. Rozszerzenie nie zwróciło żadnego wyniku. W przypadku korzystania z rozszerzenia atrybutu TestMethodAttribute należy skontaktować się z dostawcą. Cannot find a valid constructor for test class '{0}'. Valid constructors are 'public' and either parameterless or with one parameter of type 'TestContext'. - Cannot find a valid constructor for test class '{0}'. Valid constructors are 'public' and either parameterless or with one parameter of type 'TestContext'. + Nie można odnaleźć prawidłowego konstruktora dla klasy testowej „{0}”. Prawidłowe konstruktory są „publiczne” i albo bez parametrów, albo z jednym parametrem typu „TestContext”. Unable to find property {0}.TestContext. Error:{1}. - Unable to find property {0}.TestContext. Error:{1}. + Nie można znaleźć właściwości {0}.TestContext. Błąd:{1}. Unable to set TestContext property for the class {0}. Error: {1}. - Unable to set TestContext property for the class {0}. Error: {1}. + Nie można ustawić właściwości TestContext w klasie {0}. Błąd: {1}. The {0}.TestContext has incorrect type. - The {0}.TestContext has incorrect type. + Element {0}.TestContext ma niepoprawny typ. Method {0}.{1} has wrong signature. The method must be non-static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. - Method {0}.{1} has wrong signature. The method must be non-static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + Metoda {0}.{1}ma nieprawidłową sygnaturę. Metoda musi być niestatyczna, publiczna, nie może zwracać wartości i nie powinna przyjmować żadnego parametru. Ponadto jeśli w metodzie jest używane oczekiwanie asynchroniczne, wtedy zwracanym typem musi być typ „Task” lub „ValueTask”. Test method {0}.{1} threw exception: {2} - Test method {0}.{1} threw exception: + Metoda testowa {0}.{1} zgłosiła wyjątek: {2} Unable to get type {0}. Error: {1}. - Unable to get type {0}. Error: {1}. + Nie można uzyskać typu {0}. Błąd: {1}. The called code threw an exception that was caught, but the exception value was null - The called code threw an exception that was caught, but the exception value was null + Wywołany kod zgłosił wyjątek, który został przechwycony, ale wartość wyjątku miała wartość null {0} For UWP projects, if you are using UI objects in test consider using [UITestMethod] attribute instead of [TestMethod] to execute test in UI thread. - {0} For UWP projects, if you are using UI objects in test consider using [UITestMethod] attribute instead of [TestMethod] to execute test in UI thread. + {0} Jeśli w projektach UWP korzystasz z obiektów interfejsu użytkownika podczas testowania, rozważ użycie atrybutu [UITestMethod] zamiast atrybutu [TestMethod], aby wykonywać test w wątku interfejsu użytkownika. (Failed to get the message for an exception of type {0} due to an exception.) - (Failed to get the message for an exception of type {0} due to an exception.) + (Nie można pobrać komunikatu dotyczącego wyjątku typu {0} z powodu wyjątku). diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.pt-BR.xlf b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.pt-BR.xlf index 05a30643ab..48439b0656 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.pt-BR.xlf +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.pt-BR.xlf @@ -4,52 +4,52 @@ Assembly cleanup method '{0}.{1}' timed out after {2}ms - Assembly cleanup method '{0}.{1}' timed out after {2}ms + O método de limpeza da montagem '{0}.{1}' atingiu o tempo limite após {2}ms Assembly cleanup method '{0}.{1}' was canceled - Assembly cleanup method '{0}.{1}' was canceled + O método de limpeza do assembly "{0}.{1}" foi cancelado Assembly initialize method '{0}.{1}' timed out after {2}ms - Assembly initialize method '{0}.{1}' timed out after {2}ms + O método de inicialização da montagem '{0}.{1}' atingiu o tempo limite após {2}ms Assembly initialize method '{0}.{1}' was canceled - Assembly initialize method '{0}.{1}' was canceled + O método de inicialização do assembly "{0}.{1}" foi cancelado MSTestAdapterV2 - MSTestAdapterV2 + MSTestAdapterV2 Exception occurred while enumerating IDataSource attribute on "{0}.{1}": {2} - Exception occurred while enumerating IDataSource attribute on "{0}.{1}": {2} + Ocorreu uma exceção ao enumerar o atributo IDataSource em "{0}.{1}": {2} {0}: TypeName with namespace, {1}: Method name, {2}: Exception details Exception occurred while expanding IDataSource rows from attribute on "{0}.{1}": {2} - Exception occurred while expanding IDataSource rows from attribute on "{0}.{1}": {2} + Ocorreu uma exceção ao expandir as linhas IDataSource do atributo em "{0}.{1}": {2} {0}: TypeName with namespace, {1}: Method name, {2}: CannotExpandIDataSourceAttribute_DuplicateDisplayName or CannotExpandIDataSourceAttribute_CannotSerialize Data on index {0} for "{1}" cannot be serialized. All data provided through "IDataSource" should be serializable. If you need to test non-serializable data sources, please make sure you add "TestDataSourceDiscovery" attribute on your test assembly and set the discovery option to "DuringExecution". - Data on index {0} for "{1}" cannot be serialized. All data provided through "IDataSource" should be serializable. If you need to test non-serializable data sources, please make sure you add "TestDataSourceDiscovery" attribute on your test assembly and set the discovery option to "DuringExecution". + Os dados no índice {0} para "{1}" não podem ser serializados. Todos os dados fornecidos por meio de "IDataSource" devem ser serializáveis. Se você precisar testar fontes de dados não serializáveis, certifique-se de adicionar o atributo "TestDataSourceDiscovery" em seu assembly de teste e defina a opção de descoberta como "DuringExecution". {0}: Zero based index if an element inside of an array, {1}: Test name Display name "{2}" on indexes {0} and {1} are duplicate. Display names should be unique. - Display name "{2}" on indexes {0} and {1} are duplicate. Display names should be unique. + O nome de exibição "{2}" nos índices {0} e {1} são duplicados. Os nomes de exibição devem ser exclusivos. {0}, {1}: Zero based index if an element inside of an array {2}: Test display name. @@ -69,27 +69,27 @@ but received {4} argument(s), with types '{5}'. Cannot run test method '{0}.{1}': Method has parameters, but does not define any test source. Use '[DataRow]', '[DynamicData]', or a custom 'ITestDataSource' data source to provide test data. - Cannot run test method '{0}.{1}': Method has parameters, but does not define any test source. Use '[DataRow]', '[DynamicData]', or a custom 'ITestDataSource' data source to provide test data. + Não é possível executar o método de teste '{0}.{1}': o método tem parâmetros, mas não define nenhuma fonte de teste. Use '[DataRow]', '[DynamicData]' ou uma fonte de dados 'ITestDataSource' personalizada para fornecer dados de teste. Class cleanup method '{0}.{1}' timed out after {2}ms - Class cleanup method '{0}.{1}' timed out after {2}ms + O método de limpeza da classe '{0}.{1}' atingiu o tempo limite após {2}ms Class cleanup method '{0}.{1}' was canceled - Class cleanup method '{0}.{1}' was canceled + O método de limpeza de classe "{0}.{1}" foi cancelado Class initialize method '{0}.{1}' timed out after {2}ms - Class initialize method '{0}.{1}' timed out after {2}ms + O método de inicialização da classe '{0}.{1}' atingiu o tempo limite após {2}ms Class initialize method '{0}.{1}' was canceled - Class initialize method '{0}.{1}' was canceled + O método de inicialização de classe "{0}.{1}" foi cancelado @@ -99,17 +99,17 @@ but received {4} argument(s), with types '{5}'. MSTestAdapter failed to discover tests in class '{0}' of assembly '{1}' because {2}. - MSTestAdapter failed to discover tests in class '{0}' of assembly '{1}' because {2}. + O MSTestAdapter não conseguiu descobrir testes na classe '{0}' do assembly '{1}' devido a {2}. {0} (Data Row {1}) - {0} (Data Row {1}) + {0} (Linha de Dados {1}) Debug Trace: - Debug Trace: + Rastreamento de Depuração: @@ -179,28 +179,28 @@ but received {4} argument(s), with types '{5}'. [MSTest][Discovery][{0}] {1} - [MSTest][Discovery][{0}] {1} + [MSTest][Descoberta][{0}] {1} Both '.runsettings' and '.testconfig.json' files have been detected. Please select only one of these test configuration files. - Both '.runsettings' and '.testconfig.json' files have been detected. Please select only one of these test configuration files. + Ambos os arquivos '.runsettings' e '.testconfig.json' foram detectados. Selecione apenas um desses arquivos de configuração de teste. {0}: {1} - {0}: {1} + {0}: {1} "{0}": (Failed to get exception description due to an exception of type "{1}". - "{0}": (Failed to get exception description due to an exception of type "{1}". + "{0}": (Falha ao obter a descrição da exceção devido a uma exceção do tipo "{1}". {0}: Type of the original exception that we're trying to get the description of. {1}: Thrown exception Exceptions thrown: - Exceptions thrown: + Exceções lançadas: This is usually precedes by TestAssembly_AssemblyDiscoveryFailure message, and preceded by list of exceptions thrown in a test discovery session. @@ -215,7 +215,7 @@ but received {4} argument(s), with types '{5}'. Getting custom attributes for type {0} threw exception (will ignore and use the reflection way): {1} - Getting custom attributes for type {0} threw exception (will ignore and use the reflection way): {1} + A obtenção de atributos personalizados para o tipo {0} gerou uma exceção (irá ignorar e usar o modo de reflexão): {1} {0}: Attribute full type name. {1}: Exception description @@ -236,22 +236,22 @@ but received {4} argument(s), with types '{5}'. Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. - Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. + Valor inválido '{0}' especificado para 'ClassCleanupLifecycle'. Os escopos suportados são {1}. 'ClassCleanupLifecycle' is a setting name that shouldn't be localized. Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. - Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. + Valor inválido '{0}' especificado para 'Scope'. Os escopos compatíveis são {1}. 'Scope' is a setting name that shouldn't be localized. Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. - Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. + Valor inválido '{0}' especificado para 'Workers'. O valor deve ser um inteiro não negativo. `Workers` is a setting name that shouldn't be localized. Invalid settings '{0}'. Unexpected XmlAttribute: '{1}'. - Invalid settings '{0}'. Unexpected XmlAttribute: '{1}'. + Configurações inválidas '{0}'. XmlAttribute inesperado: '{1}'. @@ -261,7 +261,7 @@ but received {4} argument(s), with types '{5}'. Invalid settings '{0}'. Unexpected XmlElement: '{1}'. - Invalid settings '{0}'. Unexpected XmlElement: '{1}'. + Configurações inválidas '{0}'. XmlElement inesperado: '{1}'. @@ -271,12 +271,12 @@ but received {4} argument(s), with types '{5}'. Invalid value '{0}' for runsettings entry '{1}', setting will be ignored. - Invalid value '{0}' for runsettings entry '{1}', setting will be ignored. + Valor inválido "{0}" para a entrada runsettings "{1}", a configuração será ignorada. Warning : A testsettings file or a vsmdi file is not supported with the MSTest V2 Adapter. - Warning : A testsettings file or a vsmdi file is not supported with the MSTest V2 Adapter. + Aviso: um arquivo testsettings ou um arquivo vsmdi não tem suporte no MSTest V2 Adapter. @@ -291,67 +291,67 @@ but received {4} argument(s), with types '{5}'. An older version of MSTestV2 package is loaded in assembly, test discovery might fail to discover all data tests if they depend on `.runsettings` file. - An older version of MSTestV2 package is loaded in assembly, test discovery might fail to discover all data tests if they depend on `.runsettings` file. + Uma versão mais antiga do pacote MSTestV2 é carregada no assembly, a descoberta de teste pode falhar ao descobrir todos os testes de dados se eles dependerem do arquivo `.runsettings`. Runsettings entry '<ExecutionApartmentState>STA</ExecutionApartmentState>' is not supported on non-Windows OSes. - Runsettings entry '<ExecutionApartmentState>STA</ExecutionApartmentState>' is not supported on non-Windows OSes. + Não há suporte para a entrada runsettings "<ExecutionApartmentState>STA</ExecutionApartmentState>" em sistemas operacionais que não sejam Windows. Running tests in any of the provided sources is not supported for the selected platform - Running tests in any of the provided sources is not supported for the selected platform + Não há suporte para execução de teste em qualquer uma das origens fontes fornecidas para a plataforma selecionada Failed to discover tests from assembly {0}. Reason:{1} - Failed to discover tests from assembly {0}. Reason:{1} + Falha ao descobrir testes por meio do assembly {0}. Motivo: {1} File does not exist: {0} - File does not exist: {0} + O arquivo não existe: {0} Test cleanup method '{0}.{1}' timed out after {2}ms - Test cleanup method '{0}.{1}' timed out after {2}ms + O método de limpeza do teste '{0}.{1}' atingiu o tempo limite após {2}ms Test cleanup method '{0}.{1}' was canceled - Test cleanup method '{0}.{1}' was canceled + O método de limpeza de teste "{0}.{1}" foi cancelado TestContext cannot be Null. - TestContext cannot be Null. + TestContext não pode ser Nulo. TestContext Messages: - TestContext Messages: + Mensagens TestContext: Test initialize method '{0}.{1}' timed out after {2}ms - Test initialize method '{0}.{1}' timed out after {2}ms + O método de inicialização do teste '{0}.{1}' atingiu o tempo limite após {2}ms Test initialize method '{0}.{1}' was canceled - Test initialize method '{0}.{1}' was canceled + O método de inicialização de teste "{0}.{1}" foi cancelado Test method {0} was not found. - Test method {0} was not found. + O método de teste {0} não foi encontrado. Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) - Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) + Paralelização de Teste habilitada para {0} (Trabalhos: {1}, Escopo: {2}) `Workers` is a setting name that shouldn't be localized. 'Scope' is a setting name that shouldn't be localized. @@ -362,53 +362,53 @@ but received {4} argument(s), with types '{5}'. Unable to load types from the test source '{0}'. Some or all of the tests in this source may not be discovered. Error: {1} - Unable to load types from the test source '{0}'. Some or all of the tests in this source may not be discovered. -Error: {1} + Não é possível carregar tipos da fonte de teste '{0}'. Alguns ou todos os testes nessa fonte podem não ser descobertos. +Erro: {1} Assembly Cleanup method {0}.{1} failed. Error Message: {2}. StackTrace: {3} - Assembly Cleanup method {0}.{1} failed. Error Message: {2}. StackTrace: {3} + Falha no método de Limpeza de Assembly {0}.{1}. Mensagem de Erro: {2}. StackTrace: {3} Assembly Initialization method {0}.{1} threw exception. {2}: {3}. Aborting test execution. - Assembly Initialization method {0}.{1} threw exception. {2}: {3}. Aborting test execution. + O método de Inicialização de Assembly {0}.{1} lançou uma exceção. {2}: {3}. Anulando execução de teste. Class Cleanup method {0}.{1} failed. Error Message: {2}. Stack Trace: {3} - Class Cleanup method {0}.{1} failed. Error Message: {2}. Stack Trace: {3} + Falha no método de Limpeza de Classe {0}.{1}. Mensagem de Erro: {2}. Rastreamento de Pilha: {3} Class Initialization method {0}.{1} threw exception. {2}: {3}. - Class Initialization method {0}.{1} threw exception. {2}: {3}. + O método de Inicialização de Classe {0}.{1} lançou uma exceção. {2}: {3}. Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. - Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + O método {0}.{1} tem a assinatura incorreta. O método deve ser estático, público, não deve retornar um valor nem receber parâmetro. Além disso, se você estiver usando async-await no método, o return-type deverá ser "Task" ou "ValueTask". Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should take a single parameter of type TestContext. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. - Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should take a single parameter of type TestContext. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + O método {0}.{1} tem a assinatura incorreta. O método deve ser estático, público, não retornar um valor e deve usar um único parâmetro do tipo TestContext. Além disso, se você estiver usando async-await no método, o return-type deverá ser "Task" ou "ValueTask". TestCleanup method {0}.{1} threw exception. {2}. - TestCleanup method {0}.{1} threw exception. {2}. + O método TestCleanup {0}.{1} gerou a exceção. {2}. Error calling Test Cleanup method for test class {0}: {1} - Error calling Test Cleanup method for test class {0}: {1} + Erro ao chamar o método Test Cleanup para a classe de teste {0}: {1} TestCleanup Stack Trace - TestCleanup Stack Trace + Rastreamento de pilha TestCleanup @@ -418,7 +418,7 @@ Error: {1} --- End of inner exception stack trace --- - --- End of inner exception stack trace --- + --- Fim do rastreamento de pilha de exceção interna --- @@ -428,12 +428,12 @@ Error: {1} UTA031: class {0} does not have valid TestContext property. TestContext must be of type TestContext, must be non-static, and must be public. For example: public TestContext TestContext. - UTA031: class {0} does not have valid TestContext property. TestContext must be of type TestContext, must be non-static, and must be public. For example: public TestContext TestContext. + UTA031: a classe {0} não tem uma propriedade TestContext válida. TestContext deve ser do tipo TestContext, não deve ser estático e deve ser público. Por exemplo: public TestContext TestContext. UTA007: Method {1} defined in class {0} does not have correct signature. Test method marked with the [TestMethod] attribute must be non-static, public, return-type as void and should not take any parameter. Example: public void Test.Class1.Test(). Additionally, if you are using async-await in test method then return-type must be 'Task' or 'ValueTask'. Example: public async Task Test.Class1.Test2() - UTA007: Method {1} defined in class {0} does not have correct signature. Test method marked with the [TestMethod] attribute must be non-static, public, return-type as void and should not take any parameter. Example: public void Test.Class1.Test(). Additionally, if you are using async-await in test method then return-type must be 'Task' or 'ValueTask'. Example: public async Task Test.Class1.Test2() + UTA007: o método {1} definido na classe {0} não tem a assinatura correta. O método de teste marcado com o atributo [TestMethod] deve ser não estático, público, com tipo de retorno nulo e não deve receber parâmetros. Exemplo: Test.Class1.Test() público nulo. Além disso, se você estiver usando async-await no método de teste, return-type deverá ser "Task" ou "ValueTask". Exemplo: public async Task Test.Class1.Test2() @@ -443,52 +443,52 @@ Error: {1} UTA014: {0}: Cannot define more than one method with the AssemblyCleanup attribute inside an assembly. - UTA014: {0}: Cannot define more than one method with the AssemblyCleanup attribute inside an assembly. + UTA014: {0}: não é possível definir mais de um método com o atributo AssemblyCleanup em um assembly. UTA013: {0}: Cannot define more than one method with the AssemblyInitialize attribute inside an assembly. - UTA013: {0}: Cannot define more than one method with the AssemblyInitialize attribute inside an assembly. + UTA013: {0}: não é possível definir mais de um método com o atributo AssemblyInitialize dentro de um assembly. UTA026: {0}: Cannot define more than one method with the ClassCleanup attribute inside a class. - UTA026: {0}: Cannot define more than one method with the ClassCleanup attribute inside a class. + UTA026: {0}: não é possível definir mais de um método com o atributo ClassCleanup dentro de uma classe. UTA025: {0}: Cannot define more than one method with the ClassInitialize attribute inside a class. - UTA025: {0}: Cannot define more than one method with the ClassInitialize attribute inside a class. + UTA025: {0}: não é possível definir mais de um método com o atributo ClassInitialize em uma classe. UTA024: {0}: Cannot define more than one method with the TestCleanup attribute. - UTA024: {0}: Cannot define more than one method with the TestCleanup attribute. + UTA024: {0}: não é possível definir mais de um método com o atributo TestCleanup. UTA018: {0}: Cannot define more than one method with the TestInitialize attribute. - UTA018: {0}: Cannot define more than one method with the TestInitialize attribute. + UTA018: {0}: não é possível definir mais de um método com o atributo TestInitialize. UTA001: TestClass attribute defined on non-public class {0} - UTA001: TestClass attribute defined on non-public class {0} + UTA001: atributo TestClass definido em classe não pública {0} UTA023: {0}: Cannot define predefined property {2} on method {1}. - UTA023: {0}: Cannot define predefined property {2} on method {1}. + UTA023: {0}: não é possível definir a propriedade predefinida {2} no método {1}. TestClass attribute defined on generic non-abstract class {0} - TestClass attribute defined on generic non-abstract class {0} + Atributo TestClass definido em uma classe genérica não abstrata {0} UTA021: {0}: Null or empty custom property defined on method {1}. The custom property must have a valid name. - UTA021: {0}: Null or empty custom property defined on method {1}. The custom property must have a valid name. + UTA021: {0}: Propriedade personalizada nula ou vazia definida no método {1}. A propriedade personalizada deve ter um nome válido. @@ -501,90 +501,90 @@ Error: {1} The ExpectedException attribute defined on test method {0}.{1} threw an exception during construction. {2} - The ExpectedException attribute defined on test method {0}.{1} threw an exception during construction. + O atributo ExpectedException definido no método de teste {0}.{1} emitiu uma exceção durante a construção. {2} Failed to obtain the exception thrown by test method {0}.{1}. - Failed to obtain the exception thrown by test method {0}.{1}. + Falha ao obter a exceção lançada pelo método de teste {0}.{1}. Initialization method {0}.{1} threw exception. {2}. - Initialization method {0}.{1} threw exception. {2}. + O método de inicialização {0}.{1} gerou exceção. {2}. Unable to create instance of class {0}. Error: {1}. - Unable to create instance of class {0}. Error: {1}. + Não é possível criar instância da classe {0}. Erro: {1}. Method {0}.{1} does not exist. - Method {0}.{1} does not exist. + O método {0}.{1} não existe. The test method '{0}.{1}' has multiple attributes derived from '{2}' defined on it. Only one such attribute is allowed. - The test method '{0}.{1}' has multiple attributes derived from '{2}' defined on it. Only one such attribute is allowed. + O método de teste '{0}.{1}' tem várias características derivadas de '{2}' definidas nele. Apenas uma dessas características tem permissão. Error in executing test. No result returned by extension. If using extension of TestMethodAttribute then please contact vendor. - Error in executing test. No result returned by extension. If using extension of TestMethodAttribute then please contact vendor. + Erro ao executar o teste. Nenhum resultado retornado pela extensão. Se usar a extensão de TestMethodAttribute, entre em contato com o fornecedor. Cannot find a valid constructor for test class '{0}'. Valid constructors are 'public' and either parameterless or with one parameter of type 'TestContext'. - Cannot find a valid constructor for test class '{0}'. Valid constructors are 'public' and either parameterless or with one parameter of type 'TestContext'. + Não é possível localizar um construtor válido para a classe de teste '{0}'. Construtores válidos são 'public' e sem parâmetros ou com um parâmetro do tipo 'TestContext'. Unable to find property {0}.TestContext. Error:{1}. - Unable to find property {0}.TestContext. Error:{1}. + Não é possível encontrar propriedade {0}.TestContext. Erro:{1}. Unable to set TestContext property for the class {0}. Error: {1}. - Unable to set TestContext property for the class {0}. Error: {1}. + Não é definir a propriedade TestContext para a classe {0}. Erro: {1}. The {0}.TestContext has incorrect type. - The {0}.TestContext has incorrect type. + O {0}.TestContext é do tipo incorreto. Method {0}.{1} has wrong signature. The method must be non-static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. - Method {0}.{1} has wrong signature. The method must be non-static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + O método {0}.{1} tem a assinatura incorreta. O método deve ser não estático, público, não deve retornar um valor e não deve receber nenhum parâmetro. Além disso, se você estiver usando async-await no método, o return-type deverá ser "Task" ou "ValueTask". Test method {0}.{1} threw exception: {2} - Test method {0}.{1} threw exception: + O método de teste {0}.{1} lançou a exceção: {2} Unable to get type {0}. Error: {1}. - Unable to get type {0}. Error: {1}. + Não é possível obter o tipo {0}. Erro: {1}. The called code threw an exception that was caught, but the exception value was null - The called code threw an exception that was caught, but the exception value was null + O código chamado lançou uma exceção que foi capturada, mas o valor da exceção era nulo {0} For UWP projects, if you are using UI objects in test consider using [UITestMethod] attribute instead of [TestMethod] to execute test in UI thread. - {0} For UWP projects, if you are using UI objects in test consider using [UITestMethod] attribute instead of [TestMethod] to execute test in UI thread. + {0} Para projetos UWP, se você está usando objetos de IU no teste, considere usar o atributo [UITestMethod] em vez de [TestMethod] para executar o teste no thread da IU. (Failed to get the message for an exception of type {0} due to an exception.) - (Failed to get the message for an exception of type {0} due to an exception.) + (Falha ao obter a mensagem para uma exceção do tipo {0} devido a uma exceção.) diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.ru.xlf b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.ru.xlf index e587b45d5b..ed4a232e4c 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.ru.xlf +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.ru.xlf @@ -4,52 +4,52 @@ Assembly cleanup method '{0}.{1}' timed out after {2}ms - Assembly cleanup method '{0}.{1}' timed out after {2}ms + Время ожидания метода очистки сборки "{0}.{1}" истекло через {2} мс Assembly cleanup method '{0}.{1}' was canceled - Assembly cleanup method '{0}.{1}' was canceled + Метод очистки сборки "{0}.{1}" отменен Assembly initialize method '{0}.{1}' timed out after {2}ms - Assembly initialize method '{0}.{1}' timed out after {2}ms + Время ожидания метода инициализации сборки "{0}.{1}" истекло через {2} мс Assembly initialize method '{0}.{1}' was canceled - Assembly initialize method '{0}.{1}' was canceled + Метод инициализации сборки "{0}.{1}" отменен MSTestAdapterV2 - MSTestAdapterV2 + MSTestAdapterV2 Exception occurred while enumerating IDataSource attribute on "{0}.{1}": {2} - Exception occurred while enumerating IDataSource attribute on "{0}.{1}": {2} + Возникло исключение при перечислении атрибута IDataSource в "{0}.{1}": {2} {0}: TypeName with namespace, {1}: Method name, {2}: Exception details Exception occurred while expanding IDataSource rows from attribute on "{0}.{1}": {2} - Exception occurred while expanding IDataSource rows from attribute on "{0}.{1}": {2} + Возникло исключение при развертывании строк IDataSource из атрибута "{0}.{1}": {2} {0}: TypeName with namespace, {1}: Method name, {2}: CannotExpandIDataSourceAttribute_DuplicateDisplayName or CannotExpandIDataSourceAttribute_CannotSerialize Data on index {0} for "{1}" cannot be serialized. All data provided through "IDataSource" should be serializable. If you need to test non-serializable data sources, please make sure you add "TestDataSourceDiscovery" attribute on your test assembly and set the discovery option to "DuringExecution". - Data on index {0} for "{1}" cannot be serialized. All data provided through "IDataSource" should be serializable. If you need to test non-serializable data sources, please make sure you add "TestDataSourceDiscovery" attribute on your test assembly and set the discovery option to "DuringExecution". + Не удается сериализовать данные в индексе {0} для "{1}". Все данные, предоставленные через IDataSource, должны быть сериализуемыми. Если необходимо протестировать несериализуемые источники данных, добавьте атрибут "TestDataSourceDiscovery" в тестовую сборку и установите для параметра обнаружения значение "DuringExecution". {0}: Zero based index if an element inside of an array, {1}: Test name Display name "{2}" on indexes {0} and {1} are duplicate. Display names should be unique. - Display name "{2}" on indexes {0} and {1} are duplicate. Display names should be unique. + Отображаемые имена "{2}" в индексах {0} и {1} дублируются. Отображаемые имена должны быть уникальными. {0}, {1}: Zero based index if an element inside of an array {2}: Test display name. @@ -62,34 +62,34 @@ Cannot run test method '{0}.{1}': Test data doesn't match method parameters. Either the count or types are different. Test expected {2} parameter(s), with types '{3}', but received {4} argument(s), with types '{5}'. - Cannot run test method '{0}.{1}': Test data doesn't match method parameters. Either the count or types are different. -Test expected {2} parameter(s), with types '{3}', -but received {4} argument(s), with types '{5}'. + Не удается запустить метод теста "{0}.{1}": тестовые данные не соответствуют параметрам метода. Не совпадают количество или типы. +Для теста ожидается следующее количество параметров: {2} типов "{3}", +но число полученных аргументов — {4} и они принадлежат к типам "{5}". Cannot run test method '{0}.{1}': Method has parameters, but does not define any test source. Use '[DataRow]', '[DynamicData]', or a custom 'ITestDataSource' data source to provide test data. - Cannot run test method '{0}.{1}': Method has parameters, but does not define any test source. Use '[DataRow]', '[DynamicData]', or a custom 'ITestDataSource' data source to provide test data. + Не удается запустить метод теста "{0}.{1}": метод имеет параметры, но не определяет источник теста. Используйте "[DataRow]", "[DynamicData]" или настраиваемый источник данных "ITestDataSource" для предоставления тестовых данных. Class cleanup method '{0}.{1}' timed out after {2}ms - Class cleanup method '{0}.{1}' timed out after {2}ms + Время ожидания метода очистки класса "{0}.{1}" истекло через {2} мс Class cleanup method '{0}.{1}' was canceled - Class cleanup method '{0}.{1}' was canceled + Метод очистки класса "{0}.{1}" отменен Class initialize method '{0}.{1}' timed out after {2}ms - Class initialize method '{0}.{1}' timed out after {2}ms + Время ожидания метода инициализации класса "{0}.{1}" истекло через {2} мс Class initialize method '{0}.{1}' was canceled - Class initialize method '{0}.{1}' was canceled + Метод инициализации класса "{0}.{1}" отменен @@ -99,17 +99,17 @@ but received {4} argument(s), with types '{5}'. MSTestAdapter failed to discover tests in class '{0}' of assembly '{1}' because {2}. - MSTestAdapter failed to discover tests in class '{0}' of assembly '{1}' because {2}. + Средству MSTestAdapter не удалось обнаружить тесты в классе "{0}" сборки "{1}", так как {2}. {0} (Data Row {1}) - {0} (Data Row {1}) + {0} (строка данных {1}) Debug Trace: - Debug Trace: + Трассировка отладки: @@ -179,79 +179,79 @@ but received {4} argument(s), with types '{5}'. [MSTest][Discovery][{0}] {1} - [MSTest][Discovery][{0}] {1} + [MSTest][Discovery][{0}] {1} Both '.runsettings' and '.testconfig.json' files have been detected. Please select only one of these test configuration files. - Both '.runsettings' and '.testconfig.json' files have been detected. Please select only one of these test configuration files. + Обнаружены одновременно файлы ".runsettings" и ".testconfig.json". Выберите только один из этих файлов тестовой конфигурации. {0}: {1} - {0}: {1} + {0}: {1} "{0}": (Failed to get exception description due to an exception of type "{1}". - "{0}": (Failed to get exception description due to an exception of type "{1}". + "{0}": (Не удалось получить описание исключения из-за исключения типа "{1}". {0}: Type of the original exception that we're trying to get the description of. {1}: Thrown exception Exceptions thrown: - Exceptions thrown: + Выданные исключения: This is usually precedes by TestAssembly_AssemblyDiscoveryFailure message, and preceded by list of exceptions thrown in a test discovery session. Test '{0}' was canceled - Test '{0}' was canceled + Тест "{0}" был отменен Test '{0}' timed out after {1}ms - Test '{0}' timed out after {1}ms + Время ожидания теста "{0}" истекло через {1} мс Getting custom attributes for type {0} threw exception (will ignore and use the reflection way): {1} - Getting custom attributes for type {0} threw exception (will ignore and use the reflection way): {1} + При получении настраиваемых атрибутов для типа {0} возникло исключение (оно будет проигнорировано и будет использовано отражение): {1} {0}: Attribute full type name. {1}: Exception description The type of the generic parameter '{0}' could not be inferred. - The type of the generic parameter '{0}' could not be inferred. + Не удалось определить тип универсального параметра "{0}". The generic test method '{0}' doesn't have arguments, so the generic parameter cannot be inferred. - The generic test method '{0}' doesn't have arguments, so the generic parameter cannot be inferred. + Универсальный метод "{0}" не имеет аргументов, поэтому невозможно вывести универсальный параметр. Found two conflicting types for generic parameter '{0}'. The conflicting types are '{1}' and '{2}'. - Found two conflicting types for generic parameter '{0}'. The conflicting types are '{1}' and '{2}'. + Обнаружены два конфликтующих типа для универсального параметра "{0}". Конфликтующие типы: "{1}" и "{2}". Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. - Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. + Для параметра "ClassCleanupLifecycle" указано недопустимое значение "{0}". Поддерживаемые области: {1}. 'ClassCleanupLifecycle' is a setting name that shouldn't be localized. Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. - Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. + В поле "Область" указано недопустимое значение "{0}". Поддерживаемые области: {1}. 'Scope' is a setting name that shouldn't be localized. Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. - Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. + В поле "Рабочие роли" указано недопустимое значение "{0}". Оно должно быть неотрицательным целым числом. `Workers` is a setting name that shouldn't be localized. Invalid settings '{0}'. Unexpected XmlAttribute: '{1}'. - Invalid settings '{0}'. Unexpected XmlAttribute: '{1}'. + Недопустимые параметры "{0}". Непредвиденный атрибут XmlAttribute: "{1}". @@ -261,7 +261,7 @@ but received {4} argument(s), with types '{5}'. Invalid settings '{0}'. Unexpected XmlElement: '{1}'. - Invalid settings '{0}'. Unexpected XmlElement: '{1}'. + Недопустимые параметры "{0}". Непредвиденный элемент XmlElement: "{1}". @@ -271,12 +271,12 @@ but received {4} argument(s), with types '{5}'. Invalid value '{0}' for runsettings entry '{1}', setting will be ignored. - Invalid value '{0}' for runsettings entry '{1}', setting will be ignored. + Недопустимое значение "{0}" для записи runsettings "{1}", параметр будет пропущен. Warning : A testsettings file or a vsmdi file is not supported with the MSTest V2 Adapter. - Warning : A testsettings file or a vsmdi file is not supported with the MSTest V2 Adapter. + Внимание! Адаптер MSTest версии 2 не поддерживает файл TESTSETTINGS или VSMDI. @@ -291,67 +291,67 @@ but received {4} argument(s), with types '{5}'. An older version of MSTestV2 package is loaded in assembly, test discovery might fail to discover all data tests if they depend on `.runsettings` file. - An older version of MSTestV2 package is loaded in assembly, test discovery might fail to discover all data tests if they depend on `.runsettings` file. + В сборку загружена старая версия пакета MSTestV2. При обнаружении тестов могут быть обнаружены не все тесты данных, если они зависят от файла ".runsettings". Runsettings entry '<ExecutionApartmentState>STA</ExecutionApartmentState>' is not supported on non-Windows OSes. - Runsettings entry '<ExecutionApartmentState>STA</ExecutionApartmentState>' is not supported on non-Windows OSes. + Запись Runsettings "<ExecutionApartmentState>STA</ExecutionApartmentState>" не поддерживается в ОС, отличных от Windows. Running tests in any of the provided sources is not supported for the selected platform - Running tests in any of the provided sources is not supported for the selected platform + Запуск тестов в любом из предоставленных источников не поддерживается на выбранной платформе Failed to discover tests from assembly {0}. Reason:{1} - Failed to discover tests from assembly {0}. Reason:{1} + Не удалось обнаружить тесты из сборки {0}. Причина:{1} File does not exist: {0} - File does not exist: {0} + Файл не существует: {0} Test cleanup method '{0}.{1}' timed out after {2}ms - Test cleanup method '{0}.{1}' timed out after {2}ms + Время ожидания метода очистки теста "{0}.{1}" истекло через {2} мс Test cleanup method '{0}.{1}' was canceled - Test cleanup method '{0}.{1}' was canceled + Метод очистки теста "{0}.{1}" отменен TestContext cannot be Null. - TestContext cannot be Null. + TestContext не может иметь значение NULL. TestContext Messages: - TestContext Messages: + Сообщения TestContext: Test initialize method '{0}.{1}' timed out after {2}ms - Test initialize method '{0}.{1}' timed out after {2}ms + Время ожидания метода инициализации теста "{0}.{1}" истекло через {2} мс Test initialize method '{0}.{1}' was canceled - Test initialize method '{0}.{1}' was canceled + Метод инициализации теста "{0}.{1}" отменен Test method {0} was not found. - Test method {0} was not found. + Метод теста {0} не найден. Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) - Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) + Включена параллелизация тестов для {0} (рабочие роли: {1}, область: {2}) `Workers` is a setting name that shouldn't be localized. 'Scope' is a setting name that shouldn't be localized. @@ -362,53 +362,53 @@ but received {4} argument(s), with types '{5}'. Unable to load types from the test source '{0}'. Some or all of the tests in this source may not be discovered. Error: {1} - Unable to load types from the test source '{0}'. Some or all of the tests in this source may not be discovered. -Error: {1} + Не удалось загрузить типы из тестового источника "{0}". В этом источнике могут быть не обнаружены некоторые или все тесты. +Ошибка: {1} Assembly Cleanup method {0}.{1} failed. Error Message: {2}. StackTrace: {3} - Assembly Cleanup method {0}.{1} failed. Error Message: {2}. StackTrace: {3} + Не удалось применить метод очистки сборки {0}.{1}. Сообщение об ошибке: {2}. Трассировка стека (StackTrace): {3}. Assembly Initialization method {0}.{1} threw exception. {2}: {3}. Aborting test execution. - Assembly Initialization method {0}.{1} threw exception. {2}: {3}. Aborting test execution. + Методом инициализации сборки {0}.{1} создано исключение. {2}: {3}. Выполнение теста прекращается. Class Cleanup method {0}.{1} failed. Error Message: {2}. Stack Trace: {3} - Class Cleanup method {0}.{1} failed. Error Message: {2}. Stack Trace: {3} + Не удалось применить метод очистки класса {0}.{1}. Сообщение об ошибке: {2}. Трассировка стека: {3}. Class Initialization method {0}.{1} threw exception. {2}: {3}. - Class Initialization method {0}.{1} threw exception. {2}: {3}. + Методом инициализации класса {0}.{1} создано исключение. {2}: {3}. Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. - Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + Метод {0}.{1} имеет неправильную сигнатуру. Метод должен быть статическим и открытым, не должен возвращать значение и принимать параметры. Кроме того, при использовании async-await в методе возвращаемое значение должно иметь тип "Task" или "ValueTask". Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should take a single parameter of type TestContext. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. - Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should take a single parameter of type TestContext. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + Метод {0}.{1} имеет неправильную сигнатуру. Метод должен быть статическим и открытым, не должен возвращать значение и должен принимать один параметр, имеющий тип TestContext. Кроме того, при использовании async-await в методе возвращаемое значение должно иметь тип "Task" или "ValueTask". TestCleanup method {0}.{1} threw exception. {2}. - TestCleanup method {0}.{1} threw exception. {2}. + Метод TestCleanup {0}.{1} создал исключение. {2}. Error calling Test Cleanup method for test class {0}: {1} - Error calling Test Cleanup method for test class {0}: {1} + Ошибка при вызове метода TestCleanup для тестового класса {0}: {1} TestCleanup Stack Trace - TestCleanup Stack Trace + Трассировка стека TestCleanup @@ -418,7 +418,7 @@ Error: {1} --- End of inner exception stack trace --- - --- End of inner exception stack trace --- + --- Конец трассировки стека внутренних исключений --- @@ -428,163 +428,163 @@ Error: {1} UTA031: class {0} does not have valid TestContext property. TestContext must be of type TestContext, must be non-static, and must be public. For example: public TestContext TestContext. - UTA031: class {0} does not have valid TestContext property. TestContext must be of type TestContext, must be non-static, and must be public. For example: public TestContext TestContext. + UTA031: в классе {0} отсутствует допустимое свойство TestContext. Свойство TestContext должно относиться к типу TestContext, быть нестатическим и открытым. Например: public TestContext TestContext. UTA007: Method {1} defined in class {0} does not have correct signature. Test method marked with the [TestMethod] attribute must be non-static, public, return-type as void and should not take any parameter. Example: public void Test.Class1.Test(). Additionally, if you are using async-await in test method then return-type must be 'Task' or 'ValueTask'. Example: public async Task Test.Class1.Test2() - UTA007: Method {1} defined in class {0} does not have correct signature. Test method marked with the [TestMethod] attribute must be non-static, public, return-type as void and should not take any parameter. Example: public void Test.Class1.Test(). Additionally, if you are using async-await in test method then return-type must be 'Task' or 'ValueTask'. Example: public async Task Test.Class1.Test2() + UTA007: метод {1}, определенный в классе {0}, имеет неправильную сигнатуру. Метод теста, помеченный атрибутом [TestMethod], должен быть нестатическим, открытым и иметь тип возвращаемого значения void; он также не должен принимать параметры. Пример: public void Test.Class1.Test(). Кроме того, при использовании async-await в методе теста возвращаемое значение должно иметь тип "Task" или "ValueTask". Пример: public async Task Test.Class1.Test2() UTA054: {0}.{1} has invalid Timeout attribute. The timeout must be an integer value greater than 0. - UTA054: {0}.{1} has invalid Timeout attribute. The timeout must be an integer value greater than 0. + UTA054: {0}. {1} имеет недопустимый атрибут времени ожидания. Значение времени ожидания должно быть положительным целым числом. UTA014: {0}: Cannot define more than one method with the AssemblyCleanup attribute inside an assembly. - UTA014: {0}: Cannot define more than one method with the AssemblyCleanup attribute inside an assembly. + UTA014: {0}: в сборке невозможно определить несколько методов с атрибутом AssemblyCleanup. UTA013: {0}: Cannot define more than one method with the AssemblyInitialize attribute inside an assembly. - UTA013: {0}: Cannot define more than one method with the AssemblyInitialize attribute inside an assembly. + UTA013: {0}: в сборке невозможно определить несколько методов с атрибутом AssemblyInitialize. UTA026: {0}: Cannot define more than one method with the ClassCleanup attribute inside a class. - UTA026: {0}: Cannot define more than one method with the ClassCleanup attribute inside a class. + UTA026: {0}: в классе невозможно определить несколько методов с атрибутом ClassCleanup. UTA025: {0}: Cannot define more than one method with the ClassInitialize attribute inside a class. - UTA025: {0}: Cannot define more than one method with the ClassInitialize attribute inside a class. + UTA025: {0}: в классе невозможно определить несколько методов с атрибутом ClassInitialize. UTA024: {0}: Cannot define more than one method with the TestCleanup attribute. - UTA024: {0}: Cannot define more than one method with the TestCleanup attribute. + UTA024: {0}: невозможно определить несколько методов с атрибутом TestCleanup. UTA018: {0}: Cannot define more than one method with the TestInitialize attribute. - UTA018: {0}: Cannot define more than one method with the TestInitialize attribute. + UTA018: {0}: невозможно определить несколько методов с атрибутом TestInitialize. UTA001: TestClass attribute defined on non-public class {0} - UTA001: TestClass attribute defined on non-public class {0} + UTA001: атрибут TestClass определен в классе {0}, не являющемся открытым UTA023: {0}: Cannot define predefined property {2} on method {1}. - UTA023: {0}: Cannot define predefined property {2} on method {1}. + UTA023: {0}: не удается определить предопределенное свойство {2} в методе {1}. TestClass attribute defined on generic non-abstract class {0} - TestClass attribute defined on generic non-abstract class {0} + Атрибут TestClass определен в универсальном неабстрактном классе {0} UTA021: {0}: Null or empty custom property defined on method {1}. The custom property must have a valid name. - UTA021: {0}: Null or empty custom property defined on method {1}. The custom property must have a valid name. + UTA021: {0}: в методе {1} определено пользовательское свойство, имя которого имеет значение NULL или пусто. Пользовательское свойство должно иметь допустимое имя. An unhandled exception was thrown by the 'Execute' method. Please report this error to the author of the attribute '{0}'. {1} - An unhandled exception was thrown by the 'Execute' method. Please report this error to the author of the attribute '{0}'. + Метод "Execute" сгенерировал необработанное исключение. Сообщите об этой ошибке автору атрибута "{0}". {1} The ExpectedException attribute defined on test method {0}.{1} threw an exception during construction. {2} - The ExpectedException attribute defined on test method {0}.{1} threw an exception during construction. + Атрибут ExpectedException, определенный в методе теста {0}.{1}, породил исключение во время создания. {2} Failed to obtain the exception thrown by test method {0}.{1}. - Failed to obtain the exception thrown by test method {0}.{1}. + Не удалось получить исключение, созданное методом теста {0}.{1}. Initialization method {0}.{1} threw exception. {2}. - Initialization method {0}.{1} threw exception. {2}. + Метод инициализации {0}.{1} вызвал исключение. {2}. Unable to create instance of class {0}. Error: {1}. - Unable to create instance of class {0}. Error: {1}. + Не удалось создать экземпляр класса {0}. Ошибка: {1}. Method {0}.{1} does not exist. - Method {0}.{1} does not exist. + Метод {0}.{1} не существует. The test method '{0}.{1}' has multiple attributes derived from '{2}' defined on it. Only one such attribute is allowed. - The test method '{0}.{1}' has multiple attributes derived from '{2}' defined on it. Only one such attribute is allowed. + У метода тестирования "{0}.{1}" есть несколько атрибутов, производных от заданного в нем "{2}". Допускается только один такой атрибут. Error in executing test. No result returned by extension. If using extension of TestMethodAttribute then please contact vendor. - Error in executing test. No result returned by extension. If using extension of TestMethodAttribute then please contact vendor. + Ошибка при выполнении теста. Расширение не возвратило результаты. Если используется расширение атрибута TestMethodAttribute, обратитесь к поставщику. Cannot find a valid constructor for test class '{0}'. Valid constructors are 'public' and either parameterless or with one parameter of type 'TestContext'. - Cannot find a valid constructor for test class '{0}'. Valid constructors are 'public' and either parameterless or with one parameter of type 'TestContext'. + Не удается найти допустимый конструктор для тестового класса "{0}". Допустимые конструкторы должны быть определены как "public" и либо не иметь параметров, либо иметь один параметр типа "TestContext". Unable to find property {0}.TestContext. Error:{1}. - Unable to find property {0}.TestContext. Error:{1}. + Не удается найти свойство {0}.TestContext. Ошибка: {1}. Unable to set TestContext property for the class {0}. Error: {1}. - Unable to set TestContext property for the class {0}. Error: {1}. + Не удалось задать свойство TestContext для класса {0}. Ошибка: {1}. The {0}.TestContext has incorrect type. - The {0}.TestContext has incorrect type. + Для свойства {0}.TestContext указан неправильный тип. Method {0}.{1} has wrong signature. The method must be non-static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. - Method {0}.{1} has wrong signature. The method must be non-static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + Метод {0}.{1} имеет неправильную сигнатуру. Метод должен быть нестатическим и открытым, не должен возвращать значение и принимать параметры. Кроме того, при использовании async-await в методе возвращаемое значение должно иметь тип "Task" или "ValueTask". Test method {0}.{1} threw exception: {2} - Test method {0}.{1} threw exception: -{2} + Метод теста {0}.{1} создал исключение: +{2}. Unable to get type {0}. Error: {1}. - Unable to get type {0}. Error: {1}. + Не удается получить тип {0}. Ошибка: {1}. The called code threw an exception that was caught, but the exception value was null - The called code threw an exception that was caught, but the exception value was null + Вызванный код вызвал исключение, которое было перехвачено, но значение исключения было равно NULL {0} For UWP projects, if you are using UI objects in test consider using [UITestMethod] attribute instead of [TestMethod] to execute test in UI thread. - {0} For UWP projects, if you are using UI objects in test consider using [UITestMethod] attribute instead of [TestMethod] to execute test in UI thread. + {0} В проектах UWP, если в тесте используются объекты пользовательского интерфейса, рассмотрите возможность использования атрибута [UITestMethod] вместо атрибута [TestMethod] для выполнения теста в потоке пользовательского интерфейса. (Failed to get the message for an exception of type {0} due to an exception.) - (Failed to get the message for an exception of type {0} due to an exception.) + (Не удалось получить сообщение для исключения с типом {0} в связи с возникновением исключения.) diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.tr.xlf b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.tr.xlf index b7c43c2674..c09bd8d4e0 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.tr.xlf +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.tr.xlf @@ -4,52 +4,52 @@ Assembly cleanup method '{0}.{1}' timed out after {2}ms - Assembly cleanup method '{0}.{1}' timed out after {2}ms + '{0}.{1}' derleme temizleme yöntemi {2}ms sonra zaman aşımına uğradı Assembly cleanup method '{0}.{1}' was canceled - Assembly cleanup method '{0}.{1}' was canceled + '{0}.{1}' bütünleştirilmiş kod temizleme yöntemi iptal edildi Assembly initialize method '{0}.{1}' timed out after {2}ms - Assembly initialize method '{0}.{1}' timed out after {2}ms + '{0}.{1}' derleme başlatma yöntemi {2}ms sonra zaman aşımına uğradı Assembly initialize method '{0}.{1}' was canceled - Assembly initialize method '{0}.{1}' was canceled + '{0}.{1}' derleme başlatma yöntemi iptal edildi MSTestAdapterV2 - MSTestAdapterV2 + MSTestAdapterV2 Exception occurred while enumerating IDataSource attribute on "{0}.{1}": {2} - Exception occurred while enumerating IDataSource attribute on "{0}.{1}": {2} + "{0}.{1} " üzerinde IDataSource özniteliği numaralandırılırken özel durum oluştu: {2} {0}: TypeName with namespace, {1}: Method name, {2}: Exception details Exception occurred while expanding IDataSource rows from attribute on "{0}.{1}": {2} - Exception occurred while expanding IDataSource rows from attribute on "{0}.{1}": {2} + "{0}. {1}" üzerindeki öznitelikten IDataSource satırları genişletilirken özel durum oluştu: {2} {0}: TypeName with namespace, {1}: Method name, {2}: CannotExpandIDataSourceAttribute_DuplicateDisplayName or CannotExpandIDataSourceAttribute_CannotSerialize Data on index {0} for "{1}" cannot be serialized. All data provided through "IDataSource" should be serializable. If you need to test non-serializable data sources, please make sure you add "TestDataSourceDiscovery" attribute on your test assembly and set the discovery option to "DuringExecution". - Data on index {0} for "{1}" cannot be serialized. All data provided through "IDataSource" should be serializable. If you need to test non-serializable data sources, please make sure you add "TestDataSourceDiscovery" attribute on your test assembly and set the discovery option to "DuringExecution". + "{1}" için {0} indeksindeki veriler serileştirilemez. "IDataSource" aracılığıyla sağlanan tüm veriler serileştirilebilir olmalıdır. Serileştirilemeyen veri kaynaklarını test etmeniz gerekiyorsa, lütfen test derlemenize "TestDataSourceDiscovery" özniteliğini eklediğinizden ve keşif seçeneğini "DuringExecution" olarak ayarladığınızdan emin olun. {0}: Zero based index if an element inside of an array, {1}: Test name Display name "{2}" on indexes {0} and {1} are duplicate. Display names should be unique. - Display name "{2}" on indexes {0} and {1} are duplicate. Display names should be unique. + {0} ve {1}dizinlerinde görünen ad " {2}" yineleniyor. Görünen adlar benzersiz olmalıdır. {0}, {1}: Zero based index if an element inside of an array {2}: Test display name. @@ -69,27 +69,27 @@ but received {4} argument(s), with types '{5}'. Cannot run test method '{0}.{1}': Method has parameters, but does not define any test source. Use '[DataRow]', '[DynamicData]', or a custom 'ITestDataSource' data source to provide test data. - Cannot run test method '{0}.{1}': Method has parameters, but does not define any test source. Use '[DataRow]', '[DynamicData]', or a custom 'ITestDataSource' data source to provide test data. + '{0}.{1}' test yöntemi çalıştırılamıyor: Yöntemin parametreleri var ancak herhangi bir test kaynağı tanımlamıyor. Test verilerini sağlamak için '[DataRow]', '[DynamicData]' veya özel bir 'ITestDataSource' veri kaynağı kullanın. Class cleanup method '{0}.{1}' timed out after {2}ms - Class cleanup method '{0}.{1}' timed out after {2}ms + '{0}.{1}' sınıf temizleme yöntemi {2}ms sonra zaman aşımına uğradı Class cleanup method '{0}.{1}' was canceled - Class cleanup method '{0}.{1}' was canceled + '{0}.{1}' sınıf temizleme yöntemi iptal edildi Class initialize method '{0}.{1}' timed out after {2}ms - Class initialize method '{0}.{1}' timed out after {2}ms + '{0}.{1}' sınıf başlatma yöntemi {2}ms sonra zaman aşımına uğradı Class initialize method '{0}.{1}' was canceled - Class initialize method '{0}.{1}' was canceled + '{0}.{1}' sınıf başlatma yöntemi iptal edildi @@ -99,17 +99,17 @@ but received {4} argument(s), with types '{5}'. MSTestAdapter failed to discover tests in class '{0}' of assembly '{1}' because {2}. - MSTestAdapter failed to discover tests in class '{0}' of assembly '{1}' because {2}. + MSTestAdapter, '{1}' bütünleştirilmiş kodunun '{0}' sınıfındaki testleri bulamadı. Nedeni: {2}. {0} (Data Row {1}) - {0} (Data Row {1}) + {0} (Veri Satırı {1}) Debug Trace: - Debug Trace: + Hata Ayıklama İzleyici: @@ -179,28 +179,28 @@ but received {4} argument(s), with types '{5}'. [MSTest][Discovery][{0}] {1} - [MSTest][Discovery][{0}] {1} + [MSTest][Discovery][{0}] {1} Both '.runsettings' and '.testconfig.json' files have been detected. Please select only one of these test configuration files. - Both '.runsettings' and '.testconfig.json' files have been detected. Please select only one of these test configuration files. + Hem '.runsettings' hem de '.testconfig.json' dosyaları algılandı. Lütfen bu test yapılandırma dosyalarından yalnızca birini seçin. {0}: {1} - {0}: {1} + {0}: {1} "{0}": (Failed to get exception description due to an exception of type "{1}". - "{0}": (Failed to get exception description due to an exception of type "{1}". + "{0}": ("{1}" türündeki bir istisna nedeniyle özel durum açıklaması alınamadı. {0}: Type of the original exception that we're trying to get the description of. {1}: Thrown exception Exceptions thrown: - Exceptions thrown: + Oluşturulan özel durumlar: This is usually precedes by TestAssembly_AssemblyDiscoveryFailure message, and preceded by list of exceptions thrown in a test discovery session. @@ -215,7 +215,7 @@ but received {4} argument(s), with types '{5}'. Getting custom attributes for type {0} threw exception (will ignore and use the reflection way): {1} - Getting custom attributes for type {0} threw exception (will ignore and use the reflection way): {1} + {0} tipi için özel niteliklerin alınması özel durum oluşturdu (yok sayar ve yansıma yolunu kullanır): {1} {0}: Attribute full type name. {1}: Exception description @@ -236,22 +236,22 @@ but received {4} argument(s), with types '{5}'. Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. - Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. + 'ClassCleanupLifecycle' için geçersiz '{0}' değeri belirtildi. Desteklenen kapsamlar {1}'dir. 'ClassCleanupLifecycle' is a setting name that shouldn't be localized. Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. - Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. + 'Scope' için geçersiz '{0}' değeri belirtildi. Desteklenen kapsamlar {1}. 'Scope' is a setting name that shouldn't be localized. Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. - Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. + 'Workers' için geçersiz '{0}' değeri belirtildi. Değer negatif olmayan bir tamsayı olmalıdır. `Workers` is a setting name that shouldn't be localized. Invalid settings '{0}'. Unexpected XmlAttribute: '{1}'. - Invalid settings '{0}'. Unexpected XmlAttribute: '{1}'. + Geçersiz '{0}' ayarları. Beklenmeyen XmlAttribute: '{1}'. @@ -261,7 +261,7 @@ but received {4} argument(s), with types '{5}'. Invalid settings '{0}'. Unexpected XmlElement: '{1}'. - Invalid settings '{0}'. Unexpected XmlElement: '{1}'. + Geçersiz '{0}' ayarları. Beklenmeyen XmlElement: '{1}'. @@ -271,12 +271,12 @@ but received {4} argument(s), with types '{5}'. Invalid value '{0}' for runsettings entry '{1}', setting will be ignored. - Invalid value '{0}' for runsettings entry '{1}', setting will be ignored. + '{1}' çalıştırma ayarları girişi için '{0}' değeri geçersiz, ayar yoksayılacak. Warning : A testsettings file or a vsmdi file is not supported with the MSTest V2 Adapter. - Warning : A testsettings file or a vsmdi file is not supported with the MSTest V2 Adapter. + Uyarı : MSTest V2 Adapter ile bir testsettings dosyası veya bir vsmdi dosyası desteklenmez. @@ -291,67 +291,67 @@ but received {4} argument(s), with types '{5}'. An older version of MSTestV2 package is loaded in assembly, test discovery might fail to discover all data tests if they depend on `.runsettings` file. - An older version of MSTestV2 package is loaded in assembly, test discovery might fail to discover all data tests if they depend on `.runsettings` file. + Montaja MSTestV2 paketinin daha eski bir sürümü yüklenir, test keşfi, `.runsettings` dosyasına bağlılarsa tüm veri testlerini keşfetmede başarısız olabilir. Runsettings entry '<ExecutionApartmentState>STA</ExecutionApartmentState>' is not supported on non-Windows OSes. - Runsettings entry '<ExecutionApartmentState>STA</ExecutionApartmentState>' is not supported on non-Windows OSes. + '<ExecutionApartmentState>STA</ExecutionApartmentState>' çalışma ayarları girişi Windows dışı işletim sistemlerinde desteklenmiyor. Running tests in any of the provided sources is not supported for the selected platform - Running tests in any of the provided sources is not supported for the selected platform + Testlerin sağlanan kaynakların herhangi birinde çalıştırılması seçili platformda desteklenmiyor Failed to discover tests from assembly {0}. Reason:{1} - Failed to discover tests from assembly {0}. Reason:{1} + {0} bütünleştirilmiş kodundan testler bulunamadı. Neden:{1} File does not exist: {0} - File does not exist: {0} + Dosya yok: {0} Test cleanup method '{0}.{1}' timed out after {2}ms - Test cleanup method '{0}.{1}' timed out after {2}ms + '{0}.{1}' test temizleme yöntemi {2}ms sonra zaman aşımına uğradı Test cleanup method '{0}.{1}' was canceled - Test cleanup method '{0}.{1}' was canceled + '{0}.{1}' test temizleme yöntemi iptal edildi TestContext cannot be Null. - TestContext cannot be Null. + TestContext, Null olamaz. TestContext Messages: - TestContext Messages: + TestContext İletileri: Test initialize method '{0}.{1}' timed out after {2}ms - Test initialize method '{0}.{1}' timed out after {2}ms + '{0}.{1}' test başlatma yöntemi {2}ms sonra zaman aşımına uğradı Test initialize method '{0}.{1}' was canceled - Test initialize method '{0}.{1}' was canceled + '{0}.{1}' test başlatma yöntemi iptal edildi Test method {0} was not found. - Test method {0} was not found. + {0} test metodu bulunamadı. Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) - Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) + {0} için Test Paralelleştirme etkin (Çalışanlar: {1}, Kapsam: {2}). `Workers` is a setting name that shouldn't be localized. 'Scope' is a setting name that shouldn't be localized. @@ -362,53 +362,53 @@ but received {4} argument(s), with types '{5}'. Unable to load types from the test source '{0}'. Some or all of the tests in this source may not be discovered. Error: {1} - Unable to load types from the test source '{0}'. Some or all of the tests in this source may not be discovered. -Error: {1} + '{0}' test kaynağından türler yüklenemiyor. Kaynaktaki testlerin bazıları veya tümü bulunamayabilir. +Hata: {1} Assembly Cleanup method {0}.{1} failed. Error Message: {2}. StackTrace: {3} - Assembly Cleanup method {0}.{1} failed. Error Message: {2}. StackTrace: {3} + Bütünleştirilmiş Kod Temizleme metodu ({0}.{1}) başarısız oldu. Hata İletisi: {2}. StackTrace: {3} Assembly Initialization method {0}.{1} threw exception. {2}: {3}. Aborting test execution. - Assembly Initialization method {0}.{1} threw exception. {2}: {3}. Aborting test execution. + Bütünleştirilmiş Kod Başlatma metodu ({0}.{1}) özel durum oluşturdu. {2}: {3}. Test yürütmesi durduruluyor. Class Cleanup method {0}.{1} failed. Error Message: {2}. Stack Trace: {3} - Class Cleanup method {0}.{1} failed. Error Message: {2}. Stack Trace: {3} + Sınıf Temizleme metodu ({0}.{1}) başarısız oldu. Hata İletisi: {2}. Yığın İzlemesi: {3} Class Initialization method {0}.{1} threw exception. {2}: {3}. - Class Initialization method {0}.{1} threw exception. {2}: {3}. + Sınıf Başlatma metodu ({0}.{1}) özel durum oluşturdu. {2}: {3}. Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. - Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + {0}.{1} yönteminin imzası yanlış. Yöntem statik, genel, değer döndürmeyen bir yöntem olmalı, hiçbir parametre almamalıdır. Bunlara ek olarak, yöntemde async-await kullanıyorsanız return-type değeri 'Task' veya 'ValueTask' olmalıdır. Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should take a single parameter of type TestContext. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. - Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should take a single parameter of type TestContext. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + {0}.{1} yönteminin imzası yanlış. Yöntem statik, genel, değer döndürmeyen bir yöntem olmalı ve TestContext türünde tek bir parametre almalıdır. Bunlara ek olarak, yöntemde async-await kullanıyorsanız return-type değeri 'Task' veya 'ValueTask' olmalıdır. TestCleanup method {0}.{1} threw exception. {2}. - TestCleanup method {0}.{1} threw exception. {2}. + TestCleanup metodu {0}.{1} özel durum oluşturdu. {2}. Error calling Test Cleanup method for test class {0}: {1} - Error calling Test Cleanup method for test class {0}: {1} + {0} test sınıfı için Test Temizleme metodu çağrılırken hata oluştu: {1} TestCleanup Stack Trace - TestCleanup Stack Trace + TestCleanup Yığın İzleme @@ -418,7 +418,7 @@ Error: {1} --- End of inner exception stack trace --- - --- End of inner exception stack trace --- + --- İç özel durum yığın izlemesinin sonu --- @@ -428,67 +428,67 @@ Error: {1} UTA031: class {0} does not have valid TestContext property. TestContext must be of type TestContext, must be non-static, and must be public. For example: public TestContext TestContext. - UTA031: class {0} does not have valid TestContext property. TestContext must be of type TestContext, must be non-static, and must be public. For example: public TestContext TestContext. + UTA031: {0}sınıfı geçerli bir TestContext özelliğine sahip değil. TestContext, TestContext türünde olmalı, static olmamalı ve public olmalıdır. Örnek: public TestContext TestContext. UTA007: Method {1} defined in class {0} does not have correct signature. Test method marked with the [TestMethod] attribute must be non-static, public, return-type as void and should not take any parameter. Example: public void Test.Class1.Test(). Additionally, if you are using async-await in test method then return-type must be 'Task' or 'ValueTask'. Example: public async Task Test.Class1.Test2() - UTA007: Method {1} defined in class {0} does not have correct signature. Test method marked with the [TestMethod] attribute must be non-static, public, return-type as void and should not take any parameter. Example: public void Test.Class1.Test(). Additionally, if you are using async-await in test method then return-type must be 'Task' or 'ValueTask'. Example: public async Task Test.Class1.Test2() + UTA007: {0} sınıfında tanımlanan {1} yönteminin imzası doğru değil. [TestMethod] özniteliğiyle işaretlenmiş test yöntemi statik olmayan, genel, dönüş türü void olan bir yöntem olmalıdır ve hiçbir parametre almamalıdır. Örnek: public void Test.Class1.Test(). Bunlara ek olarak, test metodunda async-await kullanıyorsanız return-type değeri 'Task' veya 'ValueTask' olmalıdır. Örnek: public async Task Test.Class1.Test2() UTA054: {0}.{1} has invalid Timeout attribute. The timeout must be an integer value greater than 0. - UTA054: {0}.{1} has invalid Timeout attribute. The timeout must be an integer value greater than 0. + UTA054: {0}.{1} Timeout özniteliği geçersiz. Zaman aşımı değeri 0'dan büyük bir tamsayı olmalıdır. UTA014: {0}: Cannot define more than one method with the AssemblyCleanup attribute inside an assembly. - UTA014: {0}: Cannot define more than one method with the AssemblyCleanup attribute inside an assembly. + UTA014: {0}: Bir bütünleştirilmiş kod içinde AssemblyCleanup özniteliği ile birden fazla metot tanımlanamaz. UTA013: {0}: Cannot define more than one method with the AssemblyInitialize attribute inside an assembly. - UTA013: {0}: Cannot define more than one method with the AssemblyInitialize attribute inside an assembly. + UTA013: {0}: Bir bütünleştirilmiş kod içinde AssemblyInitialize özniteliği ile birden fazla metot tanımlanamaz. UTA026: {0}: Cannot define more than one method with the ClassCleanup attribute inside a class. - UTA026: {0}: Cannot define more than one method with the ClassCleanup attribute inside a class. + UTA026: {0}: Bir sınıf içinde ClassCleanup özniteliği ile birden fazla metot tanımlanamaz. UTA025: {0}: Cannot define more than one method with the ClassInitialize attribute inside a class. - UTA025: {0}: Cannot define more than one method with the ClassInitialize attribute inside a class. + UTA025: {0}: Bir sınıf içinde ClassInitialize özniteliği ile birden fazla metot tanımlanamaz. UTA024: {0}: Cannot define more than one method with the TestCleanup attribute. - UTA024: {0}: Cannot define more than one method with the TestCleanup attribute. + UTA024: {0}: TestCleanup özniteliği ile birden fazla metot tanımlanamaz. UTA018: {0}: Cannot define more than one method with the TestInitialize attribute. - UTA018: {0}: Cannot define more than one method with the TestInitialize attribute. + UTA018: {0}: TestInitialize özniteliği ile birden fazla metot tanımlanamaz. UTA001: TestClass attribute defined on non-public class {0} - UTA001: TestClass attribute defined on non-public class {0} + UTA001: TestClass özniteliği genel olmayan {0} sınıfında tanımlanmış UTA023: {0}: Cannot define predefined property {2} on method {1}. - UTA023: {0}: Cannot define predefined property {2} on method {1}. + UTA023: {0}: Önceden tanımlanmış {2} özelliği {1} metodunda tanımlanamaz. TestClass attribute defined on generic non-abstract class {0} - TestClass attribute defined on generic non-abstract class {0} + {0} genel soyut olmayan sınıf üzerinde tanımlanan TestClass özniteliği UTA021: {0}: Null or empty custom property defined on method {1}. The custom property must have a valid name. - UTA021: {0}: Null or empty custom property defined on method {1}. The custom property must have a valid name. + UTA021: {0}: {1} metodunda null veya boş özel özellik tanımlanmış. Özel özellik geçerli bir ada sahip olmalıdır. @@ -501,90 +501,90 @@ Error: {1} The ExpectedException attribute defined on test method {0}.{1} threw an exception during construction. {2} - The ExpectedException attribute defined on test method {0}.{1} threw an exception during construction. + {0}.{1} test yöntemi üzerinde tanımlanan ExpectedException özniteliği, oluşturma sırasında bir özel durum oluşturdu. {2} Failed to obtain the exception thrown by test method {0}.{1}. - Failed to obtain the exception thrown by test method {0}.{1}. + {0}.{1} metodu tarafından oluşturulan özel durum alınamadı. Initialization method {0}.{1} threw exception. {2}. - Initialization method {0}.{1} threw exception. {2}. + Başlatma metodu {0}.{1} özel durum oluşturdu. {2}. Unable to create instance of class {0}. Error: {1}. - Unable to create instance of class {0}. Error: {1}. + {0} sınıfının örneği oluşturulamıyor. Hata: {1}. Method {0}.{1} does not exist. - Method {0}.{1} does not exist. + {0}.{1} metodu yok. The test method '{0}.{1}' has multiple attributes derived from '{2}' defined on it. Only one such attribute is allowed. - The test method '{0}.{1}' has multiple attributes derived from '{2}' defined on it. Only one such attribute is allowed. + “{0}.{1}” test yöntemi, üzerinde tanımlanan “{2}” öğesinden türetilmiş birden fazla öznitelik içeriyor. Bu türde yalnızca bir tane özniteliğe izin verilir. Error in executing test. No result returned by extension. If using extension of TestMethodAttribute then please contact vendor. - Error in executing test. No result returned by extension. If using extension of TestMethodAttribute then please contact vendor. + Test yürütülürken hata oluştu. Uzantı tarafından hiç sonuç döndürülmedi. TestMethodAttribute uzantısı kullanılıyorsa, lütfen satıcıya başvurun. Cannot find a valid constructor for test class '{0}'. Valid constructors are 'public' and either parameterless or with one parameter of type 'TestContext'. - Cannot find a valid constructor for test class '{0}'. Valid constructors are 'public' and either parameterless or with one parameter of type 'TestContext'. + '{0}' test sınıfı için geçerli bir oluşturucu bulunamıyor. Geçerli oluşturucular 'public' ve parametresiz veya 'TestContext' türünde tek bir parametre içeriyor. Unable to find property {0}.TestContext. Error:{1}. - Unable to find property {0}.TestContext. Error:{1}. + {0}.TestContext özelliği bulunamıyor. Hata:{1}. Unable to set TestContext property for the class {0}. Error: {1}. - Unable to set TestContext property for the class {0}. Error: {1}. + {0} sınıfı için TestContext özelliği ayarlanamıyor. Hata: {1}. The {0}.TestContext has incorrect type. - The {0}.TestContext has incorrect type. + {0}.TestContext yanlış türe sahip. Method {0}.{1} has wrong signature. The method must be non-static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. - Method {0}.{1} has wrong signature. The method must be non-static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + {0}.{1} yönteminin imzası yanlış. Yöntem statik olmayan, genel, değer döndürmeyen bir yöntem olmalı, hiçbir parametre almamalıdır. Bunlara ek olarak, yöntemde async-await kullanıyorsanız return-type değeri 'Task' veya 'ValueTask' olmalıdır. Test method {0}.{1} threw exception: {2} - Test method {0}.{1} threw exception: + {0}.{1} test metodu özel durum oluşturdu: {2} Unable to get type {0}. Error: {1}. - Unable to get type {0}. Error: {1}. + {0} türü alınamıyor. Hata: {1}. The called code threw an exception that was caught, but the exception value was null - The called code threw an exception that was caught, but the exception value was null + Çağrılan kod, yakalanan bir özel durum yarattı, ancak özel durum değeri boştu {0} For UWP projects, if you are using UI objects in test consider using [UITestMethod] attribute instead of [TestMethod] to execute test in UI thread. - {0} For UWP projects, if you are using UI objects in test consider using [UITestMethod] attribute instead of [TestMethod] to execute test in UI thread. + {0} UWP projeleri için testte UI nesneleri kullanıyorsanız, testi UI iş parçacığında yürütmek için [TestMethod] yerine [UITestMethod] özniteliğini kullanabilirsiniz. (Failed to get the message for an exception of type {0} due to an exception.) - (Failed to get the message for an exception of type {0} due to an exception.) + (Bir özel durum nedeniyle, {0} türündeki özel durum iletisi alınamadı.) diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.zh-Hans.xlf b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.zh-Hans.xlf index 9538daa867..051d3f651a 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.zh-Hans.xlf +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.zh-Hans.xlf @@ -4,52 +4,52 @@ Assembly cleanup method '{0}.{1}' timed out after {2}ms - Assembly cleanup method '{0}.{1}' timed out after {2}ms + 程序集清理方法“{0}.{1}”在 {2} ms 后超时 Assembly cleanup method '{0}.{1}' was canceled - Assembly cleanup method '{0}.{1}' was canceled + 已取消程序集清理方法“{0}.{1}” Assembly initialize method '{0}.{1}' timed out after {2}ms - Assembly initialize method '{0}.{1}' timed out after {2}ms + 程序集初始化方法“{0}.{1}”在 {2} ms 后超时 Assembly initialize method '{0}.{1}' was canceled - Assembly initialize method '{0}.{1}' was canceled + 已取消程序集初始化方法“{0}.{1}” MSTestAdapterV2 - MSTestAdapterV2 + MSTestAdapterV2 Exception occurred while enumerating IDataSource attribute on "{0}.{1}": {2} - Exception occurred while enumerating IDataSource attribute on "{0}.{1}": {2} + 枚举 {0} 上的 IDataSource 属性时发生异常。{1}": {2} {0}: TypeName with namespace, {1}: Method name, {2}: Exception details Exception occurred while expanding IDataSource rows from attribute on "{0}.{1}": {2} - Exception occurred while expanding IDataSource rows from attribute on "{0}.{1}": {2} + 从“{0}.{1}”上的属性扩展 IDataSource 行时出现异常: {2} {0}: TypeName with namespace, {1}: Method name, {2}: CannotExpandIDataSourceAttribute_DuplicateDisplayName or CannotExpandIDataSourceAttribute_CannotSerialize Data on index {0} for "{1}" cannot be serialized. All data provided through "IDataSource" should be serializable. If you need to test non-serializable data sources, please make sure you add "TestDataSourceDiscovery" attribute on your test assembly and set the discovery option to "DuringExecution". - Data on index {0} for "{1}" cannot be serialized. All data provided through "IDataSource" should be serializable. If you need to test non-serializable data sources, please make sure you add "TestDataSourceDiscovery" attribute on your test assembly and set the discovery option to "DuringExecution". + 无法序列化“{1}”的索引 {0} 上的数据。通过“IDataSource”提供的所有数据都应可序列化。如果需要测试不可序列化的数据源,请确保在测试程序集上添加“TestDataSourceDiscovery”属性,并将发现选项设置为“DuringExecution”。 {0}: Zero based index if an element inside of an array, {1}: Test name Display name "{2}" on indexes {0} and {1} are duplicate. Display names should be unique. - Display name "{2}" on indexes {0} and {1} are duplicate. Display names should be unique. + 索引 {0} 和 {1} 上的显示名称“{2}”重复。显示名称应是唯一的。 {0}, {1}: Zero based index if an element inside of an array {2}: Test display name. @@ -62,34 +62,34 @@ Cannot run test method '{0}.{1}': Test data doesn't match method parameters. Either the count or types are different. Test expected {2} parameter(s), with types '{3}', but received {4} argument(s), with types '{5}'. - Cannot run test method '{0}.{1}': Test data doesn't match method parameters. Either the count or types are different. -Test expected {2} parameter(s), with types '{3}', -but received {4} argument(s), with types '{5}'. + 无法运行测试方法“{0}.{1}”: 测试数据与方法参数不匹配。计数或类型不同。 +测试需要类型为“{3}”的 {2} 参数, +但收到了类型为“{5}”的 {4} 参数。 Cannot run test method '{0}.{1}': Method has parameters, but does not define any test source. Use '[DataRow]', '[DynamicData]', or a custom 'ITestDataSource' data source to provide test data. - Cannot run test method '{0}.{1}': Method has parameters, but does not define any test source. Use '[DataRow]', '[DynamicData]', or a custom 'ITestDataSource' data source to provide test data. + 无法运行测试方法“{0}.{1}”: 方法具有参数,但未定义任何测试源。使用 “[DataRow]”、“[DynamicData]” 或自定义 “ITestDataSource” 数据源提供测试数据。 Class cleanup method '{0}.{1}' timed out after {2}ms - Class cleanup method '{0}.{1}' timed out after {2}ms + 类清理方法“{0}.{1}”在 {2} ms 后超时 Class cleanup method '{0}.{1}' was canceled - Class cleanup method '{0}.{1}' was canceled + 已取消类清理方法“{0}.{1}” Class initialize method '{0}.{1}' timed out after {2}ms - Class initialize method '{0}.{1}' timed out after {2}ms + 类初始化方法“{0}.{1}”在 {2} ms 后超时 Class initialize method '{0}.{1}' was canceled - Class initialize method '{0}.{1}' was canceled + 已取消类初始化方法“{0}.{1}” @@ -99,17 +99,17 @@ but received {4} argument(s), with types '{5}'. MSTestAdapter failed to discover tests in class '{0}' of assembly '{1}' because {2}. - MSTestAdapter failed to discover tests in class '{0}' of assembly '{1}' because {2}. + 由于 {2},MSTestAdapter 未能在程序集“{1}”的类“{0}”中发现测试。 {0} (Data Row {1}) - {0} (Data Row {1}) + {0} (数据行 {1}) Debug Trace: - Debug Trace: + 调试跟踪: @@ -179,79 +179,79 @@ but received {4} argument(s), with types '{5}'. [MSTest][Discovery][{0}] {1} - [MSTest][Discovery][{0}] {1} + [MSTest][发现][{0}] {1} Both '.runsettings' and '.testconfig.json' files have been detected. Please select only one of these test configuration files. - Both '.runsettings' and '.testconfig.json' files have been detected. Please select only one of these test configuration files. + 检测到 ".runsettings" 和 ".testconfig.json" 文件。请仅选择其中一个测试配置文件。 {0}: {1} - {0}: {1} + {0}: {1} "{0}": (Failed to get exception description due to an exception of type "{1}". - "{0}": (Failed to get exception description due to an exception of type "{1}". + “{0}”:(由于类型“{1}”异常,无法获取异常说明。 {0}: Type of the original exception that we're trying to get the description of. {1}: Thrown exception Exceptions thrown: - Exceptions thrown: + 引发的异常: This is usually precedes by TestAssembly_AssemblyDiscoveryFailure message, and preceded by list of exceptions thrown in a test discovery session. Test '{0}' was canceled - Test '{0}' was canceled + 测试“{0}”已取消 Test '{0}' timed out after {1}ms - Test '{0}' timed out after {1}ms + 测试“{0}”在 {1} 毫秒后超时 Getting custom attributes for type {0} threw exception (will ignore and use the reflection way): {1} - Getting custom attributes for type {0} threw exception (will ignore and use the reflection way): {1} + 获取类型 {0} 自定义属性引发异常(将忽略并使用反射方式): {1} {0}: Attribute full type name. {1}: Exception description The type of the generic parameter '{0}' could not be inferred. - The type of the generic parameter '{0}' could not be inferred. + 无法推断泛型参数“{0}”的类型。 The generic test method '{0}' doesn't have arguments, so the generic parameter cannot be inferred. - The generic test method '{0}' doesn't have arguments, so the generic parameter cannot be inferred. + 泛型测试方法“{0}”没有参数,因此无法推断泛型参数。 Found two conflicting types for generic parameter '{0}'. The conflicting types are '{1}' and '{2}'. - Found two conflicting types for generic parameter '{0}'. The conflicting types are '{1}' and '{2}'. + 发现泛型参数“{0}”有两种冲突类型。冲突类型为“{1}”和“{2}”。 Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. - Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. + 为“ClassCleanupLifecycle”指定的值“{0}”无效。支持的作用域为 {1}。 'ClassCleanupLifecycle' is a setting name that shouldn't be localized. Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. - Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. + 为“范围”指定的值“{0}”无效。受支持的范围为 {1}。 'Scope' is a setting name that shouldn't be localized. Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. - Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. + 为“辅助角色”指定的值“{0}”无效。该值应为非负整数。 `Workers` is a setting name that shouldn't be localized. Invalid settings '{0}'. Unexpected XmlAttribute: '{1}'. - Invalid settings '{0}'. Unexpected XmlAttribute: '{1}'. + 设置“{0}”无效。意外的 XmlAttribute:“{1}”。 @@ -261,7 +261,7 @@ but received {4} argument(s), with types '{5}'. Invalid settings '{0}'. Unexpected XmlElement: '{1}'. - Invalid settings '{0}'. Unexpected XmlElement: '{1}'. + 设置“{0}”无效。意外的 XmlElement:“{1}”。 @@ -271,12 +271,12 @@ but received {4} argument(s), with types '{5}'. Invalid value '{0}' for runsettings entry '{1}', setting will be ignored. - Invalid value '{0}' for runsettings entry '{1}', setting will be ignored. + runsettings 项 ‘{1}’ 的值 ‘{0}’ 无效,将忽略设置。 Warning : A testsettings file or a vsmdi file is not supported with the MSTest V2 Adapter. - Warning : A testsettings file or a vsmdi file is not supported with the MSTest V2 Adapter. + 警告: MSTest V2 适配器不支持 testsettings 文件或 vsmdi 文件。 @@ -291,67 +291,67 @@ but received {4} argument(s), with types '{5}'. An older version of MSTestV2 package is loaded in assembly, test discovery might fail to discover all data tests if they depend on `.runsettings` file. - An older version of MSTestV2 package is loaded in assembly, test discovery might fail to discover all data tests if they depend on `.runsettings` file. + 程序集中加载了 MSTestV2 包的较旧版本,如果测试发现依赖于“.runsettings”文件,则它们可能无法发现所有数据测试。 Runsettings entry '<ExecutionApartmentState>STA</ExecutionApartmentState>' is not supported on non-Windows OSes. - Runsettings entry '<ExecutionApartmentState>STA</ExecutionApartmentState>' is not supported on non-Windows OSes. + 非 Windows 操作系统不支持 Runsettings 条目 "<ExecutionApartmentState>STA</ExecutionApartmentState>"。 Running tests in any of the provided sources is not supported for the selected platform - Running tests in any of the provided sources is not supported for the selected platform + 选定的平台不支持在任何提供的源中运行测试 Failed to discover tests from assembly {0}. Reason:{1} - Failed to discover tests from assembly {0}. Reason:{1} + 未能发现程序集 {0} 中的测试。原因: {1} File does not exist: {0} - File does not exist: {0} + 文件不存在: {0} Test cleanup method '{0}.{1}' timed out after {2}ms - Test cleanup method '{0}.{1}' timed out after {2}ms + 测试清理方法“{0}.{1}”在 {2} ms 后超时 Test cleanup method '{0}.{1}' was canceled - Test cleanup method '{0}.{1}' was canceled + 已取消测试清理方法“{0}.{1}” TestContext cannot be Null. - TestContext cannot be Null. + TestContext 不能为 NULL。 TestContext Messages: - TestContext Messages: + TestContext 消息: Test initialize method '{0}.{1}' timed out after {2}ms - Test initialize method '{0}.{1}' timed out after {2}ms + 测试初始化方法“{0}.{1}”在 {2} ms 后超时 Test initialize method '{0}.{1}' was canceled - Test initialize method '{0}.{1}' was canceled + 已取消测试初始化方法“{0}.{1}” Test method {0} was not found. - Test method {0} was not found. + 未找到测试方法 {0}。 Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) - Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) + 已为 {0} 启用测试并行化(工作线程: {1},范围: {2}) `Workers` is a setting name that shouldn't be localized. 'Scope' is a setting name that shouldn't be localized. @@ -362,53 +362,53 @@ but received {4} argument(s), with types '{5}'. Unable to load types from the test source '{0}'. Some or all of the tests in this source may not be discovered. Error: {1} - Unable to load types from the test source '{0}'. Some or all of the tests in this source may not be discovered. -Error: {1} + 无法从测试源“{0}”加载类型。可能无法发现此源中的部分或所有测试。 +错误: {1} Assembly Cleanup method {0}.{1} failed. Error Message: {2}. StackTrace: {3} - Assembly Cleanup method {0}.{1} failed. Error Message: {2}. StackTrace: {3} + 程序集清理方法 {0}.{1} 失败。错误消息: {2}。StackTrace: {3} Assembly Initialization method {0}.{1} threw exception. {2}: {3}. Aborting test execution. - Assembly Initialization method {0}.{1} threw exception. {2}: {3}. Aborting test execution. + 程序集初始化方法 {0}.{1} 引发异常。{2}: {3}。正在中止测试的执行。 Class Cleanup method {0}.{1} failed. Error Message: {2}. Stack Trace: {3} - Class Cleanup method {0}.{1} failed. Error Message: {2}. Stack Trace: {3} + 类清理方法 {0}.{1} 失败。错误消息: {2}。堆栈跟踪: {3} Class Initialization method {0}.{1} threw exception. {2}: {3}. - Class Initialization method {0}.{1} threw exception. {2}: {3}. + 类初始化方法 {0}.{1} 引发异常。{2}: {3}。 Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. - Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + 方法 {0}。{1}的签名错误。该方法必须是静态的公共方法、不返回值并且不应采用任何参数。此外,如果在方法中使用同步等待,则返回类型必须为“Task”或“Value Task”。 Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should take a single parameter of type TestContext. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. - Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should take a single parameter of type TestContext. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + 方法 {0}。{1}的签名错误。该方法必须是静态的公共方法,不返回值,并且应采用一个 TestContext 类型的参数。此外,如果在方法中使用同步等待,则返回类型必须为“Task”或“Value Task”。 TestCleanup method {0}.{1} threw exception. {2}. - TestCleanup method {0}.{1} threw exception. {2}. + TestCleanup 方法 {0}.{1} 引发异常。{2}。 Error calling Test Cleanup method for test class {0}: {1} - Error calling Test Cleanup method for test class {0}: {1} + 为测试类 {0} 调用 Test Cleanup 方法时出错: {1} TestCleanup Stack Trace - TestCleanup Stack Trace + TestCleanup 堆栈跟踪 @@ -418,7 +418,7 @@ Error: {1} --- End of inner exception stack trace --- - --- End of inner exception stack trace --- + ---内部异常堆栈跟踪结束--- @@ -428,163 +428,163 @@ Error: {1} UTA031: class {0} does not have valid TestContext property. TestContext must be of type TestContext, must be non-static, and must be public. For example: public TestContext TestContext. - UTA031: class {0} does not have valid TestContext property. TestContext must be of type TestContext, must be non-static, and must be public. For example: public TestContext TestContext. + UTA031: 类 {0} 没有有效的 TestContext 属性。TestContext 必须是 TestContext 类型并且必须是非静态和公共的。例如: public TestContext TestContext。 UTA007: Method {1} defined in class {0} does not have correct signature. Test method marked with the [TestMethod] attribute must be non-static, public, return-type as void and should not take any parameter. Example: public void Test.Class1.Test(). Additionally, if you are using async-await in test method then return-type must be 'Task' or 'ValueTask'. Example: public async Task Test.Class1.Test2() - UTA007: Method {1} defined in class {0} does not have correct signature. Test method marked with the [TestMethod] attribute must be non-static, public, return-type as void and should not take any parameter. Example: public void Test.Class1.Test(). Additionally, if you are using async-await in test method then return-type must be 'Task' or 'ValueTask'. Example: public async Task Test.Class1.Test2() + UTA007: 在类 {0} 中定义的方法 {1} 没有正确的签名。用 [TestMethod] 特性标记的测试方法必须是返回类型为 void 的非静态的公共方法,并且不应采用任何参数。示例: public void Test.Class1.Test()。此外,如果在测试方法中使用同步等待,则返回类型必须为“Task”或“Value Task”。示例: public async Task Test.Class1.Test2() UTA054: {0}.{1} has invalid Timeout attribute. The timeout must be an integer value greater than 0. - UTA054: {0}.{1} has invalid Timeout attribute. The timeout must be an integer value greater than 0. + UTA054: {0}。{1} 的超时属性无效。“超时”必须是大于零的整数值。 UTA014: {0}: Cannot define more than one method with the AssemblyCleanup attribute inside an assembly. - UTA014: {0}: Cannot define more than one method with the AssemblyCleanup attribute inside an assembly. + UTA014: {0}: 在一个程序集内部,不能定义多个具有 AssemblyCleanup 特性的方法。 UTA013: {0}: Cannot define more than one method with the AssemblyInitialize attribute inside an assembly. - UTA013: {0}: Cannot define more than one method with the AssemblyInitialize attribute inside an assembly. + UTA013: {0}: 在一个程序集内部,不能定义多个具有 AssemblyInitialize 特性的方法。 UTA026: {0}: Cannot define more than one method with the ClassCleanup attribute inside a class. - UTA026: {0}: Cannot define more than one method with the ClassCleanup attribute inside a class. + UTA026: {0}: 在一个类内部,不能定义多个具有 ClassCleanup 特性的方法。 UTA025: {0}: Cannot define more than one method with the ClassInitialize attribute inside a class. - UTA025: {0}: Cannot define more than one method with the ClassInitialize attribute inside a class. + UTA025: {0}: 在一个类内部,不能定义多个具有 ClassInitialize 特性的方法。 UTA024: {0}: Cannot define more than one method with the TestCleanup attribute. - UTA024: {0}: Cannot define more than one method with the TestCleanup attribute. + UTA024: {0}: 不能定义多个具有 TestCleanup 特性的方法。 UTA018: {0}: Cannot define more than one method with the TestInitialize attribute. - UTA018: {0}: Cannot define more than one method with the TestInitialize attribute. + UTA018: {0}: 不能定义多个具有 TestInitialize 特性的方法。 UTA001: TestClass attribute defined on non-public class {0} - UTA001: TestClass attribute defined on non-public class {0} + UTA001: 在非公共类 {0} 上定义的 TestClass 特性 UTA023: {0}: Cannot define predefined property {2} on method {1}. - UTA023: {0}: Cannot define predefined property {2} on method {1}. + UTA023: {0}: 不能在方法 {1} 上定义预定义属性 {2}。 TestClass attribute defined on generic non-abstract class {0} - TestClass attribute defined on generic non-abstract class {0} + 在泛型非抽象类 {0} 上定义的 TestClass 特性 UTA021: {0}: Null or empty custom property defined on method {1}. The custom property must have a valid name. - UTA021: {0}: Null or empty custom property defined on method {1}. The custom property must have a valid name. + UTA021: {0}: 对方法 {1} 定义了为 NULL 或为空的自定义属性。自定义属性必须具有有效名称。 An unhandled exception was thrown by the 'Execute' method. Please report this error to the author of the attribute '{0}'. {1} - An unhandled exception was thrown by the 'Execute' method. Please report this error to the author of the attribute '{0}'. + “Execute”方法引发了未经处理的异常。请将此错误报告给属性“{0}”的作者。 {1} The ExpectedException attribute defined on test method {0}.{1} threw an exception during construction. {2} - The ExpectedException attribute defined on test method {0}.{1} threw an exception during construction. + 测试方法 {0}.{1} 上定义的 ExpectedException 属性在构造过程中引发了一个异常。 {2} Failed to obtain the exception thrown by test method {0}.{1}. - Failed to obtain the exception thrown by test method {0}.{1}. + 未能获取测试方法 {0}.{1} 引发的异常。 Initialization method {0}.{1} threw exception. {2}. - Initialization method {0}.{1} threw exception. {2}. + 初始化方法 {0}.{1} 引发异常。{2}。 Unable to create instance of class {0}. Error: {1}. - Unable to create instance of class {0}. Error: {1}. + 无法创建类 {0} 的实例。错误: {1}。 Method {0}.{1} does not exist. - Method {0}.{1} does not exist. + 方法 {0}.{1} 不存在。 The test method '{0}.{1}' has multiple attributes derived from '{2}' defined on it. Only one such attribute is allowed. - The test method '{0}.{1}' has multiple attributes derived from '{2}' defined on it. Only one such attribute is allowed. + 测试方法“{0}.{1}”具有多个在其上定义的“{2}”的派生属性。仅允许一个此类属性。 Error in executing test. No result returned by extension. If using extension of TestMethodAttribute then please contact vendor. - Error in executing test. No result returned by extension. If using extension of TestMethodAttribute then please contact vendor. + 执行测试时出错。扩展未返回任何结果。如果使用的是扩展 TestMethodAttribute ,请与供应商联系。 Cannot find a valid constructor for test class '{0}'. Valid constructors are 'public' and either parameterless or with one parameter of type 'TestContext'. - Cannot find a valid constructor for test class '{0}'. Valid constructors are 'public' and either parameterless or with one parameter of type 'TestContext'. + 找不到测试类“{0}”的有效构造函数。有效的构造函数为 “public”,但该构造函数无参数或具有一个类型为 “TestContext” 的参数。 Unable to find property {0}.TestContext. Error:{1}. - Unable to find property {0}.TestContext. Error:{1}. + 无法找到属性 {0}.TestContext。错误: {1}。 Unable to set TestContext property for the class {0}. Error: {1}. - Unable to set TestContext property for the class {0}. Error: {1}. + 无法设置类 {0} 的 TestContext 属性。错误: {1}。 The {0}.TestContext has incorrect type. - The {0}.TestContext has incorrect type. + {0}.TestContext 的类型不正确。 Method {0}.{1} has wrong signature. The method must be non-static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. - Method {0}.{1} has wrong signature. The method must be non-static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + 方法 {0}。{1}的签名错误。该方法必须是非静态的公共方法、不返回值并且不应采用任何参数。此外,如果在方法中使用同步等待,则返回类型必须为“Task”或“Value Task”。 Test method {0}.{1} threw exception: {2} - Test method {0}.{1} threw exception: + 测试方法 {0}.{1} 引发了异常: {2} Unable to get type {0}. Error: {1}. - Unable to get type {0}. Error: {1}. + 无法获取类型 {0}。错误: {1}。 The called code threw an exception that was caught, but the exception value was null - The called code threw an exception that was caught, but the exception value was null + 调用的代码引发了捕获的异常,但异常值为 null {0} For UWP projects, if you are using UI objects in test consider using [UITestMethod] attribute instead of [TestMethod] to execute test in UI thread. - {0} For UWP projects, if you are using UI objects in test consider using [UITestMethod] attribute instead of [TestMethod] to execute test in UI thread. + {0} 对于 UWP 项目,如果在测试中使用 UI 对象,请考虑使用 [UITestMethod] 属性代替 [TestMethod] 属性在 UI 线程中执行测试。 (Failed to get the message for an exception of type {0} due to an exception.) - (Failed to get the message for an exception of type {0} due to an exception.) + (因异常而未能获取类型为 {0} 的异常的消息。) diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.zh-Hant.xlf b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.zh-Hant.xlf index 2ff7a526fb..b28b47d3dd 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.zh-Hant.xlf +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.zh-Hant.xlf @@ -4,52 +4,52 @@ Assembly cleanup method '{0}.{1}' timed out after {2}ms - Assembly cleanup method '{0}.{1}' timed out after {2}ms + 組件清理方法 '{0}.{1}' 在 {2} 毫秒後已逾時 Assembly cleanup method '{0}.{1}' was canceled - Assembly cleanup method '{0}.{1}' was canceled + 已取消組件清理方法 '{0}.{1}' Assembly initialize method '{0}.{1}' timed out after {2}ms - Assembly initialize method '{0}.{1}' timed out after {2}ms + 組件初始化方法 '{0}.{1}' 在 {2} 毫秒後已逾時 Assembly initialize method '{0}.{1}' was canceled - Assembly initialize method '{0}.{1}' was canceled + 已取消組件初始化方法 '{0}.{1}' MSTestAdapterV2 - MSTestAdapterV2 + MSTestAdapterV2 Exception occurred while enumerating IDataSource attribute on "{0}.{1}": {2} - Exception occurred while enumerating IDataSource attribute on "{0}.{1}": {2} + 列舉「{0}.{1}」上的 IDataSource 屬性時發生例外狀況: {2} {0}: TypeName with namespace, {1}: Method name, {2}: Exception details Exception occurred while expanding IDataSource rows from attribute on "{0}.{1}": {2} - Exception occurred while expanding IDataSource rows from attribute on "{0}.{1}": {2} + 從「{0}.{1}」上的屬性展開 IDataSource 資料列時發生例外狀況: {2} {0}: TypeName with namespace, {1}: Method name, {2}: CannotExpandIDataSourceAttribute_DuplicateDisplayName or CannotExpandIDataSourceAttribute_CannotSerialize Data on index {0} for "{1}" cannot be serialized. All data provided through "IDataSource" should be serializable. If you need to test non-serializable data sources, please make sure you add "TestDataSourceDiscovery" attribute on your test assembly and set the discovery option to "DuringExecution". - Data on index {0} for "{1}" cannot be serialized. All data provided through "IDataSource" should be serializable. If you need to test non-serializable data sources, please make sure you add "TestDataSourceDiscovery" attribute on your test assembly and set the discovery option to "DuringExecution". + 無法序列化「{1}"」索引 {0} 上的資料。透過「IDataSource」提供的所有資料應可序列化。如果您需要測試不可序列化的資料來源,請務必在測試元件上新增「TestDataSourceDiscovery」屬性,並將探索選項設定為「DuringExecution」。 {0}: Zero based index if an element inside of an array, {1}: Test name Display name "{2}" on indexes {0} and {1} are duplicate. Display names should be unique. - Display name "{2}" on indexes {0} and {1} are duplicate. Display names should be unique. + 索引 {0} 和 {1} 上的顯示名稱「{2}」重複。顯示名稱必須是唯一的。 {0}, {1}: Zero based index if an element inside of an array {2}: Test display name. @@ -69,27 +69,27 @@ but received {4} argument(s), with types '{5}'. Cannot run test method '{0}.{1}': Method has parameters, but does not define any test source. Use '[DataRow]', '[DynamicData]', or a custom 'ITestDataSource' data source to provide test data. - Cannot run test method '{0}.{1}': Method has parameters, but does not define any test source. Use '[DataRow]', '[DynamicData]', or a custom 'ITestDataSource' data source to provide test data. + 無法執行測試方法 '{0}.{1}': 方法具有參數,但未定義任何測試來源。使用 '[DataRow]'、'[DynamicData]' 或自訂 'ITestDataSource' 資料來源來提供測試資料。 Class cleanup method '{0}.{1}' timed out after {2}ms - Class cleanup method '{0}.{1}' timed out after {2}ms + 類別清理方法 '{0}.{1}' 在 {2} 毫秒後已逾時 Class cleanup method '{0}.{1}' was canceled - Class cleanup method '{0}.{1}' was canceled + 已取消類別清理方法 '{0}.{1}' Class initialize method '{0}.{1}' timed out after {2}ms - Class initialize method '{0}.{1}' timed out after {2}ms + 類別初始化方法 '{0}.{1}' 在 {2} 毫秒後已逾時 Class initialize method '{0}.{1}' was canceled - Class initialize method '{0}.{1}' was canceled + 已取消類別初始化方法 '{0}.{1}' @@ -99,17 +99,17 @@ but received {4} argument(s), with types '{5}'. MSTestAdapter failed to discover tests in class '{0}' of assembly '{1}' because {2}. - MSTestAdapter failed to discover tests in class '{0}' of assembly '{1}' because {2}. + MSTestAdapter 無法在組件 '{1}' 的類別 '{0}' 中探索測試,因為 {2}。 {0} (Data Row {1}) - {0} (Data Row {1}) + {0} (資料列 {1}) Debug Trace: - Debug Trace: + 偵錯追蹤: @@ -179,28 +179,28 @@ but received {4} argument(s), with types '{5}'. [MSTest][Discovery][{0}] {1} - [MSTest][Discovery][{0}] {1} + [MSTest][Discovery][{0}] {1} Both '.runsettings' and '.testconfig.json' files have been detected. Please select only one of these test configuration files. - Both '.runsettings' and '.testconfig.json' files have been detected. Please select only one of these test configuration files. + 偵測到 '.runsettings' 和 '.testconfig.json' 檔案。請只選取其中一個測試設定檔。 {0}: {1} - {0}: {1} + {0}: {1} "{0}": (Failed to get exception description due to an exception of type "{1}". - "{0}": (Failed to get exception description due to an exception of type "{1}". + 「{0}」: (因為類型「{1}」的例外狀況而無法取得例外狀況描述。 {0}: Type of the original exception that we're trying to get the description of. {1}: Thrown exception Exceptions thrown: - Exceptions thrown: + 擲回的例外狀況數: This is usually precedes by TestAssembly_AssemblyDiscoveryFailure message, and preceded by list of exceptions thrown in a test discovery session. @@ -215,7 +215,7 @@ but received {4} argument(s), with types '{5}'. Getting custom attributes for type {0} threw exception (will ignore and use the reflection way): {1} - Getting custom attributes for type {0} threw exception (will ignore and use the reflection way): {1} + 取得類型 {0} 擲回例外狀況的自訂屬性 (將會略過並使用反映方式): {1} {0}: Attribute full type name. {1}: Exception description @@ -236,22 +236,22 @@ but received {4} argument(s), with types '{5}'. Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. - Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. + 為 'ClassCleanupLifecycle' 指定的值 '{0}' 無效。支援的範圍為 {1}。 'ClassCleanupLifecycle' is a setting name that shouldn't be localized. Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. - Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. + 為 'Scope' 指定的值 '{0}' 無效。支援的範圍為 {1}。 'Scope' is a setting name that shouldn't be localized. Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. - Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. + 為 'Workers' 的值 '{0}' 無效。值應為非負整數。 `Workers` is a setting name that shouldn't be localized. Invalid settings '{0}'. Unexpected XmlAttribute: '{1}'. - Invalid settings '{0}'. Unexpected XmlAttribute: '{1}'. + 設定 '{0}' 無效。未預期的 XmlAttribute: '{1}'。 @@ -261,7 +261,7 @@ but received {4} argument(s), with types '{5}'. Invalid settings '{0}'. Unexpected XmlElement: '{1}'. - Invalid settings '{0}'. Unexpected XmlElement: '{1}'. + 設定 '{0}' 無效。未預期的 XmlElement: '{1}'。 @@ -271,12 +271,12 @@ but received {4} argument(s), with types '{5}'. Invalid value '{0}' for runsettings entry '{1}', setting will be ignored. - Invalid value '{0}' for runsettings entry '{1}', setting will be ignored. + runsettings 項目 '{1}' 的值 '{0}' 無效,將忽略設定。 Warning : A testsettings file or a vsmdi file is not supported with the MSTest V2 Adapter. - Warning : A testsettings file or a vsmdi file is not supported with the MSTest V2 Adapter. + 警告: MSTest V2 配接器不支援 testsettings 檔案 vsmdi 檔案。 @@ -291,67 +291,67 @@ but received {4} argument(s), with types '{5}'. An older version of MSTestV2 package is loaded in assembly, test discovery might fail to discover all data tests if they depend on `.runsettings` file. - An older version of MSTestV2 package is loaded in assembly, test discovery might fail to discover all data tests if they depend on `.runsettings` file. + 元件中已載入舊版的 MSTestV2 套件,如果測試探索相依於 '.runsettings' 檔案,則測試探索可能無法探索所有資料測試。 Runsettings entry '<ExecutionApartmentState>STA</ExecutionApartmentState>' is not supported on non-Windows OSes. - Runsettings entry '<ExecutionApartmentState>STA</ExecutionApartmentState>' is not supported on non-Windows OSes. + 非 Windows OS 不支援 Runsettings 項目 '<ExecutionApartmentState>STA</ExecutionApartmentState>'。 Running tests in any of the provided sources is not supported for the selected platform - Running tests in any of the provided sources is not supported for the selected platform + 所選取的平台不支援在任何提供的來源中執行測試 Failed to discover tests from assembly {0}. Reason:{1} - Failed to discover tests from assembly {0}. Reason:{1} + 無法從組件 {0} 中探索測試。原因:{1} File does not exist: {0} - File does not exist: {0} + 檔案不存在: {0} Test cleanup method '{0}.{1}' timed out after {2}ms - Test cleanup method '{0}.{1}' timed out after {2}ms + 測試清理方法 '{0}.{1}' 在 {2} 毫秒後已逾時 Test cleanup method '{0}.{1}' was canceled - Test cleanup method '{0}.{1}' was canceled + 已取消測試清理方法 '{0}.{1}' TestContext cannot be Null. - TestContext cannot be Null. + TestContext 不可為 Null。 TestContext Messages: - TestContext Messages: + TestContext 訊息: Test initialize method '{0}.{1}' timed out after {2}ms - Test initialize method '{0}.{1}' timed out after {2}ms + 測試初始化方法 '{0}.{1}' 在 {2} 毫秒後已逾時 Test initialize method '{0}.{1}' was canceled - Test initialize method '{0}.{1}' was canceled + 已取消測試初始化方法 '{0}.{1}' Test method {0} was not found. - Test method {0} was not found. + 找不到測試方法 {0}。 Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) - Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) + 已為 {0} 啟用平行測試 (背景工作角色: {1},範圍: {2}) `Workers` is a setting name that shouldn't be localized. 'Scope' is a setting name that shouldn't be localized. @@ -362,53 +362,53 @@ but received {4} argument(s), with types '{5}'. Unable to load types from the test source '{0}'. Some or all of the tests in this source may not be discovered. Error: {1} - Unable to load types from the test source '{0}'. Some or all of the tests in this source may not be discovered. -Error: {1} + 無法從測試來源 '{0}' 載入類型。有可能無法探索此來源中的部分或所有測試。 +錯誤: {1} Assembly Cleanup method {0}.{1} failed. Error Message: {2}. StackTrace: {3} - Assembly Cleanup method {0}.{1} failed. Error Message: {2}. StackTrace: {3} + 組件清除方法 {0}.{1} 失敗。錯誤訊息: {2}。堆疊追蹤: {3} Assembly Initialization method {0}.{1} threw exception. {2}: {3}. Aborting test execution. - Assembly Initialization method {0}.{1} threw exception. {2}: {3}. Aborting test execution. + 組件初始設定方法 {0}.{1} 擲回例外狀況。{2}: {3}。正在中止測試執行。 Class Cleanup method {0}.{1} failed. Error Message: {2}. Stack Trace: {3} - Class Cleanup method {0}.{1} failed. Error Message: {2}. Stack Trace: {3} + 類別清除方法 {0}.{1} 失敗。錯誤訊息: {2}。堆疊追蹤: {3} Class Initialization method {0}.{1} threw exception. {2}: {3}. - Class Initialization method {0}.{1} threw exception. {2}: {3}. + 類別初始設定方法 {0}.{1} 擲回例外狀況。{2}: {3}。 Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. - Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + 方法 {0}.{1} 有錯誤的簽章。方法必須為靜態、公用、不傳回值,並且不應該接受任何參數。此外,如果您在方法中使用 async-await,則傳回類型必須是 'Task' 或 'ValueTask'。 Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should take a single parameter of type TestContext. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. - Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should take a single parameter of type TestContext. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + 方法 {0}.{1} 有錯誤的簽章。方法必須為靜態、公用、不傳回值,並且應接受類型為 TestContext 的單一參數。此外,如果您在方法中使用 async-await,則傳回類型必須是 'Task' 或 'ValueTask'。 TestCleanup method {0}.{1} threw exception. {2}. - TestCleanup method {0}.{1} threw exception. {2}. + TestCleanup 方法 {0}.{1} 擲回例外狀況。{2}。 Error calling Test Cleanup method for test class {0}: {1} - Error calling Test Cleanup method for test class {0}: {1} + 呼叫測試類別 {0} 的測試清除方法時發生錯誤: {1} TestCleanup Stack Trace - TestCleanup Stack Trace + TestCleanup 堆疊追蹤 @@ -418,7 +418,7 @@ Error: {1} --- End of inner exception stack trace --- - --- End of inner exception stack trace --- + --- 已到達內部例外狀況堆疊追蹤的結尾 --- @@ -428,67 +428,67 @@ Error: {1} UTA031: class {0} does not have valid TestContext property. TestContext must be of type TestContext, must be non-static, and must be public. For example: public TestContext TestContext. - UTA031: class {0} does not have valid TestContext property. TestContext must be of type TestContext, must be non-static, and must be public. For example: public TestContext TestContext. + UTA031: 類別 {0}不具備有效的 TestContext 屬性。TestContext 必須是 TestContext 類型、必須是非靜態的,而且必須是公用的。例如: public TestContext TestContext。 UTA007: Method {1} defined in class {0} does not have correct signature. Test method marked with the [TestMethod] attribute must be non-static, public, return-type as void and should not take any parameter. Example: public void Test.Class1.Test(). Additionally, if you are using async-await in test method then return-type must be 'Task' or 'ValueTask'. Example: public async Task Test.Class1.Test2() - UTA007: Method {1} defined in class {0} does not have correct signature. Test method marked with the [TestMethod] attribute must be non-static, public, return-type as void and should not take any parameter. Example: public void Test.Class1.Test(). Additionally, if you are using async-await in test method then return-type must be 'Task' or 'ValueTask'. Example: public async Task Test.Class1.Test2() + UTA007: 類別 {0} 中定義的方法 {1} 沒有正確的簽章。標記 [TestMethod] 屬性的測試方法必須為非靜態、公用、傳回類型為 void,而且不應該接受任何參數。範例: public void Test.Class1.Test()。此外,如果您在測試方法中使用 async-await,則傳回類型必須是 'Task' 或 'ValueTask'。範例: public async Task Test.Class1.Test2() UTA054: {0}.{1} has invalid Timeout attribute. The timeout must be an integer value greater than 0. - UTA054: {0}.{1} has invalid Timeout attribute. The timeout must be an integer value greater than 0. + UTA054: {0}。{1} 中具有無效的 Timeout 屬性。逾時必須為大於 0 的整數值。 UTA014: {0}: Cannot define more than one method with the AssemblyCleanup attribute inside an assembly. - UTA014: {0}: Cannot define more than one method with the AssemblyCleanup attribute inside an assembly. + UTA014: {0}: 組件內不可定義一個以上具有 AssemblyCleanup 屬性的方法。 UTA013: {0}: Cannot define more than one method with the AssemblyInitialize attribute inside an assembly. - UTA013: {0}: Cannot define more than one method with the AssemblyInitialize attribute inside an assembly. + UTA013: {0}: 組件內不可定義一個以上具有 AssemblyInitialize 屬性的方法。 UTA026: {0}: Cannot define more than one method with the ClassCleanup attribute inside a class. - UTA026: {0}: Cannot define more than one method with the ClassCleanup attribute inside a class. + UTA026: {0}: 類別內不可定義一個以上具有 ClassCleanup 屬性的方法。 UTA025: {0}: Cannot define more than one method with the ClassInitialize attribute inside a class. - UTA025: {0}: Cannot define more than one method with the ClassInitialize attribute inside a class. + UTA025: {0}: 類別內不可定義一個以上具有 ClassInitialize 屬性的方法。 UTA024: {0}: Cannot define more than one method with the TestCleanup attribute. - UTA024: {0}: Cannot define more than one method with the TestCleanup attribute. + UTA024: {0}: 不可定義一個以上具有 TestCleanup 屬性的方法。 UTA018: {0}: Cannot define more than one method with the TestInitialize attribute. - UTA018: {0}: Cannot define more than one method with the TestInitialize attribute. + UTA018: {0}: 不可定義一個以上具有 TestInitialize 屬性的方法。 UTA001: TestClass attribute defined on non-public class {0} - UTA001: TestClass attribute defined on non-public class {0} + UTA001: 在非公用類別 {0} 上定義了 TestClass 屬性 UTA023: {0}: Cannot define predefined property {2} on method {1}. - UTA023: {0}: Cannot define predefined property {2} on method {1}. + UTA023: {0}: 不可在方法 {1} 上定義預先定義的屬性 {2}。 TestClass attribute defined on generic non-abstract class {0} - TestClass attribute defined on generic non-abstract class {0} + 在一般非抽象類別上定義的 TestClass 屬性 {0} UTA021: {0}: Null or empty custom property defined on method {1}. The custom property must have a valid name. - UTA021: {0}: Null or empty custom property defined on method {1}. The custom property must have a valid name. + UTA021: {0}: 在方法 {1} 上定義了 Null 或空白的自訂屬性。自訂屬性的名稱必須有效。 @@ -501,90 +501,90 @@ Error: {1} The ExpectedException attribute defined on test method {0}.{1} threw an exception during construction. {2} - The ExpectedException attribute defined on test method {0}.{1} threw an exception during construction. + 測試方法 {0} 上定義的 ExpectedException 屬性。{1} 在建構期間擲回例外狀況。 {2} Failed to obtain the exception thrown by test method {0}.{1}. - Failed to obtain the exception thrown by test method {0}.{1}. + 無法取得測試方法 {0}.{1} 所擲回的例外狀況。 Initialization method {0}.{1} threw exception. {2}. - Initialization method {0}.{1} threw exception. {2}. + 初始設定方法 {0}.{1} 擲回例外狀況。{2}。 Unable to create instance of class {0}. Error: {1}. - Unable to create instance of class {0}. Error: {1}. + 無法建立類別 {0} 的執行個體。錯誤: {1}。 Method {0}.{1} does not exist. - Method {0}.{1} does not exist. + 方法 {0}.{1} 不存在。 The test method '{0}.{1}' has multiple attributes derived from '{2}' defined on it. Only one such attribute is allowed. - The test method '{0}.{1}' has multiple attributes derived from '{2}' defined on it. Only one such attribute is allowed. + 測試方法 '{0}.{1}' 具有多個衍生自 '{2}' 的屬性根據其定義。只允許一個此類屬性。 Error in executing test. No result returned by extension. If using extension of TestMethodAttribute then please contact vendor. - Error in executing test. No result returned by extension. If using extension of TestMethodAttribute then please contact vendor. + 執行測試時發生錯誤。擴充功能未傳回任何結果。如果您使用 TestMethodAttribute 的擴充功能,請連絡廠商。 Cannot find a valid constructor for test class '{0}'. Valid constructors are 'public' and either parameterless or with one parameter of type 'TestContext'. - Cannot find a valid constructor for test class '{0}'. Valid constructors are 'public' and either parameterless or with one parameter of type 'TestContext'. + 找不到測試類別 '{0}' 的有效建構函式。有效的建構函式為 'public' 且無參數或具有一個類型為 'TestContext' 的參數。 Unable to find property {0}.TestContext. Error:{1}. - Unable to find property {0}.TestContext. Error:{1}. + 找不到屬性 {0}.TestContext。錯誤: {1}。 Unable to set TestContext property for the class {0}. Error: {1}. - Unable to set TestContext property for the class {0}. Error: {1}. + 無法設定類別 {0} 的 TestContext 屬性。錯誤: {1}。 The {0}.TestContext has incorrect type. - The {0}.TestContext has incorrect type. + {0}.TestContext 有不正確的類型。 Method {0}.{1} has wrong signature. The method must be non-static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. - Method {0}.{1} has wrong signature. The method must be non-static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + 方法 {0}.{1} 有錯誤的簽章。方法必須為非靜態、公用、不傳回值,並且不應該接受任何參數。此外,如果您在方法中使用 async-await,則傳回類型必須是 'Task' 或 'ValueTask'。 Test method {0}.{1} threw exception: {2} - Test method {0}.{1} threw exception: + 測試方法 {0}.{1} 擲回例外狀況: {2} Unable to get type {0}. Error: {1}. - Unable to get type {0}. Error: {1}. + 無法取得類型 {0}。錯誤: {1}。 The called code threw an exception that was caught, but the exception value was null - The called code threw an exception that was caught, but the exception value was null + 被呼叫的程式碼擲回攔截到的例外狀況,但例外狀況值為 Null {0} For UWP projects, if you are using UI objects in test consider using [UITestMethod] attribute instead of [TestMethod] to execute test in UI thread. - {0} For UWP projects, if you are using UI objects in test consider using [UITestMethod] attribute instead of [TestMethod] to execute test in UI thread. + {0} 針對 UWP 專案,如果您在測試中使用 UI 物件,請考慮使用 [UITestMethod] 屬性取代 [TestMethod] 在 UI 執行緒中執行測試。 (Failed to get the message for an exception of type {0} due to an exception.) - (Failed to get the message for an exception of type {0} due to an exception.) + (因為發生例外狀況,所以無法取得類型 {0} 之例外狀況的訊息。) diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.cs.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.cs.xlf index 72b8bcc71d..e71dab1dc7 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.cs.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.cs.xlf @@ -44,7 +44,7 @@ Replace 'DataTestMethod' with 'TestMethod' - Replace 'DataTestMethod' with 'TestMethod' + Nahradit DataTestMethod hodnotou TestMethod diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ja.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ja.xlf index 109e333ead..91e6949a47 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ja.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ja.xlf @@ -44,7 +44,7 @@ Replace 'DataTestMethod' with 'TestMethod' - Replace 'DataTestMethod' with 'TestMethod' + 'DataTestMethod' を 'TestMethod' に置き換えます diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pt-BR.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pt-BR.xlf index 196cffca2e..b3c8f200d0 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pt-BR.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pt-BR.xlf @@ -44,7 +44,7 @@ Replace 'DataTestMethod' with 'TestMethod' - Replace 'DataTestMethod' with 'TestMethod' + Substitua 'DataTestMethod' por 'TestMethod' diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hans.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hans.xlf index 43c037cd5f..631f4e6466 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hans.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hans.xlf @@ -44,7 +44,7 @@ Replace 'DataTestMethod' with 'TestMethod' - Replace 'DataTestMethod' with 'TestMethod' + 将 'DataTestMethod' 替换为 'TestMethod' diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf index ac7ad3490f..57644ebf1a 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf @@ -439,17 +439,17 @@ Typ deklarující tyto metody by měl také respektovat následující pravidla: 'DataTestMethodAttribute' is obsolete and provides no additional functionality over 'TestMethodAttribute'. Use 'TestMethodAttribute' for all test methods, including parameterized tests. - 'DataTestMethodAttribute' is obsolete and provides no additional functionality over 'TestMethodAttribute'. Use 'TestMethodAttribute' for all test methods, including parameterized tests. + Možnost DataTestMethodAttribute je zastaralá a neposkytuje žádné funkce navíc oproti možnosti TestMethodAttribute. Pro všechny testovací metody, včetně parametrizovaných testů, použijte možnost TestMethodAttribute. 'DataTestMethod' is obsolete. Use 'TestMethod' instead. - 'DataTestMethod' is obsolete. Use 'TestMethod' instead. + Možnost DataTestMethod je zastaralá. Místo ní použijte možnost TestMethod. Prefer 'TestMethod' over 'DataTestMethod' - Prefer 'TestMethod' over 'DataTestMethod' + Preferovat TestMethod před DataTestMethod diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf index 6272a68732..c44fcf1403 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf @@ -439,17 +439,17 @@ O tipo que declara esses métodos também deve respeitar as seguintes regras: 'DataTestMethodAttribute' is obsolete and provides no additional functionality over 'TestMethodAttribute'. Use 'TestMethodAttribute' for all test methods, including parameterized tests. - 'DataTestMethodAttribute' is obsolete and provides no additional functionality over 'TestMethodAttribute'. Use 'TestMethodAttribute' for all test methods, including parameterized tests. + 'DataTestMethodAttribute' está obsoleto e não oferece funcionalidade adicional em relação a 'TestMethodAttribute'. Use 'TestMethodAttribute' para todos os métodos de teste, inclusive testes parametrizados. 'DataTestMethod' is obsolete. Use 'TestMethod' instead. - 'DataTestMethod' is obsolete. Use 'TestMethod' instead. + 'DataTestMethod' está obsoleto. Use 'TestMethod' em vez disso. Prefer 'TestMethod' over 'DataTestMethod' - Prefer 'TestMethod' over 'DataTestMethod' + Prefira 'TestMethod' a 'DataTestMethod' diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf index a0354e5f93..eb83b2e5e6 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf @@ -445,17 +445,17 @@ The type declaring these methods should also respect the following rules: 'DataTestMethodAttribute' is obsolete and provides no additional functionality over 'TestMethodAttribute'. Use 'TestMethodAttribute' for all test methods, including parameterized tests. - 'DataTestMethodAttribute' is obsolete and provides no additional functionality over 'TestMethodAttribute'. Use 'TestMethodAttribute' for all test methods, including parameterized tests. + Атрибут "DataTestMethodAttribute" устарел и не предоставляет дополнительных функций по сравнению с "TestMethodAttribute". Используйте '"TestMethodAttribute" для всех методов тестирования, включая параметризованные тесты. 'DataTestMethod' is obsolete. Use 'TestMethod' instead. - 'DataTestMethod' is obsolete. Use 'TestMethod' instead. + "DataTestMethod" устарел. Используйте вместо него "TestMethod". Prefer 'TestMethod' over 'DataTestMethod' - Prefer 'TestMethod' over 'DataTestMethod' + Следует предпочитать метод "TestMethod" методу "DataTestMethod" diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf index 2be5ac4279..45efc76bf0 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf @@ -439,17 +439,17 @@ The type declaring these methods should also respect the following rules: 'DataTestMethodAttribute' is obsolete and provides no additional functionality over 'TestMethodAttribute'. Use 'TestMethodAttribute' for all test methods, including parameterized tests. - 'DataTestMethodAttribute' is obsolete and provides no additional functionality over 'TestMethodAttribute'. Use 'TestMethodAttribute' for all test methods, including parameterized tests. + 'DataTestMethodAttribute' 已过时,并且不再提供 'TestMethodAttribute' 之外的其他功能。对所有测试方法(包括参数化测试)使用 'TestMethodAttribute'。 'DataTestMethod' is obsolete. Use 'TestMethod' instead. - 'DataTestMethod' is obsolete. Use 'TestMethod' instead. + 'DataTestMethod' 已过时。请改用 'TestMethod'。 Prefer 'TestMethod' over 'DataTestMethod' - Prefer 'TestMethod' over 'DataTestMethod' + 首选 'TestMethod' 而不是 'DataTestMethod' From 918b8448850f1f4b1d58c39a9e721504942e10f1 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Fri, 13 Jun 2025 15:45:44 +0200 Subject: [PATCH 088/541] Update DataTestMethod analyzer severity to warning (don't add to release notes - patching feature in same release) (#5760) --- src/Analyzers/MSTest.Analyzers/AnalyzerReleases.Unshipped.md | 2 +- .../PreferTestMethodOverDataTestMethodAnalyzer.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Analyzers/MSTest.Analyzers/AnalyzerReleases.Unshipped.md b/src/Analyzers/MSTest.Analyzers/AnalyzerReleases.Unshipped.md index ab12abf384..079622cb08 100644 --- a/src/Analyzers/MSTest.Analyzers/AnalyzerReleases.Unshipped.md +++ b/src/Analyzers/MSTest.Analyzers/AnalyzerReleases.Unshipped.md @@ -5,4 +5,4 @@ Rule ID | Category | Severity | Notes --------|----------|----------|------- -MSTEST0044 | Design | Info | PreferTestMethodOverDataTestMethodAnalyzer, [Documentation](https://learn.microsoft.com/dotnet/core/testing/mstest-analyzers/mstest0044) +MSTEST0044 | Design | Warning | PreferTestMethodOverDataTestMethodAnalyzer, [Documentation](https://learn.microsoft.com/dotnet/core/testing/mstest-analyzers/mstest0044) diff --git a/src/Analyzers/MSTest.Analyzers/PreferTestMethodOverDataTestMethodAnalyzer.cs b/src/Analyzers/MSTest.Analyzers/PreferTestMethodOverDataTestMethodAnalyzer.cs index 22c9a51fee..faf8481797 100644 --- a/src/Analyzers/MSTest.Analyzers/PreferTestMethodOverDataTestMethodAnalyzer.cs +++ b/src/Analyzers/MSTest.Analyzers/PreferTestMethodOverDataTestMethodAnalyzer.cs @@ -24,7 +24,7 @@ public sealed class PreferTestMethodOverDataTestMethodAnalyzer : DiagnosticAnaly messageFormat: new LocalizableResourceString(nameof(Resources.PreferTestMethodOverDataTestMethodAnalyzerMessageFormat), Resources.ResourceManager, typeof(Resources)), description: new LocalizableResourceString(nameof(Resources.PreferTestMethodOverDataTestMethodAnalyzerDescription), Resources.ResourceManager, typeof(Resources)), Category.Design, - DiagnosticSeverity.Info, + DiagnosticSeverity.Warning, isEnabledByDefault: true); /// From 7096d508630a77bfd0d795ec10b2582c30f10c8f Mon Sep 17 00:00:00 2001 From: Copilot <198982749+Copilot@users.noreply.github.com> Date: Fri, 13 Jun 2025 17:32:23 +0200 Subject: [PATCH 089/541] Add predicate-based overloads for Assert.ContainsSingle API (#5767) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: Evangelink <11340282+Evangelink@users.noreply.github.com> Co-authored-by: Amaury Levé --- .../Assertions/Assert.Contains.cs | 47 ++++++ .../PublicAPI/PublicAPI.Unshipped.txt | 3 + .../Assertions/AssertTests.Contains.cs | 138 ++++++++++++++++++ .../Assertions/AssertTests.Items.cs | 44 ++++++ 4 files changed, 232 insertions(+) diff --git a/src/TestFramework/TestFramework/Assertions/Assert.Contains.cs b/src/TestFramework/TestFramework/Assertions/Assert.Contains.cs index 74abfeb3cd..d8f4b85747 100644 --- a/src/TestFramework/TestFramework/Assertions/Assert.Contains.cs +++ b/src/TestFramework/TestFramework/Assertions/Assert.Contains.cs @@ -144,6 +144,53 @@ public static T ContainsSingle(IEnumerable collection, [StringSyntax(Strin return default; } + /// + /// Tests whether the specified collection contains exactly one element that matches the given predicate. + /// + /// The type of the collection items. + /// A function to test each element for a condition. + /// The collection. + /// The item that matches the predicate. + public static T ContainsSingle(Func predicate, IEnumerable collection) + => ContainsSingle(predicate, collection, string.Empty, null); + + /// + /// Tests whether the specified collection contains exactly one element that matches the given predicate. + /// + /// The type of the collection items. + /// A function to test each element for a condition. + /// The collection. + /// The message to display when the assertion fails. + /// The item that matches the predicate. + public static T ContainsSingle(Func predicate, IEnumerable collection, string? message) + => ContainsSingle(predicate, collection, message, null); + + /// + /// Tests whether the specified collection contains exactly one element that matches the given predicate. + /// + /// The type of the collection items. + /// A function to test each element for a condition. + /// The collection. + /// The message format to display when the assertion fails. + /// The parameters to format the message. + /// The item that matches the predicate. + public static T ContainsSingle(Func predicate, IEnumerable collection, [StringSyntax(StringSyntaxAttribute.CompositeFormat)] string? message, params object?[]? parameters) + { + var matchingElements = collection.Where(predicate).ToList(); + int actualCount = matchingElements.Count; + + if (actualCount == 1) + { + return matchingElements[0]; + } + + string userMessage = BuildUserMessage(message, parameters); + ThrowAssertCountFailed("ContainsSingle", 1, actualCount, userMessage); + + // Unreachable code but compiler cannot work it out + return default; + } + #region Contains /// diff --git a/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Unshipped.txt b/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Unshipped.txt index 112144eb52..a9c1dc2d57 100644 --- a/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Unshipped.txt +++ b/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Unshipped.txt @@ -1,4 +1,7 @@ #nullable enable Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AssertNonStrictThrowsInterpolatedStringHandler.AssertNonStrictThrowsInterpolatedStringHandler(int literalLength, int formattedCount, System.Func! action, out bool shouldAppend) -> void Microsoft.VisualStudio.TestTools.UnitTesting.ConditionBaseAttribute.Mode.get -> Microsoft.VisualStudio.TestTools.UnitTesting.ConditionMode +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.ContainsSingle(System.Func! predicate, System.Collections.Generic.IEnumerable! collection) -> T +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.ContainsSingle(System.Func! predicate, System.Collections.Generic.IEnumerable! collection, string? message) -> T +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.ContainsSingle(System.Func! predicate, System.Collections.Generic.IEnumerable! collection, string? message, params object?[]? parameters) -> T static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.Throws(System.Func! action, ref Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AssertNonStrictThrowsInterpolatedStringHandler message) -> TException! diff --git a/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.Contains.cs b/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.Contains.cs index 10c11bb8b0..fd497214e4 100644 --- a/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.Contains.cs +++ b/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.Contains.cs @@ -595,4 +595,142 @@ public void DoesNotContain_StringVersion_SubstringPresent_ThrowsException() private static bool IsEven(int x) => x % 2 == 0; #endregion + + #region ContainsSingle with Predicate Tests + + /// + /// Tests the ContainsSingle method with predicate when exactly one element matches. + /// + public void ContainsSinglePredicate_NoMessage_OneItemMatches_ReturnsElement() + { + // Arrange + var collection = new List { 1, 2, 3, 4, 5 }; + + // Act + int result = Assert.ContainsSingle(x => x == 3, collection); + + // Assert + result.Should().Be(3); + } + + /// + /// Tests the ContainsSingle method with predicate and message when exactly one element matches. + /// + public void ContainsSinglePredicate_WithMessage_OneItemMatches_ReturnsElement() + { + // Arrange + var collection = new List { "apple", "banana", "cherry" }; + + // Act +#pragma warning disable CA1865 // Use char overload - not netfx + string result = Assert.ContainsSingle(x => x.StartsWith("b", StringComparison.Ordinal), collection, "Expected one item starting with 'b'"); +#pragma warning restore CA1865 // Use char overload + + // Assert + result.Should().Be("banana"); + } + + /// + /// Tests the ContainsSingle method with predicate when no elements match. + /// Expects an exception. + /// + public void ContainsSinglePredicate_NoItemMatches_ThrowsException() + { + // Arrange + var collection = new List { 1, 3, 5 }; + + // Act + Action action = () => Assert.ContainsSingle(x => x % 2 == 0, collection); + + // Assert + action.Should().Throw().WithMessage("*Expected collection of size 1. Actual: 0*"); + } + + /// + /// Tests the ContainsSingle method with predicate when multiple elements match. + /// Expects an exception. + /// + public void ContainsSinglePredicate_MultipleItemsMatch_ThrowsException() + { + // Arrange + var collection = new List { 2, 4, 6, 8 }; + + // Act + Action action = () => Assert.ContainsSingle(x => x % 2 == 0, collection); + + // Assert + action.Should().Throw().WithMessage("*Expected collection of size 1. Actual: 4*"); + } + + /// + /// Tests the ContainsSingle method with predicate and formatted message when no elements match. + /// Expects an exception with the custom message. + /// + public void ContainsSinglePredicate_WithMessageAndParams_NoItemMatches_ThrowsException() + { + // Arrange + var collection = new List { 1, 3, 5 }; + + // Act + Action action = () => Assert.ContainsSingle(x => x % 2 == 0, collection, "No even numbers found in collection with {0} items", collection.Count); + + // Assert + action.Should().Throw().WithMessage("*No even numbers found in collection with 3 items*"); + } + + /// + /// Tests the ContainsSingle method with predicate and formatted message when multiple elements match. + /// Expects an exception with the custom message. + /// + public void ContainsSinglePredicate_WithMessageAndParams_MultipleItemsMatch_ThrowsException() + { + // Arrange + var collection = new List { 2, 4, 6 }; + + // Act + Action action = () => Assert.ContainsSingle(x => x % 2 == 0, collection, "Too many even numbers found: {0}", collection.Count); + + // Assert + action.Should().Throw().WithMessage("*Too many even numbers found: 3*"); + } + + /// + /// Tests the ContainsSingle method with predicate using complex objects. + /// + public void ContainsSinglePredicate_ComplexObjects_OneItemMatches_ReturnsElement() + { + // Arrange + var items = new List + { + new("Alice", 25), + new("Bob", 30), + new("Charlie", 35), + }; + + // Act + Person result = Assert.ContainsSingle(p => p.Age == 30, items); + + // Assert + result.Name.Should().Be("Bob"); + result.Age.Should().Be(30); + } + + /// + /// Tests the ContainsSingle method with predicate using null values. + /// + public void ContainsSinglePredicate_WithNullValues_OneItemMatches_ReturnsElement() + { + // Arrange + var collection = new List { "apple", null, "banana" }; + + // Act + string? result = Assert.ContainsSingle(x => x == null, collection); + + // Assert + result.Should().BeNull(); + } + + private record Person(string Name, int Age); + + #endregion } diff --git a/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.Items.cs b/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.Items.cs index fb3ddb017f..0008ee22e5 100644 --- a/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.Items.cs +++ b/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.Items.cs @@ -131,6 +131,50 @@ public async Task Single_InterpolatedString_WhenMultipleItems_ShouldFail() Verify(o.WasToStringCalled); } + public void SinglePredicate_WhenOneItemMatches_ShouldPass() + { + var collection = new List { 1, 3, 5 }; + int result = Assert.ContainsSingle(x => x == 3, collection); + Verify(result == 3); + } + + public void SinglePredicate_WithMessage_WhenOneItemMatches_ShouldPass() + { + var collection = new List { "apple", "banana", "cherry" }; +#pragma warning disable CA1865 // Use char overload - not netfx + string result = Assert.ContainsSingle(x => x.StartsWith("b", StringComparison.Ordinal), collection, "Expected one item starting with 'b'"); +#pragma warning restore CA1865 + Verify(result == "banana"); + } + + public void SinglePredicate_WhenNoItemMatches_ShouldFail() + { + var collection = new List { 1, 3, 5 }; + Exception ex = VerifyThrows(() => Assert.ContainsSingle(x => x % 2 == 0, collection)); + Verify(ex.Message == "Assert.ContainsSingle failed. Expected collection of size 1. Actual: 0. "); + } + + public void SinglePredicate_WhenMultipleItemsMatch_ShouldFail() + { + var collection = new List { 2, 4, 6 }; + Exception ex = VerifyThrows(() => Assert.ContainsSingle(x => x % 2 == 0, collection)); + Verify(ex.Message == "Assert.ContainsSingle failed. Expected collection of size 1. Actual: 3. "); + } + + public void SinglePredicate_MessageArgs_WhenNoItemMatches_ShouldFail() + { + var collection = new List { 1, 3, 5 }; + Exception ex = VerifyThrows(() => Assert.ContainsSingle(x => x % 2 == 0, collection, "No even numbers found: {0}", "test")); + Verify(ex.Message == "Assert.ContainsSingle failed. Expected collection of size 1. Actual: 0. No even numbers found: test"); + } + + public void SinglePredicate_MessageArgs_WhenMultipleItemsMatch_ShouldFail() + { + var collection = new List { 2, 4, 6 }; + Exception ex = VerifyThrows(() => Assert.ContainsSingle(x => x % 2 == 0, collection, "Too many even numbers: {0}", "test")); + Verify(ex.Message == "Assert.ContainsSingle failed. Expected collection of size 1. Actual: 3. Too many even numbers: test"); + } + public void Any_WhenOneItem_ShouldPass() { var collection = new List { 1 }; From d5ae7a766e1193525b1ab76cd1a743b7a8eabf46 Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Sat, 14 Jun 2025 03:50:00 +0000 Subject: [PATCH 090/541] [main] Update dependencies from devdiv/DevDiv/vs-code-coverage, dotnet/arcade (#5772) [main] Update dependencies from devdiv/DevDiv/vs-code-coverage, dotnet/arcade --- eng/Version.Details.xml | 16 ++++++++-------- eng/Versions.props | 4 ++-- global.json | 2 +- 3 files changed, 11 insertions(+), 11 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index e1d5e59fa5..e7458b37cc 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -1,21 +1,21 @@ - + https://github.com/dotnet/arcade - 186172916558a2e41c87c1ca4e02850e9bba5f53 + 7a09c1144283309440a7966c664199944198c920 - + https://github.com/dotnet/arcade - 186172916558a2e41c87c1ca4e02850e9bba5f53 + 7a09c1144283309440a7966c664199944198c920 - + https://github.com/dotnet/arcade - 186172916558a2e41c87c1ca4e02850e9bba5f53 + 7a09c1144283309440a7966c664199944198c920 - + https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage - 899af124a773e3eed658a50d5d2171a4213cb8f8 + d895947216a71972ae98f3e88bd8c6e113f04d7a diff --git a/eng/Versions.props b/eng/Versions.props index a333943c9c..3616c6739a 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -7,7 +7,7 @@ preview - 10.0.0-beta.25312.3 - 17.15.0-preview.25312.3 + 10.0.0-beta.25313.2 + 17.15.0-preview.25313.3 diff --git a/global.json b/global.json index da30ccee88..a7c826ecaf 100644 --- a/global.json +++ b/global.json @@ -33,7 +33,7 @@ "rollForward": "latestFeature" }, "msbuild-sdks": { - "Microsoft.DotNet.Arcade.Sdk": "10.0.0-beta.25312.3", + "Microsoft.DotNet.Arcade.Sdk": "10.0.0-beta.25313.2", "MSBuild.Sdk.Extras": "3.0.44" } } From 69373b9ff2765e1114baa9c042dc19fdb8ff4b75 Mon Sep 17 00:00:00 2001 From: dotnet bot Date: Fri, 13 Jun 2025 21:01:36 -0700 Subject: [PATCH 091/541] Localized file check-in by OneLocBuild Task: Build definition ID 1218: Build ID 2730055 --- .../Resources/xlf/Resource.de.xlf | 18 +++++++++--------- .../Resources/xlf/Resource.ja.xlf | 19 ++++++++++--------- .../Resources/xlf/Resource.ko.xlf | 18 +++++++++--------- .../Resources/xlf/Resource.tr.xlf | 18 +++++++++--------- .../Resources/xlf/Resource.zh-Hant.xlf | 18 +++++++++--------- .../xlf/CodeFixResources.de.xlf | 2 +- .../xlf/CodeFixResources.it.xlf | 2 +- .../xlf/CodeFixResources.ko.xlf | 2 +- .../xlf/CodeFixResources.pl.xlf | 2 +- .../xlf/CodeFixResources.ru.xlf | 2 +- .../xlf/CodeFixResources.tr.xlf | 2 +- .../xlf/CodeFixResources.zh-Hant.xlf | 2 +- .../MSTest.Analyzers/xlf/Resources.es.xlf | 6 +++--- .../MSTest.Analyzers/xlf/Resources.ja.xlf | 6 +++--- .../MSTest.Analyzers/xlf/Resources.ko.xlf | 6 +++--- .../MSTest.Analyzers/xlf/Resources.pl.xlf | 6 +++--- .../MSTest.Analyzers/xlf/Resources.tr.xlf | 6 +++--- .../xlf/Resources.zh-Hant.xlf | 6 +++--- 18 files changed, 71 insertions(+), 70 deletions(-) diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.de.xlf b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.de.xlf index 8890afe3e0..3259758c4b 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.de.xlf +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.de.xlf @@ -62,9 +62,9 @@ Cannot run test method '{0}.{1}': Test data doesn't match method parameters. Either the count or types are different. Test expected {2} parameter(s), with types '{3}', but received {4} argument(s), with types '{5}'. - Cannot run test method '{0}.{1}': Test data doesn't match method parameters. Either the count or types are different. -Test expected {2} parameter(s), with types '{3}', -but received {4} argument(s), with types '{5}'. + Die Testmethode „{0}.{1}“ kann nicht ausgeführt werden: Testdaten stimmen nicht mit Methodenparametern überein. Die Anzahl oder die Typen unterscheiden sich. +Test erwartete {2} Parameter mit den Typen „{3}“, +aber empfing {4} Argument(e) mit den Typen „{5}“. @@ -205,12 +205,12 @@ but received {4} argument(s), with types '{5}'. Test '{0}' was canceled - Test '{0}' was canceled + Test „{0}“ wurde abgebrochen Test '{0}' timed out after {1}ms - Test '{0}' timed out after {1}ms + Timeout bei Test „{0}“ nach {1} ms @@ -221,17 +221,17 @@ but received {4} argument(s), with types '{5}'. The type of the generic parameter '{0}' could not be inferred. - The type of the generic parameter '{0}' could not be inferred. + Der Typ des generischen Parameters „{0}“ konnte nicht abgeleitet werden. The generic test method '{0}' doesn't have arguments, so the generic parameter cannot be inferred. - The generic test method '{0}' doesn't have arguments, so the generic parameter cannot be inferred. + Die generische Testmethode „{0}“ hat keine Argumente, daher kann der generische Parameter nicht abgeleitet werden. Found two conflicting types for generic parameter '{0}'. The conflicting types are '{1}' and '{2}'. - Found two conflicting types for generic parameter '{0}'. The conflicting types are '{1}' and '{2}'. + Es wurden zwei in Konflikt stehende Typen für den generischen Parameter „{0}“ gefunden. Die in Konflikt stehenden Typen sind „{1}“ und „{2}“. @@ -494,7 +494,7 @@ Fehler: {1} An unhandled exception was thrown by the 'Execute' method. Please report this error to the author of the attribute '{0}'. {1} - An unhandled exception was thrown by the 'Execute' method. Please report this error to the author of the attribute '{0}'. + Von der„Execute“-Methode wurde ein Ausnahmefehler ausgelöst. Melden Sie diesen Fehler dem Autor des Attributs „{0}“. {1} diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.ja.xlf b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.ja.xlf index c1cf893a9f..df3c8c3eb3 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.ja.xlf +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.ja.xlf @@ -62,9 +62,10 @@ Cannot run test method '{0}.{1}': Test data doesn't match method parameters. Either the count or types are different. Test expected {2} parameter(s), with types '{3}', but received {4} argument(s), with types '{5}'. - Cannot run test method '{0}.{1}': Test data doesn't match method parameters. Either the count or types are different. -Test expected {2} parameter(s), with types '{3}', -but received {4} argument(s), with types '{5}'. + テスト メソッド '{0}.{1}' を実行できません: テスト データがメソッド パラメーターと一致しません。カウントまたは型が異なります。 +型 '{3}'、 + を持つ、予期された {2} パラメーターをテストします +ただし、型 '{5}' の引数 {4} を受け取りました。 @@ -205,12 +206,12 @@ but received {4} argument(s), with types '{5}'. Test '{0}' was canceled - Test '{0}' was canceled + テスト '{0}' が取り消されました Test '{0}' timed out after {1}ms - Test '{0}' timed out after {1}ms + テスト '{0}' が {1} ミリ秒後にタイムアウトしました @@ -221,17 +222,17 @@ but received {4} argument(s), with types '{5}'. The type of the generic parameter '{0}' could not be inferred. - The type of the generic parameter '{0}' could not be inferred. + ジェネリック パラメーター '{0}' の型を推論できませんでした。 The generic test method '{0}' doesn't have arguments, so the generic parameter cannot be inferred. - The generic test method '{0}' doesn't have arguments, so the generic parameter cannot be inferred. + ジェネリック テスト メソッド '{0}' に引数がないため、ジェネリック パラメーターを推論できません。 Found two conflicting types for generic parameter '{0}'. The conflicting types are '{1}' and '{2}'. - Found two conflicting types for generic parameter '{0}'. The conflicting types are '{1}' and '{2}'. + ジェネリック パラメーター '{0}' に 2 つの競合する型が見つかりました。競合する型は '{1}' および '{2}' です。 @@ -494,7 +495,7 @@ Error: {1} An unhandled exception was thrown by the 'Execute' method. Please report this error to the author of the attribute '{0}'. {1} - An unhandled exception was thrown by the 'Execute' method. Please report this error to the author of the attribute '{0}'. + 'Execute' メソッドによってハンドルされない例外がスローされました。属性 '{0}' の作成者にこのエラーを報告してください。 {1} diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.ko.xlf b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.ko.xlf index 8a68f5f803..3b20de7d5a 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.ko.xlf +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.ko.xlf @@ -62,9 +62,9 @@ Cannot run test method '{0}.{1}': Test data doesn't match method parameters. Either the count or types are different. Test expected {2} parameter(s), with types '{3}', but received {4} argument(s), with types '{5}'. - Cannot run test method '{0}.{1}': Test data doesn't match method parameters. Either the count or types are different. -Test expected {2} parameter(s), with types '{3}', -but received {4} argument(s), with types '{5}'. + 테스트 메서드 '{0}{1}'을(를) 실행할 수 없음: 테스트 데이터가 메서드 매개 변수와 일치하지 않습니다. 개수 또는 형식이 다릅니다. +테스트에 {2} 매개 변수로 ‘{3}’ 형식이 필요하지만, +{4} 인수의 ‘{5}’ 형식을 받았습니다. @@ -205,12 +205,12 @@ but received {4} argument(s), with types '{5}'. Test '{0}' was canceled - Test '{0}' was canceled + 테스트 '{0}'이(가) 취소되었습니다. Test '{0}' timed out after {1}ms - Test '{0}' timed out after {1}ms + 테스트 '{0}'이(가) {1}밀리초 후에 시간 초과되었습니다. @@ -221,17 +221,17 @@ but received {4} argument(s), with types '{5}'. The type of the generic parameter '{0}' could not be inferred. - The type of the generic parameter '{0}' could not be inferred. + 제네릭 매개 변수 '{0}'의 형식을 유추할 수 없습니다. The generic test method '{0}' doesn't have arguments, so the generic parameter cannot be inferred. - The generic test method '{0}' doesn't have arguments, so the generic parameter cannot be inferred. + 제네릭 테스트 메서드 '{0}'에 인수가 없으므로 제네릭 매개 변수를 유추할 수 없습니다. Found two conflicting types for generic parameter '{0}'. The conflicting types are '{1}' and '{2}'. - Found two conflicting types for generic parameter '{0}'. The conflicting types are '{1}' and '{2}'. + 제네릭 매개 변수 '{0}'에 대해 충돌하는 두 가지 형식을 찾았습니다. 충돌하는 형식은 '{1}' 및 ''{2}입니다. @@ -494,7 +494,7 @@ Error: {1} An unhandled exception was thrown by the 'Execute' method. Please report this error to the author of the attribute '{0}'. {1} - An unhandled exception was thrown by the 'Execute' method. Please report this error to the author of the attribute '{0}'. + 'Execute' 메서드에서 처리되지 않은 예외가 발생했습니다. '{0}' 특성의 작성자에게 이 오류를 보고하세요. {1} diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.tr.xlf b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.tr.xlf index c09bd8d4e0..f13e545d33 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.tr.xlf +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.tr.xlf @@ -62,9 +62,9 @@ Cannot run test method '{0}.{1}': Test data doesn't match method parameters. Either the count or types are different. Test expected {2} parameter(s), with types '{3}', but received {4} argument(s), with types '{5}'. - Cannot run test method '{0}.{1}': Test data doesn't match method parameters. Either the count or types are different. -Test expected {2} parameter(s), with types '{3}', -but received {4} argument(s), with types '{5}'. + '{0}.{1}' test yöntemi çalıştırılamıyor: Test verileri yöntem parametreleriyle eşleşmiyor. Ya sayıları ya da türleri birbirinden farklı. +Test '{3}' türünde {2} parametre bekledi, +ancak, '{5}' türünde {4} bağımsız değişken aldı. @@ -205,12 +205,12 @@ but received {4} argument(s), with types '{5}'. Test '{0}' was canceled - Test '{0}' was canceled + '{0}' testi iptal edildi Test '{0}' timed out after {1}ms - Test '{0}' timed out after {1}ms + '{0}' testi {1} ms sonra zaman aşımına uğradı @@ -221,17 +221,17 @@ but received {4} argument(s), with types '{5}'. The type of the generic parameter '{0}' could not be inferred. - The type of the generic parameter '{0}' could not be inferred. + '{0}' genel parametre türü çıkarsanamadı. The generic test method '{0}' doesn't have arguments, so the generic parameter cannot be inferred. - The generic test method '{0}' doesn't have arguments, so the generic parameter cannot be inferred. + '{0}' genel test metodu bağımsız değişkenlere sahip olmadığından, genel parametre çıkarsanamıyor. Found two conflicting types for generic parameter '{0}'. The conflicting types are '{1}' and '{2}'. - Found two conflicting types for generic parameter '{0}'. The conflicting types are '{1}' and '{2}'. + '{0}' genel parametresi için iki çakışan tür bulundu. Çakışan türler '{1}' ile '{2}'. @@ -494,7 +494,7 @@ Hata: {1} An unhandled exception was thrown by the 'Execute' method. Please report this error to the author of the attribute '{0}'. {1} - An unhandled exception was thrown by the 'Execute' method. Please report this error to the author of the attribute '{0}'. + 'Execute' yöntemi tarafından işlenmeyen bir özel durum oluştu. Lütfen bu hatayı '{0}' özniteliğinin yazarına bildirin. {1} diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.zh-Hant.xlf b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.zh-Hant.xlf index b28b47d3dd..c9aef388e4 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.zh-Hant.xlf +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.zh-Hant.xlf @@ -62,9 +62,9 @@ Cannot run test method '{0}.{1}': Test data doesn't match method parameters. Either the count or types are different. Test expected {2} parameter(s), with types '{3}', but received {4} argument(s), with types '{5}'. - Cannot run test method '{0}.{1}': Test data doesn't match method parameters. Either the count or types are different. -Test expected {2} parameter(s), with types '{3}', -but received {4} argument(s), with types '{5}'. + 無法執行測試方法 '{0}.{1}': 測試資料不符合方法參數。計數或類型不同。 +測試預期的 {2} 參數,類型為 '{3}', +但收到 {4} 引數,類型為 '{5}'。 @@ -205,12 +205,12 @@ but received {4} argument(s), with types '{5}'. Test '{0}' was canceled - Test '{0}' was canceled + 測試 '{0}' 已取消 Test '{0}' timed out after {1}ms - Test '{0}' timed out after {1}ms + 測試 '{0}' 在 {1} 毫秒後逾時 @@ -221,17 +221,17 @@ but received {4} argument(s), with types '{5}'. The type of the generic parameter '{0}' could not be inferred. - The type of the generic parameter '{0}' could not be inferred. + 無法推斷泛型參數 '{0}' 的類型。 The generic test method '{0}' doesn't have arguments, so the generic parameter cannot be inferred. - The generic test method '{0}' doesn't have arguments, so the generic parameter cannot be inferred. + 泛型測試方法 '{0}' 沒有引數,因此無法推斷泛型參數。 Found two conflicting types for generic parameter '{0}'. The conflicting types are '{1}' and '{2}'. - Found two conflicting types for generic parameter '{0}'. The conflicting types are '{1}' and '{2}'. + 發現泛型參數 '{0}' 有兩個衝突類型。衝突類型為 '{1}' 和 '{2}'。 @@ -494,7 +494,7 @@ Error: {1} An unhandled exception was thrown by the 'Execute' method. Please report this error to the author of the attribute '{0}'. {1} - An unhandled exception was thrown by the 'Execute' method. Please report this error to the author of the attribute '{0}'. + 'Execute' 方法擲回未處理的例外狀況。請將此錯誤回報給屬性 '{0}' 的作者。 {1} diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.de.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.de.xlf index 52eae8f0fa..9003d1701b 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.de.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.de.xlf @@ -44,7 +44,7 @@ Replace 'DataTestMethod' with 'TestMethod' - Replace 'DataTestMethod' with 'TestMethod' + „DataTestMethod“ durch „TestMethod“ ersetzen diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.it.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.it.xlf index 383065c770..f7d47355f4 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.it.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.it.xlf @@ -44,7 +44,7 @@ Replace 'DataTestMethod' with 'TestMethod' - Replace 'DataTestMethod' with 'TestMethod' + Sostituisci 'DataTestMethod' con 'TestMethod' diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ko.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ko.xlf index 35865aa78b..48fafa86db 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ko.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ko.xlf @@ -44,7 +44,7 @@ Replace 'DataTestMethod' with 'TestMethod' - Replace 'DataTestMethod' with 'TestMethod' + 'DataTestMethod'를 'TestMethod'로 바꾸기 diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pl.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pl.xlf index 9bb87921b7..8e3ca7b353 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pl.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pl.xlf @@ -44,7 +44,7 @@ Replace 'DataTestMethod' with 'TestMethod' - Replace 'DataTestMethod' with 'TestMethod' + Zastąp element „DataTestMethod” elementem „TestMethod” diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ru.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ru.xlf index 127258218a..fa9d48d7c3 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ru.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ru.xlf @@ -44,7 +44,7 @@ Replace 'DataTestMethod' with 'TestMethod' - Replace 'DataTestMethod' with 'TestMethod' + Заменить "DataTestMethod" на "TestMethod" diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.tr.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.tr.xlf index 40263d1576..168ef7ca5f 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.tr.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.tr.xlf @@ -44,7 +44,7 @@ Replace 'DataTestMethod' with 'TestMethod' - Replace 'DataTestMethod' with 'TestMethod' + 'DataTestMethod' yöntemini 'TestMethod' ile değiştirin diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hant.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hant.xlf index 622334ef26..b3c5a1fe77 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hant.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hant.xlf @@ -44,7 +44,7 @@ Replace 'DataTestMethod' with 'TestMethod' - Replace 'DataTestMethod' with 'TestMethod' + 將 'DataTestMethod' 取代為 'TestMethod' diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf index 232854564f..6644a0ed64 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf @@ -439,17 +439,17 @@ El tipo que declara estos métodos también debe respetar las reglas siguientes: 'DataTestMethodAttribute' is obsolete and provides no additional functionality over 'TestMethodAttribute'. Use 'TestMethodAttribute' for all test methods, including parameterized tests. - 'DataTestMethodAttribute' is obsolete and provides no additional functionality over 'TestMethodAttribute'. Use 'TestMethodAttribute' for all test methods, including parameterized tests. + "DataTestMethodAttribute" está obsoleto y no proporciona ninguna funcionalidad adicional sobre "TestMethodAttribute". Use "TestMethodAttribute" para todos los métodos de prueba, incluidas las pruebas parametrizadas. 'DataTestMethod' is obsolete. Use 'TestMethod' instead. - 'DataTestMethod' is obsolete. Use 'TestMethod' instead. + "DataTestMethod" está obsoleto. Use "TestMethod" en su lugar. Prefer 'TestMethod' over 'DataTestMethod' - Prefer 'TestMethod' over 'DataTestMethod' + Preferir "TestMethod" a "DataTestMethod" diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf index 664263b7df..a962c4698e 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf @@ -439,17 +439,17 @@ The type declaring these methods should also respect the following rules: 'DataTestMethodAttribute' is obsolete and provides no additional functionality over 'TestMethodAttribute'. Use 'TestMethodAttribute' for all test methods, including parameterized tests. - 'DataTestMethodAttribute' is obsolete and provides no additional functionality over 'TestMethodAttribute'. Use 'TestMethodAttribute' for all test methods, including parameterized tests. + 'DataTestMethodAttribute' は廃止されており、'TestMethodAttribute' に対して追加の機能は提供しません。パラメーター化されたテストを含むすべてのテスト メソッドには、'TestMethodAttribute' を使用してください。 'DataTestMethod' is obsolete. Use 'TestMethod' instead. - 'DataTestMethod' is obsolete. Use 'TestMethod' instead. + 'DataTestMethod' は廃止されました。代わりに 'TestMethod' を使用してください。 Prefer 'TestMethod' over 'DataTestMethod' - Prefer 'TestMethod' over 'DataTestMethod' + 'DataTestMethod' よりも 'TestMethod' を優先する diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf index 8b7e9cc65d..97388ae0b0 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf @@ -439,17 +439,17 @@ The type declaring these methods should also respect the following rules: 'DataTestMethodAttribute' is obsolete and provides no additional functionality over 'TestMethodAttribute'. Use 'TestMethodAttribute' for all test methods, including parameterized tests. - 'DataTestMethodAttribute' is obsolete and provides no additional functionality over 'TestMethodAttribute'. Use 'TestMethodAttribute' for all test methods, including parameterized tests. + 'DataTestMethodAttribute'는 더 이상 사용되지 않으며 'TestMethodAttribute'에 대한 추가 기능을 제공하지 않습니다. 매개 변수가 있는 테스트를 포함하여 모든 테스트 메서드에 'TestMethodAttribute'를 사용하세요. 'DataTestMethod' is obsolete. Use 'TestMethod' instead. - 'DataTestMethod' is obsolete. Use 'TestMethod' instead. + 'DataTestMethod'는 사용되지 않습니다. 대신 'TestMethod'를 사용하세요. Prefer 'TestMethod' over 'DataTestMethod' - Prefer 'TestMethod' over 'DataTestMethod' + 'DataTestMethod'보다 'TestMethod' 선호 diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf index 8181c95c2a..f5b5b3f41c 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf @@ -439,17 +439,17 @@ Typ deklarujący te metody powinien również przestrzegać następujących regu 'DataTestMethodAttribute' is obsolete and provides no additional functionality over 'TestMethodAttribute'. Use 'TestMethodAttribute' for all test methods, including parameterized tests. - 'DataTestMethodAttribute' is obsolete and provides no additional functionality over 'TestMethodAttribute'. Use 'TestMethodAttribute' for all test methods, including parameterized tests. + Atrybut „DataTestMethodAttribute” jest przestarzały i nie zapewnia dodatkowych funkcji w stosunku do atrybutu „TestMethodAttribute”. Użyj atrybutu „TestMethodAttribute” dla wszystkich metod testowych, w tym testów sparametryzowanych. 'DataTestMethod' is obsolete. Use 'TestMethod' instead. - 'DataTestMethod' is obsolete. Use 'TestMethod' instead. + Element „DataTestMethod” jest przestarzały. Zamiast niego użyj elementu „TestMethod”. Prefer 'TestMethod' over 'DataTestMethod' - Prefer 'TestMethod' over 'DataTestMethod' + Wybieraj element „TestMethod”, anie „DataTestMethod” diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf index 8ab55f1ba0..53b646d41f 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf @@ -439,17 +439,17 @@ Bu yöntemleri bildiren tipin ayrıca aşağıdaki kurallara uyması gerekir: 'DataTestMethodAttribute' is obsolete and provides no additional functionality over 'TestMethodAttribute'. Use 'TestMethodAttribute' for all test methods, including parameterized tests. - 'DataTestMethodAttribute' is obsolete and provides no additional functionality over 'TestMethodAttribute'. Use 'TestMethodAttribute' for all test methods, including parameterized tests. + 'DataTestMethodAttribute' artık kullanılmıyor ve 'TestMethodAttribute' üzerinde ek bir işlevsellik sunmuyor. Parametreli testler de dahil, tüm test yöntemleri için 'TestMethodAttribute' kullanın. 'DataTestMethod' is obsolete. Use 'TestMethod' instead. - 'DataTestMethod' is obsolete. Use 'TestMethod' instead. + 'DataTestMethod' artık kullanılmıyor. Bunun yerine 'TestMethod' kullanın. Prefer 'TestMethod' over 'DataTestMethod' - Prefer 'TestMethod' over 'DataTestMethod' + 'DataTestMethod' yerine 'TestMethod' yöntemini tercih edin diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf index 5dbdf5721f..d56848dfe3 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf @@ -439,17 +439,17 @@ The type declaring these methods should also respect the following rules: 'DataTestMethodAttribute' is obsolete and provides no additional functionality over 'TestMethodAttribute'. Use 'TestMethodAttribute' for all test methods, including parameterized tests. - 'DataTestMethodAttribute' is obsolete and provides no additional functionality over 'TestMethodAttribute'. Use 'TestMethodAttribute' for all test methods, including parameterized tests. + 'DataTestMethodAttribute' 已過時,未提供比 'TestMethodAttribute' 更多的功能。針對所有測試方法使用 'TestMethodAttribute',包括參數化測試。 'DataTestMethod' is obsolete. Use 'TestMethod' instead. - 'DataTestMethod' is obsolete. Use 'TestMethod' instead. + 'DataTestMethod' 已過時。請改用 'TestMethod'。 Prefer 'TestMethod' over 'DataTestMethod' - Prefer 'TestMethod' over 'DataTestMethod' + 優先使用 'TestMethod' 而不是 'DataTestMethod' From 2706c464f42d0e940804aa8c01bbce3a4f835b58 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Mon, 16 Jun 2025 09:59:39 +0200 Subject: [PATCH 092/541] nit: Fix indentation in TrxDataConsumer (#5780) --- .../Microsoft.Testing.Extensions.TrxReport/TrxDataConsumer.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxDataConsumer.cs b/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxDataConsumer.cs index 5b146fe3c7..25a5313c63 100644 --- a/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxDataConsumer.cs +++ b/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxDataConsumer.cs @@ -227,8 +227,8 @@ public async Task OnTestSessionFinishingAsync(SessionUid sessionUid, Cancellatio int exitCode = _testApplicationProcessExitCode.GetProcessExitCode(); TrxReportEngine trxReportGeneratorEngine = new(_testApplicationModuleInfo, _environment, _commandLineOptionsService, _configuration, - _clock, [.. _tests], _failedTestsCount, _passedTestsCount, _notExecutedTestsCount, _timeoutTestsCount, _artifactsByExtension, - _adapterSupportTrxCapability, _testFramework, _testStartTime.Value, exitCode, cancellationToken); + _clock, [.. _tests], _failedTestsCount, _passedTestsCount, _notExecutedTestsCount, _timeoutTestsCount, _artifactsByExtension, + _adapterSupportTrxCapability, _testFramework, _testStartTime.Value, exitCode, cancellationToken); (string reportFileName, string? warning) = await trxReportGeneratorEngine.GenerateReportAsync().ConfigureAwait(false); if (warning is not null) { From 7a7110e79a3b16118f45347ba5b711707cd929b7 Mon Sep 17 00:00:00 2001 From: dotnet bot Date: Mon, 16 Jun 2025 01:11:27 -0700 Subject: [PATCH 093/541] Localized file check-in by OneLocBuild Task: Build definition ID 1218: Build ID 2731076 --- .../Resources/xlf/Resource.cs.xlf | 20 ++++++------- .../Resources/xlf/Resource.de.xlf | 2 +- .../Resources/xlf/Resource.es.xlf | 2 +- .../Resources/xlf/Resource.fr.xlf | 28 +++++++++---------- .../Resources/xlf/Resource.it.xlf | 20 ++++++------- .../Resources/xlf/Resource.ja.xlf | 2 +- .../Resources/xlf/Resource.ko.xlf | 2 +- .../Resources/xlf/Resource.pl.xlf | 22 +++++++-------- .../Resources/xlf/Resource.pt-BR.xlf | 22 +++++++-------- .../Resources/xlf/Resource.ru.xlf | 2 +- .../Resources/xlf/Resource.tr.xlf | 2 +- .../Resources/xlf/Resource.zh-Hans.xlf | 2 +- .../Resources/xlf/Resource.zh-Hant.xlf | 2 +- .../xlf/CodeFixResources.es.xlf | 2 +- .../xlf/CodeFixResources.fr.xlf | 2 +- .../MSTest.Analyzers/xlf/Resources.de.xlf | 6 ++-- .../MSTest.Analyzers/xlf/Resources.fr.xlf | 6 ++-- .../MSTest.Analyzers/xlf/Resources.it.xlf | 6 ++-- 18 files changed, 75 insertions(+), 75 deletions(-) diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.cs.xlf b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.cs.xlf index a68b985ad9..1efbb9e1cc 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.cs.xlf +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.cs.xlf @@ -62,9 +62,9 @@ Cannot run test method '{0}.{1}': Test data doesn't match method parameters. Either the count or types are different. Test expected {2} parameter(s), with types '{3}', but received {4} argument(s), with types '{5}'. - Cannot run test method '{0}.{1}': Test data doesn't match method parameters. Either the count or types are different. -Test expected {2} parameter(s), with types '{3}', -but received {4} argument(s), with types '{5}'. + Testovací metodu {0}.{1} nejde spustit: Testovací data neodpovídají parametrům metody. Liší se počet nebo typy. +Pro test se očekával tento počet parametrů: {2} s typy {3}, +byl však přijat tento počet argumentů: {4} s typy {5}. @@ -205,12 +205,12 @@ but received {4} argument(s), with types '{5}'. Test '{0}' was canceled - Test '{0}' was canceled + Test {0} byl zrušen. Test '{0}' timed out after {1}ms - Test '{0}' timed out after {1}ms + Časový limit testu {0} vypršel po {1} ms. @@ -221,17 +221,17 @@ but received {4} argument(s), with types '{5}'. The type of the generic parameter '{0}' could not be inferred. - The type of the generic parameter '{0}' could not be inferred. + Typ obecného parametru {0} nelze odvodit. The generic test method '{0}' doesn't have arguments, so the generic parameter cannot be inferred. - The generic test method '{0}' doesn't have arguments, so the generic parameter cannot be inferred. + Obecná testovací metoda {0}'nemá argumenty, takže nelze odvodit obecný parametr. Found two conflicting types for generic parameter '{0}'. The conflicting types are '{1}' and '{2}'. - Found two conflicting types for generic parameter '{0}'. The conflicting types are '{1}' and '{2}'. + Byly nalezeny dva konfliktní typy pro obecný parametr {0}. Konfliktní typy jsou {1} a {2}. @@ -494,7 +494,7 @@ Chyba: {1} An unhandled exception was thrown by the 'Execute' method. Please report this error to the author of the attribute '{0}'. {1} - An unhandled exception was thrown by the 'Execute' method. Please report this error to the author of the attribute '{0}'. + Metoda Execute vyvolala neošetřenou výjimku. Nahlaste prosím tuto chybu autorovi atributu {0}. {1} @@ -589,7 +589,7 @@ Chyba: {1} 'MSTest.TestAdapter' and 'MSTest.TestFramework' must have the same version. Found 'MSTest.TestAdapter' version '{0}' and 'MSTest.TestFramework' version '{1}'. Please make sure that the versions of 'MSTest.TestAdapter' and 'MSTest.TestFramework' NuGet packages have the same version. - 'MSTest.TestAdapter' and 'MSTest.TestFramework' must have the same version. Found 'MSTest.TestAdapter' version '{0}' and 'MSTest.TestFramework' version '{1}'. Please make sure that the versions of 'MSTest.TestAdapter' and 'MSTest.TestFramework' NuGet packages have the same version. + MSTest.TestAdapter a MSTest.TestFramework musí mít stejnou verzi. Byla nalezena verze MSTest.TestAdapter {0} a verze MSTest.TestFramework {1}. Ujistěte se prosím, že verze balíčků NuGet MSTest.TestAdapter a MSTest.TestFramework jsou shodné. diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.de.xlf b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.de.xlf index 3259758c4b..45fefe8360 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.de.xlf +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.de.xlf @@ -589,7 +589,7 @@ Fehler: {1} 'MSTest.TestAdapter' and 'MSTest.TestFramework' must have the same version. Found 'MSTest.TestAdapter' version '{0}' and 'MSTest.TestFramework' version '{1}'. Please make sure that the versions of 'MSTest.TestAdapter' and 'MSTest.TestFramework' NuGet packages have the same version. - 'MSTest.TestAdapter' and 'MSTest.TestFramework' must have the same version. Found 'MSTest.TestAdapter' version '{0}' and 'MSTest.TestFramework' version '{1}'. Please make sure that the versions of 'MSTest.TestAdapter' and 'MSTest.TestFramework' NuGet packages have the same version. + „MSTest.TestAdapter“ und „MSTest.TestFramework“ müssen dieselbe Version aufweisen. Gefunden wurde „MSTest.TestAdapter“ Version „{0}“ und „MSTest.TestFramework“ Version „{1}“. Stellen Sie sicher, dass die Versionen der NuGet-Pakete „MSTest.TestAdapter“ und „MSTest.TestFramework“ übereinstimmen. diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.es.xlf b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.es.xlf index 3d8036ba23..d2af8480fa 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.es.xlf +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.es.xlf @@ -589,7 +589,7 @@ Error: {1} 'MSTest.TestAdapter' and 'MSTest.TestFramework' must have the same version. Found 'MSTest.TestAdapter' version '{0}' and 'MSTest.TestFramework' version '{1}'. Please make sure that the versions of 'MSTest.TestAdapter' and 'MSTest.TestFramework' NuGet packages have the same version. - 'MSTest.TestAdapter' and 'MSTest.TestFramework' must have the same version. Found 'MSTest.TestAdapter' version '{0}' and 'MSTest.TestFramework' version '{1}'. Please make sure that the versions of 'MSTest.TestAdapter' and 'MSTest.TestFramework' NuGet packages have the same version. + "MSTest.TestAdapter" y "MSTest.TestFramework" deben tener la misma versión. Se encontró la versión "{0}" de "MSTest.TestAdapter" y la versión "{1}" de "MSTest.TestFramework". Asegúrese de que las versiones de los paquetes NuGet "MSTest.TestAdapter" y "MSTest.TestFramework" tienen la misma versión. diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.fr.xlf b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.fr.xlf index d31b404ee2..1929980124 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.fr.xlf +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.fr.xlf @@ -62,9 +62,9 @@ Cannot run test method '{0}.{1}': Test data doesn't match method parameters. Either the count or types are different. Test expected {2} parameter(s), with types '{3}', but received {4} argument(s), with types '{5}'. - Cannot run test method '{0}.{1}': Test data doesn't match method parameters. Either the count or types are different. -Test expected {2} parameter(s), with types '{3}', -but received {4} argument(s), with types '{5}'. + Impossible d’exécuter la méthode de test « {0}.{1} » : les données de test ne correspondent pas aux paramètres de la méthode. Le nombre ou les types sont différents. +Tester le ou les paramètres de {2} attendus, avec les types « {3} », +mais a reçu {4} argument(s), avec les types « {5} ». @@ -205,12 +205,12 @@ but received {4} argument(s), with types '{5}'. Test '{0}' was canceled - Test '{0}' was canceled + Le test {0} a été annulé Test '{0}' timed out after {1}ms - Test '{0}' timed out after {1}ms + Le test « {0} » a expiré après {1} ms @@ -221,17 +221,17 @@ but received {4} argument(s), with types '{5}'. The type of the generic parameter '{0}' could not be inferred. - The type of the generic parameter '{0}' could not be inferred. + Le type du paramètre générique « {0} » n'a pas pu être déduit. The generic test method '{0}' doesn't have arguments, so the generic parameter cannot be inferred. - The generic test method '{0}' doesn't have arguments, so the generic parameter cannot be inferred. + La méthode de test générique « {0} » n’a pas d’arguments, donc le paramètre générique ne peut pas être déduit. Found two conflicting types for generic parameter '{0}'. The conflicting types are '{1}' and '{2}'. - Found two conflicting types for generic parameter '{0}'. The conflicting types are '{1}' and '{2}'. + Deux types en conflit ont été trouvés pour le paramètre générique « {0} ». Les types en conflit sont « {1} » et « {2} ». @@ -388,12 +388,12 @@ Erreur : {1} Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. - Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + La méthode {0}.{1} présente une signature incorrecte. La méthode doit être statique, publique et ne doit retourner aucune valeur ni accepter aucun paramètre. En outre, si vous utilisez async-await dans la méthode, return-type doit être « Task » ou « ValueTask ». Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should take a single parameter of type TestContext. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. - Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should take a single parameter of type TestContext. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + La méthode {0}.{1} présente une signature incorrecte. La méthode doit être statique, publique et ne doit retourner aucune valeur et accepter un seul paramètre de type TestContext. En outre, si vous utilisez async-await dans la méthode, return-type doit être « Task » ou « ValueTask ». @@ -433,7 +433,7 @@ Erreur : {1} UTA007: Method {1} defined in class {0} does not have correct signature. Test method marked with the [TestMethod] attribute must be non-static, public, return-type as void and should not take any parameter. Example: public void Test.Class1.Test(). Additionally, if you are using async-await in test method then return-type must be 'Task' or 'ValueTask'. Example: public async Task Test.Class1.Test2() - UTA007: Method {1} defined in class {0} does not have correct signature. Test method marked with the [TestMethod] attribute must be non-static, public, return-type as void and should not take any parameter. Example: public void Test.Class1.Test(). Additionally, if you are using async-await in test method then return-type must be 'Task' or 'ValueTask'. Example: public async Task Test.Class1.Test2() + UTA007 : la méthode {1} définie dans la classe {0} ne dispose pas d'une signature correcte. Une méthode de test marquée avec l'attribut [TestMethod] doit être non statique, doit utiliser void pour return-type et ne doit accepter aucun paramètre. Exemple : public void Test.Class1.Test(). En outre, si vous utilisez async-await dans la méthode test, return-type doit être « Task » ou « ValueTask ». Exemple : public async Task Test.Class1.Test2() @@ -494,7 +494,7 @@ Erreur : {1} An unhandled exception was thrown by the 'Execute' method. Please report this error to the author of the attribute '{0}'. {1} - An unhandled exception was thrown by the 'Execute' method. Please report this error to the author of the attribute '{0}'. + Une exception non gérée a été levée par la méthode « Execute ». Veuillez signaler cette erreur à l’auteur de l’attribut « {0} ». {1} @@ -557,7 +557,7 @@ Erreur : {1} Method {0}.{1} has wrong signature. The method must be non-static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. - Method {0}.{1} has wrong signature. The method must be non-static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'. + La méthode {0}.{1} présente une signature incorrecte. La méthode doit être non statique, publique et ne doit retourner aucune valeur ni accepter aucun paramètre. En outre, si vous utilisez async-await dans la méthode, return-type doit être « Task » ou « ValueTask ». @@ -589,7 +589,7 @@ Erreur : {1} 'MSTest.TestAdapter' and 'MSTest.TestFramework' must have the same version. Found 'MSTest.TestAdapter' version '{0}' and 'MSTest.TestFramework' version '{1}'. Please make sure that the versions of 'MSTest.TestAdapter' and 'MSTest.TestFramework' NuGet packages have the same version. - 'MSTest.TestAdapter' and 'MSTest.TestFramework' must have the same version. Found 'MSTest.TestAdapter' version '{0}' and 'MSTest.TestFramework' version '{1}'. Please make sure that the versions of 'MSTest.TestAdapter' and 'MSTest.TestFramework' NuGet packages have the same version. + « MSTest.TestAdapter » et « MSTest.TestFramework » doivent avoir la même version. Version de « MSTest.TestAdapter » : « {0} » et version de « MSTest.TestFramework » : « {1} ». Veuillez vous assurer que les versions des packages NuGet « MSTest.TestAdapter » et « MSTest.TestFramework » sont identiques. diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.it.xlf b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.it.xlf index dbe79e38f9..237f15eff0 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.it.xlf +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.it.xlf @@ -62,9 +62,9 @@ Cannot run test method '{0}.{1}': Test data doesn't match method parameters. Either the count or types are different. Test expected {2} parameter(s), with types '{3}', but received {4} argument(s), with types '{5}'. - Cannot run test method '{0}.{1}': Test data doesn't match method parameters. Either the count or types are different. -Test expected {2} parameter(s), with types '{3}', -but received {4} argument(s), with types '{5}'. + Non è possibile eseguire il metodo di test '{0}.{1}': i dati del test non corrispondono ai parametri del metodo. Il numero o il tipo è diverso. +Il test prevedeva {2} parametri, con tipi '{3}', +ma ha ricevuto {4} argomenti, con tipi '{5}'. @@ -205,12 +205,12 @@ but received {4} argument(s), with types '{5}'. Test '{0}' was canceled - Test '{0}' was canceled + Il test '{0}' è stato annullato Test '{0}' timed out after {1}ms - Test '{0}' timed out after {1}ms + Timeout del test '{0}' dopo {1} ms @@ -221,17 +221,17 @@ but received {4} argument(s), with types '{5}'. The type of the generic parameter '{0}' could not be inferred. - The type of the generic parameter '{0}' could not be inferred. + Non è possibile dedurre il tipo del parametro generico '{0}'. The generic test method '{0}' doesn't have arguments, so the generic parameter cannot be inferred. - The generic test method '{0}' doesn't have arguments, so the generic parameter cannot be inferred. + Il metodo di test generico '{0}' non ha argomenti, quindi non è possibile dedurre il parametro generico. Found two conflicting types for generic parameter '{0}'. The conflicting types are '{1}' and '{2}'. - Found two conflicting types for generic parameter '{0}'. The conflicting types are '{1}' and '{2}'. + Sono stati trovati due tipi in conflitto per il parametro generico '{0}'. I tipi in conflitto sono '{1}' e '{2}'. @@ -494,7 +494,7 @@ Errore: {1} An unhandled exception was thrown by the 'Execute' method. Please report this error to the author of the attribute '{0}'. {1} - An unhandled exception was thrown by the 'Execute' method. Please report this error to the author of the attribute '{0}'. + Un'eccezione non gestita è stata generata dal metodo 'Execute'. Segnalare questo errore all'autore dell'attributo '{0}'. {1} @@ -589,7 +589,7 @@ Errore: {1} 'MSTest.TestAdapter' and 'MSTest.TestFramework' must have the same version. Found 'MSTest.TestAdapter' version '{0}' and 'MSTest.TestFramework' version '{1}'. Please make sure that the versions of 'MSTest.TestAdapter' and 'MSTest.TestFramework' NuGet packages have the same version. - 'MSTest.TestAdapter' and 'MSTest.TestFramework' must have the same version. Found 'MSTest.TestAdapter' version '{0}' and 'MSTest.TestFramework' version '{1}'. Please make sure that the versions of 'MSTest.TestAdapter' and 'MSTest.TestFramework' NuGet packages have the same version. + 'MSTest.TestAdapter' e 'MSTest.TestFramework' devono avere la stessa versione. Trovato 'MSTest.TestAdapter' versione '{0}' e 'MSTest.TestFramework' versione '{1}'. Assicurarsi che le versioni dei pacchetti NuGet 'MSTest.TestAdapter' e 'MSTest.TestFramework' siano identiche. diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.ja.xlf b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.ja.xlf index df3c8c3eb3..59cf4cb86e 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.ja.xlf +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.ja.xlf @@ -590,7 +590,7 @@ Error: {1} 'MSTest.TestAdapter' and 'MSTest.TestFramework' must have the same version. Found 'MSTest.TestAdapter' version '{0}' and 'MSTest.TestFramework' version '{1}'. Please make sure that the versions of 'MSTest.TestAdapter' and 'MSTest.TestFramework' NuGet packages have the same version. - 'MSTest.TestAdapter' and 'MSTest.TestFramework' must have the same version. Found 'MSTest.TestAdapter' version '{0}' and 'MSTest.TestFramework' version '{1}'. Please make sure that the versions of 'MSTest.TestAdapter' and 'MSTest.TestFramework' NuGet packages have the same version. + 'MSTest.TestAdapter' と 'MSTest.TestFramework' は同じバージョンである必要があります。'MSTest.TestAdapter' バージョン '{0}' と 'MSTest.TestFramework' バージョン '{1}' が見つかりました。'MSTest.TestAdapter' と 'MSTest.TestFramework' の NuGet パッケージのバージョンが同じであることを確認してください。 diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.ko.xlf b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.ko.xlf index 3b20de7d5a..56084fe47c 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.ko.xlf +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.ko.xlf @@ -589,7 +589,7 @@ Error: {1} 'MSTest.TestAdapter' and 'MSTest.TestFramework' must have the same version. Found 'MSTest.TestAdapter' version '{0}' and 'MSTest.TestFramework' version '{1}'. Please make sure that the versions of 'MSTest.TestAdapter' and 'MSTest.TestFramework' NuGet packages have the same version. - 'MSTest.TestAdapter' and 'MSTest.TestFramework' must have the same version. Found 'MSTest.TestAdapter' version '{0}' and 'MSTest.TestFramework' version '{1}'. Please make sure that the versions of 'MSTest.TestAdapter' and 'MSTest.TestFramework' NuGet packages have the same version. + 'MSTest.TestAdapter'와 'MSTest.TestFramework'의 버전이 같아야 합니다. 'MSTest.TestAdapter'의 버전은 '{0}'이고, 'MSTest.TestFramework'의 버전은 '{1}'입니다. 'MSTest.TestAdapter'와 'MSTest.TestFramework' NuGet 패키지의 버전이 동일한지 확인하세요. diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.pl.xlf b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.pl.xlf index de9cf91dd6..ab1778d736 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.pl.xlf +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.pl.xlf @@ -62,14 +62,14 @@ Cannot run test method '{0}.{1}': Test data doesn't match method parameters. Either the count or types are different. Test expected {2} parameter(s), with types '{3}', but received {4} argument(s), with types '{5}'. - Cannot run test method '{0}.{1}': Test data doesn't match method parameters. Either the count or types are different. -Test expected {2} parameter(s), with types '{3}', -but received {4} argument(s), with types '{5}'. + Nie można uruchomić metody testowej „{0}.{1}”: dane testowe nie są zgodne z parametrami metody. Liczba lub typy są różne. +Testowanie oczekiwał parametrów {2} z typami „{3}”, +ale odebrał argumenty {4} z typami „{5}”. Cannot run test method '{0}.{1}': Method has parameters, but does not define any test source. Use '[DataRow]', '[DynamicData]', or a custom 'ITestDataSource' data source to provide test data. - Cannot run test method '{0}.{1}': Method has parameters, but does not define any test source. Use '[DataRow]', '[DynamicData]', or a custom 'ITestDataSource' data source to provide test data. + Nie można uruchomić metody testowej „{0}.{1}”: metoda ma parametry, ale nie definiuje żadnego źródła testowego. Użyj źródła danych „[DataRow]”, „[DynamicData]” lub niestandardowego źródła danych „ITestDataSource”, aby dostarczyć dane testowe. @@ -205,12 +205,12 @@ but received {4} argument(s), with types '{5}'. Test '{0}' was canceled - Test '{0}' was canceled + Test „{0}” został anulowany Test '{0}' timed out after {1}ms - Test '{0}' timed out after {1}ms + Upłynął limit czasu testu „{0}” po {1}ms @@ -221,17 +221,17 @@ but received {4} argument(s), with types '{5}'. The type of the generic parameter '{0}' could not be inferred. - The type of the generic parameter '{0}' could not be inferred. + Nie można wywnioskować typu parametru ogólnego „{0}”. The generic test method '{0}' doesn't have arguments, so the generic parameter cannot be inferred. - The generic test method '{0}' doesn't have arguments, so the generic parameter cannot be inferred. + Ogólna metoda testowa „{0}” nie ma argumentów, więc nie można wywnioskować parametru ogólnego. Found two conflicting types for generic parameter '{0}'. The conflicting types are '{1}' and '{2}'. - Found two conflicting types for generic parameter '{0}'. The conflicting types are '{1}' and '{2}'. + Znaleziono dwa typy powodujące konflikt dla parametru ogólnego „{0}”. Typy powodujące konflikt to „{1}” i „{2}”. @@ -494,7 +494,7 @@ Błąd: {1} An unhandled exception was thrown by the 'Execute' method. Please report this error to the author of the attribute '{0}'. {1} - An unhandled exception was thrown by the 'Execute' method. Please report this error to the author of the attribute '{0}'. + Metoda „Execute” zgłosiła nieobsługiwany wyjątek. Zgłoś ten błąd autorowi atrybutu „{0}”. {1} @@ -589,7 +589,7 @@ Błąd: {1} 'MSTest.TestAdapter' and 'MSTest.TestFramework' must have the same version. Found 'MSTest.TestAdapter' version '{0}' and 'MSTest.TestFramework' version '{1}'. Please make sure that the versions of 'MSTest.TestAdapter' and 'MSTest.TestFramework' NuGet packages have the same version. - 'MSTest.TestAdapter' and 'MSTest.TestFramework' must have the same version. Found 'MSTest.TestAdapter' version '{0}' and 'MSTest.TestFramework' version '{1}'. Please make sure that the versions of 'MSTest.TestAdapter' and 'MSTest.TestFramework' NuGet packages have the same version. + Elementy „MSTest.TestAdapter” i „MSTest.TestFramework” muszą mieć tę samą wersję. Znaleziono element „MSTest.TestAdapter” w wersji „{0}” i element „MSTest.TestFramework” w wersji „{1}”. Upewnij się, że wersje pakietów NuGet „MSTest.TestAdapter” i „MSTest.TestFramework” mają tę samą wersję. diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.pt-BR.xlf b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.pt-BR.xlf index 48439b0656..352c0d1f34 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.pt-BR.xlf +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.pt-BR.xlf @@ -62,9 +62,9 @@ Cannot run test method '{0}.{1}': Test data doesn't match method parameters. Either the count or types are different. Test expected {2} parameter(s), with types '{3}', but received {4} argument(s), with types '{5}'. - Cannot run test method '{0}.{1}': Test data doesn't match method parameters. Either the count or types are different. -Test expected {2} parameter(s), with types '{3}', -but received {4} argument(s), with types '{5}'. + Não é possível executar o método de teste '{0}.{1}': Os dados de teste não correspondem aos parâmetros do método. A contagem ou os tipos são diferentes. +Testar {2} parâmetros esperados, com tipos '{3}', +mas {4} argumentos recebidos, com tipos '{5}'. @@ -205,12 +205,12 @@ but received {4} argument(s), with types '{5}'. Test '{0}' was canceled - Test '{0}' was canceled + O teste "{0}" foi cancelado Test '{0}' timed out after {1}ms - Test '{0}' timed out after {1}ms + O teste "{0}" atingiu o tempo limite após {1}ms @@ -221,17 +221,17 @@ but received {4} argument(s), with types '{5}'. The type of the generic parameter '{0}' could not be inferred. - The type of the generic parameter '{0}' could not be inferred. + O tipo do parâmetro genérico "{0}" não pôde ser inferido. The generic test method '{0}' doesn't have arguments, so the generic parameter cannot be inferred. - The generic test method '{0}' doesn't have arguments, so the generic parameter cannot be inferred. + O método de teste genérico "{0}" não tem argumentos; portanto, o parâmetro genérico não pode ser inferido. Found two conflicting types for generic parameter '{0}'. The conflicting types are '{1}' and '{2}'. - Found two conflicting types for generic parameter '{0}'. The conflicting types are '{1}' and '{2}'. + Foram encontrados dois tipos conflitantes para o parâmetro genérico "{0}". Os tipos conflitantes são "{1}" e "{2}". @@ -438,7 +438,7 @@ Erro: {1} UTA054: {0}.{1} has invalid Timeout attribute. The timeout must be an integer value greater than 0. - UTA054: {0}.{1} has invalid Timeout attribute. The timeout must be an integer value greater than 0. + UTA054: {0}.{1} tem atributo Timeout inválido. O tempo limite deve ser um valor inteiro maior que 0. @@ -494,7 +494,7 @@ Erro: {1} An unhandled exception was thrown by the 'Execute' method. Please report this error to the author of the attribute '{0}'. {1} - An unhandled exception was thrown by the 'Execute' method. Please report this error to the author of the attribute '{0}'. + Uma exceção sem tratamento foi lançada pelo método "Execute". Relate esse erro ao autor do atributo "{0}". {1} @@ -589,7 +589,7 @@ Erro: {1} 'MSTest.TestAdapter' and 'MSTest.TestFramework' must have the same version. Found 'MSTest.TestAdapter' version '{0}' and 'MSTest.TestFramework' version '{1}'. Please make sure that the versions of 'MSTest.TestAdapter' and 'MSTest.TestFramework' NuGet packages have the same version. - 'MSTest.TestAdapter' and 'MSTest.TestFramework' must have the same version. Found 'MSTest.TestAdapter' version '{0}' and 'MSTest.TestFramework' version '{1}'. Please make sure that the versions of 'MSTest.TestAdapter' and 'MSTest.TestFramework' NuGet packages have the same version. + 'MSTest.TestAdapter' e 'MSTest.TestFramework' devem ter a mesma versão. Encontrada a versão '{0}' do 'MSTest.TestAdapter' e a versão '{1}' do 'MSTest.TestFramework'. Por favor, verifique se as versões dos pacotes NuGet 'MSTest.TestAdapter' e 'MSTest.TestFramework' são iguais. diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.ru.xlf b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.ru.xlf index ed4a232e4c..6fd7005d92 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.ru.xlf +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.ru.xlf @@ -589,7 +589,7 @@ Error: {1} 'MSTest.TestAdapter' and 'MSTest.TestFramework' must have the same version. Found 'MSTest.TestAdapter' version '{0}' and 'MSTest.TestFramework' version '{1}'. Please make sure that the versions of 'MSTest.TestAdapter' and 'MSTest.TestFramework' NuGet packages have the same version. - 'MSTest.TestAdapter' and 'MSTest.TestFramework' must have the same version. Found 'MSTest.TestAdapter' version '{0}' and 'MSTest.TestFramework' version '{1}'. Please make sure that the versions of 'MSTest.TestAdapter' and 'MSTest.TestFramework' NuGet packages have the same version. + "MSTest.TestAdapter" и "MSTest.TestFramework" должны использовать одинаковую версию. Обнаружены "MSTest.TestAdapter" версии "{0}" и "MSTest.TestFramework" версии "{1}". Убедитесь, что версии пакетов NuGet "MSTest.TestAdapter" и "MSTest.TestFramework" совпадают. diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.tr.xlf b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.tr.xlf index f13e545d33..2c2dc60814 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.tr.xlf +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.tr.xlf @@ -589,7 +589,7 @@ Hata: {1} 'MSTest.TestAdapter' and 'MSTest.TestFramework' must have the same version. Found 'MSTest.TestAdapter' version '{0}' and 'MSTest.TestFramework' version '{1}'. Please make sure that the versions of 'MSTest.TestAdapter' and 'MSTest.TestFramework' NuGet packages have the same version. - 'MSTest.TestAdapter' and 'MSTest.TestFramework' must have the same version. Found 'MSTest.TestAdapter' version '{0}' and 'MSTest.TestFramework' version '{1}'. Please make sure that the versions of 'MSTest.TestAdapter' and 'MSTest.TestFramework' NuGet packages have the same version. + 'MSTest.TestAdapter' ve 'MSTest.TestFramework' aynı sürüme sahip olmalıdır. 'MSTest.TestAdapter' sürümü '{0}' ve 'MSTest.TestFramework' sürümü '{1}' bulundu. Lütfen 'MSTest.TestAdapter' ve 'MSTest.TestFramework' NuGet paketlerinin aynı sürüme sahip olduğundan emin olun. diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.zh-Hans.xlf b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.zh-Hans.xlf index 051d3f651a..4d80166a18 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.zh-Hans.xlf +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.zh-Hans.xlf @@ -589,7 +589,7 @@ Error: {1} 'MSTest.TestAdapter' and 'MSTest.TestFramework' must have the same version. Found 'MSTest.TestAdapter' version '{0}' and 'MSTest.TestFramework' version '{1}'. Please make sure that the versions of 'MSTest.TestAdapter' and 'MSTest.TestFramework' NuGet packages have the same version. - 'MSTest.TestAdapter' and 'MSTest.TestFramework' must have the same version. Found 'MSTest.TestAdapter' version '{0}' and 'MSTest.TestFramework' version '{1}'. Please make sure that the versions of 'MSTest.TestAdapter' and 'MSTest.TestFramework' NuGet packages have the same version. + 'MSTest.TestAdapter' 和 'MSTest.TestFramework' 必须具有相同的版本。找到 'MSTest.TestAdapter' 版本“{0}”和 'MSTest.TestFramework' 版本“{1}”。请确保 'MSTest.TestAdapter' 和 'MSTest.TestFramework' NuGet 包的版本具有相同的版本。 diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.zh-Hant.xlf b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.zh-Hant.xlf index c9aef388e4..b933d9305b 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.zh-Hant.xlf +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.zh-Hant.xlf @@ -589,7 +589,7 @@ Error: {1} 'MSTest.TestAdapter' and 'MSTest.TestFramework' must have the same version. Found 'MSTest.TestAdapter' version '{0}' and 'MSTest.TestFramework' version '{1}'. Please make sure that the versions of 'MSTest.TestAdapter' and 'MSTest.TestFramework' NuGet packages have the same version. - 'MSTest.TestAdapter' and 'MSTest.TestFramework' must have the same version. Found 'MSTest.TestAdapter' version '{0}' and 'MSTest.TestFramework' version '{1}'. Please make sure that the versions of 'MSTest.TestAdapter' and 'MSTest.TestFramework' NuGet packages have the same version. + 'MSTest.TestAdapter' 和 'MSTest.TestFramework' 必須使用相同的版本。發現 'MSTest.TestAdapter' 的版本為 '{0}',而 'MSTest.TestFramework' 的版本為 '{1}'。請確保 'MSTest.TestAdapter' 和 'MSTest.TestFramework' 的 NuGet 套件版本一致。 diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.es.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.es.xlf index d51a97e215..4e17f390b0 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.es.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.es.xlf @@ -44,7 +44,7 @@ Replace 'DataTestMethod' with 'TestMethod' - Replace 'DataTestMethod' with 'TestMethod' + Reemplazar "DataTestMethod" por "TestMethod" diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.fr.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.fr.xlf index 498cfe7ea8..d9200767e8 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.fr.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.fr.xlf @@ -44,7 +44,7 @@ Replace 'DataTestMethod' with 'TestMethod' - Replace 'DataTestMethod' with 'TestMethod' + Remplacer « DataTestMethod » par « TestMethod » diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf index dfc9df7f99..62e3354ba3 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf @@ -440,17 +440,17 @@ Der Typ, der diese Methoden deklariert, sollte auch die folgenden Regeln beachte 'DataTestMethodAttribute' is obsolete and provides no additional functionality over 'TestMethodAttribute'. Use 'TestMethodAttribute' for all test methods, including parameterized tests. - 'DataTestMethodAttribute' is obsolete and provides no additional functionality over 'TestMethodAttribute'. Use 'TestMethodAttribute' for all test methods, including parameterized tests. + „DataTestMethodAttribute“ ist veraltet und bietet keine zusätzliche Funktionalität im Vergleich zu „TestMethodAttribute“. Verwenden Sie „TestMethodAttribute“ für alle Testmethoden, einschließlich parametrisierter Tests. 'DataTestMethod' is obsolete. Use 'TestMethod' instead. - 'DataTestMethod' is obsolete. Use 'TestMethod' instead. + „DataTestMethod“ ist veraltet. Verwenden Sie stattdessen „TestMethod“. Prefer 'TestMethod' over 'DataTestMethod' - Prefer 'TestMethod' over 'DataTestMethod' + „TestMethod“ gegenüber „DataTestMethod“ bevorzugen diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf index 726fde02fc..6e2051e718 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf @@ -439,17 +439,17 @@ Le type doit être une classe 'DataTestMethodAttribute' is obsolete and provides no additional functionality over 'TestMethodAttribute'. Use 'TestMethodAttribute' for all test methods, including parameterized tests. - 'DataTestMethodAttribute' is obsolete and provides no additional functionality over 'TestMethodAttribute'. Use 'TestMethodAttribute' for all test methods, including parameterized tests. + « DataTestMethodAttribute » est obsolète et ne fournit aucune fonctionnalité supplémentaire par rapport à « TestMethodAttribute ». Utiliser « TestMethodAttribute » pour toutes les méthodes de test, y compris les tests paramétrés. 'DataTestMethod' is obsolete. Use 'TestMethod' instead. - 'DataTestMethod' is obsolete. Use 'TestMethod' instead. + « DataTestMethod » est obsolète. Utilisez « TestMethod » à la place. Prefer 'TestMethod' over 'DataTestMethod' - Prefer 'TestMethod' over 'DataTestMethod' + Préférer « TestMethod » à « DataTestMethod » diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf index 941bca4679..07b5748ae2 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf @@ -439,17 +439,17 @@ Anche il tipo che dichiara questi metodi deve rispettare le regole seguenti: 'DataTestMethodAttribute' is obsolete and provides no additional functionality over 'TestMethodAttribute'. Use 'TestMethodAttribute' for all test methods, including parameterized tests. - 'DataTestMethodAttribute' is obsolete and provides no additional functionality over 'TestMethodAttribute'. Use 'TestMethodAttribute' for all test methods, including parameterized tests. + 'DataTestMethodAttribute' è obsoleto e non offre funzionalità aggiuntive rispetto a 'TestMethodAttribute'. Utilizzare 'TestMethodAttribute' per tutti i metodi di test, inclusi i test con parametri. 'DataTestMethod' is obsolete. Use 'TestMethod' instead. - 'DataTestMethod' is obsolete. Use 'TestMethod' instead. + 'DataTestMethod' è obsoleto. Utilizzare 'TestMethod' invece. Prefer 'TestMethod' over 'DataTestMethod' - Prefer 'TestMethod' over 'DataTestMethod' + Preferisci 'TestMethod' a 'DataTestMethod' From ddc7aded8869b2492e05b901387a7128acae3b91 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Mon, 16 Jun 2025 10:51:36 +0200 Subject: [PATCH 094/541] Cleanup two equivalent properties in TestMethodInfo (#5776) --- .../Execution/TestMethodInfo.cs | 43 ++++++++----------- .../Execution/TestMethodRunner.cs | 2 +- .../Execution/TypeCache.cs | 12 +++--- .../Execution/UnitTestRunner.cs | 2 +- .../Execution/TypeCacheTests.cs | 12 +++--- 5 files changed, 33 insertions(+), 38 deletions(-) diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestMethodInfo.cs b/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestMethodInfo.cs index 9543fd4950..3214c13692 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestMethodInfo.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestMethodInfo.cs @@ -41,7 +41,7 @@ internal TestMethodInfo( DebugEx.Assert(testMethod != null, "TestMethod should not be null"); DebugEx.Assert(parent != null, "Parent should not be null"); - TestMethod = testMethod; + MethodInfo = testMethod; Parent = parent; TestContext = testContext; ExpectedException = ResolveExpectedException(); @@ -74,12 +74,12 @@ internal TestMethodInfo( /// /// Gets the parameter types of the test method. /// - public ParameterInfo[] ParameterTypes => TestMethod.GetParameters(); + public ParameterInfo[] ParameterTypes => MethodInfo.GetParameters(); /// /// Gets the return type of the test method. /// - public Type ReturnType => TestMethod.ReturnType; + public Type ReturnType => MethodInfo.ReturnType; /// /// Gets the name of the class declaring the test method. @@ -89,23 +89,18 @@ internal TestMethodInfo( /// /// Gets the name of the test method. /// - public string TestMethodName => TestMethod.Name; + public string TestMethodName => MethodInfo.Name; /// /// Gets the methodInfo for test method. /// - public MethodInfo MethodInfo => TestMethod; + public MethodInfo MethodInfo { get; } /// /// Gets the arguments with which test method is invoked. /// public object?[]? Arguments { get; private set; } - /// - /// Gets testMethod referred by this object. - /// - internal MethodInfo TestMethod { get; } - /// /// Gets the parent class Info object. /// @@ -121,7 +116,7 @@ internal TestMethodInfo( /// Whether or not getting the attributes that are inherited. /// An array of the attributes. public Attribute[]? GetAllAttributes(bool inherit) - => [.. ReflectHelper.Instance.GetAttributes(TestMethod, inherit)]; + => [.. ReflectHelper.Instance.GetAttributes(MethodInfo, inherit)]; /// /// Gets all attributes of the test method. @@ -131,7 +126,7 @@ internal TestMethodInfo( /// An array of the attributes. public TAttributeType[] GetAttributes(bool inherit) where TAttributeType : Attribute - => [.. ReflectHelper.Instance.GetAttributes(TestMethod, inherit)]; + => [.. ReflectHelper.Instance.GetAttributes(MethodInfo, inherit)]; /// public virtual TestResult Invoke(object?[]? arguments) @@ -191,7 +186,7 @@ public virtual async Task InvokeAsync(object?[]? arguments) internal object?[] ResolveArguments(object?[] arguments) { - ParameterInfo[] parametersInfo = TestMethod.GetParameters(); + ParameterInfo[] parametersInfo = MethodInfo.GetParameters(); int requiredParameterCount = 0; bool hasParamsValue = false; object? paramsValues = null; @@ -270,8 +265,8 @@ public virtual async Task InvokeAsync(object?[]? arguments) /// The timeout value if defined in milliseconds. 0 if not defined. private TimeoutInfo GetTestTimeout() { - DebugEx.Assert(TestMethod != null, "TestMethod should be non-null"); - TimeoutAttribute? timeoutAttribute = ReflectHelper.Instance.GetFirstAttributeOrDefault(TestMethod, inherit: false); + DebugEx.Assert(MethodInfo != null, "TestMethod should be non-null"); + TimeoutAttribute? timeoutAttribute = ReflectHelper.Instance.GetFirstAttributeOrDefault(MethodInfo, inherit: false); if (timeoutAttribute is null) { return TimeoutInfo.FromTestTimeoutSettings(); @@ -279,7 +274,7 @@ private TimeoutInfo GetTestTimeout() if (!timeoutAttribute.HasCorrectTimeout) { - string message = string.Format(CultureInfo.CurrentCulture, Resource.UTA_ErrorInvalidTimeout, TestMethod.DeclaringType!.FullName, TestMethod.Name); + string message = string.Format(CultureInfo.CurrentCulture, Resource.UTA_ErrorInvalidTimeout, MethodInfo.DeclaringType!.FullName, MethodInfo.Name); throw new TypeInspectionException(message); } @@ -294,7 +289,7 @@ private TestMethodAttribute GetTestMethodAttribute() { // Get the derived TestMethod attribute from reflection. // It should be non-null as it was already validated by IsValidTestMethod. - TestMethodAttribute testMethodAttribute = ReflectHelper.Instance.GetFirstAttributeOrDefault(TestMethod, inherit: false)!; + TestMethodAttribute testMethodAttribute = ReflectHelper.Instance.GetFirstAttributeOrDefault(MethodInfo, inherit: false)!; // Get the derived TestMethod attribute from Extended TestClass Attribute // If the extended TestClass Attribute doesn't have extended TestMethod attribute then base class returns back the original testMethod Attribute @@ -314,7 +309,7 @@ private TestMethodAttribute GetTestMethodAttribute() try { - expectedExceptions = ReflectHelper.Instance.GetAttributes(TestMethod, inherit: true); + expectedExceptions = ReflectHelper.Instance.GetAttributes(MethodInfo, inherit: true); } catch (Exception ex) { @@ -324,7 +319,7 @@ private TestMethodAttribute GetTestMethodAttribute() CultureInfo.CurrentCulture, Resource.UTA_ExpectedExceptionAttributeConstructionException, Parent.ClassType.FullName, - TestMethod.Name, + MethodInfo.Name, ex.GetFormattedExceptionMessage()); throw new TypeInspectionException(errorMessage); } @@ -350,7 +345,7 @@ private TestMethodAttribute GetTestMethodAttribute() /// private RetryBaseAttribute? GetRetryAttribute() { - IEnumerable attributes = ReflectHelper.Instance.GetAttributes(TestMethod, inherit: true); + IEnumerable attributes = ReflectHelper.Instance.GetAttributes(MethodInfo, inherit: true); using IEnumerator enumerator = attributes.GetEnumerator(); if (!enumerator.MoveNext()) { @@ -376,7 +371,7 @@ private void ThrowMultipleAttributesException(string attributeName) CultureInfo.CurrentCulture, Resource.UTA_MultipleAttributesOnTestMethod, Parent.ClassType.FullName, - TestMethod.Name, + MethodInfo.Name, attributeName); throw new TypeInspectionException(errorMessage); } @@ -390,7 +385,7 @@ private void ThrowMultipleAttributesException(string attributeName) [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Requirement is to handle all kinds of user exceptions and message appropriately.")] private async Task ExecuteInternalAsync(object?[]? arguments, CancellationTokenSource? timeoutTokenSource) { - DebugEx.Assert(TestMethod != null, "UnitTestExecuter.DefaultTestMethodInvoke: testMethod = null."); + DebugEx.Assert(MethodInfo != null, "UnitTestExecuter.DefaultTestMethodInvoke: testMethod = null."); var result = new TestResult(); @@ -417,7 +412,7 @@ private async Task ExecuteInternalAsync(object?[]? arguments, Cancel if (executionContext is null) { - Task? invokeResult = TestMethod.GetInvokeResultAsync(_classInstance, arguments); + Task? invokeResult = MethodInfo.GetInvokeResultAsync(_classInstance, arguments); if (invokeResult is not null) { await invokeResult.ConfigureAwait(false); @@ -432,7 +427,7 @@ private async Task ExecuteInternalAsync(object?[]? arguments, Cancel { try { - Task? invokeResult = TestMethod.GetInvokeResultAsync(_classInstance, arguments); + Task? invokeResult = MethodInfo.GetInvokeResultAsync(_classInstance, arguments); if (invokeResult is not null) { await invokeResult.ConfigureAwait(false); diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestMethodRunner.cs b/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestMethodRunner.cs index 3512e38437..e7dc802ac7 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestMethodRunner.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestMethodRunner.cs @@ -161,7 +161,7 @@ async Task SafeRunTestMethodAsync(string initializationLogs, strin internal async Task RunTestMethodAsync() { DebugEx.Assert(_test != null, "Test should not be null."); - DebugEx.Assert(_testMethodInfo.TestMethod != null, "Test method should not be null."); + DebugEx.Assert(_testMethodInfo.MethodInfo != null, "Test method should not be null."); List results = []; if (_testMethodInfo.Executor == null) diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Execution/TypeCache.cs b/src/Adapter/MSTestAdapter.PlatformServices/Execution/TypeCache.cs index f34f2d4016..7b9585b367 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Execution/TypeCache.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Execution/TypeCache.cs @@ -777,9 +777,9 @@ private MethodInfo GetMethodInfoForTestMethod(TestMethod testMethod, TestClassIn private void SetCustomProperties(TestMethodInfo testMethodInfo, ITestContext testContext) { DebugEx.Assert(testMethodInfo != null, "testMethodInfo is Null"); - DebugEx.Assert(testMethodInfo.TestMethod != null, "testMethodInfo.TestMethod is Null"); + DebugEx.Assert(testMethodInfo.MethodInfo != null, "testMethodInfo.TestMethod is Null"); - IEnumerable attributes = _reflectionHelper.GetAttributes(testMethodInfo.TestMethod, inherit: true); + IEnumerable attributes = _reflectionHelper.GetAttributes(testMethodInfo.MethodInfo, inherit: true); DebugEx.Assert(attributes != null, "attributes is null"); attributes = attributes.Concat(_reflectionHelper.GetAttributes(testMethodInfo.Parent.ClassType, inherit: true)); @@ -812,8 +812,8 @@ private static bool ValidateAndAssignTestProperty( testMethodInfo.NotRunnableReason = string.Format( CultureInfo.CurrentCulture, Resource.UTA_ErrorPredefinedTestProperty, - testMethodInfo.TestMethod.DeclaringType!.FullName, - testMethodInfo.TestMethod.Name, + testMethodInfo.MethodInfo.DeclaringType!.FullName, + testMethodInfo.MethodInfo.Name, propertyName); return false; @@ -824,8 +824,8 @@ private static bool ValidateAndAssignTestProperty( testMethodInfo.NotRunnableReason = string.Format( CultureInfo.CurrentCulture, Resource.UTA_ErrorTestPropertyNullOrEmpty, - testMethodInfo.TestMethod.DeclaringType!.FullName, - testMethodInfo.TestMethod.Name); + testMethodInfo.MethodInfo.DeclaringType!.FullName, + testMethodInfo.MethodInfo.Name); return false; } diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Execution/UnitTestRunner.cs b/src/Adapter/MSTestAdapter.PlatformServices/Execution/UnitTestRunner.cs index e0b25147eb..4634bf8c68 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Execution/UnitTestRunner.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Execution/UnitTestRunner.cs @@ -428,7 +428,7 @@ private static bool IsTestMethodRunnable( } bool shouldIgnoreClass = testMethodInfo.Parent.ClassType.IsIgnored(out string? ignoreMessageOnClass); - bool shouldIgnoreMethod = testMethodInfo.TestMethod.IsIgnored(out string? ignoreMessageOnMethod); + bool shouldIgnoreMethod = testMethodInfo.MethodInfo.IsIgnored(out string? ignoreMessageOnMethod); string? ignoreMessage = ignoreMessageOnClass; if (StringEx.IsNullOrEmpty(ignoreMessage) && shouldIgnoreMethod) diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TypeCacheTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TypeCacheTests.cs index 2136801507..ead4e93cd4 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TypeCacheTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TypeCacheTests.cs @@ -814,7 +814,7 @@ public void GetTestMethodInfoShouldReturnTestMethodInfo() testMethod, new TestContextImplementation(testMethod, new ThreadSafeStringWriter(null!, "test"), new Dictionary())); - Verify(methodInfo == testMethodInfo!.TestMethod); + Verify(methodInfo == testMethodInfo!.MethodInfo); Verify(testMethodInfo.TimeoutInfo.Timeout == 0); Verify(_typeCache.ClassInfoCache.First() == testMethodInfo.Parent); Verify(testMethodInfo.Executor is not null); @@ -834,7 +834,7 @@ public void GetTestMethodInfoShouldReturnTestMethodInfoWithTimeout() testMethod, new TestContextImplementation(testMethod, new ThreadSafeStringWriter(null!, "test"), new Dictionary())); - Verify(methodInfo == testMethodInfo!.TestMethod); + Verify(methodInfo == testMethodInfo!.MethodInfo); Verify(testMethodInfo.TimeoutInfo.Timeout == 10); Verify(_typeCache.ClassInfoCache.First() == testMethodInfo.Parent); Verify(testMethodInfo.Executor is not null); @@ -982,7 +982,7 @@ public void GetTestMethodInfoShouldReturnTestMethodInfoForMethodsAdornedWithADer testMethod, new TestContextImplementation(testMethod, new ThreadSafeStringWriter(null!, "test"), new Dictionary())); - Verify(methodInfo == testMethodInfo!.TestMethod); + Verify(methodInfo == testMethodInfo!.MethodInfo); Verify(testMethodInfo.TimeoutInfo.Timeout == 0); Verify(_typeCache.ClassInfoCache.First() == testMethodInfo.Parent); Verify(testMethodInfo.Executor is not null); @@ -1115,7 +1115,7 @@ public void GetTestMethodInfoShouldReturnTestMethodInfoForDerivedTestClasses() testMethod, new TestContextImplementation(testMethod, new ThreadSafeStringWriter(null!, "test"), new Dictionary())); - Verify(methodInfo == testMethodInfo!.TestMethod); + Verify(methodInfo == testMethodInfo!.MethodInfo); Verify(testMethodInfo.TimeoutInfo.Timeout == 0); Verify(_typeCache.ClassInfoCache.First() == testMethodInfo.Parent); Verify(testMethodInfo.Executor is not null); @@ -1132,7 +1132,7 @@ public void GetTestMethodInfoShouldReturnTestMethodInfoForDerivedClassMethodOver testMethod, new TestContextImplementation(testMethod, new ThreadSafeStringWriter(null!, "test"), new Dictionary())); - Verify(methodInfo == testMethodInfo!.TestMethod); + Verify(methodInfo == testMethodInfo!.MethodInfo); Verify(testMethodInfo.TimeoutInfo.Timeout == 0); Verify(_typeCache.ClassInfoCache.First() == testMethodInfo.Parent); Verify(testMethodInfo.Executor is not null); @@ -1155,7 +1155,7 @@ public void GetTestMethodInfoShouldReturnTestMethodInfoForDeclaringTypeMethodOve // The two MethodInfo instances will have different ReflectedType properties, // so cannot be compared directly. Use MethodHandle to verify it's the same. - Verify(methodInfo.MethodHandle == testMethodInfo!.TestMethod.MethodHandle); + Verify(methodInfo.MethodHandle == testMethodInfo!.MethodInfo.MethodHandle); Verify(testMethodInfo.TimeoutInfo.Timeout == 0); Verify(_typeCache.ClassInfoCache.First() == testMethodInfo.Parent); Verify(testMethodInfo.Executor is not null); From e2d90a60c596b350a70160d3996192f20113a94f Mon Sep 17 00:00:00 2001 From: Copilot <198982749+Copilot@users.noreply.github.com> Date: Mon, 16 Jun 2025 12:47:06 +0200 Subject: [PATCH 095/541] Add Assert.IsInRange API with three overloads (#5765) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: Evangelink <11340282+Evangelink@users.noreply.github.com> Co-authored-by: Amaury Levé --- .../Assertions/Assert.Contains.cs | 55 +++ .../PublicAPI/PublicAPI.Unshipped.txt | 3 + .../Resources/FrameworkMessages.Designer.cs | 9 + .../Resources/FrameworkMessages.resx | 3 + .../Resources/xlf/FrameworkMessages.cs.xlf | 5 + .../Resources/xlf/FrameworkMessages.de.xlf | 5 + .../Resources/xlf/FrameworkMessages.es.xlf | 5 + .../Resources/xlf/FrameworkMessages.fr.xlf | 5 + .../Resources/xlf/FrameworkMessages.it.xlf | 5 + .../Resources/xlf/FrameworkMessages.ja.xlf | 5 + .../Resources/xlf/FrameworkMessages.ko.xlf | 5 + .../Resources/xlf/FrameworkMessages.pl.xlf | 5 + .../Resources/xlf/FrameworkMessages.pt-BR.xlf | 5 + .../Resources/xlf/FrameworkMessages.ru.xlf | 5 + .../Resources/xlf/FrameworkMessages.tr.xlf | 5 + .../xlf/FrameworkMessages.zh-Hans.xlf | 5 + .../xlf/FrameworkMessages.zh-Hant.xlf | 5 + .../Assertions/AssertTests.IsInRange.cs | 336 ++++++++++++++++++ 18 files changed, 471 insertions(+) create mode 100644 test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.IsInRange.cs diff --git a/src/TestFramework/TestFramework/Assertions/Assert.Contains.cs b/src/TestFramework/TestFramework/Assertions/Assert.Contains.cs index d8f4b85747..c81dc34187 100644 --- a/src/TestFramework/TestFramework/Assertions/Assert.Contains.cs +++ b/src/TestFramework/TestFramework/Assertions/Assert.Contains.cs @@ -732,4 +732,59 @@ public static void DoesNotContain(string substring, string value, StringComparis } #endregion // DoesNotContain + + #region IsInRange + + /// + /// Tests whether the specified value is within the expected range (inclusive). + /// The range includes both the minimum and maximum values. + /// + /// The type of the values to compare. + /// The minimum value of the expected range (inclusive). + /// The maximum value of the expected range (inclusive). + /// The value to test. + public static void IsInRange(T minValue, T maxValue, T value) + where T : struct, IComparable + => IsInRange(minValue, maxValue, value, string.Empty, null); + + /// + /// Tests whether the specified value is within the expected range (inclusive). + /// The range includes both the minimum and maximum values. + /// + /// The type of the values to compare. + /// The minimum value of the expected range (inclusive). + /// The maximum value of the expected range (inclusive). + /// The value to test. + /// The message to display when the assertion fails. + public static void IsInRange(T minValue, T maxValue, T value, string? message) + where T : struct, IComparable + => IsInRange(minValue, maxValue, value, message, null); + + /// + /// Tests whether the specified value is within the expected range (inclusive). + /// The range includes both the minimum and maximum values. + /// + /// The type of the values to compare. + /// The minimum value of the expected range (inclusive). + /// The maximum value of the expected range (inclusive). + /// The value to test. + /// The message format to display when the assertion fails. + /// The parameters to format the message. + public static void IsInRange(T minValue, T maxValue, T value, [StringSyntax(StringSyntaxAttribute.CompositeFormat)] string? message, params object?[]? parameters) + where T : struct, IComparable + { + if (maxValue.CompareTo(minValue) <= 0) + { + throw new ArgumentOutOfRangeException(nameof(maxValue), "The maximum value must be greater than the minimum value."); + } + + if (value.CompareTo(minValue) < 0 || value.CompareTo(maxValue) > 0) + { + string userMessage = BuildUserMessage(message, parameters); + string finalMessage = string.Format(CultureInfo.CurrentCulture, FrameworkMessages.IsInRangeFail, value, minValue, maxValue, userMessage); + ThrowAssertFailed("IsInRange", finalMessage); + } + } + + #endregion // IsInRange } diff --git a/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Unshipped.txt b/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Unshipped.txt index a9c1dc2d57..8e931d54f2 100644 --- a/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Unshipped.txt +++ b/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Unshipped.txt @@ -1,6 +1,9 @@ #nullable enable Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AssertNonStrictThrowsInterpolatedStringHandler.AssertNonStrictThrowsInterpolatedStringHandler(int literalLength, int formattedCount, System.Func! action, out bool shouldAppend) -> void Microsoft.VisualStudio.TestTools.UnitTesting.ConditionBaseAttribute.Mode.get -> Microsoft.VisualStudio.TestTools.UnitTesting.ConditionMode +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsInRange(T minValue, T maxValue, T value) -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsInRange(T minValue, T maxValue, T value, string? message) -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsInRange(T minValue, T maxValue, T value, string? message, params object?[]? parameters) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.ContainsSingle(System.Func! predicate, System.Collections.Generic.IEnumerable! collection) -> T static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.ContainsSingle(System.Func! predicate, System.Collections.Generic.IEnumerable! collection, string? message) -> T static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.ContainsSingle(System.Func! predicate, System.Collections.Generic.IEnumerable! collection, string? message, params object?[]? parameters) -> T diff --git a/src/TestFramework/TestFramework/Resources/FrameworkMessages.Designer.cs b/src/TestFramework/TestFramework/Resources/FrameworkMessages.Designer.cs index 51c9d1dd52..983b2d9341 100644 --- a/src/TestFramework/TestFramework/Resources/FrameworkMessages.Designer.cs +++ b/src/TestFramework/TestFramework/Resources/FrameworkMessages.Designer.cs @@ -413,6 +413,15 @@ internal static string InvalidPropertyType { } } + /// + /// Looks up a localized string similar to Value '{0}' is not within the expected range [{1}, {2}]. {3}. + /// + internal static string IsInRangeFail { + get { + return ResourceManager.GetString("IsInRangeFail", resourceCulture); + } + } + /// /// Looks up a localized string similar to {0} Expected type:<{1}>. Actual type:<{2}>.. /// diff --git a/src/TestFramework/TestFramework/Resources/FrameworkMessages.resx b/src/TestFramework/TestFramework/Resources/FrameworkMessages.resx index ceca8be756..5ae35512eb 100644 --- a/src/TestFramework/TestFramework/Resources/FrameworkMessages.resx +++ b/src/TestFramework/TestFramework/Resources/FrameworkMessages.resx @@ -165,6 +165,9 @@ String '{0}' does not contain string '{1}'. {2}. + + Value '{0}' is not within the expected range [{1}, {2}]. {3} + The number of elements in the collections do not match. Expected:<{1}>. Actual:<{2}>.{0} diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.cs.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.cs.xlf index ddfcc9862b..7988770e9a 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.cs.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.cs.xlf @@ -141,6 +141,11 @@ Skutečnost: {2} Neplatná adresa URL lístku GitHubu + + Value '{0}' is not within the expected range [{1}, {2}]. {3} + Value '{0}' is not within the expected range [{1}, {2}]. {3} + + {0} Expected type:<{1}>. Actual type:<{2}>. {0} Očekávaný typ:<{1}>. Aktuální typ:<{2}>. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.de.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.de.xlf index 651d41e168..0055572296 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.de.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.de.xlf @@ -141,6 +141,11 @@ Tatsächlich: {2} Ungültige GitHub-Ticket-URL. + + Value '{0}' is not within the expected range [{1}, {2}]. {3} + Value '{0}' is not within the expected range [{1}, {2}]. {3} + + {0} Expected type:<{1}>. Actual type:<{2}>. {0}Erwarteter Typ:<{1}>. Tatsächlicher Typ:<{2}>. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.es.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.es.xlf index f838df72e1..c1e47e5e8b 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.es.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.es.xlf @@ -141,6 +141,11 @@ Real: {2} Dirección URL de vale de GitHub no válida + + Value '{0}' is not within the expected range [{1}, {2}]. {3} + Value '{0}' is not within the expected range [{1}, {2}]. {3} + + {0} Expected type:<{1}>. Actual type:<{2}>. {0} Tipo esperado:<{1}>. Tipo real:<{2}>. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.fr.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.fr.xlf index c342c620e5..8e677f7cfb 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.fr.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.fr.xlf @@ -141,6 +141,11 @@ Réel : {2} URL de ticket GitHub non valide + + Value '{0}' is not within the expected range [{1}, {2}]. {3} + Value '{0}' is not within the expected range [{1}, {2}]. {3} + + {0} Expected type:<{1}>. Actual type:<{2}>. {0}Type attendu :<{1}>. Type réel :<{2}>. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.it.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.it.xlf index 3b297c7af2..fef17b3ca8 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.it.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.it.xlf @@ -141,6 +141,11 @@ Effettivo: {2} L'URL del ticket GitHub non è valido + + Value '{0}' is not within the expected range [{1}, {2}]. {3} + Value '{0}' is not within the expected range [{1}, {2}]. {3} + + {0} Expected type:<{1}>. Actual type:<{2}>. {0} Tipo previsto:<{1}>. Tipo effettivo:<{2}>. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ja.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ja.xlf index ad0c99078d..daa41f4e26 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ja.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ja.xlf @@ -141,6 +141,11 @@ Actual: {2} GitHub チケット URL が無効です + + Value '{0}' is not within the expected range [{1}, {2}]. {3} + Value '{0}' is not within the expected range [{1}, {2}]. {3} + + {0} Expected type:<{1}>. Actual type:<{2}>. {0} には型 <{1}> が必要ですが、型 <{2}> が指定されました。 diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ko.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ko.xlf index e0428e081c..c5f9023288 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ko.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ko.xlf @@ -141,6 +141,11 @@ Actual: {2} 잘못된 GitHub 티켓 URL + + Value '{0}' is not within the expected range [{1}, {2}]. {3} + Value '{0}' is not within the expected range [{1}, {2}]. {3} + + {0} Expected type:<{1}>. Actual type:<{2}>. {0} 예상 형식: <{1}>, 실제 형식: <{2}>. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pl.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pl.xlf index 41afe70660..d809fd5bf9 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pl.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pl.xlf @@ -141,6 +141,11 @@ Rzeczywiste: {2} Nieprawidłowy adres URL biletu usługi GitHub + + Value '{0}' is not within the expected range [{1}, {2}]. {3} + Value '{0}' is not within the expected range [{1}, {2}]. {3} + + {0} Expected type:<{1}>. Actual type:<{2}>. {0} Oczekiwany typ:<{1}>. Rzeczywisty typ:<{2}>. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf index 8078eeba69..ca320a6468 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf @@ -141,6 +141,11 @@ Real: {2} URL de tíquete do GitHub inválida + + Value '{0}' is not within the expected range [{1}, {2}]. {3} + Value '{0}' is not within the expected range [{1}, {2}]. {3} + + {0} Expected type:<{1}>. Actual type:<{2}>. {0} Tipo esperado:<{1}>. Tipo real:<{2}>. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ru.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ru.xlf index f27e54ae56..3babb3c3a7 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ru.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ru.xlf @@ -141,6 +141,11 @@ Actual: {2} Недопустимый URL-адрес билета GitHub + + Value '{0}' is not within the expected range [{1}, {2}]. {3} + Value '{0}' is not within the expected range [{1}, {2}]. {3} + + {0} Expected type:<{1}>. Actual type:<{2}>. {0}Ожидается тип: <{1}>. Фактический тип: <{2}>. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.tr.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.tr.xlf index 6ba4ddec3d..59ffe8eb13 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.tr.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.tr.xlf @@ -141,6 +141,11 @@ Gerçekte olan: {2} Geçersiz GitHub anahtar URL'si + + Value '{0}' is not within the expected range [{1}, {2}]. {3} + Value '{0}' is not within the expected range [{1}, {2}]. {3} + + {0} Expected type:<{1}>. Actual type:<{2}>. {0} Beklenen tür:<{1}>. Gerçek tür:<{2}>. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf index f8f3b68731..e597dffd4d 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf @@ -141,6 +141,11 @@ Actual: {2} GitHub 票证 URL 无效 + + Value '{0}' is not within the expected range [{1}, {2}]. {3} + Value '{0}' is not within the expected range [{1}, {2}]. {3} + + {0} Expected type:<{1}>. Actual type:<{2}>. {0} 类型应为: <{1}>。类型实为: <{2}>。 diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf index 49aa1e77f7..3e2131ca8c 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf @@ -141,6 +141,11 @@ Actual: {2} 無效的 GitHub 票證 URL + + Value '{0}' is not within the expected range [{1}, {2}]. {3} + Value '{0}' is not within the expected range [{1}, {2}]. {3} + + {0} Expected type:<{1}>. Actual type:<{2}>. {0} 預期的類型: <{1}>,實際的類型: <{2}>。 diff --git a/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.IsInRange.cs b/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.IsInRange.cs new file mode 100644 index 0000000000..16922019d8 --- /dev/null +++ b/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.IsInRange.cs @@ -0,0 +1,336 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using FluentAssertions; + +using TestFramework.ForTestingMSTest; + +namespace Microsoft.VisualStudio.TestTools.UnitTesting.UnitTests; + +/// +/// Unit tests for the Assert.IsInRange methods. +/// +public partial class AssertTests : TestContainer +{ + #region IsInRange Tests + + public void IsInRange_WithValueInRange_DoesNotThrow() + { + // Arrange + int minValue = 1; + int maxValue = 10; + int value = 5; + + // Act & Assert + Assert.IsInRange(minValue, maxValue, value); + } + + public void IsInRange_WithValueEqualToMin_DoesNotThrow() + { + // Arrange + int minValue = 1; + int maxValue = 10; + int value = 1; + + // Act & Assert + Assert.IsInRange(minValue, maxValue, value); + } + + public void IsInRange_WithValueEqualToMax_DoesNotThrow() + { + // Arrange + int minValue = 1; + int maxValue = 10; + int value = 10; + + // Act & Assert + Assert.IsInRange(minValue, maxValue, value); + } + + public void IsInRange_WithValueBelowRange_ThrowsAssertFailedException() + { + // Arrange + int minValue = 5; + int maxValue = 10; + int value = 3; + + // Act & Assert + Exception ex = VerifyThrows(() => Assert.IsInRange(minValue, maxValue, value)); + Verify(ex.Message.Contains("Value '3' is not within the expected range [5, 10]")); + } + + public void IsInRange_WithValueAboveRange_ThrowsAssertFailedException() + { + // Arrange + int minValue = 1; + int maxValue = 5; + int value = 8; + + // Act & Assert + Exception ex = VerifyThrows(() => Assert.IsInRange(minValue, maxValue, value)); + Verify(ex.Message.Contains("Value '8' is not within the expected range [1, 5]")); + } + + public void IsInRange_WithCustomMessage_IncludesCustomMessage() + { + // Arrange + int minValue = 1; + int maxValue = 5; + int value = 10; + string customMessage = "Custom error message"; + + // Act + Action action = () => Assert.IsInRange(minValue, maxValue, value, customMessage); + + // Assert + action.Should().ThrowExactly() + .And.Message.Should().Contain("Value '10' is not within the expected range [1, 5]") + .And.Contain(customMessage); + } + + public void IsInRange_WithMessageAndParameters_FormatsMessage() + { + // Arrange + int minValue = 1; + int maxValue = 5; + int value = 10; + string messageFormat = "Test with parameter: {0}"; + string parameter = "TestValue"; + + // Act + Action action = () => Assert.IsInRange(minValue, maxValue, value, messageFormat, parameter); + + // Assert + action.Should().ThrowExactly() + .And.Message.Should().Contain("Value '10' is not within the expected range [1, 5]") + .And.Contain("Test with parameter: TestValue"); + } + + public void IsInRange_WithDoubleValues_WorksCorrectly() + { + // Arrange + double minValue = 1.5; + double maxValue = 5.5; + double valueInRange = 3.0; + double valueOutOfRange = 6.0; + + // Act & Assert + Assert.IsInRange(minValue, maxValue, valueInRange); + Exception ex = VerifyThrows(() => Assert.IsInRange(minValue, maxValue, valueOutOfRange)); + Verify(ex.Message.Contains("Value '6' is not within the expected range [1.5, 5.5]")); + } + + public void IsInRange_WithDateTimeValues_WorksCorrectly() + { + // Arrange + var minValue = new DateTime(2023, 1, 1); + var maxValue = new DateTime(2023, 12, 31); + var valueInRange = new DateTime(2023, 6, 15); + var valueOutOfRange = new DateTime(2024, 1, 1); + + // Act + Assert.IsInRange(minValue, maxValue, valueInRange); + Action action = () => Assert.IsInRange(minValue, maxValue, valueOutOfRange); + + // Assert + action.Should().ThrowExactly() + .And.Message.Should().Contain("is not within the expected range"); + } + + public void IsInRange_WithCharValues_WorksCorrectly() + { + // Arrange + char minValue = 'A'; + char maxValue = 'Z'; + char valueInRange = 'M'; + char valueOutOfRange = 'a'; + + // Act + Assert.IsInRange(minValue, maxValue, valueInRange); + Action action = () => Assert.IsInRange(minValue, maxValue, valueOutOfRange); + + // Assert + action.Should().ThrowExactly() + .And.Message.Should().Contain("Value 'a' is not within the expected range [A, Z]"); + } + + public void IsInRange_WithNullMessage_DoesNotThrow() + { + // Arrange + int minValue = 1; + int maxValue = 5; + int value = 3; + + // Act & Assert + Assert.IsInRange(minValue, maxValue, value, null); + } + + public void IsInRange_WithEmptyMessage_DoesNotThrow() + { + // Arrange + int minValue = 1; + int maxValue = 5; + int value = 3; + + // Act & Assert + Assert.IsInRange(minValue, maxValue, value, string.Empty); + } + + public void IsInRange_WithNullParameters_DoesNotThrow() + { + // Arrange + int minValue = 1; + int maxValue = 5; + int value = 3; + + // Act & Assert + Assert.IsInRange(minValue, maxValue, value, "Test message", null); + } + + public void IsInRange_WithAllNegativeValuesInRange_DoesNotThrow() + { + // Arrange + int minValue = -10; + int maxValue = -5; + int value = -7; + + // Act & Assert + Assert.IsInRange(minValue, maxValue, value); + } + + public void IsInRange_WithAllNegativeValuesBelowRange_ThrowsAssertFailedException() + { + // Arrange + int minValue = -10; + int maxValue = -5; + int value = -12; + + // Act & Assert + Action action = () => Assert.IsInRange(minValue, maxValue, value); + + // Assert + action.Should().ThrowExactly() + .And.Message.Should().Contain("Value '-12' is not within the expected range [-10, -5]"); + } + + public void IsInRange_WithAllNegativeValuesAboveRange_ThrowsAssertFailedException() + { + // Arrange + int minValue = -10; + int maxValue = -5; + int value = -3; + + // Act + Action action = () => Assert.IsInRange(minValue, maxValue, value); + + // Assert + action.Should().ThrowExactly() + .And.Message.Should().Contain("Value '-3' is not within the expected range [-10, -5]"); + } + + public void IsInRange_WithRangeSpanningNegativeToPositive_ValueInRange_DoesNotThrow() + { + // Arrange + int minValue = -5; + int maxValue = 5; + int value = 0; + + // Act & Assert + Assert.IsInRange(minValue, maxValue, value); + } + + public void IsInRange_WithRangeSpanningNegativeToPositive_NegativeValueInRange_DoesNotThrow() + { + // Arrange + int minValue = -5; + int maxValue = 5; + int value = -3; + + // Act & Assert + Assert.IsInRange(minValue, maxValue, value); + } + + public void IsInRange_WithRangeSpanningNegativeToPositive_PositiveValueInRange_DoesNotThrow() + { + // Arrange + int minValue = -5; + int maxValue = 5; + int value = 3; + + // Act & Assert + Assert.IsInRange(minValue, maxValue, value); + } + + public void IsInRange_WithRangeSpanningNegativeToPositive_ValueBelowRange_ThrowsAssertFailedException() + { + // Arrange + int minValue = -5; + int maxValue = 5; + int value = -7; + + // Act + Action action = () => Assert.IsInRange(minValue, maxValue, value); + + // Assert + action.Should().ThrowExactly() + .And.Message.Should().Contain("Value '-7' is not within the expected range [-5, 5]"); + } + + public void IsInRange_WithRangeSpanningNegativeToPositive_ValueAboveRange_ThrowsAssertFailedException() + { + // Arrange + int minValue = -5; + int maxValue = 5; + int value = 7; + + // Act + Action action = () => Assert.IsInRange(minValue, maxValue, value); + + // Assert + action.Should().ThrowExactly() + .And.Message.Should().Contain("Value '7' is not within the expected range [-5, 5]"); + } + + public void IsInRange_WithNegativeDoubleValues_WorksCorrectly() + { + // Arrange + double minValue = -10.5; + double maxValue = -2.5; + double valueInRange = -5.0; + + // Act & Assert + Assert.IsInRange(minValue, maxValue, valueInRange); + } + + public void IsInRange_WithMaxValueLessThanMinValue_ThrowsArgumentOutOfRangeException() + { + // Arrange + int minValue = 10; + int maxValue = 5; + int value = 7; + + // Act + Action action = () => Assert.IsInRange(minValue, maxValue, value); + + // Assert + action.Should().ThrowExactly() + .And.Message.Should().Contain("The maximum value must be greater than the minimum value"); + } + + public void IsInRange_WithMaxValueEqualToMinValue_ThrowsArgumentOutOfRangeException() + { + // Arrange + int minValue = 5; + int maxValue = 5; + int value = 5; + + // Act + Action action = () => Assert.IsInRange(minValue, maxValue, value); + + // Assert + action.Should().ThrowExactly() + .And.Message.Should().Contain("The maximum value must be greater than the minimum value"); + } + + #endregion // IsInRange Tests +} From b7abf4550f53d6b2c3f089d2b3c7aaece804ffe0 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Mon, 16 Jun 2025 14:26:24 +0200 Subject: [PATCH 096/541] Fix TraceListenerManager thread safety issue (#5750) --- .../Execution/ClassCleanupManager.cs | 8 +- .../Execution/ConsoleErrorCapturer.cs | 52 +++++ .../Execution/ConsoleOutCapturer.cs | 52 +++++ .../Execution/TestAssemblyInfo.cs | 43 ++--- .../Execution/TestClassInfo.cs | 134 +++++-------- .../Execution/TestMethodInfo.cs | 19 +- .../Execution/TestMethodRunner.cs | 9 +- .../Execution/TraceTextWriter.cs | 27 +++ .../Execution/UnitTestRunner.cs | 108 +++-------- .../IPlatformServiceProvider.cs | 5 +- .../PlatformServiceProvider.cs | 7 +- .../Services/TestContextImplementation.cs | 182 ++++++++++-------- .../Execution/TestClassInfoTests.cs | 26 +-- .../PlatformServiceProviderTests.cs | 3 +- .../TestContextImplementationTests.cs | 2 +- .../TestablePlatformServiceProvider.cs | 4 +- 16 files changed, 367 insertions(+), 314 deletions(-) create mode 100644 src/Adapter/MSTestAdapter.PlatformServices/Execution/ConsoleErrorCapturer.cs create mode 100644 src/Adapter/MSTestAdapter.PlatformServices/Execution/ConsoleOutCapturer.cs create mode 100644 src/Adapter/MSTestAdapter.PlatformServices/Execution/TraceTextWriter.cs diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Execution/ClassCleanupManager.cs b/src/Adapter/MSTestAdapter.PlatformServices/Execution/ClassCleanupManager.cs index 268fb8d2c7..064a33759b 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Execution/ClassCleanupManager.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Execution/ClassCleanupManager.cs @@ -65,13 +65,11 @@ public void MarkTestComplete(TestMethodInfo testMethodInfo, TestMethod testMetho internal static void ForceCleanup(TypeCache typeCache, IDictionary sourceLevelParameters, IMessageLogger logger) { - using var writer = new ThreadSafeStringWriter(CultureInfo.InvariantCulture, "context"); - TestContext testContext = new TestContextImplementation(null, writer, sourceLevelParameters, logger, testRunCancellationToken: null); + TestContext testContext = new TestContextImplementation(null, sourceLevelParameters, logger, testRunCancellationToken: null); IEnumerable classInfoCache = typeCache.ClassInfoListWithExecutableCleanupMethods; - LogMessageListener? listener = null; foreach (TestClassInfo classInfo in classInfoCache) { - TestFailedException? ex = classInfo.ExecuteClassCleanup(testContext, out listener); + TestFailedException? ex = classInfo.ExecuteClassCleanup(testContext); if (ex is not null) { throw ex; @@ -81,7 +79,7 @@ internal static void ForceCleanup(TypeCache typeCache, IDictionary assemblyInfoCache = typeCache.AssemblyInfoListWithExecutableCleanupMethods; foreach (TestAssemblyInfo assemblyInfo in assemblyInfoCache) { - TestFailedException? ex = assemblyInfo.ExecuteAssemblyCleanup(testContext, ref listener); + TestFailedException? ex = assemblyInfo.ExecuteAssemblyCleanup(testContext); if (ex is not null) { throw ex; diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Execution/ConsoleErrorCapturer.cs b/src/Adapter/MSTestAdapter.PlatformServices/Execution/ConsoleErrorCapturer.cs new file mode 100644 index 0000000000..78f73054ae --- /dev/null +++ b/src/Adapter/MSTestAdapter.PlatformServices/Execution/ConsoleErrorCapturer.cs @@ -0,0 +1,52 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; + +namespace Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution; + +internal sealed class ConsoleErrorCapturer : TextWriter +{ + private readonly TextWriter _originalConsoleErr; + + public ConsoleErrorCapturer(TextWriter originalConsoleErr) + => _originalConsoleErr = originalConsoleErr; + + public override Encoding Encoding => Encoding.UTF8; + + public override void Write(char value) + { + if (TestContextImplementation.CurrentTestContext is { } testContext) + { + testContext.WriteConsoleErr(value); + } + else + { + _originalConsoleErr.Write(value); + } + } + + public override void Write(string? value) + { + if (TestContextImplementation.CurrentTestContext is { } testContext) + { + testContext.WriteConsoleErr(value); + } + else + { + _originalConsoleErr.Write(value); + } + } + + public override void Write(char[] buffer, int index, int count) + { + if (TestContextImplementation.CurrentTestContext is { } testContext) + { + testContext.WriteConsoleErr(buffer, index, count); + } + else + { + _originalConsoleErr.Write(buffer, index, count); + } + } +} diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Execution/ConsoleOutCapturer.cs b/src/Adapter/MSTestAdapter.PlatformServices/Execution/ConsoleOutCapturer.cs new file mode 100644 index 0000000000..612602f5ad --- /dev/null +++ b/src/Adapter/MSTestAdapter.PlatformServices/Execution/ConsoleOutCapturer.cs @@ -0,0 +1,52 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; + +namespace Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution; + +internal sealed class ConsoleOutCapturer : TextWriter +{ + private readonly TextWriter _originalConsoleOut; + + public ConsoleOutCapturer(TextWriter originalConsoleOut) + => _originalConsoleOut = originalConsoleOut; + + public override Encoding Encoding => Encoding.UTF8; + + public override void Write(char value) + { + if (TestContextImplementation.CurrentTestContext is { } testContext) + { + testContext.WriteConsoleOut(value); + } + else + { + _originalConsoleOut.Write(value); + } + } + + public override void Write(string? value) + { + if (TestContextImplementation.CurrentTestContext is { } testContext) + { + testContext.WriteConsoleOut(value); + } + else + { + _originalConsoleOut.Write(value); + } + } + + public override void Write(char[] buffer, int index, int count) + { + if (TestContextImplementation.CurrentTestContext is { } testContext) + { + testContext.WriteConsoleOut(buffer, index, count); + } + else + { + _originalConsoleOut.Write(buffer, index, count); + } + } +} diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestAssemblyInfo.cs b/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestAssemblyInfo.cs index 21aab26542..93e3f82295 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestAssemblyInfo.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestAssemblyInfo.cs @@ -114,13 +114,7 @@ internal set /// The test context. /// Throws a test failed exception if the initialization method throws an exception. public void RunAssemblyInitialize(TestContext testContext) - => RunAssemblyInitialize(testContext, out _); - - [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Requirement is to handle all kinds of user exceptions and message appropriately.")] - internal void RunAssemblyInitialize(TestContext testContext, out LogMessageListener? logListener) { - logListener = null; - // No assembly initialize => nothing to do. if (AssemblyInitializeMethod == null) { @@ -146,15 +140,18 @@ internal void RunAssemblyInitialize(TestContext testContext, out LogMessageListe // Perform a check again. if (!IsAssemblyInitializeExecuted) { - LogMessageListener? logMessageListener = null; - try { AssemblyInitializationException = FixtureMethodRunner.RunWithTimeoutAndCancellation( () => { - logMessageListener = new LogMessageListener(MSTestSettings.CurrentSettings.CaptureDebugTraces); - AssemblyInitializeMethod.InvokeAsSynchronousTask(null, testContext); + // NOTE: It's unclear what the effect is if we reset the current test context before vs after the capture. + // It's safer to reset it before the capture. + using (TestContextImplementation.SetCurrentTestContext(testContext as TestContextImplementation)) + { + AssemblyInitializeMethod.InvokeAsSynchronousTask(null, testContext); + } + // **After** we have executed the assembly initialize, we save the current context. // This context will contain async locals set by the assembly initialize method. ExecutionContext = ExecutionContext.Capture(); @@ -173,7 +170,6 @@ internal void RunAssemblyInitialize(TestContext testContext, out LogMessageListe finally { IsAssemblyInitializeExecuted = true; - logListener = logMessageListener; } } } @@ -280,7 +276,7 @@ internal void RunAssemblyInitialize(TestContext testContext, out LogMessageListe /// It is a replacement for RunAssemblyCleanup but as we are in a bug-fix version, we do not want to touch /// public API and so we introduced this method. /// - internal TestFailedException? ExecuteAssemblyCleanup(TestContext testContext, ref LogMessageListener? logListener) + internal TestFailedException? ExecuteAssemblyCleanup(TestContext testContext) { if (AssemblyCleanupMethod == null) { @@ -289,20 +285,23 @@ internal void RunAssemblyInitialize(TestContext testContext, out LogMessageListe lock (_assemblyInfoExecuteSyncObject) { - LogMessageListener? logMessageListener = logListener; try { AssemblyCleanupException = FixtureMethodRunner.RunWithTimeoutAndCancellation( () => { - logMessageListener ??= new LogMessageListener(MSTestSettings.CurrentSettings.CaptureDebugTraces); - if (AssemblyCleanupMethod.GetParameters().Length == 0) + // NOTE: It's unclear what the effect is if we reset the current test context before vs after the capture. + // It's safer to reset it before the capture. + using (TestContextImplementation.SetCurrentTestContext(testContext as TestContextImplementation)) { - AssemblyCleanupMethod.InvokeAsSynchronousTask(null); - } - else - { - AssemblyCleanupMethod.InvokeAsSynchronousTask(null, testContext); + if (AssemblyCleanupMethod.GetParameters().Length == 0) + { + AssemblyCleanupMethod.InvokeAsSynchronousTask(null); + } + else + { + AssemblyCleanupMethod.InvokeAsSynchronousTask(null, testContext); + } } ExecutionContext = ExecutionContext.Capture(); @@ -318,10 +317,6 @@ internal void RunAssemblyInitialize(TestContext testContext, out LogMessageListe { AssemblyCleanupException = ex; } - finally - { - logListener = logMessageListener; - } } // If assemblyCleanup was successful, then don't do anything diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestClassInfo.cs b/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestClassInfo.cs index 85b388b123..3c285bf9de 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestClassInfo.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestClassInfo.cs @@ -250,13 +250,7 @@ internal set /// The test context. /// Throws a test failed exception if the initialization method throws an exception. public void RunClassInitialize(TestContext testContext) - => RunClassInitialize(testContext, out _); - - [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Requirement is to handle all kinds of user exceptions and message appropriately.")] - internal void RunClassInitialize(TestContext testContext, out LogMessageListener? logListener) { - logListener = null; - // If no class initialize and no base class initialize, return if (ClassInitializeMethod is null && BaseClassInitMethods.Count == 0) { @@ -287,7 +281,7 @@ internal void RunClassInitialize(TestContext testContext, out LogMessageListener for (int i = BaseClassInitMethods.Count - 1; i >= 0; i--) { initializeMethod = BaseClassInitMethods[i]; - ClassInitializationException = InvokeInitializeMethod(initializeMethod, testContext, ref logListener); + ClassInitializationException = InvokeInitializeMethod(initializeMethod, testContext); if (ClassInitializationException is not null) { break; @@ -297,7 +291,7 @@ internal void RunClassInitialize(TestContext testContext, out LogMessageListener if (ClassInitializationException is null) { initializeMethod = ClassInitializeMethod; - ClassInitializationException = InvokeInitializeMethod(ClassInitializeMethod, testContext, ref logListener); + ClassInitializationException = InvokeInitializeMethod(ClassInitializeMethod, testContext); } } catch (Exception ex) @@ -361,7 +355,7 @@ internal void RunClassInitialize(TestContext testContext, out LogMessageListener TestFailureException = _classInitializeResult.TestFailureException, }; - internal TestResult GetResultOrRunClassInitialize(ITestContext testContext, string initializationLogs, string initializationErrorLogs, string initializationTrace, string initializationTestContextMessages) + internal TestResult GetResultOrRunClassInitialize(ITestContext testContext, string? initializationLogs, string? initializationErrorLogs, string? initializationTrace, string? initializationTestContextMessages) { TestResult? clonedInitializeResult = TryGetClonedCachedClassInitializeResult(); @@ -458,26 +452,8 @@ TestResult DoRun() try { - LogMessageListener? logListener = null; - try - { - // This runs the ClassInitialize methods only once but saves the - RunClassInitialize(testContext.Context, out logListener); - } - finally - { - if (logListener is not null) - { - ExecutionContextHelpers.RunOnContext(ExecutionContext, () => - { - initializationLogs += logListener.GetAndClearStandardOutput(); - initializationTrace += logListener.GetAndClearDebugTrace(); - initializationErrorLogs += logListener.GetAndClearStandardError(); - initializationTestContextMessages += testContext.GetAndClearDiagnosticMessages(); - logListener?.Dispose(); - }); - } - } + // This runs the ClassInitialize methods only once but saves the + RunClassInitialize(testContext.Context); } catch (TestFailedException ex) { @@ -494,10 +470,11 @@ TestResult DoRun() finally { // Assembly initialize and class initialize logs are pre-pended to the first result. - result.LogOutput = initializationLogs; - result.LogError = initializationErrorLogs; - result.DebugTrace = initializationTrace; - result.TestContextMessages = initializationTestContextMessages; + var testContextImpl = testContext as TestContextImplementation; + result.LogOutput = initializationLogs + testContextImpl?.GetOut(); + result.LogError = initializationErrorLogs + testContextImpl?.GetErr(); + result.DebugTrace = initializationTrace + testContextImpl?.GetTrace(); + result.TestContextMessages = initializationTestContextMessages + testContext.GetAndClearDiagnosticMessages(); } _classInitializeResult = result; @@ -505,7 +482,7 @@ TestResult DoRun() } } - private TestFailedException? InvokeInitializeMethod(MethodInfo? methodInfo, TestContext testContext, ref LogMessageListener? logListener) + private TestFailedException? InvokeInitializeMethod(MethodInfo? methodInfo, TestContext testContext) { if (methodInfo is null) { @@ -518,12 +495,16 @@ TestResult DoRun() timeout = localTimeout; } - LogMessageListener? logMessageListener = logListener; TestFailedException? result = FixtureMethodRunner.RunWithTimeoutAndCancellation( () => { - logMessageListener ??= new LogMessageListener(MSTestSettings.CurrentSettings.CaptureDebugTraces); - methodInfo.InvokeAsSynchronousTask(null, testContext); + // NOTE: It's unclear what the effect is if we reset the current test context before vs after the capture. + // It's safer to reset it before the capture. + using (TestContextImplementation.SetCurrentTestContext(testContext as TestContextImplementation)) + { + methodInfo.InvokeAsSynchronousTask(null, testContext); + } + // **After** we have executed the class initialize, we save the current context. // This context will contain async locals set by the class initialize method. ExecutionContext = ExecutionContext.Capture(); @@ -534,7 +515,7 @@ TestResult DoRun() ExecutionContext ?? Parent?.ExecutionContext, Resource.ClassInitializeWasCancelled, Resource.ClassInitializeTimedOut); - logListener = logMessageListener; + return result; } @@ -571,13 +552,12 @@ TestResult DoRun() try { classCleanupMethod = ClassCleanupMethod; - LogMessageListener? listener = null; - ClassCleanupException = classCleanupMethod is not null ? InvokeCleanupMethod(classCleanupMethod, null!, ref listener) : null; + ClassCleanupException = classCleanupMethod is not null ? InvokeCleanupMethod(classCleanupMethod, null!) : null; var baseClassCleanupQueue = new Queue(BaseClassCleanupMethods); while (baseClassCleanupQueue.Count > 0 && ClassCleanupException is null) { classCleanupMethod = baseClassCleanupQueue.Dequeue(); - ClassCleanupException = InvokeCleanupMethod(classCleanupMethod, null!, ref listener); + ClassCleanupException = InvokeCleanupMethod(classCleanupMethod, null!); } IsClassCleanupExecuted = ClassCleanupException is null; @@ -629,10 +609,8 @@ TestResult DoRun() /// This is a replacement for RunClassCleanup but as we are on a bug fix version, we do not want to change /// the public API, hence this method. /// - internal TestFailedException? ExecuteClassCleanup(TestContext testContext, out LogMessageListener? logListener) + internal TestFailedException? ExecuteClassCleanup(TestContext testContext) { - logListener = null; - if ((ClassCleanupMethod is null && BaseClassCleanupMethods.Count == 0) || IsClassCleanupExecuted) { @@ -659,7 +637,7 @@ TestResult DoRun() { if (!classCleanupMethod.DeclaringType!.IsIgnored(out _)) { - ClassCleanupException = InvokeCleanupMethod(classCleanupMethod, testContext, ref logListener); + ClassCleanupException = InvokeCleanupMethod(classCleanupMethod, testContext); } } @@ -670,7 +648,7 @@ TestResult DoRun() classCleanupMethod = BaseClassCleanupMethods[i]; if (!classCleanupMethod.DeclaringType!.IsIgnored(out _)) { - ClassCleanupException = InvokeCleanupMethod(classCleanupMethod, testContext, ref logListener); + ClassCleanupException = InvokeCleanupMethod(classCleanupMethod, testContext); if (ClassCleanupException is not null) { break; @@ -780,38 +758,16 @@ internal void RunClassCleanup(ITestContext testContext, ClassCleanupManager clas // Local functions void DoRun() { - string? initializationLogs = string.Empty; - string? initializationErrorLogs = string.Empty; - string? initializationTrace = string.Empty; - string? initializationTestContextMessages = string.Empty; try { - LogMessageListener? logListener = null; - try + TestFailedException? ex = ExecuteClassCleanup(testContext.Context); + if (ex is not null && results.Length > 0) { - TestFailedException? ex = ExecuteClassCleanup(testContext.Context, out logListener); - if (ex is not null && results.Length > 0) - { #pragma warning disable IDE0056 // Use index operator - TestResult lastResult = results[results.Length - 1]; + TestResult lastResult = results[results.Length - 1]; #pragma warning restore IDE0056 // Use index operator - lastResult.Outcome = TestTools.UnitTesting.UnitTestOutcome.Error; - lastResult.TestFailureException = ex; - } - } - finally - { - if (logListener is not null) - { - ExecutionContextHelpers.RunOnContext(ExecutionContext, () => - { - initializationLogs = logListener.GetAndClearStandardOutput(); - initializationErrorLogs = logListener.GetAndClearStandardError(); - initializationTrace = logListener.GetAndClearDebugTrace(); - initializationTestContextMessages = testContext.GetAndClearDiagnosticMessages(); - logListener.Dispose(); - }); - } + lastResult.Outcome = TestTools.UnitTesting.UnitTestOutcome.Error; + lastResult.TestFailureException = ex; } } finally @@ -821,16 +777,17 @@ void DoRun() #pragma warning disable IDE0056 // Use index operator TestResult lastResult = results[results.Length - 1]; #pragma warning restore IDE0056 // Use index operator - lastResult.LogOutput += initializationLogs; - lastResult.LogError += initializationErrorLogs; - lastResult.DebugTrace += initializationTrace; - lastResult.TestContextMessages += initializationTestContextMessages; + var testContextImpl = testContext as TestContextImplementation; + lastResult.LogOutput += testContextImpl?.GetOut(); + lastResult.LogError += testContextImpl?.GetErr(); + lastResult.DebugTrace += testContextImpl?.GetTrace(); + lastResult.TestContextMessages += testContext.GetAndClearDiagnosticMessages(); } } } } - private TestFailedException? InvokeCleanupMethod(MethodInfo methodInfo, TestContext testContext, ref LogMessageListener? logListener) + private TestFailedException? InvokeCleanupMethod(MethodInfo methodInfo, TestContext testContext) { TimeoutInfo? timeout = null; if (ClassCleanupMethodTimeoutMilliseconds.TryGetValue(methodInfo, out TimeoutInfo localTimeout)) @@ -838,19 +795,21 @@ void DoRun() timeout = localTimeout; } - LogMessageListener? logMessageListener = logListener; TestFailedException? result = FixtureMethodRunner.RunWithTimeoutAndCancellation( () => { - logMessageListener ??= new LogMessageListener(MSTestSettings.CurrentSettings.CaptureDebugTraces); - - if (methodInfo.GetParameters().Length == 0) - { - methodInfo.InvokeAsSynchronousTask(null); - } - else + // NOTE: It's unclear what the effect is if we reset the current test context before vs after the capture. + // It's safer to reset it before the capture. + using (TestContextImplementation.SetCurrentTestContext(testContext as TestContextImplementation)) { - methodInfo.InvokeAsSynchronousTask(null, testContext); + if (methodInfo.GetParameters().Length == 0) + { + methodInfo.InvokeAsSynchronousTask(null); + } + else + { + methodInfo.InvokeAsSynchronousTask(null, testContext); + } } // **After** we have executed the class cleanup, we save the current context. @@ -865,7 +824,6 @@ void DoRun() Resource.ClassCleanupWasCancelled, Resource.ClassCleanupTimedOut); - logListener = logMessageListener; return result; } diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestMethodInfo.cs b/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestMethodInfo.cs index 3214c13692..9db5d41ec6 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestMethodInfo.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestMethodInfo.cs @@ -147,14 +147,10 @@ public virtual async Task InvokeAsync(object?[]? arguments) // check if arguments are set for data driven tests arguments ??= Arguments; - LogMessageListener? listener = null; watch.Start(); try { - ThreadSafeStringWriter.CleanState(); - listener = new LogMessageListener(MSTestSettings.CurrentSettings.CaptureDebugTraces); - result = IsTimeoutSet ? await ExecuteInternalWithTimeoutAsync(arguments).ConfigureAwait(false) : await ExecuteInternalAsync(arguments, null).ConfigureAwait(false); @@ -166,16 +162,13 @@ public virtual async Task InvokeAsync(object?[]? arguments) if (result != null) { + var testContextImpl = TestContext as TestContextImplementation; + result.LogOutput = testContextImpl?.GetOut(); + result.LogError = testContextImpl?.GetErr(); + result.DebugTrace = testContextImpl?.GetTrace(); + result.TestContextMessages = TestContext?.GetAndClearDiagnosticMessages(); + result.ResultFiles = TestContext?.GetResultFiles(); result.Duration = watch.Elapsed; - if (listener is not null) - { - result.DebugTrace = listener.GetAndClearDebugTrace(); - result.LogOutput = listener.GetAndClearStandardOutput(); - result.LogError = listener.GetAndClearStandardError(); - result.TestContextMessages = TestContext?.GetAndClearDiagnosticMessages(); - result.ResultFiles = TestContext?.GetResultFiles(); - listener.Dispose(); - } } } diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestMethodRunner.cs b/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestMethodRunner.cs index e7dc802ac7..f62f52fa18 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestMethodRunner.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestMethodRunner.cs @@ -63,7 +63,7 @@ public TestMethodRunner(TestMethodInfo testMethodInfo, TestMethod testMethod, IT /// Executes a test. /// /// The test results. - internal async Task ExecuteAsync(string initializationLogs, string initializationErrorLogs, string initializationTrace, string initializationTestContextMessages) + internal async Task ExecuteAsync(string? initializationLogs, string? initializationErrorLogs, string? initializationTrace, string? initializationTestContextMessages) { _testContext.Context.TestRunCount++; bool isSTATestClass = _testMethodInfo.Parent.ClassAttribute is STATestClassAttribute; @@ -109,7 +109,7 @@ internal async Task ExecuteAsync(string initializationLogs, string } // Local functions - async Task SafeRunTestMethodAsync(string initializationLogs, string initializationErrorLogs, string initializationTrace, string initializationTestContextMessages) + async Task SafeRunTestMethodAsync(string? initializationLogs, string? initializationErrorLogs, string? initializationTrace, string? initializationTestContextMessages) { TestResult[]? result = null; @@ -469,7 +469,10 @@ private async Task ExecuteTestAsync(TestMethodInfo testMethodInfo) { try { - tcs.SetResult(await _testMethodInfo.Executor.ExecuteAsync(testMethodInfo).ConfigureAwait(false)); + using (TestContextImplementation.SetCurrentTestContext(_testMethodInfo.TestContext as TestContextImplementation)) + { + tcs.SetResult(await _testMethodInfo.Executor.ExecuteAsync(testMethodInfo).ConfigureAwait(false)); + } } catch (Exception e) { diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Execution/TraceTextWriter.cs b/src/Adapter/MSTestAdapter.PlatformServices/Execution/TraceTextWriter.cs new file mode 100644 index 0000000000..261de5d466 --- /dev/null +++ b/src/Adapter/MSTestAdapter.PlatformServices/Execution/TraceTextWriter.cs @@ -0,0 +1,27 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; + +namespace Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution; + +internal sealed class TraceTextWriter : TextWriter +{ + public override Encoding Encoding => Encoding.UTF8; + + public override void Write(char value) + { + if (TestContextImplementation.CurrentTestContext is { } testContext) + { + testContext.WriteTrace(value); + } + } + + public override void Write(string? value) + { + if (TestContextImplementation.CurrentTestContext is { } testContext) + { + testContext.WriteTrace(value); + } + } +} diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Execution/UnitTestRunner.cs b/src/Adapter/MSTestAdapter.PlatformServices/Execution/UnitTestRunner.cs index 4634bf8c68..ef58ac4366 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Execution/UnitTestRunner.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Execution/UnitTestRunner.cs @@ -53,6 +53,13 @@ internal UnitTestRunner(MSTestSettings settings, UnitTestElement[] testsToRun, i // This would just be resetting the settings to itself in non desktop workflows. MSTestSettings.PopulateSettings(settings); + if (MSTestSettings.CurrentSettings.CaptureDebugTraces) + { + Console.SetOut(new ConsoleOutCapturer(Console.Out)); + Console.SetError(new ConsoleErrorCapturer(Console.Error)); + Trace.Listeners.Add(new TextWriterTraceListener(new TraceTextWriter())); + } + PlatformServiceProvider.Instance.TestRunCancellationToken ??= new TestRunCancellationToken(); _reflectHelper = reflectHelper; @@ -150,9 +157,8 @@ internal async Task RunSingleTestAsync(TestMethod testMethod, IDic try { - using var writer = new ThreadSafeStringWriter(CultureInfo.InvariantCulture, "context"); var properties = new Dictionary(testContextProperties); - testContextForTestExecution = PlatformServiceProvider.Instance.GetTestContext(testMethod, writer, properties, messageLogger, UTF.UnitTestOutcome.InProgress); + testContextForTestExecution = PlatformServiceProvider.Instance.GetTestContext(testMethod, properties, messageLogger, UTF.UnitTestOutcome.InProgress); // Get the testMethod TestMethodInfo? testMethodInfo = _typeCache.GetTestMethodInfo( @@ -172,7 +178,7 @@ internal async Task RunSingleTestAsync(TestMethod testMethod, IDic _assemblyFixtureTests.TryAdd(testMethod.AssemblyName, testMethodInfo.Parent.Parent); _classFixtureTests.TryAdd(testMethod.AssemblyName + testMethod.FullClassName, testMethodInfo.Parent); - testContextForAssemblyInit = PlatformServiceProvider.Instance.GetTestContext(testMethod, writer, properties, messageLogger, testContextForTestExecution.Context.CurrentTestOutcome); + testContextForAssemblyInit = PlatformServiceProvider.Instance.GetTestContext(testMethod, properties, messageLogger, testContextForTestExecution.Context.CurrentTestOutcome); TestResult assemblyInitializeResult = RunAssemblyInitializeIfNeeded(testMethodInfo, testContextForAssemblyInit); @@ -182,9 +188,9 @@ internal async Task RunSingleTestAsync(TestMethod testMethod, IDic } else { - testContextForClassInit = PlatformServiceProvider.Instance.GetTestContext(testMethod, writer, properties, messageLogger, testContextForAssemblyInit.Context.CurrentTestOutcome); + testContextForClassInit = PlatformServiceProvider.Instance.GetTestContext(testMethod, properties, messageLogger, testContextForAssemblyInit.Context.CurrentTestOutcome); - TestResult classInitializeResult = testMethodInfo.Parent.GetResultOrRunClassInitialize(testContextForClassInit, assemblyInitializeResult.LogOutput!, assemblyInitializeResult.LogError!, assemblyInitializeResult.DebugTrace!, assemblyInitializeResult.TestContextMessages!); + TestResult classInitializeResult = testMethodInfo.Parent.GetResultOrRunClassInitialize(testContextForClassInit, assemblyInitializeResult.LogOutput, assemblyInitializeResult.LogError, assemblyInitializeResult.DebugTrace, assemblyInitializeResult.TestContextMessages); DebugEx.Assert(testMethodInfo.Parent.IsClassInitializeExecuted, "IsClassInitializeExecuted should be true after attempting to run it."); if (classInitializeResult.Outcome != UTF.UnitTestOutcome.Passed) { @@ -196,16 +202,13 @@ internal async Task RunSingleTestAsync(TestMethod testMethod, IDic testContextForTestExecution.SetOutcome(testContextForClassInit.Context.CurrentTestOutcome); RetryBaseAttribute? retryAttribute = testMethodInfo.RetryAttribute; var testMethodRunner = new TestMethodRunner(testMethodInfo, testMethod, testContextForTestExecution); - result = await testMethodRunner.ExecuteAsync(classInitializeResult.LogOutput!, classInitializeResult.LogError!, classInitializeResult.DebugTrace!, classInitializeResult.TestContextMessages!).ConfigureAwait(false); + result = await testMethodRunner.ExecuteAsync(classInitializeResult.LogOutput, classInitializeResult.LogError, classInitializeResult.DebugTrace, classInitializeResult.TestContextMessages).ConfigureAwait(false); if (retryAttribute is not null && !RetryBaseAttribute.IsAcceptableResultForRetry(result)) { RetryResult retryResult = await retryAttribute.ExecuteAsync( new RetryContext( - async () => await testMethodRunner.ExecuteAsync( - classInitializeResult.LogOutput!, - classInitializeResult.LogError!, - classInitializeResult.DebugTrace!, - classInitializeResult.TestContextMessages!).ConfigureAwait(false), result)).ConfigureAwait(false); + async () => await testMethodRunner.ExecuteAsync(classInitializeResult.LogOutput, classInitializeResult.LogError, classInitializeResult.DebugTrace, classInitializeResult.TestContextMessages).ConfigureAwait(false), + result)).ConfigureAwait(false); result = retryResult.TryGetLast() ?? throw ApplicationStateGuard.Unreachable(); } @@ -213,12 +216,12 @@ internal async Task RunSingleTestAsync(TestMethod testMethod, IDic } } - testContextForClassCleanup = PlatformServiceProvider.Instance.GetTestContext(testMethod, writer, properties, messageLogger, testContextForTestExecution.Context.CurrentTestOutcome); + testContextForClassCleanup = PlatformServiceProvider.Instance.GetTestContext(testMethod, properties, messageLogger, testContextForTestExecution.Context.CurrentTestOutcome); testMethodInfo?.Parent.RunClassCleanup(testContextForClassCleanup, _classCleanupManager, testMethodInfo, testMethod, result); if (testMethodInfo?.Parent.Parent.IsAssemblyInitializeExecuted == true) { - testContextForAssemblyCleanup = PlatformServiceProvider.Instance.GetTestContext(testMethod, writer, properties, messageLogger, testContextForClassCleanup.Context.CurrentTestOutcome); + testContextForAssemblyCleanup = PlatformServiceProvider.Instance.GetTestContext(testMethod, properties, messageLogger, testContextForClassCleanup.Context.CurrentTestOutcome); RunAssemblyCleanupIfNeeded(testContextForAssemblyCleanup, _classCleanupManager, _typeCache, result); } @@ -248,33 +251,11 @@ internal async Task RunSingleTestAsync(TestMethod testMethod, IDic private static TestResult RunAssemblyInitializeIfNeeded(TestMethodInfo testMethodInfo, ITestContext testContext) { - string? initializationLogs = string.Empty; - string? initializationErrorLogs = string.Empty; - string? initializationTrace = string.Empty; - string? initializationTestContextMessages = string.Empty; var result = new TestResult { Outcome = UnitTestOutcome.Passed }; try { - LogMessageListener? logListener = null; - try - { - testMethodInfo.Parent.Parent.RunAssemblyInitialize(testContext.Context, out logListener); - } - finally - { - if (logListener is not null) - { - ExecutionContextHelpers.RunOnContext(testMethodInfo.Parent.Parent.ExecutionContext, () => - { - initializationLogs = logListener.GetAndClearStandardOutput(); - initializationErrorLogs = logListener.GetAndClearStandardError(); - initializationTrace = logListener.GetAndClearDebugTrace(); - initializationTestContextMessages = testContext.GetAndClearDiagnosticMessages(); - logListener.Dispose(); - }); - } - } + testMethodInfo.Parent.Parent.RunAssemblyInitialize(testContext.Context); } catch (TestFailedException ex) { @@ -287,10 +268,11 @@ private static TestResult RunAssemblyInitializeIfNeeded(TestMethodInfo testMetho } finally { - result.LogOutput = initializationLogs; - result.LogError = initializationErrorLogs; - result.DebugTrace = initializationTrace; - result.TestContextMessages = initializationTestContextMessages; + var testContextImpl = testContext.Context as TestContextImplementation; + result.LogOutput = testContextImpl?.GetOut(); + result.LogError = testContextImpl?.GetErr(); + result.DebugTrace = testContextImpl?.GetTrace(); + result.TestContextMessages = testContext.GetAndClearDiagnosticMessages(); } return result; @@ -303,33 +285,16 @@ private static void RunAssemblyCleanupIfNeeded(ITestContext testContext, ClassCl return; } - string? initializationLogs = string.Empty; - string? initializationErrorLogs = string.Empty; - string? initializationTrace = string.Empty; - string? initializationTestContextMessages = string.Empty; try { - LogMessageListener? logListener = null; // TODO: We are using the same TestContext here for ClassCleanup and AssemblyCleanup. // They should be different. IEnumerable classInfoCache = typeCache.ClassInfoListWithExecutableCleanupMethods; foreach (TestClassInfo classInfo in classInfoCache) { - TestFailedException? ex = classInfo.ExecuteClassCleanup(testContext.Context, out logListener); - if (logListener is not null) - { - ExecutionContextHelpers.RunOnContext(classInfo.ExecutionContext, () => - { - initializationLogs += logListener.GetAndClearStandardOutput(); - initializationErrorLogs += logListener.GetAndClearStandardError(); - initializationTrace += logListener.GetAndClearDebugTrace(); - initializationTestContextMessages += testContext.GetAndClearDiagnosticMessages(); - logListener.Dispose(); - logListener = null; - }); - } + TestFailedException? ex = classInfo.ExecuteClassCleanup(testContext.Context); - if (ex is not null && results.Length > 0) + if (results.Length > 0 && ex is not null) { #pragma warning disable IDE0056 // Use index operator TestResult lastResult = results[results.Length - 1]; @@ -343,21 +308,9 @@ private static void RunAssemblyCleanupIfNeeded(ITestContext testContext, ClassCl IEnumerable assemblyInfoCache = typeCache.AssemblyInfoListWithExecutableCleanupMethods; foreach (TestAssemblyInfo assemblyInfo in assemblyInfoCache) { - TestFailedException? ex = assemblyInfo.ExecuteAssemblyCleanup(testContext.Context, ref logListener); - if (logListener is not null) - { - ExecutionContextHelpers.RunOnContext(assemblyInfo.ExecutionContext, () => - { - initializationLogs += logListener.GetAndClearStandardOutput(); - initializationErrorLogs += logListener.GetAndClearStandardError(); - initializationTrace += logListener.GetAndClearDebugTrace(); - initializationTestContextMessages += testContext.GetAndClearDiagnosticMessages(); - logListener.Dispose(); - logListener = null; - }); - } + TestFailedException? ex = assemblyInfo.ExecuteAssemblyCleanup(testContext.Context); - if (ex is not null && results.Length > 0) + if (results.Length > 0 && ex is not null) { #pragma warning disable IDE0056 // Use index operator TestResult lastResult = results[results.Length - 1]; @@ -375,10 +328,11 @@ private static void RunAssemblyCleanupIfNeeded(ITestContext testContext, ClassCl #pragma warning disable IDE0056 // Use index operator TestResult lastResult = results[results.Length - 1]; #pragma warning restore IDE0056 // Use index operator - lastResult.LogOutput += initializationLogs; - lastResult.LogError += initializationErrorLogs; - lastResult.DebugTrace += initializationTrace; - lastResult.TestContextMessages += initializationTestContextMessages; + var testContextImpl = testContext as TestContextImplementation; + lastResult.LogOutput += testContextImpl?.GetOut(); + lastResult.LogError += testContextImpl?.GetErr(); + lastResult.DebugTrace += testContextImpl?.GetTrace(); + lastResult.TestContextMessages += testContext.GetAndClearDiagnosticMessages(); } } } diff --git a/src/Adapter/MSTestAdapter.PlatformServices/IPlatformServiceProvider.cs b/src/Adapter/MSTestAdapter.PlatformServices/IPlatformServiceProvider.cs index 9df85c3521..b1857bf2ef 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/IPlatformServiceProvider.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/IPlatformServiceProvider.cs @@ -117,9 +117,6 @@ ITestSourceHost CreateTestSourceHost( /// /// The test method. /// - /// - /// The writer instance for logging. - /// /// /// The default set of properties the test context needs to be filled with. /// @@ -131,5 +128,5 @@ ITestSourceHost CreateTestSourceHost( /// /// This was required for compatibility reasons since the TestContext object that the V1 adapter had for desktop is not .Net Core compliant. /// - ITestContext GetTestContext(ITestMethod testMethod, StringWriter writer, IDictionary properties, IMessageLogger messageLogger, UTF.UnitTestOutcome outcome); + ITestContext GetTestContext(ITestMethod testMethod, IDictionary properties, IMessageLogger messageLogger, UTF.UnitTestOutcome outcome); } diff --git a/src/Adapter/MSTestAdapter.PlatformServices/PlatformServiceProvider.cs b/src/Adapter/MSTestAdapter.PlatformServices/PlatformServiceProvider.cs index eade6b5a1c..755127a1eb 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/PlatformServiceProvider.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/PlatformServiceProvider.cs @@ -192,9 +192,6 @@ public ITestSourceHost CreateTestSourceHost( /// /// The test method. /// - /// - /// The writer instance for logging. - /// /// /// The default set of properties the test context needs to be filled with. /// @@ -206,9 +203,9 @@ public ITestSourceHost CreateTestSourceHost( /// /// This was required for compatibility reasons since the TestContext object that the V1 adapter had for desktop is not .Net Core compliant. /// - public ITestContext GetTestContext(ITestMethod testMethod, StringWriter writer, IDictionary properties, IMessageLogger messageLogger, UTF.UnitTestOutcome outcome) + public ITestContext GetTestContext(ITestMethod testMethod, IDictionary properties, IMessageLogger messageLogger, UTF.UnitTestOutcome outcome) { - var testContextImplementation = new TestContextImplementation(testMethod, writer, properties, messageLogger, TestRunCancellationToken); + var testContextImplementation = new TestContextImplementation(testMethod, properties, messageLogger, TestRunCancellationToken); testContextImplementation.SetOutcome(outcome); return testContextImplementation; } diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Services/TestContextImplementation.cs b/src/Adapter/MSTestAdapter.PlatformServices/Services/TestContextImplementation.cs index 23dc365800..b2d0ab97d1 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Services/TestContextImplementation.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Services/TestContextImplementation.cs @@ -27,16 +27,16 @@ namespace Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; #endif public class TestContextImplementation : TestContext, ITestContext, IDisposable { + private static readonly AsyncLocal CurrentTestContextAsyncLocal = new(); + /// /// List of result files associated with the test. /// private readonly List _testResultFiles; - /// - /// Writer on which the messages given by the user should be written. - /// - private readonly StringWriter _stringWriter; - private readonly ThreadSafeStringWriter? _threadSafeStringWriter; + // This should be removed. Don't rely on it. + // We only keep it for public constructor, but we don't pass it by the adapter. + private readonly StringWriter? _stringWriter; /// /// Properties. @@ -45,10 +45,10 @@ public class TestContextImplementation : TestContext, ITestContext, IDisposable private readonly IMessageLogger? _messageLogger; private readonly CancellationTokenRegistration? _cancellationTokenRegistration; - /// - /// Specifies whether the writer is disposed or not. - /// - private bool _stringWriterDisposed; + private StringBuilder? _stdOutStringBuilder; + private StringBuilder? _stdErrStringBuilder; + private StringBuilder? _traceStringBuilder; + private StringBuilder? _testContextMessageStringBuilder; private bool _isDisposed; @@ -75,12 +75,11 @@ public class TestContextImplementation : TestContext, ITestContext, IDisposable /// Initializes a new instance of the class. /// /// The test method. - /// The writer where diagnostic messages are written to. /// Properties/configuration passed in. /// The message logger to use. /// The global test run cancellation token. - internal TestContextImplementation(ITestMethod? testMethod, StringWriter stringWriter, IDictionary properties, IMessageLogger messageLogger, TestRunCancellationToken? testRunCancellationToken) - : this(testMethod, stringWriter, properties) + internal TestContextImplementation(ITestMethod? testMethod, IDictionary properties, IMessageLogger messageLogger, TestRunCancellationToken? testRunCancellationToken) + : this(testMethod, null!, properties) { _messageLogger = messageLogger; _cancellationTokenRegistration = testRunCancellationToken?.Register(CancelDelegate, this); @@ -97,14 +96,7 @@ public TestContextImplementation(ITestMethod? testMethod, StringWriter stringWri // testMethod can be null when running ForceCleanup (done when reaching --maximum-failed-tests. DebugEx.Assert(properties != null, "properties is not null"); -#if NETFRAMEWORK - DebugEx.Assert(stringWriter != null, "StringWriter is not null"); -#endif - _stringWriter = stringWriter; - - // Cannot get this type in constructor directly, because all signatures for all platforms need to be the same. - _threadSafeStringWriter = stringWriter as ThreadSafeStringWriter; _properties = testMethod is null ? new Dictionary(properties) : new Dictionary(properties) @@ -118,6 +110,8 @@ public TestContextImplementation(ITestMethod? testMethod, StringWriter stringWri _testResultFiles = []; } + internal static TestContextImplementation? CurrentTestContext => CurrentTestContextAsyncLocal.Value; + #region TestContext impl /// @@ -188,20 +182,9 @@ public override void AddResultFile(string fileName) /// The formatted string that contains the trace message. public override void Write(string? message) { - if (_stringWriterDisposed) - { - return; - } - - try - { - string? msg = message?.Replace("\0", "\\0"); - _stringWriter.Write(msg); - } - catch (ObjectDisposedException) - { - _stringWriterDisposed = true; - } + string? msg = message?.Replace("\0", "\\0"); + GetTestContextMessagesStringBuilder().Append(msg); + _stringWriter?.Write(msg); } /// @@ -212,20 +195,9 @@ public override void Write(string? message) /// Arguments to add to the trace message. public override void Write(string format, params object?[] args) { - if (_stringWriterDisposed) - { - return; - } - - try - { - string message = string.Format(CultureInfo.CurrentCulture, format.Replace("\0", "\\0"), args); - _stringWriter.Write(message); - } - catch (ObjectDisposedException) - { - _stringWriterDisposed = true; - } + string message = string.Format(CultureInfo.CurrentCulture, format.Replace("\0", "\\0"), args); + GetTestContextMessagesStringBuilder().Append(message); + _stringWriter?.Write(message); } /// @@ -235,20 +207,9 @@ public override void Write(string format, params object?[] args) /// The formatted string that contains the trace message. public override void WriteLine(string? message) { - if (_stringWriterDisposed) - { - return; - } - - try - { - string? msg = message?.Replace("\0", "\\0"); - _stringWriter.WriteLine(msg); - } - catch (ObjectDisposedException) - { - _stringWriterDisposed = true; - } + string? msg = message?.Replace("\0", "\\0"); + GetTestContextMessagesStringBuilder().AppendLine(msg); + _stringWriter?.Write(msg); } /// @@ -259,20 +220,9 @@ public override void WriteLine(string? message) /// Arguments to add to the trace message. public override void WriteLine(string format, params object?[] args) { - if (_stringWriterDisposed) - { - return; - } - - try - { - string message = string.Format(CultureInfo.CurrentCulture, format.Replace("\0", "\\0"), args); - _stringWriter.WriteLine(message); - } - catch (ObjectDisposedException) - { - _stringWriterDisposed = true; - } + string message = string.Format(CultureInfo.CurrentCulture, format.Replace("\0", "\\0"), args); + GetTestContextMessagesStringBuilder().AppendLine(message); + _stringWriter?.Write(message); } /// @@ -364,13 +314,16 @@ public void AddProperty(string propertyName, string propertyValue) /// /// The test context messages added so far. public string? GetDiagnosticMessages() - => _stringWriter.ToString(); + => _testContextMessageStringBuilder?.ToString(); /// /// Clears the previous testContext writeline messages. /// public void ClearDiagnosticMessages() - => _threadSafeStringWriter?.ToStringAndClear(); + { + _testContextMessageStringBuilder?.Clear(); + (_stringWriter as ThreadSafeStringWriter)?.ToStringAndClear(); + } /// public void SetDisplayName(string? displayName) @@ -404,4 +357,79 @@ protected virtual void Dispose(bool disposing) } } } + + internal readonly struct ScopedTestContextSetter : IDisposable + { + internal ScopedTestContextSetter(TestContextImplementation? testContext) + => CurrentTestContextAsyncLocal.Value = testContext; + + public void Dispose() + => CurrentTestContextAsyncLocal.Value = null; + } + + internal static ScopedTestContextSetter SetCurrentTestContext(TestContextImplementation? testContext) + => new(testContext); + + internal void WriteConsoleOut(char value) + => GetOutStringBuilder().Append(value); + + internal void WriteConsoleOut(string? value) + => GetOutStringBuilder().Append(value); + + internal void WriteConsoleOut(char[] buffer, int index, int count) + => GetOutStringBuilder().Append(buffer, index, count); + + internal void WriteConsoleErr(char value) + => GetErrStringBuilder().Append(value); + + internal void WriteConsoleErr(string? value) + => GetErrStringBuilder().Append(value); + + internal void WriteConsoleErr(char[] buffer, int index, int count) + => GetErrStringBuilder().Append(buffer, index, count); + + internal void WriteTrace(char value) + => GetTraceStringBuilder().Append(value); + + internal void WriteTrace(string? value) + => GetTraceStringBuilder().Append(value); + + private StringBuilder GetOutStringBuilder() + { + _ = _stdOutStringBuilder ?? Interlocked.CompareExchange(ref _stdOutStringBuilder, new StringBuilder(), null)!; + return _stdOutStringBuilder; + } + + private StringBuilder GetErrStringBuilder() + { + _ = _stdErrStringBuilder ?? Interlocked.CompareExchange(ref _stdErrStringBuilder, new StringBuilder(), null)!; + return _stdErrStringBuilder; + } + + private StringBuilder GetTraceStringBuilder() + { + _ = _traceStringBuilder ?? Interlocked.CompareExchange(ref _traceStringBuilder, new StringBuilder(), null)!; + return _traceStringBuilder; + } + + private StringBuilder GetTestContextMessagesStringBuilder() + { + // Prefer writing to the current test context instead of 'this'. + // This is just a hack to preserve backward compatibility. + // It's relevant for cases where users store 'TestContext' in a static field. + // Then, they write to the "wrong" test context. + // Here, we are correcting user's fault by finding out the correct TestContext that should receive the message. + TestContextImplementation @this = CurrentTestContext ?? this; + _ = @this._testContextMessageStringBuilder ?? Interlocked.CompareExchange(ref @this._testContextMessageStringBuilder, new StringBuilder(), null)!; + return @this._testContextMessageStringBuilder; + } + + internal string? GetOut() + => _stdOutStringBuilder?.ToString(); + + internal string? GetErr() + => _stdErrStringBuilder?.ToString(); + + internal string? GetTrace() + => _traceStringBuilder?.ToString(); } diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestClassInfoTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestClassInfoTests.cs index 3e0a7eaad0..a20fcdeddf 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestClassInfoTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestClassInfoTests.cs @@ -131,7 +131,7 @@ public void TestClassInfoClassCleanupMethodShouldNotInvokeWhenNoTestClassInitial _testClassInfo.ClassCleanupMethod = typeof(DummyTestClass).GetMethod("ClassCleanupMethod")!; _testClassInfo.ClassInitializeMethod = typeof(DummyTestClass).GetMethod("ClassInitializeMethod")!; - TestFailedException? ex = _testClassInfo.ExecuteClassCleanup(new TestContextImplementation(null, new StringWriter(), new Dictionary()), out _); // call cleanup without calling init + TestFailedException? ex = _testClassInfo.ExecuteClassCleanup(new TestContextImplementation(null, new StringWriter(), new Dictionary())); // call cleanup without calling init Verify(ex is null); Verify(classCleanupCallCount == 0); } @@ -145,7 +145,7 @@ public void TestClassInfoClassCleanupMethodShouldInvokeWhenTestClassInitializedI _testClassInfo.ClassInitializeMethod = typeof(DummyTestClass).GetMethod("ClassInitializeMethod")!; GetResultOrRunClassInitialize(); - TestFailedException? ex = _testClassInfo.ExecuteClassCleanup(new TestContextImplementation(null, new StringWriter(), new Dictionary()), out _); // call cleanup without calling init + TestFailedException? ex = _testClassInfo.ExecuteClassCleanup(new TestContextImplementation(null, new StringWriter(), new Dictionary())); // call cleanup without calling init Verify(ex is null); Verify(classCleanupCallCount == 1); @@ -160,7 +160,7 @@ public void TestClassInfoClassCleanupMethodShouldInvokeBaseClassCleanupMethodWhe _testClassInfo.BaseClassCleanupMethods.Add(typeof(DummyBaseTestClass).GetMethod("CleanupClassMethod")!); GetResultOrRunClassInitialize(); - TestFailedException? ex = _testClassInfo.ExecuteClassCleanup(new TestContextImplementation(null, new StringWriter(), new Dictionary()), out _); + TestFailedException? ex = _testClassInfo.ExecuteClassCleanup(new TestContextImplementation(null, new StringWriter(), new Dictionary())); Verify(ex is null); Verify(classCleanupCallCount == 1); @@ -464,7 +464,7 @@ public void RunClassCleanupShouldInvokeIfClassCleanupMethod() // Act GetResultOrRunClassInitialize(null); - TestFailedException? ex = _testClassInfo.ExecuteClassCleanup(new TestContextImplementation(null, new StringWriter(), new Dictionary()), out _); + TestFailedException? ex = _testClassInfo.ExecuteClassCleanup(new TestContextImplementation(null, new StringWriter(), new Dictionary())); // Assert Verify(ex is null); @@ -479,7 +479,7 @@ public void RunClassCleanupShouldNotInvokeIfClassCleanupIsNull() _testClassInfo.ClassCleanupMethod = null; // Act - TestFailedException? ex = _testClassInfo.ExecuteClassCleanup(new TestContextImplementation(null, new StringWriter(), new Dictionary()), out _); + TestFailedException? ex = _testClassInfo.ExecuteClassCleanup(new TestContextImplementation(null, new StringWriter(), new Dictionary())); // Assert Verify(ex is null); @@ -494,7 +494,7 @@ public void RunClassCleanupShouldReturnAssertFailureExceptionDetails() // Act GetResultOrRunClassInitialize(null); - TestFailedException? classCleanupException = _testClassInfo.ExecuteClassCleanup(new TestContextImplementation(null, new StringWriter(), new Dictionary()), out _); + TestFailedException? classCleanupException = _testClassInfo.ExecuteClassCleanup(new TestContextImplementation(null, new StringWriter(), new Dictionary())); // Assert Verify(classCleanupException is not null); @@ -516,7 +516,7 @@ public void RunClassCleanupShouldReturnAssertInconclusiveExceptionDetails() // Act GetResultOrRunClassInitialize(null); - TestFailedException? classCleanupException = _testClassInfo.ExecuteClassCleanup(new TestContextImplementation(null, new StringWriter(), new Dictionary()), out _); + TestFailedException? classCleanupException = _testClassInfo.ExecuteClassCleanup(new TestContextImplementation(null, new StringWriter(), new Dictionary())); // Assert Verify(classCleanupException is not null); @@ -537,7 +537,7 @@ public void RunClassCleanupShouldReturnExceptionDetailsOfNonAssertExceptions() // Act GetResultOrRunClassInitialize(null); - TestFailedException? classCleanupException = _testClassInfo.ExecuteClassCleanup(new TestContextImplementation(null, new StringWriter(), new Dictionary()), out _); + TestFailedException? classCleanupException = _testClassInfo.ExecuteClassCleanup(new TestContextImplementation(null, new StringWriter(), new Dictionary())); // Assert Verify(classCleanupException is not null); @@ -556,7 +556,7 @@ public void RunBaseClassCleanupWithNoDerivedClassCleanupShouldReturnExceptionDet // Act GetResultOrRunClassInitialize(null); - TestFailedException? classCleanupException = _testClassInfo.ExecuteClassCleanup(new TestContextImplementation(null, new StringWriter(), new Dictionary()), out _); + TestFailedException? classCleanupException = _testClassInfo.ExecuteClassCleanup(new TestContextImplementation(null, new StringWriter(), new Dictionary())); // Assert Verify(classCleanupException is not null); @@ -575,7 +575,7 @@ public void RunBaseClassCleanupEvenIfThereIsNoDerivedClassCleanup() _testClassInfo.BaseClassCleanupMethods.Add(baseClassCleanupMethod); // Act - TestFailedException? ex = _testClassInfo.ExecuteClassCleanup(new TestContextImplementation(null, new StringWriter(), new Dictionary()), out _); + TestFailedException? ex = _testClassInfo.ExecuteClassCleanup(new TestContextImplementation(null, new StringWriter(), new Dictionary())); // Assert Verify(ex is null); @@ -584,7 +584,7 @@ public void RunBaseClassCleanupEvenIfThereIsNoDerivedClassCleanup() // Act 2 GetResultOrRunClassInitialize(null); - ex = _testClassInfo.ExecuteClassCleanup(new TestContextImplementation(null, new StringWriter(), new Dictionary()), out _); + ex = _testClassInfo.ExecuteClassCleanup(new TestContextImplementation(null, new StringWriter(), new Dictionary())); // Assert 2 Verify(ex is null); @@ -593,7 +593,7 @@ public void RunBaseClassCleanupEvenIfThereIsNoDerivedClassCleanup() Verify(classCleanupCallCount == 1, "DummyBaseTestClass.CleanupClassMethod call count"); // Act 3 - ex = _testClassInfo.ExecuteClassCleanup(new TestContextImplementation(null, new StringWriter(), new Dictionary()), out _); + ex = _testClassInfo.ExecuteClassCleanup(new TestContextImplementation(null, new StringWriter(), new Dictionary())); // Assert 3 Verify(ex is null); @@ -610,7 +610,7 @@ public void RunClassCleanupShouldThrowTheInnerMostExceptionWhenThereAreMultipleN _testClassInfo.ClassCleanupMethod = typeof(DummyTestClass).GetMethod("ClassCleanupMethod")!; GetResultOrRunClassInitialize(null); - TestFailedException? classCleanupException = _testClassInfo.ExecuteClassCleanup(new TestContextImplementation(null, new StringWriter(), new Dictionary()), out _); + TestFailedException? classCleanupException = _testClassInfo.ExecuteClassCleanup(new TestContextImplementation(null, new StringWriter(), new Dictionary())); Verify(classCleanupException is not null); Verify(classCleanupException.Message.StartsWith("Class Cleanup method DummyTestClass.ClassCleanupMethod failed. Error Message: System.InvalidOperationException: I fail..", StringComparison.Ordinal)); diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/PlatformServiceProviderTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/PlatformServiceProviderTests.cs index 8d1f6f8884..2d4e5d21d4 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/PlatformServiceProviderTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/PlatformServiceProviderTests.cs @@ -58,13 +58,12 @@ public void GetTestContextShouldReturnAValidTestContext() { // Arrange. var testMethod = new Mock(); - var writer = new ThreadSafeStringWriter(null!, "test"); var properties = new Dictionary { { "prop", "value" } }; testMethod.Setup(tm => tm.FullClassName).Returns("A.C.M"); testMethod.Setup(tm => tm.Name).Returns("M"); // Act. - PlatformServices.Interface.ITestContext testContext = PlatformServiceProvider.Instance.GetTestContext(testMethod.Object, writer, properties, null!, default); + PlatformServices.Interface.ITestContext testContext = PlatformServiceProvider.Instance.GetTestContext(testMethod.Object, properties, null!, default); // Assert. Verify(testContext.Context.FullyQualifiedTestClassName == "A.C.M"); diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/TestContextImplementationTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/TestContextImplementationTests.cs index 4e74bc80f3..92d5588978 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/TestContextImplementationTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/TestContextImplementationTests.cs @@ -398,7 +398,7 @@ public void DisplayMessageShouldForwardToIMessageLogger() messageLoggerMock .Setup(l => l.SendMessage(It.IsAny(), It.IsAny())); - _testContextImplementation = new TestContextImplementation(_testMethod.Object, new ThreadSafeStringWriter(null!, "test"), _properties, messageLoggerMock.Object, testRunCancellationToken: null); + _testContextImplementation = new TestContextImplementation(_testMethod.Object, _properties, messageLoggerMock.Object, testRunCancellationToken: null); _testContextImplementation.DisplayMessage(MessageLevel.Informational, "InfoMessage"); _testContextImplementation.DisplayMessage(MessageLevel.Warning, "WarningMessage"); _testContextImplementation.DisplayMessage(MessageLevel.Error, "ErrorMessage"); diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/TestableImplementations/TestablePlatformServiceProvider.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/TestableImplementations/TestablePlatformServiceProvider.cs index 375a4d7fc2..73acb57073 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/TestableImplementations/TestablePlatformServiceProvider.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/TestableImplementations/TestablePlatformServiceProvider.cs @@ -69,9 +69,9 @@ public IReflectionOperations2 ReflectionOperations public bool IsGracefulStopRequested { get; set; } - public ITestContext GetTestContext(ITestMethod testMethod, StringWriter writer, IDictionary properties, IMessageLogger messageLogger, UnitTestOutcome outcome) + public ITestContext GetTestContext(ITestMethod testMethod, IDictionary properties, IMessageLogger messageLogger, UnitTestOutcome outcome) { - var testContextImpl = new TestContextImplementation(testMethod, writer, properties, messageLogger, testRunCancellationToken: null); + var testContextImpl = new TestContextImplementation(testMethod, properties, messageLogger, testRunCancellationToken: null); testContextImpl.SetOutcome(outcome); return testContextImpl; } From ca5c2e61d4f06d9867476ed289d23100d24aa843 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Mon, 16 Jun 2025 16:14:30 +0200 Subject: [PATCH 097/541] Refactor ClassCleanupManager (#5779) --- .../Execution/ClassCleanupManager.cs | 81 +++++++++++++------ .../Execution/TestClassInfo.cs | 6 +- .../Execution/UnitTestRunner.cs | 10 +-- .../Helpers/ReflectHelper.cs | 27 ------- .../Execution/ClassCleanupManagerTests.cs | 6 +- 5 files changed, 68 insertions(+), 62 deletions(-) diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Execution/ClassCleanupManager.cs b/src/Adapter/MSTestAdapter.PlatformServices/Execution/ClassCleanupManager.cs index 064a33759b..0fbfdb5bff 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Execution/ClassCleanupManager.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Execution/ClassCleanupManager.cs @@ -11,56 +11,91 @@ namespace Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution; internal sealed class ClassCleanupManager { - private readonly ClassCleanupBehavior? _lifecycleFromMsTest; - private readonly ClassCleanupBehavior _lifecycleFromAssembly; + private readonly ClassCleanupBehavior _lifecycleFromMsTestOrAssembly; private readonly ReflectHelper _reflectHelper; - private readonly ConcurrentDictionary> _remainingTestsByClass; + private readonly ConcurrentDictionary _remainingTestCountsByClass; public ClassCleanupManager( IEnumerable testsToRun, - ClassCleanupBehavior? lifecycleFromMsTest, - ClassCleanupBehavior lifecycleFromAssembly, + ClassCleanupBehavior lifecycleFromMsTestOrAssembly, ReflectHelper reflectHelper) { IEnumerable runnableTests = testsToRun.Where(t => t.Traits is null || !t.Traits.Any(t => t.Name == EngineConstants.FixturesTestTrait)); - _remainingTestsByClass = + _remainingTestCountsByClass = new(runnableTests.GroupBy(t => t.TestMethod.FullClassName) .ToDictionary( g => g.Key, - g => new List(g.Select(t => t.TestMethod.UniqueName)))); - _lifecycleFromMsTest = lifecycleFromMsTest; - _lifecycleFromAssembly = lifecycleFromAssembly; + g => g.Count())); + _lifecycleFromMsTestOrAssembly = lifecycleFromMsTestOrAssembly; _reflectHelper = reflectHelper; } - public bool ShouldRunEndOfAssemblyCleanup { get; private set; } + public bool ShouldRunEndOfAssemblyCleanup => _remainingTestCountsByClass.IsEmpty; - public void MarkTestComplete(TestMethodInfo testMethodInfo, TestMethod testMethod, out bool shouldRunEndOfClassCleanup) + public void MarkTestComplete(TestMethodInfo testMethodInfo, out bool shouldRunEndOfClassCleanup) { shouldRunEndOfClassCleanup = false; - if (!_remainingTestsByClass.TryGetValue(testMethodInfo.TestClassName, out List? testsByClass)) - { - return; - } - lock (testsByClass) + lock (_remainingTestCountsByClass) { - testsByClass.Remove(testMethod.UniqueName); - if (testsByClass.Count == 0) + if (!_remainingTestCountsByClass.TryGetValue(testMethodInfo.TestClassName, out int remainingCount)) + { + return; + } + + remainingCount--; + _remainingTestCountsByClass[testMethodInfo.TestClassName] = remainingCount; + if (remainingCount == 0) { - _remainingTestsByClass.TryRemove(testMethodInfo.TestClassName, out _); + _remainingTestCountsByClass.TryRemove(testMethodInfo.TestClassName, out _); if (testMethodInfo.Parent.HasExecutableCleanupMethod) { - ClassCleanupBehavior cleanupLifecycle = _reflectHelper.GetClassCleanupBehavior(testMethodInfo.Parent) - ?? _lifecycleFromMsTest - ?? _lifecycleFromAssembly; + ClassCleanupBehavior cleanupLifecycle = GetClassCleanupBehavior(testMethodInfo.Parent); shouldRunEndOfClassCleanup = cleanupLifecycle == ClassCleanupBehavior.EndOfClass; } } + } + } + + /// + /// Gets the class cleanup lifecycle for the class, if set. + /// + /// The class to inspect. + /// Returns if provided, otherwise null. + private ClassCleanupBehavior GetClassCleanupBehavior(TestClassInfo classInfo) + { + // TODO: not discovery related but seems expensive and unnecessary, because we do inheritance lookup, and to put the method into the stack we've already did this lookup before? + DebugEx.Assert(classInfo.HasExecutableCleanupMethod, "'GetClassCleanupBehavior' should only be called if 'HasExecutableCleanupMethod' is true"); + + bool hasEndOfAssembly = false; + if (classInfo.ClassCleanupMethod is not null) + { + ClassCleanupBehavior? cleanupBehavior = _reflectHelper.GetFirstAttributeOrDefault(classInfo.ClassCleanupMethod, inherit: true)?.CleanupBehavior; + if (cleanupBehavior == ClassCleanupBehavior.EndOfClass) + { + return ClassCleanupBehavior.EndOfClass; + } + else if (cleanupBehavior == ClassCleanupBehavior.EndOfAssembly) + { + hasEndOfAssembly = true; + } + } - ShouldRunEndOfAssemblyCleanup = _remainingTestsByClass.IsEmpty; + foreach (MethodInfo baseClassCleanupMethod in classInfo.BaseClassCleanupMethods) + { + ClassCleanupBehavior? cleanupBehavior = _reflectHelper.GetFirstAttributeOrDefault(baseClassCleanupMethod, inherit: true)?.CleanupBehavior; + if (cleanupBehavior == ClassCleanupBehavior.EndOfClass) + { + return ClassCleanupBehavior.EndOfClass; + } + else if (cleanupBehavior == ClassCleanupBehavior.EndOfAssembly) + { + hasEndOfAssembly = true; + } } + + return hasEndOfAssembly ? ClassCleanupBehavior.EndOfAssembly : _lifecycleFromMsTestOrAssembly; } internal static void ForceCleanup(TypeCache typeCache, IDictionary sourceLevelParameters, IMessageLogger logger) diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestClassInfo.cs b/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestClassInfo.cs index 3c285bf9de..8243abc9fb 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestClassInfo.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestClassInfo.cs @@ -704,16 +704,18 @@ TestResult DoRun() return testFailedException; } - internal void RunClassCleanup(ITestContext testContext, ClassCleanupManager classCleanupManager, TestMethodInfo testMethodInfo, TestMethod testMethod, TestResult[] results) + internal void RunClassCleanup(ITestContext testContext, ClassCleanupManager classCleanupManager, TestMethodInfo testMethodInfo, TestResult[] results) { DebugEx.Assert(testMethodInfo.Parent == this, "Parent of testMethodInfo should be this TestClassInfo."); - classCleanupManager.MarkTestComplete(testMethodInfo, testMethod, out bool shouldRunEndOfClassCleanup); + classCleanupManager.MarkTestComplete(testMethodInfo, out bool shouldRunEndOfClassCleanup); if (!shouldRunEndOfClassCleanup) { return; } + // TODO: Looks like 'ClassCleanupMethod is null && BaseClassCleanupMethods.Count == 0' is always false? + // shouldRunEndOfClassCleanup should be false if there are no class cleanup methods at all. if ((ClassCleanupMethod is null && BaseClassCleanupMethods.Count == 0) || IsClassCleanupExecuted) { diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Execution/UnitTestRunner.cs b/src/Adapter/MSTestAdapter.PlatformServices/Execution/UnitTestRunner.cs index ef58ac4366..bba2874103 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Execution/UnitTestRunner.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Execution/UnitTestRunner.cs @@ -26,7 +26,6 @@ internal sealed class UnitTestRunner : MarshalByRefObject private readonly ConcurrentDictionary _assemblyFixtureTests = new(); private readonly ConcurrentDictionary _classFixtureTests = new(); private readonly TypeCache _typeCache; - private readonly ReflectHelper _reflectHelper; private readonly ClassCleanupManager _classCleanupManager; /// @@ -61,8 +60,6 @@ internal UnitTestRunner(MSTestSettings settings, UnitTestElement[] testsToRun, i } PlatformServiceProvider.Instance.TestRunCancellationToken ??= new TestRunCancellationToken(); - - _reflectHelper = reflectHelper; _typeCache = new TypeCache(reflectHelper); // We can't transport the Enum across AppDomain boundaries because of backwards and forwards compatibility. @@ -75,9 +72,8 @@ internal UnitTestRunner(MSTestSettings settings, UnitTestElement[] testsToRun, i _classCleanupManager = new ClassCleanupManager( testsToRun, - MSTestSettings.CurrentSettings.ClassCleanupLifecycle, - lifecycle, - _reflectHelper); + MSTestSettings.CurrentSettings.ClassCleanupLifecycle ?? lifecycle, + reflectHelper); } #pragma warning disable CA1822 // Mark members as static @@ -217,7 +213,7 @@ internal async Task RunSingleTestAsync(TestMethod testMethod, IDic } testContextForClassCleanup = PlatformServiceProvider.Instance.GetTestContext(testMethod, properties, messageLogger, testContextForTestExecution.Context.CurrentTestOutcome); - testMethodInfo?.Parent.RunClassCleanup(testContextForClassCleanup, _classCleanupManager, testMethodInfo, testMethod, result); + testMethodInfo?.Parent.RunClassCleanup(testContextForClassCleanup, _classCleanupManager, testMethodInfo, result); if (testMethodInfo?.Parent.Parent.IsAssemblyInitializeExecuted == true) { diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Helpers/ReflectHelper.cs b/src/Adapter/MSTestAdapter.PlatformServices/Helpers/ReflectHelper.cs index 861c8ca0d1..c671899b5a 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Helpers/ReflectHelper.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Helpers/ReflectHelper.cs @@ -3,7 +3,6 @@ using System.Security; -using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution; using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; using Microsoft.VisualStudio.TestPlatform.ObjectModel; using Microsoft.VisualStudio.TestTools.UnitTesting; @@ -214,32 +213,6 @@ internal static bool IsDoNotParallelizeSet(Assembly assembly) internal virtual int? GetPriority(MemberInfo priorityAttributeProvider) => GetFirstAttributeOrDefault(priorityAttributeProvider, inherit: true)?.Priority; - /// - /// Gets the class cleanup lifecycle for the class, if set. - /// - /// The class to inspect. - /// Returns if provided, otherwise null. - internal virtual ClassCleanupBehavior? GetClassCleanupBehavior(TestClassInfo classInfo) - { - // TODO: not discovery related but seems expensive and unnecessary, because we do inheritance lookup, and to put the method into the stack we've already did this lookup before? - if (!classInfo.HasExecutableCleanupMethod) - { - return null; - } - - var cleanupBehaviors = - new HashSet( - classInfo.BaseClassCleanupMethods - .Select(x => GetFirstAttributeOrDefault(x, inherit: true)?.CleanupBehavior)) - { - classInfo.ClassCleanupMethod == null ? null : GetFirstAttributeOrDefault(classInfo.ClassCleanupMethod, inherit: true)?.CleanupBehavior, - }; - - return cleanupBehaviors.Contains(ClassCleanupBehavior.EndOfClass) - ? ClassCleanupBehavior.EndOfClass - : cleanupBehaviors.Contains(ClassCleanupBehavior.EndOfAssembly) ? ClassCleanupBehavior.EndOfAssembly : null; - } - /// /// KeyValue pairs that are provided by TestPropertyAttributes of the given test method. /// diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/ClassCleanupManagerTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/ClassCleanupManagerTests.cs index 055e52f37c..76c86755e8 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/ClassCleanupManagerTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/ClassCleanupManagerTests.cs @@ -30,7 +30,7 @@ public void AssemblyCleanupRunsAfterAllTestsFinishEvenIfWeScheduleTheSameTestMul new(testMethod) ]; - var classCleanupManager = new ClassCleanupManager(testsToRun, ClassCleanupBehavior.EndOfClass, ClassCleanupBehavior.EndOfClass, reflectHelper); + var classCleanupManager = new ClassCleanupManager(testsToRun, ClassCleanupBehavior.EndOfClass, reflectHelper); TestClassInfo testClassInfo = new(typeof(FakeTestClass), null!, true, new TestClassAttribute(), null!) { @@ -38,13 +38,13 @@ public void AssemblyCleanupRunsAfterAllTestsFinishEvenIfWeScheduleTheSameTestMul ClassCleanupMethod = classCleanupMethodInfo, }; TestMethodInfo testMethodInfo = new(methodInfo, testClassInfo, null!); - classCleanupManager.MarkTestComplete(testMethodInfo, testMethod, out bool shouldRunEndOfClassCleanup); + classCleanupManager.MarkTestComplete(testMethodInfo, out bool shouldRunEndOfClassCleanup); // The cleanup should not run here yet, we have 1 remaining test to run. Assert.IsFalse(shouldRunEndOfClassCleanup); Assert.IsFalse(classCleanupManager.ShouldRunEndOfAssemblyCleanup); - classCleanupManager.MarkTestComplete(testMethodInfo, testMethod, out shouldRunEndOfClassCleanup); + classCleanupManager.MarkTestComplete(testMethodInfo, out shouldRunEndOfClassCleanup); // The cleanup should run here. Assert.IsTrue(shouldRunEndOfClassCleanup); Assert.IsTrue(classCleanupManager.ShouldRunEndOfAssemblyCleanup); From 256bc4dd4a1a1e1358c66295f959cc266652d82c Mon Sep 17 00:00:00 2001 From: youssef-backport-bot Date: Mon, 16 Jun 2025 21:29:52 +0200 Subject: [PATCH 098/541] Rename "Capturer" to "Router" by @Copilot (#5784) Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: Youssef1313 <31348972+Youssef1313@users.noreply.github.com> --- .../{ConsoleErrorCapturer.cs => ConsoleErrorRouter.cs} | 4 ++-- .../Execution/{ConsoleOutCapturer.cs => ConsoleOutRouter.cs} | 4 ++-- .../Execution/UnitTestRunner.cs | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) rename src/Adapter/MSTestAdapter.PlatformServices/Execution/{ConsoleErrorCapturer.cs => ConsoleErrorRouter.cs} (92%) rename src/Adapter/MSTestAdapter.PlatformServices/Execution/{ConsoleOutCapturer.cs => ConsoleOutRouter.cs} (92%) diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Execution/ConsoleErrorCapturer.cs b/src/Adapter/MSTestAdapter.PlatformServices/Execution/ConsoleErrorRouter.cs similarity index 92% rename from src/Adapter/MSTestAdapter.PlatformServices/Execution/ConsoleErrorCapturer.cs rename to src/Adapter/MSTestAdapter.PlatformServices/Execution/ConsoleErrorRouter.cs index 78f73054ae..7ca55cf1f2 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Execution/ConsoleErrorCapturer.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Execution/ConsoleErrorRouter.cs @@ -5,11 +5,11 @@ namespace Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution; -internal sealed class ConsoleErrorCapturer : TextWriter +internal sealed class ConsoleErrorRouter : TextWriter { private readonly TextWriter _originalConsoleErr; - public ConsoleErrorCapturer(TextWriter originalConsoleErr) + public ConsoleErrorRouter(TextWriter originalConsoleErr) => _originalConsoleErr = originalConsoleErr; public override Encoding Encoding => Encoding.UTF8; diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Execution/ConsoleOutCapturer.cs b/src/Adapter/MSTestAdapter.PlatformServices/Execution/ConsoleOutRouter.cs similarity index 92% rename from src/Adapter/MSTestAdapter.PlatformServices/Execution/ConsoleOutCapturer.cs rename to src/Adapter/MSTestAdapter.PlatformServices/Execution/ConsoleOutRouter.cs index 612602f5ad..c4774ec629 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Execution/ConsoleOutCapturer.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Execution/ConsoleOutRouter.cs @@ -5,11 +5,11 @@ namespace Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution; -internal sealed class ConsoleOutCapturer : TextWriter +internal sealed class ConsoleOutRouter : TextWriter { private readonly TextWriter _originalConsoleOut; - public ConsoleOutCapturer(TextWriter originalConsoleOut) + public ConsoleOutRouter(TextWriter originalConsoleOut) => _originalConsoleOut = originalConsoleOut; public override Encoding Encoding => Encoding.UTF8; diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Execution/UnitTestRunner.cs b/src/Adapter/MSTestAdapter.PlatformServices/Execution/UnitTestRunner.cs index bba2874103..9adcb833e9 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Execution/UnitTestRunner.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Execution/UnitTestRunner.cs @@ -54,8 +54,8 @@ internal UnitTestRunner(MSTestSettings settings, UnitTestElement[] testsToRun, i if (MSTestSettings.CurrentSettings.CaptureDebugTraces) { - Console.SetOut(new ConsoleOutCapturer(Console.Out)); - Console.SetError(new ConsoleErrorCapturer(Console.Error)); + Console.SetOut(new ConsoleOutRouter(Console.Out)); + Console.SetError(new ConsoleErrorRouter(Console.Error)); Trace.Listeners.Add(new TextWriterTraceListener(new TraceTextWriter())); } From 166a1d1a976fdbdb0b8ab5f0d64451a9ffa097ac Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Tue, 17 Jun 2025 06:29:15 +0000 Subject: [PATCH 099/541] [main] Update dependencies from dotnet/arcade (#5794) [main] Update dependencies from dotnet/arcade --- eng/Version.Details.xml | 12 ++++++------ eng/Versions.props | 2 +- global.json | 2 +- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index e7458b37cc..6b684ee717 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -1,17 +1,17 @@ - + https://github.com/dotnet/arcade - 7a09c1144283309440a7966c664199944198c920 + d9d02d858b71562509f72ea84409853e4deffc8f - + https://github.com/dotnet/arcade - 7a09c1144283309440a7966c664199944198c920 + d9d02d858b71562509f72ea84409853e4deffc8f - + https://github.com/dotnet/arcade - 7a09c1144283309440a7966c664199944198c920 + d9d02d858b71562509f72ea84409853e4deffc8f https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage diff --git a/eng/Versions.props b/eng/Versions.props index 3616c6739a..14d91a06d2 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -7,7 +7,7 @@ preview - 10.0.0-beta.25313.2 + 10.0.0-beta.25316.2 17.15.0-preview.25313.3 diff --git a/global.json b/global.json index a7c826ecaf..c014537571 100644 --- a/global.json +++ b/global.json @@ -33,7 +33,7 @@ "rollForward": "latestFeature" }, "msbuild-sdks": { - "Microsoft.DotNet.Arcade.Sdk": "10.0.0-beta.25313.2", + "Microsoft.DotNet.Arcade.Sdk": "10.0.0-beta.25316.2", "MSBuild.Sdk.Extras": "3.0.44" } } From 7bf53d17d85a1e99a61130febeacc1581aff8a4c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Tue, 17 Jun 2025 18:30:21 +0200 Subject: [PATCH 100/541] Add `copilot-instructions.md` (#5798) --- .github/copilot-instructions.md | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 .github/copilot-instructions.md diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md new file mode 100644 index 0000000000..168d8307cb --- /dev/null +++ b/.github/copilot-instructions.md @@ -0,0 +1,31 @@ +This is a .NET based repository that contains the MSTest testing framework and Microsoft.Testing.Platform (aka MTP) testing platform. Please follow these guidelines when contributing: + +## Code Standards + +You MUST follow all code-formatting and naming conventions defined in [`.editorconfig`](./.editorconfig). + +In addition to the rules enforced by `.editorconfig`, you SHOULD: + +- Prefer file-scoped namespace declarations and single-line using directives. +- Ensure that the final return statement of a method is on its own line. +- Use pattern matching and switch expressions wherever possible. +- Use `nameof` instead of string literals when referring to member names. +- Always use `is null` or `is not null` instead of `== null` or `!= null`. +- Trust the C# null annotations and don't add null checks when the type system says a value cannot be null. +- Prefer `?.` if applicable (e.g. `scope?.Dispose()`). +- Use `ObjectDisposedException.ThrowIf` where applicable. +- Respect StyleCop.Analyzers rules. + +You MUST minimize adding public API surface area but any newly added public API MUST be declared in the related `PublicAPI.Unshipped.txt` file. + +## Localization Guidelines + +Anytime you add a new localization resource, you MUST: +- Add a corresponding entry in the localization resource file. +- Add an entry in all `*.xlf` files related to the modified `.resx` file. + +## Testing Guidelines + +- Tests for MTP and MSTest analyzers MUST use MSTest. +- Unit tests for MSTest MUST use the internal test framework defined in [`TestFramework.ForTestingMSTest`](./test/Utilities/TestFramework.ForTestingMSTest). +- All assertions must be written using FluentAssertions style of assertion. From 4df4034173c5f3cd32833d83649dbf3fa1ba9e34 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Jare=C5=A1?= Date: Wed, 18 Jun 2025 09:19:28 +0200 Subject: [PATCH 101/541] Add changelogs for 3.9.3 (#5802) Co-authored-by: Youssef Victor --- docs/Changelog-Platform.md | 19 ++++++++++++++++++- docs/Changelog.md | 24 ++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 1 deletion(-) diff --git a/docs/Changelog-Platform.md b/docs/Changelog-Platform.md index 0e8ee74760..13fda7dd6c 100644 --- a/docs/Changelog-Platform.md +++ b/docs/Changelog-Platform.md @@ -4,7 +4,24 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) -## [3.9.2] - 2025-06-10 +## [1.7.3] - 2025-06-17 + +See full log [of v3.9.2...v3.9.3](https://github.com/microsoft/testfx/compare/v3.9.2...v3.9.3) + +### Fixed + +* Simpler fix for dotnet test when using retry by @Youssef1313 in [#5731](https://github.com/microsoft/testfx/pull/5684) + +### Artifacts + +* Microsoft.Testing.Extensions.CrashDump: [1.7.3](https://www.nuget.org/packages/Microsoft.Testing.Extensions.CrashDump/1.7.3) +* Microsoft.Testing.Extensions.HangDump: [1.7.3](https://www.nuget.org/packages/Microsoft.Testing.Extensions.HangDump/1.7.3) +* Microsoft.Testing.Extensions.HotReload: [1.7.3](https://www.nuget.org/packages/Microsoft.Testing.Extensions.HotReload/1.7.3) +* Microsoft.Testing.Extensions.Retry: [1.7.3](https://www.nuget.org/packages/Microsoft.Testing.Extensions.Retry/1.7.3) +* Microsoft.Testing.Extensions.TrxReport: [1.7.3](https://www.nuget.org/packages/Microsoft.Testing.Extensions.TrxReport/1.7.3) +* Microsoft.Testing.Extensions.AzureDevOpsReport [1.0.0-alpha.25317.1](https://www.nuget.org/packages/Microsoft.Testing.Extensions.AzureDevOpsReport/1.0.0-alpha.25317.1) + +## [1.7.2] - 2025-06-10 See full log [of v3.9.1...v3.9.2](https://github.com/microsoft/testfx/compare/v3.9.1...v3.9.2) diff --git a/docs/Changelog.md b/docs/Changelog.md index 9513782ff4..350f80b081 100644 --- a/docs/Changelog.md +++ b/docs/Changelog.md @@ -4,6 +4,30 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) +## [3.9.3] - 2025-06-17 + +See full log [of v3.9.2...v3.9.3](https://github.com/microsoft/testfx/compare/v3.9.2...v3.9.3) + +### Fixed + +* No change, released to keep version aligned with Microsoft.Testing.Platform. + +### Artifacts + +* MSTest: [3.9.3](https://www.nuget.org/packages/MSTest/3.9.3) +* MSTest.TestFramework: [3.9.3](https://www.nuget.org/packages/MSTest.TestFramework/3.9.3) +* MSTest.TestAdapter: [3.9.3](https://www.nuget.org/packages/MSTest.TestAdapter/3.9.3) +* MSTest.Analyzers: [3.9.3](https://www.nuget.org/packages/MSTest.Analyzers/3.9.3) +* MSTest.Sdk: [3.9.3](https://www.nuget.org/packages/MSTest.Sdk/3.9.3) +* Microsoft.Testing.Extensions.CrashDump: [1.7.3](https://www.nuget.org/packages/Microsoft.Testing.Extensions.CrashDump/1.7.3) +* Microsoft.Testing.Extensions.HangDump: [1.7.3](https://www.nuget.org/packages/Microsoft.Testing.Extensions.HangDump/1.7.3) +* Microsoft.Testing.Extensions.HotReload: [1.7.3](https://www.nuget.org/packages/Microsoft.Testing.Extensions.HotReload/1.7.3) +* Microsoft.Testing.Extensions.Retry: [1.7.3](https://www.nuget.org/packages/Microsoft.Testing.Extensions.Retry/1.7.3) +* Microsoft.Testing.Extensions.TrxReport: [1.7.3](https://www.nuget.org/packages/Microsoft.Testing.Extensions.TrxReport/1.7.3) +* Microsoft.Testing.Extensions.AzureDevOpsReport [1.0.0-alpha.25317.1](https://www.nuget.org/packages/Microsoft.Testing.Extensions.AzureDevOpsReport/1.0.0-alpha.25317.1) +* MSTest.SourceGeneration: [1.0.0-alpha.25317.1](https://www.nuget.org/packages/MSTest.SourceGeneration/1.0.0-alpha.25317.1) +* MSTest.Engine: [1.0.0-alpha.25317.1](https://www.nuget.org/packages/MSTest.Engine/1.0.0-alpha.25317.1) + ## [3.9.2] - 2025-06-10 See full log [of v3.9.1...v3.9.2](https://github.com/microsoft/testfx/compare/v3.9.1...v3.9.2) From 56d410913515ddc1ffda983a9e03fe6454fdbc65 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Wed, 18 Jun 2025 09:28:57 +0200 Subject: [PATCH 102/541] Prefer async over blocking (#5805) --- .../Execution/TestMethodInfo.cs | 25 +- .../Execution/TestMethodInfoTests.cs | 320 +++++++++--------- 2 files changed, 183 insertions(+), 162 deletions(-) diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestMethodInfo.cs b/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestMethodInfo.cs index 9db5d41ec6..ccbcfba1d9 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestMethodInfo.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestMethodInfo.cs @@ -523,7 +523,7 @@ private async Task ExecuteInternalAsync(object?[]? arguments, Cancel // Pulling it out so extension writers can abort custom cleanups if need be. Having this in a finally block // does not allow a thread abort exception to be raised within the block but throws one after finally is executed // crashing the process. This was blocking writing an extension for Dynamic Timeout in VSO. - RunTestCleanupMethod(result, executionContext, timeoutTokenSource); + await RunTestCleanupMethodAsync(result, executionContext, timeoutTokenSource).ConfigureAwait(false); return testRunnerException != null ? throw testRunnerException : result; } @@ -671,13 +671,22 @@ private static TestFailedException HandleMethodException(Exception ex, Exception /// The execution context to run on. /// The timeout token source. [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Requirement is to handle all kinds of user exceptions and message appropriately.")] - private void RunTestCleanupMethod(TestResult result, ExecutionContext? executionContext, CancellationTokenSource? timeoutTokenSource) + private +#if NET6_0_OR_GREATER + async +#endif + Task + RunTestCleanupMethodAsync(TestResult result, ExecutionContext? executionContext, CancellationTokenSource? timeoutTokenSource) { DebugEx.Assert(result != null, "result != null"); if (_classInstance is null || !_isTestContextSet || _isTestCleanupInvoked) { +#if NET6_0_OR_GREATER return; +#else + return Task.CompletedTask; +#endif } _isTestCleanupInvoked = true; @@ -714,7 +723,7 @@ private void RunTestCleanupMethod(TestResult result, ExecutionContext? execution if (_classInstance is IAsyncDisposable classInstanceAsAsyncDisposable) { // If you implement IAsyncDisposable without calling the DisposeAsync this would result a resource leak. - classInstanceAsAsyncDisposable.DisposeAsync().AsTask().Wait(); + await classInstanceAsAsyncDisposable.DisposeAsync().ConfigureAwait(false); } #endif if (_classInstance is IDisposable classInstanceAsDisposable) @@ -731,7 +740,11 @@ private void RunTestCleanupMethod(TestResult result, ExecutionContext? execution // If testCleanup was successful, then don't do anything if (testCleanupException == null) { +#if NET6_0_OR_GREATER return; +#else + return Task.CompletedTask; +#endif } Exception realException = testCleanupException.GetRealException(); @@ -751,6 +764,10 @@ private void RunTestCleanupMethod(TestResult result, ExecutionContext? execution realException); result.TestFailureException = realException; + +#if !NET6_0_OR_GREATER + return Task.CompletedTask; +#endif } /// @@ -1114,7 +1131,7 @@ private async Task ExecuteInternalWithTimeoutAsync(object?[]? argume // We don't know when the cancellation happened so it's possible that the cleanup wasn't executed, so we need to run it here. // The method already checks if the cleanup was already executed. - RunTestCleanupMethod(timeoutResult, executionContext, null); + await RunTestCleanupMethodAsync(timeoutResult, executionContext, null).ConfigureAwait(false); return timeoutResult; // Local functions diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestMethodInfoTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestMethodInfoTests.cs index d0af85fbd1..b8c430d7a8 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestMethodInfoTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestMethodInfoTests.cs @@ -82,7 +82,7 @@ public void SetArgumentsShouldSetArgumentsNeededForCurrentTestRun() #region TestMethod invoke scenarios - public void TestMethodInfoInvokeShouldWaitForAsyncTestMethodsToComplete() + public async Task TestMethodInfoInvokeShouldWaitForAsyncTestMethodsToComplete() { bool methodCalled = false; DummyTestClass.DummyAsyncTestMethodBody = () => Task.Run(() => methodCalled = true); @@ -94,13 +94,13 @@ public void TestMethodInfoInvokeShouldWaitForAsyncTestMethodsToComplete() Executor = _testMethodAttribute, }; - TestResult result = method.Invoke(null); + TestResult result = await method.InvokeAsync(null); Verify(methodCalled); Verify(result.Outcome == UTF.UnitTestOutcome.Passed); } - public void TestMethodInfoInvokeAsyncShouldHandleThrowAssertInconclusive() + public async Task TestMethodInfoInvokeAsyncShouldHandleThrowAssertInconclusive() { DummyTestClass.DummyAsyncTestMethodBody = () => Task.Run(() => throw new AssertInconclusiveException()); MethodInfo asyncMethodInfo = typeof(DummyTestClass).GetMethod("DummyAsyncTestMethod")!; @@ -114,12 +114,12 @@ public void TestMethodInfoInvokeAsyncShouldHandleThrowAssertInconclusive() Executor = _testMethodAttribute, }; - TestResult result = method.Invoke(null); + TestResult result = await method.InvokeAsync(null); Verify(result.Outcome == UTF.UnitTestOutcome.Inconclusive); } - public void TestMethodInfoInvokeAsyncShouldHandleAssertInconclusive() + public async Task TestMethodInfoInvokeAsyncShouldHandleAssertInconclusive() { DummyTestClass.DummyAsyncTestMethodBody = () => Task.Run(() => UTF.Assert.Inconclusive()); MethodInfo asyncMethodInfo = typeof(DummyTestClass).GetMethod("DummyAsyncTestMethod")!; @@ -133,12 +133,12 @@ public void TestMethodInfoInvokeAsyncShouldHandleAssertInconclusive() Executor = _testMethodAttribute, }; - TestResult result = method.Invoke(null); + TestResult result = await method.InvokeAsync(null); Verify(result.Outcome == UTF.UnitTestOutcome.Inconclusive); } - public void TestMethodInfoInvokeShouldHandleThrowAssertInconclusive() + public async Task TestMethodInfoInvokeShouldHandleThrowAssertInconclusive() { DummyTestClass.TestMethodBody = d => throw new AssertInconclusiveException(); MethodInfo dummyMethodInfo = typeof(DummyTestClass).GetMethod("DummyTestMethod")!; @@ -152,12 +152,12 @@ public void TestMethodInfoInvokeShouldHandleThrowAssertInconclusive() Executor = _testMethodAttribute, }; - TestResult result = method.Invoke(null); + TestResult result = await method.InvokeAsync(null); Verify(result.Outcome == UTF.UnitTestOutcome.Inconclusive); } - public void TestMethodInfoInvokeShouldHandleAssertInconclusive() + public async Task TestMethodInfoInvokeShouldHandleAssertInconclusive() { DummyTestClass.TestMethodBody = d => UTF.Assert.Inconclusive(); MethodInfo dummyMethodInfo = typeof(DummyTestClass).GetMethod("DummyTestMethod")!; @@ -171,12 +171,12 @@ public void TestMethodInfoInvokeShouldHandleAssertInconclusive() Executor = _testMethodAttribute, }; - TestResult result = method.Invoke(null); + TestResult result = await method.InvokeAsync(null); Verify(result.Outcome == UTF.UnitTestOutcome.Inconclusive); } - public void TestMethodInfoInvokeShouldReportTestContextMessages() + public async Task TestMethodInfoInvokeShouldReportTestContextMessages() { DummyTestClass.TestMethodBody = o => _testContextImplementation.WriteLine("TestContext"); @@ -189,12 +189,12 @@ public void TestMethodInfoInvokeShouldReportTestContextMessages() Executor = _testMethodAttribute, }; - TestResult result = method.Invoke(null); + TestResult result = await method.InvokeAsync(null); Verify(result.TestContextMessages!.Contains("TestContext")); } - public void TestMethodInfoInvokeShouldClearTestContextMessagesAfterReporting() + public async Task TestMethodInfoInvokeShouldClearTestContextMessagesAfterReporting() { DummyTestClass.TestMethodBody = o => _testContextImplementation.WriteLine("TestContext"); @@ -207,18 +207,18 @@ public void TestMethodInfoInvokeShouldClearTestContextMessagesAfterReporting() Executor = _testMethodAttribute, }; - TestResult result = method.Invoke(null); + TestResult result = await method.InvokeAsync(null); Verify(result.TestContextMessages!.Contains("TestContext")); DummyTestClass.TestMethodBody = o => _testContextImplementation.WriteLine("SeaShore"); - result = method.Invoke(null); + result = await method.InvokeAsync(null); Verify(result.TestContextMessages!.Contains("SeaShore")); } - public void Invoke_WhenTestMethodThrowsMissingMethodException_TestOutcomeIsFailedAndExceptionIsPreserved() + public async Task Invoke_WhenTestMethodThrowsMissingMethodException_TestOutcomeIsFailedAndExceptionIsPreserved() { DummyTestClass.TestMethodBody = _ => { @@ -240,7 +240,7 @@ public void Invoke_WhenTestMethodThrowsMissingMethodException_TestOutcomeIsFaile Executor = _testMethodAttribute, }; - TestResult result = method.Invoke(null); + TestResult result = await method.InvokeAsync(null); Verify(result.Outcome == UTF.UnitTestOutcome.Failed); Verify(result.TestFailureException is TestFailedException); @@ -251,32 +251,32 @@ public void Invoke_WhenTestMethodThrowsMissingMethodException_TestOutcomeIsFaile #region TestClass constructor setup - public void TestMethodInfoInvokeShouldCreateNewInstanceOfTestClassOnEveryCall() + public async Task TestMethodInfoInvokeShouldCreateNewInstanceOfTestClassOnEveryCall() { int ctorCallCount = 0; DummyTestClass.TestConstructorMethodBody = () => ctorCallCount++; - TestResult result = _testMethodInfo.Invoke(null); - _testMethodInfo.Invoke(null); + TestResult result = await _testMethodInfo.InvokeAsync(null); + await _testMethodInfo.InvokeAsync(null); Verify(result.Outcome == UTF.UnitTestOutcome.Passed); Verify(ctorCallCount == 2); } - public void TestMethodInfoInvokeShouldMarkOutcomeFailedIfTestClassConstructorThrows() + public async Task TestMethodInfoInvokeShouldMarkOutcomeFailedIfTestClassConstructorThrows() { DummyTestClass.TestConstructorMethodBody = () => throw new NotImplementedException(); - TestResult result = _testMethodInfo.Invoke(null); + TestResult result = await _testMethodInfo.InvokeAsync(null); Verify(result.Outcome == UTF.UnitTestOutcome.Failed); } - public void TestMethodInfoInvokeShouldSetErrorMessageIfTestClassConstructorThrows() + public async Task TestMethodInfoInvokeShouldSetErrorMessageIfTestClassConstructorThrows() { DummyTestClass.TestConstructorMethodBody = () => throw new NotImplementedException("dummyExceptionMessage"); - TestResult result = _testMethodInfo.Invoke(null); + TestResult result = await _testMethodInfo.InvokeAsync(null); string errorMessage = string.Format( CultureInfo.InvariantCulture, @@ -286,7 +286,7 @@ public void TestMethodInfoInvokeShouldSetErrorMessageIfTestClassConstructorThrow Verify(errorMessage == result.TestFailureException!.Message); } - public void TestMethodInfoInvokeShouldSetErrorMessageIfTestClassConstructorThrowsWithoutInnerException() + public async Task TestMethodInfoInvokeShouldSetErrorMessageIfTestClassConstructorThrowsWithoutInnerException() { ConstructorInfo ctorInfo = typeof(DummyTestClassWithParameterizedCtor).GetConstructors().Single(); var testClass = new TestClassInfo(typeof(DummyTestClassWithParameterizedCtor), ctorInfo, true, _classAttribute, _testAssemblyInfo); @@ -296,7 +296,7 @@ public void TestMethodInfoInvokeShouldSetErrorMessageIfTestClassConstructorThrow Executor = _testMethodAttribute, }; - TestResult result = method.Invoke(null); + TestResult result = await method.InvokeAsync(null); string errorMessage = string.Format( CultureInfo.InvariantCulture, Resource.UTA_InstanceCreationError, @@ -307,11 +307,11 @@ public void TestMethodInfoInvokeShouldSetErrorMessageIfTestClassConstructorThrow Verify(errorMessage == result.TestFailureException!.Message); } - public void TestMethodInfoInvokeShouldSetStackTraceInformationIfTestClassConstructorThrows() + public async Task TestMethodInfoInvokeShouldSetStackTraceInformationIfTestClassConstructorThrows() { DummyTestClass.TestConstructorMethodBody = () => throw new NotImplementedException("dummyExceptionMessage"); - var exception = _testMethodInfo.Invoke(null).TestFailureException as TestFailedException; + var exception = (await _testMethodInfo.InvokeAsync(null)).TestFailureException as TestFailedException; Verify(exception is not null); Verify(exception.StackTraceInformation is not null); @@ -320,7 +320,7 @@ public void TestMethodInfoInvokeShouldSetStackTraceInformationIfTestClassConstru " at Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Execution.TestMethodInfoTests.<>c.b__", StringComparison.Ordinal)); } - public void TestMethodInfoInvokeShouldSetStackTraceInformationIfTestClassConstructorThrowsWithoutInnerException() + public async Task TestMethodInfoInvokeShouldSetStackTraceInformationIfTestClassConstructorThrowsWithoutInnerException() { ConstructorInfo ctorInfo = typeof(DummyTestClassWithParameterizedCtor).GetConstructors().Single(); var testClass = new TestClassInfo(typeof(DummyTestClassWithParameterizedCtor), ctorInfo, true, _classAttribute, _testAssemblyInfo); @@ -330,7 +330,7 @@ public void TestMethodInfoInvokeShouldSetStackTraceInformationIfTestClassConstru Executor = _testMethodAttribute, }; - var exception = method.Invoke(null).TestFailureException as TestFailedException; + var exception = (await method.InvokeAsync(null)).TestFailureException as TestFailedException; Verify(exception is not null); Verify(exception.StackTraceInformation is not null); @@ -339,7 +339,7 @@ public void TestMethodInfoInvokeShouldSetStackTraceInformationIfTestClassConstru " at System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)", StringComparison.Ordinal)); } - public void TestMethodInfoInvokeShouldSetResultFilesIfTestContextHasAttachments() + public async Task TestMethodInfoInvokeShouldSetResultFilesIfTestContextHasAttachments() { Mock testContext = new(); testContext.Setup(tc => tc.GetResultFiles()).Returns(["C:\\temp.txt"]); @@ -353,11 +353,11 @@ public void TestMethodInfoInvokeShouldSetResultFilesIfTestContextHasAttachments( Executor = _testMethodAttribute, }; - TestResult result = method.Invoke(null); + TestResult result = await method.InvokeAsync(null); Verify(result.ResultFiles!.Contains("C:\\temp.txt")); } - public void TestMethodInfoInvoke_WhenCtorHasOneParameterOfTypeTestContext_SetsItToTestContext() + public async Task TestMethodInfoInvoke_WhenCtorHasOneParameterOfTypeTestContext_SetsItToTestContext() { ConstructorInfo ctorInfo = typeof(DummyTestClass).GetConstructor([typeof(TestContext)])!; var testClassInfo = new TestClassInfo(typeof(DummyTestClass), ctorInfo, false, _classAttribute, _testAssemblyInfo); @@ -367,7 +367,7 @@ public void TestMethodInfoInvoke_WhenCtorHasOneParameterOfTypeTestContext_SetsIt Executor = _testMethodAttribute, }; - TestResult result = testMethodInfo.Invoke(null); + TestResult result = await testMethodInfo.InvokeAsync(null); Verify(result.Outcome == UTF.UnitTestOutcome.Passed); } @@ -376,7 +376,7 @@ public void TestMethodInfoInvoke_WhenCtorHasOneParameterOfTypeTestContext_SetsIt #region TestClass.TestContext property setup - public void TestMethodInfoInvokeShouldNotThrowIfTestContextIsNotPresent() + public async Task TestMethodInfoInvokeShouldNotThrowIfTestContextIsNotPresent() { var testClass = new TestClassInfo(typeof(DummyTestClass), _constructorInfo, true, _classAttribute, _testAssemblyInfo); var method = new TestMethodInfo(_methodInfo, testClass, _testContextImplementation) @@ -385,14 +385,16 @@ public void TestMethodInfoInvokeShouldNotThrowIfTestContextIsNotPresent() Executor = _testMethodAttribute, }; - TestResult result; - void RunMethod() => result = method.Invoke(null); +#pragma warning disable IDE0059 // Unnecessary assignment of a value - fp + TestResult result = null!; +#pragma warning restore IDE0059 // Unnecessary assignment of a value + async Task RunMethod() => result = await method.InvokeAsync(null); - RunMethod(); + await RunMethod(); Verify(result.Outcome == UTF.UnitTestOutcome.Passed); } - public void TestMethodInfoInvokeShouldNotThrowIfTestContextDoesNotHaveASetter() + public async Task TestMethodInfoInvokeShouldNotThrowIfTestContextDoesNotHaveASetter() { var testClass = new TestClassInfo(typeof(DummyTestClass), _constructorInfo, true, _classAttribute, _testAssemblyInfo); var method = new TestMethodInfo(_methodInfo, testClass, _testContextImplementation) @@ -401,37 +403,39 @@ public void TestMethodInfoInvokeShouldNotThrowIfTestContextDoesNotHaveASetter() Executor = _testMethodAttribute, }; - TestResult result; - void RunMethod() => result = method.Invoke(null); +#pragma warning disable IDE0059 // Unnecessary assignment of a value - fp + TestResult result = null!; +#pragma warning restore IDE0059 // Unnecessary assignment of a value + async Task RunMethod() => result = await method.InvokeAsync(null); - RunMethod(); + await RunMethod(); Verify(result.Outcome == UTF.UnitTestOutcome.Passed); } - public void TestMethodInfoInvokeShouldSetTestContextForTestClassInstance() + public async Task TestMethodInfoInvokeShouldSetTestContextForTestClassInstance() { TestContext? testContext = null; DummyTestClass.TestContextSetterBody = context => testContext = context as TestContext; - _testMethodInfo.Invoke(null); + await _testMethodInfo.InvokeAsync(null); Verify(_testContextImplementation.Equals(testContext)); } - public void TestMethodInfoInvokeShouldMarkOutcomeFailedIfSetTestContextThrows() + public async Task TestMethodInfoInvokeShouldMarkOutcomeFailedIfSetTestContextThrows() { DummyTestClass.TestContextSetterBody = value => throw new NotImplementedException(); - TestResult result = _testMethodInfo.Invoke(null); + TestResult result = await _testMethodInfo.InvokeAsync(null); Verify(result.Outcome == UTF.UnitTestOutcome.Failed); } - public void TestMethodInfoInvokeShouldSetErrorMessageIfSetTestContextThrows() + public async Task TestMethodInfoInvokeShouldSetErrorMessageIfSetTestContextThrows() { DummyTestClass.TestContextSetterBody = value => throw new NotImplementedException("dummyExceptionMessage"); - var exception = _testMethodInfo.Invoke(null).TestFailureException as TestFailedException; + var exception = (await _testMethodInfo.InvokeAsync(null)).TestFailureException as TestFailedException; string errorMessage = string.Format( CultureInfo.InvariantCulture, @@ -442,11 +446,11 @@ public void TestMethodInfoInvokeShouldSetErrorMessageIfSetTestContextThrows() Verify(errorMessage == exception?.Message); } - public void TestMethodInfoInvokeShouldSetStackTraceInformationIfSetTestContextThrows() + public async Task TestMethodInfoInvokeShouldSetStackTraceInformationIfSetTestContextThrows() { DummyTestClass.TestConstructorMethodBody = () => throw new NotImplementedException("dummyExceptionMessage"); - var exception = _testMethodInfo.Invoke(null).TestFailureException as TestFailedException; + var exception = (await _testMethodInfo.InvokeAsync(null)).TestFailureException as TestFailedException; Verify(exception is not null); Verify(exception.StackTraceInformation is not null); @@ -455,7 +459,7 @@ public void TestMethodInfoInvokeShouldSetStackTraceInformationIfSetTestContextTh " at Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Execution.TestMethodInfoTests.<>c.b__", StringComparison.Ordinal)); } - public void TestMethodInfoInvoke_WhenCtorHasOneParameterOfTypeTestContextAndTestContextProperty_InitializeBothTestContexts() + public async Task TestMethodInfoInvoke_WhenCtorHasOneParameterOfTypeTestContextAndTestContextProperty_InitializeBothTestContexts() { ConstructorInfo ctorInfo = typeof(DummyTestClass).GetConstructor([typeof(TestContext)])!; var testClassInfo = new TestClassInfo(typeof(DummyTestClass), ctorInfo, false, _classAttribute, _testAssemblyInfo); @@ -467,7 +471,7 @@ public void TestMethodInfoInvoke_WhenCtorHasOneParameterOfTypeTestContextAndTest TestContext? testContext = null; DummyTestClass.TestContextSetterBody = context => testContext = context as TestContext; - TestResult result = testMethodInfo.Invoke(null); + TestResult result = await testMethodInfo.InvokeAsync(null); Verify(result.Outcome == UTF.UnitTestOutcome.Passed); Verify(_testContextImplementation.Equals(testContext)); @@ -477,31 +481,31 @@ public void TestMethodInfoInvoke_WhenCtorHasOneParameterOfTypeTestContextAndTest #region TestInitialize method setup - public void TestMethodInfoInvokeShouldCallTestInitialize() + public async Task TestMethodInfoInvokeShouldCallTestInitialize() { bool testInitializeCalled = false; DummyTestClass.TestInitializeMethodBody = classInstance => testInitializeCalled = true; _testClassInfo.TestInitializeMethod = typeof(DummyTestClass).GetMethod("DummyTestInitializeMethod")!; - TestResult result = _testMethodInfo.Invoke(null); + TestResult result = await _testMethodInfo.InvokeAsync(null); Verify(testInitializeCalled); Verify(result.Outcome == UTF.UnitTestOutcome.Passed); } - public void TestMethodInfoInvokeShouldCallAsyncTestInitializeAndWaitForCompletion() + public async Task TestMethodInfoInvokeShouldCallAsyncTestInitializeAndWaitForCompletion() { bool testInitializeCalled = false; DummyTestClass.DummyAsyncTestMethodBody = () => Task.Run(() => testInitializeCalled = true); _testClassInfo.TestInitializeMethod = typeof(DummyTestClass).GetMethod("DummyAsyncTestMethod")!; - TestResult result = _testMethodInfo.Invoke(null); + TestResult result = await _testMethodInfo.InvokeAsync(null); Verify(testInitializeCalled); Verify(result.Outcome == UTF.UnitTestOutcome.Passed); } - public void TestMethodInfoInvokeShouldCallTestInitializeOfAllBaseClasses() + public async Task TestMethodInfoInvokeShouldCallTestInitializeOfAllBaseClasses() { var callOrder = new List(); DummyTestClassBase.BaseTestClassMethodBody = classInstance => callOrder.Add("baseTestInitializeCalled2"); @@ -511,7 +515,7 @@ public void TestMethodInfoInvokeShouldCallTestInitializeOfAllBaseClasses() _testClassInfo.BaseTestInitializeMethodsQueue.Enqueue(typeof(DummyTestClassBase).GetMethod("DummyBaseTestClassMethod")!); _testClassInfo.BaseTestInitializeMethodsQueue.Enqueue(typeof(DummyTestClass).GetMethod("DummyAsyncTestMethod")!); - TestResult result = _testMethodInfo.Invoke(null); + TestResult result = await _testMethodInfo.InvokeAsync(null); var expectedCallOrder = new List { @@ -523,25 +527,25 @@ public void TestMethodInfoInvokeShouldCallTestInitializeOfAllBaseClasses() Verify(expectedCallOrder.SequenceEqual(callOrder)); } - public void TestMethodInfoInvokeShouldNotThrowIfTestInitializeIsNull() + public async Task TestMethodInfoInvokeShouldNotThrowIfTestInitializeIsNull() { _testClassInfo.TestInitializeMethod = null; - TestResult result = _testMethodInfo.Invoke(null); + TestResult result = await _testMethodInfo.InvokeAsync(null); Verify(result.Outcome == UTF.UnitTestOutcome.Passed); } - public void TestMethodInfoInvokeShouldNotThrowIfTestInitializeForBaseClassIsNull() + public async Task TestMethodInfoInvokeShouldNotThrowIfTestInitializeForBaseClassIsNull() { _testClassInfo.BaseTestInitializeMethodsQueue.Enqueue(null!); - TestResult result = _testMethodInfo.Invoke(null); + TestResult result = await _testMethodInfo.InvokeAsync(null); Verify(result.Outcome == UTF.UnitTestOutcome.Passed); } - public void TestMethodInfoInvokeWhenTestThrowsReturnsExpectedResult() + public async Task TestMethodInfoInvokeWhenTestThrowsReturnsExpectedResult() { // Arrange. DummyTestClass.TestInitializeMethodBody = classInstance => throw new ArgumentException("Some exception message", new InvalidOperationException("Inner exception message")); @@ -561,7 +565,7 @@ public void TestMethodInfoInvokeWhenTestThrowsReturnsExpectedResult() }; // Act. - TestResult result = testMethodInfo.Invoke(null); + TestResult result = await testMethodInfo.InvokeAsync(null); // Assert. Verify(result.Outcome == UTF.UnitTestOutcome.Failed); @@ -578,7 +582,7 @@ public void TestMethodInfoInvokeWhenTestThrowsReturnsExpectedResult() #endif } - public void TestInitialize_WhenTestReturnsTaskFromException_DisplayProperException() + public async Task TestInitialize_WhenTestReturnsTaskFromException_DisplayProperException() { // Arrange. DummyTestClass.TestInitializeMethodBodyAsync = async classInstance => await Task.FromException(new Exception("Outer", new InvalidOperationException("Inner"))); @@ -591,7 +595,7 @@ public void TestInitialize_WhenTestReturnsTaskFromException_DisplayProperExcepti }; // Act. - TestResult result = testMethodInfo.Invoke(null); + TestResult result = await testMethodInfo.InvokeAsync(null); // Assert. Verify(result.Outcome == UTF.UnitTestOutcome.Failed); @@ -612,7 +616,7 @@ public void TestInitialize_WhenTestReturnsTaskFromException_DisplayProperExcepti Verify(exception.StackTraceInformation is not null); } - public void TestMethodInfoInvokeWhenTestThrowsAssertFailReturnsExpectedResult() + public async Task TestMethodInfoInvokeWhenTestThrowsAssertFailReturnsExpectedResult() { // Arrange. DummyTestClass.TestInitializeMethodBody = classInstance => UTF.Assert.Fail("dummyFailMessage"); @@ -632,7 +636,7 @@ public void TestMethodInfoInvokeWhenTestThrowsAssertFailReturnsExpectedResult() }; // Act. - TestResult result = testMethodInfo.Invoke(null); + TestResult result = await testMethodInfo.InvokeAsync(null); // Assert. Verify(result.Outcome == UTF.UnitTestOutcome.Failed); @@ -648,7 +652,7 @@ public void TestMethodInfoInvokeWhenTestThrowsAssertFailReturnsExpectedResult() #endif } - public void TestMethodInfoInvokeWhenTestThrowsAssertInconclusiveReturnsExpectedResult() + public async Task TestMethodInfoInvokeWhenTestThrowsAssertInconclusiveReturnsExpectedResult() { // Arrange. DummyTestClass.TestInitializeMethodBody = classInstance => UTF.Assert.Inconclusive("dummyFailMessage"); @@ -668,7 +672,7 @@ public void TestMethodInfoInvokeWhenTestThrowsAssertInconclusiveReturnsExpectedR }; // Act. - TestResult result = testMethodInfo.Invoke(null); + TestResult result = await testMethodInfo.InvokeAsync(null); // Assert. Verify(result.Outcome == UTF.UnitTestOutcome.Inconclusive); @@ -688,7 +692,7 @@ public void TestMethodInfoInvokeWhenTestThrowsAssertInconclusiveReturnsExpectedR #region TestCleanup method setup - public void TestCleanup_WhenTestReturnsTaskFromException_DisplayProperException() + public async Task TestCleanup_WhenTestReturnsTaskFromException_DisplayProperException() { // Arrange. DummyTestClass.TestCleanupMethodBodyAsync = async classInstance => await Task.FromException(new Exception("Outer", new InvalidOperationException("Inner"))); @@ -700,7 +704,7 @@ public void TestCleanup_WhenTestReturnsTaskFromException_DisplayProperException( }; // Act. - TestResult result = testMethodInfo.Invoke(null); + TestResult result = await testMethodInfo.InvokeAsync(null); // Assert. Verify(result.Outcome == UTF.UnitTestOutcome.Failed); @@ -725,40 +729,40 @@ public void TestCleanup_WhenTestReturnsTaskFromException_DisplayProperException( } } - public void TestMethodInfoInvokeShouldCallTestCleanup() + public async Task TestMethodInfoInvokeShouldCallTestCleanup() { bool cleanupMethodCalled = false; DummyTestClass.DummyAsyncTestMethodBody = () => Task.Run(() => cleanupMethodCalled = true); _testClassInfo.TestCleanupMethod = typeof(DummyTestClass).GetMethod("DummyAsyncTestMethod")!; - TestResult result = _testMethodInfo.Invoke(null); + TestResult result = await _testMethodInfo.InvokeAsync(null); Verify(result.Outcome == UTF.UnitTestOutcome.Passed); Verify(cleanupMethodCalled); } - public void TestMethodInfoInvokeShouldCallAsyncTestCleanup() + public async Task TestMethodInfoInvokeShouldCallAsyncTestCleanup() { bool cleanupMethodCalled = false; DummyTestClass.TestCleanupMethodBody = classInstance => cleanupMethodCalled = true; _testClassInfo.TestCleanupMethod = typeof(DummyTestClass).GetMethod("DummyTestCleanupMethod")!; - TestResult result = _testMethodInfo.Invoke(null); + TestResult result = await _testMethodInfo.InvokeAsync(null); Verify(result.Outcome == UTF.UnitTestOutcome.Passed); Verify(cleanupMethodCalled); } - public void TestMethodInfoInvokeShouldNotThrowIfTestCleanupMethodIsNull() + public async Task TestMethodInfoInvokeShouldNotThrowIfTestCleanupMethodIsNull() { _testClassInfo.TestCleanupMethod = null; - TestResult result = _testMethodInfo.Invoke(null); + TestResult result = await _testMethodInfo.InvokeAsync(null); Verify(result.Outcome == UTF.UnitTestOutcome.Passed); } - public void TestMethodInfoInvokeShouldCallTestCleanupForBaseTestClasses() + public async Task TestMethodInfoInvokeShouldCallTestCleanupForBaseTestClasses() { var callOrder = new List(); DummyTestClassBase.BaseTestClassMethodBody = classInstance => callOrder.Add("baseTestCleanupCalled" + callOrder.Count); @@ -767,7 +771,7 @@ public void TestMethodInfoInvokeShouldCallTestCleanupForBaseTestClasses() _testClassInfo.BaseTestCleanupMethodsQueue.Enqueue(typeof(DummyTestClassBase).GetMethod("DummyBaseTestClassMethod")!); _testClassInfo.BaseTestCleanupMethodsQueue.Enqueue(typeof(DummyTestClassBase).GetMethod("DummyBaseTestClassMethod")!); - TestResult result = _testMethodInfo.Invoke(null); + TestResult result = await _testMethodInfo.InvokeAsync(null); var expectedCallOrder = new List { @@ -779,7 +783,7 @@ public void TestMethodInfoInvokeShouldCallTestCleanupForBaseTestClasses() Verify(expectedCallOrder.SequenceEqual(callOrder)); } - public void TestMethodInfoInvokeShouldCallTestCleanupForBaseTestClassesAlways() + public async Task TestMethodInfoInvokeShouldCallTestCleanupForBaseTestClassesAlways() { var callOrder = new List(); DummyTestClassBase.BaseTestClassMethodBody = classInstance => callOrder.Add("baseTestCleanupCalled" + callOrder.Count); @@ -788,8 +792,8 @@ public void TestMethodInfoInvokeShouldCallTestCleanupForBaseTestClassesAlways() _testClassInfo.BaseTestCleanupMethodsQueue.Enqueue(typeof(DummyTestClassBase).GetMethod("DummyBaseTestClassMethod")!); _testClassInfo.BaseTestCleanupMethodsQueue.Enqueue(typeof(DummyTestClassBase).GetMethod("DummyBaseTestClassMethod")!); - _testMethodInfo.Invoke(null); - TestResult result = _testMethodInfo.Invoke(null); + await _testMethodInfo.InvokeAsync(null); + TestResult result = await _testMethodInfo.InvokeAsync(null); var expectedCallOrder = new List { @@ -805,7 +809,7 @@ public void TestMethodInfoInvokeShouldCallTestCleanupForBaseTestClassesAlways() Verify(expectedCallOrder.SequenceEqual(callOrder)); } - public void TestMethodInfoInvokeWhenTestCleanupThrowsReturnsExpectedResult() + public async Task TestMethodInfoInvokeWhenTestCleanupThrowsReturnsExpectedResult() { DummyTestClass.TestCleanupMethodBody = classInstance => throw new ArgumentException("Some exception message", new InvalidOperationException("Inner exception message")); _testClassInfo.TestCleanupMethod = typeof(DummyTestClass).GetMethod("DummyTestCleanupMethod")!; @@ -817,7 +821,7 @@ public void TestMethodInfoInvokeWhenTestCleanupThrowsReturnsExpectedResult() _testClassInfo.TestCleanupMethod!.Name, "System.ArgumentException: Some exception message ---> System.InvalidOperationException: Inner exception message"); - TestResult result = _testMethodInfo.Invoke(null); + TestResult result = await _testMethodInfo.InvokeAsync(null); Verify(result.Outcome == UTF.UnitTestOutcome.Failed); @@ -834,7 +838,7 @@ public void TestMethodInfoInvokeWhenTestCleanupThrowsReturnsExpectedResult() #endif } - public void TestMethodInfoInvokeWhenTestCleanupThrowsAssertInconclusiveReturnsExpectedResult() + public async Task TestMethodInfoInvokeWhenTestCleanupThrowsAssertInconclusiveReturnsExpectedResult() { DummyTestClass.TestCleanupMethodBody = classInstance => UTF.Assert.Inconclusive("Test inconclusive"); _testClassInfo.TestCleanupMethod = typeof(DummyTestClass).GetMethod("DummyTestCleanupMethod")!; @@ -846,7 +850,7 @@ public void TestMethodInfoInvokeWhenTestCleanupThrowsAssertInconclusiveReturnsEx _testClassInfo.TestCleanupMethod.Name, "Microsoft.VisualStudio.TestTools.UnitTesting.AssertInconclusiveException: Assert.Inconclusive failed. Test inconclusive"); - TestResult result = _testMethodInfo.Invoke(null); + TestResult result = await _testMethodInfo.InvokeAsync(null); Verify(result.Outcome == UTF.UnitTestOutcome.Inconclusive); @@ -861,7 +865,7 @@ public void TestMethodInfoInvokeWhenTestCleanupThrowsAssertInconclusiveReturnsEx #endif } - public void TestMethodInfoInvokeWhenTestCleanupThrowsAssertFailedReturnsExpectedResult() + public async Task TestMethodInfoInvokeWhenTestCleanupThrowsAssertFailedReturnsExpectedResult() { DummyTestClass.TestCleanupMethodBody = classInstance => UTF.Assert.Fail("Test failed"); _testClassInfo.TestCleanupMethod = typeof(DummyTestClass).GetMethod("DummyTestCleanupMethod")!; @@ -873,7 +877,7 @@ public void TestMethodInfoInvokeWhenTestCleanupThrowsAssertFailedReturnsExpected _testClassInfo.TestCleanupMethod!.Name, "Microsoft.VisualStudio.TestTools.UnitTesting.AssertFailedException: Assert.Fail failed. Test failed"); - TestResult result = _testMethodInfo.Invoke(null); + TestResult result = await _testMethodInfo.InvokeAsync(null); Verify(result.Outcome == UTF.UnitTestOutcome.Failed); @@ -888,13 +892,13 @@ public void TestMethodInfoInvokeWhenTestCleanupThrowsAssertFailedReturnsExpected #endif } - public void TestMethodInfoInvokeShouldAppendErrorMessagesIfBothTestMethodAndTestCleanupThrows() + public async Task TestMethodInfoInvokeShouldAppendErrorMessagesIfBothTestMethodAndTestCleanupThrows() { DummyTestClass.TestCleanupMethodBody = classInstance => throw new NotImplementedException("dummyErrorMessage"); DummyTestClass.TestMethodBody = classInstance => throw new NotImplementedException("dummyMethodError"); _testClassInfo.TestCleanupMethod = typeof(DummyTestClass).GetMethod("DummyTestCleanupMethod")!; - TestResult result = _testMethodInfo.Invoke(null); + TestResult result = await _testMethodInfo.InvokeAsync(null); var exception = result.TestFailureException as AggregateException; string errorMessage = string.Format( CultureInfo.CurrentCulture, @@ -915,13 +919,13 @@ public void TestMethodInfoInvokeShouldAppendErrorMessagesIfBothTestMethodAndTest Verify(exception.InnerExceptions[1].Message.Contains(cleanupError)); } - public void TestMethodInfoInvokeShouldAppendStackTraceInformationIfBothTestMethodAndTestCleanupThrows() + public async Task TestMethodInfoInvokeShouldAppendStackTraceInformationIfBothTestMethodAndTestCleanupThrows() { DummyTestClass.TestCleanupMethodBody = classInstance => throw new NotImplementedException(); DummyTestClass.TestMethodBody = classInstance => throw new NotImplementedException("dummyMethodError"); _testClassInfo.TestCleanupMethod = typeof(DummyTestClass).GetMethod("DummyTestCleanupMethod")!; - TestResult result = _testMethodInfo.Invoke(null); + TestResult result = await _testMethodInfo.InvokeAsync(null); var exception = result.TestFailureException as AggregateException; Verify(result.Outcome == UTF.UnitTestOutcome.Failed); @@ -932,12 +936,12 @@ public void TestMethodInfoInvokeShouldAppendStackTraceInformationIfBothTestMetho #endif } - public void TestMethodInfoInvokeShouldSetOutcomeAsInconclusiveIfTestCleanupIsInconclusive() + public async Task TestMethodInfoInvokeShouldSetOutcomeAsInconclusiveIfTestCleanupIsInconclusive() { DummyTestClass.TestCleanupMethodBody = classInstance => throw new AssertInconclusiveException(); _testClassInfo.TestCleanupMethod = typeof(DummyTestClass).GetMethod("DummyTestCleanupMethod")!; - TestResult result = _testMethodInfo.Invoke(null); + TestResult result = await _testMethodInfo.InvokeAsync(null); var exception = result.TestFailureException as TestFailedException; Verify(result.Outcome == UTF.UnitTestOutcome.Inconclusive); @@ -945,18 +949,18 @@ public void TestMethodInfoInvokeShouldSetOutcomeAsInconclusiveIfTestCleanupIsInc Verify(exception.Message.Contains("Microsoft.VisualStudio.TestTools.UnitTesting.AssertInconclusiveException")); } - public void TestMethodInfoInvokeShouldSetMoreImportantOutcomeIfTestCleanupIsInconclusiveButTestMethodFails() + public async Task TestMethodInfoInvokeShouldSetMoreImportantOutcomeIfTestCleanupIsInconclusiveButTestMethodFails() { DummyTestClass.TestCleanupMethodBody = classInstance => throw new AssertInconclusiveException(); DummyTestClass.TestMethodBody = classInstance => Fail(); _testClassInfo.TestCleanupMethod = typeof(DummyTestClass).GetMethod("DummyTestCleanupMethod")!; - TestResult result = _testMethodInfo.Invoke(null); + TestResult result = await _testMethodInfo.InvokeAsync(null); Verify(result.Outcome == UTF.UnitTestOutcome.Failed); } - public void TestMethodInfoInvokeShouldCallDisposeForDisposableTestClass() + public async Task TestMethodInfoInvokeShouldCallDisposeForDisposableTestClass() { bool disposeCalled = false; DummyTestClassWithDisposable.DisposeMethodBody = () => disposeCalled = true; @@ -968,13 +972,13 @@ public void TestMethodInfoInvokeShouldCallDisposeForDisposableTestClass() Executor = _testMethodAttribute, }; - method.Invoke(null); + await method.InvokeAsync(null); Verify(disposeCalled); } #if NET6_0_OR_GREATER - public void TestMethodInfoInvoke_WhenTestClassIsAsyncDisposable_ShouldDisposeAsync() + public async Task TestMethodInfoInvoke_WhenTestClassIsAsyncDisposable_ShouldDisposeAsync() { // Arrange bool asyncDisposeCalled = false; @@ -988,13 +992,13 @@ public void TestMethodInfoInvoke_WhenTestClassIsAsyncDisposable_ShouldDisposeAsy }; // Act - method.Invoke(null); + await method.InvokeAsync(null); // Assert Verify(asyncDisposeCalled); } - public void TestMethodInfoInvoke_WhenTestClassIsDisposableAndAsyncDisposable_ShouldCallAsyncDisposeThenDispose() + public async Task TestMethodInfoInvoke_WhenTestClassIsDisposableAndAsyncDisposable_ShouldCallAsyncDisposeThenDispose() { // Arrange int order = 0; @@ -1013,7 +1017,7 @@ public void TestMethodInfoInvoke_WhenTestClassIsDisposableAndAsyncDisposable_Sho }; // Act - method.Invoke(null); + await method.InvokeAsync(null); // Assert Verify(disposeCalledOrder == 2); @@ -1021,7 +1025,7 @@ public void TestMethodInfoInvoke_WhenTestClassIsDisposableAndAsyncDisposable_Sho } #endif - public void TestMethodInfoInvokeShouldCallDisposeForDisposableTestClassIfTestCleanupThrows() + public async Task TestMethodInfoInvokeShouldCallDisposeForDisposableTestClassIfTestCleanupThrows() { bool disposeCalled = false; DummyTestClassWithDisposable.DisposeMethodBody = () => disposeCalled = true; @@ -1037,25 +1041,25 @@ public void TestMethodInfoInvokeShouldCallDisposeForDisposableTestClassIfTestCle Executor = _testMethodAttribute, }; - method.Invoke(null); + await method.InvokeAsync(null); Verify(disposeCalled); } - public void TestMethodInfoInvokeShouldCallTestCleanupEvenIfTestMethodThrows() + public async Task TestMethodInfoInvokeShouldCallTestCleanupEvenIfTestMethodThrows() { bool testCleanupMethodCalled = false; DummyTestClass.TestMethodBody = classInstance => throw new NotImplementedException(); DummyTestClass.TestCleanupMethodBody = classInstance => testCleanupMethodCalled = true; _testClassInfo.TestCleanupMethod = typeof(DummyTestClass).GetMethod("DummyTestCleanupMethod")!; - TestResult result = _testMethodInfo.Invoke(null); + TestResult result = await _testMethodInfo.InvokeAsync(null); Verify(testCleanupMethodCalled); Verify(result.Outcome == UTF.UnitTestOutcome.Failed); } - public void TestMethodInfoInvokeShouldCallTestCleanupEvenIfTestInitializeMethodThrows() + public async Task TestMethodInfoInvokeShouldCallTestCleanupEvenIfTestInitializeMethodThrows() { bool testCleanupMethodCalled = false; DummyTestClass.TestInitializeMethodBody = classInstance => throw new NotImplementedException(); @@ -1063,13 +1067,13 @@ public void TestMethodInfoInvokeShouldCallTestCleanupEvenIfTestInitializeMethodT _testClassInfo.TestInitializeMethod = typeof(DummyTestClass).GetMethod("DummyTestInitializeMethod")!; _testClassInfo.TestCleanupMethod = typeof(DummyTestClass).GetMethod("DummyTestCleanupMethod")!; - TestResult result = _testMethodInfo.Invoke(null); + TestResult result = await _testMethodInfo.InvokeAsync(null); Verify(testCleanupMethodCalled); Verify(result.Outcome == UTF.UnitTestOutcome.Failed); } - public void TestMethodInfoInvokeShouldCallTestCleanupIfTestClassInstanceIsNotNull() + public async Task TestMethodInfoInvokeShouldCallTestCleanupIfTestClassInstanceIsNotNull() { bool testCleanupMethodCalled = false; @@ -1077,25 +1081,25 @@ public void TestMethodInfoInvokeShouldCallTestCleanupIfTestClassInstanceIsNotNul DummyTestClass.TestConstructorMethodBody = () => throw new NotImplementedException(); DummyTestClass.TestCleanupMethodBody = classInstance => testCleanupMethodCalled = true; - TestResult result = _testMethodInfo.Invoke(null); + TestResult result = await _testMethodInfo.InvokeAsync(null); Verify(!testCleanupMethodCalled); Verify(result.Outcome == UTF.UnitTestOutcome.Failed); } - public void TestMethodInfoInvokeShouldNotCallTestCleanupIfClassSetContextThrows() + public async Task TestMethodInfoInvokeShouldNotCallTestCleanupIfClassSetContextThrows() { bool testCleanupCalled = false; DummyTestClass.TestCleanupMethodBody = classInstance => testCleanupCalled = true; DummyTestClass.TestContextSetterBody = o => throw new NotImplementedException(); _testClassInfo.TestCleanupMethod = typeof(DummyTestClass).GetMethod("DummyTestCleanupMethod")!; - _testMethodInfo.Invoke(null); + await _testMethodInfo.InvokeAsync(null); Verify(!testCleanupCalled); } - public void TestMethodInfoInvokeShouldSetResultAsPassedIfExpectedExceptionIsThrown() + public async Task TestMethodInfoInvokeShouldSetResultAsPassedIfExpectedExceptionIsThrown() { DummyTestClass.TestMethodBody = o => throw new DivideByZeroException(); var testMethodInfo = new TestMethodInfo(_methodInfo, _testClassInfo, _testContextImplementation) @@ -1105,12 +1109,12 @@ public void TestMethodInfoInvokeShouldSetResultAsPassedIfExpectedExceptionIsThro ExpectedException = _expectedException, }; - TestResult result = testMethodInfo.Invoke(null); + TestResult result = await testMethodInfo.InvokeAsync(null); Verify(result.Outcome == UTF.UnitTestOutcome.Passed); } - public void TestMethodInfoInvokeShouldSetResultAsFailedIfExceptionDifferentFromExpectedExceptionIsThrown() + public async Task TestMethodInfoInvokeShouldSetResultAsFailedIfExceptionDifferentFromExpectedExceptionIsThrown() { DummyTestClass.TestMethodBody = o => throw new IndexOutOfRangeException(); var testMethodInfo = new TestMethodInfo(_methodInfo, _testClassInfo, _testContextImplementation) @@ -1120,7 +1124,7 @@ public void TestMethodInfoInvokeShouldSetResultAsFailedIfExceptionDifferentFromE ExpectedException = _expectedException, }; - TestResult result = testMethodInfo.Invoke(null); + TestResult result = await testMethodInfo.InvokeAsync(null); Verify(result.Outcome == UTF.UnitTestOutcome.Failed); string message = "Test method threw exception System.IndexOutOfRangeException, but exception System.DivideByZeroException was expected. " + @@ -1128,7 +1132,7 @@ public void TestMethodInfoInvokeShouldSetResultAsFailedIfExceptionDifferentFromE Verify(message == result.TestFailureException!.Message); } - public void TestMethodInfoInvokeShouldSetResultAsFailedWhenExceptionIsExpectedButIsNotThrown() + public async Task TestMethodInfoInvokeShouldSetResultAsFailedWhenExceptionIsExpectedButIsNotThrown() { DummyTestClass.TestMethodBody = o => { }; var testMethodInfo = new TestMethodInfo(_methodInfo, _testClassInfo, _testContextImplementation) @@ -1137,13 +1141,13 @@ public void TestMethodInfoInvokeShouldSetResultAsFailedWhenExceptionIsExpectedBu Executor = _testMethodAttribute, ExpectedException = _expectedException, }; - TestResult result = testMethodInfo.Invoke(null); + TestResult result = await testMethodInfo.InvokeAsync(null); Verify(result.Outcome == UTF.UnitTestOutcome.Failed); string message = "Test method did not throw expected exception System.DivideByZeroException."; Verify(result.TestFailureException!.Message.Contains(message)); } - public void TestMethodInfoInvokeShouldSetResultAsInconclusiveWhenExceptionIsAssertInconclusiveException() + public async Task TestMethodInfoInvokeShouldSetResultAsInconclusiveWhenExceptionIsAssertInconclusiveException() { DummyTestClass.TestMethodBody = o => throw new AssertInconclusiveException(); var testMethodInfo = new TestMethodInfo(_methodInfo, _testClassInfo, _testContextImplementation) @@ -1152,13 +1156,13 @@ public void TestMethodInfoInvokeShouldSetResultAsInconclusiveWhenExceptionIsAsse Executor = _testMethodAttribute, ExpectedException = _expectedException, }; - TestResult result = testMethodInfo.Invoke(null); + TestResult result = await testMethodInfo.InvokeAsync(null); Verify(result.Outcome == UTF.UnitTestOutcome.Inconclusive); string message = "Exception of type 'Microsoft.VisualStudio.TestTools.UnitTesting.AssertInconclusiveException' was thrown."; Verify(message == result.TestFailureException!.Message); } - public void TestMethodInfoInvokeShouldSetTestOutcomeBeforeTestCleanup() + public async Task TestMethodInfoInvokeShouldSetTestOutcomeBeforeTestCleanup() { UTF.UnitTestOutcome testOutcome = UTF.UnitTestOutcome.Unknown; DummyTestClass.TestMethodBody = o => throw new AssertInconclusiveException(); @@ -1177,12 +1181,12 @@ public void TestMethodInfoInvokeShouldSetTestOutcomeBeforeTestCleanup() ExpectedException = _expectedException, }; - TestResult result = testMethodInfo.Invoke(null); + TestResult result = await testMethodInfo.InvokeAsync(null); Verify(testOutcome == UTF.UnitTestOutcome.Inconclusive); } - public void HandleMethodExceptionShouldInvokeVerifyOfCustomExpectedException() + public async Task HandleMethodExceptionShouldInvokeVerifyOfCustomExpectedException() { CustomExpectedExceptionAttribute customExpectedException = new(typeof(DivideByZeroException), "Attempted to divide by zero"); var method = new TestMethodInfo( @@ -1196,12 +1200,12 @@ public void HandleMethodExceptionShouldInvokeVerifyOfCustomExpectedException() }; DummyTestClass.TestMethodBody = o => throw new DivideByZeroException(); - TestResult result = method.Invoke(null); + TestResult result = await method.InvokeAsync(null); Verify(customExpectedException.IsVerifyInvoked); Verify(result.Outcome == UTF.UnitTestOutcome.Passed); } - public void HandleMethodExceptionShouldSetOutcomeAsFailedIfVerifyOfExpectedExceptionThrows() + public async Task HandleMethodExceptionShouldSetOutcomeAsFailedIfVerifyOfExpectedExceptionThrows() { CustomExpectedExceptionAttribute customExpectedException = new(typeof(DivideByZeroException), "Custom Exception"); var method = new TestMethodInfo( @@ -1215,12 +1219,12 @@ public void HandleMethodExceptionShouldSetOutcomeAsFailedIfVerifyOfExpectedExcep }; DummyTestClass.TestMethodBody = o => throw new DivideByZeroException(); - TestResult result = method.Invoke(null); + TestResult result = await method.InvokeAsync(null); Verify(result.TestFailureException!.Message == "The exception message doesn't contain the string defined in the exception attribute"); Verify(result.Outcome == UTF.UnitTestOutcome.Failed); } - public void HandleMethodExceptionShouldSetOutcomeAsInconclusiveIfVerifyOfExpectedExceptionThrowsAssertInconclusiveException() + public async Task HandleMethodExceptionShouldSetOutcomeAsInconclusiveIfVerifyOfExpectedExceptionThrowsAssertInconclusiveException() { CustomExpectedExceptionAttribute customExpectedException = new(typeof(DivideByZeroException), "Custom Exception"); var method = new TestMethodInfo( @@ -1234,13 +1238,13 @@ public void HandleMethodExceptionShouldSetOutcomeAsInconclusiveIfVerifyOfExpecte }; DummyTestClass.TestMethodBody = o => throw new AssertInconclusiveException(); - TestResult result = method.Invoke(null); + TestResult result = await method.InvokeAsync(null); string message = "Exception of type 'Microsoft.VisualStudio.TestTools.UnitTesting.AssertInconclusiveException' was thrown."; Verify(result.TestFailureException!.Message == message); Verify(result.Outcome == UTF.UnitTestOutcome.Inconclusive); } - public void HandleMethodExceptionShouldInvokeVerifyOfDerivedCustomExpectedException() + public async Task HandleMethodExceptionShouldInvokeVerifyOfDerivedCustomExpectedException() { DerivedCustomExpectedExceptionAttribute derivedCustomExpectedException = new(typeof(DivideByZeroException), "Attempted to divide by zero"); var method = new TestMethodInfo( @@ -1254,12 +1258,12 @@ public void HandleMethodExceptionShouldInvokeVerifyOfDerivedCustomExpectedExcept }; DummyTestClass.TestMethodBody = o => throw new DivideByZeroException(); - TestResult result = method.Invoke(null); + TestResult result = await method.InvokeAsync(null); Verify(derivedCustomExpectedException.IsVerifyInvoked); Verify(result.Outcome == UTF.UnitTestOutcome.Passed); } - public void VerifyShouldNotThrowIfThrownExceptionCanBeAssignedToExpectedException() + public async Task VerifyShouldNotThrowIfThrownExceptionCanBeAssignedToExpectedException() { ExpectedExceptionAttribute expectedException = new(typeof(Exception)) { @@ -1276,11 +1280,11 @@ public void VerifyShouldNotThrowIfThrownExceptionCanBeAssignedToExpectedExceptio }; DummyTestClass.TestMethodBody = o => throw new DivideByZeroException(); - TestResult result = method.Invoke(null); + TestResult result = await method.InvokeAsync(null); Verify(result.Outcome == UTF.UnitTestOutcome.Passed); } - public void VerifyShouldThrowExceptionIfThrownExceptionCannotBeAssignedToExpectedException() + public async Task VerifyShouldThrowExceptionIfThrownExceptionCannotBeAssignedToExpectedException() { ExpectedExceptionAttribute expectedException = new(typeof(DivideByZeroException), "Custom Exception") { @@ -1297,14 +1301,14 @@ public void VerifyShouldThrowExceptionIfThrownExceptionCannotBeAssignedToExpecte }; DummyTestClass.TestMethodBody = o => throw new ArgumentNullException(); - TestResult result = method.Invoke(null); + TestResult result = await method.InvokeAsync(null); string message = "Test method threw exception System.ArgumentNullException, but exception System.DivideByZeroException" + " or a type derived from it was expected. Exception message: System.ArgumentNullException: Value cannot be null."; Verify(result.TestFailureException!.Message == message); Verify(result.Outcome == UTF.UnitTestOutcome.Failed); } - public void VerifyShouldRethrowExceptionIfThrownExceptionIsAssertFailedException() + public async Task VerifyShouldRethrowExceptionIfThrownExceptionIsAssertFailedException() { ExpectedExceptionAttribute expectedException = new(typeof(DivideByZeroException)) { @@ -1321,13 +1325,13 @@ public void VerifyShouldRethrowExceptionIfThrownExceptionIsAssertFailedException }; DummyTestClass.TestMethodBody = o => throw new AssertFailedException(); - TestResult result = method.Invoke(null); + TestResult result = await method.InvokeAsync(null); string message = "Exception of type 'Microsoft.VisualStudio.TestTools.UnitTesting.AssertFailedException' was thrown."; Verify(result.TestFailureException!.Message == message); Verify(result.Outcome == UTF.UnitTestOutcome.Failed); } - public void VerifyShouldRethrowExceptionIfThrownExceptionIsAssertInconclusiveException() + public async Task VerifyShouldRethrowExceptionIfThrownExceptionIsAssertInconclusiveException() { ExpectedExceptionAttribute expectedException = new(typeof(DivideByZeroException)) { @@ -1344,13 +1348,13 @@ public void VerifyShouldRethrowExceptionIfThrownExceptionIsAssertInconclusiveExc }; DummyTestClass.TestMethodBody = o => throw new AssertInconclusiveException(); - TestResult result = method.Invoke(null); + TestResult result = await method.InvokeAsync(null); string message = "Exception of type 'Microsoft.VisualStudio.TestTools.UnitTesting.AssertInconclusiveException' was thrown."; Verify(result.TestFailureException!.Message == message); Verify(result.Outcome == UTF.UnitTestOutcome.Inconclusive); } - public void VerifyShouldThrowIfThrownExceptionIsNotSameAsExpectedException() + public async Task VerifyShouldThrowIfThrownExceptionIsNotSameAsExpectedException() { ExpectedExceptionAttribute expectedException = new(typeof(Exception)); var method = new TestMethodInfo( @@ -1364,14 +1368,14 @@ public void VerifyShouldThrowIfThrownExceptionIsNotSameAsExpectedException() }; DummyTestClass.TestMethodBody = o => throw new DivideByZeroException(); - TestResult result = method.Invoke(null); + TestResult result = await method.InvokeAsync(null); string message = "Test method threw exception System.DivideByZeroException, but exception System.Exception was expected. " + "Exception message: System.DivideByZeroException: Attempted to divide by zero."; Verify(result.TestFailureException!.Message == message); Verify(result.Outcome == UTF.UnitTestOutcome.Failed); } - public void VerifyShouldRethrowIfThrownExceptionIsAssertExceptionWhichIsNotSameAsExpectedException() + public async Task VerifyShouldRethrowIfThrownExceptionIsAssertExceptionWhichIsNotSameAsExpectedException() { ExpectedExceptionAttribute expectedException = new(typeof(Exception)); var method = new TestMethodInfo( @@ -1385,7 +1389,7 @@ public void VerifyShouldRethrowIfThrownExceptionIsAssertExceptionWhichIsNotSameA }; DummyTestClass.TestMethodBody = o => throw new AssertInconclusiveException(); - TestResult result = method.Invoke(null); + TestResult result = await method.InvokeAsync(null); string message = "Exception of type 'Microsoft.VisualStudio.TestTools.UnitTesting.AssertInconclusiveException' was thrown."; Verify(result.TestFailureException!.Message == message); Verify(result.Outcome == UTF.UnitTestOutcome.Inconclusive); @@ -1472,7 +1476,7 @@ public void ResolveExpectedExceptionHelperShouldReturnNullIfExpectedExceptionAtt #region TestMethod invoke setup order - public void TestMethodInfoInvokeShouldInitializeClassInstanceTestInitializeAndTestCleanupInOrder() + public async Task TestMethodInfoInvokeShouldInitializeClassInstanceTestInitializeAndTestCleanupInOrder() { var callOrder = new List(); _testClassInfo.TestInitializeMethod = typeof(DummyTestClass).GetMethod("DummyTestInitializeMethod")!; @@ -1484,7 +1488,7 @@ public void TestMethodInfoInvokeShouldInitializeClassInstanceTestInitializeAndTe DummyTestClass.TestMethodBody = classInstance => callOrder.Add("testMethodInfo"); DummyTestClass.TestCleanupMethodBody = classInstance => callOrder.Add("testCleanup"); - TestResult result = _testMethodInfo.Invoke(null); + TestResult result = await _testMethodInfo.InvokeAsync(null); var expectedCallOrder = new List { @@ -1502,11 +1506,11 @@ public void TestMethodInfoInvokeShouldInitializeClassInstanceTestInitializeAndTe #region TestMethod timeout scenarios - public void TestMethodInfoInvokeShouldReturnTestFailureOnTimeout() + public async Task TestMethodInfoInvokeShouldReturnTestFailureOnTimeout() { var testablePlatformServiceProvider = new TestablePlatformServiceProvider(); - RunWithTestablePlatformService(testablePlatformServiceProvider, () => + await RunWithTestablePlatformService(testablePlatformServiceProvider, async () => { testablePlatformServiceProvider.MockThreadOperations.CallBase = true; @@ -1520,14 +1524,14 @@ public void TestMethodInfoInvokeShouldReturnTestFailureOnTimeout() Executor = _testMethodAttribute, }; - TestResult result = method.Invoke(null); + TestResult result = await method.InvokeAsync(null); Verify(result.Outcome == UTF.UnitTestOutcome.Timeout); Verify(result.TestFailureException!.Message.Equals("Test 'DummyTestMethod' timed out after 1ms", StringComparison.Ordinal)); }); } - public void TestMethodInfoInvokeShouldReturnTestPassedOnCompletionWithinTimeout() + public async Task TestMethodInfoInvokeShouldReturnTestPassedOnCompletionWithinTimeout() { DummyTestClass.TestMethodBody = o => { /* do nothing */ }; var method = new TestMethodInfo(_methodInfo, _testClassInfo, _testContextImplementation) @@ -1535,14 +1539,14 @@ public void TestMethodInfoInvokeShouldReturnTestPassedOnCompletionWithinTimeout( TimeoutInfo = TimeoutInfo.FromTimeout(3600 * 1000), Executor = _testMethodAttribute, }; - TestResult result = method.Invoke(null); + TestResult result = await method.InvokeAsync(null); Verify(result.Outcome == UTF.UnitTestOutcome.Passed); } - public void TestMethodInfoInvokeShouldCancelTokenSourceOnTimeout() + public async Task TestMethodInfoInvokeShouldCancelTokenSourceOnTimeout() { var testablePlatformServiceProvider = new TestablePlatformServiceProvider(); - RunWithTestablePlatformService(testablePlatformServiceProvider, () => + await RunWithTestablePlatformService(testablePlatformServiceProvider, async () => { testablePlatformServiceProvider.MockThreadOperations.CallBase = true; PlatformServiceProvider.Instance = testablePlatformServiceProvider; @@ -1555,7 +1559,7 @@ public void TestMethodInfoInvokeShouldCancelTokenSourceOnTimeout() TimeoutInfo = TimeoutInfo.FromTimeout(1), Executor = _testMethodAttribute, }; - TestResult result = method.Invoke(null); + TestResult result = await method.InvokeAsync(null); Verify(result.Outcome == UTF.UnitTestOutcome.Timeout); Verify(result.TestFailureException!.Message.Equals("Test 'DummyTestMethod' timed out after 1ms", StringComparison.Ordinal)); @@ -1563,10 +1567,10 @@ public void TestMethodInfoInvokeShouldCancelTokenSourceOnTimeout() }); } - public void TestMethodInfoInvokeShouldFailOnTokenSourceCancellation() + public async Task TestMethodInfoInvokeShouldFailOnTokenSourceCancellation() { var testablePlatformServiceProvider = new TestablePlatformServiceProvider(); - RunWithTestablePlatformService(testablePlatformServiceProvider, () => + await RunWithTestablePlatformService(testablePlatformServiceProvider, async () => { testablePlatformServiceProvider.MockThreadOperations.CallBase = true; PlatformServiceProvider.Instance = testablePlatformServiceProvider; @@ -1589,7 +1593,7 @@ public void TestMethodInfoInvokeShouldFailOnTokenSourceCancellation() TimeoutInfo = TimeoutInfo.FromTimeout(100000), Executor = _testMethodAttribute, }; - TestResult result = method.Invoke(null); + TestResult result = await method.InvokeAsync(null); Verify(result.Outcome == UTF.UnitTestOutcome.Timeout); Verify(result.TestFailureException!.Message.Equals("Test 'DummyTestMethod' was canceled", StringComparison.Ordinal)); @@ -1731,7 +1735,7 @@ public void ResolveArgumentsShouldReturnPopulatedParamsWithAllProvided() #region helper methods - private static void RunWithTestablePlatformService(TestablePlatformServiceProvider testablePlatformServiceProvider, Action action) + private static async Task RunWithTestablePlatformService(TestablePlatformServiceProvider testablePlatformServiceProvider, Func action) { try { @@ -1740,7 +1744,7 @@ private static void RunWithTestablePlatformService(TestablePlatformServiceProvid Returns(true). Callback((Action a, int timeout, CancellationToken token) => a.Invoke()); - action.Invoke(); + await action(); } finally { From 1b90ee5c629e3c121a29b08d6ef0301abb7dafcf Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Wed, 18 Jun 2025 09:31:43 +0200 Subject: [PATCH 103/541] Migrate from sln to slnx (#5808) --- MSTest.slnf | 2 +- Microsoft.Testing.Platform.slnf | 2 +- NonWindowsTests.slnf | 2 +- TestFx.sln | 636 -------------------------------- TestFx.slnx | 135 +++++++ eng/Build.props | 2 +- eng/build.ps1 | 2 +- 7 files changed, 140 insertions(+), 641 deletions(-) delete mode 100644 TestFx.sln create mode 100644 TestFx.slnx diff --git a/MSTest.slnf b/MSTest.slnf index 80979689ba..af9d38802e 100644 --- a/MSTest.slnf +++ b/MSTest.slnf @@ -1,6 +1,6 @@ { "solution": { - "path": "TestFx.sln", + "path": "TestFx.slnx", "projects": [ "samples\\FxExtensibility\\FxExtensibility.csproj", "samples\\Playground\\Playground.csproj", diff --git a/Microsoft.Testing.Platform.slnf b/Microsoft.Testing.Platform.slnf index 1595904e3a..d32084741e 100644 --- a/Microsoft.Testing.Platform.slnf +++ b/Microsoft.Testing.Platform.slnf @@ -1,6 +1,6 @@ { "solution": { - "path": "TestFx.sln", + "path": "TestFx.slnx", "projects": [ "samples\\Playground\\Playground.csproj", "src\\Platform\\Microsoft.Testing.Extensions.CrashDump\\Microsoft.Testing.Extensions.CrashDump.csproj", diff --git a/NonWindowsTests.slnf b/NonWindowsTests.slnf index e965c3ed7e..a0168d54d3 100644 --- a/NonWindowsTests.slnf +++ b/NonWindowsTests.slnf @@ -1,6 +1,6 @@ { "solution": { - "path": "TestFx.sln", + "path": "TestFx.slnx", "projects": [ "test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests.csproj", "test/IntegrationTests/MSTest.Acceptance.IntegrationTests/MSTest.Acceptance.IntegrationTests.csproj", diff --git a/TestFx.sln b/TestFx.sln deleted file mode 100644 index 55c2fa31d9..0000000000 --- a/TestFx.sln +++ /dev/null @@ -1,636 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 17 -VisualStudioVersion = 17.1.31910.343 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{FF8B1B72-55A1-4FFE-809E-7B79323ED8D0}" - ProjectSection(SolutionItems) = preProject - src\.editorconfig = src\.editorconfig - src\Directory.Build.props = src\Directory.Build.props - EndProjectSection -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "2 - Adapter", "2 - Adapter", "{24088844-2107-4DB2-8F3F-CBCA94FC4B28}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MSTest.TestAdapter", "src\Adapter\MSTest.TestAdapter\MSTest.TestAdapter.csproj", "{98BA6D2C-1F3D-4636-8E1D-D4932B7A253D}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MSTestAdapter.PlatformServices", "src\Adapter\MSTestAdapter.PlatformServices\MSTestAdapter.PlatformServices.csproj", "{5D153CAA-80C2-4551-9549-6C406FCEEFB1}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "3 - TestFramework", "3 - TestFramework", "{E48AC786-E150-4F41-9A16-32F02E4493D8}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TestFramework", "src\TestFramework\TestFramework\TestFramework.csproj", "{7252D9E3-267D-442C-96BC-C73AEF3241D6}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "test", "test", "{A9596292-7E67-4566-9096-143DDAA4E8D8}" - ProjectSection(SolutionItems) = preProject - test\.editorconfig = test\.editorconfig - test\Directory.Build.props = test\Directory.Build.props - test\Directory.Build.targets = test\Directory.Build.targets - EndProjectSection -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TestFramework.Extensions", "src\TestFramework\TestFramework.Extensions\TestFramework.Extensions.csproj", "{DF131865-84EE-4540-8112-E88ACEBDEA09}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "TestUtilities", "TestUtilities", "{33D3029D-E653-4929-BB31-C714178C4BEE}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{929A3EDE-893B-4801-82BA-01FD947291CB}" - ProjectSection(SolutionItems) = preProject - .editorconfig = .editorconfig - .gitignore = .gitignore - Directory.Build.props = Directory.Build.props - Directory.Build.targets = Directory.Build.targets - Directory.Packages.props = Directory.Packages.props - global.json = global.json - Nuget.config = Nuget.config - EndProjectSection -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "5 - Package", "5 - Package", "{E374A3A6-C364-4890-B315-D60F5C682B6E}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MSTestAdapter.UnitTests", "test\UnitTests\MSTestAdapter.UnitTests\MSTestAdapter.UnitTests.csproj", "{1CEB5743-70BF-475E-91BC-0AEBD63835B7}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MSTestAdapter.PlatformServices.UnitTests", "test\UnitTests\MSTestAdapter.PlatformServices.UnitTests\MSTestAdapter.PlatformServices.UnitTests.csproj", "{599833DC-EC5A-40CA-B5CF-DEF719548EEF}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TestFramework.UnitTests", "test\UnitTests\TestFramework.UnitTests\TestFramework.UnitTests.csproj", "{0A4A76DD-FEE1-4D04-926B-38E1A24A7ED2}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "eng", "eng", "{FE0DF239-0D81-46CA-9277-3342009E83F9}" - ProjectSection(SolutionItems) = preProject - eng\AfterSolutionBuild.targets = eng\AfterSolutionBuild.targets - eng\Analyzers.props = eng\Analyzers.props - eng\Build.props = eng\Build.props - eng\coverage.config = eng\coverage.config - eng\install-windows-sdk.ps1 = eng\install-windows-sdk.ps1 - eng\verify-nupkgs.ps1 = eng\verify-nupkgs.ps1 - eng\Version.Details.xml = eng\Version.Details.xml - eng\Versions.props = eng\Versions.props - eng\write-release-notes.ps1 = eng\write-release-notes.ps1 - EndProjectSection -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "samples", "samples", "{92F8E9A2-903E-4025-99BC-7DC478D5466D}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "FxExtensibility", "samples\FxExtensibility\FxExtensibility.csproj", "{A82770C0-1FF5-43C7-8790-471D5E4F8D6E}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "UnitTests", "UnitTests", "{BB874DF1-44FE-415A-B634-A6B829107890}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "IntegrationTests", "IntegrationTests", "{FF69998C-C661-4EF0-804B-845675B3602E}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "TestAssets", "TestAssets", "{C9F82701-0E0F-4E61-B05B-AE387E7631F6}" - ProjectSection(SolutionItems) = preProject - test\IntegrationTests\TestAssets\Directory.Build.targets = test\IntegrationTests\TestAssets\Directory.Build.targets - EndProjectSection -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MSTest.IntegrationTests", "test\IntegrationTests\MSTest.IntegrationTests\MSTest.IntegrationTests.csproj", "{6359B7FD-5C63-487A-9467-99323C17AA10}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MSTest.VstestConsoleWrapper.IntegrationTests", "test\IntegrationTests\MSTest.VstestConsoleWrapper.IntegrationTests\MSTest.VstestConsoleWrapper.IntegrationTests.csproj", "{FE2A0AE6-835E-4603-9CE9-C8E25D14C4A0}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "PlatformServices.Desktop.IntegrationTests", "test\IntegrationTests\PlatformServices.Desktop.IntegrationTests\PlatformServices.Desktop.IntegrationTests.csproj", "{93D3B3B5-6850-461C-9A08-A78D2921F86F}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DataRowTestProject", "test\IntegrationTests\TestAssets\DataRowTestProject\DataRowTestProject.csproj", "{2833FDA8-ECA0-439C-97E4-620AB9EC45AA}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DataSourceTestProject", "test\IntegrationTests\TestAssets\DataSourceTestProject\DataSourceTestProject.csproj", "{60116E14-11A3-47DF-B730-8A28ABD9B7AF}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DeploymentTestProject.Never", "test\IntegrationTests\TestAssets\DeploymentTestProject.Never\DeploymentTestProject.Never.csproj", "{CA6A4A5A-CFDE-440B-898E-FF6FBA405540}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DeploymentTestProject.PreserveNewest", "test\IntegrationTests\TestAssets\DeploymentTestProject.PreserveNewest\DeploymentTestProject.PreserveNewest.csproj", "{9C81E66B-5DFE-4130-982E-64EF8D7F6A60}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DesktopTestProjectx64Debug", "test\IntegrationTests\TestAssets\DesktopTestProjectx64Debug\DesktopTestProjectx64Debug.csproj", "{BE21907B-A4C1-41D7-A2EF-5C73A33090A0}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DesktopTestProjectx64Release", "test\IntegrationTests\TestAssets\DesktopTestProjectx64Release\DesktopTestProjectx64Release.csproj", "{F6AD3FE2-3C82-44E8-A694-C4C447EB2F10}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DesktopTestProjectx86Debug", "test\IntegrationTests\TestAssets\DesktopTestProjectx86Debug\DesktopTestProjectx86Debug.csproj", "{41DD903C-CA88-4761-831B-978EC793508F}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DesktopTestProjectx86Release", "test\IntegrationTests\TestAssets\DesktopTestProjectx86Release\DesktopTestProjectx86Release.csproj", "{93B2E07F-A41D-42DC-AF5D-47048761DFA9}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DiscoverInternalsProject", "test\IntegrationTests\TestAssets\DiscoverInternalsProject\DiscoverInternalsProject.csproj", "{48A0431B-9EFA-46DA-9AA9-D6552A7DA109}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DoNotParallelizeTestProject", "test\IntegrationTests\TestAssets\DoNotParallelizeTestProject\DoNotParallelizeTestProject.csproj", "{A2C5B6FE-A5B4-4419-A1FC-3F977DE24D2B}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DynamicDataTestProject", "test\IntegrationTests\TestAssets\DynamicDataTestProject\DynamicDataTestProject.csproj", "{D11D17B0-74DB-43B2-B5AC-7F86E0ACEFCD}" -EndProject -Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "FSharpTestProject", "test\IntegrationTests\TestAssets\FSharpTestProject\FSharpTestProject.fsproj", "{C37026D9-6525-4128-A4A1-9E3E2C195737}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "FxExtensibilityTestProject", "test\IntegrationTests\TestAssets\FxExtensibilityTestProject\FxExtensibilityTestProject.csproj", "{2F4DFABA-B031-4164-A178-25F0753C9971}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "HierarchyProject", "test\IntegrationTests\TestAssets\HierarchyProject\HierarchyProject.csproj", "{77CDBBF7-895B-44E1-8C86-05D81286BC3A}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "LibProjectReferencedByDataSourceTest", "test\IntegrationTests\TestAssets\LibProjectReferencedByDataSourceTest\LibProjectReferencedByDataSourceTest.csproj", "{DBE6C4AF-4D79-44BB-94B5-C57FEC8B4E69}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OutputTestProject", "test\IntegrationTests\TestAssets\OutputTestProject\OutputTestProject.csproj", "{2607F3CC-3AFE-4968-B028-4F502B9F6A28}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ParallelClassesTestProject", "test\IntegrationTests\TestAssets\ParallelTestClass\ParallelClassesTestProject.csproj", "{60AE14C4-C54C-419D-AFF8-D7E49901D42B}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SampleFrameworkExtensions", "test\IntegrationTests\TestAssets\SampleFrameworkExtensions\SampleFrameworkExtensions.csproj", "{17025461-E4B9-4D4A-AD74-AF1C355E61BC}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SampleProjectForAssemblyResolution", "test\IntegrationTests\TestAssets\SampleProjectForAssemblyResolution\SampleProjectForAssemblyResolution.csproj", "{279E5DCA-3CD6-4C66-9D5F-475FDE96F3B8}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SuiteLifeCycleTestProject", "test\IntegrationTests\TestAssets\SuiteLifeCycleTestProject\SuiteLifeCycleTestProject.csproj", "{CAA66039-6747-4516-ADBA-F3D4C349E9EA}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TestIdProject.DefaultStrategy", "test\IntegrationTests\TestAssets\TestIdProject.DefaultStrategy\TestIdProject.DefaultStrategy.csproj", "{8BCC6F49-CF4F-40DA-8EFC-D232C7984ABC}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TestIdProject.DisplayNameStrategy", "test\IntegrationTests\TestAssets\TestIdProject.DisplayNameStrategy\TestIdProject.DisplayNameStrategy.csproj", "{34714FAD-A226-432E-9083-6BCF79D71873}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TestIdProject.FullyQualifiedStrategy", "test\IntegrationTests\TestAssets\TestIdProject.FullyQualifiedTestStrategy\TestIdProject.FullyQualifiedStrategy.csproj", "{27CFE39F-3F60-47E0-9281-12CB13C7B91E}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TestIdProject.LegacyStrategy", "test\IntegrationTests\TestAssets\TestIdProject.LegacyStrategy\TestIdProject.LegacyStrategy.csproj", "{DBA74878-65BF-4EE7-925A-67AF395F7D11}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TestProjectForDiscovery", "test\IntegrationTests\TestAssets\TestProject\TestProjectForDiscovery.csproj", "{B3419F35-A31F-4CAA-A606-034D5DB669A2}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TimeoutTestProject", "test\IntegrationTests\TestAssets\TimeoutTestProject\TimeoutTestProject.csproj", "{4A184EC4-8BAB-498F-ABC6-300C70BF8240}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ParallelMethodsTestProject", "test\IntegrationTests\TestAssets\ParallelTestMethods\ParallelMethodsTestProject.csproj", "{CA5D66E2-7244-4E72-AFB6-58A826A30B74}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Automation.CLI", "test\Utilities\Automation.CLI\Automation.CLI.csproj", "{35E90097-976B-4FF5-B55F-2F51561D7A33}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TestFramework.ForTestingMSTest", "test\Utilities\TestFramework.ForTestingMSTest\TestFramework.ForTestingMSTest.csproj", "{17CE999F-F3D1-48B4-A18F-8BA050C3A4AD}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MSTest", "src\Package\MSTest\MSTest.csproj", "{ED8534D1-3136-4915-8071-5547E8D84DC3}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "TestingPlatformRunner", "TestingPlatformRunner", "{A9F9C49E-3CDA-4207-AA53-CC80AF1798FE}" - ProjectSection(SolutionItems) = preProject - eng\TestingPlatformRunner\TestingPlatform.Runner.targets = eng\TestingPlatformRunner\TestingPlatform.Runner.targets - eng\TestingPlatformRunner\TestingPlatformRunner.targets = eng\TestingPlatformRunner\TestingPlatformRunner.targets - EndProjectSection -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "1 - Platform and Extensions", "1 - Platform and Extensions", "{6AEE1440-FDF0-4729-8196-B24D0E333550}" - ProjectSection(SolutionItems) = preProject - src\Platform\Directory.Build.props = src\Platform\Directory.Build.props - EndProjectSection -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Testing.Platform", "src\Platform\Microsoft.Testing.Platform\Microsoft.Testing.Platform.csproj", "{48FAB979-8DA5-492E-8B3F-5DBBE82F659A}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Testing.Platform.UnitTests", "test\UnitTests\Microsoft.Testing.Platform.UnitTests\Microsoft.Testing.Platform.UnitTests.csproj", "{0F1BB08E-BB6C-43E0-A7DF-1D6A03DA5DC7}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "4 - Analyzers", "4 - Analyzers", "{E7F15C9C-3928-47AD-8462-64FD29FFCA54}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MSTest.Analyzers", "src\Analyzers\MSTest.Analyzers\MSTest.Analyzers.csproj", "{72C4FA49-E553-4B39-825A-8C4EA6CE93E2}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MSTest.Analyzers.CodeFixes", "src\Analyzers\MSTest.Analyzers.CodeFixes\MSTest.Analyzers.CodeFixes.csproj", "{462B0201-1C26-4951-97C9-722C2A58EF8C}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MSTest.Analyzers.Package", "src\Analyzers\MSTest.Analyzers.Package\MSTest.Analyzers.Package.csproj", "{DC068986-7549-4B75-8EFC-A9958FD5CF88}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MSTest.Analyzers.UnitTests", "test\UnitTests\MSTest.Analyzers.UnitTests\MSTest.Analyzers.UnitTests.csproj", "{1FF35C23-C128-4C95-B3F8-67B1B4C51E4D}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MSTest.Sdk", "src\Package\MSTest.Sdk\MSTest.Sdk.csproj", "{10930CFD-EDF9-4486-B0A3-49230B5A6798}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ClsTestProject", "test\IntegrationTests\TestAssets\ClsTestProject\ClsTestProject.csproj", "{100CF515-8291-45FF-9FFD-2A9064FECC72}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Testing.TestInfrastructure", "test\Utilities\Microsoft.Testing.TestInfrastructure\Microsoft.Testing.TestInfrastructure.csproj", "{9DCE14DA-3DFB-48DE-A3CC-A02C3465973C}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Testing.Platform.Acceptance.IntegrationTests", "test\IntegrationTests\Microsoft.Testing.Platform.Acceptance.IntegrationTests\Microsoft.Testing.Platform.Acceptance.IntegrationTests.csproj", "{3CF3861E-EB1B-4FA6-9355-372A9816DF6B}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Performance", "Performance", "{CB0CC552-2017-40C0-934A-C8A3B00EF650}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MSTest.Performance.Runner", "test\Performance\MSTest.Performance.Runner\MSTest.Performance.Runner.csproj", "{7E9D98E7-733C-4D6B-A5AC-087D588A40ED}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Playground", "samples\Playground\Playground.csproj", "{8A41B37E-0732-4F28-B214-A44233B447FE}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MSTest.Acceptance.IntegrationTests", "test\IntegrationTests\MSTest.Acceptance.IntegrationTests\MSTest.Acceptance.IntegrationTests.csproj", "{BCB42780-C559-40B6-8C4A-85EBC464AAA8}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "FixturesTestProject", "test\IntegrationTests\TestAssets\FixturesTestProject\FixturesTestProject.csproj", "{A7D0995D-0516-4975-ABBD-EB93E1B79292}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Testing.Extensions.TrxReport.Abstractions", "src\Platform\Microsoft.Testing.Extensions.TrxReport.Abstractions\Microsoft.Testing.Extensions.TrxReport.Abstractions.csproj", "{9164E0BA-0846-4839-BA0F-C25F5FBE056C}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Testing.Extensions.TrxReport", "src\Platform\Microsoft.Testing.Extensions.TrxReport\Microsoft.Testing.Extensions.TrxReport.csproj", "{29B9F157-3733-471E-A11E-A5FF3C6D1348}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Testing.Extensions.VSTestBridge", "src\Platform\Microsoft.Testing.Extensions.VSTestBridge\Microsoft.Testing.Extensions.VSTestBridge.csproj", "{60763BAA-C963-4858-8DA1-78DB92428865}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Testing.Platform.MSBuild", "src\Platform\Microsoft.Testing.Platform.MSBuild\Microsoft.Testing.Platform.MSBuild.csproj", "{1B30B69C-A4E3-4660-9CA8-140D0C34B4A5}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Testing.Extensions.Telemetry", "src\Platform\Microsoft.Testing.Extensions.Telemetry\Microsoft.Testing.Extensions.Telemetry.csproj", "{BCA498E6-22C7-4E3F-8862-A7FAA06652D1}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Testing.Extensions.CrashDump", "src\Platform\Microsoft.Testing.Extensions.CrashDump\Microsoft.Testing.Extensions.CrashDump.csproj", "{DFC9B46A-BFA7-407D-B872-7104C78A0787}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Testing.Extensions.HangDump", "src\Platform\Microsoft.Testing.Extensions.HangDump\Microsoft.Testing.Extensions.HangDump.csproj", "{8C743361-B796-4A92-BD69-3B5DD734BA6F}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Testing.Extensions.UnitTests", "test\UnitTests\Microsoft.Testing.Extensions.UnitTests\Microsoft.Testing.Extensions.UnitTests.csproj", "{16FEFD31-B0D6-4291-B620-F902A16F39DC}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Testing.Extensions.VSTestBridge.UnitTests", "test\UnitTests\Microsoft.Testing.Extensions.VSTestBridge.UnitTests\Microsoft.Testing.Extensions.VSTestBridge.UnitTests.csproj", "{573C617F-6BB2-403A-AD87-E00A7FD537F0}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Testing.Platform.MSBuild.UnitTests", "test\UnitTests\Microsoft.Testing.Platform.MSBuild.UnitTests\Microsoft.Testing.Platform.MSBuild.UnitTests.csproj", "{F422398C-72CD-43EA-AC8E-E0DBD08E5563}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.Testing.Extensions.MSBuild", "src\Platform\Microsoft.Testing.Extensions.MSBuild\Microsoft.Testing.Extensions.MSBuild.csproj", "{8CE782A2-7374-4916-9C69-1F87E51A64A9}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MSTest.Internal.Analyzers", "src\Analyzers\MSTest.Internal.Analyzers\MSTest.Internal.Analyzers.csproj", "{4A93E1A2-B61E-31B2-33F2-478156A9B5E7}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.Testing.Extensions.HotReload", "src\Platform\Microsoft.Testing.Extensions.HotReload\Microsoft.Testing.Extensions.HotReload.csproj", "{53EBA540-F6CF-0715-1F62-241A53F537EC}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.Testing.Extensions.Retry", "src\Platform\Microsoft.Testing.Extensions.Retry\Microsoft.Testing.Extensions.Retry.csproj", "{FB4ED3AA-A12E-4192-861F-4B025876AA0F}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MSTest.GlobalConfigsGenerator", "src\Analyzers\MSTest.GlobalConfigsGenerator\MSTest.GlobalConfigsGenerator.csproj", "{A85AA656-6DB6-4A0B-AA80-CBB4058B3DDB}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MSTest.Engine", "src\Adapter\MSTest.Engine\MSTest.Engine.csproj", "{82881535-7E40-80D9-F086-A3847775F2E7}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MSTest.SourceGeneration", "src\Analyzers\MSTest.SourceGeneration\MSTest.SourceGeneration.csproj", "{7BA0E74E-798E-4399-2EDE-A23BD5DA78CA}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MSTest.Engine.UnitTests", "test\UnitTests\MSTest.Engine.UnitTests\MSTest.Engine.UnitTests.csproj", "{2C0DFAC0-5D58-D172-ECE4-CBB78AD03435}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MSTest.SourceGeneration.UnitTests", "test\UnitTests\MSTest.SourceGeneration.UnitTests\MSTest.SourceGeneration.UnitTests.csproj", "{E6C0466E-BE8D-C04F-149A-FD98438F1413}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.Testing.Extensions.AzureDevOpsReport", "src\Platform\Microsoft.Testing.Extensions.AzureDevOpsReport\Microsoft.Testing.Extensions.AzureDevOpsReport.csproj", "{F608D3A3-125B-CD88-1D51-8714ED142029}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MSTest.SelfRealExamples.UnitTests", "test\UnitTests\MSTest.SelfRealExamples.UnitTests\MSTest.SelfRealExamples.UnitTests.csproj", "{E5DE7057-7304-439A-94D7-D1609CC40631}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {98BA6D2C-1F3D-4636-8E1D-D4932B7A253D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {98BA6D2C-1F3D-4636-8E1D-D4932B7A253D}.Debug|Any CPU.Build.0 = Debug|Any CPU - {98BA6D2C-1F3D-4636-8E1D-D4932B7A253D}.Release|Any CPU.ActiveCfg = Release|Any CPU - {98BA6D2C-1F3D-4636-8E1D-D4932B7A253D}.Release|Any CPU.Build.0 = Release|Any CPU - {5D153CAA-80C2-4551-9549-6C406FCEEFB1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {5D153CAA-80C2-4551-9549-6C406FCEEFB1}.Debug|Any CPU.Build.0 = Debug|Any CPU - {5D153CAA-80C2-4551-9549-6C406FCEEFB1}.Release|Any CPU.ActiveCfg = Release|Any CPU - {5D153CAA-80C2-4551-9549-6C406FCEEFB1}.Release|Any CPU.Build.0 = Release|Any CPU - {7252D9E3-267D-442C-96BC-C73AEF3241D6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {7252D9E3-267D-442C-96BC-C73AEF3241D6}.Debug|Any CPU.Build.0 = Debug|Any CPU - {7252D9E3-267D-442C-96BC-C73AEF3241D6}.Release|Any CPU.ActiveCfg = Release|Any CPU - {7252D9E3-267D-442C-96BC-C73AEF3241D6}.Release|Any CPU.Build.0 = Release|Any CPU - {DF131865-84EE-4540-8112-E88ACEBDEA09}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {DF131865-84EE-4540-8112-E88ACEBDEA09}.Debug|Any CPU.Build.0 = Debug|Any CPU - {DF131865-84EE-4540-8112-E88ACEBDEA09}.Release|Any CPU.ActiveCfg = Release|Any CPU - {DF131865-84EE-4540-8112-E88ACEBDEA09}.Release|Any CPU.Build.0 = Release|Any CPU - {1CEB5743-70BF-475E-91BC-0AEBD63835B7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {1CEB5743-70BF-475E-91BC-0AEBD63835B7}.Debug|Any CPU.Build.0 = Debug|Any CPU - {1CEB5743-70BF-475E-91BC-0AEBD63835B7}.Release|Any CPU.ActiveCfg = Release|Any CPU - {1CEB5743-70BF-475E-91BC-0AEBD63835B7}.Release|Any CPU.Build.0 = Release|Any CPU - {599833DC-EC5A-40CA-B5CF-DEF719548EEF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {599833DC-EC5A-40CA-B5CF-DEF719548EEF}.Debug|Any CPU.Build.0 = Debug|Any CPU - {599833DC-EC5A-40CA-B5CF-DEF719548EEF}.Release|Any CPU.ActiveCfg = Release|Any CPU - {599833DC-EC5A-40CA-B5CF-DEF719548EEF}.Release|Any CPU.Build.0 = Release|Any CPU - {0A4A76DD-FEE1-4D04-926B-38E1A24A7ED2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {0A4A76DD-FEE1-4D04-926B-38E1A24A7ED2}.Debug|Any CPU.Build.0 = Debug|Any CPU - {0A4A76DD-FEE1-4D04-926B-38E1A24A7ED2}.Release|Any CPU.ActiveCfg = Release|Any CPU - {0A4A76DD-FEE1-4D04-926B-38E1A24A7ED2}.Release|Any CPU.Build.0 = Release|Any CPU - {A82770C0-1FF5-43C7-8790-471D5E4F8D6E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {A82770C0-1FF5-43C7-8790-471D5E4F8D6E}.Debug|Any CPU.Build.0 = Debug|Any CPU - {A82770C0-1FF5-43C7-8790-471D5E4F8D6E}.Release|Any CPU.ActiveCfg = Release|Any CPU - {A82770C0-1FF5-43C7-8790-471D5E4F8D6E}.Release|Any CPU.Build.0 = Release|Any CPU - {6359B7FD-5C63-487A-9467-99323C17AA10}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {6359B7FD-5C63-487A-9467-99323C17AA10}.Debug|Any CPU.Build.0 = Debug|Any CPU - {6359B7FD-5C63-487A-9467-99323C17AA10}.Release|Any CPU.ActiveCfg = Release|Any CPU - {6359B7FD-5C63-487A-9467-99323C17AA10}.Release|Any CPU.Build.0 = Release|Any CPU - {FE2A0AE6-835E-4603-9CE9-C8E25D14C4A0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {FE2A0AE6-835E-4603-9CE9-C8E25D14C4A0}.Debug|Any CPU.Build.0 = Debug|Any CPU - {FE2A0AE6-835E-4603-9CE9-C8E25D14C4A0}.Release|Any CPU.ActiveCfg = Release|Any CPU - {FE2A0AE6-835E-4603-9CE9-C8E25D14C4A0}.Release|Any CPU.Build.0 = Release|Any CPU - {93D3B3B5-6850-461C-9A08-A78D2921F86F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {93D3B3B5-6850-461C-9A08-A78D2921F86F}.Debug|Any CPU.Build.0 = Debug|Any CPU - {93D3B3B5-6850-461C-9A08-A78D2921F86F}.Release|Any CPU.ActiveCfg = Release|Any CPU - {93D3B3B5-6850-461C-9A08-A78D2921F86F}.Release|Any CPU.Build.0 = Release|Any CPU - {2833FDA8-ECA0-439C-97E4-620AB9EC45AA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {2833FDA8-ECA0-439C-97E4-620AB9EC45AA}.Debug|Any CPU.Build.0 = Debug|Any CPU - {2833FDA8-ECA0-439C-97E4-620AB9EC45AA}.Release|Any CPU.ActiveCfg = Release|Any CPU - {2833FDA8-ECA0-439C-97E4-620AB9EC45AA}.Release|Any CPU.Build.0 = Release|Any CPU - {60116E14-11A3-47DF-B730-8A28ABD9B7AF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {60116E14-11A3-47DF-B730-8A28ABD9B7AF}.Debug|Any CPU.Build.0 = Debug|Any CPU - {60116E14-11A3-47DF-B730-8A28ABD9B7AF}.Release|Any CPU.ActiveCfg = Release|Any CPU - {60116E14-11A3-47DF-B730-8A28ABD9B7AF}.Release|Any CPU.Build.0 = Release|Any CPU - {CA6A4A5A-CFDE-440B-898E-FF6FBA405540}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {CA6A4A5A-CFDE-440B-898E-FF6FBA405540}.Debug|Any CPU.Build.0 = Debug|Any CPU - {CA6A4A5A-CFDE-440B-898E-FF6FBA405540}.Release|Any CPU.ActiveCfg = Release|Any CPU - {CA6A4A5A-CFDE-440B-898E-FF6FBA405540}.Release|Any CPU.Build.0 = Release|Any CPU - {9C81E66B-5DFE-4130-982E-64EF8D7F6A60}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {9C81E66B-5DFE-4130-982E-64EF8D7F6A60}.Debug|Any CPU.Build.0 = Debug|Any CPU - {9C81E66B-5DFE-4130-982E-64EF8D7F6A60}.Release|Any CPU.ActiveCfg = Release|Any CPU - {9C81E66B-5DFE-4130-982E-64EF8D7F6A60}.Release|Any CPU.Build.0 = Release|Any CPU - {BE21907B-A4C1-41D7-A2EF-5C73A33090A0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {BE21907B-A4C1-41D7-A2EF-5C73A33090A0}.Debug|Any CPU.Build.0 = Debug|Any CPU - {BE21907B-A4C1-41D7-A2EF-5C73A33090A0}.Release|Any CPU.ActiveCfg = Release|Any CPU - {BE21907B-A4C1-41D7-A2EF-5C73A33090A0}.Release|Any CPU.Build.0 = Release|Any CPU - {F6AD3FE2-3C82-44E8-A694-C4C447EB2F10}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {F6AD3FE2-3C82-44E8-A694-C4C447EB2F10}.Debug|Any CPU.Build.0 = Debug|Any CPU - {F6AD3FE2-3C82-44E8-A694-C4C447EB2F10}.Release|Any CPU.ActiveCfg = Release|Any CPU - {F6AD3FE2-3C82-44E8-A694-C4C447EB2F10}.Release|Any CPU.Build.0 = Release|Any CPU - {41DD903C-CA88-4761-831B-978EC793508F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {41DD903C-CA88-4761-831B-978EC793508F}.Debug|Any CPU.Build.0 = Debug|Any CPU - {41DD903C-CA88-4761-831B-978EC793508F}.Release|Any CPU.ActiveCfg = Release|Any CPU - {41DD903C-CA88-4761-831B-978EC793508F}.Release|Any CPU.Build.0 = Release|Any CPU - {93B2E07F-A41D-42DC-AF5D-47048761DFA9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {93B2E07F-A41D-42DC-AF5D-47048761DFA9}.Debug|Any CPU.Build.0 = Debug|Any CPU - {93B2E07F-A41D-42DC-AF5D-47048761DFA9}.Release|Any CPU.ActiveCfg = Release|Any CPU - {93B2E07F-A41D-42DC-AF5D-47048761DFA9}.Release|Any CPU.Build.0 = Release|Any CPU - {48A0431B-9EFA-46DA-9AA9-D6552A7DA109}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {48A0431B-9EFA-46DA-9AA9-D6552A7DA109}.Debug|Any CPU.Build.0 = Debug|Any CPU - {48A0431B-9EFA-46DA-9AA9-D6552A7DA109}.Release|Any CPU.ActiveCfg = Release|Any CPU - {48A0431B-9EFA-46DA-9AA9-D6552A7DA109}.Release|Any CPU.Build.0 = Release|Any CPU - {A2C5B6FE-A5B4-4419-A1FC-3F977DE24D2B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {A2C5B6FE-A5B4-4419-A1FC-3F977DE24D2B}.Debug|Any CPU.Build.0 = Debug|Any CPU - {A2C5B6FE-A5B4-4419-A1FC-3F977DE24D2B}.Release|Any CPU.ActiveCfg = Release|Any CPU - {A2C5B6FE-A5B4-4419-A1FC-3F977DE24D2B}.Release|Any CPU.Build.0 = Release|Any CPU - {D11D17B0-74DB-43B2-B5AC-7F86E0ACEFCD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {D11D17B0-74DB-43B2-B5AC-7F86E0ACEFCD}.Debug|Any CPU.Build.0 = Debug|Any CPU - {D11D17B0-74DB-43B2-B5AC-7F86E0ACEFCD}.Release|Any CPU.ActiveCfg = Release|Any CPU - {D11D17B0-74DB-43B2-B5AC-7F86E0ACEFCD}.Release|Any CPU.Build.0 = Release|Any CPU - {C37026D9-6525-4128-A4A1-9E3E2C195737}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {C37026D9-6525-4128-A4A1-9E3E2C195737}.Debug|Any CPU.Build.0 = Debug|Any CPU - {C37026D9-6525-4128-A4A1-9E3E2C195737}.Release|Any CPU.ActiveCfg = Release|Any CPU - {C37026D9-6525-4128-A4A1-9E3E2C195737}.Release|Any CPU.Build.0 = Release|Any CPU - {2F4DFABA-B031-4164-A178-25F0753C9971}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {2F4DFABA-B031-4164-A178-25F0753C9971}.Debug|Any CPU.Build.0 = Debug|Any CPU - {2F4DFABA-B031-4164-A178-25F0753C9971}.Release|Any CPU.ActiveCfg = Release|Any CPU - {2F4DFABA-B031-4164-A178-25F0753C9971}.Release|Any CPU.Build.0 = Release|Any CPU - {77CDBBF7-895B-44E1-8C86-05D81286BC3A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {77CDBBF7-895B-44E1-8C86-05D81286BC3A}.Debug|Any CPU.Build.0 = Debug|Any CPU - {77CDBBF7-895B-44E1-8C86-05D81286BC3A}.Release|Any CPU.ActiveCfg = Release|Any CPU - {77CDBBF7-895B-44E1-8C86-05D81286BC3A}.Release|Any CPU.Build.0 = Release|Any CPU - {DBE6C4AF-4D79-44BB-94B5-C57FEC8B4E69}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {DBE6C4AF-4D79-44BB-94B5-C57FEC8B4E69}.Debug|Any CPU.Build.0 = Debug|Any CPU - {DBE6C4AF-4D79-44BB-94B5-C57FEC8B4E69}.Release|Any CPU.ActiveCfg = Release|Any CPU - {DBE6C4AF-4D79-44BB-94B5-C57FEC8B4E69}.Release|Any CPU.Build.0 = Release|Any CPU - {2607F3CC-3AFE-4968-B028-4F502B9F6A28}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {2607F3CC-3AFE-4968-B028-4F502B9F6A28}.Debug|Any CPU.Build.0 = Debug|Any CPU - {2607F3CC-3AFE-4968-B028-4F502B9F6A28}.Release|Any CPU.ActiveCfg = Release|Any CPU - {2607F3CC-3AFE-4968-B028-4F502B9F6A28}.Release|Any CPU.Build.0 = Release|Any CPU - {60AE14C4-C54C-419D-AFF8-D7E49901D42B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {60AE14C4-C54C-419D-AFF8-D7E49901D42B}.Debug|Any CPU.Build.0 = Debug|Any CPU - {60AE14C4-C54C-419D-AFF8-D7E49901D42B}.Release|Any CPU.ActiveCfg = Release|Any CPU - {60AE14C4-C54C-419D-AFF8-D7E49901D42B}.Release|Any CPU.Build.0 = Release|Any CPU - {17025461-E4B9-4D4A-AD74-AF1C355E61BC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {17025461-E4B9-4D4A-AD74-AF1C355E61BC}.Debug|Any CPU.Build.0 = Debug|Any CPU - {17025461-E4B9-4D4A-AD74-AF1C355E61BC}.Release|Any CPU.ActiveCfg = Release|Any CPU - {17025461-E4B9-4D4A-AD74-AF1C355E61BC}.Release|Any CPU.Build.0 = Release|Any CPU - {279E5DCA-3CD6-4C66-9D5F-475FDE96F3B8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {279E5DCA-3CD6-4C66-9D5F-475FDE96F3B8}.Debug|Any CPU.Build.0 = Debug|Any CPU - {279E5DCA-3CD6-4C66-9D5F-475FDE96F3B8}.Release|Any CPU.ActiveCfg = Release|Any CPU - {279E5DCA-3CD6-4C66-9D5F-475FDE96F3B8}.Release|Any CPU.Build.0 = Release|Any CPU - {CAA66039-6747-4516-ADBA-F3D4C349E9EA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {CAA66039-6747-4516-ADBA-F3D4C349E9EA}.Debug|Any CPU.Build.0 = Debug|Any CPU - {CAA66039-6747-4516-ADBA-F3D4C349E9EA}.Release|Any CPU.ActiveCfg = Release|Any CPU - {CAA66039-6747-4516-ADBA-F3D4C349E9EA}.Release|Any CPU.Build.0 = Release|Any CPU - {8BCC6F49-CF4F-40DA-8EFC-D232C7984ABC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {8BCC6F49-CF4F-40DA-8EFC-D232C7984ABC}.Debug|Any CPU.Build.0 = Debug|Any CPU - {8BCC6F49-CF4F-40DA-8EFC-D232C7984ABC}.Release|Any CPU.ActiveCfg = Release|Any CPU - {8BCC6F49-CF4F-40DA-8EFC-D232C7984ABC}.Release|Any CPU.Build.0 = Release|Any CPU - {34714FAD-A226-432E-9083-6BCF79D71873}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {34714FAD-A226-432E-9083-6BCF79D71873}.Debug|Any CPU.Build.0 = Debug|Any CPU - {34714FAD-A226-432E-9083-6BCF79D71873}.Release|Any CPU.ActiveCfg = Release|Any CPU - {34714FAD-A226-432E-9083-6BCF79D71873}.Release|Any CPU.Build.0 = Release|Any CPU - {27CFE39F-3F60-47E0-9281-12CB13C7B91E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {27CFE39F-3F60-47E0-9281-12CB13C7B91E}.Debug|Any CPU.Build.0 = Debug|Any CPU - {27CFE39F-3F60-47E0-9281-12CB13C7B91E}.Release|Any CPU.ActiveCfg = Release|Any CPU - {27CFE39F-3F60-47E0-9281-12CB13C7B91E}.Release|Any CPU.Build.0 = Release|Any CPU - {DBA74878-65BF-4EE7-925A-67AF395F7D11}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {DBA74878-65BF-4EE7-925A-67AF395F7D11}.Debug|Any CPU.Build.0 = Debug|Any CPU - {DBA74878-65BF-4EE7-925A-67AF395F7D11}.Release|Any CPU.ActiveCfg = Release|Any CPU - {DBA74878-65BF-4EE7-925A-67AF395F7D11}.Release|Any CPU.Build.0 = Release|Any CPU - {B3419F35-A31F-4CAA-A606-034D5DB669A2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {B3419F35-A31F-4CAA-A606-034D5DB669A2}.Debug|Any CPU.Build.0 = Debug|Any CPU - {B3419F35-A31F-4CAA-A606-034D5DB669A2}.Release|Any CPU.ActiveCfg = Release|Any CPU - {B3419F35-A31F-4CAA-A606-034D5DB669A2}.Release|Any CPU.Build.0 = Release|Any CPU - {4A184EC4-8BAB-498F-ABC6-300C70BF8240}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {4A184EC4-8BAB-498F-ABC6-300C70BF8240}.Debug|Any CPU.Build.0 = Debug|Any CPU - {4A184EC4-8BAB-498F-ABC6-300C70BF8240}.Release|Any CPU.ActiveCfg = Release|Any CPU - {4A184EC4-8BAB-498F-ABC6-300C70BF8240}.Release|Any CPU.Build.0 = Release|Any CPU - {CA5D66E2-7244-4E72-AFB6-58A826A30B74}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {CA5D66E2-7244-4E72-AFB6-58A826A30B74}.Debug|Any CPU.Build.0 = Debug|Any CPU - {CA5D66E2-7244-4E72-AFB6-58A826A30B74}.Release|Any CPU.ActiveCfg = Release|Any CPU - {CA5D66E2-7244-4E72-AFB6-58A826A30B74}.Release|Any CPU.Build.0 = Release|Any CPU - {35E90097-976B-4FF5-B55F-2F51561D7A33}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {35E90097-976B-4FF5-B55F-2F51561D7A33}.Debug|Any CPU.Build.0 = Debug|Any CPU - {35E90097-976B-4FF5-B55F-2F51561D7A33}.Release|Any CPU.ActiveCfg = Release|Any CPU - {35E90097-976B-4FF5-B55F-2F51561D7A33}.Release|Any CPU.Build.0 = Release|Any CPU - {17CE999F-F3D1-48B4-A18F-8BA050C3A4AD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {17CE999F-F3D1-48B4-A18F-8BA050C3A4AD}.Debug|Any CPU.Build.0 = Debug|Any CPU - {17CE999F-F3D1-48B4-A18F-8BA050C3A4AD}.Release|Any CPU.ActiveCfg = Release|Any CPU - {17CE999F-F3D1-48B4-A18F-8BA050C3A4AD}.Release|Any CPU.Build.0 = Release|Any CPU - {ED8534D1-3136-4915-8071-5547E8D84DC3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {ED8534D1-3136-4915-8071-5547E8D84DC3}.Debug|Any CPU.Build.0 = Debug|Any CPU - {ED8534D1-3136-4915-8071-5547E8D84DC3}.Release|Any CPU.ActiveCfg = Release|Any CPU - {ED8534D1-3136-4915-8071-5547E8D84DC3}.Release|Any CPU.Build.0 = Release|Any CPU - {48FAB979-8DA5-492E-8B3F-5DBBE82F659A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {48FAB979-8DA5-492E-8B3F-5DBBE82F659A}.Debug|Any CPU.Build.0 = Debug|Any CPU - {48FAB979-8DA5-492E-8B3F-5DBBE82F659A}.Release|Any CPU.ActiveCfg = Release|Any CPU - {48FAB979-8DA5-492E-8B3F-5DBBE82F659A}.Release|Any CPU.Build.0 = Release|Any CPU - {0F1BB08E-BB6C-43E0-A7DF-1D6A03DA5DC7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {0F1BB08E-BB6C-43E0-A7DF-1D6A03DA5DC7}.Debug|Any CPU.Build.0 = Debug|Any CPU - {0F1BB08E-BB6C-43E0-A7DF-1D6A03DA5DC7}.Release|Any CPU.ActiveCfg = Release|Any CPU - {0F1BB08E-BB6C-43E0-A7DF-1D6A03DA5DC7}.Release|Any CPU.Build.0 = Release|Any CPU - {72C4FA49-E553-4B39-825A-8C4EA6CE93E2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {72C4FA49-E553-4B39-825A-8C4EA6CE93E2}.Debug|Any CPU.Build.0 = Debug|Any CPU - {72C4FA49-E553-4B39-825A-8C4EA6CE93E2}.Release|Any CPU.ActiveCfg = Release|Any CPU - {72C4FA49-E553-4B39-825A-8C4EA6CE93E2}.Release|Any CPU.Build.0 = Release|Any CPU - {462B0201-1C26-4951-97C9-722C2A58EF8C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {462B0201-1C26-4951-97C9-722C2A58EF8C}.Debug|Any CPU.Build.0 = Debug|Any CPU - {462B0201-1C26-4951-97C9-722C2A58EF8C}.Release|Any CPU.ActiveCfg = Release|Any CPU - {462B0201-1C26-4951-97C9-722C2A58EF8C}.Release|Any CPU.Build.0 = Release|Any CPU - {DC068986-7549-4B75-8EFC-A9958FD5CF88}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {DC068986-7549-4B75-8EFC-A9958FD5CF88}.Debug|Any CPU.Build.0 = Debug|Any CPU - {DC068986-7549-4B75-8EFC-A9958FD5CF88}.Release|Any CPU.ActiveCfg = Release|Any CPU - {DC068986-7549-4B75-8EFC-A9958FD5CF88}.Release|Any CPU.Build.0 = Release|Any CPU - {1FF35C23-C128-4C95-B3F8-67B1B4C51E4D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {1FF35C23-C128-4C95-B3F8-67B1B4C51E4D}.Debug|Any CPU.Build.0 = Debug|Any CPU - {1FF35C23-C128-4C95-B3F8-67B1B4C51E4D}.Release|Any CPU.ActiveCfg = Release|Any CPU - {1FF35C23-C128-4C95-B3F8-67B1B4C51E4D}.Release|Any CPU.Build.0 = Release|Any CPU - {10930CFD-EDF9-4486-B0A3-49230B5A6798}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {10930CFD-EDF9-4486-B0A3-49230B5A6798}.Debug|Any CPU.Build.0 = Debug|Any CPU - {10930CFD-EDF9-4486-B0A3-49230B5A6798}.Release|Any CPU.ActiveCfg = Release|Any CPU - {10930CFD-EDF9-4486-B0A3-49230B5A6798}.Release|Any CPU.Build.0 = Release|Any CPU - {100CF515-8291-45FF-9FFD-2A9064FECC72}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {100CF515-8291-45FF-9FFD-2A9064FECC72}.Debug|Any CPU.Build.0 = Debug|Any CPU - {100CF515-8291-45FF-9FFD-2A9064FECC72}.Release|Any CPU.ActiveCfg = Release|Any CPU - {100CF515-8291-45FF-9FFD-2A9064FECC72}.Release|Any CPU.Build.0 = Release|Any CPU - {9DCE14DA-3DFB-48DE-A3CC-A02C3465973C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {9DCE14DA-3DFB-48DE-A3CC-A02C3465973C}.Debug|Any CPU.Build.0 = Debug|Any CPU - {9DCE14DA-3DFB-48DE-A3CC-A02C3465973C}.Release|Any CPU.ActiveCfg = Release|Any CPU - {9DCE14DA-3DFB-48DE-A3CC-A02C3465973C}.Release|Any CPU.Build.0 = Release|Any CPU - {3CF3861E-EB1B-4FA6-9355-372A9816DF6B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {3CF3861E-EB1B-4FA6-9355-372A9816DF6B}.Debug|Any CPU.Build.0 = Debug|Any CPU - {3CF3861E-EB1B-4FA6-9355-372A9816DF6B}.Release|Any CPU.ActiveCfg = Release|Any CPU - {3CF3861E-EB1B-4FA6-9355-372A9816DF6B}.Release|Any CPU.Build.0 = Release|Any CPU - {7E9D98E7-733C-4D6B-A5AC-087D588A40ED}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {7E9D98E7-733C-4D6B-A5AC-087D588A40ED}.Debug|Any CPU.Build.0 = Debug|Any CPU - {7E9D98E7-733C-4D6B-A5AC-087D588A40ED}.Release|Any CPU.ActiveCfg = Release|Any CPU - {7E9D98E7-733C-4D6B-A5AC-087D588A40ED}.Release|Any CPU.Build.0 = Release|Any CPU - {8A41B37E-0732-4F28-B214-A44233B447FE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {8A41B37E-0732-4F28-B214-A44233B447FE}.Debug|Any CPU.Build.0 = Debug|Any CPU - {8A41B37E-0732-4F28-B214-A44233B447FE}.Release|Any CPU.ActiveCfg = Release|Any CPU - {8A41B37E-0732-4F28-B214-A44233B447FE}.Release|Any CPU.Build.0 = Release|Any CPU - {BCB42780-C559-40B6-8C4A-85EBC464AAA8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {BCB42780-C559-40B6-8C4A-85EBC464AAA8}.Debug|Any CPU.Build.0 = Debug|Any CPU - {BCB42780-C559-40B6-8C4A-85EBC464AAA8}.Release|Any CPU.ActiveCfg = Release|Any CPU - {BCB42780-C559-40B6-8C4A-85EBC464AAA8}.Release|Any CPU.Build.0 = Release|Any CPU - {A7D0995D-0516-4975-ABBD-EB93E1B79292}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {A7D0995D-0516-4975-ABBD-EB93E1B79292}.Debug|Any CPU.Build.0 = Debug|Any CPU - {A7D0995D-0516-4975-ABBD-EB93E1B79292}.Release|Any CPU.ActiveCfg = Release|Any CPU - {A7D0995D-0516-4975-ABBD-EB93E1B79292}.Release|Any CPU.Build.0 = Release|Any CPU - {9164E0BA-0846-4839-BA0F-C25F5FBE056C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {9164E0BA-0846-4839-BA0F-C25F5FBE056C}.Debug|Any CPU.Build.0 = Debug|Any CPU - {9164E0BA-0846-4839-BA0F-C25F5FBE056C}.Release|Any CPU.ActiveCfg = Release|Any CPU - {9164E0BA-0846-4839-BA0F-C25F5FBE056C}.Release|Any CPU.Build.0 = Release|Any CPU - {29B9F157-3733-471E-A11E-A5FF3C6D1348}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {29B9F157-3733-471E-A11E-A5FF3C6D1348}.Debug|Any CPU.Build.0 = Debug|Any CPU - {29B9F157-3733-471E-A11E-A5FF3C6D1348}.Release|Any CPU.ActiveCfg = Release|Any CPU - {29B9F157-3733-471E-A11E-A5FF3C6D1348}.Release|Any CPU.Build.0 = Release|Any CPU - {60763BAA-C963-4858-8DA1-78DB92428865}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {60763BAA-C963-4858-8DA1-78DB92428865}.Debug|Any CPU.Build.0 = Debug|Any CPU - {60763BAA-C963-4858-8DA1-78DB92428865}.Release|Any CPU.ActiveCfg = Release|Any CPU - {60763BAA-C963-4858-8DA1-78DB92428865}.Release|Any CPU.Build.0 = Release|Any CPU - {1B30B69C-A4E3-4660-9CA8-140D0C34B4A5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {1B30B69C-A4E3-4660-9CA8-140D0C34B4A5}.Debug|Any CPU.Build.0 = Debug|Any CPU - {1B30B69C-A4E3-4660-9CA8-140D0C34B4A5}.Release|Any CPU.ActiveCfg = Release|Any CPU - {1B30B69C-A4E3-4660-9CA8-140D0C34B4A5}.Release|Any CPU.Build.0 = Release|Any CPU - {BCA498E6-22C7-4E3F-8862-A7FAA06652D1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {BCA498E6-22C7-4E3F-8862-A7FAA06652D1}.Debug|Any CPU.Build.0 = Debug|Any CPU - {BCA498E6-22C7-4E3F-8862-A7FAA06652D1}.Release|Any CPU.ActiveCfg = Release|Any CPU - {BCA498E6-22C7-4E3F-8862-A7FAA06652D1}.Release|Any CPU.Build.0 = Release|Any CPU - {DFC9B46A-BFA7-407D-B872-7104C78A0787}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {DFC9B46A-BFA7-407D-B872-7104C78A0787}.Debug|Any CPU.Build.0 = Debug|Any CPU - {DFC9B46A-BFA7-407D-B872-7104C78A0787}.Release|Any CPU.ActiveCfg = Release|Any CPU - {DFC9B46A-BFA7-407D-B872-7104C78A0787}.Release|Any CPU.Build.0 = Release|Any CPU - {8C743361-B796-4A92-BD69-3B5DD734BA6F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {8C743361-B796-4A92-BD69-3B5DD734BA6F}.Debug|Any CPU.Build.0 = Debug|Any CPU - {8C743361-B796-4A92-BD69-3B5DD734BA6F}.Release|Any CPU.ActiveCfg = Release|Any CPU - {8C743361-B796-4A92-BD69-3B5DD734BA6F}.Release|Any CPU.Build.0 = Release|Any CPU - {16FEFD31-B0D6-4291-B620-F902A16F39DC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {16FEFD31-B0D6-4291-B620-F902A16F39DC}.Debug|Any CPU.Build.0 = Debug|Any CPU - {16FEFD31-B0D6-4291-B620-F902A16F39DC}.Release|Any CPU.ActiveCfg = Release|Any CPU - {16FEFD31-B0D6-4291-B620-F902A16F39DC}.Release|Any CPU.Build.0 = Release|Any CPU - {573C617F-6BB2-403A-AD87-E00A7FD537F0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {573C617F-6BB2-403A-AD87-E00A7FD537F0}.Debug|Any CPU.Build.0 = Debug|Any CPU - {573C617F-6BB2-403A-AD87-E00A7FD537F0}.Release|Any CPU.ActiveCfg = Release|Any CPU - {573C617F-6BB2-403A-AD87-E00A7FD537F0}.Release|Any CPU.Build.0 = Release|Any CPU - {F422398C-72CD-43EA-AC8E-E0DBD08E5563}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {F422398C-72CD-43EA-AC8E-E0DBD08E5563}.Debug|Any CPU.Build.0 = Debug|Any CPU - {F422398C-72CD-43EA-AC8E-E0DBD08E5563}.Release|Any CPU.ActiveCfg = Release|Any CPU - {F422398C-72CD-43EA-AC8E-E0DBD08E5563}.Release|Any CPU.Build.0 = Release|Any CPU - {8CE782A2-7374-4916-9C69-1F87E51A64A9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {8CE782A2-7374-4916-9C69-1F87E51A64A9}.Debug|Any CPU.Build.0 = Debug|Any CPU - {8CE782A2-7374-4916-9C69-1F87E51A64A9}.Release|Any CPU.ActiveCfg = Release|Any CPU - {8CE782A2-7374-4916-9C69-1F87E51A64A9}.Release|Any CPU.Build.0 = Release|Any CPU - {4A93E1A2-B61E-31B2-33F2-478156A9B5E7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {4A93E1A2-B61E-31B2-33F2-478156A9B5E7}.Debug|Any CPU.Build.0 = Debug|Any CPU - {4A93E1A2-B61E-31B2-33F2-478156A9B5E7}.Release|Any CPU.ActiveCfg = Release|Any CPU - {4A93E1A2-B61E-31B2-33F2-478156A9B5E7}.Release|Any CPU.Build.0 = Release|Any CPU - {53EBA540-F6CF-0715-1F62-241A53F537EC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {53EBA540-F6CF-0715-1F62-241A53F537EC}.Debug|Any CPU.Build.0 = Debug|Any CPU - {53EBA540-F6CF-0715-1F62-241A53F537EC}.Release|Any CPU.ActiveCfg = Release|Any CPU - {53EBA540-F6CF-0715-1F62-241A53F537EC}.Release|Any CPU.Build.0 = Release|Any CPU - {FB4ED3AA-A12E-4192-861F-4B025876AA0F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {FB4ED3AA-A12E-4192-861F-4B025876AA0F}.Debug|Any CPU.Build.0 = Debug|Any CPU - {FB4ED3AA-A12E-4192-861F-4B025876AA0F}.Release|Any CPU.ActiveCfg = Release|Any CPU - {FB4ED3AA-A12E-4192-861F-4B025876AA0F}.Release|Any CPU.Build.0 = Release|Any CPU - {A85AA656-6DB6-4A0B-AA80-CBB4058B3DDB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {A85AA656-6DB6-4A0B-AA80-CBB4058B3DDB}.Debug|Any CPU.Build.0 = Debug|Any CPU - {A85AA656-6DB6-4A0B-AA80-CBB4058B3DDB}.Release|Any CPU.ActiveCfg = Release|Any CPU - {A85AA656-6DB6-4A0B-AA80-CBB4058B3DDB}.Release|Any CPU.Build.0 = Release|Any CPU - {82881535-7E40-80D9-F086-A3847775F2E7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {82881535-7E40-80D9-F086-A3847775F2E7}.Debug|Any CPU.Build.0 = Debug|Any CPU - {82881535-7E40-80D9-F086-A3847775F2E7}.Release|Any CPU.ActiveCfg = Release|Any CPU - {82881535-7E40-80D9-F086-A3847775F2E7}.Release|Any CPU.Build.0 = Release|Any CPU - {7BA0E74E-798E-4399-2EDE-A23BD5DA78CA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {7BA0E74E-798E-4399-2EDE-A23BD5DA78CA}.Debug|Any CPU.Build.0 = Debug|Any CPU - {7BA0E74E-798E-4399-2EDE-A23BD5DA78CA}.Release|Any CPU.ActiveCfg = Release|Any CPU - {7BA0E74E-798E-4399-2EDE-A23BD5DA78CA}.Release|Any CPU.Build.0 = Release|Any CPU - {2C0DFAC0-5D58-D172-ECE4-CBB78AD03435}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {2C0DFAC0-5D58-D172-ECE4-CBB78AD03435}.Debug|Any CPU.Build.0 = Debug|Any CPU - {2C0DFAC0-5D58-D172-ECE4-CBB78AD03435}.Release|Any CPU.ActiveCfg = Release|Any CPU - {2C0DFAC0-5D58-D172-ECE4-CBB78AD03435}.Release|Any CPU.Build.0 = Release|Any CPU - {E6C0466E-BE8D-C04F-149A-FD98438F1413}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {E6C0466E-BE8D-C04F-149A-FD98438F1413}.Debug|Any CPU.Build.0 = Debug|Any CPU - {E6C0466E-BE8D-C04F-149A-FD98438F1413}.Release|Any CPU.ActiveCfg = Release|Any CPU - {E6C0466E-BE8D-C04F-149A-FD98438F1413}.Release|Any CPU.Build.0 = Release|Any CPU - {F608D3A3-125B-CD88-1D51-8714ED142029}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {F608D3A3-125B-CD88-1D51-8714ED142029}.Debug|Any CPU.Build.0 = Debug|Any CPU - {F608D3A3-125B-CD88-1D51-8714ED142029}.Release|Any CPU.ActiveCfg = Release|Any CPU - {F608D3A3-125B-CD88-1D51-8714ED142029}.Release|Any CPU.Build.0 = Release|Any CPU - {E5DE7057-7304-439A-94D7-D1609CC40631}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {E5DE7057-7304-439A-94D7-D1609CC40631}.Debug|Any CPU.Build.0 = Debug|Any CPU - {E5DE7057-7304-439A-94D7-D1609CC40631}.Release|Any CPU.ActiveCfg = Release|Any CPU - {E5DE7057-7304-439A-94D7-D1609CC40631}.Release|Any CPU.Build.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(NestedProjects) = preSolution - {24088844-2107-4DB2-8F3F-CBCA94FC4B28} = {FF8B1B72-55A1-4FFE-809E-7B79323ED8D0} - {98BA6D2C-1F3D-4636-8E1D-D4932B7A253D} = {24088844-2107-4DB2-8F3F-CBCA94FC4B28} - {5D153CAA-80C2-4551-9549-6C406FCEEFB1} = {24088844-2107-4DB2-8F3F-CBCA94FC4B28} - {E48AC786-E150-4F41-9A16-32F02E4493D8} = {FF8B1B72-55A1-4FFE-809E-7B79323ED8D0} - {7252D9E3-267D-442C-96BC-C73AEF3241D6} = {E48AC786-E150-4F41-9A16-32F02E4493D8} - {DF131865-84EE-4540-8112-E88ACEBDEA09} = {E48AC786-E150-4F41-9A16-32F02E4493D8} - {33D3029D-E653-4929-BB31-C714178C4BEE} = {A9596292-7E67-4566-9096-143DDAA4E8D8} - {E374A3A6-C364-4890-B315-D60F5C682B6E} = {FF8B1B72-55A1-4FFE-809E-7B79323ED8D0} - {1CEB5743-70BF-475E-91BC-0AEBD63835B7} = {BB874DF1-44FE-415A-B634-A6B829107890} - {599833DC-EC5A-40CA-B5CF-DEF719548EEF} = {BB874DF1-44FE-415A-B634-A6B829107890} - {0A4A76DD-FEE1-4D04-926B-38E1A24A7ED2} = {BB874DF1-44FE-415A-B634-A6B829107890} - {FE0DF239-0D81-46CA-9277-3342009E83F9} = {929A3EDE-893B-4801-82BA-01FD947291CB} - {A82770C0-1FF5-43C7-8790-471D5E4F8D6E} = {92F8E9A2-903E-4025-99BC-7DC478D5466D} - {BB874DF1-44FE-415A-B634-A6B829107890} = {A9596292-7E67-4566-9096-143DDAA4E8D8} - {FF69998C-C661-4EF0-804B-845675B3602E} = {A9596292-7E67-4566-9096-143DDAA4E8D8} - {C9F82701-0E0F-4E61-B05B-AE387E7631F6} = {FF69998C-C661-4EF0-804B-845675B3602E} - {6359B7FD-5C63-487A-9467-99323C17AA10} = {FF69998C-C661-4EF0-804B-845675B3602E} - {FE2A0AE6-835E-4603-9CE9-C8E25D14C4A0} = {FF69998C-C661-4EF0-804B-845675B3602E} - {93D3B3B5-6850-461C-9A08-A78D2921F86F} = {FF69998C-C661-4EF0-804B-845675B3602E} - {2833FDA8-ECA0-439C-97E4-620AB9EC45AA} = {C9F82701-0E0F-4E61-B05B-AE387E7631F6} - {60116E14-11A3-47DF-B730-8A28ABD9B7AF} = {C9F82701-0E0F-4E61-B05B-AE387E7631F6} - {CA6A4A5A-CFDE-440B-898E-FF6FBA405540} = {C9F82701-0E0F-4E61-B05B-AE387E7631F6} - {9C81E66B-5DFE-4130-982E-64EF8D7F6A60} = {C9F82701-0E0F-4E61-B05B-AE387E7631F6} - {BE21907B-A4C1-41D7-A2EF-5C73A33090A0} = {C9F82701-0E0F-4E61-B05B-AE387E7631F6} - {F6AD3FE2-3C82-44E8-A694-C4C447EB2F10} = {C9F82701-0E0F-4E61-B05B-AE387E7631F6} - {41DD903C-CA88-4761-831B-978EC793508F} = {C9F82701-0E0F-4E61-B05B-AE387E7631F6} - {93B2E07F-A41D-42DC-AF5D-47048761DFA9} = {C9F82701-0E0F-4E61-B05B-AE387E7631F6} - {48A0431B-9EFA-46DA-9AA9-D6552A7DA109} = {C9F82701-0E0F-4E61-B05B-AE387E7631F6} - {A2C5B6FE-A5B4-4419-A1FC-3F977DE24D2B} = {C9F82701-0E0F-4E61-B05B-AE387E7631F6} - {D11D17B0-74DB-43B2-B5AC-7F86E0ACEFCD} = {C9F82701-0E0F-4E61-B05B-AE387E7631F6} - {C37026D9-6525-4128-A4A1-9E3E2C195737} = {C9F82701-0E0F-4E61-B05B-AE387E7631F6} - {2F4DFABA-B031-4164-A178-25F0753C9971} = {C9F82701-0E0F-4E61-B05B-AE387E7631F6} - {77CDBBF7-895B-44E1-8C86-05D81286BC3A} = {C9F82701-0E0F-4E61-B05B-AE387E7631F6} - {DBE6C4AF-4D79-44BB-94B5-C57FEC8B4E69} = {C9F82701-0E0F-4E61-B05B-AE387E7631F6} - {2607F3CC-3AFE-4968-B028-4F502B9F6A28} = {C9F82701-0E0F-4E61-B05B-AE387E7631F6} - {60AE14C4-C54C-419D-AFF8-D7E49901D42B} = {C9F82701-0E0F-4E61-B05B-AE387E7631F6} - {17025461-E4B9-4D4A-AD74-AF1C355E61BC} = {C9F82701-0E0F-4E61-B05B-AE387E7631F6} - {279E5DCA-3CD6-4C66-9D5F-475FDE96F3B8} = {C9F82701-0E0F-4E61-B05B-AE387E7631F6} - {CAA66039-6747-4516-ADBA-F3D4C349E9EA} = {C9F82701-0E0F-4E61-B05B-AE387E7631F6} - {8BCC6F49-CF4F-40DA-8EFC-D232C7984ABC} = {C9F82701-0E0F-4E61-B05B-AE387E7631F6} - {34714FAD-A226-432E-9083-6BCF79D71873} = {C9F82701-0E0F-4E61-B05B-AE387E7631F6} - {27CFE39F-3F60-47E0-9281-12CB13C7B91E} = {C9F82701-0E0F-4E61-B05B-AE387E7631F6} - {DBA74878-65BF-4EE7-925A-67AF395F7D11} = {C9F82701-0E0F-4E61-B05B-AE387E7631F6} - {B3419F35-A31F-4CAA-A606-034D5DB669A2} = {C9F82701-0E0F-4E61-B05B-AE387E7631F6} - {4A184EC4-8BAB-498F-ABC6-300C70BF8240} = {C9F82701-0E0F-4E61-B05B-AE387E7631F6} - {CA5D66E2-7244-4E72-AFB6-58A826A30B74} = {C9F82701-0E0F-4E61-B05B-AE387E7631F6} - {35E90097-976B-4FF5-B55F-2F51561D7A33} = {33D3029D-E653-4929-BB31-C714178C4BEE} - {17CE999F-F3D1-48B4-A18F-8BA050C3A4AD} = {33D3029D-E653-4929-BB31-C714178C4BEE} - {ED8534D1-3136-4915-8071-5547E8D84DC3} = {E374A3A6-C364-4890-B315-D60F5C682B6E} - {A9F9C49E-3CDA-4207-AA53-CC80AF1798FE} = {FE0DF239-0D81-46CA-9277-3342009E83F9} - {6AEE1440-FDF0-4729-8196-B24D0E333550} = {FF8B1B72-55A1-4FFE-809E-7B79323ED8D0} - {48FAB979-8DA5-492E-8B3F-5DBBE82F659A} = {6AEE1440-FDF0-4729-8196-B24D0E333550} - {0F1BB08E-BB6C-43E0-A7DF-1D6A03DA5DC7} = {BB874DF1-44FE-415A-B634-A6B829107890} - {E7F15C9C-3928-47AD-8462-64FD29FFCA54} = {FF8B1B72-55A1-4FFE-809E-7B79323ED8D0} - {72C4FA49-E553-4B39-825A-8C4EA6CE93E2} = {E7F15C9C-3928-47AD-8462-64FD29FFCA54} - {462B0201-1C26-4951-97C9-722C2A58EF8C} = {E7F15C9C-3928-47AD-8462-64FD29FFCA54} - {DC068986-7549-4B75-8EFC-A9958FD5CF88} = {E7F15C9C-3928-47AD-8462-64FD29FFCA54} - {1FF35C23-C128-4C95-B3F8-67B1B4C51E4D} = {BB874DF1-44FE-415A-B634-A6B829107890} - {10930CFD-EDF9-4486-B0A3-49230B5A6798} = {E374A3A6-C364-4890-B315-D60F5C682B6E} - {100CF515-8291-45FF-9FFD-2A9064FECC72} = {C9F82701-0E0F-4E61-B05B-AE387E7631F6} - {9DCE14DA-3DFB-48DE-A3CC-A02C3465973C} = {33D3029D-E653-4929-BB31-C714178C4BEE} - {3CF3861E-EB1B-4FA6-9355-372A9816DF6B} = {FF69998C-C661-4EF0-804B-845675B3602E} - {CB0CC552-2017-40C0-934A-C8A3B00EF650} = {A9596292-7E67-4566-9096-143DDAA4E8D8} - {7E9D98E7-733C-4D6B-A5AC-087D588A40ED} = {CB0CC552-2017-40C0-934A-C8A3B00EF650} - {8A41B37E-0732-4F28-B214-A44233B447FE} = {92F8E9A2-903E-4025-99BC-7DC478D5466D} - {BCB42780-C559-40B6-8C4A-85EBC464AAA8} = {FF69998C-C661-4EF0-804B-845675B3602E} - {A7D0995D-0516-4975-ABBD-EB93E1B79292} = {C9F82701-0E0F-4E61-B05B-AE387E7631F6} - {9164E0BA-0846-4839-BA0F-C25F5FBE056C} = {6AEE1440-FDF0-4729-8196-B24D0E333550} - {29B9F157-3733-471E-A11E-A5FF3C6D1348} = {6AEE1440-FDF0-4729-8196-B24D0E333550} - {60763BAA-C963-4858-8DA1-78DB92428865} = {6AEE1440-FDF0-4729-8196-B24D0E333550} - {1B30B69C-A4E3-4660-9CA8-140D0C34B4A5} = {6AEE1440-FDF0-4729-8196-B24D0E333550} - {BCA498E6-22C7-4E3F-8862-A7FAA06652D1} = {6AEE1440-FDF0-4729-8196-B24D0E333550} - {DFC9B46A-BFA7-407D-B872-7104C78A0787} = {6AEE1440-FDF0-4729-8196-B24D0E333550} - {8C743361-B796-4A92-BD69-3B5DD734BA6F} = {6AEE1440-FDF0-4729-8196-B24D0E333550} - {16FEFD31-B0D6-4291-B620-F902A16F39DC} = {BB874DF1-44FE-415A-B634-A6B829107890} - {573C617F-6BB2-403A-AD87-E00A7FD537F0} = {BB874DF1-44FE-415A-B634-A6B829107890} - {F422398C-72CD-43EA-AC8E-E0DBD08E5563} = {BB874DF1-44FE-415A-B634-A6B829107890} - {8CE782A2-7374-4916-9C69-1F87E51A64A9} = {6AEE1440-FDF0-4729-8196-B24D0E333550} - {4A93E1A2-B61E-31B2-33F2-478156A9B5E7} = {E7F15C9C-3928-47AD-8462-64FD29FFCA54} - {53EBA540-F6CF-0715-1F62-241A53F537EC} = {6AEE1440-FDF0-4729-8196-B24D0E333550} - {FB4ED3AA-A12E-4192-861F-4B025876AA0F} = {6AEE1440-FDF0-4729-8196-B24D0E333550} - {A85AA656-6DB6-4A0B-AA80-CBB4058B3DDB} = {E7F15C9C-3928-47AD-8462-64FD29FFCA54} - {82881535-7E40-80D9-F086-A3847775F2E7} = {24088844-2107-4DB2-8F3F-CBCA94FC4B28} - {7BA0E74E-798E-4399-2EDE-A23BD5DA78CA} = {E7F15C9C-3928-47AD-8462-64FD29FFCA54} - {2C0DFAC0-5D58-D172-ECE4-CBB78AD03435} = {BB874DF1-44FE-415A-B634-A6B829107890} - {E6C0466E-BE8D-C04F-149A-FD98438F1413} = {BB874DF1-44FE-415A-B634-A6B829107890} - {F608D3A3-125B-CD88-1D51-8714ED142029} = {6AEE1440-FDF0-4729-8196-B24D0E333550} - {E5DE7057-7304-439A-94D7-D1609CC40631} = {BB874DF1-44FE-415A-B634-A6B829107890} - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {31E0F4D5-975A-41CC-933E-545B2201FAF9} - EndGlobalSection -EndGlobal diff --git a/TestFx.slnx b/TestFx.slnx new file mode 100644 index 0000000000..39e28d3ae3 --- /dev/null +++ b/TestFx.slnx @@ -0,0 +1,135 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/eng/Build.props b/eng/Build.props index 57aac3a459..c1eb7bb1ac 100644 --- a/eng/Build.props +++ b/eng/Build.props @@ -6,7 +6,7 @@ - + diff --git a/eng/build.ps1 b/eng/build.ps1 index 330a5c2309..ee14198255 100644 --- a/eng/build.ps1 +++ b/eng/build.ps1 @@ -57,7 +57,7 @@ if ($vs -or $vscode) { if ($vs) { # Launch Visual Studio with the locally defined environment variables - & "$PSScriptRoot\..\TestFx.sln" + & "$PSScriptRoot\..\TestFx.slnx" } else { if (Get-Command code -ErrorAction Ignore) { & code "$PSScriptRoot\.." From 8b20e9cacefd2313fe2b22837473595ca21128ea Mon Sep 17 00:00:00 2001 From: Copilot <198982749+Copilot@users.noreply.github.com> Date: Wed, 18 Jun 2025 09:33:26 +0200 Subject: [PATCH 104/541] Fix UTA023 error for OwnerAttribute and PriorityAttribute in MSTest 3.10.0-preview (#5804) Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: Youssef1313 <31348972+Youssef1313@users.noreply.github.com> Co-authored-by: Youssef Victor --- .../Execution/TypeCache.cs | 8 +- .../Execution/TypeCacheTests.cs | 116 ++++++++++++++++++ 2 files changed, 121 insertions(+), 3 deletions(-) diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Execution/TypeCache.cs b/src/Adapter/MSTestAdapter.PlatformServices/Execution/TypeCache.cs index 7b9585b367..2fc12e9f2e 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Execution/TypeCache.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Execution/TypeCache.cs @@ -786,7 +786,7 @@ private void SetCustomProperties(TestMethodInfo testMethodInfo, ITestContext tes foreach (TestPropertyAttribute attribute in attributes) { - if (!ValidateAndAssignTestProperty(testMethodInfo, testContext, attribute.Name, attribute.Value)) + if (!ValidateAndAssignTestProperty(testMethodInfo, testContext, attribute.Name, attribute.Value, isPredefinedAttribute: attribute is OwnerAttribute or PriorityAttribute)) { break; } @@ -800,14 +800,16 @@ private void SetCustomProperties(TestMethodInfo testMethodInfo, ITestContext tes /// The test context. /// The property name. /// The property value. + /// If the property originates from a predefined attribute. /// True if its a valid Test Property. private static bool ValidateAndAssignTestProperty( TestMethodInfo testMethodInfo, ITestContext testContext, string propertyName, - string propertyValue) + string propertyValue, + bool isPredefinedAttribute) { - if (PredefinedNames.Any(predefinedProp => predefinedProp == propertyName)) + if (!isPredefinedAttribute && PredefinedNames.Any(predefinedProp => predefinedProp == propertyName)) { testMethodInfo.NotRunnableReason = string.Format( CultureInfo.CurrentCulture, diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TypeCacheTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TypeCacheTests.cs index ead4e93cd4..4b3a1cd12b 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TypeCacheTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TypeCacheTests.cs @@ -1015,6 +1015,30 @@ public void GetTestMethodInfoShouldReportWarningIfCustomPropertyHasSameNameAsPre // Setting up the mock feels unnecessary when the original production implementation can work just fine. var typeCache = new TypeCache(new ReflectHelper()); Type type = typeof(DummyTestClassWithTestMethods); + MethodInfo methodInfo = type.GetMethod("TestMethodWithTestCategoryAsCustomProperty")!; + var testMethod = new TestMethod(methodInfo.Name, type.FullName!, "A", isAsync: false); + var testContext = new TestContextImplementation( + testMethod, + new ThreadSafeStringWriter(null!, "test"), + new Dictionary()); + + TestMethodInfo? testMethodInfo = typeCache.GetTestMethodInfo(testMethod, testContext); + + Verify(testMethodInfo is not null); + string expectedMessage = string.Format( + CultureInfo.InvariantCulture, + "UTA023: {0}: Cannot define predefined property {2} on method {1}.", + methodInfo.DeclaringType!.FullName!, + methodInfo.Name, + "TestCategory"); + Verify(expectedMessage == testMethodInfo.NotRunnableReason); + } + + public void GetTestMethodInfoShouldReportWarningIfCustomOwnerPropertyIsDefined() + { + // Test that [TestProperty("Owner", "value")] is still blocked + var typeCache = new TypeCache(new ReflectHelper()); + Type type = typeof(DummyTestClassWithTestMethods); MethodInfo methodInfo = type.GetMethod("TestMethodWithOwnerAsCustomProperty")!; var testMethod = new TestMethod(methodInfo.Name, type.FullName!, "A", isAsync: false); var testContext = new TestContextImplementation( @@ -1034,6 +1058,74 @@ public void GetTestMethodInfoShouldReportWarningIfCustomPropertyHasSameNameAsPre Verify(expectedMessage == testMethodInfo.NotRunnableReason); } + public void GetTestMethodInfoShouldReportWarningIfCustomPriorityPropertyIsDefined() + { + // Test that [TestProperty("Priority", "value")] is still blocked + var typeCache = new TypeCache(new ReflectHelper()); + Type type = typeof(DummyTestClassWithTestMethods); + MethodInfo methodInfo = type.GetMethod("TestMethodWithPriorityAsCustomProperty")!; + var testMethod = new TestMethod(methodInfo.Name, type.FullName!, "A", isAsync: false); + var testContext = new TestContextImplementation( + testMethod, + new ThreadSafeStringWriter(null!, "test"), + new Dictionary()); + + TestMethodInfo? testMethodInfo = typeCache.GetTestMethodInfo(testMethod, testContext); + + Verify(testMethodInfo is not null); + string expectedMessage = string.Format( + CultureInfo.InvariantCulture, + "UTA023: {0}: Cannot define predefined property {2} on method {1}.", + methodInfo.DeclaringType!.FullName!, + methodInfo.Name, + "Priority"); + Verify(expectedMessage == testMethodInfo.NotRunnableReason); + } + + public void GetTestMethodInfoShouldAllowActualOwnerAttribute() + { + // Test that the actual OwnerAttribute is allowed + var typeCache = new TypeCache(new ReflectHelper()); + Type type = typeof(DummyTestClassWithTestMethods); + MethodInfo methodInfo = type.GetMethod("TestMethodWithActualOwnerAttribute")!; + var testMethod = new TestMethod(methodInfo.Name, type.FullName!, "A", isAsync: false); + var testContext = new TestContextImplementation( + testMethod, + new ThreadSafeStringWriter(null!, "test"), + new Dictionary()); + + TestMethodInfo? testMethodInfo = typeCache.GetTestMethodInfo(testMethod, testContext); + + Verify(testMethodInfo is not null); + // Owner should be allowed - no NotRunnableReason should be set + Verify(string.IsNullOrEmpty(testMethodInfo.NotRunnableReason)); + // The Owner property should be added to the test context + Verify(testContext.TryGetPropertyValue("Owner", out object? ownerValue)); + Verify(ownerValue?.ToString() == "TestOwner"); + } + + public void GetTestMethodInfoShouldAllowActualPriorityAttribute() + { + // Test that the actual PriorityAttribute is allowed + var typeCache = new TypeCache(new ReflectHelper()); + Type type = typeof(DummyTestClassWithTestMethods); + MethodInfo methodInfo = type.GetMethod("TestMethodWithActualPriorityAttribute")!; + var testMethod = new TestMethod(methodInfo.Name, type.FullName!, "A", isAsync: false); + var testContext = new TestContextImplementation( + testMethod, + new ThreadSafeStringWriter(null!, "test"), + new Dictionary()); + + TestMethodInfo? testMethodInfo = typeCache.GetTestMethodInfo(testMethod, testContext); + + Verify(testMethodInfo is not null); + // Priority should be allowed - no NotRunnableReason should be set + Verify(string.IsNullOrEmpty(testMethodInfo.NotRunnableReason)); + // The Priority property should be added to the test context + Verify(testContext.TryGetPropertyValue("Priority", out object? priorityValue)); + Verify(priorityValue?.ToString() == "1"); + } + public void GetTestMethodInfoShouldReportWarningIfCustomPropertyNameIsEmpty() { // Not using _typeCache here which uses a mocked ReflectHelper which doesn't work well with this test. @@ -1350,6 +1442,30 @@ public void TestMethodWithOwnerAsCustomProperty() { } + [TestMethod] + [TestProperty("TestCategory", "SomeCategory")] + public void TestMethodWithTestCategoryAsCustomProperty() + { + } + + [TestMethod] + [Owner("TestOwner")] + public void TestMethodWithActualOwnerAttribute() + { + } + + [TestMethod] + [Priority(1)] + public void TestMethodWithActualPriorityAttribute() + { + } + + [TestMethod] + [TestProperty("Priority", "2")] + public void TestMethodWithPriorityAsCustomProperty() + { + } + [TestMethod] [TestProperty("", "You")] public void TestMethodWithEmptyCustomPropertyName() From 03424191dd17cbbb6c4095ba8b2804b36a839e44 Mon Sep 17 00:00:00 2001 From: dotnet bot Date: Wed, 18 Jun 2025 09:37:17 +0200 Subject: [PATCH 105/541] Localized file check-in by OneLocBuild Task: Build definition ID 1218: Build ID 2732711 --- .../TestFramework/Resources/xlf/FrameworkMessages.cs.xlf | 2 +- .../TestFramework/Resources/xlf/FrameworkMessages.de.xlf | 2 +- .../TestFramework/Resources/xlf/FrameworkMessages.es.xlf | 2 +- .../TestFramework/Resources/xlf/FrameworkMessages.it.xlf | 2 +- .../TestFramework/Resources/xlf/FrameworkMessages.ko.xlf | 2 +- .../TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf | 2 +- .../TestFramework/Resources/xlf/FrameworkMessages.ru.xlf | 2 +- .../TestFramework/Resources/xlf/FrameworkMessages.tr.xlf | 2 +- .../TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf | 2 +- 9 files changed, 9 insertions(+), 9 deletions(-) diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.cs.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.cs.xlf index 7988770e9a..e9421d1683 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.cs.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.cs.xlf @@ -143,7 +143,7 @@ Skutečnost: {2} Value '{0}' is not within the expected range [{1}, {2}]. {3} - Value '{0}' is not within the expected range [{1}, {2}]. {3} + Hodnota {0} není v očekávaném rozsahu [{1}, {2}]. {3} diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.de.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.de.xlf index 0055572296..29559818d2 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.de.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.de.xlf @@ -143,7 +143,7 @@ Tatsächlich: {2} Value '{0}' is not within the expected range [{1}, {2}]. {3} - Value '{0}' is not within the expected range [{1}, {2}]. {3} + Der Wert „{0}“ liegt nicht im erwarteten Bereich [{1}, {2}]. {3} diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.es.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.es.xlf index c1e47e5e8b..4beb222e8f 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.es.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.es.xlf @@ -143,7 +143,7 @@ Real: {2} Value '{0}' is not within the expected range [{1}, {2}]. {3} - Value '{0}' is not within the expected range [{1}, {2}]. {3} + El valor "{0}" no está dentro del rango esperado [{1}, {2}]. {3} diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.it.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.it.xlf index fef17b3ca8..0104dd3bfc 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.it.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.it.xlf @@ -143,7 +143,7 @@ Effettivo: {2} Value '{0}' is not within the expected range [{1}, {2}]. {3} - Value '{0}' is not within the expected range [{1}, {2}]. {3} + Il valore '{0}' non è compreso nell'intervallo previsto [{1}, {2}]. {3} diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ko.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ko.xlf index c5f9023288..edf05fda06 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ko.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ko.xlf @@ -143,7 +143,7 @@ Actual: {2} Value '{0}' is not within the expected range [{1}, {2}]. {3} - Value '{0}' is not within the expected range [{1}, {2}]. {3} + '{0}' 값이 예상 범위 [{1}, {2}] 내에 있지 않습니다. {3} diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf index ca320a6468..e4c01aa215 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf @@ -143,7 +143,7 @@ Real: {2} Value '{0}' is not within the expected range [{1}, {2}]. {3} - Value '{0}' is not within the expected range [{1}, {2}]. {3} + O valor '{0}' não está dentro do intervalo esperado [{1}, {2}]. {3} diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ru.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ru.xlf index 3babb3c3a7..60330f2af3 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ru.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ru.xlf @@ -143,7 +143,7 @@ Actual: {2} Value '{0}' is not within the expected range [{1}, {2}]. {3} - Value '{0}' is not within the expected range [{1}, {2}]. {3} + Значение "{0}" не находится в пределах ожидаемого диапазона [{1}, {2}]. {3} diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.tr.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.tr.xlf index 59ffe8eb13..187927a7e6 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.tr.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.tr.xlf @@ -143,7 +143,7 @@ Gerçekte olan: {2} Value '{0}' is not within the expected range [{1}, {2}]. {3} - Value '{0}' is not within the expected range [{1}, {2}]. {3} + '{0}' değeri beklenen aralıkta [{1}, {2}] değil. {3} diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf index 3e2131ca8c..7aa9cba997 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf @@ -143,7 +143,7 @@ Actual: {2} Value '{0}' is not within the expected range [{1}, {2}]. {3} - Value '{0}' is not within the expected range [{1}, {2}]. {3} + 值 '{0}' 不在預期的範圍 [{1}, {2}] 內。{3} From eb6fde15fa63cb644479ac0dfb30fb5ca363c69d Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Wed, 18 Jun 2025 09:56:49 +0200 Subject: [PATCH 106/541] Store the actual data to instead of deserializing (#5778) --- .../Discovery/AssemblyEnumerator.cs | 1 + .../Discovery/UnitTestDiscoverer.cs | 12 ++ .../Execution/TestMethodRunner.cs | 2 +- .../Extensions/TestCaseExtensions.cs | 5 + .../ObjectModel/TestMethod.cs | 6 + .../ParameterizedTestTests.cs | 113 +++++++++++++++++- ...ParameterizedTestSerializationIssue2390.cs | 28 +++++ 7 files changed, 165 insertions(+), 2 deletions(-) create mode 100644 test/UnitTests/MSTest.SelfRealExamples.UnitTests/ParameterizedTestSerializationIssue2390.cs diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Discovery/AssemblyEnumerator.cs b/src/Adapter/MSTestAdapter.PlatformServices/Discovery/AssemblyEnumerator.cs index 39a8adf671..1f9e26cc47 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Discovery/AssemblyEnumerator.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Discovery/AssemblyEnumerator.cs @@ -464,6 +464,7 @@ private static bool TryUnfoldITestDataSource(ITestDataSource dataSource, TestDat try { discoveredTest.TestMethod.SerializedData = DataSerializationHelper.Serialize(d); + discoveredTest.TestMethod.ActualData = d; discoveredTest.TestMethod.TestDataSourceIgnoreMessage = testDataSourceIgnoreMessage; discoveredTest.TestMethod.DataType = DynamicDataType.ITestDataSource; } diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Discovery/UnitTestDiscoverer.cs b/src/Adapter/MSTestAdapter.PlatformServices/Discovery/UnitTestDiscoverer.cs index 2de1b9dcb4..79a2d02642 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Discovery/UnitTestDiscoverer.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Discovery/UnitTestDiscoverer.cs @@ -85,6 +85,13 @@ internal virtual void DiscoverTestsInSource( SendTestCases(source, testElements, discoverySink, discoveryContext, logger); } +#pragma warning disable IDE0028 // Collection initialization can be simplified - cannot be done for all TFMs. So suppressing. + private static readonly ConditionalWeakTable TestCaseToDataDictionary = new(); +#pragma warning restore IDE0028 // Collection initialization can be simplified + + internal static bool TryGetActualData(TestCase testCase, [NotNullWhen(true)] out object?[]? actualData) + => TestCaseToDataDictionary.TryGetValue(testCase, out actualData); + internal void SendTestCases(string source, IEnumerable testElements, ITestCaseDiscoverySink discoverySink, IDiscoveryContext? discoveryContext, IMessageLogger logger) { bool shouldCollectSourceInformation = MSTestSettings.RunConfigurationSettings.CollectSourceInformation; @@ -123,6 +130,11 @@ internal void SendTestCases(string source, IEnumerable testElem continue; } + if (testElement.TestMethod.ActualData is { } actualData) + { + TestCaseToDataDictionary.Add(testCase, actualData); + } + if (!hasAnyRunnableTests) { hasAnyRunnableTests = !hasFixtureTraits; diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestMethodRunner.cs b/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestMethodRunner.cs index f62f52fa18..9714daeafe 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestMethodRunner.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestMethodRunner.cs @@ -179,7 +179,7 @@ internal async Task RunTestMethodAsync() return [TestResult.CreateIgnoredResult(_test.TestDataSourceIgnoreMessage)]; } - object?[]? data = DataSerializationHelper.Deserialize(_test.SerializedData); + object?[]? data = _test.ActualData ?? DataSerializationHelper.Deserialize(_test.SerializedData); TestResult[] testResults = await ExecuteTestWithDataSourceAsync(null, data).ConfigureAwait(false); results.AddRange(testResults); } diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Extensions/TestCaseExtensions.cs b/src/Adapter/MSTestAdapter.PlatformServices/Extensions/TestCaseExtensions.cs index 434c6f5f8b..b4f6fc6366 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Extensions/TestCaseExtensions.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Extensions/TestCaseExtensions.cs @@ -86,6 +86,11 @@ internal static UnitTestElement ToUnitTestElement(this TestCase testCase, string testMethod.DataType = dataType; testMethod.SerializedData = data; + if (UnitTestDiscoverer.TryGetActualData(testCase, out object?[]? actualData)) + { + testMethod.ActualData = actualData; + } + testMethod.TestDataSourceIgnoreMessage = testCase.GetPropertyValue(EngineConstants.TestDataSourceIgnoreMessageProperty) as string; } diff --git a/src/Adapter/MSTestAdapter.PlatformServices/ObjectModel/TestMethod.cs b/src/Adapter/MSTestAdapter.PlatformServices/ObjectModel/TestMethod.cs index 3b821899ed..47a5affb94 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/ObjectModel/TestMethod.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/ObjectModel/TestMethod.cs @@ -147,6 +147,12 @@ public string? DeclaringClassFullName /// internal string?[]? SerializedData { get; set; } + // This holds user types that may not be serializable. + // If app domains are enabled, we have no choice other than losing the original data. + // In that case, we fallback to deserializing the SerializedData. + [field: NonSerialized] + internal object?[]? ActualData { get; set; } + /// /// Gets or sets the test data source ignore message. /// diff --git a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/ParameterizedTestTests.cs b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/ParameterizedTestTests.cs index 0a029a6421..1783bf3843 100644 --- a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/ParameterizedTestTests.cs +++ b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/ParameterizedTestTests.cs @@ -12,6 +12,7 @@ public class ParameterizedTestTests : AcceptanceTestBase await UsingDataRowThatDoesNotRoundTripUsingDataContractJsonSerializerCore(currentTfm, "AppDomainEnabled"); + + [TestMethod] + [DynamicData(nameof(TargetFrameworks.AllForDynamicData), typeof(TargetFrameworks))] + public async Task UsingDataRowThatDoesNotRoundTripUsingDataContractJsonSerializerWithoutAppDomains(string currentTfm) + => await UsingDataRowThatDoesNotRoundTripUsingDataContractJsonSerializerCore(currentTfm, "AppDomainDisabled"); + + private static async Task UsingDataRowThatDoesNotRoundTripUsingDataContractJsonSerializerCore(string currentTfm, string runSettings) + { + var testHost = TestHost.LocateFrom(AssetFixture.GetAssetPath(DataRowAssetName), DataRowAssetName, currentTfm); + + TestHostResult testHostResult = await testHost.ExecuteAsync($"--settings {runSettings}.runsettings --filter ClassName=ParameterizedTestSerializationIssue2390"); + + testHostResult.AssertExitCodeIs(ExitCodes.Success); + testHostResult.AssertOutputContainsSummary(failed: 0, passed: 3, skipped: 0); + } + private static async Task RunTestsAsync(string currentTfm, string assetName, bool? isEmptyDataInconclusive) { var testHost = TestHost.LocateFrom(AssetFixture.GetAssetPath(assetName), assetName, currentTfm); @@ -163,7 +184,97 @@ public sealed class TestAssetFixture() : TestAssetFixtureBase(AcceptanceFixture. SourceCodeDataSource .PatchTargetFrameworks(TargetFrameworks.All) .PatchCodeWithReplace("$MSTestVersion$", MSTestVersion)); + yield return (DataRowAssetName, DataRowAssetName, + SourceCodeDataRow + .PatchTargetFrameworks(TargetFrameworks.All) + .PatchCodeWithReplace("$MSTestVersion$", MSTestVersion)); + } + + private const string SourceCodeDataRow = """ +#file DataRowTests.csproj + + + + Exe + true + $TargetFrameworks$ + preview + + + + + + + + + + PreserveNewest + + + + + + PreserveNewest + + + + + +#file AppDomainEnabled.runsettings + + + + + false + + + +#file AppDomainDisabled.runsettings + + + + true + + + +#file UnitTest1.cs + +using System; +using System.Collections.Generic; +using System.Linq; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +// Test for https://github.com/microsoft/testfx/issues/2390 +[TestClass] +public class ParameterizedTestSerializationIssue2390 +{ + [TestMethod] + [DataRow((byte)0, new object[] { (byte)0 })] + [DataRow((short)0, new object[] { (short)0 })] + [DataRow(0L, new object[] { 0L })] + public void CheckNestedInputTypes(object expected, object nested) + { + object[] array = (object[])nested; + object actual = Assert.ContainsSingle(array); + +#if NETFRAMEWORK + var appDomainEnabled = Environment.GetCommandLineArgs().Contains("AppDomainEnabled.runsettings"); + if (appDomainEnabled) + { + // Buggy behavior, because of app domains. + Assert.AreEqual(typeof(int), actual.GetType(), AppDomain.CurrentDomain.FriendlyName); } + else +#endif + { + Assert.AreEqual(expected.GetType(), actual.GetType(), AppDomain.CurrentDomain.FriendlyName); + Assert.AreEqual(expected, actual); + } + } +} + +"""; private const string SourceCodeDynamicData = """ #file DynamicData.csproj @@ -181,7 +292,7 @@ public sealed class TestAssetFixture() : TestAssetFixtureBase(AcceptanceFixture. - + PreserveNewest diff --git a/test/UnitTests/MSTest.SelfRealExamples.UnitTests/ParameterizedTestSerializationIssue2390.cs b/test/UnitTests/MSTest.SelfRealExamples.UnitTests/ParameterizedTestSerializationIssue2390.cs new file mode 100644 index 0000000000..073cc54902 --- /dev/null +++ b/test/UnitTests/MSTest.SelfRealExamples.UnitTests/ParameterizedTestSerializationIssue2390.cs @@ -0,0 +1,28 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace MSTest.SelfRealExamples.UnitTests; + +// Test for https://github.com/microsoft/testfx/issues/2390 +[TestClass] +public class ParameterizedTestSerializationIssue2390 +{ + [TestMethod] + [DataRow((byte)0, new object[] { (byte)0 })] + [DataRow((short)0, new object[] { (short)0 })] + [DataRow(0L, new object[] { 0L })] + public void CheckNestedInputTypes(object expected, object nested) + { + object[] array = (object[])nested; + object actual = Assert.ContainsSingle(array); +#if NETFRAMEWORK + // Buggy behavior, because of app domains. + Assert.AreEqual(typeof(int), actual.GetType()); +#else + Assert.AreEqual(expected.GetType(), actual.GetType()); + Assert.AreEqual(expected, actual); +#endif + } +} From 18078adddeacee20ef66d094b37f17b8817b348e Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Wed, 18 Jun 2025 10:15:41 +0200 Subject: [PATCH 107/541] Cleanup RunSettingsPatcher (#5799) --- .../ObjectModel/RunSettingsPatcher.cs | 6 ------ 1 file changed, 6 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/RunSettingsPatcher.cs b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/RunSettingsPatcher.cs index 97fa572220..75ec2efa0e 100644 --- a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/RunSettingsPatcher.cs +++ b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/RunSettingsPatcher.cs @@ -49,12 +49,6 @@ private static XDocument PatchSettingsWithDefaults(string? runSettingsXml, bool runSettingsElement.AddFirst(runConfigurationElement); } - if (runConfigurationElement.Element("DisableAppDomain") is null) - { - AddPatchingCommentIfNeeded(runConfigurationElement, ref isPatchingCommentAdded); - runConfigurationElement.Add(new XElement("DisableAppDomain", false)); - } - if (runConfigurationElement.Element("DesignMode") is null) { AddPatchingCommentIfNeeded(runConfigurationElement, ref isPatchingCommentAdded); From bd581d6bc2d351db8c693d2e8926b888c0fa23e0 Mon Sep 17 00:00:00 2001 From: Copilot <198982749+Copilot@users.noreply.github.com> Date: Wed, 18 Jun 2025 10:20:30 +0200 Subject: [PATCH 108/541] Add comparison Assert APIs (IsGreaterThan, IsLessThan, IsPositive, IsNegative) (#5790) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: Evangelink <11340282+Evangelink@users.noreply.github.com> Co-authored-by: Amaury Levé --- .../Assertions/Assert.IComparable.cs | 604 ++++++++++++++++++ .../PublicAPI/PublicAPI.Unshipped.txt | 18 + .../Resources/FrameworkMessages.Designer.cs | 54 ++ .../Resources/FrameworkMessages.resx | 18 + .../Resources/xlf/FrameworkMessages.cs.xlf | 30 + .../Resources/xlf/FrameworkMessages.de.xlf | 30 + .../Resources/xlf/FrameworkMessages.es.xlf | 30 + .../Resources/xlf/FrameworkMessages.fr.xlf | 30 + .../Resources/xlf/FrameworkMessages.it.xlf | 30 + .../Resources/xlf/FrameworkMessages.ja.xlf | 30 + .../Resources/xlf/FrameworkMessages.ko.xlf | 30 + .../Resources/xlf/FrameworkMessages.pl.xlf | 30 + .../Resources/xlf/FrameworkMessages.pt-BR.xlf | 30 + .../Resources/xlf/FrameworkMessages.ru.xlf | 30 + .../Resources/xlf/FrameworkMessages.tr.xlf | 30 + .../xlf/FrameworkMessages.zh-Hans.xlf | 30 + .../xlf/FrameworkMessages.zh-Hant.xlf | 30 + .../AssertTests.IComparableTests.cs | 377 +++++++++++ 18 files changed, 1461 insertions(+) create mode 100644 src/TestFramework/TestFramework/Assertions/Assert.IComparable.cs create mode 100644 test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.IComparableTests.cs diff --git a/src/TestFramework/TestFramework/Assertions/Assert.IComparable.cs b/src/TestFramework/TestFramework/Assertions/Assert.IComparable.cs new file mode 100644 index 0000000000..84b3ac4051 --- /dev/null +++ b/src/TestFramework/TestFramework/Assertions/Assert.IComparable.cs @@ -0,0 +1,604 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +namespace Microsoft.VisualStudio.TestTools.UnitTesting; + +/// +/// A collection of helper classes to test various conditions within +/// unit tests. If the condition being tested is not met, an exception +/// is thrown. +/// +public sealed partial class Assert +{ + #region IsGreaterThan + + /// + /// Tests whether the value is greater than the lower bound and throws an exception + /// if it is not. + /// + /// + /// The type of values to compare. + /// + /// + /// The lower bound value that the value should exceed. + /// + /// + /// The value to compare. This is the value produced by the code under test. + /// + /// + /// Thrown if is not greater than . + /// + public static void IsGreaterThan(T lowerBound, T value) + where T : IComparable + => IsGreaterThan(lowerBound, value, string.Empty, null); + + /// + /// Tests whether the value is greater than the lower bound and throws an exception + /// if it is not. + /// + /// + /// The type of values to compare. + /// + /// + /// The lower bound value that the value should exceed. + /// + /// + /// The value to compare. This is the value produced by the code under test. + /// + /// + /// The message to include in the exception when + /// is not greater than . The message is shown in + /// test results. + /// + /// + /// Thrown if is not greater than . + /// + public static void IsGreaterThan(T lowerBound, T value, string? message) + where T : IComparable + => IsGreaterThan(lowerBound, value, message, null); + + /// + /// Tests whether the value is greater than the lower bound and throws an exception + /// if it is not. + /// + /// + /// The type of values to compare. + /// + /// + /// The lower bound value that the value should exceed. + /// + /// + /// The value to compare. This is the value produced by the code under test. + /// + /// + /// The message to include in the exception when + /// is not greater than . The message is shown in + /// test results. + /// + /// + /// An array of parameters to use when formatting . + /// + /// + /// Thrown if is not greater than . + /// + public static void IsGreaterThan(T lowerBound, T value, [StringSyntax(StringSyntaxAttribute.CompositeFormat)] string? message, params object?[]? parameters) + where T : IComparable + { + if (value.CompareTo(lowerBound) > 0) + { + return; + } + + string userMessage = BuildUserMessage(message, parameters); + ThrowAssertIsGreaterThanFailed(lowerBound, value, userMessage); + } + + #endregion // IsGreaterThan + + #region IsGreaterThanOrEqualTo + + /// + /// Tests whether the value is greater than or equal to the lower bound and throws an exception + /// if it is not. + /// + /// + /// The type of values to compare. + /// + /// + /// The lower bound value that the value should meet or exceed. + /// + /// + /// The value to compare. This is the value produced by the code under test. + /// + /// + /// Thrown if is not greater than or equal to . + /// + public static void IsGreaterThanOrEqualTo(T lowerBound, T value) + where T : IComparable + => IsGreaterThanOrEqualTo(lowerBound, value, string.Empty, null); + + /// + /// Tests whether the value is greater than or equal to the lower bound and throws an exception + /// if it is not. + /// + /// + /// The type of values to compare. + /// + /// + /// The lower bound value that the value should meet or exceed. + /// + /// + /// The value to compare. This is the value produced by the code under test. + /// + /// + /// The message to include in the exception when + /// is not greater than or equal to . The message is shown in + /// test results. + /// + /// + /// Thrown if is not greater than or equal to . + /// + public static void IsGreaterThanOrEqualTo(T lowerBound, T value, string? message) + where T : IComparable + => IsGreaterThanOrEqualTo(lowerBound, value, message, null); + + /// + /// Tests whether the value is greater than or equal to the lower bound and throws an exception + /// if it is not. + /// + /// + /// The type of values to compare. + /// + /// + /// The lower bound value that the value should meet or exceed. + /// + /// + /// The value to compare. This is the value produced by the code under test. + /// + /// + /// The message to include in the exception when + /// is not greater than or equal to . The message is shown in + /// test results. + /// + /// + /// An array of parameters to use when formatting . + /// + /// + /// Thrown if is not greater than or equal to . + /// + public static void IsGreaterThanOrEqualTo(T lowerBound, T value, [StringSyntax(StringSyntaxAttribute.CompositeFormat)] string? message, params object?[]? parameters) + where T : IComparable + { + if (value.CompareTo(lowerBound) >= 0) + { + return; + } + + string userMessage = BuildUserMessage(message, parameters); + ThrowAssertIsGreaterThanOrEqualToFailed(lowerBound, value, userMessage); + } + + #endregion // IsGreaterThanOrEqualTo + + #region IsLessThan + + /// + /// Tests whether the value is less than the upper bound and throws an exception + /// if it is not. + /// + /// + /// The type of values to compare. + /// + /// + /// The upper bound value that the value should be less than. + /// + /// + /// The value to compare. This is the value produced by the code under test. + /// + /// + /// Thrown if is not less than . + /// + public static void IsLessThan(T upperBound, T value) + where T : IComparable + => IsLessThan(upperBound, value, string.Empty, null); + + /// + /// Tests whether the value is less than the upper bound and throws an exception + /// if it is not. + /// + /// + /// The type of values to compare. + /// + /// + /// The upper bound value that the value should be less than. + /// + /// + /// The value to compare. This is the value produced by the code under test. + /// + /// + /// The message to include in the exception when + /// is not less than . The message is shown in + /// test results. + /// + /// + /// Thrown if is not less than . + /// + public static void IsLessThan(T upperBound, T value, string? message) + where T : IComparable + => IsLessThan(upperBound, value, message, null); + + /// + /// Tests whether the value is less than the upper bound and throws an exception + /// if it is not. + /// + /// + /// The type of values to compare. + /// + /// + /// The upper bound value that the value should be less than. + /// + /// + /// The value to compare. This is the value produced by the code under test. + /// + /// + /// The message to include in the exception when + /// is not less than . The message is shown in + /// test results. + /// + /// + /// An array of parameters to use when formatting . + /// + /// + /// Thrown if is not less than . + /// + public static void IsLessThan(T upperBound, T value, [StringSyntax(StringSyntaxAttribute.CompositeFormat)] string? message, params object?[]? parameters) + where T : IComparable + { + if (value.CompareTo(upperBound) < 0) + { + return; + } + + string userMessage = BuildUserMessage(message, parameters); + ThrowAssertIsLessThanFailed(upperBound, value, userMessage); + } + + #endregion // IsLessThan + + #region IsLessThanOrEqualTo + + /// + /// Tests whether the value is less than or equal to the upper bound and throws an exception + /// if it is not. + /// + /// + /// The type of values to compare. + /// + /// + /// The upper bound value that the value should not exceed. + /// + /// + /// The value to compare. This is the value produced by the code under test. + /// + /// + /// Thrown if is not less than or equal to . + /// + public static void IsLessThanOrEqualTo(T upperBound, T value) + where T : IComparable + => IsLessThanOrEqualTo(upperBound, value, string.Empty, null); + + /// + /// Tests whether the value is less than or equal to the upper bound and throws an exception + /// if it is not. + /// + /// + /// The type of values to compare. + /// + /// + /// The upper bound value that the value should not exceed. + /// + /// + /// The value to compare. This is the value produced by the code under test. + /// + /// + /// The message to include in the exception when + /// is not less than or equal to . The message is shown in + /// test results. + /// + /// + /// Thrown if is not less than or equal to . + /// + public static void IsLessThanOrEqualTo(T upperBound, T value, string? message) + where T : IComparable + => IsLessThanOrEqualTo(upperBound, value, message, null); + + /// + /// Tests whether the value is less than or equal to the upper bound and throws an exception + /// if it is not. + /// + /// + /// The type of values to compare. + /// + /// + /// The upper bound value that the value should not exceed. + /// + /// + /// The value to compare. This is the value produced by the code under test. + /// + /// + /// The message to include in the exception when + /// is not less than or equal to . The message is shown in + /// test results. + /// + /// + /// An array of parameters to use when formatting . + /// + /// + /// Thrown if is not less than or equal to . + /// + public static void IsLessThanOrEqualTo(T upperBound, T value, [StringSyntax(StringSyntaxAttribute.CompositeFormat)] string? message, params object?[]? parameters) + where T : IComparable + { + if (value.CompareTo(upperBound) <= 0) + { + return; + } + + string userMessage = BuildUserMessage(message, parameters); + ThrowAssertIsLessThanOrEqualToFailed(upperBound, value, userMessage); + } + + #endregion // IsLessThanOrEqualTo + + #region IsPositive + + /// + /// Tests whether the specified value is positive and throws an exception + /// if it is not. + /// + /// + /// The type of value to test. + /// + /// + /// The value to test. + /// + /// + /// Thrown if is not positive. + /// + public static void IsPositive(T value) + where T : struct, IComparable + => IsPositive(value, string.Empty, null); + + /// + /// Tests whether the specified value is positive and throws an exception + /// if it is not. + /// + /// + /// The type of value to test. + /// + /// + /// The value to test. + /// + /// + /// The message to include in the exception when + /// is not positive. The message is shown in test results. + /// + /// + /// Thrown if is not positive. + /// + public static void IsPositive(T value, string? message) + where T : struct, IComparable + => IsPositive(value, message, null); + + /// + /// Tests whether the specified value is positive and throws an exception + /// if it is not. + /// + /// + /// The type of value to test. + /// + /// + /// The value to test. + /// + /// + /// The message to include in the exception when + /// is not positive. The message is shown in test results. + /// + /// + /// An array of parameters to use when formatting . + /// + /// + /// Thrown if is not positive. + /// + public static void IsPositive(T value, [StringSyntax(StringSyntaxAttribute.CompositeFormat)] string? message, params object?[]? parameters) + where T : struct, IComparable + { + var zero = default(T); + + // Handle special case for floating point NaN values + if (value is float floatValue && float.IsNaN(floatValue)) + { + string userMessage = BuildUserMessage(message, parameters); + ThrowAssertIsPositiveFailed(value, userMessage); + return; + } + + if (value is double doubleValue && double.IsNaN(doubleValue)) + { + string userMessage = BuildUserMessage(message, parameters); + ThrowAssertIsPositiveFailed(value, userMessage); + return; + } + + if (value.CompareTo(zero) > 0) + { + return; + } + + string userMessage2 = BuildUserMessage(message, parameters); + ThrowAssertIsPositiveFailed(value, userMessage2); + } + + #endregion // IsPositive + + #region IsNegative + + /// + /// Tests whether the specified value is negative and throws an exception + /// if it is not. + /// + /// + /// The type of value to test. + /// + /// + /// The value to test. + /// + /// + /// Thrown if is not negative. + /// + public static void IsNegative(T value) + where T : struct, IComparable + => IsNegative(value, string.Empty, null); + + /// + /// Tests whether the specified value is negative and throws an exception + /// if it is not. + /// + /// + /// The type of value to test. + /// + /// + /// The value to test. + /// + /// + /// The message to include in the exception when + /// is not negative. The message is shown in test results. + /// + /// + /// Thrown if is not negative. + /// + public static void IsNegative(T value, string? message) + where T : struct, IComparable + => IsNegative(value, message, null); + + /// + /// Tests whether the specified value is negative and throws an exception + /// if it is not. + /// + /// + /// The type of value to test. + /// + /// + /// The value to test. + /// + /// + /// The message to include in the exception when + /// is not negative. The message is shown in test results. + /// + /// + /// An array of parameters to use when formatting . + /// + /// + /// Thrown if is not negative. + /// + public static void IsNegative(T value, [StringSyntax(StringSyntaxAttribute.CompositeFormat)] string? message, params object?[]? parameters) + where T : struct, IComparable + { + var zero = default(T); + + // Handle special case for floating point NaN values + if (value is float floatValue && float.IsNaN(floatValue)) + { + string userMessage = BuildUserMessage(message, parameters); + ThrowAssertIsNegativeFailed(value, userMessage); + return; + } + + if (value is double doubleValue && double.IsNaN(doubleValue)) + { + string userMessage = BuildUserMessage(message, parameters); + ThrowAssertIsNegativeFailed(value, userMessage); + return; + } + + if (value.CompareTo(zero) < 0) + { + return; + } + + string userMessage2 = BuildUserMessage(message, parameters); + ThrowAssertIsNegativeFailed(value, userMessage2); + } + + #endregion // IsNegative + + [DoesNotReturn] + private static void ThrowAssertIsGreaterThanFailed(T lowerBound, T value, string userMessage) + { + string finalMessage = string.Format( + CultureInfo.CurrentCulture, + FrameworkMessages.IsGreaterThanFailMsg, + userMessage, + ReplaceNulls(lowerBound), + ReplaceNulls(value)); + ThrowAssertFailed("Assert.IsGreaterThan", finalMessage); + } + + [DoesNotReturn] + private static void ThrowAssertIsGreaterThanOrEqualToFailed(T lowerBound, T value, string userMessage) + { + string finalMessage = string.Format( + CultureInfo.CurrentCulture, + FrameworkMessages.IsGreaterThanOrEqualToFailMsg, + userMessage, + ReplaceNulls(lowerBound), + ReplaceNulls(value)); + ThrowAssertFailed("Assert.IsGreaterThanOrEqualTo", finalMessage); + } + + [DoesNotReturn] + private static void ThrowAssertIsLessThanFailed(T upperBound, T value, string userMessage) + { + string finalMessage = string.Format( + CultureInfo.CurrentCulture, + FrameworkMessages.IsLessThanFailMsg, + userMessage, + ReplaceNulls(upperBound), + ReplaceNulls(value)); + ThrowAssertFailed("Assert.IsLessThan", finalMessage); + } + + [DoesNotReturn] + private static void ThrowAssertIsLessThanOrEqualToFailed(T upperBound, T value, string userMessage) + { + string finalMessage = string.Format( + CultureInfo.CurrentCulture, + FrameworkMessages.IsLessThanOrEqualToFailMsg, + userMessage, + ReplaceNulls(upperBound), + ReplaceNulls(value)); + ThrowAssertFailed("Assert.IsLessThanOrEqualTo", finalMessage); + } + + [DoesNotReturn] + private static void ThrowAssertIsPositiveFailed(T value, string userMessage) + { + string finalMessage = string.Format( + CultureInfo.CurrentCulture, + FrameworkMessages.IsPositiveFailMsg, + userMessage, + ReplaceNulls(value)); + ThrowAssertFailed("Assert.IsPositive", finalMessage); + } + + [DoesNotReturn] + private static void ThrowAssertIsNegativeFailed(T value, string userMessage) + { + string finalMessage = string.Format( + CultureInfo.CurrentCulture, + FrameworkMessages.IsNegativeFailMsg, + userMessage, + ReplaceNulls(value)); + ThrowAssertFailed("Assert.IsNegative", finalMessage); + } +} diff --git a/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Unshipped.txt b/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Unshipped.txt index 8e931d54f2..064a648383 100644 --- a/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Unshipped.txt +++ b/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Unshipped.txt @@ -1,10 +1,28 @@ #nullable enable Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AssertNonStrictThrowsInterpolatedStringHandler.AssertNonStrictThrowsInterpolatedStringHandler(int literalLength, int formattedCount, System.Func! action, out bool shouldAppend) -> void Microsoft.VisualStudio.TestTools.UnitTesting.ConditionBaseAttribute.Mode.get -> Microsoft.VisualStudio.TestTools.UnitTesting.ConditionMode +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsGreaterThan(T lowerBound, T value) -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsGreaterThan(T lowerBound, T value, string? message) -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsGreaterThan(T lowerBound, T value, string? message, params object?[]? parameters) -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsGreaterThanOrEqualTo(T lowerBound, T value) -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsGreaterThanOrEqualTo(T lowerBound, T value, string? message) -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsGreaterThanOrEqualTo(T lowerBound, T value, string? message, params object?[]? parameters) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsInRange(T minValue, T maxValue, T value) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsInRange(T minValue, T maxValue, T value, string? message) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsInRange(T minValue, T maxValue, T value, string? message, params object?[]? parameters) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.ContainsSingle(System.Func! predicate, System.Collections.Generic.IEnumerable! collection) -> T static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.ContainsSingle(System.Func! predicate, System.Collections.Generic.IEnumerable! collection, string? message) -> T static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.ContainsSingle(System.Func! predicate, System.Collections.Generic.IEnumerable! collection, string? message, params object?[]? parameters) -> T +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsLessThan(T upperBound, T value) -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsLessThan(T upperBound, T value, string? message) -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsLessThan(T upperBound, T value, string? message, params object?[]? parameters) -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsLessThanOrEqualTo(T upperBound, T value) -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsLessThanOrEqualTo(T upperBound, T value, string? message) -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsLessThanOrEqualTo(T upperBound, T value, string? message, params object?[]? parameters) -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsNegative(T value) -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsNegative(T value, string? message) -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsNegative(T value, string? message, params object?[]? parameters) -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsPositive(T value) -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsPositive(T value, string? message) -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsPositive(T value, string? message, params object?[]? parameters) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.Throws(System.Func! action, ref Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AssertNonStrictThrowsInterpolatedStringHandler message) -> TException! diff --git a/src/TestFramework/TestFramework/Resources/FrameworkMessages.Designer.cs b/src/TestFramework/TestFramework/Resources/FrameworkMessages.Designer.cs index 983b2d9341..346096f271 100644 --- a/src/TestFramework/TestFramework/Resources/FrameworkMessages.Designer.cs +++ b/src/TestFramework/TestFramework/Resources/FrameworkMessages.Designer.cs @@ -583,6 +583,60 @@ internal static string UTF_TestMethodWrongExceptionDerivedAllowed { } } + /// + /// Looks up a localized string similar to Expected value <{1}> to be greater than actual value <{2}>. {0}. + /// + internal static string IsGreaterThanFailMsg { + get { + return ResourceManager.GetString("IsGreaterThanFailMsg", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Expected value <{1}> to be greater than or equal to actual value <{2}>. {0}. + /// + internal static string IsGreaterThanOrEqualToFailMsg { + get { + return ResourceManager.GetString("IsGreaterThanOrEqualToFailMsg", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Expected value <{1}> to be less than actual value <{2}>. {0}. + /// + internal static string IsLessThanFailMsg { + get { + return ResourceManager.GetString("IsLessThanFailMsg", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Expected value <{1}> to be less than or equal to actual value <{2}>. {0}. + /// + internal static string IsLessThanOrEqualToFailMsg { + get { + return ResourceManager.GetString("IsLessThanOrEqualToFailMsg", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Expected value <{1}> to be negative. {0}. + /// + internal static string IsNegativeFailMsg { + get { + return ResourceManager.GetString("IsNegativeFailMsg", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Expected value <{1}> to be positive. {0}. + /// + internal static string IsPositiveFailMsg { + get { + return ResourceManager.GetString("IsPositiveFailMsg", resourceCulture); + } + } + /// /// Looks up a localized string similar to Expected exception type:<{1}>. Actual exception type:<{2}>. {0}. /// diff --git a/src/TestFramework/TestFramework/Resources/FrameworkMessages.resx b/src/TestFramework/TestFramework/Resources/FrameworkMessages.resx index 5ae35512eb..9df59c95fa 100644 --- a/src/TestFramework/TestFramework/Resources/FrameworkMessages.resx +++ b/src/TestFramework/TestFramework/Resources/FrameworkMessages.resx @@ -305,4 +305,22 @@ Actual: {2} String '{0}' does contain string '{1}'. {2}. + + Actual value <{2}> is not greater than expected value <{1}>. {0} + + + Actual value <{2}> is not greater than or equal to expected value <{1}>. {0} + + + Actual value <{2}> is not less than expected value <{1}>. {0} + + + Actual value <{2}> is not less than or equal to expected value <{1}>. {0} + + + Expected value <{1}> to be positive. {0} + + + Expected value <{1}> to be negative. {0} + \ No newline at end of file diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.cs.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.cs.xlf index e9421d1683..053e32f458 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.cs.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.cs.xlf @@ -315,6 +315,36 @@ Skutečnost: {2} - {1} fully qualified class name like "Microsoft.UI.Xaml.Application" + + Actual value <{2}> is not greater than expected value <{1}>. {0} + Actual value <{2}> is not greater than expected value <{1}>. {0} + + + + Actual value <{2}> is not greater than or equal to expected value <{1}>. {0} + Actual value <{2}> is not greater than or equal to expected value <{1}>. {0} + + + + Actual value <{2}> is not less than expected value <{1}>. {0} + Actual value <{2}> is not less than expected value <{1}>. {0} + + + + Actual value <{2}> is not less than or equal to expected value <{1}>. {0} + Actual value <{2}> is not less than or equal to expected value <{1}>. {0} + + + + Expected value <{1}> to be positive. {0} + Expected value <{1}> to be positive. {0} + + + + Expected value <{1}> to be negative. {0} + Expected value <{1}> to be negative. {0} + + \ No newline at end of file diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.de.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.de.xlf index 29559818d2..8306786e8c 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.de.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.de.xlf @@ -315,6 +315,36 @@ Tatsächlich: {2} - {1} fully qualified class name like "Microsoft.UI.Xaml.Application" + + Actual value <{2}> is not greater than expected value <{1}>. {0} + Actual value <{2}> is not greater than expected value <{1}>. {0} + + + + Actual value <{2}> is not greater than or equal to expected value <{1}>. {0} + Actual value <{2}> is not greater than or equal to expected value <{1}>. {0} + + + + Actual value <{2}> is not less than expected value <{1}>. {0} + Actual value <{2}> is not less than expected value <{1}>. {0} + + + + Actual value <{2}> is not less than or equal to expected value <{1}>. {0} + Actual value <{2}> is not less than or equal to expected value <{1}>. {0} + + + + Expected value <{1}> to be positive. {0} + Expected value <{1}> to be positive. {0} + + + + Expected value <{1}> to be negative. {0} + Expected value <{1}> to be negative. {0} + + \ No newline at end of file diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.es.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.es.xlf index 4beb222e8f..e81069cbc7 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.es.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.es.xlf @@ -315,6 +315,36 @@ Real: {2} - {1} fully qualified class name like "Microsoft.UI.Xaml.Application" + + Actual value <{2}> is not greater than expected value <{1}>. {0} + Actual value <{2}> is not greater than expected value <{1}>. {0} + + + + Actual value <{2}> is not greater than or equal to expected value <{1}>. {0} + Actual value <{2}> is not greater than or equal to expected value <{1}>. {0} + + + + Actual value <{2}> is not less than expected value <{1}>. {0} + Actual value <{2}> is not less than expected value <{1}>. {0} + + + + Actual value <{2}> is not less than or equal to expected value <{1}>. {0} + Actual value <{2}> is not less than or equal to expected value <{1}>. {0} + + + + Expected value <{1}> to be positive. {0} + Expected value <{1}> to be positive. {0} + + + + Expected value <{1}> to be negative. {0} + Expected value <{1}> to be negative. {0} + + \ No newline at end of file diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.fr.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.fr.xlf index 8e677f7cfb..1084bf3f8c 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.fr.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.fr.xlf @@ -315,6 +315,36 @@ Réel : {2} - {1} fully qualified class name like "Microsoft.UI.Xaml.Application" + + Actual value <{2}> is not greater than expected value <{1}>. {0} + Actual value <{2}> is not greater than expected value <{1}>. {0} + + + + Actual value <{2}> is not greater than or equal to expected value <{1}>. {0} + Actual value <{2}> is not greater than or equal to expected value <{1}>. {0} + + + + Actual value <{2}> is not less than expected value <{1}>. {0} + Actual value <{2}> is not less than expected value <{1}>. {0} + + + + Actual value <{2}> is not less than or equal to expected value <{1}>. {0} + Actual value <{2}> is not less than or equal to expected value <{1}>. {0} + + + + Expected value <{1}> to be positive. {0} + Expected value <{1}> to be positive. {0} + + + + Expected value <{1}> to be negative. {0} + Expected value <{1}> to be negative. {0} + + \ No newline at end of file diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.it.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.it.xlf index 0104dd3bfc..6c38f092db 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.it.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.it.xlf @@ -315,6 +315,36 @@ Effettivo: {2} - {1} fully qualified class name like "Microsoft.UI.Xaml.Application" + + Actual value <{2}> is not greater than expected value <{1}>. {0} + Actual value <{2}> is not greater than expected value <{1}>. {0} + + + + Actual value <{2}> is not greater than or equal to expected value <{1}>. {0} + Actual value <{2}> is not greater than or equal to expected value <{1}>. {0} + + + + Actual value <{2}> is not less than expected value <{1}>. {0} + Actual value <{2}> is not less than expected value <{1}>. {0} + + + + Actual value <{2}> is not less than or equal to expected value <{1}>. {0} + Actual value <{2}> is not less than or equal to expected value <{1}>. {0} + + + + Expected value <{1}> to be positive. {0} + Expected value <{1}> to be positive. {0} + + + + Expected value <{1}> to be negative. {0} + Expected value <{1}> to be negative. {0} + + \ No newline at end of file diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ja.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ja.xlf index daa41f4e26..bb594294f6 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ja.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ja.xlf @@ -315,6 +315,36 @@ Actual: {2} - {1} fully qualified class name like "Microsoft.UI.Xaml.Application" + + Actual value <{2}> is not greater than expected value <{1}>. {0} + Actual value <{2}> is not greater than expected value <{1}>. {0} + + + + Actual value <{2}> is not greater than or equal to expected value <{1}>. {0} + Actual value <{2}> is not greater than or equal to expected value <{1}>. {0} + + + + Actual value <{2}> is not less than expected value <{1}>. {0} + Actual value <{2}> is not less than expected value <{1}>. {0} + + + + Actual value <{2}> is not less than or equal to expected value <{1}>. {0} + Actual value <{2}> is not less than or equal to expected value <{1}>. {0} + + + + Expected value <{1}> to be positive. {0} + Expected value <{1}> to be positive. {0} + + + + Expected value <{1}> to be negative. {0} + Expected value <{1}> to be negative. {0} + + \ No newline at end of file diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ko.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ko.xlf index edf05fda06..fa13dee467 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ko.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ko.xlf @@ -315,6 +315,36 @@ Actual: {2} - {1} fully qualified class name like "Microsoft.UI.Xaml.Application" + + Actual value <{2}> is not greater than expected value <{1}>. {0} + Actual value <{2}> is not greater than expected value <{1}>. {0} + + + + Actual value <{2}> is not greater than or equal to expected value <{1}>. {0} + Actual value <{2}> is not greater than or equal to expected value <{1}>. {0} + + + + Actual value <{2}> is not less than expected value <{1}>. {0} + Actual value <{2}> is not less than expected value <{1}>. {0} + + + + Actual value <{2}> is not less than or equal to expected value <{1}>. {0} + Actual value <{2}> is not less than or equal to expected value <{1}>. {0} + + + + Expected value <{1}> to be positive. {0} + Expected value <{1}> to be positive. {0} + + + + Expected value <{1}> to be negative. {0} + Expected value <{1}> to be negative. {0} + + \ No newline at end of file diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pl.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pl.xlf index d809fd5bf9..26106ca118 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pl.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pl.xlf @@ -315,6 +315,36 @@ Rzeczywiste: {2} - {1} fully qualified class name like "Microsoft.UI.Xaml.Application" + + Actual value <{2}> is not greater than expected value <{1}>. {0} + Actual value <{2}> is not greater than expected value <{1}>. {0} + + + + Actual value <{2}> is not greater than or equal to expected value <{1}>. {0} + Actual value <{2}> is not greater than or equal to expected value <{1}>. {0} + + + + Actual value <{2}> is not less than expected value <{1}>. {0} + Actual value <{2}> is not less than expected value <{1}>. {0} + + + + Actual value <{2}> is not less than or equal to expected value <{1}>. {0} + Actual value <{2}> is not less than or equal to expected value <{1}>. {0} + + + + Expected value <{1}> to be positive. {0} + Expected value <{1}> to be positive. {0} + + + + Expected value <{1}> to be negative. {0} + Expected value <{1}> to be negative. {0} + + \ No newline at end of file diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf index e4c01aa215..5b9618f714 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf @@ -315,6 +315,36 @@ Real: {2} - {1} fully qualified class name like "Microsoft.UI.Xaml.Application" + + Actual value <{2}> is not greater than expected value <{1}>. {0} + Actual value <{2}> is not greater than expected value <{1}>. {0} + + + + Actual value <{2}> is not greater than or equal to expected value <{1}>. {0} + Actual value <{2}> is not greater than or equal to expected value <{1}>. {0} + + + + Actual value <{2}> is not less than expected value <{1}>. {0} + Actual value <{2}> is not less than expected value <{1}>. {0} + + + + Actual value <{2}> is not less than or equal to expected value <{1}>. {0} + Actual value <{2}> is not less than or equal to expected value <{1}>. {0} + + + + Expected value <{1}> to be positive. {0} + Expected value <{1}> to be positive. {0} + + + + Expected value <{1}> to be negative. {0} + Expected value <{1}> to be negative. {0} + + \ No newline at end of file diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ru.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ru.xlf index 60330f2af3..49354000c7 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ru.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ru.xlf @@ -315,6 +315,36 @@ Actual: {2} - {1} fully qualified class name like "Microsoft.UI.Xaml.Application" + + Actual value <{2}> is not greater than expected value <{1}>. {0} + Actual value <{2}> is not greater than expected value <{1}>. {0} + + + + Actual value <{2}> is not greater than or equal to expected value <{1}>. {0} + Actual value <{2}> is not greater than or equal to expected value <{1}>. {0} + + + + Actual value <{2}> is not less than expected value <{1}>. {0} + Actual value <{2}> is not less than expected value <{1}>. {0} + + + + Actual value <{2}> is not less than or equal to expected value <{1}>. {0} + Actual value <{2}> is not less than or equal to expected value <{1}>. {0} + + + + Expected value <{1}> to be positive. {0} + Expected value <{1}> to be positive. {0} + + + + Expected value <{1}> to be negative. {0} + Expected value <{1}> to be negative. {0} + + \ No newline at end of file diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.tr.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.tr.xlf index 187927a7e6..feb6805ebd 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.tr.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.tr.xlf @@ -315,6 +315,36 @@ Gerçekte olan: {2} - {1} fully qualified class name like "Microsoft.UI.Xaml.Application" + + Actual value <{2}> is not greater than expected value <{1}>. {0} + Actual value <{2}> is not greater than expected value <{1}>. {0} + + + + Actual value <{2}> is not greater than or equal to expected value <{1}>. {0} + Actual value <{2}> is not greater than or equal to expected value <{1}>. {0} + + + + Actual value <{2}> is not less than expected value <{1}>. {0} + Actual value <{2}> is not less than expected value <{1}>. {0} + + + + Actual value <{2}> is not less than or equal to expected value <{1}>. {0} + Actual value <{2}> is not less than or equal to expected value <{1}>. {0} + + + + Expected value <{1}> to be positive. {0} + Expected value <{1}> to be positive. {0} + + + + Expected value <{1}> to be negative. {0} + Expected value <{1}> to be negative. {0} + + \ No newline at end of file diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf index e597dffd4d..a61ca2d6c6 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf @@ -315,6 +315,36 @@ Actual: {2} - {1} fully qualified class name like "Microsoft.UI.Xaml.Application" + + Actual value <{2}> is not greater than expected value <{1}>. {0} + Actual value <{2}> is not greater than expected value <{1}>. {0} + + + + Actual value <{2}> is not greater than or equal to expected value <{1}>. {0} + Actual value <{2}> is not greater than or equal to expected value <{1}>. {0} + + + + Actual value <{2}> is not less than expected value <{1}>. {0} + Actual value <{2}> is not less than expected value <{1}>. {0} + + + + Actual value <{2}> is not less than or equal to expected value <{1}>. {0} + Actual value <{2}> is not less than or equal to expected value <{1}>. {0} + + + + Expected value <{1}> to be positive. {0} + Expected value <{1}> to be positive. {0} + + + + Expected value <{1}> to be negative. {0} + Expected value <{1}> to be negative. {0} + + \ No newline at end of file diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf index 7aa9cba997..d6e525a898 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf @@ -315,6 +315,36 @@ Actual: {2} - {1} fully qualified class name like "Microsoft.UI.Xaml.Application" + + Actual value <{2}> is not greater than expected value <{1}>. {0} + Actual value <{2}> is not greater than expected value <{1}>. {0} + + + + Actual value <{2}> is not greater than or equal to expected value <{1}>. {0} + Actual value <{2}> is not greater than or equal to expected value <{1}>. {0} + + + + Actual value <{2}> is not less than expected value <{1}>. {0} + Actual value <{2}> is not less than expected value <{1}>. {0} + + + + Actual value <{2}> is not less than or equal to expected value <{1}>. {0} + Actual value <{2}> is not less than or equal to expected value <{1}>. {0} + + + + Expected value <{1}> to be positive. {0} + Expected value <{1}> to be positive. {0} + + + + Expected value <{1}> to be negative. {0} + Expected value <{1}> to be negative. {0} + + \ No newline at end of file diff --git a/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.IComparableTests.cs b/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.IComparableTests.cs new file mode 100644 index 0000000000..113d6cfc05 --- /dev/null +++ b/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.IComparableTests.cs @@ -0,0 +1,377 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using FluentAssertions; + +using TestFramework.ForTestingMSTest; + +namespace Microsoft.VisualStudio.TestPlatform.TestFramework.UnitTests; + +public partial class AssertTests : TestContainer +{ + #region IsGreaterThan tests + + public void IsGreaterThanShouldNotThrowWhenActualIsGreater() => + Assert.IsGreaterThan(5, 10); + + public void IsGreaterThanShouldWorkWithReferenceTypes() => + Assert.IsGreaterThan("a", "b"); + + public void IsGreaterThanShouldThrowWhenActualIsNotGreater() + { + // Act + Action action = () => Assert.IsGreaterThan(10, 5); + + // Assert + action.Should().Throw(); + } + + public void IsGreaterThanShouldThrowWhenBothAreEqual() + { + // Act + Action action = () => Assert.IsGreaterThan(5, 5); + + // Assert + action.Should().Throw(); + } + + public void IsGreaterThanShouldThrowWithMessage() + { + // Act + Action action = () => Assert.IsGreaterThan(10, 5, "A Message"); + + // Assert + action.Should().Throw() + .WithMessage("Assert.IsGreaterThan failed. Actual value <5> is not greater than expected value <10>. A Message"); + } + + public void IsGreaterThanShouldThrowWithMessageAndParameters() + { + // Act + Action action = () => Assert.IsGreaterThan(10, 5, "A Message {0}", "param"); + + // Assert + action.Should().Throw() + .WithMessage("Assert.IsGreaterThan failed. Actual value <5> is not greater than expected value <10>. A Message param"); + } + + public void IsGreaterThanShouldWorkWithDoubles() => + Assert.IsGreaterThan(5.0, 5.5); + + public void IsGreaterThanShouldThrowWithDoubles() + { + // Act + Action action = () => Assert.IsGreaterThan(5.5, 5.0); + + // Assert + action.Should().Throw(); + } + + #endregion + + #region IsGreaterThanOrEqualTo tests + + public void IsGreaterThanOrEqualToShouldNotThrowWhenActualIsGreater() => + Assert.IsGreaterThanOrEqualTo(5, 10); + + public void IsGreaterThanOrEqualToShouldWorkWithReferenceTypes() => + Assert.IsGreaterThanOrEqualTo("a", "b"); + + public void IsGreaterThanOrEqualToShouldNotThrowWhenBothAreEqual() => + Assert.IsGreaterThanOrEqualTo(5, 5); + + public void IsGreaterThanOrEqualToShouldThrowWhenActualIsLess() + { + // Act + Action action = () => Assert.IsGreaterThanOrEqualTo(10, 5); + + // Assert + action.Should().Throw(); + } + + public void IsGreaterThanOrEqualToShouldThrowWithMessage() + { + // Act + Action action = () => Assert.IsGreaterThanOrEqualTo(10, 5, "A Message"); + + // Assert + action.Should().Throw() + .WithMessage("Assert.IsGreaterThanOrEqualTo failed. Actual value <5> is not greater than or equal to expected value <10>. A Message"); + } + + public void IsGreaterThanOrEqualToShouldThrowWithMessageAndParameters() + { + // Act + Action action = () => Assert.IsGreaterThanOrEqualTo(10, 5, "A Message {0}", "param"); + + // Assert + action.Should().Throw() + .WithMessage("Assert.IsGreaterThanOrEqualTo failed. Actual value <5> is not greater than or equal to expected value <10>. A Message param"); + } + + public void IsGreaterThanOrEqualToShouldWorkWithDoubles() => + Assert.IsGreaterThanOrEqualTo(5.0, 5.5); + + public void IsGreaterThanOrEqualToShouldWorkWithEqualDoubles() => + Assert.IsGreaterThanOrEqualTo(5.5, 5.5); + + #endregion + + #region IsLessThan tests + + public void IsLessThanShouldNotThrowWhenActualIsLess() => + Assert.IsLessThan(10, 5); + + public void IsLessThanShouldWorkWithReferenceTypes() => + Assert.IsLessThan("b", "a"); + + public void IsLessThanShouldThrowWhenActualIsNotLess() + { + // Act + Action action = () => Assert.IsLessThan(5, 10); + + // Assert + action.Should().Throw(); + } + + public void IsLessThanShouldThrowWhenBothAreEqual() + { + // Act + Action action = () => Assert.IsLessThan(5, 5); + + // Assert + action.Should().Throw(); + } + + public void IsLessThanShouldThrowWithMessage() + { + // Act + Action action = () => Assert.IsLessThan(5, 10, "A Message"); + + // Assert + action.Should().Throw() + .WithMessage("Assert.IsLessThan failed. Actual value <10> is not less than expected value <5>. A Message"); + } + + public void IsLessThanShouldThrowWithMessageAndParameters() + { + // Act + Action action = () => Assert.IsLessThan(5, 10, "A Message {0}", "param"); + + // Assert + action.Should().Throw() + .WithMessage("Assert.IsLessThan failed. Actual value <10> is not less than expected value <5>. A Message param"); + } + + public void IsLessThanShouldWorkWithDoubles() => + Assert.IsLessThan(5.5, 5.0); + + public void IsLessThanShouldThrowWithDoubles() + { + // Act + Action action = () => Assert.IsLessThan(5.0, 5.5); + + // Assert + action.Should().Throw(); + } + + #endregion + + #region IsLessThanOrEqualTo tests + + public void IsLessThanOrEqualToShouldNotThrowWhenActualIsLess() => + Assert.IsLessThanOrEqualTo(10, 5); + + public void IsLessThanOrEqualToShouldWorkWithReferenceTypes() => + Assert.IsLessThanOrEqualTo("b", "a"); + + public void IsLessThanOrEqualToShouldNotThrowWhenBothAreEqual() => + Assert.IsLessThanOrEqualTo(5, 5); + + public void IsLessThanOrEqualToShouldThrowWhenActualIsGreater() + { + // Act + Action action = () => Assert.IsLessThanOrEqualTo(5, 10); + + // Assert + action.Should().Throw(); + } + + public void IsLessThanOrEqualToShouldThrowWithMessage() + { + // Act + Action action = () => Assert.IsLessThanOrEqualTo(5, 10, "A Message"); + + // Assert + action.Should().Throw() + .WithMessage("Assert.IsLessThanOrEqualTo failed. Actual value <10> is not less than or equal to expected value <5>. A Message"); + } + + public void IsLessThanOrEqualToShouldThrowWithMessageAndParameters() + { + // Act + Action action = () => Assert.IsLessThanOrEqualTo(5, 10, "A Message {0}", "param"); + + // Assert + action.Should().Throw() + .WithMessage("Assert.IsLessThanOrEqualTo failed. Actual value <10> is not less than or equal to expected value <5>. A Message param"); + } + + public void IsLessThanOrEqualToShouldWorkWithDoubles() => + Assert.IsLessThanOrEqualTo(5.5, 5.0); + + public void IsLessThanOrEqualToShouldWorkWithEqualDoubles() => + Assert.IsLessThanOrEqualTo(5.5, 5.5); + + #endregion + + #region IsPositive tests + + public void IsPositiveShouldNotThrowForPositiveNumber() => + Assert.IsPositive(5); + + public void IsPositiveShouldThrowForZero() + { + // Act + Action action = () => Assert.IsPositive(0); + + // Assert + action.Should().Throw(); + } + + public void IsPositiveShouldThrowForNegativeNumber() + { + // Act + Action action = () => Assert.IsPositive(-5); + + // Assert + action.Should().Throw(); + } + + public void IsPositiveShouldThrowForNaN() + { + // Act + Action action = () => Assert.IsPositive(float.NaN); + + // Assert + action.Should().Throw(); + } + + public void IsPositiveShouldThrowForDoubleNaN() + { + // Act + Action action = () => Assert.IsPositive(double.NaN); + + // Assert + action.Should().Throw(); + } + + public void IsPositiveShouldThrowWithMessage() + { + // Act + Action action = () => Assert.IsPositive(-5, "A Message"); + + // Assert + action.Should().Throw() + .WithMessage("Assert.IsPositive failed. Expected value <-5> to be positive. A Message"); + } + + public void IsPositiveShouldThrowWithMessageAndParameters() + { + // Act + Action action = () => Assert.IsPositive(-5, "A Message {0}", "param"); + + // Assert + action.Should().Throw() + .WithMessage("Assert.IsPositive failed. Expected value <-5> to be positive. A Message param"); + } + + public void IsPositiveShouldWorkWithDoubles() => + Assert.IsPositive(5.5); + + public void IsPositiveShouldThrowForZeroDouble() + { + // Act + Action action = () => Assert.IsPositive(0.0); + + // Assert + action.Should().Throw(); + } + + #endregion + + #region IsNegative tests + + public void IsNegativeShouldNotThrowForNegativeNumber() => + Assert.IsNegative(-5); + + public void IsNegativeShouldThrowForZero() + { + // Act + Action action = () => Assert.IsNegative(0); + + // Assert + action.Should().Throw(); + } + + public void IsNegativeShouldThrowForPositiveNumber() + { + // Act + Action action = () => Assert.IsNegative(5); + + // Assert + action.Should().Throw(); + } + + public void IsNegativeShouldThrowForNaN() + { + // Act + Action action = () => Assert.IsNegative(float.NaN); + + // Assert + action.Should().Throw(); + } + + public void IsNegativeShouldThrowForDoubleNaN() + { + // Act + Action action = () => Assert.IsNegative(double.NaN); + + // Assert + action.Should().Throw(); + } + + public void IsNegativeShouldThrowWithMessage() + { + // Act + Action action = () => Assert.IsNegative(5, "A Message"); + + // Assert + action.Should().Throw() + .WithMessage("Assert.IsNegative failed. Expected value <5> to be negative. A Message"); + } + + public void IsNegativeShouldThrowWithMessageAndParameters() + { + // Act + Action action = () => Assert.IsNegative(5, "A Message {0}", "param"); + + // Assert + action.Should().Throw() + .WithMessage("Assert.IsNegative failed. Expected value <5> to be negative. A Message param"); + } + + public void IsNegativeShouldWorkWithDoubles() => + Assert.IsNegative(-5.5); + + public void IsNegativeShouldThrowForZeroDouble() + { + // Act + Action action = () => Assert.IsNegative(0.0); + + // Assert + action.Should().Throw(); + } + + #endregion +} From 8100b08d315462a0914172585d64cc4b7db812fc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Jare=C5=A1?= Date: Wed, 18 Jun 2025 11:26:39 +0200 Subject: [PATCH 109/541] Enable local dumps for handle not initialized issue (#5796) --- azure-pipelines.yml | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/azure-pipelines.yml b/azure-pipelines.yml index 612e8fdd38..9184b3e60a 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -76,7 +76,15 @@ stages: filePath: ./eng/install-procdump.ps1 failOnStderr: true showWarnings: true - + - task: PowerShell@2 + displayName: 'Enable local dumps' + inputs: + targetType: 'inline' + script: | + New-Item -Path $(Build.SourcesDirectory)\artifacts\CrashDumps -ItemType Directory -Force + Get-ChildItem "HKLM:\SOFTWARE\Microsoft\Windows\Windows Error Reporting\LocalDumps" + New-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\Windows Error Reporting\LocalDumps" -Name "DumpFolder" -Value "$(Build.SourcesDirectory)\artifacts\CrashDumps" -PropertyType ExpandString -Force + New-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\Windows Error Reporting\LocalDumps" -Name "DumpCount" -Value 10 -PropertyType DWord -Force - task: PowerShell@2 displayName: 'Install Access Database Engine' inputs: @@ -138,6 +146,13 @@ stages: displayName: Upload coverage to codecov.io condition: and(succeeded(), eq(variables._BuildConfig, 'Debug')) + - task: PublishBuildArtifacts@1 + displayName: 'Publish local dumps' + inputs: + PathtoPublish: '$(Build.SourcesDirectory)/artifacts/CrashDumps' + ArtifactName: TestResults_Windows_$(_BuildConfig) + condition: failed() + - job: Linux timeoutInMinutes: 90 pool: From 46523169829f5265f791e1f74e00b4096effecb3 Mon Sep 17 00:00:00 2001 From: dotnet bot Date: Wed, 18 Jun 2025 13:50:12 +0200 Subject: [PATCH 110/541] Localized file check-in by OneLocBuild Task: Build definition ID 1218: Build ID 2732833 --- .../TestFramework/Resources/xlf/FrameworkMessages.ja.xlf | 2 +- .../TestFramework/Resources/xlf/FrameworkMessages.pl.xlf | 2 +- .../TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ja.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ja.xlf index bb594294f6..b55df0c903 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ja.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ja.xlf @@ -143,7 +143,7 @@ Actual: {2} Value '{0}' is not within the expected range [{1}, {2}]. {3} - Value '{0}' is not within the expected range [{1}, {2}]. {3} + 値 '{0}' は予期される範囲 [{1}, {2}] にありません。 {3} diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pl.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pl.xlf index 26106ca118..6cb27f8a76 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pl.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pl.xlf @@ -143,7 +143,7 @@ Rzeczywiste: {2} Value '{0}' is not within the expected range [{1}, {2}]. {3} - Value '{0}' is not within the expected range [{1}, {2}]. {3} + Wartość „{0}” nie mieści się w oczekiwanym zakresie [{1}, {2}]. {3} diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf index a61ca2d6c6..e61a0f94f0 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf @@ -143,7 +143,7 @@ Actual: {2} Value '{0}' is not within the expected range [{1}, {2}]. {3} - Value '{0}' is not within the expected range [{1}, {2}]. {3} + 值“{0}”不在预期范围 [{1}, {2}] 内。{3} From f036f445e508eca78603236fa1adf514a1d1d351 Mon Sep 17 00:00:00 2001 From: Copilot <198982749+Copilot@users.noreply.github.com> Date: Wed, 18 Jun 2025 12:55:54 +0000 Subject: [PATCH 111/541] Add analyzer to suggest using cooperative cancellation for timeout (#5786) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: Youssef1313 <31348972+Youssef1313@users.noreply.github.com> Co-authored-by: Evangelink <11340282+Evangelink@users.noreply.github.com> Co-authored-by: Amaury Levé --- .../CodeFixResources.Designer.cs | 9 + .../CodeFixResources.resx | 3 + .../PublicAPI.Unshipped.txt | 5 + ...eCooperativeCancellationForTimeoutFixer.cs | 121 +++++ .../xlf/CodeFixResources.cs.xlf | 5 + .../xlf/CodeFixResources.de.xlf | 5 + .../xlf/CodeFixResources.es.xlf | 5 + .../xlf/CodeFixResources.fr.xlf | 5 + .../xlf/CodeFixResources.it.xlf | 5 + .../xlf/CodeFixResources.ja.xlf | 5 + .../xlf/CodeFixResources.ko.xlf | 5 + .../xlf/CodeFixResources.pl.xlf | 5 + .../xlf/CodeFixResources.pt-BR.xlf | 5 + .../xlf/CodeFixResources.ru.xlf | 5 + .../xlf/CodeFixResources.tr.xlf | 5 + .../xlf/CodeFixResources.zh-Hans.xlf | 5 + .../xlf/CodeFixResources.zh-Hant.xlf | 5 + .../AnalyzerReleases.Unshipped.md | 1 + .../MSTest.Analyzers/Helpers/DiagnosticIds.cs | 1 + .../Helpers/WellKnownTypeNames.cs | 1 + .../MSTest.Analyzers/PublicAPI.Unshipped.txt | 4 + .../MSTest.Analyzers/Resources.Designer.cs | 27 ++ src/Analyzers/MSTest.Analyzers/Resources.resx | 9 + ...operativeCancellationForTimeoutAnalyzer.cs | 79 ++++ .../MSTest.Analyzers/xlf/Resources.cs.xlf | 15 + .../MSTest.Analyzers/xlf/Resources.de.xlf | 15 + .../MSTest.Analyzers/xlf/Resources.es.xlf | 15 + .../MSTest.Analyzers/xlf/Resources.fr.xlf | 15 + .../MSTest.Analyzers/xlf/Resources.it.xlf | 15 + .../MSTest.Analyzers/xlf/Resources.ja.xlf | 15 + .../MSTest.Analyzers/xlf/Resources.ko.xlf | 15 + .../MSTest.Analyzers/xlf/Resources.pl.xlf | 15 + .../MSTest.Analyzers/xlf/Resources.pt-BR.xlf | 15 + .../MSTest.Analyzers/xlf/Resources.ru.xlf | 15 + .../MSTest.Analyzers/xlf/Resources.tr.xlf | 15 + .../xlf/Resources.zh-Hans.xlf | 15 + .../xlf/Resources.zh-Hant.xlf | 15 + ...tiveCancellationForTimeoutAnalyzerTests.cs | 443 ++++++++++++++++++ 38 files changed, 963 insertions(+) create mode 100644 src/Analyzers/MSTest.Analyzers.CodeFixes/UseCooperativeCancellationForTimeoutFixer.cs create mode 100644 src/Analyzers/MSTest.Analyzers/UseCooperativeCancellationForTimeoutAnalyzer.cs create mode 100644 test/UnitTests/MSTest.Analyzers.UnitTests/UseCooperativeCancellationForTimeoutAnalyzerTests.cs diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/CodeFixResources.Designer.cs b/src/Analyzers/MSTest.Analyzers.CodeFixes/CodeFixResources.Designer.cs index 93920133f3..89110576fc 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/CodeFixResources.Designer.cs +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/CodeFixResources.Designer.cs @@ -248,5 +248,14 @@ internal static string UseProperAssertMethodsFix { return ResourceManager.GetString("UseProperAssertMethodsFix", resourceCulture); } } + + /// + /// Looks up a localized string similar to Use 'CooperativeCancellation = true'. + /// + internal static string UseCooperativeCancellationForTimeoutFix { + get { + return ResourceManager.GetString("UseCooperativeCancellationForTimeoutFix", resourceCulture); + } + } } } diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/CodeFixResources.resx b/src/Analyzers/MSTest.Analyzers.CodeFixes/CodeFixResources.resx index 0e215460ca..008d1922fb 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/CodeFixResources.resx +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/CodeFixResources.resx @@ -180,4 +180,7 @@ Replace 'DataTestMethod' with 'TestMethod' + + Use 'CooperativeCancellation = true' + diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/PublicAPI.Unshipped.txt b/src/Analyzers/MSTest.Analyzers.CodeFixes/PublicAPI.Unshipped.txt index 4af97d242d..eff3fb1deb 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/PublicAPI.Unshipped.txt +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/PublicAPI.Unshipped.txt @@ -4,3 +4,8 @@ MSTest.Analyzers.PreferTestMethodOverDataTestMethodFixer.PreferTestMethodOverDat override MSTest.Analyzers.PreferTestMethodOverDataTestMethodFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray override MSTest.Analyzers.PreferTestMethodOverDataTestMethodFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! override MSTest.Analyzers.PreferTestMethodOverDataTestMethodFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! +MSTest.Analyzers.UseCooperativeCancellationForTimeoutFixer +MSTest.Analyzers.UseCooperativeCancellationForTimeoutFixer.UseCooperativeCancellationForTimeoutFixer() -> void +override MSTest.Analyzers.UseCooperativeCancellationForTimeoutFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! +override sealed MSTest.Analyzers.UseCooperativeCancellationForTimeoutFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray +override sealed MSTest.Analyzers.UseCooperativeCancellationForTimeoutFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/UseCooperativeCancellationForTimeoutFixer.cs b/src/Analyzers/MSTest.Analyzers.CodeFixes/UseCooperativeCancellationForTimeoutFixer.cs new file mode 100644 index 0000000000..a3052a78f1 --- /dev/null +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/UseCooperativeCancellationForTimeoutFixer.cs @@ -0,0 +1,121 @@ +// 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.Immutable; +using System.Composition; + +using Analyzer.Utilities; + +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CodeActions; +using Microsoft.CodeAnalysis.CodeFixes; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Editing; +using Microsoft.CodeAnalysis.Text; + +using MSTest.Analyzers.Helpers; + +namespace MSTest.Analyzers; + +/// +/// Code fixer for . +/// +[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(UseCooperativeCancellationForTimeoutFixer))] +[Shared] +public sealed class UseCooperativeCancellationForTimeoutFixer : CodeFixProvider +{ + /// + public sealed override ImmutableArray FixableDiagnosticIds { get; } + = ImmutableArray.Create(DiagnosticIds.UseCooperativeCancellationForTimeoutRuleId); + + /// + public override FixAllProvider GetFixAllProvider() + // See https://github.com/dotnet/roslyn/blob/main/docs/analyzers/FixAllProvider.md for more information on Fix All Providers + => WellKnownFixAllProviders.BatchFixer; + + /// + public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) + { + SyntaxNode root = await context.Document.GetRequiredSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); + Diagnostic diagnostic = context.Diagnostics[0]; + TextSpan diagnosticSpan = diagnostic.Location.SourceSpan; + + // Find the attribute syntax node identified by the diagnostic + SyntaxNode attributeNode = root.FindNode(diagnosticSpan, getInnermostNodeForTie: true); + if (attributeNode is not AttributeSyntax attributeSyntax) + { + return; + } + + // Register a code action that will invoke the fix + context.RegisterCodeFix( + CodeAction.Create( + title: CodeFixResources.UseCooperativeCancellationForTimeoutFix, + createChangedDocument: c => AddCooperativeCancellationAsync(context.Document, attributeSyntax, c), + equivalenceKey: nameof(UseCooperativeCancellationForTimeoutFixer)), + diagnostic); + } + + private static async Task AddCooperativeCancellationAsync(Document document, AttributeSyntax attributeSyntax, CancellationToken cancellationToken) + { + DocumentEditor editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false); + + AttributeSyntax newAttributeSyntax; + + if (attributeSyntax.ArgumentList == null) + { + // No argument list exists, create one with CooperativeCancellation = true + AttributeArgumentSyntax cooperativeCancellationArg = SyntaxFactory.AttributeArgument( + SyntaxFactory.NameEquals("CooperativeCancellation"), + null, + SyntaxFactory.LiteralExpression(SyntaxKind.TrueLiteralExpression)); + + newAttributeSyntax = attributeSyntax.WithArgumentList( + SyntaxFactory.AttributeArgumentList( + SyntaxFactory.SingletonSeparatedList(cooperativeCancellationArg))); + } + else + { + // Argument list exists, check if CooperativeCancellation is already specified + bool hasCooperativeCancellation = false; + List newArguments = []; + + foreach (AttributeArgumentSyntax arg in attributeSyntax.ArgumentList.Arguments) + { + if (arg.NameEquals?.Name.Identifier.ValueText == "CooperativeCancellation") + { + // Replace existing CooperativeCancellation = false with true + hasCooperativeCancellation = true; + AttributeArgumentSyntax newArg = arg.WithExpression( + SyntaxFactory.LiteralExpression(SyntaxKind.TrueLiteralExpression)); + newArguments.Add(newArg); + } + else + { + newArguments.Add(arg); + } + } + + if (!hasCooperativeCancellation) + { + // Add CooperativeCancellation = true to existing arguments + AttributeArgumentSyntax cooperativeCancellationArg = SyntaxFactory.AttributeArgument( + SyntaxFactory.NameEquals("CooperativeCancellation"), + null, + SyntaxFactory.LiteralExpression(SyntaxKind.TrueLiteralExpression)); + + newArguments.Add(cooperativeCancellationArg); + } + + newAttributeSyntax = attributeSyntax.WithArgumentList( + attributeSyntax.ArgumentList.WithArguments( + SyntaxFactory.SeparatedList(newArguments))); + } + + // Replace the old attribute with the new one + editor.ReplaceNode(attributeSyntax, newAttributeSyntax); + + return editor.GetChangedDocument(); + } +} diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.cs.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.cs.xlf index e71dab1dc7..b1fa26c3dd 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.cs.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.cs.xlf @@ -97,6 +97,11 @@ Přidat [TestMethod] + + Use 'CooperativeCancellation = true' + Use 'CooperativeCancellation = true' + + Use '{0}' Použít {0} diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.de.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.de.xlf index 9003d1701b..ff96bdfeab 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.de.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.de.xlf @@ -97,6 +97,11 @@ „[TestMethod]“ hinzufügen + + Use 'CooperativeCancellation = true' + Use 'CooperativeCancellation = true' + + Use '{0}' „{0}“ verwenden diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.es.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.es.xlf index 4e17f390b0..ed2a4544bf 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.es.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.es.xlf @@ -97,6 +97,11 @@ Agregar '[TestMethod]' + + Use 'CooperativeCancellation = true' + Use 'CooperativeCancellation = true' + + Use '{0}' Usar "{0}" diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.fr.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.fr.xlf index d9200767e8..12098b7ede 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.fr.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.fr.xlf @@ -97,6 +97,11 @@ Ajouter « [TestMethod] » + + Use 'CooperativeCancellation = true' + Use 'CooperativeCancellation = true' + + Use '{0}' Utiliser « {0} » diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.it.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.it.xlf index f7d47355f4..029c82d292 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.it.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.it.xlf @@ -97,6 +97,11 @@ Aggiungi '[TestMethod]' + + Use 'CooperativeCancellation = true' + Use 'CooperativeCancellation = true' + + Use '{0}' Usare ‘{0}’ diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ja.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ja.xlf index 91e6949a47..8b5bea42f0 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ja.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ja.xlf @@ -97,6 +97,11 @@ '[TestMethod]' の追加 + + Use 'CooperativeCancellation = true' + Use 'CooperativeCancellation = true' + + Use '{0}' '{0}' を使用する diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ko.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ko.xlf index 48fafa86db..a696d30d84 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ko.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ko.xlf @@ -97,6 +97,11 @@ '[TestMethod]' 추가 + + Use 'CooperativeCancellation = true' + Use 'CooperativeCancellation = true' + + Use '{0}' '{0}' 사용 diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pl.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pl.xlf index 8e3ca7b353..7aa82ebaea 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pl.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pl.xlf @@ -97,6 +97,11 @@ Dodaj „[TestMethod]” + + Use 'CooperativeCancellation = true' + Use 'CooperativeCancellation = true' + + Use '{0}' Użyj „{0}” diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pt-BR.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pt-BR.xlf index b3c8f200d0..13b834c897 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pt-BR.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pt-BR.xlf @@ -97,6 +97,11 @@ Adicionar ''[TestMethod]" + + Use 'CooperativeCancellation = true' + Use 'CooperativeCancellation = true' + + Use '{0}' Usar "{0}" diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ru.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ru.xlf index fa9d48d7c3..938bb14017 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ru.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ru.xlf @@ -97,6 +97,11 @@ Добавить "[TestMethod]" + + Use 'CooperativeCancellation = true' + Use 'CooperativeCancellation = true' + + Use '{0}' Использовать "{0}" diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.tr.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.tr.xlf index 168ef7ca5f..4e8c21035e 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.tr.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.tr.xlf @@ -97,6 +97,11 @@ '[TestMethod]' ekle + + Use 'CooperativeCancellation = true' + Use 'CooperativeCancellation = true' + + Use '{0}' '{0}' kullan diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hans.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hans.xlf index 631f4e6466..b9e86e472f 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hans.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hans.xlf @@ -97,6 +97,11 @@ 添加“[TestMethod]” + + Use 'CooperativeCancellation = true' + Use 'CooperativeCancellation = true' + + Use '{0}' 使用“{0}” diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hant.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hant.xlf index b3c5a1fe77..f09f986525 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hant.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hant.xlf @@ -97,6 +97,11 @@ 新增 '[TestMethod]' + + Use 'CooperativeCancellation = true' + Use 'CooperativeCancellation = true' + + Use '{0}' 使用 '{0}' diff --git a/src/Analyzers/MSTest.Analyzers/AnalyzerReleases.Unshipped.md b/src/Analyzers/MSTest.Analyzers/AnalyzerReleases.Unshipped.md index 079622cb08..213270ba16 100644 --- a/src/Analyzers/MSTest.Analyzers/AnalyzerReleases.Unshipped.md +++ b/src/Analyzers/MSTest.Analyzers/AnalyzerReleases.Unshipped.md @@ -6,3 +6,4 @@ Rule ID | Category | Severity | Notes --------|----------|----------|------- MSTEST0044 | Design | Warning | PreferTestMethodOverDataTestMethodAnalyzer, [Documentation](https://learn.microsoft.com/dotnet/core/testing/mstest-analyzers/mstest0044) +MSTEST0045 | Usage | Info | UseCooperativeCancellationForTimeoutAnalyzer, [Documentation](https://learn.microsoft.com/dotnet/core/testing/mstest-analyzers/mstest0045) diff --git a/src/Analyzers/MSTest.Analyzers/Helpers/DiagnosticIds.cs b/src/Analyzers/MSTest.Analyzers/Helpers/DiagnosticIds.cs index 6c30e60f1b..24ae712f8a 100644 --- a/src/Analyzers/MSTest.Analyzers/Helpers/DiagnosticIds.cs +++ b/src/Analyzers/MSTest.Analyzers/Helpers/DiagnosticIds.cs @@ -49,4 +49,5 @@ internal static class DiagnosticIds public const string DuplicateDataRowRuleId = "MSTEST0042"; public const string UseRetryWithTestMethodRuleId = "MSTEST0043"; public const string PreferTestMethodOverDataTestMethodRuleId = "MSTEST0044"; + public const string UseCooperativeCancellationForTimeoutRuleId = "MSTEST0045"; } diff --git a/src/Analyzers/MSTest.Analyzers/Helpers/WellKnownTypeNames.cs b/src/Analyzers/MSTest.Analyzers/Helpers/WellKnownTypeNames.cs index a56d8069a0..65389f66b6 100644 --- a/src/Analyzers/MSTest.Analyzers/Helpers/WellKnownTypeNames.cs +++ b/src/Analyzers/MSTest.Analyzers/Helpers/WellKnownTypeNames.cs @@ -40,6 +40,7 @@ internal static class WellKnownTypeNames public const string MicrosoftVisualStudioTestToolsUnitTestingTestInitializeAttribute = "Microsoft.VisualStudio.TestTools.UnitTesting.TestInitializeAttribute"; public const string MicrosoftVisualStudioTestToolsUnitTestingTestMethodAttribute = "Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute"; public const string MicrosoftVisualStudioTestToolsUnitTestingTestPropertyAttribute = "Microsoft.VisualStudio.TestTools.UnitTesting.TestPropertyAttribute"; + public const string MicrosoftVisualStudioTestToolsUnitTestingTimeoutAttribute = "Microsoft.VisualStudio.TestTools.UnitTesting.TimeoutAttribute"; public const string MicrosoftVisualStudioTestToolsUnitTestingWorkItemAttribute = "Microsoft.VisualStudio.TestTools.UnitTesting.WorkItemAttribute"; public const string System = "System"; diff --git a/src/Analyzers/MSTest.Analyzers/PublicAPI.Unshipped.txt b/src/Analyzers/MSTest.Analyzers/PublicAPI.Unshipped.txt index 04b7181a13..dcb3006d98 100644 --- a/src/Analyzers/MSTest.Analyzers/PublicAPI.Unshipped.txt +++ b/src/Analyzers/MSTest.Analyzers/PublicAPI.Unshipped.txt @@ -3,3 +3,7 @@ MSTest.Analyzers.PreferTestMethodOverDataTestMethodAnalyzer MSTest.Analyzers.PreferTestMethodOverDataTestMethodAnalyzer.PreferTestMethodOverDataTestMethodAnalyzer() -> void override MSTest.Analyzers.PreferTestMethodOverDataTestMethodAnalyzer.Initialize(Microsoft.CodeAnalysis.Diagnostics.AnalysisContext! context) -> void override MSTest.Analyzers.PreferTestMethodOverDataTestMethodAnalyzer.SupportedDiagnostics.get -> System.Collections.Immutable.ImmutableArray +MSTest.Analyzers.UseCooperativeCancellationForTimeoutAnalyzer +MSTest.Analyzers.UseCooperativeCancellationForTimeoutAnalyzer.UseCooperativeCancellationForTimeoutAnalyzer() -> void +override MSTest.Analyzers.UseCooperativeCancellationForTimeoutAnalyzer.Initialize(Microsoft.CodeAnalysis.Diagnostics.AnalysisContext! context) -> void +override MSTest.Analyzers.UseCooperativeCancellationForTimeoutAnalyzer.SupportedDiagnostics.get -> System.Collections.Immutable.ImmutableArray diff --git a/src/Analyzers/MSTest.Analyzers/Resources.Designer.cs b/src/Analyzers/MSTest.Analyzers/Resources.Designer.cs index 0281966296..23d0723ad0 100644 --- a/src/Analyzers/MSTest.Analyzers/Resources.Designer.cs +++ b/src/Analyzers/MSTest.Analyzers/Resources.Designer.cs @@ -1239,5 +1239,32 @@ internal static string UseRetryWithTestMethodTitle { return ResourceManager.GetString("UseRetryWithTestMethodTitle", resourceCulture); } } + + /// + /// Looks up a localized string similar to Using '[Timeout]' without explicitly setting 'CooperativeCancellation = true' is discouraged. In a future version, cooperative cancellation will become the default behavior. Set 'CooperativeCancellation = true' to opt into the recommended behavior and avoid breaking changes.. + /// + internal static string UseCooperativeCancellationForTimeoutDescription { + get { + return ResourceManager.GetString("UseCooperativeCancellationForTimeoutDescription", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Use 'CooperativeCancellation = true' with '[Timeout]' to enable cooperative cancellation behavior. + /// + internal static string UseCooperativeCancellationForTimeoutMessageFormat { + get { + return ResourceManager.GetString("UseCooperativeCancellationForTimeoutMessageFormat", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Use 'CooperativeCancellation = true' with '[Timeout]'. + /// + internal static string UseCooperativeCancellationForTimeoutTitle { + get { + return ResourceManager.GetString("UseCooperativeCancellationForTimeoutTitle", resourceCulture); + } + } } } diff --git a/src/Analyzers/MSTest.Analyzers/Resources.resx b/src/Analyzers/MSTest.Analyzers/Resources.resx index 3a14ec010c..eacef2a1ab 100644 --- a/src/Analyzers/MSTest.Analyzers/Resources.resx +++ b/src/Analyzers/MSTest.Analyzers/Resources.resx @@ -594,4 +594,13 @@ The type declaring these methods should also respect the following rules: 'DataTestMethodAttribute' is obsolete and provides no additional functionality over 'TestMethodAttribute'. Use 'TestMethodAttribute' for all test methods, including parameterized tests. + + Use 'CooperativeCancellation = true' with '[Timeout]' + + + Use 'CooperativeCancellation = true' with '[Timeout]' to enable cooperative cancellation behavior + + + Using '[Timeout]' without explicitly setting 'CooperativeCancellation = true' is discouraged. In a future version, cooperative cancellation will become the default behavior. Set 'CooperativeCancellation = true' to opt into the recommended behavior and avoid breaking changes. + diff --git a/src/Analyzers/MSTest.Analyzers/UseCooperativeCancellationForTimeoutAnalyzer.cs b/src/Analyzers/MSTest.Analyzers/UseCooperativeCancellationForTimeoutAnalyzer.cs new file mode 100644 index 0000000000..d73e67d3c0 --- /dev/null +++ b/src/Analyzers/MSTest.Analyzers/UseCooperativeCancellationForTimeoutAnalyzer.cs @@ -0,0 +1,79 @@ +// 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.Immutable; + +using Analyzer.Utilities.Extensions; + +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Diagnostics; + +using MSTest.Analyzers.Helpers; + +namespace MSTest.Analyzers; + +/// +/// MSTEST0045: . +/// +[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] +public sealed class UseCooperativeCancellationForTimeoutAnalyzer : DiagnosticAnalyzer +{ + private static readonly LocalizableResourceString Title = new(nameof(Resources.UseCooperativeCancellationForTimeoutTitle), Resources.ResourceManager, typeof(Resources)); + private static readonly LocalizableResourceString Description = new(nameof(Resources.UseCooperativeCancellationForTimeoutDescription), Resources.ResourceManager, typeof(Resources)); + private static readonly LocalizableResourceString MessageFormat = new(nameof(Resources.UseCooperativeCancellationForTimeoutMessageFormat), Resources.ResourceManager, typeof(Resources)); + + internal static readonly DiagnosticDescriptor UseCooperativeCancellationForTimeoutRule = DiagnosticDescriptorHelper.Create( + DiagnosticIds.UseCooperativeCancellationForTimeoutRuleId, + Title, + MessageFormat, + Description, + Category.Design, + DiagnosticSeverity.Info, + isEnabledByDefault: true); + + /// + public override ImmutableArray SupportedDiagnostics { get; } + = ImmutableArray.Create(UseCooperativeCancellationForTimeoutRule); + + /// + public override void Initialize(AnalysisContext context) + { + context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); + context.EnableConcurrentExecution(); + + context.RegisterCompilationStartAction(context => + { + if (context.Compilation.TryGetOrCreateTypeByMetadataName(WellKnownTypeNames.MicrosoftVisualStudioTestToolsUnitTestingTimeoutAttribute, out INamedTypeSymbol? timeoutAttributeSymbol)) + { + context.RegisterSymbolAction( + context => AnalyzeSymbol(context, timeoutAttributeSymbol), + SymbolKind.Method); + } + }); + } + + private static void AnalyzeSymbol(SymbolAnalysisContext context, INamedTypeSymbol timeoutAttributeSymbol) + { + var methodSymbol = (IMethodSymbol)context.Symbol; + + AttributeData? timeoutAttribute = null; + foreach (AttributeData attribute in methodSymbol.GetAttributes()) + { + if (SymbolEqualityComparer.Default.Equals(attribute.AttributeClass, timeoutAttributeSymbol)) + { + timeoutAttribute = attribute; + break; + } + } + + // Report diagnostic if CooperativeCancellation is not explicitly set to true + if (timeoutAttribute is not null + && !timeoutAttribute.NamedArguments.Any(x => x.Key == "CooperativeCancellation" && x.Value.Value is bool boolValue && boolValue)) + { + if (timeoutAttribute.ApplicationSyntaxReference?.GetSyntax() is { } syntax) + { + context.ReportDiagnostic(syntax.CreateDiagnostic(UseCooperativeCancellationForTimeoutRule)); + } + } + } +} diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf index 57644ebf1a..22063a35b8 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf @@ -779,6 +779,21 @@ Typ deklarující tyto metody by měl také respektovat následující pravidla: Použít ConditionBaseAttribute u testovacích tříd + + Using '[Timeout]' without explicitly setting 'CooperativeCancellation = true' is discouraged. In a future version, cooperative cancellation will become the default behavior. Set 'CooperativeCancellation = true' to opt into the recommended behavior and avoid breaking changes. + Using '[Timeout]' without explicitly setting 'CooperativeCancellation = true' is discouraged. In a future version, cooperative cancellation will become the default behavior. Set 'CooperativeCancellation = true' to opt into the recommended behavior and avoid breaking changes. + + + + Use 'CooperativeCancellation = true' with '[Timeout]' to enable cooperative cancellation behavior + Use 'CooperativeCancellation = true' with '[Timeout]' to enable cooperative cancellation behavior + + + + Use 'CooperativeCancellation = true' with '[Timeout]' + Use 'CooperativeCancellation = true' with '[Timeout]' + + '[DeploymentItem]' can be specified only on test class or test method [DeploymentItem] se dá zadat jenom pro testovací třídu nebo testovací metodu. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf index 62e3354ba3..fe75593577 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf @@ -780,6 +780,21 @@ Der Typ, der diese Methoden deklariert, sollte auch die folgenden Regeln beachte "ConditionBaseAttribute" für Testklassen verwenden + + Using '[Timeout]' without explicitly setting 'CooperativeCancellation = true' is discouraged. In a future version, cooperative cancellation will become the default behavior. Set 'CooperativeCancellation = true' to opt into the recommended behavior and avoid breaking changes. + Using '[Timeout]' without explicitly setting 'CooperativeCancellation = true' is discouraged. In a future version, cooperative cancellation will become the default behavior. Set 'CooperativeCancellation = true' to opt into the recommended behavior and avoid breaking changes. + + + + Use 'CooperativeCancellation = true' with '[Timeout]' to enable cooperative cancellation behavior + Use 'CooperativeCancellation = true' with '[Timeout]' to enable cooperative cancellation behavior + + + + Use 'CooperativeCancellation = true' with '[Timeout]' + Use 'CooperativeCancellation = true' with '[Timeout]' + + '[DeploymentItem]' can be specified only on test class or test method „[DeploymentItem]“ kann nur für die Testklasse oder Testmethode angegeben werden. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf index 6644a0ed64..87bf00ca81 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf @@ -779,6 +779,21 @@ El tipo que declara estos métodos también debe respetar las reglas siguientes: Usar 'ConditionBaseAttribute' en clases de prueba + + Using '[Timeout]' without explicitly setting 'CooperativeCancellation = true' is discouraged. In a future version, cooperative cancellation will become the default behavior. Set 'CooperativeCancellation = true' to opt into the recommended behavior and avoid breaking changes. + Using '[Timeout]' without explicitly setting 'CooperativeCancellation = true' is discouraged. In a future version, cooperative cancellation will become the default behavior. Set 'CooperativeCancellation = true' to opt into the recommended behavior and avoid breaking changes. + + + + Use 'CooperativeCancellation = true' with '[Timeout]' to enable cooperative cancellation behavior + Use 'CooperativeCancellation = true' with '[Timeout]' to enable cooperative cancellation behavior + + + + Use 'CooperativeCancellation = true' with '[Timeout]' + Use 'CooperativeCancellation = true' with '[Timeout]' + + '[DeploymentItem]' can be specified only on test class or test method '[DeploymentItem]' solo se puede especificar en la clase de prueba o el método de prueba diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf index 6e2051e718..6d8124a4cf 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf @@ -779,6 +779,21 @@ Le type doit être une classe Utiliser 'ConditionBaseAttribute' sur les classes de test + + Using '[Timeout]' without explicitly setting 'CooperativeCancellation = true' is discouraged. In a future version, cooperative cancellation will become the default behavior. Set 'CooperativeCancellation = true' to opt into the recommended behavior and avoid breaking changes. + Using '[Timeout]' without explicitly setting 'CooperativeCancellation = true' is discouraged. In a future version, cooperative cancellation will become the default behavior. Set 'CooperativeCancellation = true' to opt into the recommended behavior and avoid breaking changes. + + + + Use 'CooperativeCancellation = true' with '[Timeout]' to enable cooperative cancellation behavior + Use 'CooperativeCancellation = true' with '[Timeout]' to enable cooperative cancellation behavior + + + + Use 'CooperativeCancellation = true' with '[Timeout]' + Use 'CooperativeCancellation = true' with '[Timeout]' + + '[DeploymentItem]' can be specified only on test class or test method « [DeploymentItem] » ne peut être spécifié que sur une classe de test ou une méthode de test diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf index 07b5748ae2..dc2f115821 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf @@ -779,6 +779,21 @@ Anche il tipo che dichiara questi metodi deve rispettare le regole seguenti: Usa 'ConditionBaseAttribute' nelle classi di test + + Using '[Timeout]' without explicitly setting 'CooperativeCancellation = true' is discouraged. In a future version, cooperative cancellation will become the default behavior. Set 'CooperativeCancellation = true' to opt into the recommended behavior and avoid breaking changes. + Using '[Timeout]' without explicitly setting 'CooperativeCancellation = true' is discouraged. In a future version, cooperative cancellation will become the default behavior. Set 'CooperativeCancellation = true' to opt into the recommended behavior and avoid breaking changes. + + + + Use 'CooperativeCancellation = true' with '[Timeout]' to enable cooperative cancellation behavior + Use 'CooperativeCancellation = true' with '[Timeout]' to enable cooperative cancellation behavior + + + + Use 'CooperativeCancellation = true' with '[Timeout]' + Use 'CooperativeCancellation = true' with '[Timeout]' + + '[DeploymentItem]' can be specified only on test class or test method '[DeploymentItem]' può essere specificato solo per la classe di test o il metodo di test diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf index a962c4698e..dedfbc8403 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf @@ -779,6 +779,21 @@ The type declaring these methods should also respect the following rules: テスト クラスで 'ConditionBaseAttribute' を使用する + + Using '[Timeout]' without explicitly setting 'CooperativeCancellation = true' is discouraged. In a future version, cooperative cancellation will become the default behavior. Set 'CooperativeCancellation = true' to opt into the recommended behavior and avoid breaking changes. + Using '[Timeout]' without explicitly setting 'CooperativeCancellation = true' is discouraged. In a future version, cooperative cancellation will become the default behavior. Set 'CooperativeCancellation = true' to opt into the recommended behavior and avoid breaking changes. + + + + Use 'CooperativeCancellation = true' with '[Timeout]' to enable cooperative cancellation behavior + Use 'CooperativeCancellation = true' with '[Timeout]' to enable cooperative cancellation behavior + + + + Use 'CooperativeCancellation = true' with '[Timeout]' + Use 'CooperativeCancellation = true' with '[Timeout]' + + '[DeploymentItem]' can be specified only on test class or test method '[DeploymentItem]' は、テスト クラスまたはテスト メソッドでのみ指定できます diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf index 97388ae0b0..601f5c7c93 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf @@ -779,6 +779,21 @@ The type declaring these methods should also respect the following rules: 테스트 클래스에 'ConditionBaseAttribute' 사용 + + Using '[Timeout]' without explicitly setting 'CooperativeCancellation = true' is discouraged. In a future version, cooperative cancellation will become the default behavior. Set 'CooperativeCancellation = true' to opt into the recommended behavior and avoid breaking changes. + Using '[Timeout]' without explicitly setting 'CooperativeCancellation = true' is discouraged. In a future version, cooperative cancellation will become the default behavior. Set 'CooperativeCancellation = true' to opt into the recommended behavior and avoid breaking changes. + + + + Use 'CooperativeCancellation = true' with '[Timeout]' to enable cooperative cancellation behavior + Use 'CooperativeCancellation = true' with '[Timeout]' to enable cooperative cancellation behavior + + + + Use 'CooperativeCancellation = true' with '[Timeout]' + Use 'CooperativeCancellation = true' with '[Timeout]' + + '[DeploymentItem]' can be specified only on test class or test method '[DeploymentItem]'은(는) 테스트 클래스 또는 테스트 메서드에만 지정할 수 있습니다. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf index f5b5b3f41c..6ffcf37698 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf @@ -779,6 +779,21 @@ Typ deklarujący te metody powinien również przestrzegać następujących regu Użyj atrybutu "ConditionBaseAttribute" w klasach testu + + Using '[Timeout]' without explicitly setting 'CooperativeCancellation = true' is discouraged. In a future version, cooperative cancellation will become the default behavior. Set 'CooperativeCancellation = true' to opt into the recommended behavior and avoid breaking changes. + Using '[Timeout]' without explicitly setting 'CooperativeCancellation = true' is discouraged. In a future version, cooperative cancellation will become the default behavior. Set 'CooperativeCancellation = true' to opt into the recommended behavior and avoid breaking changes. + + + + Use 'CooperativeCancellation = true' with '[Timeout]' to enable cooperative cancellation behavior + Use 'CooperativeCancellation = true' with '[Timeout]' to enable cooperative cancellation behavior + + + + Use 'CooperativeCancellation = true' with '[Timeout]' + Use 'CooperativeCancellation = true' with '[Timeout]' + + '[DeploymentItem]' can be specified only on test class or test method Element „[DeploymentItem]” można określić tylko dla klasy testowej lub metody testowej diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf index c44fcf1403..ae5fcb582b 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf @@ -779,6 +779,21 @@ O tipo que declara esses métodos também deve respeitar as seguintes regras: Usar 'ConditionBaseAttribute' em classes de teste + + Using '[Timeout]' without explicitly setting 'CooperativeCancellation = true' is discouraged. In a future version, cooperative cancellation will become the default behavior. Set 'CooperativeCancellation = true' to opt into the recommended behavior and avoid breaking changes. + Using '[Timeout]' without explicitly setting 'CooperativeCancellation = true' is discouraged. In a future version, cooperative cancellation will become the default behavior. Set 'CooperativeCancellation = true' to opt into the recommended behavior and avoid breaking changes. + + + + Use 'CooperativeCancellation = true' with '[Timeout]' to enable cooperative cancellation behavior + Use 'CooperativeCancellation = true' with '[Timeout]' to enable cooperative cancellation behavior + + + + Use 'CooperativeCancellation = true' with '[Timeout]' + Use 'CooperativeCancellation = true' with '[Timeout]' + + '[DeploymentItem]' can be specified only on test class or test method '[DeploymentItem]' pode ser especificado apenas na classe de teste ou método de teste diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf index eb83b2e5e6..11a5dd39a3 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf @@ -791,6 +791,21 @@ The type declaring these methods should also respect the following rules: Использовать ConditionBaseAttribute для тестовых классов + + Using '[Timeout]' without explicitly setting 'CooperativeCancellation = true' is discouraged. In a future version, cooperative cancellation will become the default behavior. Set 'CooperativeCancellation = true' to opt into the recommended behavior and avoid breaking changes. + Using '[Timeout]' without explicitly setting 'CooperativeCancellation = true' is discouraged. In a future version, cooperative cancellation will become the default behavior. Set 'CooperativeCancellation = true' to opt into the recommended behavior and avoid breaking changes. + + + + Use 'CooperativeCancellation = true' with '[Timeout]' to enable cooperative cancellation behavior + Use 'CooperativeCancellation = true' with '[Timeout]' to enable cooperative cancellation behavior + + + + Use 'CooperativeCancellation = true' with '[Timeout]' + Use 'CooperativeCancellation = true' with '[Timeout]' + + '[DeploymentItem]' can be specified only on test class or test method Указать "[DeploymentItem]" можно только для тестового класса или метода. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf index 53b646d41f..89633f209d 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf @@ -781,6 +781,21 @@ Bu yöntemleri bildiren tipin ayrıca aşağıdaki kurallara uyması gerekir: Test sınıflarda 'ConditionBaseAttribute' kullanın + + Using '[Timeout]' without explicitly setting 'CooperativeCancellation = true' is discouraged. In a future version, cooperative cancellation will become the default behavior. Set 'CooperativeCancellation = true' to opt into the recommended behavior and avoid breaking changes. + Using '[Timeout]' without explicitly setting 'CooperativeCancellation = true' is discouraged. In a future version, cooperative cancellation will become the default behavior. Set 'CooperativeCancellation = true' to opt into the recommended behavior and avoid breaking changes. + + + + Use 'CooperativeCancellation = true' with '[Timeout]' to enable cooperative cancellation behavior + Use 'CooperativeCancellation = true' with '[Timeout]' to enable cooperative cancellation behavior + + + + Use 'CooperativeCancellation = true' with '[Timeout]' + Use 'CooperativeCancellation = true' with '[Timeout]' + + '[DeploymentItem]' can be specified only on test class or test method '[DeploymentItem]' yalnızca test sınıfında veya test yönteminde belirtilebilir diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf index 45efc76bf0..56f36c52f0 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf @@ -779,6 +779,21 @@ The type declaring these methods should also respect the following rules: 对测试类使用 “ConditionBaseAttribute” + + Using '[Timeout]' without explicitly setting 'CooperativeCancellation = true' is discouraged. In a future version, cooperative cancellation will become the default behavior. Set 'CooperativeCancellation = true' to opt into the recommended behavior and avoid breaking changes. + Using '[Timeout]' without explicitly setting 'CooperativeCancellation = true' is discouraged. In a future version, cooperative cancellation will become the default behavior. Set 'CooperativeCancellation = true' to opt into the recommended behavior and avoid breaking changes. + + + + Use 'CooperativeCancellation = true' with '[Timeout]' to enable cooperative cancellation behavior + Use 'CooperativeCancellation = true' with '[Timeout]' to enable cooperative cancellation behavior + + + + Use 'CooperativeCancellation = true' with '[Timeout]' + Use 'CooperativeCancellation = true' with '[Timeout]' + + '[DeploymentItem]' can be specified only on test class or test method 只能对测试类或测试方法指定 "[DeploymentItem]" diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf index d56848dfe3..9e6690d134 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf @@ -779,6 +779,21 @@ The type declaring these methods should also respect the following rules: 在測試類別上使用 'ConditionBaseAttribute' + + Using '[Timeout]' without explicitly setting 'CooperativeCancellation = true' is discouraged. In a future version, cooperative cancellation will become the default behavior. Set 'CooperativeCancellation = true' to opt into the recommended behavior and avoid breaking changes. + Using '[Timeout]' without explicitly setting 'CooperativeCancellation = true' is discouraged. In a future version, cooperative cancellation will become the default behavior. Set 'CooperativeCancellation = true' to opt into the recommended behavior and avoid breaking changes. + + + + Use 'CooperativeCancellation = true' with '[Timeout]' to enable cooperative cancellation behavior + Use 'CooperativeCancellation = true' with '[Timeout]' to enable cooperative cancellation behavior + + + + Use 'CooperativeCancellation = true' with '[Timeout]' + Use 'CooperativeCancellation = true' with '[Timeout]' + + '[DeploymentItem]' can be specified only on test class or test method '[DeploymentItem]' 只能在測試類或測試方法上指定 diff --git a/test/UnitTests/MSTest.Analyzers.UnitTests/UseCooperativeCancellationForTimeoutAnalyzerTests.cs b/test/UnitTests/MSTest.Analyzers.UnitTests/UseCooperativeCancellationForTimeoutAnalyzerTests.cs new file mode 100644 index 0000000000..5d090b4bae --- /dev/null +++ b/test/UnitTests/MSTest.Analyzers.UnitTests/UseCooperativeCancellationForTimeoutAnalyzerTests.cs @@ -0,0 +1,443 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using VerifyCS = MSTest.Analyzers.Test.CSharpCodeFixVerifier< + MSTest.Analyzers.UseCooperativeCancellationForTimeoutAnalyzer, + MSTest.Analyzers.UseCooperativeCancellationForTimeoutFixer>; + +namespace MSTest.Analyzers.Test; + +[TestClass] +public sealed class UseCooperativeCancellationForTimeoutAnalyzerTests +{ + [TestMethod] + public async Task WhenTimeoutAttributeHasCooperativeCancellationTrue_NoDiagnostic() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + [Timeout(5000, CooperativeCancellation = true)] + public void MyTestMethod() + { + } + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, code); + } + + [TestMethod] + public async Task WhenTimeoutAttributeWithoutCooperativeCancellation_Diagnostic() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + [[|Timeout(5000)|]] + public void MyTestMethod() + { + } + } + """; + + string fixedCode = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + [Timeout(5000, CooperativeCancellation = true)] + public void MyTestMethod() + { + } + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, fixedCode); + } + + [TestMethod] + public async Task WhenTimeoutAttributeWithCooperativeCancellationFalse_Diagnostic() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + [[|Timeout(5000, CooperativeCancellation = false)|]] + public void MyTestMethod() + { + } + } + """; + + string fixedCode = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + [Timeout(5000, CooperativeCancellation = true)] + public void MyTestMethod() + { + } + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, fixedCode); + } + + [TestMethod] + public async Task WhenTimeoutAttributeOnNonTestMethod_Diagnostic() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [[|Timeout(5000)|]] + public void NonTestMethod() + { + } + } + """; + + string fixedCode = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [Timeout(5000, CooperativeCancellation = true)] + public void NonTestMethod() + { + } + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, fixedCode); + } + + [TestMethod] + public async Task WhenTestMethodWithoutTimeoutAttribute_NoDiagnostic() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + } + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, code); + } + + [TestMethod] + public async Task WhenTimeoutAttributeWithoutCooperativeCancellation_CodeFixAddsProperty() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + [{|#0:Timeout(5000)|}] + public void MyTestMethod() + { + } + } + """; + + string fixedCode = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + [Timeout(5000, CooperativeCancellation = true)] + public void MyTestMethod() + { + } + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, VerifyCS.Diagnostic().WithLocation(0), fixedCode); + } + + [TestMethod] + public async Task WhenTimeoutAttributeWithCooperativeCancellationFalse_CodeFixChangesToTrue() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + [{|#0:Timeout(5000, CooperativeCancellation = false)|}] + public void MyTestMethod() + { + } + } + """; + + string fixedCode = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + [Timeout(5000, CooperativeCancellation = true)] + public void MyTestMethod() + { + } + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, VerifyCS.Diagnostic().WithLocation(0), fixedCode); + } + + [TestMethod] + public async Task WhenTimeoutAttributeOnClassInitialize_Diagnostic() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [ClassInitialize] + [[|Timeout(5000)|]] + public static void MyClassInitialize(TestContext context) + { + } + } + """; + + string fixedCode = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [ClassInitialize] + [Timeout(5000, CooperativeCancellation = true)] + public static void MyClassInitialize(TestContext context) + { + } + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, fixedCode); + } + + [TestMethod] + public async Task WhenTimeoutAttributeOnClassInitializeWithCooperativeCancellationTrue_NoDiagnostic() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [ClassInitialize] + [Timeout(5000, CooperativeCancellation = true)] + public static void MyClassInitialize(TestContext context) + { + } + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, code); + } + + [TestMethod] + public async Task WhenTimeoutAttributeOnAssemblyInitialize_Diagnostic() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [AssemblyInitialize] + [[|Timeout(5000)|]] + public static void MyAssemblyInitialize(TestContext context) + { + } + } + """; + + string fixedCode = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [AssemblyInitialize] + [Timeout(5000, CooperativeCancellation = true)] + public static void MyAssemblyInitialize(TestContext context) + { + } + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, fixedCode); + } + + [TestMethod] + public async Task WhenTimeoutAttributeOnTestInitialize_Diagnostic() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestInitialize] + [[|Timeout(5000)|]] + public void MyTestInitialize() + { + } + } + """; + + string fixedCode = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestInitialize] + [Timeout(5000, CooperativeCancellation = true)] + public void MyTestInitialize() + { + } + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, fixedCode); + } + + [TestMethod] + public async Task WhenTimeoutAttributeOnTestCleanup_Diagnostic() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestCleanup] + [[|Timeout(5000)|]] + public void MyTestCleanup() + { + } + } + """; + + string fixedCode = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestCleanup] + [Timeout(5000, CooperativeCancellation = true)] + public void MyTestCleanup() + { + } + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, fixedCode); + } + + [TestMethod] + public async Task WhenTimeoutAttributeOnClassCleanup_Diagnostic() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [ClassCleanup] + [[|Timeout(5000)|]] + public static void MyClassCleanup() + { + } + } + """; + + string fixedCode = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [ClassCleanup] + [Timeout(5000, CooperativeCancellation = true)] + public static void MyClassCleanup() + { + } + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, fixedCode); + } + + [TestMethod] + public async Task WhenTimeoutAttributeOnAssemblyCleanup_Diagnostic() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [AssemblyCleanup] + [[|Timeout(5000)|]] + public static void MyAssemblyCleanup() + { + } + } + """; + + string fixedCode = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [AssemblyCleanup] + [Timeout(5000, CooperativeCancellation = true)] + public static void MyAssemblyCleanup() + { + } + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, fixedCode); + } +} From 0d6c7ff56a7e25407d3a85ecbd85846a077a50cf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Wed, 18 Jun 2025 14:58:46 +0200 Subject: [PATCH 112/541] Deprecates `That` property and suggest `Instance` instead (#5811) --- .../TestFramework/Assertions/Assert.cs | 18 +++++++++++++++++- .../Assertions/CollectionAssert.cs | 18 +++++++++++++++++- .../TestFramework/Assertions/StringAssert.cs | 18 +++++++++++++++++- .../TestFramework/FrameworkConstants.cs | 1 + .../PublicAPI/PublicAPI.Unshipped.txt | 3 +++ .../FxExtensibilityTestProject/AssertExTest.cs | 8 ++++---- .../Assertions/AssertTests.cs | 6 +++--- .../Assertions/CollectionAssertTests.cs | 4 ++-- .../Assertions/StringAssertTests.cs | 4 ++-- 9 files changed, 66 insertions(+), 14 deletions(-) diff --git a/src/TestFramework/TestFramework/Assertions/Assert.cs b/src/TestFramework/TestFramework/Assertions/Assert.cs index 61ebec34ae..978b77b856 100644 --- a/src/TestFramework/TestFramework/Assertions/Assert.cs +++ b/src/TestFramework/TestFramework/Assertions/Assert.cs @@ -14,6 +14,17 @@ private Assert() { } + /// + /// Gets the singleton instance of the Assert functionality. + /// + /// + /// Users can use this to plug-in custom assertions through C# extension methods. + /// For instance, the signature of a custom assertion provider could be "public static void IsOfType<T>(this Assert assert, object obj)" + /// Users could then use a syntax similar to the default assertions which in this case is "Assert.Instance.IsOfType<Dog>(animal);" + /// More documentation is at "https://github.com/Microsoft/testfx/docs/README.md". + /// + public static Assert Instance { get; } = new Assert(); + /// /// Gets the singleton instance of the Assert functionality. /// @@ -23,7 +34,12 @@ private Assert() /// Users could then use a syntax similar to the default assertions which in this case is "Assert.That.IsOfType<Dog>(animal);" /// More documentation is at "https://github.com/Microsoft/testfx/docs/README.md". /// - public static Assert That { get; } = new Assert(); +#if NET6_0_OR_GREATER + [Obsolete(FrameworkConstants.ThatPropertyObsoleteMessage, DiagnosticId = "MSTESTOBS")] +#else + [Obsolete(FrameworkConstants.ThatPropertyObsoleteMessage)] +#endif + public static Assert That { get; } = Instance; /// /// Replaces null characters ('\0') with "\\0". diff --git a/src/TestFramework/TestFramework/Assertions/CollectionAssert.cs b/src/TestFramework/TestFramework/Assertions/CollectionAssert.cs index 0d87f35366..35fd6945bb 100644 --- a/src/TestFramework/TestFramework/Assertions/CollectionAssert.cs +++ b/src/TestFramework/TestFramework/Assertions/CollectionAssert.cs @@ -16,6 +16,17 @@ private CollectionAssert() { } + /// + /// Gets the singleton instance of the CollectionAssert functionality. + /// + /// + /// Users can use this to plug-in custom assertions through C# extension methods. + /// For instance, the signature of a custom assertion provider could be "public static void AreEqualUnordered(this CollectionAssert customAssert, ICollection expected, ICollection actual)" + /// Users could then use a syntax similar to the default assertions which in this case is "CollectionAssert.Instance.AreEqualUnordered(list1, list2);" + /// More documentation is at "https://github.com/Microsoft/testfx/docs/README.md". + /// + public static CollectionAssert Instance { get; } = new CollectionAssert(); + /// /// Gets the singleton instance of the CollectionAssert functionality. /// @@ -25,7 +36,12 @@ private CollectionAssert() /// Users could then use a syntax similar to the default assertions which in this case is "CollectionAssert.That.AreEqualUnordered(list1, list2);" /// More documentation is at "https://github.com/Microsoft/testfx/docs/README.md". /// - public static CollectionAssert That { get; } = new CollectionAssert(); +#if NET6_0_OR_GREATER + [Obsolete(FrameworkConstants.ThatPropertyObsoleteMessage, DiagnosticId = "MSTESTOBS")] +#else + [Obsolete(FrameworkConstants.ThatPropertyObsoleteMessage)] +#endif + public static CollectionAssert That { get; } = Instance; #endregion diff --git a/src/TestFramework/TestFramework/Assertions/StringAssert.cs b/src/TestFramework/TestFramework/Assertions/StringAssert.cs index a55c653c4f..bd9d3ab16c 100644 --- a/src/TestFramework/TestFramework/Assertions/StringAssert.cs +++ b/src/TestFramework/TestFramework/Assertions/StringAssert.cs @@ -16,6 +16,17 @@ private StringAssert() { } + /// + /// Gets the singleton instance of the StringAssert functionality. + /// + /// + /// Users can use this to plug-in custom assertions through C# extension methods. + /// For instance, the signature of a custom assertion provider could be "public static void ContainsWords(this StringAssert customAssert, string value, ICollection substrings)" + /// Users could then use a syntax similar to the default assertions which in this case is "StringAssert.Instance.ContainsWords(value, substrings);" + /// More documentation is at "https://github.com/Microsoft/testfx/docs/README.md". + /// + public static StringAssert Instance { get; } = new StringAssert(); + /// /// Gets the singleton instance of the StringAssert functionality. /// @@ -25,7 +36,12 @@ private StringAssert() /// Users could then use a syntax similar to the default assertions which in this case is "StringAssert.That.ContainsWords(value, substrings);" /// More documentation is at "https://github.com/Microsoft/testfx/docs/README.md". /// - public static StringAssert That { get; } = new StringAssert(); +#if NET6_0_OR_GREATER + [Obsolete(FrameworkConstants.ThatPropertyObsoleteMessage, DiagnosticId = "MSTESTOBS")] +#else + [Obsolete(FrameworkConstants.ThatPropertyObsoleteMessage)] +#endif + public static StringAssert That { get; } = Instance; #endregion diff --git a/src/TestFramework/TestFramework/FrameworkConstants.cs b/src/TestFramework/TestFramework/FrameworkConstants.cs index 7f37a607f6..a26c0a058f 100644 --- a/src/TestFramework/TestFramework/FrameworkConstants.cs +++ b/src/TestFramework/TestFramework/FrameworkConstants.cs @@ -9,4 +9,5 @@ namespace Microsoft.VisualStudio.TestTools.UnitTesting; internal static class FrameworkConstants { internal const string PublicTypeObsoleteMessage = "We will remove or hide this type starting with v4. If you are using this type, reach out to our team on https://github.com/microsoft/testfx."; + internal const string ThatPropertyObsoleteMessage = "The 'That' property is obsolete and will be removed in a future version. Use the 'Instance' property instead."; } diff --git a/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Unshipped.txt b/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Unshipped.txt index 064a648383..452b727267 100644 --- a/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Unshipped.txt +++ b/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Unshipped.txt @@ -7,6 +7,7 @@ static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsGreaterThan(T lo static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsGreaterThanOrEqualTo(T lowerBound, T value) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsGreaterThanOrEqualTo(T lowerBound, T value, string? message) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsGreaterThanOrEqualTo(T lowerBound, T value, string? message, params object?[]? parameters) -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.Instance.get -> Microsoft.VisualStudio.TestTools.UnitTesting.Assert! static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsInRange(T minValue, T maxValue, T value) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsInRange(T minValue, T maxValue, T value, string? message) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsInRange(T minValue, T maxValue, T value, string? message, params object?[]? parameters) -> void @@ -26,3 +27,5 @@ static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsPositive(T value static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsPositive(T value, string? message) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsPositive(T value, string? message, params object?[]? parameters) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.Throws(System.Func! action, ref Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AssertNonStrictThrowsInterpolatedStringHandler message) -> TException! +static Microsoft.VisualStudio.TestTools.UnitTesting.CollectionAssert.Instance.get -> Microsoft.VisualStudio.TestTools.UnitTesting.CollectionAssert! +static Microsoft.VisualStudio.TestTools.UnitTesting.StringAssert.Instance.get -> Microsoft.VisualStudio.TestTools.UnitTesting.StringAssert! diff --git a/test/IntegrationTests/TestAssets/FxExtensibilityTestProject/AssertExTest.cs b/test/IntegrationTests/TestAssets/FxExtensibilityTestProject/AssertExTest.cs index 37e0f8709f..e6852bc745 100644 --- a/test/IntegrationTests/TestAssets/FxExtensibilityTestProject/AssertExTest.cs +++ b/test/IntegrationTests/TestAssets/FxExtensibilityTestProject/AssertExTest.cs @@ -11,16 +11,16 @@ namespace FxExtensibilityTestProject; public class AssertExTest { [TestMethod] - public void BasicAssertExtensionTest() => Assert.That.IsOfType(new ArgumentOutOfRangeException()); + public void BasicAssertExtensionTest() => Assert.Instance.IsOfType(new ArgumentOutOfRangeException()); [TestMethod] [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] - public void BasicFailingAssertExtensionTest() => Assert.That.IsOfType(new ArgumentNullException()); + public void BasicFailingAssertExtensionTest() => Assert.Instance.IsOfType(new ArgumentNullException()); [TestMethod] - public void ChainedAssertExtensionTest() => Assert.That.Is().Divisor(120, 5); + public void ChainedAssertExtensionTest() => Assert.Instance.Is().Divisor(120, 5); [TestMethod] [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] - public void ChainedFailingAssertExtensionTest() => Assert.That.Is().Positive(-10); + public void ChainedFailingAssertExtensionTest() => Assert.Instance.Is().Positive(-10); } diff --git a/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.cs b/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.cs index 91873731a5..e2dbd35660 100644 --- a/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.cs +++ b/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.cs @@ -5,10 +5,10 @@ namespace Microsoft.VisualStudio.TestPlatform.TestFramework.UnitTests; public partial class AssertTests { - #region That tests - public void ThatShouldReturnAnInstanceOfAssert() => Verify(Assert.That is not null); + #region Instance tests + public void InstanceShouldReturnAnInstanceOfAssert() => Verify(Assert.Instance is not null); - public void ThatShouldCacheAssertInstance() => Verify(ReferenceEquals(Assert.That, Assert.That)); + public void InstanceShouldCacheAssertInstance() => Verify(ReferenceEquals(Assert.Instance, Assert.Instance)); #endregion #region ReplaceNullChars tests diff --git a/test/UnitTests/TestFramework.UnitTests/Assertions/CollectionAssertTests.cs b/test/UnitTests/TestFramework.UnitTests/Assertions/CollectionAssertTests.cs index 4c32ca18af..8341740393 100644 --- a/test/UnitTests/TestFramework.UnitTests/Assertions/CollectionAssertTests.cs +++ b/test/UnitTests/TestFramework.UnitTests/Assertions/CollectionAssertTests.cs @@ -9,9 +9,9 @@ namespace Microsoft.VisualStudio.TestPlatform.TestFramework.UnitTests.Assertions public class CollectionAssertTests : TestContainer { - public void ThatShouldReturnAnInstanceOfCollectionAssert() => Verify(CollectionAssert.That is not null); + public void InstanceShouldReturnAnInstanceOfCollectionAssert() => Verify(CollectionAssert.Instance is not null); - public void ThatShouldCacheCollectionAssertInstance() => Verify(CollectionAssert.That == CollectionAssert.That); + public void InstanceShouldCacheCollectionAssertInstance() => Verify(CollectionAssert.Instance == CollectionAssert.Instance); public void CollectionAssertContainsNullabilityPostConditions() { diff --git a/test/UnitTests/TestFramework.UnitTests/Assertions/StringAssertTests.cs b/test/UnitTests/TestFramework.UnitTests/Assertions/StringAssertTests.cs index 7ecf1a3ac8..245950a7d3 100644 --- a/test/UnitTests/TestFramework.UnitTests/Assertions/StringAssertTests.cs +++ b/test/UnitTests/TestFramework.UnitTests/Assertions/StringAssertTests.cs @@ -7,9 +7,9 @@ namespace Microsoft.VisualStudio.TestPlatform.TestFramework.UnitTests.Assertions public class StringAssertTests : TestContainer { - public void ThatShouldReturnAnInstanceOfStringAssert() => Verify(StringAssert.That is not null); + public void InstanceShouldReturnAnInstanceOfStringAssert() => Verify(StringAssert.Instance is not null); - public void ThatShouldCacheStringAssertInstance() => Verify(StringAssert.That == StringAssert.That); + public void InstanceShouldCacheStringAssertInstance() => Verify(StringAssert.Instance == StringAssert.Instance); public void StringAssertContains() { From 1dcce25e9ca4b91d4d5ce563c7d9f6cb20199771 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Wed, 18 Jun 2025 15:35:53 +0200 Subject: [PATCH 113/541] Add support for xlf in editorconfig (#5816) --- .editorconfig | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/.editorconfig b/.editorconfig index 5386ccd6ae..76c9203e22 100644 --- a/.editorconfig +++ b/.editorconfig @@ -35,7 +35,11 @@ charset = utf-8 indent_size = 2 # Xml files -[*.{xml}] +[*.xml] +indent_size = 2 + +# Xlf files +[*.xlf] indent_size = 2 # YAML files @@ -832,4 +836,4 @@ resharper_replace_with_single_call_to_first_or_default_highlighting = warning resharper_replace_conditional_expression_with_null_coalescing_highlighting = warning # Redundant cast -resharper_redundant_cast_highlighting = warning \ No newline at end of file +resharper_redundant_cast_highlighting = warning From e52547dee17aead847bec652233836bc30bbde74 Mon Sep 17 00:00:00 2001 From: Copilot <198982749+Copilot@users.noreply.github.com> Date: Wed, 18 Jun 2025 19:56:38 +0000 Subject: [PATCH 114/541] Improve error message for all Assert.Contains.cs APIs (#5793) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: Evangelink <11340282+Evangelink@users.noreply.github.com> Co-authored-by: Amaury Levé --- .../Assertions/Assert.Contains.cs | 160 ++++++++++++------ .../TestFramework/Assertions/Assert.Count.cs | 2 +- .../PublicAPI/PublicAPI.Shipped.txt | 1 - .../PublicAPI/PublicAPI.Unshipped.txt | 2 + .../Resources/FrameworkMessages.Designer.cs | 54 ++++++ .../Resources/FrameworkMessages.resx | 18 ++ .../Resources/xlf/FrameworkMessages.cs.xlf | 30 ++++ .../Resources/xlf/FrameworkMessages.de.xlf | 30 ++++ .../Resources/xlf/FrameworkMessages.es.xlf | 30 ++++ .../Resources/xlf/FrameworkMessages.fr.xlf | 30 ++++ .../Resources/xlf/FrameworkMessages.it.xlf | 30 ++++ .../Resources/xlf/FrameworkMessages.ja.xlf | 30 ++++ .../Resources/xlf/FrameworkMessages.ko.xlf | 30 ++++ .../Resources/xlf/FrameworkMessages.pl.xlf | 30 ++++ .../Resources/xlf/FrameworkMessages.pt-BR.xlf | 30 ++++ .../Resources/xlf/FrameworkMessages.ru.xlf | 30 ++++ .../Resources/xlf/FrameworkMessages.tr.xlf | 30 ++++ .../xlf/FrameworkMessages.zh-Hans.xlf | 30 ++++ .../xlf/FrameworkMessages.zh-Hant.xlf | 30 ++++ .../Assertions/AssertTests.Contains.cs | 97 +++++++++-- .../Assertions/AssertTests.Items.cs | 20 +-- 21 files changed, 666 insertions(+), 78 deletions(-) diff --git a/src/TestFramework/TestFramework/Assertions/Assert.Contains.cs b/src/TestFramework/TestFramework/Assertions/Assert.Contains.cs index c81dc34187..6290035726 100644 --- a/src/TestFramework/TestFramework/Assertions/Assert.Contains.cs +++ b/src/TestFramework/TestFramework/Assertions/Assert.Contains.cs @@ -35,11 +35,11 @@ public AssertSingleInterpolatedStringHandler(int literalLength, int formattedCou } } - internal TItem ComputeAssertion(string assertionName) + internal TItem ComputeAssertion() { if (_builder is not null) { - ThrowAssertCountFailed(assertionName, 1, _actualCount, _builder.ToString()); + ThrowAssertContainsSingleFailed(_actualCount, _builder.ToString()); } return _item!; @@ -119,7 +119,7 @@ public static T ContainsSingle(IEnumerable collection, string? message) #pragma warning disable IDE0060 // Remove unused parameter public static T ContainsSingle(IEnumerable collection, [InterpolatedStringHandlerArgument(nameof(collection))] ref AssertSingleInterpolatedStringHandler message) #pragma warning restore IDE0060 // Remove unused parameter - => message.ComputeAssertion("ContainsSingle"); + => message.ComputeAssertion(); /// /// Tests whether the specified collection contains exactly one element. @@ -138,7 +138,7 @@ public static T ContainsSingle(IEnumerable collection, [StringSyntax(Strin } string userMessage = BuildUserMessage(message, parameters); - ThrowAssertCountFailed("ContainsSingle", 1, actualCount, userMessage); + ThrowAssertContainsSingleFailed(actualCount, userMessage); // Unreachable code but compiler cannot work it out return default; @@ -185,7 +185,7 @@ public static T ContainsSingle(Func predicate, IEnumerable collec } string userMessage = BuildUserMessage(message, parameters); - ThrowAssertCountFailed("ContainsSingle", 1, actualCount, userMessage); + ThrowAssertSingleMatchFailed(actualCount, userMessage); // Unreachable code but compiler cannot work it out return default; @@ -225,7 +225,7 @@ public static void Contains(T expected, IEnumerable collection, string? me if (!collection.Contains(expected)) { string userMessage = BuildUserMessage(message, parameters); - ThrowAssertFailed("Contains", userMessage); + ThrowAssertContainsItemFailed(userMessage); } } @@ -264,7 +264,7 @@ public static void Contains(T expected, IEnumerable collection, IEqualityC if (!collection.Contains(expected, comparer)) { string userMessage = BuildUserMessage(message, parameters); - ThrowAssertFailed("Contains", userMessage); + ThrowAssertContainsItemFailed(userMessage); } } @@ -281,10 +281,10 @@ public static void Contains(Func predicate, IEnumerable collectio /// Tests whether the specified collection contains the given element. /// /// The type of the collection items. - /// The collection. /// A function to test each element for a condition. + /// The collection. /// The message to display when the assertion fails. - public static void Contains(IEnumerable collection, Func predicate, string? message) + public static void Contains(Func predicate, IEnumerable collection, string? message) => Contains(predicate, collection, message, null); /// @@ -300,7 +300,7 @@ public static void Contains(Func predicate, IEnumerable collectio if (!collection.Any(predicate)) { string userMessage = BuildUserMessage(message, parameters); - ThrowAssertFailed("Contains", userMessage); + ThrowAssertContainsPredicateFailed(userMessage); } } @@ -456,7 +456,7 @@ public static void Contains(string substring, string value, StringComparison com { string userMessage = BuildUserMessage(message, parameters); string finalMessage = string.Format(CultureInfo.CurrentCulture, FrameworkMessages.ContainsFail, value, substring, userMessage); - ThrowAssertFailed("StringAssert.Contains", finalMessage); + ThrowAssertFailed("Assert.Contains", finalMessage); } } @@ -496,7 +496,7 @@ public static void DoesNotContain(T expected, IEnumerable collection, stri if (collection.Contains(expected)) { string userMessage = BuildUserMessage(message, parameters); - ThrowAssertFailed("DoesNotContain", userMessage); + ThrowAssertDoesNotContainItemFailed(userMessage); } } @@ -535,7 +535,7 @@ public static void DoesNotContain(T expected, IEnumerable collection, IEqu if (collection.Contains(expected, comparer)) { string userMessage = BuildUserMessage(message, parameters); - ThrowAssertFailed("DoesNotContain", userMessage); + ThrowAssertDoesNotContainItemFailed(userMessage); } } @@ -571,65 +571,65 @@ public static void DoesNotContain(Func predicate, IEnumerable col if (collection.Any(predicate)) { string userMessage = BuildUserMessage(message, parameters); - ThrowAssertFailed("DoesNotContain", userMessage); + ThrowAssertDoesNotContainPredicateFailed(userMessage); } } /// - /// Tests whether the specified string contains the specified substring - /// and throws an exception if the substring does not occur within the + /// Tests whether the specified string does not contain the specified substring + /// and throws an exception if the substring occurs within the /// test string. /// /// - /// The string expected to occur within . + /// The string expected to not occur within . /// /// - /// The string that is expected to contain . + /// The string that is expected to not contain . /// /// /// is null, or is null, - /// or does not contain . + /// or contains . /// public static void DoesNotContain(string substring, string value) => DoesNotContain(substring, value, StringComparison.Ordinal, string.Empty); /// - /// Tests whether the specified string contains the specified substring - /// and throws an exception if the substring does not occur within the + /// Tests whether the specified string does not contain the specified substring + /// and throws an exception if the substring occurs within the /// test string. /// /// - /// The string expected to occur within . + /// The string expected to not occur within . /// /// - /// The string that is expected to contain . + /// The string that is expected to not contain . /// /// /// The message to include in the exception when - /// is not in . The message is shown in + /// is in . The message is shown in /// test results. /// /// /// is null, or is null, - /// or does not contain . + /// or contains . /// public static void DoesNotContain(string substring, string value, string? message) => DoesNotContain(substring, value, StringComparison.Ordinal, message); /// - /// Tests whether the specified string contains the specified substring - /// and throws an exception if the substring does not occur within the + /// Tests whether the specified string does not contain the specified substring + /// and throws an exception if the substring occurs within the /// test string. /// /// - /// The string expected to occur within . + /// The string expected to not occur within . /// /// - /// The string that is expected to contain . + /// The string that is expected to not contain . /// /// /// The message to include in the exception when - /// is not in . The message is shown in + /// is in . The message is shown in /// test results. /// /// @@ -637,76 +637,76 @@ public static void DoesNotContain(string substring, string value, string? messag /// /// /// is null, or is null, - /// or does not contain . + /// or contains . /// public static void DoesNotContain(string substring, string value, [StringSyntax(StringSyntaxAttribute.CompositeFormat)] string? message, params object?[]? parameters) => DoesNotContain(substring, value, StringComparison.Ordinal, message, parameters); /// - /// Tests whether the specified string contains the specified substring - /// and throws an exception if the substring does not occur within the + /// Tests whether the specified string does not contain the specified substring + /// and throws an exception if the substring occurs within the /// test string. /// /// - /// The string expected to occur within . + /// The string expected to not occur within . /// /// - /// The string that is expected to contain . + /// The string that is expected to not contain . /// /// /// The comparison method to compare strings . /// /// /// is null, or is null, - /// or does not contain . + /// or contains . /// public static void DoesNotContain(string substring, string value, StringComparison comparisonType) => DoesNotContain(substring, value, comparisonType, string.Empty); /// - /// Tests whether the specified string contains the specified substring - /// and throws an exception if the substring does not occur within the + /// Tests whether the specified string does not contain the specified substring + /// and throws an exception if the substring occurs within the /// test string. /// /// - /// The string expected to occur within . + /// The string expected to not occur within . /// /// - /// The string that is expected to contain . + /// The string that is expected to not contain . /// /// /// The comparison method to compare strings . /// /// /// The message to include in the exception when - /// is not in . The message is shown in + /// is in . The message is shown in /// test results. /// /// /// is null, or is null, - /// or does not contain . + /// or contains . /// public static void DoesNotContain(string substring, string value, StringComparison comparisonType, string? message) => DoesNotContain(substring, value, comparisonType, message, null); /// - /// Tests whether the specified string contains the specified substring - /// and throws an exception if the substring does not occur within the + /// Tests whether the specified string does not contain the specified substring + /// and throws an exception if the substring occurs within the /// test string. /// /// - /// The string expected to occur within . + /// The string expected to not occur within . /// /// - /// The string that is expected to contain . + /// The string that is expected to not contain . /// /// /// The comparison method to compare strings . /// /// /// The message to include in the exception when - /// is not in . The message is shown in + /// is in . The message is shown in /// test results. /// /// @@ -714,7 +714,7 @@ public static void DoesNotContain(string substring, string value, StringComparis /// /// /// is null, or is null, - /// or does not contain . + /// or contains . /// public static void DoesNotContain(string substring, string value, StringComparison comparisonType, [StringSyntax(StringSyntaxAttribute.CompositeFormat)] string? message, params object?[]? parameters) @@ -727,7 +727,7 @@ public static void DoesNotContain(string substring, string value, StringComparis { string userMessage = BuildUserMessage(message, parameters); string finalMessage = string.Format(CultureInfo.CurrentCulture, FrameworkMessages.DoesNotContainFail, value, substring, userMessage); - ThrowAssertFailed("StringAssert.DoesNotContain", finalMessage); + ThrowAssertFailed("Assert.DoesNotContain", finalMessage); } } @@ -787,4 +787,66 @@ public static void IsInRange(T minValue, T maxValue, T value, [StringSyntax(S } #endregion // IsInRange + + [DoesNotReturn] + private static void ThrowAssertSingleMatchFailed(int actualCount, string userMessage) + { + string finalMessage = string.Format( + CultureInfo.CurrentCulture, + FrameworkMessages.ContainsSingleMatchFailMsg, + userMessage, + actualCount); + ThrowAssertFailed("Assert.ContainsSingle", finalMessage); + } + + [DoesNotReturn] + private static void ThrowAssertContainsSingleFailed(int actualCount, string userMessage) + { + string finalMessage = string.Format( + CultureInfo.CurrentCulture, + FrameworkMessages.ContainsSingleFailMsg, + userMessage, + actualCount); + ThrowAssertFailed("Assert.ContainsSingle", finalMessage); + } + + [DoesNotReturn] + private static void ThrowAssertContainsItemFailed(string userMessage) + { + string finalMessage = string.Format( + CultureInfo.CurrentCulture, + FrameworkMessages.ContainsItemFailMsg, + userMessage); + ThrowAssertFailed("Assert.Contains", finalMessage); + } + + [DoesNotReturn] + private static void ThrowAssertContainsPredicateFailed(string userMessage) + { + string finalMessage = string.Format( + CultureInfo.CurrentCulture, + FrameworkMessages.ContainsPredicateFailMsg, + userMessage); + ThrowAssertFailed("Assert.Contains", finalMessage); + } + + [DoesNotReturn] + private static void ThrowAssertDoesNotContainItemFailed(string userMessage) + { + string finalMessage = string.Format( + CultureInfo.CurrentCulture, + FrameworkMessages.DoesNotContainItemFailMsg, + userMessage); + ThrowAssertFailed("Assert.DoesNotContain", finalMessage); + } + + [DoesNotReturn] + private static void ThrowAssertDoesNotContainPredicateFailed(string userMessage) + { + string finalMessage = string.Format( + CultureInfo.CurrentCulture, + FrameworkMessages.DoesNotContainPredicateFailMsg, + userMessage); + ThrowAssertFailed("Assert.DoesNotContain", finalMessage); + } } diff --git a/src/TestFramework/TestFramework/Assertions/Assert.Count.cs b/src/TestFramework/TestFramework/Assertions/Assert.Count.cs index 5c01a9e767..d86e37f5a3 100644 --- a/src/TestFramework/TestFramework/Assertions/Assert.Count.cs +++ b/src/TestFramework/TestFramework/Assertions/Assert.Count.cs @@ -320,6 +320,6 @@ private static void ThrowAssertIsNotEmptyFailed(string userMessage) CultureInfo.CurrentCulture, FrameworkMessages.IsNotEmptyFailMsg, userMessage); - ThrowAssertFailed($"Assert.IsNotEmpty", finalMessage); + ThrowAssertFailed("Assert.IsNotEmpty", finalMessage); } } diff --git a/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Shipped.txt b/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Shipped.txt index 6264cadf2f..e05ec781bb 100644 --- a/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Shipped.txt +++ b/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Shipped.txt @@ -624,7 +624,6 @@ static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.Contains(string! subs static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.Contains(string! substring, string! value, System.StringComparison comparisonType, string? message) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.Contains(string! substring, string! value, System.StringComparison comparisonType) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.Contains(string! substring, string! value) -> void -static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.Contains(System.Collections.Generic.IEnumerable! collection, System.Func! predicate, string? message) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.Contains(System.Func! predicate, System.Collections.Generic.IEnumerable! collection, string? message, params object?[]? parameters) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.Contains(System.Func! predicate, System.Collections.Generic.IEnumerable! collection) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.Contains(T expected, System.Collections.Generic.IEnumerable! collection, string? message, params object?[]? parameters) -> void diff --git a/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Unshipped.txt b/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Unshipped.txt index 452b727267..323e0b84f1 100644 --- a/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Unshipped.txt +++ b/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Unshipped.txt @@ -8,6 +8,7 @@ static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsGreaterThanOrEqualT static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsGreaterThanOrEqualTo(T lowerBound, T value, string? message) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsGreaterThanOrEqualTo(T lowerBound, T value, string? message, params object?[]? parameters) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.Instance.get -> Microsoft.VisualStudio.TestTools.UnitTesting.Assert! +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.Contains(System.Func! predicate, System.Collections.Generic.IEnumerable! collection, string? message) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsInRange(T minValue, T maxValue, T value) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsInRange(T minValue, T maxValue, T value, string? message) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsInRange(T minValue, T maxValue, T value, string? message, params object?[]? parameters) -> void @@ -29,3 +30,4 @@ static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsPositive(T value static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.Throws(System.Func! action, ref Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AssertNonStrictThrowsInterpolatedStringHandler message) -> TException! static Microsoft.VisualStudio.TestTools.UnitTesting.CollectionAssert.Instance.get -> Microsoft.VisualStudio.TestTools.UnitTesting.CollectionAssert! static Microsoft.VisualStudio.TestTools.UnitTesting.StringAssert.Instance.get -> Microsoft.VisualStudio.TestTools.UnitTesting.StringAssert! +*REMOVED*static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.Contains(System.Collections.Generic.IEnumerable! collection, System.Func! predicate, string? message) -> void diff --git a/src/TestFramework/TestFramework/Resources/FrameworkMessages.Designer.cs b/src/TestFramework/TestFramework/Resources/FrameworkMessages.Designer.cs index 346096f271..df310e3fea 100644 --- a/src/TestFramework/TestFramework/Resources/FrameworkMessages.Designer.cs +++ b/src/TestFramework/TestFramework/Resources/FrameworkMessages.Designer.cs @@ -395,6 +395,60 @@ internal static string HasCountFailMsg { } } + /// + /// Looks up a localized string similar to Expected exactly one item to match the predicate. Actual: {1}. {0}. + /// + internal static string ContainsSingleMatchFailMsg { + get { + return ResourceManager.GetString("ContainsSingleMatchFailMsg", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Expected collection to contain exactly one element. Actual: {1}. {0}. + /// + internal static string ContainsSingleFailMsg { + get { + return ResourceManager.GetString("ContainsSingleFailMsg", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Expected collection to contain '{1}'. {0}. + /// + internal static string ContainsItemFailMsg { + get { + return ResourceManager.GetString("ContainsItemFailMsg", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Expected at least one item to match the predicate. {0}. + /// + internal static string ContainsPredicateFailMsg { + get { + return ResourceManager.GetString("ContainsPredicateFailMsg", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Expected collection to not contain '{1}'. {0}. + /// + internal static string DoesNotContainItemFailMsg { + get { + return ResourceManager.GetString("DoesNotContainItemFailMsg", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Expected no items to match the predicate. {0}. + /// + internal static string DoesNotContainPredicateFailMsg { + get { + return ResourceManager.GetString("DoesNotContainPredicateFailMsg", resourceCulture); + } + } + /// /// Looks up a localized string similar to Invalid GitHub ticket URL. /// diff --git a/src/TestFramework/TestFramework/Resources/FrameworkMessages.resx b/src/TestFramework/TestFramework/Resources/FrameworkMessages.resx index 9df59c95fa..3a4cad3de9 100644 --- a/src/TestFramework/TestFramework/Resources/FrameworkMessages.resx +++ b/src/TestFramework/TestFramework/Resources/FrameworkMessages.resx @@ -296,6 +296,24 @@ Actual: {2} Expected collection of size {1}. Actual: {2}. {0} + + Expected exactly one item to match the predicate but found {1} item(s). {0} + + + Expected collection to contain exactly one element but found {1} element(s). {0} + + + Expected collection to contain the specified item. {0} + + + Expected at least one item to match the predicate. {0} + + + Expected collection to not contain the specified item. {0} + + + Expected no items to match the predicate. {0} + Expected collection to contain any item but it is empty. {0} diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.cs.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.cs.xlf index 053e32f458..c24e84e14d 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.cs.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.cs.xlf @@ -82,11 +82,41 @@ Řetězec '{0}' neobsahuje řetězec '{1}'. {2}. + + Expected collection to contain the specified item. {0} + Expected collection to contain the specified item. {0} + + + + Expected at least one item to match the predicate. {0} + Expected at least one item to match the predicate. {0} + + + + Expected collection to contain exactly one element but found {1} element(s). {0} + Expected collection to contain exactly one element but found {1} element(s). {0} + + + + Expected exactly one item to match the predicate but found {1} item(s). {0} + Expected exactly one item to match the predicate but found {1} item(s). {0} + + String '{0}' does contain string '{1}'. {2}. Řetězec {0} obsahuje řetězec {1}. {2}. + + Expected collection to not contain the specified item. {0} + Expected collection to not contain the specified item. {0} + + + + Expected no items to match the predicate. {0} + Expected no items to match the predicate. {0} + + Dynamic data method '{0}' should be static, parameterless and non-generic. Metoda dynamických dat {0} by měla být statická, bez parametrů a negenerická. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.de.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.de.xlf index 8306786e8c..ccf1e56764 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.de.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.de.xlf @@ -82,11 +82,41 @@ Die Zeichenfolge "{0}" enthält nicht die Zeichenfolge "{1}". {2}. + + Expected collection to contain the specified item. {0} + Expected collection to contain the specified item. {0} + + + + Expected at least one item to match the predicate. {0} + Expected at least one item to match the predicate. {0} + + + + Expected collection to contain exactly one element but found {1} element(s). {0} + Expected collection to contain exactly one element. Actual: {1}. {0} + + + + Expected exactly one item to match the predicate but found {1} item(s). {0} + Expected exactly one item to match the predicate. Actual: {1}. {0} + + String '{0}' does contain string '{1}'. {2}. Die Zeichenfolge „{0}“ enthält die Zeichenfolge „{1}“. {2}. + + Expected collection to not contain the specified item. {0} + Expected collection to not contain the specified item. {0} + + + + Expected no items to match the predicate. {0} + Expected no items to match the predicate. {0} + + Dynamic data method '{0}' should be static, parameterless and non-generic. Die dynamische Datenmethode "{0}" muss statisch, parameterlos sein und nichtgenerisch sein. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.es.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.es.xlf index e81069cbc7..dcf3fdcd10 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.es.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.es.xlf @@ -82,11 +82,41 @@ La cadena '{0}' no contiene la cadena '{1}'. {2}. + + Expected collection to contain the specified item. {0} + Expected collection to contain the specified item. {0} + + + + Expected at least one item to match the predicate. {0} + Expected at least one item to match the predicate. {0} + + + + Expected collection to contain exactly one element but found {1} element(s). {0} + Expected collection to contain exactly one element. Actual: {1}. {0} + + + + Expected exactly one item to match the predicate but found {1} item(s). {0} + Expected exactly one item to match the predicate. Actual: {1}. {0} + + String '{0}' does contain string '{1}'. {2}. La cadena '{0}' contiene la cadena '{1}'. {2}. + + Expected collection to not contain the specified item. {0} + Expected collection to not contain the specified item. {0} + + + + Expected no items to match the predicate. {0} + Expected no items to match the predicate. {0} + + Dynamic data method '{0}' should be static, parameterless and non-generic. El método de datos dinámicos '{0}' debe ser estático, sin parámetros y no genérico. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.fr.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.fr.xlf index 1084bf3f8c..ca23e9c56d 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.fr.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.fr.xlf @@ -82,11 +82,41 @@ La chaîne '{0}' ne contient pas la chaîne '{1}'. {2}. + + Expected collection to contain the specified item. {0} + Expected collection to contain the specified item. {0} + + + + Expected at least one item to match the predicate. {0} + Expected at least one item to match the predicate. {0} + + + + Expected collection to contain exactly one element but found {1} element(s). {0} + Expected collection to contain exactly one element. Actual: {1}. {0} + + + + Expected exactly one item to match the predicate but found {1} item(s). {0} + Expected exactly one item to match the predicate. Actual: {1}. {0} + + String '{0}' does contain string '{1}'. {2}. La chaîne « {0} » contient la chaîne « {1} ». {2}. + + Expected collection to not contain the specified item. {0} + Expected collection to not contain the specified item. {0} + + + + Expected no items to match the predicate. {0} + Expected no items to match the predicate. {0} + + Dynamic data method '{0}' should be static, parameterless and non-generic. La méthode de données dynamiques « {0} » doit être statique, sans paramètre et non générique. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.it.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.it.xlf index 6c38f092db..9f413a85bf 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.it.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.it.xlf @@ -82,11 +82,41 @@ La stringa '{0}' non contiene la stringa '{1}'. {2}. + + Expected collection to contain the specified item. {0} + Expected collection to contain the specified item. {0} + + + + Expected at least one item to match the predicate. {0} + Expected at least one item to match the predicate. {0} + + + + Expected collection to contain exactly one element but found {1} element(s). {0} + Expected collection to contain exactly one element. Actual: {1}. {0} + + + + Expected exactly one item to match the predicate but found {1} item(s). {0} + Expected exactly one item to match the predicate. Actual: {1}. {0} + + String '{0}' does contain string '{1}'. {2}. La stringa '{0}' contiene la stringa '{1}'. {2}. + + Expected collection to not contain the specified item. {0} + Expected collection to not contain the specified item. {0} + + + + Expected no items to match the predicate. {0} + Expected no items to match the predicate. {0} + + Dynamic data method '{0}' should be static, parameterless and non-generic. Il metodo '{0}' di Dynamic Data deve essere statico, senza parametri e non generico. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ja.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ja.xlf index b55df0c903..7c684ac724 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ja.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ja.xlf @@ -82,11 +82,41 @@ 文字列 '{0}' は文字列 '{1}' を含んでいません。{2}。 + + Expected collection to contain the specified item. {0} + Expected collection to contain the specified item. {0} + + + + Expected at least one item to match the predicate. {0} + Expected at least one item to match the predicate. {0} + + + + Expected collection to contain exactly one element but found {1} element(s). {0} + Expected collection to contain exactly one element. Actual: {1}. {0} + + + + Expected exactly one item to match the predicate but found {1} item(s). {0} + Expected exactly one item to match the predicate. Actual: {1}. {0} + + String '{0}' does contain string '{1}'. {2}. 文字列 '{0}' は文字列 '{1}' を含んでいます。{2}。 + + Expected collection to not contain the specified item. {0} + Expected collection to not contain the specified item. {0} + + + + Expected no items to match the predicate. {0} + Expected no items to match the predicate. {0} + + Dynamic data method '{0}' should be static, parameterless and non-generic. 動的データ メソッド '{0}' は、静的、パラメーターなし、および非ジェネリックである必要があります。 diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ko.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ko.xlf index fa13dee467..03240de39a 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ko.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ko.xlf @@ -82,11 +82,41 @@ '{0}' 문자열이 '{1}' 문자열을 포함하지 않습니다. {2} + + Expected collection to contain the specified item. {0} + Expected collection to contain the specified item. {0} + + + + Expected at least one item to match the predicate. {0} + Expected at least one item to match the predicate. {0} + + + + Expected collection to contain exactly one element but found {1} element(s). {0} + Expected collection to contain exactly one element. Actual: {1}. {0} + + + + Expected exactly one item to match the predicate but found {1} item(s). {0} + Expected exactly one item to match the predicate. Actual: {1}. {0} + + String '{0}' does contain string '{1}'. {2}. '{0}' 문자열에 '{1}' 문자열이 포함되어 있습니다. {2}. + + Expected collection to not contain the specified item. {0} + Expected collection to not contain the specified item. {0} + + + + Expected no items to match the predicate. {0} + Expected no items to match the predicate. {0} + + Dynamic data method '{0}' should be static, parameterless and non-generic. 동적 데이터 메서드 '{0}'은(는) 정적이고 매개 변수가 없으며 제네릭이 아니어야 합니다. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pl.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pl.xlf index 6cb27f8a76..7672e5af80 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pl.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pl.xlf @@ -82,11 +82,41 @@ Ciąg „{0}” nie zawiera ciągu „{1}”. {2}. + + Expected collection to contain the specified item. {0} + Expected collection to contain the specified item. {0} + + + + Expected at least one item to match the predicate. {0} + Expected at least one item to match the predicate. {0} + + + + Expected collection to contain exactly one element but found {1} element(s). {0} + Expected collection to contain exactly one element. Actual: {1}. {0} + + + + Expected exactly one item to match the predicate but found {1} item(s). {0} + Expected exactly one item to match the predicate. Actual: {1}. {0} + + String '{0}' does contain string '{1}'. {2}. Ciąg „{0}” zawiera ciąg „{1}”. {2}. + + Expected collection to not contain the specified item. {0} + Expected collection to not contain the specified item. {0} + + + + Expected no items to match the predicate. {0} + Expected no items to match the predicate. {0} + + Dynamic data method '{0}' should be static, parameterless and non-generic. Metoda danych dynamicznych „{0}” powinna być statyczna, bez parametrów i nie generyczna. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf index 5b9618f714..31a306ed06 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf @@ -82,11 +82,41 @@ A cadeia de caracteres '{0}' não contém a cadeia de caracteres '{1}'. {2}. + + Expected collection to contain the specified item. {0} + Expected collection to contain the specified item. {0} + + + + Expected at least one item to match the predicate. {0} + Expected at least one item to match the predicate. {0} + + + + Expected collection to contain exactly one element but found {1} element(s). {0} + Expected collection to contain exactly one element. Actual: {1}. {0} + + + + Expected exactly one item to match the predicate but found {1} item(s). {0} + Expected exactly one item to match the predicate. Actual: {1}. {0} + + String '{0}' does contain string '{1}'. {2}. A cadeia de caracteres "{0}" contém a cadeia de caracteres "{1}". {2}. + + Expected collection to not contain the specified item. {0} + Expected collection to not contain the specified item. {0} + + + + Expected no items to match the predicate. {0} + Expected no items to match the predicate. {0} + + Dynamic data method '{0}' should be static, parameterless and non-generic. O método de dados dinâmicos "{0}" deve ser estático, sem parâmetros e não genérico. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ru.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ru.xlf index 49354000c7..3e1b32c2fa 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ru.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ru.xlf @@ -82,11 +82,41 @@ Строка "{0}" не содержит строку "{1}". {2}. + + Expected collection to contain the specified item. {0} + Expected collection to contain the specified item. {0} + + + + Expected at least one item to match the predicate. {0} + Expected at least one item to match the predicate. {0} + + + + Expected collection to contain exactly one element but found {1} element(s). {0} + Expected collection to contain exactly one element. Actual: {1}. {0} + + + + Expected exactly one item to match the predicate but found {1} item(s). {0} + Expected exactly one item to match the predicate. Actual: {1}. {0} + + String '{0}' does contain string '{1}'. {2}. Строка "{0}" не содержит строку "{1}". {2}. + + Expected collection to not contain the specified item. {0} + Expected collection to not contain the specified item. {0} + + + + Expected no items to match the predicate. {0} + Expected no items to match the predicate. {0} + + Dynamic data method '{0}' should be static, parameterless and non-generic. Метод динамических данных "{0}" должен быть статическим, не иметь параметров и быть неуниверсальным. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.tr.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.tr.xlf index feb6805ebd..b71a3d0cac 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.tr.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.tr.xlf @@ -82,11 +82,41 @@ '{0}' dizesi, '{1}' dizesini içermiyor. {2}. + + Expected collection to contain the specified item. {0} + Expected collection to contain the specified item. {0} + + + + Expected at least one item to match the predicate. {0} + Expected at least one item to match the predicate. {0} + + + + Expected collection to contain exactly one element but found {1} element(s). {0} + Expected collection to contain exactly one element. Actual: {1}. {0} + + + + Expected exactly one item to match the predicate but found {1} item(s). {0} + Expected exactly one item to match the predicate. Actual: {1}. {0} + + String '{0}' does contain string '{1}'. {2}. '{0}' dizesi, '{1}' dizesini içermiyor. {2}. + + Expected collection to not contain the specified item. {0} + Expected collection to not contain the specified item. {0} + + + + Expected no items to match the predicate. {0} + Expected no items to match the predicate. {0} + + Dynamic data method '{0}' should be static, parameterless and non-generic. '{0}' dinamik veri yöntemi statik ve parametresiz olmalı ve genel olmamalıdır. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf index e61a0f94f0..42a13ba135 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf @@ -82,11 +82,41 @@ 字符串“{0}”不包含字符串“{1}”。{2}。 + + Expected collection to contain the specified item. {0} + Expected collection to contain the specified item. {0} + + + + Expected at least one item to match the predicate. {0} + Expected at least one item to match the predicate. {0} + + + + Expected collection to contain exactly one element but found {1} element(s). {0} + Expected collection to contain exactly one element. Actual: {1}. {0} + + + + Expected exactly one item to match the predicate but found {1} item(s). {0} + Expected exactly one item to match the predicate. Actual: {1}. {0} + + String '{0}' does contain string '{1}'. {2}. 字符串“{0}”确实包含字符串“{1}”。{2} + + Expected collection to not contain the specified item. {0} + Expected collection to not contain the specified item. {0} + + + + Expected no items to match the predicate. {0} + Expected no items to match the predicate. {0} + + Dynamic data method '{0}' should be static, parameterless and non-generic. 动态数据方法“{0}”应为静态、无参数和非泛型。 diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf index d6e525a898..c3e50cf656 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf @@ -82,11 +82,41 @@ 字串 '{0}' 未包含字串 '{1}'。{2}。 + + Expected collection to contain the specified item. {0} + Expected collection to contain the specified item. {0} + + + + Expected at least one item to match the predicate. {0} + Expected at least one item to match the predicate. {0} + + + + Expected collection to contain exactly one element but found {1} element(s). {0} + Expected collection to contain exactly one element. Actual: {1}. {0} + + + + Expected exactly one item to match the predicate but found {1} item(s). {0} + Expected exactly one item to match the predicate. Actual: {1}. {0} + + String '{0}' does contain string '{1}'. {2}. 字串 '{0}' 有包含字串 '{1}'。{2}。 + + Expected collection to not contain the specified item. {0} + Expected collection to not contain the specified item. {0} + + + + Expected no items to match the predicate. {0} + Expected no items to match the predicate. {0} + + Dynamic data method '{0}' should be static, parameterless and non-generic. 動態資料方法 '{0}' 應為靜態、無參數及非泛型。 diff --git a/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.Contains.cs b/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.Contains.cs index fd497214e4..6d885b74fc 100644 --- a/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.Contains.cs +++ b/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.Contains.cs @@ -19,14 +19,13 @@ public partial class AssertTests : TestContainer /// /// The type parameter. /// The handler instance. - /// The assertion name. /// The exception message thrown by ComputeAssertion. - private static string GetComputeAssertionExceptionMessage(Assert.AssertSingleInterpolatedStringHandler handler, string assertionName) + private static string GetComputeAssertionExceptionMessage(Assert.AssertSingleInterpolatedStringHandler handler) { try { // This call is expected to throw when _builder is not null. - _ = handler.ComputeAssertion(assertionName); + _ = handler.ComputeAssertion(); } catch (Exception ex) { @@ -52,7 +51,7 @@ public void ComputeAssertion_WhenCollectionHasSingleElement_ReturnsElement() shouldAppend.Should().BeFalse(); // Act - int result = handler.ComputeAssertion("ContainsSingle"); + int result = handler.ComputeAssertion(); // Assert result.Should().Be(singleItem); @@ -69,7 +68,7 @@ public void ComputeAssertion_WhenCollectionDoesNotHaveSingleElement_ThrowsExcept shouldAppend.Should().BeTrue(); // Act - string exMsg = GetComputeAssertionExceptionMessage(handler, "ContainsSingle"); + string exMsg = GetComputeAssertionExceptionMessage(handler); // Assert: verify that the exception message contains expected parts. exMsg.Should().Contain("ContainsSingle"); @@ -93,7 +92,7 @@ public void AppendLiteral_WhenCalled_AppendsLiteralText() handler.AppendLiteral(literal); // Act - string exMsg = GetComputeAssertionExceptionMessage(handler, "ContainsSingle"); + string exMsg = GetComputeAssertionExceptionMessage(handler); // Assert: the exception message should contain the literal appended. exMsg.Should().Contain(literal); @@ -112,7 +111,7 @@ public void AppendFormatted_GenericValue_WithoutFormat_AppendsValue() handler.AppendFormatted(value); // Act - string exMsg = GetComputeAssertionExceptionMessage(handler, "ContainsSingle"); + string exMsg = GetComputeAssertionExceptionMessage(handler); // Assert exMsg.Should().Contain(value); @@ -132,7 +131,7 @@ public void AppendFormatted_GenericValue_WithFormat_AppendsFormattedValue() handler.AppendFormatted(value, format); // Act - string exMsg = GetComputeAssertionExceptionMessage(handler, "ContainsSingle"); + string exMsg = GetComputeAssertionExceptionMessage(handler); // Assert: Check if the value was formatted accordingly ("00123") exMsg.Should().Contain("00123"); @@ -152,7 +151,7 @@ public void AppendFormatted_GenericValue_WithAlignment_AppendsAlignedValue() handler.AppendFormatted(value, alignment); // Act - string exMsg = GetComputeAssertionExceptionMessage(handler, "ContainsSingle"); + string exMsg = GetComputeAssertionExceptionMessage(handler); // Assert: alignment is applied via StringBuilder.AppendFormat so result should contain formatted spacing. exMsg.Should().Contain("3.14"); @@ -173,7 +172,7 @@ public void AppendFormatted_GenericValue_WithAlignmentAndFormat_AppendsFormatted handler.AppendFormatted(value, alignment, format); // Act - string exMsg = GetComputeAssertionExceptionMessage(handler, "ContainsSingle"); + string exMsg = GetComputeAssertionExceptionMessage(handler); // Assert: formatted year "2023" should appear. exMsg.Should().Contain("2023"); @@ -192,7 +191,7 @@ public void AppendFormatted_StringValue_WithoutAdditionalParameters_AppendsStrin handler.AppendFormatted(value); // Act - string exMsg = GetComputeAssertionExceptionMessage(handler, "ContainsSingle"); + string exMsg = GetComputeAssertionExceptionMessage(handler); // Assert exMsg.Should().Contain(value); @@ -213,7 +212,7 @@ public void AppendFormatted_StringValue_WithAlignmentAndFormat_AppendsFormattedS handler.AppendFormatted(value, alignment, format); // Act - string exMsg = GetComputeAssertionExceptionMessage(handler, "ContainsSingle"); + string exMsg = GetComputeAssertionExceptionMessage(handler); // Assert exMsg.Should().Contain(value); @@ -234,7 +233,7 @@ public void AppendFormatted_ObjectValue_WithAlignmentAndFormat_AppendsFormattedO handler.AppendFormatted(value, alignment, format); // Act - string exMsg = GetComputeAssertionExceptionMessage(handler, "ContainsSingle"); + string exMsg = GetComputeAssertionExceptionMessage(handler); // Assert: Formatted value should appear (e.g. "099"). exMsg.Should().Contain("099"); @@ -254,7 +253,7 @@ public void AppendFormatted_ReadOnlySpan_AppendsSpanValue() handler.AppendFormatted(spanValue); // Act - string exMsg = GetComputeAssertionExceptionMessage(handler, "ContainsSingle"); + string exMsg = GetComputeAssertionExceptionMessage(handler); // Assert exMsg.Should().Contain("SpanText"); @@ -309,7 +308,7 @@ public void ContainsSingle_InterpolatedHandler_WithMultipleElements_ThrowsExcept Action action = () => Assert.ContainsSingle(collection, ref handler); // Assert - action.Should().Throw().WithMessage("*1*"); + action.Should().Throw().WithMessage("Assert.ContainsSingle failed. Expected collection to contain exactly one element but found 3 element(s). "); } /// @@ -643,7 +642,7 @@ public void ContainsSinglePredicate_NoItemMatches_ThrowsException() Action action = () => Assert.ContainsSingle(x => x % 2 == 0, collection); // Assert - action.Should().Throw().WithMessage("*Expected collection of size 1. Actual: 0*"); + action.Should().Throw().WithMessage("*Expected exactly one item to match the predicate but found 0 item(s)*"); } /// @@ -659,7 +658,7 @@ public void ContainsSinglePredicate_MultipleItemsMatch_ThrowsException() Action action = () => Assert.ContainsSingle(x => x % 2 == 0, collection); // Assert - action.Should().Throw().WithMessage("*Expected collection of size 1. Actual: 4*"); + action.Should().Throw().WithMessage("*Expected exactly one item to match the predicate but found 4 item(s)*"); } /// @@ -730,6 +729,70 @@ public void ContainsSinglePredicate_WithNullValues_OneItemMatches_ReturnsElement result.Should().BeNull(); } + #region New Error Message Tests + + /// + /// Tests that Contains (item) failure shows specific error message. + /// + public void Contains_ItemNotFound_ShowsSpecificErrorMessage() + { + // Arrange + var collection = new List { 1, 2, 3 }; + + // Act + Action action = () => Assert.Contains(5, collection); + + // Assert + action.Should().Throw().WithMessage("*Expected collection to contain the specified item*"); + } + + /// + /// Tests that Contains (predicate) failure shows specific error message. + /// + public void Contains_PredicateNotMatched_ShowsSpecificErrorMessage() + { + // Arrange + var collection = new List { 1, 3, 5 }; + + // Act + Action action = () => Assert.Contains(x => x % 2 == 0, collection); + + // Assert + action.Should().Throw().WithMessage("*Expected at least one item to match the predicate*"); + } + + /// + /// Tests that DoesNotContain (item) failure shows specific error message. + /// + public void DoesNotContain_ItemFound_ShowsSpecificErrorMessage() + { + // Arrange + var collection = new List { 1, 2, 3 }; + + // Act + Action action = () => Assert.DoesNotContain(2, collection); + + // Assert + action.Should().Throw().WithMessage("*Expected collection to not contain the specified item*"); + } + + /// + /// Tests that DoesNotContain (predicate) failure shows specific error message. + /// + public void DoesNotContain_PredicateMatched_ShowsSpecificErrorMessage() + { + // Arrange + var collection = new List { 1, 2, 3 }; + + // Act + Action action = () => Assert.DoesNotContain(x => x % 2 == 0, collection); + + // Assert + action.Should().Throw().WithMessage("*Expected no items to match the predicate*"); + } + + #endregion + private record Person(string Name, int Age); #endregion diff --git a/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.Items.cs b/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.Items.cs index 0008ee22e5..2f5ece1027 100644 --- a/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.Items.cs +++ b/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.Items.cs @@ -92,25 +92,25 @@ public void Single_InterpolatedString_WhenOneItem_ShouldPass() public void Single_WhenNoItems_ShouldFail() { Exception ex = VerifyThrows(() => Assert.ContainsSingle(Array.Empty())); - Verify(ex.Message == "Assert.ContainsSingle failed. Expected collection of size 1. Actual: 0. "); + Verify(ex.Message == "Assert.ContainsSingle failed. Expected collection to contain exactly one element but found 0 element(s). "); } public void Single_WhenMultipleItems_ShouldFail() { Exception ex = VerifyThrows(() => Assert.ContainsSingle([1, 2, 3])); - Verify(ex.Message == "Assert.ContainsSingle failed. Expected collection of size 1. Actual: 3. "); + Verify(ex.Message == "Assert.ContainsSingle failed. Expected collection to contain exactly one element but found 3 element(s). "); } public void Single_MessageArgs_WhenNoItem_ShouldFail() { Exception ex = VerifyThrows(() => Assert.ContainsSingle(Array.Empty(), "User-provided message: System.Object type: {0}", new object().GetType())); - Verify(ex.Message == "Assert.ContainsSingle failed. Expected collection of size 1. Actual: 0. User-provided message: System.Object type: System.Object"); + Verify(ex.Message == "Assert.ContainsSingle failed. Expected collection to contain exactly one element but found 0 element(s). User-provided message: System.Object type: System.Object"); } public void Single_MessageArgs_WhenMultipleItems_ShouldFail() { Exception ex = VerifyThrows(() => Assert.ContainsSingle([1, 2, 3], "User-provided message: System.Object type: {0}", new object().GetType())); - Verify(ex.Message == "Assert.ContainsSingle failed. Expected collection of size 1. Actual: 3. User-provided message: System.Object type: System.Object"); + Verify(ex.Message == "Assert.ContainsSingle failed. Expected collection to contain exactly one element but found 3 element(s). User-provided message: System.Object type: System.Object"); } public async Task Single_InterpolatedString_WhenNoItem_ShouldFail() @@ -118,7 +118,7 @@ public async Task Single_InterpolatedString_WhenNoItem_ShouldFail() DummyClassTrackingToStringCalls o = new(); DateTime dateTime = DateTime.Now; Exception ex = await VerifyThrowsAsync(async () => Assert.ContainsSingle(Array.Empty(), $"User-provided message. {o}, {o,35}, {await GetHelloStringAsync()}, {new DummyIFormattable()}, {dateTime:tt}, {dateTime,5:tt}")); - Verify(ex.Message == $"Assert.ContainsSingle failed. Expected collection of size 1. Actual: 0. User-provided message. DummyClassTrackingToStringCalls, DummyClassTrackingToStringCalls, Hello, DummyIFormattable.ToString(), {string.Format(null, "{0:tt}", dateTime)}, {string.Format(null, "{0,5:tt}", dateTime)}"); + Verify(ex.Message == $"Assert.ContainsSingle failed. Expected collection to contain exactly one element but found 0 element(s). User-provided message. DummyClassTrackingToStringCalls, DummyClassTrackingToStringCalls, Hello, DummyIFormattable.ToString(), {string.Format(null, "{0:tt}", dateTime)}, {string.Format(null, "{0,5:tt}", dateTime)}"); Verify(o.WasToStringCalled); } @@ -127,7 +127,7 @@ public async Task Single_InterpolatedString_WhenMultipleItems_ShouldFail() DummyClassTrackingToStringCalls o = new(); DateTime dateTime = DateTime.Now; Exception ex = await VerifyThrowsAsync(async () => Assert.ContainsSingle([1, 2, 3], $"User-provided message. {o}, {o,35}, {await GetHelloStringAsync()}, {new DummyIFormattable()}, {dateTime:tt}, {dateTime,5:tt}")); - Verify(ex.Message == $"Assert.ContainsSingle failed. Expected collection of size 1. Actual: 3. User-provided message. DummyClassTrackingToStringCalls, DummyClassTrackingToStringCalls, Hello, DummyIFormattable.ToString(), {string.Format(null, "{0:tt}", dateTime)}, {string.Format(null, "{0,5:tt}", dateTime)}"); + Verify(ex.Message == $"Assert.ContainsSingle failed. Expected collection to contain exactly one element but found 3 element(s). User-provided message. DummyClassTrackingToStringCalls, DummyClassTrackingToStringCalls, Hello, DummyIFormattable.ToString(), {string.Format(null, "{0:tt}", dateTime)}, {string.Format(null, "{0,5:tt}", dateTime)}"); Verify(o.WasToStringCalled); } @@ -151,28 +151,28 @@ public void SinglePredicate_WhenNoItemMatches_ShouldFail() { var collection = new List { 1, 3, 5 }; Exception ex = VerifyThrows(() => Assert.ContainsSingle(x => x % 2 == 0, collection)); - Verify(ex.Message == "Assert.ContainsSingle failed. Expected collection of size 1. Actual: 0. "); + Verify(ex.Message == "Assert.ContainsSingle failed. Expected exactly one item to match the predicate but found 0 item(s). "); } public void SinglePredicate_WhenMultipleItemsMatch_ShouldFail() { var collection = new List { 2, 4, 6 }; Exception ex = VerifyThrows(() => Assert.ContainsSingle(x => x % 2 == 0, collection)); - Verify(ex.Message == "Assert.ContainsSingle failed. Expected collection of size 1. Actual: 3. "); + Verify(ex.Message == "Assert.ContainsSingle failed. Expected exactly one item to match the predicate but found 3 item(s). "); } public void SinglePredicate_MessageArgs_WhenNoItemMatches_ShouldFail() { var collection = new List { 1, 3, 5 }; Exception ex = VerifyThrows(() => Assert.ContainsSingle(x => x % 2 == 0, collection, "No even numbers found: {0}", "test")); - Verify(ex.Message == "Assert.ContainsSingle failed. Expected collection of size 1. Actual: 0. No even numbers found: test"); + Verify(ex.Message == "Assert.ContainsSingle failed. Expected exactly one item to match the predicate but found 0 item(s). No even numbers found: test"); } public void SinglePredicate_MessageArgs_WhenMultipleItemsMatch_ShouldFail() { var collection = new List { 2, 4, 6 }; Exception ex = VerifyThrows(() => Assert.ContainsSingle(x => x % 2 == 0, collection, "Too many even numbers: {0}", "test")); - Verify(ex.Message == "Assert.ContainsSingle failed. Expected collection of size 1. Actual: 3. Too many even numbers: test"); + Verify(ex.Message == "Assert.ContainsSingle failed. Expected exactly one item to match the predicate but found 3 item(s). Too many even numbers: test"); } public void Any_WhenOneItem_ShouldPass() From d6e481e955cc963dcc6c8e3071f231d7d69041a0 Mon Sep 17 00:00:00 2001 From: dotnet bot Date: Wed, 18 Jun 2025 22:15:33 +0200 Subject: [PATCH 115/541] Localized file check-in by OneLocBuild Task: Build definition ID 1218: Build ID 2733074 --- .../TestFramework/Resources/xlf/FrameworkMessages.de.xlf | 4 ++-- .../TestFramework/Resources/xlf/FrameworkMessages.es.xlf | 4 ++-- .../TestFramework/Resources/xlf/FrameworkMessages.fr.xlf | 4 ++-- .../TestFramework/Resources/xlf/FrameworkMessages.it.xlf | 4 ++-- .../TestFramework/Resources/xlf/FrameworkMessages.ja.xlf | 4 ++-- .../TestFramework/Resources/xlf/FrameworkMessages.ko.xlf | 4 ++-- .../TestFramework/Resources/xlf/FrameworkMessages.pl.xlf | 4 ++-- .../TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf | 4 ++-- .../TestFramework/Resources/xlf/FrameworkMessages.ru.xlf | 4 ++-- .../TestFramework/Resources/xlf/FrameworkMessages.tr.xlf | 4 ++-- .../TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf | 4 ++-- .../TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf | 4 ++-- 12 files changed, 24 insertions(+), 24 deletions(-) diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.de.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.de.xlf index ccf1e56764..23ed27cc41 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.de.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.de.xlf @@ -94,12 +94,12 @@ Expected collection to contain exactly one element but found {1} element(s). {0} - Expected collection to contain exactly one element. Actual: {1}. {0} + Expected collection to contain exactly one element but found {1} element(s). {0} Expected exactly one item to match the predicate but found {1} item(s). {0} - Expected exactly one item to match the predicate. Actual: {1}. {0} + Expected exactly one item to match the predicate but found {1} item(s). {0} diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.es.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.es.xlf index dcf3fdcd10..ec6395cb5d 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.es.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.es.xlf @@ -94,12 +94,12 @@ Expected collection to contain exactly one element but found {1} element(s). {0} - Expected collection to contain exactly one element. Actual: {1}. {0} + Expected collection to contain exactly one element but found {1} element(s). {0} Expected exactly one item to match the predicate but found {1} item(s). {0} - Expected exactly one item to match the predicate. Actual: {1}. {0} + Expected exactly one item to match the predicate but found {1} item(s). {0} diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.fr.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.fr.xlf index ca23e9c56d..b0945cd203 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.fr.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.fr.xlf @@ -94,12 +94,12 @@ Expected collection to contain exactly one element but found {1} element(s). {0} - Expected collection to contain exactly one element. Actual: {1}. {0} + Expected collection to contain exactly one element but found {1} element(s). {0} Expected exactly one item to match the predicate but found {1} item(s). {0} - Expected exactly one item to match the predicate. Actual: {1}. {0} + Expected exactly one item to match the predicate but found {1} item(s). {0} diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.it.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.it.xlf index 9f413a85bf..6a286037b5 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.it.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.it.xlf @@ -94,12 +94,12 @@ Expected collection to contain exactly one element but found {1} element(s). {0} - Expected collection to contain exactly one element. Actual: {1}. {0} + Expected collection to contain exactly one element but found {1} element(s). {0} Expected exactly one item to match the predicate but found {1} item(s). {0} - Expected exactly one item to match the predicate. Actual: {1}. {0} + Expected exactly one item to match the predicate but found {1} item(s). {0} diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ja.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ja.xlf index 7c684ac724..94b6a9785b 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ja.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ja.xlf @@ -94,12 +94,12 @@ Expected collection to contain exactly one element but found {1} element(s). {0} - Expected collection to contain exactly one element. Actual: {1}. {0} + Expected collection to contain exactly one element but found {1} element(s). {0} Expected exactly one item to match the predicate but found {1} item(s). {0} - Expected exactly one item to match the predicate. Actual: {1}. {0} + Expected exactly one item to match the predicate but found {1} item(s). {0} diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ko.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ko.xlf index 03240de39a..f7d99eddbe 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ko.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ko.xlf @@ -94,12 +94,12 @@ Expected collection to contain exactly one element but found {1} element(s). {0} - Expected collection to contain exactly one element. Actual: {1}. {0} + Expected collection to contain exactly one element but found {1} element(s). {0} Expected exactly one item to match the predicate but found {1} item(s). {0} - Expected exactly one item to match the predicate. Actual: {1}. {0} + Expected exactly one item to match the predicate but found {1} item(s). {0} diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pl.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pl.xlf index 7672e5af80..062a4c7dca 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pl.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pl.xlf @@ -94,12 +94,12 @@ Expected collection to contain exactly one element but found {1} element(s). {0} - Expected collection to contain exactly one element. Actual: {1}. {0} + Expected collection to contain exactly one element but found {1} element(s). {0} Expected exactly one item to match the predicate but found {1} item(s). {0} - Expected exactly one item to match the predicate. Actual: {1}. {0} + Expected exactly one item to match the predicate but found {1} item(s). {0} diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf index 31a306ed06..634418e4e9 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf @@ -94,12 +94,12 @@ Expected collection to contain exactly one element but found {1} element(s). {0} - Expected collection to contain exactly one element. Actual: {1}. {0} + Expected collection to contain exactly one element but found {1} element(s). {0} Expected exactly one item to match the predicate but found {1} item(s). {0} - Expected exactly one item to match the predicate. Actual: {1}. {0} + Expected exactly one item to match the predicate but found {1} item(s). {0} diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ru.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ru.xlf index 3e1b32c2fa..0a7d64ebbc 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ru.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ru.xlf @@ -94,12 +94,12 @@ Expected collection to contain exactly one element but found {1} element(s). {0} - Expected collection to contain exactly one element. Actual: {1}. {0} + Expected collection to contain exactly one element but found {1} element(s). {0} Expected exactly one item to match the predicate but found {1} item(s). {0} - Expected exactly one item to match the predicate. Actual: {1}. {0} + Expected exactly one item to match the predicate but found {1} item(s). {0} diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.tr.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.tr.xlf index b71a3d0cac..6b51802cd0 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.tr.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.tr.xlf @@ -94,12 +94,12 @@ Expected collection to contain exactly one element but found {1} element(s). {0} - Expected collection to contain exactly one element. Actual: {1}. {0} + Expected collection to contain exactly one element but found {1} element(s). {0} Expected exactly one item to match the predicate but found {1} item(s). {0} - Expected exactly one item to match the predicate. Actual: {1}. {0} + Expected exactly one item to match the predicate but found {1} item(s). {0} diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf index 42a13ba135..741f48147a 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf @@ -94,12 +94,12 @@ Expected collection to contain exactly one element but found {1} element(s). {0} - Expected collection to contain exactly one element. Actual: {1}. {0} + Expected collection to contain exactly one element but found {1} element(s). {0} Expected exactly one item to match the predicate but found {1} item(s). {0} - Expected exactly one item to match the predicate. Actual: {1}. {0} + Expected exactly one item to match the predicate but found {1} item(s). {0} diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf index c3e50cf656..1ceae9d222 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf @@ -94,12 +94,12 @@ Expected collection to contain exactly one element but found {1} element(s). {0} - Expected collection to contain exactly one element. Actual: {1}. {0} + Expected collection to contain exactly one element but found {1} element(s). {0} Expected exactly one item to match the predicate but found {1} item(s). {0} - Expected exactly one item to match the predicate. Actual: {1}. {0} + Expected exactly one item to match the predicate but found {1} item(s). {0} From 526054e3aa7d7c4cfe559ec7b0d34137e63d7d3a Mon Sep 17 00:00:00 2001 From: dotnet bot Date: Thu, 19 Jun 2025 05:32:40 +0200 Subject: [PATCH 116/541] Localized file check-in by OneLocBuild Task: Build definition ID 1218: Build ID 2733315 --- .../TestFramework/Resources/xlf/FrameworkMessages.fr.xlf | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.fr.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.fr.xlf index b0945cd203..a4db3c3800 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.fr.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.fr.xlf @@ -173,7 +173,7 @@ Réel : {2} Value '{0}' is not within the expected range [{1}, {2}]. {3} - Value '{0}' is not within the expected range [{1}, {2}]. {3} + La valeur « {0} » n'est pas dans la plage attendue [{1}, {2}]. {3} From 35b7726fb047336f35a7d12f01ec02341c7b09d4 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Thu, 19 Jun 2025 09:01:51 +0200 Subject: [PATCH 117/541] Fix build race condition with MSTest.GlobalConfigsGenerator (#5817) --- NonWindowsTests.slnf | 40 +++++++++++++++---- TestFx.slnx | 4 +- eng/Build.props | 6 +-- .../MSTest.Analyzers.Package.csproj | 2 +- 4 files changed, 38 insertions(+), 14 deletions(-) diff --git a/NonWindowsTests.slnf b/NonWindowsTests.slnf index a0168d54d3..a69cbb51e1 100644 --- a/NonWindowsTests.slnf +++ b/NonWindowsTests.slnf @@ -2,13 +2,39 @@ "solution": { "path": "TestFx.slnx", "projects": [ - "test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests.csproj", - "test/IntegrationTests/MSTest.Acceptance.IntegrationTests/MSTest.Acceptance.IntegrationTests.csproj", - "test/UnitTests/Microsoft.Testing.Extensions.UnitTests/Microsoft.Testing.Extensions.UnitTests.csproj", - "test/UnitTests/Microsoft.Testing.Extensions.VSTestBridge.UnitTests/Microsoft.Testing.Extensions.VSTestBridge.UnitTests.csproj", - "test/UnitTests/Microsoft.Testing.Platform.UnitTests/Microsoft.Testing.Platform.UnitTests.csproj", - "test/UnitTests/Microsoft.Testing.Platform.MSBuild.UnitTests/Microsoft.Testing.Platform.MSBuild.UnitTests.csproj", - "test/UnitTests/MSTest.Analyzers.UnitTests/MSTest.Analyzers.UnitTests.csproj" + "src\\Adapter\\MSTest.Engine\\MSTest.Engine.csproj", + "src\\Adapter\\MSTest.TestAdapter\\MSTest.TestAdapter.csproj", + "src\\Adapter\\MSTestAdapter.PlatformServices\\MSTestAdapter.PlatformServices.csproj", + "src\\Analyzers\\MSTest.Analyzers.CodeFixes\\MSTest.Analyzers.CodeFixes.csproj", + "src\\Analyzers\\MSTest.Analyzers.Package\\MSTest.Analyzers.Package.csproj", + "src\\Analyzers\\MSTest.Analyzers\\MSTest.Analyzers.csproj", + "src\\Analyzers\\MSTest.GlobalConfigsGenerator\\MSTest.GlobalConfigsGenerator.csproj", + "src\\Analyzers\\MSTest.Internal.Analyzers\\MSTest.Internal.Analyzers.csproj", + "src\\Analyzers\\MSTest.SourceGeneration\\MSTest.SourceGeneration.csproj", + "src\\Package\\MSTest.Sdk\\MSTest.Sdk.csproj", + "src\\Package\\MSTest\\MSTest.csproj", + "src\\Platform\\Microsoft.Testing.Extensions.AzureDevOpsReport\\Microsoft.Testing.Extensions.AzureDevOpsReport.csproj", + "src\\Platform\\Microsoft.Testing.Extensions.CrashDump\\Microsoft.Testing.Extensions.CrashDump.csproj", + "src\\Platform\\Microsoft.Testing.Extensions.HangDump\\Microsoft.Testing.Extensions.HangDump.csproj", + "src\\Platform\\Microsoft.Testing.Extensions.HotReload\\Microsoft.Testing.Extensions.HotReload.csproj", + "src\\Platform\\Microsoft.Testing.Extensions.MSBuild\\Microsoft.Testing.Extensions.MSBuild.csproj", + "src\\Platform\\Microsoft.Testing.Extensions.Retry\\Microsoft.Testing.Extensions.Retry.csproj", + "src\\Platform\\Microsoft.Testing.Extensions.Telemetry\\Microsoft.Testing.Extensions.Telemetry.csproj", + "src\\Platform\\Microsoft.Testing.Extensions.TrxReport.Abstractions\\Microsoft.Testing.Extensions.TrxReport.Abstractions.csproj", + "src\\Platform\\Microsoft.Testing.Extensions.TrxReport\\Microsoft.Testing.Extensions.TrxReport.csproj", + "src\\Platform\\Microsoft.Testing.Extensions.VSTestBridge\\Microsoft.Testing.Extensions.VSTestBridge.csproj", + "src\\Platform\\Microsoft.Testing.Platform.MSBuild\\Microsoft.Testing.Platform.MSBuild.csproj", + "src\\Platform\\Microsoft.Testing.Platform\\Microsoft.Testing.Platform.csproj", + "src\\TestFramework\\TestFramework.Extensions\\TestFramework.Extensions.csproj", + "src\\TestFramework\\TestFramework\\TestFramework.csproj", + "test\\IntegrationTests\\MSTest.Acceptance.IntegrationTests\\MSTest.Acceptance.IntegrationTests.csproj", + "test\\IntegrationTests\\Microsoft.Testing.Platform.Acceptance.IntegrationTests\\Microsoft.Testing.Platform.Acceptance.IntegrationTests.csproj", + "test\\UnitTests\\MSTest.Analyzers.UnitTests\\MSTest.Analyzers.UnitTests.csproj", + "test\\UnitTests\\Microsoft.Testing.Extensions.UnitTests\\Microsoft.Testing.Extensions.UnitTests.csproj", + "test\\UnitTests\\Microsoft.Testing.Extensions.VSTestBridge.UnitTests\\Microsoft.Testing.Extensions.VSTestBridge.UnitTests.csproj", + "test\\UnitTests\\Microsoft.Testing.Platform.MSBuild.UnitTests\\Microsoft.Testing.Platform.MSBuild.UnitTests.csproj", + "test\\UnitTests\\Microsoft.Testing.Platform.UnitTests\\Microsoft.Testing.Platform.UnitTests.csproj", + "test\\Utilities\\Microsoft.Testing.TestInfrastructure\\Microsoft.Testing.TestInfrastructure.csproj" ] } } \ No newline at end of file diff --git a/TestFx.slnx b/TestFx.slnx index 39e28d3ae3..d51b6d22e2 100644 --- a/TestFx.slnx +++ b/TestFx.slnx @@ -57,7 +57,9 @@ - + + + diff --git a/eng/Build.props b/eng/Build.props index c1eb7bb1ac..559d7f3749 100644 --- a/eng/Build.props +++ b/eng/Build.props @@ -11,11 +11,7 @@ - - - - - + diff --git a/src/Analyzers/MSTest.Analyzers.Package/MSTest.Analyzers.Package.csproj b/src/Analyzers/MSTest.Analyzers.Package/MSTest.Analyzers.Package.csproj index 1cbbe6129d..71244cd642 100644 --- a/src/Analyzers/MSTest.Analyzers.Package/MSTest.Analyzers.Package.csproj +++ b/src/Analyzers/MSTest.Analyzers.Package/MSTest.Analyzers.Package.csproj @@ -40,7 +40,7 @@ $(DotNetRoot)dotnet.exe $(DotNetRoot)dotnet - + From d8b6235488fe58e9aa3747fc603d2cd7428bee4e Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Thu, 19 Jun 2025 07:58:13 +0000 Subject: [PATCH 118/541] [main] Update dependencies from devdiv/DevDiv/vs-code-coverage (#5821) [main] Update dependencies from devdiv/DevDiv/vs-code-coverage --- eng/Version.Details.xml | 4 ++-- eng/Versions.props | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index 6b684ee717..394621bfb6 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -13,9 +13,9 @@ https://github.com/dotnet/arcade d9d02d858b71562509f72ea84409853e4deffc8f - + https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage - d895947216a71972ae98f3e88bd8c6e113f04d7a + 67cf10b2f0c18fb045326765e14c7d2304b6c0c1 diff --git a/eng/Versions.props b/eng/Versions.props index 14d91a06d2..5fd948ff56 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -8,6 +8,6 @@ 10.0.0-beta.25316.2 - 17.15.0-preview.25313.3 + 17.15.0-preview.25318.1 From 27f5b2f45b42c12f00acfb6f2105cf6c96e1f069 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Thu, 19 Jun 2025 10:37:24 +0200 Subject: [PATCH 119/541] =?UTF-8?q?Add=20Assert=20StartsWith/DoesNotStartW?= =?UTF-8?q?ith,=20EndsWith/DoesNotEndsWith,=20Mat=E2=80=A6=20(#5768)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Assertions/Assert.EndsWith.cs | 320 ++++++++++++++++++ .../Assertions/Assert.Matches.cs | 309 +++++++++++++++++ .../Assertions/Assert.StartsWith.cs | 314 +++++++++++++++++ .../PublicAPI/PublicAPI.Unshipped.txt | 36 ++ .../Resources/FrameworkMessages.Designer.cs | 134 ++++---- .../Resources/FrameworkMessages.resx | 16 +- .../Resources/xlf/FrameworkMessages.cs.xlf | 68 ++-- .../Resources/xlf/FrameworkMessages.de.xlf | 36 +- .../Resources/xlf/FrameworkMessages.es.xlf | 68 ++-- .../Resources/xlf/FrameworkMessages.fr.xlf | 68 ++-- .../Resources/xlf/FrameworkMessages.it.xlf | 68 ++-- .../Resources/xlf/FrameworkMessages.ja.xlf | 68 ++-- .../Resources/xlf/FrameworkMessages.ko.xlf | 68 ++-- .../Resources/xlf/FrameworkMessages.pl.xlf | 68 ++-- .../Resources/xlf/FrameworkMessages.pt-BR.xlf | 68 ++-- .../Resources/xlf/FrameworkMessages.ru.xlf | 68 ++-- .../Resources/xlf/FrameworkMessages.tr.xlf | 68 ++-- .../xlf/FrameworkMessages.zh-Hans.xlf | 68 ++-- .../xlf/FrameworkMessages.zh-Hant.xlf | 68 ++-- 19 files changed, 1569 insertions(+), 412 deletions(-) create mode 100644 src/TestFramework/TestFramework/Assertions/Assert.EndsWith.cs create mode 100644 src/TestFramework/TestFramework/Assertions/Assert.Matches.cs create mode 100644 src/TestFramework/TestFramework/Assertions/Assert.StartsWith.cs diff --git a/src/TestFramework/TestFramework/Assertions/Assert.EndsWith.cs b/src/TestFramework/TestFramework/Assertions/Assert.EndsWith.cs new file mode 100644 index 0000000000..43057b46e2 --- /dev/null +++ b/src/TestFramework/TestFramework/Assertions/Assert.EndsWith.cs @@ -0,0 +1,320 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +namespace Microsoft.VisualStudio.TestTools.UnitTesting; + +public sealed partial class Assert +{ + #region EndsWith + + /// + /// Tests whether the specified string ends with the specified substring + /// and throws an exception if the test string does not end with the + /// substring. + /// + /// + /// The string expected to be a suffix of . + /// + /// + /// The string that is expected to end with . + /// + /// + /// is null, or is null, + /// or does not end with . + /// + public static void EndsWith([NotNull] string? substring, [NotNull] string? value) + => EndsWith(substring, value, StringComparison.Ordinal, string.Empty); + + /// + /// Tests whether the specified string ends with the specified substring + /// and throws an exception if the test string does not end with the + /// substring. + /// + /// + /// The string expected to be a suffix of . + /// + /// + /// The string that is expected to end with . + /// + /// + /// The message to include in the exception when + /// does not end with . The message is + /// shown in test results. + /// + /// + /// is null, or is null, + /// or does not end with . + /// + public static void EndsWith([NotNull] string? substring, [NotNull] string? value, string? message) + => EndsWith(substring, value, StringComparison.Ordinal, message); + + /// + /// Tests whether the specified string ends with the specified substring + /// and throws an exception if the test string does not end with the + /// substring. + /// + /// + /// The string expected to be a suffix of . + /// + /// + /// The string that is expected to end with . + /// + /// + /// The message to include in the exception when + /// does not end with . The message is + /// shown in test results. + /// + /// + /// An array of parameters to use when formatting . + /// + /// + /// is null, or is null, + /// or does not end with . + /// + public static void EndsWith([NotNull] string? substring, [NotNull] string? value, [StringSyntax(StringSyntaxAttribute.CompositeFormat)] string? message, params object?[]? parameters) + => EndsWith(substring, value, StringComparison.Ordinal, message, parameters); + + /// + /// Tests whether the specified string ends with the specified substring + /// and throws an exception if the test string does not end with the + /// substring. + /// + /// + /// The string expected to be a suffix of . + /// + /// + /// The string that is expected to end with . + /// + /// + /// The comparison method to compare strings . + /// + /// + /// is null, or is null, + /// or does not end with . + /// + public static void EndsWith([NotNull] string? substring, [NotNull] string? value, StringComparison comparisonType) + => EndsWith(substring, value, comparisonType, string.Empty, null); + + /// + /// Tests whether the specified string ends with the specified substring + /// and throws an exception if the test string does not end with the + /// substring. + /// + /// + /// The string expected to be a suffix of . + /// + /// + /// The string that is expected to end with . + /// + /// + /// The message to include in the exception when + /// does not end with . The message is + /// shown in test results. + /// + /// + /// The comparison method to compare strings . + /// + /// + /// is null, or is null, + /// or does not end with . + /// + public static void EndsWith([NotNull] string? substring, [NotNull] string? value, string? message, StringComparison comparisonType) + => EndsWith(substring, value, comparisonType, message, null); + + /// + /// Tests whether the specified string ends with the specified substring + /// and throws an exception if the test string does not end with the + /// substring. + /// + /// + /// The string expected to be a suffix of . + /// + /// + /// The string that is expected to end with . + /// + /// + /// The comparison method to compare strings . + /// + /// + /// The message to include in the exception when + /// does not end with . The message is + /// shown in test results. + /// + /// + /// An array of parameters to use when formatting . + /// + /// + /// is null, or is null, + /// or does not start with . + /// + public static void EndsWith([NotNull] string? substring, [NotNull] string? value, StringComparison comparisonType, [StringSyntax(StringSyntaxAttribute.CompositeFormat)] string? message, params object?[]? parameters) + { + CheckParameterNotNull(value, "Assert.EndsWith", "value", string.Empty); + CheckParameterNotNull(substring, "Assert.EndsWith", "substring", string.Empty); + if (!value.EndsWith(substring, comparisonType)) + { + string userMessage = BuildUserMessage(message, parameters); + string finalMessage = string.Format(CultureInfo.CurrentCulture, FrameworkMessages.EndsWithFail, value, substring, userMessage); + ThrowAssertFailed("Assert.EndsWith", finalMessage); + } + } + + #endregion // EndsWith + + #region DoesNotEndWith + + /// + /// Tests whether the specified string does not end with the specified substring + /// and throws an exception if the test string does not end with the + /// substring. + /// + /// + /// The string expected not to be a suffix of . + /// + /// + /// The string that is expected not to end with . + /// + /// + /// is null, or is null, + /// or ends with . + /// + public static void DoesNotEndWith([NotNull] string? substring, [NotNull] string? value) + => DoesNotEndWith(substring, value, StringComparison.Ordinal, string.Empty); + + /// + /// Tests whether the specified string does not end with the specified substring + /// and throws an exception if the test string does not end with the + /// substring. + /// + /// + /// The string expected not to be a suffix of . + /// + /// + /// The string that is expected not to end with . + /// + /// + /// The message to include in the exception when + /// ends with . The message is + /// shown in test results. + /// + /// + /// is null, or is null, + /// or ends with . + /// + public static void DoesNotEndWith([NotNull] string? substring, [NotNull] string? value, string? message) + => DoesNotEndWith(substring, value, StringComparison.Ordinal, message); + + /// + /// Tests whether the specified string does not end with the specified substring + /// and throws an exception if the test string does not end with the + /// substring. + /// + /// + /// The string expected not to be a suffix of . + /// + /// + /// The string that is expected not to end with . + /// + /// + /// The message to include in the exception when + /// ends with . The message is + /// shown in test results. + /// + /// + /// An array of parameters to use when formatting . + /// + /// + /// is null, or is null, + /// or ends with . + /// + public static void DoesNotEndWith([NotNull] string? substring, [NotNull] string? value, [StringSyntax(StringSyntaxAttribute.CompositeFormat)] string? message, params object?[]? parameters) + => DoesNotEndWith(substring, value, StringComparison.Ordinal, message, parameters); + + /// + /// Tests whether the specified string does not end with the specified substring + /// and throws an exception if the test string does not end with the + /// substring. + /// + /// + /// The string expected not to be a suffix of . + /// + /// + /// The string that is expected not to end with . + /// + /// + /// The comparison method to compare strings . + /// + /// + /// is null, or is null, + /// or ends with . + /// + public static void DoesNotEndWith([NotNull] string? substring, [NotNull] string? value, StringComparison comparisonType) + => DoesNotEndWith(substring, value, comparisonType, string.Empty, null); + + /// + /// Tests whether the specified string does not end with the specified substring + /// and throws an exception if the test string does not end with the + /// substring. + /// + /// + /// The string expected not to be a suffix of . + /// + /// + /// The string that is expected not to end with . + /// + /// + /// The message to include in the exception when + /// ends with . The message is + /// shown in test results. + /// + /// + /// The comparison method to compare strings . + /// + /// + /// is null, or is null, + /// or ends with . + /// + public static void DoesNotEndWith([NotNull] string? substring, [NotNull] string? value, string? message, StringComparison comparisonType) + => DoesNotEndWith(substring, value, comparisonType, message, null); + + /// + /// Tests whether the specified string does not end with the specified substring + /// and throws an exception if the test string does not end with the + /// substring. + /// + /// + /// The string expected not to be a suffix of . + /// + /// + /// The string that is expected not to end with . + /// + /// + /// The comparison method to compare strings . + /// + /// + /// The message to include in the exception when + /// ends with . The message is + /// shown in test results. + /// + /// + /// An array of parameters to use when formatting . + /// + /// + /// is null, or is null, + /// or ends with . + /// + public static void DoesNotEndWith([NotNull] string? substring, [NotNull] string? value, StringComparison comparisonType, + [StringSyntax(StringSyntaxAttribute.CompositeFormat)] string? message, params object?[]? parameters) + { + CheckParameterNotNull(value, "Assert.DoesNotEndWith", "value", string.Empty); + CheckParameterNotNull(substring, "Assert.DoesNotEndWith", "substring", string.Empty); + if (value.EndsWith(substring, comparisonType)) + { + string userMessage = BuildUserMessage(message, parameters); + string finalMessage = string.Format(CultureInfo.CurrentCulture, FrameworkMessages.DoesNotEndWithFail, value, substring, userMessage); + ThrowAssertFailed("Assert.DoesNotEndWith", finalMessage); + } + } + + #endregion // DoesNotEndWith +} diff --git a/src/TestFramework/TestFramework/Assertions/Assert.Matches.cs b/src/TestFramework/TestFramework/Assertions/Assert.Matches.cs new file mode 100644 index 0000000000..df2c0d9b4e --- /dev/null +++ b/src/TestFramework/TestFramework/Assertions/Assert.Matches.cs @@ -0,0 +1,309 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +namespace Microsoft.VisualStudio.TestTools.UnitTesting; + +public sealed partial class Assert +{ + #region MatchesRegex + + /// + /// Tests whether the specified string MatchesRegex a regular expression and + /// throws an exception if the string does not match the expression. + /// + /// + /// The regular expression that is + /// expected to match. + /// + /// + /// The string that is expected to match . + /// + /// + /// is null, or is null, + /// or does not match . + /// + public static void MatchesRegex([NotNull] Regex? pattern, [NotNull] string? value) + => MatchesRegex(pattern, value, string.Empty, null); + + /// + /// Tests whether the specified string MatchesRegex a regular expression and + /// throws an exception if the string does not match the expression. + /// + /// + /// The regular expression that is + /// expected to match. + /// + /// + /// The string that is expected to match . + /// + /// + /// The message to include in the exception when + /// does not match . The message is shown in + /// test results. + /// + /// + /// is null, or is null, + /// or does not match . + /// + public static void MatchesRegex([NotNull] Regex? pattern, [NotNull] string? value, string? message) + => MatchesRegex(pattern, value, message, null); + + /// + /// Tests whether the specified string MatchesRegex a regular expression and + /// throws an exception if the string does not match the expression. + /// + /// + /// The regular expression that is + /// expected to match. + /// + /// + /// The string that is expected to match . + /// + /// + /// The message to include in the exception when + /// does not match . The message is shown in + /// test results. + /// + /// + /// An array of parameters to use when formatting . + /// + /// + /// is null, or is null, + /// or does not match . + /// + public static void MatchesRegex([NotNull] Regex? pattern, [NotNull] string? value, [StringSyntax(StringSyntaxAttribute.CompositeFormat)] string? message, params object?[]? parameters) + { + CheckParameterNotNull(value, "Assert.MatchesRegex", "value", string.Empty); + CheckParameterNotNull(pattern, "Assert.MatchesRegex", "pattern", string.Empty); + + if (!pattern.IsMatch(value)) + { + string userMessage = BuildUserMessage(message, parameters); + string finalMessage = string.Format(CultureInfo.CurrentCulture, FrameworkMessages.IsMatchFail, value, pattern, userMessage); + ThrowAssertFailed("Assert.MatchesRegex", finalMessage); + } + } + + /// + /// Tests whether the specified string MatchesRegex a regular expression and + /// throws an exception if the string does not match the expression. + /// + /// + /// The regular expression that is + /// expected to match. + /// + /// + /// The string that is expected to match . + /// + /// + /// is null, or is null, + /// or does not match . + /// + public static void MatchesRegex([NotNull] string? pattern, [NotNull] string? value) + => MatchesRegex(ToRegex(pattern), value, string.Empty, null); + + /// + /// Tests whether the specified string MatchesRegex a regular expression and + /// throws an exception if the string does not match the expression. + /// + /// + /// The regular expression that is + /// expected to match. + /// + /// + /// The string that is expected to match . + /// + /// + /// The message to include in the exception when + /// does not match . The message is shown in + /// test results. + /// + /// + /// is null, or is null, + /// or does not match . + /// + public static void MatchesRegex([NotNull] string? pattern, [NotNull] string? value, string? message) + => MatchesRegex(ToRegex(pattern), value, message, null); + + /// + /// Tests whether the specified string MatchesRegex a regular expression and + /// throws an exception if the string does not match the expression. + /// + /// + /// The regular expression that is + /// expected to match. + /// + /// + /// The string that is expected to match . + /// + /// + /// The message to include in the exception when + /// does not match . The message is shown in + /// test results. + /// + /// + /// An array of parameters to use when formatting . + /// + /// + /// is null, or is null, + /// or does not match . + /// + public static void MatchesRegex([NotNull] string? pattern, [NotNull] string? value, [StringSyntax(StringSyntaxAttribute.CompositeFormat)] string? message, params object?[]? parameters) + => MatchesRegex(ToRegex(pattern), value, message, parameters); + + #endregion // MatchesRegex + + #region DoesNotMatchRegex + + /// + /// Tests whether the specified string does not match a regular expression + /// and throws an exception if the string MatchesRegex the expression. + /// + /// + /// The regular expression that is + /// expected to not match. + /// + /// + /// The string that is expected not to match . + /// + /// + /// is null, or is null, + /// or MatchesRegex . + /// + public static void DoesNotMatchRegex([NotNull] Regex? pattern, [NotNull] string? value) + => DoesNotMatchRegex(pattern, value, string.Empty); + + /// + /// Tests whether the specified string does not match a regular expression + /// and throws an exception if the string MatchesRegex the expression. + /// + /// + /// The regular expression that is + /// expected to not match. + /// + /// + /// The string that is expected not to match . + /// + /// + /// The message to include in the exception when + /// MatchesRegex . The message is shown in test + /// results. + /// + /// + /// is null, or is null, + /// or MatchesRegex . + /// + public static void DoesNotMatchRegex([NotNull] Regex? pattern, [NotNull] string? value, string? message) + => DoesNotMatchRegex(pattern, value, message, null); + + /// + /// Tests whether the specified string does not match a regular expression + /// and throws an exception if the string MatchesRegex the expression. + /// + /// + /// The regular expression that is + /// expected to not match. + /// + /// + /// The string that is expected not to match . + /// + /// + /// The message to include in the exception when + /// MatchesRegex . The message is shown in test + /// results. + /// + /// + /// An array of parameters to use when formatting . + /// + /// + /// is null, or is null, + /// or MatchesRegex . + /// + public static void DoesNotMatchRegex([NotNull] Regex? pattern, [NotNull] string? value, [StringSyntax(StringSyntaxAttribute.CompositeFormat)] string? message, params object?[]? parameters) + { + CheckParameterNotNull(value, "Assert.DoesNotMatchRegex", "value", string.Empty); + CheckParameterNotNull(pattern, "Assert.DoesNotMatchRegex", "pattern", string.Empty); + + if (pattern.IsMatch(value)) + { + string userMessage = BuildUserMessage(message, parameters); + string finalMessage = string.Format(CultureInfo.CurrentCulture, FrameworkMessages.IsNotMatchFail, value, pattern, userMessage); + ThrowAssertFailed("Assert.DoesNotMatchRegex", finalMessage); + } + } + + /// + /// Tests whether the specified string does not match a regular expression + /// and throws an exception if the string MatchesRegex the expression. + /// + /// + /// The regular expression that is + /// expected to not match. + /// + /// + /// The string that is expected not to match . + /// + /// + /// is null, or is null, + /// or MatchesRegex . + /// + public static void DoesNotMatchRegex([NotNull] string? pattern, [NotNull] string? value) + => DoesNotMatchRegex(ToRegex(pattern), value, string.Empty, null); + + /// + /// Tests whether the specified string does not match a regular expression + /// and throws an exception if the string MatchesRegex the expression. + /// + /// + /// The regular expression that is + /// expected to not match. + /// + /// + /// The string that is expected not to match . + /// + /// + /// The message to include in the exception when + /// MatchesRegex . The message is shown in test + /// results. + /// + /// + /// is null, or is null, + /// or MatchesRegex . + /// + public static void DoesNotMatchRegex([NotNull] string? pattern, [NotNull] string? value, string? message) + => DoesNotMatchRegex(ToRegex(pattern), value, message, null); + + /// + /// Tests whether the specified string does not match a regular expression + /// and throws an exception if the string MatchesRegex the expression. + /// + /// + /// The regular expression that is + /// expected to not match. + /// + /// + /// The string that is expected not to match . + /// + /// + /// The message to include in the exception when + /// MatchesRegex . The message is shown in test + /// results. + /// + /// + /// An array of parameters to use when formatting . + /// + /// + /// is null, or is null, + /// or MatchesRegex . + /// + public static void DoesNotMatchRegex([NotNull] string? pattern, [NotNull] string? value, [StringSyntax(StringSyntaxAttribute.CompositeFormat)] string? message, params object?[]? parameters) + => DoesNotMatchRegex(ToRegex(pattern), value, message, parameters); + + #endregion // DoesNotMatchRegex + + private static Regex? ToRegex([NotNull] string? pattern) + { + CheckParameterNotNull(pattern, "Assert.MatchesRegex", "pattern", string.Empty); + return new Regex(pattern); + } +} diff --git a/src/TestFramework/TestFramework/Assertions/Assert.StartsWith.cs b/src/TestFramework/TestFramework/Assertions/Assert.StartsWith.cs new file mode 100644 index 0000000000..abbae94d2b --- /dev/null +++ b/src/TestFramework/TestFramework/Assertions/Assert.StartsWith.cs @@ -0,0 +1,314 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +namespace Microsoft.VisualStudio.TestTools.UnitTesting; + +public sealed partial class Assert +{ + #region StartsWith + + /// + /// Tests whether the specified string begins with the specified substring + /// and throws an exception if the test string does not start with the + /// substring. + /// + /// + /// The string expected to be a prefix of . + /// + /// + /// The string that is expected to begin with . + /// + /// + /// is null, or is null, + /// or does not start with . + /// + public static void StartsWith([NotNull] string? substring, [NotNull] string? value) + => StartsWith(substring, value, StringComparison.Ordinal, string.Empty); + + /// + /// Tests whether the specified string begins with the specified substring + /// and throws an exception if the test string does not start with the + /// substring. + /// + /// + /// The string expected to be a prefix of . + /// + /// + /// The string that is expected to begin with . + /// + /// + /// The message to include in the exception when + /// does not begin with . The message is + /// shown in test results. + /// + /// + /// is null, or is null, + /// or does not start with . + /// + public static void StartsWith([NotNull] string? substring, [NotNull] string? value, string? message) + => StartsWith(substring, value, StringComparison.Ordinal, message); + + /// + /// Tests whether the specified string begins with the specified substring + /// and throws an exception if the test string does not start with the + /// substring. + /// + /// + /// The string expected to be a prefix of . + /// + /// + /// The string that is expected to begin with . + /// + /// + /// The message to include in the exception when + /// does not begin with . The message is + /// shown in test results. + /// + /// + /// An array of parameters to use when formatting . + /// + /// + /// is null, or is null, + /// or does not start with . + /// + public static void StartsWith([NotNull] string? substring, [NotNull] string? value, [StringSyntax(StringSyntaxAttribute.CompositeFormat)] string? message, params object?[]? parameters) + => StartsWith(substring, value, StringComparison.Ordinal, message, parameters); + + /// + /// Tests whether the specified string begins with the specified substring + /// and throws an exception if the test string does not start with the + /// substring. + /// + /// + /// The string expected to be a prefix of . + /// + /// + /// The string that is expected to begin with . + /// + /// + /// The comparison method to compare strings . + /// + /// + /// is null, or is null, + /// or does not start with . + /// + public static void StartsWith([NotNull] string? substring, [NotNull] string? value, StringComparison comparisonType) + => StartsWith(substring, value, comparisonType, string.Empty, null); + + /// + /// Tests whether the specified string begins with the specified substring + /// and throws an exception if the test string does not start with the + /// substring. + /// + /// + /// The string expected to be a prefix of . + /// + /// + /// The string that is expected to begin with . + /// + /// + /// The message to include in the exception when + /// does not begin with . The message is + /// shown in test results. + /// + /// + /// The comparison method to compare strings . + /// + /// + /// is null, or is null, + /// or does not start with . + /// + public static void StartsWith([NotNull] string? substring, [NotNull] string? value, string? message, StringComparison comparisonType) + => StartsWith(substring, value, comparisonType, message, null); + + /// + /// Tests whether the specified string begins with the specified substring + /// and throws an exception if the test string does not start with the + /// substring. + /// + /// + /// The string expected to be a prefix of . + /// + /// + /// The string that is expected to begin with . + /// + /// + /// The comparison method to compare strings . + /// + /// + /// The message to include in the exception when + /// does not begin with . The message is + /// shown in test results. + /// + /// + /// An array of parameters to use when formatting . + /// + /// + /// is null, or is null, + /// or does not start with . + /// + public static void StartsWith([NotNull] string? substring, [NotNull] string? value, StringComparison comparisonType, [StringSyntax(StringSyntaxAttribute.CompositeFormat)] string? message, params object?[]? parameters) + { + CheckParameterNotNull(value, "Assert.StartsWith", "value", string.Empty); + CheckParameterNotNull(substring, "Assert.StartsWith", "substring", string.Empty); + if (!value.StartsWith(substring, comparisonType)) + { + string userMessage = BuildUserMessage(message, parameters); + string finalMessage = string.Format(CultureInfo.CurrentCulture, FrameworkMessages.StartsWithFail, value, substring, userMessage); + ThrowAssertFailed("Assert.StartsWith", finalMessage); + } + } + + #endregion // StartsWith + + #region DoesNotStartWith + + /// + /// Tests whether the specified string does not begin with the specified substring + /// and throws an exception if the test string does start with the substring. + /// + /// + /// The string expected to be a prefix of . + /// + /// + /// The string that is expected to begin with . + /// + /// + /// is null, or is null, + /// or does not start with . + /// + public static void DoesNotStartWith([NotNull] string? substring, [NotNull] string? value) + => DoesNotStartWith(substring, value, StringComparison.Ordinal, string.Empty); + + /// + /// Tests whether the specified string does not begin with the specified substring + /// and throws an exception if the test string does start with the substring. + /// + /// + /// The string expected to be a prefix of . + /// + /// + /// The string that is expected to begin with . + /// + /// + /// The message to include in the exception when + /// does not begin with . The message is + /// shown in test results. + /// + /// + /// is null, or is null, + /// or does not start with . + /// + public static void DoesNotStartWith([NotNull] string? substring, [NotNull] string? value, string? message) + => DoesNotStartWith(substring, value, StringComparison.Ordinal, message); + + /// + /// Tests whether the specified string does not begin with the specified substring + /// and throws an exception if the test string does start with the substring. + /// + /// + /// The string expected to be a prefix of . + /// + /// + /// The string that is expected to begin with . + /// + /// + /// The message to include in the exception when + /// does not begin with . The message is + /// shown in test results. + /// + /// + /// An array of parameters to use when formatting . + /// + /// + /// is null, or is null, + /// or does not start with . + /// + public static void DoesNotStartWith([NotNull] string? substring, [NotNull] string? value, [StringSyntax(StringSyntaxAttribute.CompositeFormat)] string? message, params object?[]? parameters) + => DoesNotStartWith(substring, value, StringComparison.Ordinal, message, parameters); + + /// + /// Tests whether the specified string does not begin with the specified substring + /// and throws an exception if the test string does start with the substring. + /// + /// + /// The string expected to be a prefix of . + /// + /// + /// The string that is expected to begin with . + /// + /// + /// The comparison method to compare strings . + /// + /// + /// is null, or is null, + /// or does not start with . + /// + public static void DoesNotStartWith([NotNull] string? substring, [NotNull] string? value, StringComparison comparisonType) + => DoesNotStartWith(substring, value, comparisonType, string.Empty, null); + + /// + /// Tests whether the specified string does not begin with the specified substring + /// and throws an exception if the test string does start with the substring. + /// + /// + /// The string expected to be a prefix of . + /// + /// + /// The string that is expected to begin with . + /// + /// + /// The message to include in the exception when + /// does not begin with . The message is + /// shown in test results. + /// + /// + /// The comparison method to compare strings . + /// + /// + /// is null, or is null, + /// or does not start with . + /// + public static void DoesNotStartWith([NotNull] string? substring, [NotNull] string? value, string? message, StringComparison comparisonType) + => DoesNotStartWith(substring, value, comparisonType, message, null); + + /// + /// Tests whether the specified string does not begin with the specified substring + /// and throws an exception if the test string does start with the substring. + /// + /// + /// The string expected to be a prefix of . + /// + /// + /// The string that is expected to begin with . + /// + /// + /// The comparison method to compare strings . + /// + /// + /// The message to include in the exception when + /// does not begin with . The message is + /// shown in test results. + /// + /// + /// An array of parameters to use when formatting . + /// + /// + /// is null, or is null, + /// or does not start with . + /// + public static void DoesNotStartWith([NotNull] string? substring, [NotNull] string? value, StringComparison comparisonType, + [StringSyntax(StringSyntaxAttribute.CompositeFormat)] string? message, params object?[]? parameters) + { + CheckParameterNotNull(value, "Assert.DoesNotStartWith", "value", string.Empty); + CheckParameterNotNull(substring, "Assert.DoesNotStartWith", "substring", string.Empty); + if (value.StartsWith(substring, comparisonType)) + { + string userMessage = BuildUserMessage(message, parameters); + string finalMessage = string.Format(CultureInfo.CurrentCulture, FrameworkMessages.DoesNotStartWithFail, value, substring, userMessage); + ThrowAssertFailed("Assert.DoesNotStartWith", finalMessage); + } + } + + #endregion // DoesNotStartWith +} diff --git a/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Unshipped.txt b/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Unshipped.txt index 323e0b84f1..92c6805d6b 100644 --- a/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Unshipped.txt +++ b/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Unshipped.txt @@ -9,6 +9,30 @@ static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsGreaterThanOrEqualT static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsGreaterThanOrEqualTo(T lowerBound, T value, string? message, params object?[]? parameters) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.Instance.get -> Microsoft.VisualStudio.TestTools.UnitTesting.Assert! static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.Contains(System.Func! predicate, System.Collections.Generic.IEnumerable! collection, string? message) -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.DoesNotEndWith(string? substring, string? value) -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.DoesNotEndWith(string? substring, string? value, string? message) -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.DoesNotEndWith(string? substring, string? value, string? message, params object?[]? parameters) -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.DoesNotEndWith(string? substring, string? value, string? message, System.StringComparison comparisonType) -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.DoesNotEndWith(string? substring, string? value, System.StringComparison comparisonType) -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.DoesNotEndWith(string? substring, string? value, System.StringComparison comparisonType, string? message, params object?[]? parameters) -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.DoesNotMatchRegex(string? pattern, string? value) -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.DoesNotMatchRegex(string? pattern, string? value, string? message) -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.DoesNotMatchRegex(string? pattern, string? value, string? message, params object?[]? parameters) -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.DoesNotMatchRegex(System.Text.RegularExpressions.Regex? pattern, string? value) -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.DoesNotMatchRegex(System.Text.RegularExpressions.Regex? pattern, string? value, string? message) -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.DoesNotMatchRegex(System.Text.RegularExpressions.Regex? pattern, string? value, string? message, params object?[]? parameters) -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.DoesNotStartWith(string? substring, string? value) -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.DoesNotStartWith(string? substring, string? value, string? message) -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.DoesNotStartWith(string? substring, string? value, string? message, params object?[]? parameters) -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.DoesNotStartWith(string? substring, string? value, string? message, System.StringComparison comparisonType) -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.DoesNotStartWith(string? substring, string? value, System.StringComparison comparisonType) -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.DoesNotStartWith(string? substring, string? value, System.StringComparison comparisonType, string? message, params object?[]? parameters) -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.EndsWith(string? substring, string? value) -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.EndsWith(string? substring, string? value, string? message) -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.EndsWith(string? substring, string? value, string? message, params object?[]? parameters) -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.EndsWith(string? substring, string? value, string? message, System.StringComparison comparisonType) -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.EndsWith(string? substring, string? value, System.StringComparison comparisonType) -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.EndsWith(string? substring, string? value, System.StringComparison comparisonType, string? message, params object?[]? parameters) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsInRange(T minValue, T maxValue, T value) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsInRange(T minValue, T maxValue, T value, string? message) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsInRange(T minValue, T maxValue, T value, string? message, params object?[]? parameters) -> void @@ -27,6 +51,18 @@ static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsNegative(T value static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsPositive(T value) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsPositive(T value, string? message) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsPositive(T value, string? message, params object?[]? parameters) -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.MatchesRegex(string? pattern, string? value) -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.MatchesRegex(string? pattern, string? value, string? message) -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.MatchesRegex(string? pattern, string? value, string? message, params object?[]? parameters) -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.MatchesRegex(System.Text.RegularExpressions.Regex? pattern, string? value) -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.MatchesRegex(System.Text.RegularExpressions.Regex? pattern, string? value, string? message) -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.MatchesRegex(System.Text.RegularExpressions.Regex? pattern, string? value, string? message, params object?[]? parameters) -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.StartsWith(string? substring, string? value) -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.StartsWith(string? substring, string? value, string? message) -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.StartsWith(string? substring, string? value, string? message, params object?[]? parameters) -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.StartsWith(string? substring, string? value, string? message, System.StringComparison comparisonType) -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.StartsWith(string? substring, string? value, System.StringComparison comparisonType) -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.StartsWith(string? substring, string? value, System.StringComparison comparisonType, string? message, params object?[]? parameters) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.Throws(System.Func! action, ref Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AssertNonStrictThrowsInterpolatedStringHandler message) -> TException! static Microsoft.VisualStudio.TestTools.UnitTesting.CollectionAssert.Instance.get -> Microsoft.VisualStudio.TestTools.UnitTesting.CollectionAssert! static Microsoft.VisualStudio.TestTools.UnitTesting.StringAssert.Instance.get -> Microsoft.VisualStudio.TestTools.UnitTesting.StringAssert! diff --git a/src/TestFramework/TestFramework/Resources/FrameworkMessages.Designer.cs b/src/TestFramework/TestFramework/Resources/FrameworkMessages.Designer.cs index df310e3fea..7583c35788 100644 --- a/src/TestFramework/TestFramework/Resources/FrameworkMessages.Designer.cs +++ b/src/TestFramework/TestFramework/Resources/FrameworkMessages.Designer.cs @@ -276,6 +276,24 @@ internal static string DoesNotContainFail { } } + /// + /// Looks up a localized string similar to String '{0}' ends with string '{1}'. {2}. + /// + internal static string DoesNotEndWithFail { + get { + return ResourceManager.GetString("DoesNotEndWithFail", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to String '{0}' starts with string '{1}'. {2}. + /// + internal static string DoesNotStartWithFail { + get { + return ResourceManager.GetString("DoesNotStartWithFail", resourceCulture); + } + } + /// /// Looks up a localized string similar to Assert.Equals should not be used for Assertions. Please use Assert.AreEqual & overloads instead.. /// @@ -378,7 +396,7 @@ internal static string ElementTypesAtIndexDontMatch { } /// - /// Looks up a localized string similar to String '{0}' does not end with string '{1}'. {2}.. + /// Looks up a localized string similar to String '{0}' does not end with string '{1}'. {2}. /// internal static string EndsWithFail { get { @@ -467,6 +485,24 @@ internal static string InvalidPropertyType { } } + /// + /// Looks up a localized string similar to Actual value <{2}> is not greater than expected value <{1}>. {0}. + /// + internal static string IsGreaterThanFailMsg { + get { + return ResourceManager.GetString("IsGreaterThanFailMsg", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Actual value <{2}> is not greater than or equal to expected value <{1}>. {0}. + /// + internal static string IsGreaterThanOrEqualToFailMsg { + get { + return ResourceManager.GetString("IsGreaterThanOrEqualToFailMsg", resourceCulture); + } + } + /// /// Looks up a localized string similar to Value '{0}' is not within the expected range [{1}, {2}]. {3}. /// @@ -486,7 +522,25 @@ internal static string IsInstanceOfFailMsg { } /// - /// Looks up a localized string similar to String '{0}' does not match pattern '{1}'. {2}.. + /// Looks up a localized string similar to Actual value <{2}> is not less than expected value <{1}>. {0}. + /// + internal static string IsLessThanFailMsg { + get { + return ResourceManager.GetString("IsLessThanFailMsg", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Actual value <{2}> is not less than or equal to expected value <{1}>. {0}. + /// + internal static string IsLessThanOrEqualToFailMsg { + get { + return ResourceManager.GetString("IsLessThanOrEqualToFailMsg", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to String '{0}' does not match pattern '{1}'. {2}. /// internal static string IsMatchFail { get { @@ -494,6 +548,15 @@ internal static string IsMatchFail { } } + /// + /// Looks up a localized string similar to Expected value <{1}> to be negative. {0}. + /// + internal static string IsNegativeFailMsg { + get { + return ResourceManager.GetString("IsNegativeFailMsg", resourceCulture); + } + } + /// /// Looks up a localized string similar to Expected collection to contain any item but it is empty. {0}. /// @@ -513,7 +576,7 @@ internal static string IsNotInstanceOfFailMsg { } /// - /// Looks up a localized string similar to String '{0}' matches pattern '{1}'. {2}.. + /// Looks up a localized string similar to String '{0}' matches pattern '{1}'. {2}. /// internal static string IsNotMatchFail { get { @@ -521,6 +584,15 @@ internal static string IsNotMatchFail { } } + /// + /// Looks up a localized string similar to Expected value <{1}> to be positive. {0}. + /// + internal static string IsPositiveFailMsg { + get { + return ResourceManager.GetString("IsPositiveFailMsg", resourceCulture); + } + } + /// /// Looks up a localized string similar to Expected exception type:<{1}> but no exception was thrown. {0}. /// @@ -575,7 +647,7 @@ internal static string PrivateAccessorMemberNotFound { } /// - /// Looks up a localized string similar to String '{0}' does not start with string '{1}'. {2}.. + /// Looks up a localized string similar to String '{0}' does not start with string '{1}'. {2}. /// internal static string StartsWithFail { get { @@ -637,60 +709,6 @@ internal static string UTF_TestMethodWrongExceptionDerivedAllowed { } } - /// - /// Looks up a localized string similar to Expected value <{1}> to be greater than actual value <{2}>. {0}. - /// - internal static string IsGreaterThanFailMsg { - get { - return ResourceManager.GetString("IsGreaterThanFailMsg", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Expected value <{1}> to be greater than or equal to actual value <{2}>. {0}. - /// - internal static string IsGreaterThanOrEqualToFailMsg { - get { - return ResourceManager.GetString("IsGreaterThanOrEqualToFailMsg", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Expected value <{1}> to be less than actual value <{2}>. {0}. - /// - internal static string IsLessThanFailMsg { - get { - return ResourceManager.GetString("IsLessThanFailMsg", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Expected value <{1}> to be less than or equal to actual value <{2}>. {0}. - /// - internal static string IsLessThanOrEqualToFailMsg { - get { - return ResourceManager.GetString("IsLessThanOrEqualToFailMsg", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Expected value <{1}> to be negative. {0}. - /// - internal static string IsNegativeFailMsg { - get { - return ResourceManager.GetString("IsNegativeFailMsg", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Expected value <{1}> to be positive. {0}. - /// - internal static string IsPositiveFailMsg { - get { - return ResourceManager.GetString("IsPositiveFailMsg", resourceCulture); - } - } - /// /// Looks up a localized string similar to Expected exception type:<{1}>. Actual exception type:<{2}>. {0}. /// diff --git a/src/TestFramework/TestFramework/Resources/FrameworkMessages.resx b/src/TestFramework/TestFramework/Resources/FrameworkMessages.resx index 3a4cad3de9..f1eee89b5c 100644 --- a/src/TestFramework/TestFramework/Resources/FrameworkMessages.resx +++ b/src/TestFramework/TestFramework/Resources/FrameworkMessages.resx @@ -180,7 +180,7 @@ Actual: {2} Element at index {1} is not of expected type. Expected type:<{2}>. Actual type:<{3}>.{0} - String '{0}' does not end with string '{1}'. {2}. + String '{0}' does not end with string '{1}'. {2} {0} failed. {1} @@ -189,13 +189,13 @@ Actual: {2} {0} Expected type:<{1}>. Actual type:<{2}>. - String '{0}' does not match pattern '{1}'. {2}. + String '{0}' does not match pattern '{1}'. {2} Wrong Type:<{1}>. Actual type:<{2}>. {0} - String '{0}' matches pattern '{1}'. {2}. + String '{0}' matches pattern '{1}'. {2} Assert.Equals should not be used for Assertions. Please use Assert.AreEqual & overloads instead. @@ -221,7 +221,7 @@ Actual: {2} Different number of elements. - String '{0}' does not start with string '{1}'. {2}. + String '{0}' does not start with string '{1}'. {2} The property {0} has type {1}; expected type {2}. @@ -341,4 +341,10 @@ Actual: {2} Expected value <{1}> to be negative. {0} - \ No newline at end of file + + String '{0}' ends with string '{1}'. {2} + + + String '{0}' starts with string '{1}'. {2} + + diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.cs.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.cs.xlf index c24e84e14d..30903b4759 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.cs.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.cs.xlf @@ -117,6 +117,16 @@ Expected no items to match the predicate. {0} + + String '{0}' ends with string '{1}'. {2} + String '{0}' ends with string '{1}'. {2} + + + + String '{0}' starts with string '{1}'. {2} + String '{0}' starts with string '{1}'. {2} + + Dynamic data method '{0}' should be static, parameterless and non-generic. Metoda dynamických dat {0} by měla být statická, bez parametrů a negenerická. @@ -141,9 +151,11 @@ Element at index {0} do not match. Expected: {1} Actual: {2} - Element v indexu {0} nesouhlasí. -Očekáváno: {1} -Skutečnost: {2} + + Element v indexu {0} nesouhlasí. + Očekáváno: {1} + Skutečnost: {2} + @@ -152,9 +164,9 @@ Skutečnost: {2} - String '{0}' does not end with string '{1}'. {2}. - Řetězec '{0}' nekončí řetězcem '{1}'. {2}. - + String '{0}' does not end with string '{1}'. {2} + Řetězec '{0}' nekončí řetězcem '{1}'. {2}. + {0} failed. {1} @@ -182,9 +194,9 @@ Skutečnost: {2} - String '{0}' does not match pattern '{1}'. {2}. - Řetězec '{0}' neodpovídá vzoru '{1}'. {2}. - + String '{0}' does not match pattern '{1}'. {2} + Řetězec '{0}' neodpovídá vzoru '{1}'. {2}. + Expected collection to contain any item but it is empty. {0} @@ -197,9 +209,9 @@ Skutečnost: {2} - String '{0}' matches pattern '{1}'. {2}. - Řetězec '{0}' odpovídá vzoru '{1}'. {2}. - + String '{0}' matches pattern '{1}'. {2} + Řetězec '{0}' odpovídá vzoru '{1}'. {2}. + Assert.Equals should not be used for Assertions. Please use Assert.AreEqual & overloads instead. @@ -212,12 +224,12 @@ Skutečnost: {2} or the member may be private and defined on a base class. If the latter is true, you need to pass the type that defines the member into PrivateObject's constructor. - - Zadaný člen ({0}) nemohl být nalezen. Je možné, že bude zapotřebí obnovit soukromý přístupový objekt, - nebo může být člen soukromý a definovaný v základní třídě. Pokud je tvrzení pravdivé, bude zapotřebí předat typ - , který definuje člena do konstruktoru PrivateObject. - - + + Zadaný člen ({0}) nemohl být nalezen. Je možné, že bude zapotřebí obnovit soukromý přístupový objekt, + nebo může být člen soukromý a definovaný v základní třídě. Pokud je tvrzení pravdivé, bude zapotřebí předat typ + , který definuje člena do konstruktoru PrivateObject. + + @@ -225,12 +237,12 @@ Skutečnost: {2} or the member may be private and defined on a base class. If the latter is true, you need to pass the type that defines the member into PrivateObject's constructor. - - Konstruktor se zadaným podpisem se nepovedlo najít. Je možné, že bude zapotřebí obnovit soukromý přistupující objekt, - nebo může být člen soukromý a definovaný v základní třídě. Pokud je tvrzení pravdivé, bude zapotřebí předat typ - , který definuje člena do konstruktoru PrivateObject. - - + + Konstruktor se zadaným podpisem se nepovedlo najít. Je možné, že bude zapotřebí obnovit soukromý přistupující objekt, + nebo může být člen soukromý a definovaný v základní třídě. Pokud je tvrzení pravdivé, bude zapotřebí předat typ + , který definuje člena do konstruktoru PrivateObject. + + The parameter '{0}' is invalid. The value cannot be null. {1}. @@ -243,9 +255,9 @@ Skutečnost: {2} - String '{0}' does not start with string '{1}'. {2}. - Řetězec '{0}' nezačíná řetězcem '{1}'. {2}. - + String '{0}' does not start with string '{1}'. {2} + Řetězec '{0}' nezačíná řetězcem '{1}'. {2}. + The property {0} has type {1}; expected type {2}. @@ -339,7 +351,7 @@ Skutečnost: {2} Type '{0}' is not assignable to '{1}'. - Typ „{0}“ nelze přiřadit k „{1}“. + Typ „{0}“ nelze přiřadit k „{1}“. - {0} argument name like "applicationType" - {1} fully qualified class name like "Microsoft.UI.Xaml.Application" diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.de.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.de.xlf index 23ed27cc41..3512ca0350 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.de.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.de.xlf @@ -117,6 +117,16 @@ Expected no items to match the predicate. {0} + + String '{0}' ends with string '{1}'. {2} + String '{0}' ends with string '{1}'. {2} + + + + String '{0}' starts with string '{1}'. {2} + String '{0}' starts with string '{1}'. {2} + + Dynamic data method '{0}' should be static, parameterless and non-generic. Die dynamische Datenmethode "{0}" muss statisch, parameterlos sein und nichtgenerisch sein. @@ -152,9 +162,9 @@ Tatsächlich: {2} - String '{0}' does not end with string '{1}'. {2}. - Die Zeichenfolge "{0}" endet nicht auf die Zeichenfolge "{1}". {2}. - + String '{0}' does not end with string '{1}'. {2} + Die Zeichenfolge "{0}" endet nicht auf die Zeichenfolge "{1}". {2}. + {0} failed. {1} @@ -182,9 +192,9 @@ Tatsächlich: {2} - String '{0}' does not match pattern '{1}'. {2}. - Die Zeichenfolge "{0}" stimmt nicht mit dem Muster "{1}" überein. {2}. - + String '{0}' does not match pattern '{1}'. {2} + Die Zeichenfolge "{0}" stimmt nicht mit dem Muster "{1}" überein. {2}. + Expected collection to contain any item but it is empty. {0} @@ -197,9 +207,9 @@ Tatsächlich: {2} - String '{0}' matches pattern '{1}'. {2}. - Die Zeichenfolge "{0}" stimmt mit dem Muster "{1}" überein. {2}. - + String '{0}' matches pattern '{1}'. {2} + Die Zeichenfolge "{0}" stimmt mit dem Muster "{1}" überein. {2}. + Assert.Equals should not be used for Assertions. Please use Assert.AreEqual & overloads instead. @@ -243,9 +253,9 @@ Tatsächlich: {2} - String '{0}' does not start with string '{1}'. {2}. - Die Zeichenfolge "{0}" beginnt nicht mit der Zeichenfolge "{1}". {2}. - + String '{0}' does not start with string '{1}'. {2} + Die Zeichenfolge "{0}" beginnt nicht mit der Zeichenfolge "{1}". {2}. + The property {0} has type {1}; expected type {2}. @@ -377,4 +387,4 @@ Tatsächlich: {2} - \ No newline at end of file + diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.es.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.es.xlf index ec6395cb5d..89579a0d64 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.es.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.es.xlf @@ -117,6 +117,16 @@ Expected no items to match the predicate. {0} + + String '{0}' ends with string '{1}'. {2} + String '{0}' ends with string '{1}'. {2} + + + + String '{0}' starts with string '{1}'. {2} + String '{0}' starts with string '{1}'. {2} + + Dynamic data method '{0}' should be static, parameterless and non-generic. El método de datos dinámicos '{0}' debe ser estático, sin parámetros y no genérico. @@ -141,9 +151,11 @@ Element at index {0} do not match. Expected: {1} Actual: {2} - El elemento del índice {0} no coincide. -Esperado: {1} -Real: {2} + + El elemento del índice {0} no coincide. + Esperado: {1} + Real: {2} + @@ -152,9 +164,9 @@ Real: {2} - String '{0}' does not end with string '{1}'. {2}. - La cadena '{0}' no termina con la cadena '{1}'. {2}. - + String '{0}' does not end with string '{1}'. {2} + La cadena '{0}' no termina con la cadena '{1}'. {2}. + {0} failed. {1} @@ -182,9 +194,9 @@ Real: {2} - String '{0}' does not match pattern '{1}'. {2}. - La cadena '{0}' no coincide con el patrón '{1}'. {2}. - + String '{0}' does not match pattern '{1}'. {2} + La cadena '{0}' no coincide con el patrón '{1}'. {2}. + Expected collection to contain any item but it is empty. {0} @@ -197,9 +209,9 @@ Real: {2} - String '{0}' matches pattern '{1}'. {2}. - La cadena '{0}' coincide con el patrón '{1}'. {2}. - + String '{0}' matches pattern '{1}'. {2} + La cadena '{0}' coincide con el patrón '{1}'. {2}. + Assert.Equals should not be used for Assertions. Please use Assert.AreEqual & overloads instead. @@ -212,12 +224,12 @@ Real: {2} or the member may be private and defined on a base class. If the latter is true, you need to pass the type that defines the member into PrivateObject's constructor. - - No se encontró el miembro especificado ({0}). Es posible que tenga que volver a generar el descriptor de acceso privado, - o que el miembro sea privado y esté definido en una clase base. Si esto último es cierto, debe pasar el tipo - que define el miembro al constructor de PrivateObject. - - + + No se encontró el miembro especificado ({0}). Es posible que tenga que volver a generar el descriptor de acceso privado, + o que el miembro sea privado y esté definido en una clase base. Si esto último es cierto, debe pasar el tipo + que define el miembro al constructor de PrivateObject. + + @@ -225,12 +237,12 @@ Real: {2} or the member may be private and defined on a base class. If the latter is true, you need to pass the type that defines the member into PrivateObject's constructor. - - No se encontró el constructor con la signatura especificada. Es posible que tenga que volver a generar el descriptor de acceso privado, - o que el miembro sea privado y esté definido en una clase base. Si esto último es cierto, debe pasar el tipo - que define el miembro al constructor de PrivateObject. - - + + No se encontró el constructor con la signatura especificada. Es posible que tenga que volver a generar el descriptor de acceso privado, + o que el miembro sea privado y esté definido en una clase base. Si esto último es cierto, debe pasar el tipo + que define el miembro al constructor de PrivateObject. + + The parameter '{0}' is invalid. The value cannot be null. {1}. @@ -243,9 +255,9 @@ Real: {2} - String '{0}' does not start with string '{1}'. {2}. - La cadena '{0}' no empieza con la cadena '{1}'. {2}. - + String '{0}' does not start with string '{1}'. {2} + La cadena '{0}' no empieza con la cadena '{1}'. {2}. + The property {0} has type {1}; expected type {2}. @@ -339,7 +351,7 @@ Real: {2} Type '{0}' is not assignable to '{1}'. - Tipo "{0}" no se puede asignar a "{1}". + Tipo "{0}" no se puede asignar a "{1}". - {0} argument name like "applicationType" - {1} fully qualified class name like "Microsoft.UI.Xaml.Application" diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.fr.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.fr.xlf index a4db3c3800..4ea1be6613 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.fr.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.fr.xlf @@ -117,6 +117,16 @@ Expected no items to match the predicate. {0} + + String '{0}' ends with string '{1}'. {2} + String '{0}' ends with string '{1}'. {2} + + + + String '{0}' starts with string '{1}'. {2} + String '{0}' starts with string '{1}'. {2} + + Dynamic data method '{0}' should be static, parameterless and non-generic. La méthode de données dynamiques « {0} » doit être statique, sans paramètre et non générique. @@ -141,9 +151,11 @@ Element at index {0} do not match. Expected: {1} Actual: {2} - L’élément au {0} d’index ne correspond pas. -Attendu : {1} -Réel : {2} + + L’élément au {0} d’index ne correspond pas. + Attendu : {1} + Réel : {2} + @@ -152,9 +164,9 @@ Réel : {2} - String '{0}' does not end with string '{1}'. {2}. - La chaîne '{0}' ne se termine pas par la chaîne '{1}'. {2}. - + String '{0}' does not end with string '{1}'. {2} + La chaîne '{0}' ne se termine pas par la chaîne '{1}'. {2}. + {0} failed. {1} @@ -182,9 +194,9 @@ Réel : {2} - String '{0}' does not match pattern '{1}'. {2}. - La chaîne '{0}' ne correspond pas au modèle '{1}'. {2}. - + String '{0}' does not match pattern '{1}'. {2} + La chaîne '{0}' ne correspond pas au modèle '{1}'. {2}. + Expected collection to contain any item but it is empty. {0} @@ -197,9 +209,9 @@ Réel : {2} - String '{0}' matches pattern '{1}'. {2}. - La chaîne '{0}' correspond au modèle '{1}'. {2}. - + String '{0}' matches pattern '{1}'. {2} + La chaîne '{0}' correspond au modèle '{1}'. {2}. + Assert.Equals should not be used for Assertions. Please use Assert.AreEqual & overloads instead. @@ -212,12 +224,12 @@ Réel : {2} or the member may be private and defined on a base class. If the latter is true, you need to pass the type that defines the member into PrivateObject's constructor. - - Le membre spécifié ({0}) est introuvable. Vous devrez peut-être régénérer votre accesseur private, - ou le membre est peut-être private et défini sur une classe de base. Si le dernier cas est vrai, vous devez transmettre le type - qui définit le membre dans le constructeur de PrivateObject. - - + + Le membre spécifié ({0}) est introuvable. Vous devrez peut-être régénérer votre accesseur private, + ou le membre est peut-être private et défini sur une classe de base. Si le dernier cas est vrai, vous devez transmettre le type + qui définit le membre dans le constructeur de PrivateObject. + + @@ -225,12 +237,12 @@ Réel : {2} or the member may be private and defined on a base class. If the latter is true, you need to pass the type that defines the member into PrivateObject's constructor. - - Le constructeur doté de la signature spécifiée est introuvable. Vous devrez peut-être régénérer votre accesseur private, - ou le membre est peut-être private et défini sur une classe de base. Si le dernier cas est vrai, vous devez transmettre le type - qui définit le membre dans le constructeur de PrivateObject. - - + + Le constructeur doté de la signature spécifiée est introuvable. Vous devrez peut-être régénérer votre accesseur private, + ou le membre est peut-être private et défini sur une classe de base. Si le dernier cas est vrai, vous devez transmettre le type + qui définit le membre dans le constructeur de PrivateObject. + + The parameter '{0}' is invalid. The value cannot be null. {1}. @@ -243,9 +255,9 @@ Réel : {2} - String '{0}' does not start with string '{1}'. {2}. - La chaîne '{0}' ne commence pas par la chaîne '{1}'. {2}. - + String '{0}' does not start with string '{1}'. {2} + La chaîne '{0}' ne commence pas par la chaîne '{1}'. {2}. + The property {0} has type {1}; expected type {2}. @@ -339,7 +351,7 @@ Réel : {2} Type '{0}' is not assignable to '{1}'. - Impossible d'assigner le type '{0}' à '{1}'. + Impossible d'assigner le type '{0}' à '{1}'. - {0} argument name like "applicationType" - {1} fully qualified class name like "Microsoft.UI.Xaml.Application" diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.it.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.it.xlf index 6a286037b5..c51115a9b6 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.it.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.it.xlf @@ -117,6 +117,16 @@ Expected no items to match the predicate. {0} + + String '{0}' ends with string '{1}'. {2} + String '{0}' ends with string '{1}'. {2} + + + + String '{0}' starts with string '{1}'. {2} + String '{0}' starts with string '{1}'. {2} + + Dynamic data method '{0}' should be static, parameterless and non-generic. Il metodo '{0}' di Dynamic Data deve essere statico, senza parametri e non generico. @@ -141,9 +151,11 @@ Element at index {0} do not match. Expected: {1} Actual: {2} - L'elemento nell'indice {0} non corrisponde. -Previsto: {1} -Effettivo: {2} + + L'elemento nell'indice {0} non corrisponde. + Previsto: {1} + Effettivo: {2} + @@ -152,9 +164,9 @@ Effettivo: {2} - String '{0}' does not end with string '{1}'. {2}. - La stringa '{0}' non termina con la stringa '{1}'. {2}. - + String '{0}' does not end with string '{1}'. {2} + La stringa '{0}' non termina con la stringa '{1}'. {2}. + {0} failed. {1} @@ -182,9 +194,9 @@ Effettivo: {2} - String '{0}' does not match pattern '{1}'. {2}. - La stringa '{0}' non corrisponde al criterio '{1}'. {2}. - + String '{0}' does not match pattern '{1}'. {2} + La stringa '{0}' non corrisponde al criterio '{1}'. {2}. + Expected collection to contain any item but it is empty. {0} @@ -197,9 +209,9 @@ Effettivo: {2} - String '{0}' matches pattern '{1}'. {2}. - La stringa '{0}' corrisponde al criterio '{1}'. {2}. - + String '{0}' matches pattern '{1}'. {2} + La stringa '{0}' corrisponde al criterio '{1}'. {2}. + Assert.Equals should not be used for Assertions. Please use Assert.AreEqual & overloads instead. @@ -212,12 +224,12 @@ Effettivo: {2} or the member may be private and defined on a base class. If the latter is true, you need to pass the type that defines the member into PrivateObject's constructor. - - Il membro specificato ({0}) non è stato trovato. Potrebbe essere necessario rigenerare la funzione di accesso privata - oppure il membro potrebbe essere privato e definito per una classe base. In quest'ultimo caso, è necessario passare il tipo - che definisce il membro nel costruttore di PrivateObject. - - + + Il membro specificato ({0}) non è stato trovato. Potrebbe essere necessario rigenerare la funzione di accesso privata + oppure il membro potrebbe essere privato e definito per una classe base. In quest'ultimo caso, è necessario passare il tipo + che definisce il membro nel costruttore di PrivateObject. + + @@ -225,12 +237,12 @@ Effettivo: {2} or the member may be private and defined on a base class. If the latter is true, you need to pass the type that defines the member into PrivateObject's constructor. - - Il costruttore con la firma specificata non è stato trovato. Potrebbe essere necessario rigenerare la funzione di accesso privata - oppure il membro potrebbe essere privato e definito per una classe base. In quest'ultimo caso, è necessario passare il tipo - che definisce il membro nel costruttore di PrivateObject. - - + + Il costruttore con la firma specificata non è stato trovato. Potrebbe essere necessario rigenerare la funzione di accesso privata + oppure il membro potrebbe essere privato e definito per una classe base. In quest'ultimo caso, è necessario passare il tipo + che definisce il membro nel costruttore di PrivateObject. + + The parameter '{0}' is invalid. The value cannot be null. {1}. @@ -243,9 +255,9 @@ Effettivo: {2} - String '{0}' does not start with string '{1}'. {2}. - La stringa '{0}' non inizia con la stringa '{1}'. {2}. - + String '{0}' does not start with string '{1}'. {2} + La stringa '{0}' non inizia con la stringa '{1}'. {2}. + The property {0} has type {1}; expected type {2}. @@ -339,7 +351,7 @@ Effettivo: {2} Type '{0}' is not assignable to '{1}'. - Il tipo '{0}' non è assegnabile a '{1}'. + Il tipo '{0}' non è assegnabile a '{1}'. - {0} argument name like "applicationType" - {1} fully qualified class name like "Microsoft.UI.Xaml.Application" diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ja.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ja.xlf index 94b6a9785b..636ffd5361 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ja.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ja.xlf @@ -117,6 +117,16 @@ Expected no items to match the predicate. {0} + + String '{0}' ends with string '{1}'. {2} + String '{0}' ends with string '{1}'. {2} + + + + String '{0}' starts with string '{1}'. {2} + String '{0}' starts with string '{1}'. {2} + + Dynamic data method '{0}' should be static, parameterless and non-generic. 動的データ メソッド '{0}' は、静的、パラメーターなし、および非ジェネリックである必要があります。 @@ -141,9 +151,11 @@ Element at index {0} do not match. Expected: {1} Actual: {2} - インデックス {0} の要素が一致しません。 -予想: {1} -実際: {2} + + インデックス {0} の要素が一致しません。 + 予想: {1} + 実際: {2} + @@ -152,9 +164,9 @@ Actual: {2} - String '{0}' does not end with string '{1}'. {2}. - 文字列 '{0}' は文字列 '{1}' で終わりません。{2}。 - + String '{0}' does not end with string '{1}'. {2} + 文字列 '{0}' は文字列 '{1}' で終わりません。{2}。 + {0} failed. {1} @@ -182,9 +194,9 @@ Actual: {2} - String '{0}' does not match pattern '{1}'. {2}. - 文字列 '{0}' はパターン '{1}' と一致しません。{2}。 - + String '{0}' does not match pattern '{1}'. {2} + 文字列 '{0}' はパターン '{1}' と一致しません。{2}。 + Expected collection to contain any item but it is empty. {0} @@ -197,9 +209,9 @@ Actual: {2} - String '{0}' matches pattern '{1}'. {2}. - 文字列 '{0}' はパターン '{1}' と一致します。{2}。 - + String '{0}' matches pattern '{1}'. {2} + 文字列 '{0}' はパターン '{1}' と一致します。{2}。 + Assert.Equals should not be used for Assertions. Please use Assert.AreEqual & overloads instead. @@ -212,12 +224,12 @@ Actual: {2} or the member may be private and defined on a base class. If the latter is true, you need to pass the type that defines the member into PrivateObject's constructor. - - 指定されたメンバー ({0}) が見つかりませんでした。プライベート アクセサーを再生成しなければならないか、 - またはメンバーがプライベートであり、基底クラスで定義されている可能性があります。後者である場合は、メンバーを - 定義する型を PrivateObject のコンストラクターに渡す必要があります。 - - + + 指定されたメンバー ({0}) が見つかりませんでした。プライベート アクセサーを再生成しなければならないか、 + またはメンバーがプライベートであり、基底クラスで定義されている可能性があります。後者である場合は、メンバーを + 定義する型を PrivateObject のコンストラクターに渡す必要があります。 + + @@ -225,12 +237,12 @@ Actual: {2} or the member may be private and defined on a base class. If the latter is true, you need to pass the type that defines the member into PrivateObject's constructor. - - 指定されたシグネチャを使用するコンストラクターが見つかりませんでした。プライベート アクセサーを再生成しなければならないか、 - またはメンバーがプライベートであり、基底クラスで定義されている可能性があります。後者である場合は、メンバーを - 定義する型を PrivateObject のコンストラクターに渡す必要があります。 - - + + 指定されたシグネチャを使用するコンストラクターが見つかりませんでした。プライベート アクセサーを再生成しなければならないか、 + またはメンバーがプライベートであり、基底クラスで定義されている可能性があります。後者である場合は、メンバーを + 定義する型を PrivateObject のコンストラクターに渡す必要があります。 + + The parameter '{0}' is invalid. The value cannot be null. {1}. @@ -243,9 +255,9 @@ Actual: {2} - String '{0}' does not start with string '{1}'. {2}. - 文字列 '{0}' は文字列 '{1}' で始まりません。{2}。 - + String '{0}' does not start with string '{1}'. {2} + 文字列 '{0}' は文字列 '{1}' で始まりません。{2}。 + The property {0} has type {1}; expected type {2}. @@ -339,7 +351,7 @@ Actual: {2} Type '{0}' is not assignable to '{1}'. - 型 '{0}' を '{1}' に割り当てることはできません。 + 型 '{0}' を '{1}' に割り当てることはできません。 - {0} argument name like "applicationType" - {1} fully qualified class name like "Microsoft.UI.Xaml.Application" diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ko.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ko.xlf index f7d99eddbe..f0c3cb6646 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ko.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ko.xlf @@ -117,6 +117,16 @@ Expected no items to match the predicate. {0} + + String '{0}' ends with string '{1}'. {2} + String '{0}' ends with string '{1}'. {2} + + + + String '{0}' starts with string '{1}'. {2} + String '{0}' starts with string '{1}'. {2} + + Dynamic data method '{0}' should be static, parameterless and non-generic. 동적 데이터 메서드 '{0}'은(는) 정적이고 매개 변수가 없으며 제네릭이 아니어야 합니다. @@ -141,9 +151,11 @@ Element at index {0} do not match. Expected: {1} Actual: {2} - 인덱스 {0}에 있는 요소가 일치하지 않습니다. -예상: {1} -실제: {2} + + 인덱스 {0}에 있는 요소가 일치하지 않습니다. + 예상: {1} + 실제: {2} + @@ -152,9 +164,9 @@ Actual: {2} - String '{0}' does not end with string '{1}'. {2}. - '{0}' 문자열이 '{1}' 문자열로 끝나지 않습니다. {2} - + String '{0}' does not end with string '{1}'. {2} + '{0}' 문자열이 '{1}' 문자열로 끝나지 않습니다. {2} + {0} failed. {1} @@ -182,9 +194,9 @@ Actual: {2} - String '{0}' does not match pattern '{1}'. {2}. - '{0}' 문자열이 '{1}' 패턴과 일치하지 않습니다. {2} - + String '{0}' does not match pattern '{1}'. {2} + '{0}' 문자열이 '{1}' 패턴과 일치하지 않습니다. {2} + Expected collection to contain any item but it is empty. {0} @@ -197,9 +209,9 @@ Actual: {2} - String '{0}' matches pattern '{1}'. {2}. - '{0}' 문자열이 '{1}' 패턴과 일치합니다. {2} - + String '{0}' matches pattern '{1}'. {2} + '{0}' 문자열이 '{1}' 패턴과 일치합니다. {2} + Assert.Equals should not be used for Assertions. Please use Assert.AreEqual & overloads instead. @@ -212,12 +224,12 @@ Actual: {2} or the member may be private and defined on a base class. If the latter is true, you need to pass the type that defines the member into PrivateObject's constructor. - - 지정한 멤버({0})를 찾을 수 없습니다. 프라이빗 접근자를 다시 생성해야 할 수 있습니다. - 또는 멤버가 기본 클래스에 정의된 프라이빗 멤버일 수 있습니다. 기본 클래스에 정의된 전용 멤버인 경우에는 이 멤버를 정의하는 형식을 - PrivateObject의 생성자에 전달해야 합니다. - - + + 지정한 멤버({0})를 찾을 수 없습니다. 프라이빗 접근자를 다시 생성해야 할 수 있습니다. + 또는 멤버가 기본 클래스에 정의된 프라이빗 멤버일 수 있습니다. 기본 클래스에 정의된 전용 멤버인 경우에는 이 멤버를 정의하는 형식을 + PrivateObject의 생성자에 전달해야 합니다. + + @@ -225,12 +237,12 @@ Actual: {2} or the member may be private and defined on a base class. If the latter is true, you need to pass the type that defines the member into PrivateObject's constructor. - - 지정한 서명을 가진 생성자를 찾을 수 없습니다. 프라이빗 접근자를 다시 생성해야 할 수 있습니다. - 또는 멤버가 기본 클래스에 정의된 프라이빗 멤버일 수 있습니다. 기본 클래스에 정의된 전용 멤버인 경우에는 이 멤버를 정의하는 형식을 - PrivateObject의 생성자에 전달해야 합니다. - - + + 지정한 서명을 가진 생성자를 찾을 수 없습니다. 프라이빗 접근자를 다시 생성해야 할 수 있습니다. + 또는 멤버가 기본 클래스에 정의된 프라이빗 멤버일 수 있습니다. 기본 클래스에 정의된 전용 멤버인 경우에는 이 멤버를 정의하는 형식을 + PrivateObject의 생성자에 전달해야 합니다. + + The parameter '{0}' is invalid. The value cannot be null. {1}. @@ -243,9 +255,9 @@ Actual: {2} - String '{0}' does not start with string '{1}'. {2}. - '{0}' 문자열이 '{1}' 문자열로 시작되지 않습니다. {2} - + String '{0}' does not start with string '{1}'. {2} + '{0}' 문자열이 '{1}' 문자열로 시작되지 않습니다. {2} + The property {0} has type {1}; expected type {2}. @@ -339,7 +351,7 @@ Actual: {2} Type '{0}' is not assignable to '{1}'. - '{0}' 형식은 '{1}'에 할당할 수 없습니다. + '{0}' 형식은 '{1}'에 할당할 수 없습니다. - {0} argument name like "applicationType" - {1} fully qualified class name like "Microsoft.UI.Xaml.Application" diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pl.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pl.xlf index 062a4c7dca..567fe8cef7 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pl.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pl.xlf @@ -117,6 +117,16 @@ Expected no items to match the predicate. {0} + + String '{0}' ends with string '{1}'. {2} + String '{0}' ends with string '{1}'. {2} + + + + String '{0}' starts with string '{1}'. {2} + String '{0}' starts with string '{1}'. {2} + + Dynamic data method '{0}' should be static, parameterless and non-generic. Metoda danych dynamicznych „{0}” powinna być statyczna, bez parametrów i nie generyczna. @@ -141,9 +151,11 @@ Element at index {0} do not match. Expected: {1} Actual: {2} - Element w indeksie {0} nie jest zgodny. -Oczekiwano: {1} -Rzeczywiste: {2} + + Element w indeksie {0} nie jest zgodny. + Oczekiwano: {1} + Rzeczywiste: {2} + @@ -152,9 +164,9 @@ Rzeczywiste: {2} - String '{0}' does not end with string '{1}'. {2}. - Ciąg „{0}” nie kończy się ciągiem „{1}”. {2}. - + String '{0}' does not end with string '{1}'. {2} + Ciąg „{0}” nie kończy się ciągiem „{1}”. {2}. + {0} failed. {1} @@ -182,9 +194,9 @@ Rzeczywiste: {2} - String '{0}' does not match pattern '{1}'. {2}. - Ciąg „{0}” nie jest zgodny ze wzorcem „{1}”. {2}. - + String '{0}' does not match pattern '{1}'. {2} + Ciąg „{0}” nie jest zgodny ze wzorcem „{1}”. {2}. + Expected collection to contain any item but it is empty. {0} @@ -197,9 +209,9 @@ Rzeczywiste: {2} - String '{0}' matches pattern '{1}'. {2}. - Ciąg „{0}” jest zgodny ze wzorcem „{1}”. {2}. - + String '{0}' matches pattern '{1}'. {2} + Ciąg „{0}” jest zgodny ze wzorcem „{1}”. {2}. + Assert.Equals should not be used for Assertions. Please use Assert.AreEqual & overloads instead. @@ -212,12 +224,12 @@ Rzeczywiste: {2} or the member may be private and defined on a base class. If the latter is true, you need to pass the type that defines the member into PrivateObject's constructor. - - Nie można odnaleźć określonej składowej ({0}). Może być konieczne ponowne wygenerowanie prywatnej metody dostępu - lub składowa może być zdefiniowana jako prywatna w klasie bazowej. W drugim przypadku należy przekazać typ, - który definiuje składową w konstruktorze obiektu PrivateObject. - - + + Nie można odnaleźć określonej składowej ({0}). Może być konieczne ponowne wygenerowanie prywatnej metody dostępu + lub składowa może być zdefiniowana jako prywatna w klasie bazowej. W drugim przypadku należy przekazać typ, + który definiuje składową w konstruktorze obiektu PrivateObject. + + @@ -225,12 +237,12 @@ Rzeczywiste: {2} or the member may be private and defined on a base class. If the latter is true, you need to pass the type that defines the member into PrivateObject's constructor. - - Nie można odnaleźć konstruktora z określoną sygnaturą. Może być konieczne ponowne wygenerowanie prywatnej metody dostępu - lub składowa może być zdefiniowana jako prywatna w klasie bazowej. W drugim przypadku należy przekazać typ, - który definiuje składową w konstruktorze obiektu PrivateObject. - - + + Nie można odnaleźć konstruktora z określoną sygnaturą. Może być konieczne ponowne wygenerowanie prywatnej metody dostępu + lub składowa może być zdefiniowana jako prywatna w klasie bazowej. W drugim przypadku należy przekazać typ, + który definiuje składową w konstruktorze obiektu PrivateObject. + + The parameter '{0}' is invalid. The value cannot be null. {1}. @@ -243,9 +255,9 @@ Rzeczywiste: {2} - String '{0}' does not start with string '{1}'. {2}. - Ciąg „{0}” nie rozpoczyna się od ciągu „{1}”. {2}. - + String '{0}' does not start with string '{1}'. {2} + Ciąg „{0}” nie rozpoczyna się od ciągu „{1}”. {2}. + The property {0} has type {1}; expected type {2}. @@ -339,7 +351,7 @@ Rzeczywiste: {2} Type '{0}' is not assignable to '{1}'. - Typu „{0}” nie można przypisać do typu „{1}”. + Typu „{0}” nie można przypisać do typu „{1}”. - {0} argument name like "applicationType" - {1} fully qualified class name like "Microsoft.UI.Xaml.Application" diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf index 634418e4e9..5e2eb1ad84 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf @@ -117,6 +117,16 @@ Expected no items to match the predicate. {0} + + String '{0}' ends with string '{1}'. {2} + String '{0}' ends with string '{1}'. {2} + + + + String '{0}' starts with string '{1}'. {2} + String '{0}' starts with string '{1}'. {2} + + Dynamic data method '{0}' should be static, parameterless and non-generic. O método de dados dinâmicos "{0}" deve ser estático, sem parâmetros e não genérico. @@ -141,9 +151,11 @@ Element at index {0} do not match. Expected: {1} Actual: {2} - O elemento no índice {0} não corresponde. -Esperado: {1} -Real: {2} + + O elemento no índice {0} não corresponde. + Esperado: {1} + Real: {2} + @@ -152,9 +164,9 @@ Real: {2} - String '{0}' does not end with string '{1}'. {2}. - A cadeia de caracteres '{0}' não termina com a cadeia de caracteres '{1}'. {2}. - + String '{0}' does not end with string '{1}'. {2} + A cadeia de caracteres '{0}' não termina com a cadeia de caracteres '{1}'. {2}. + {0} failed. {1} @@ -182,9 +194,9 @@ Real: {2} - String '{0}' does not match pattern '{1}'. {2}. - A cadeia de caracteres '{0}' não corresponde ao padrão '{1}'. {2}. - + String '{0}' does not match pattern '{1}'. {2} + A cadeia de caracteres '{0}' não corresponde ao padrão '{1}'. {2}. + Expected collection to contain any item but it is empty. {0} @@ -197,9 +209,9 @@ Real: {2} - String '{0}' matches pattern '{1}'. {2}. - A cadeia de caracteres '{0}' corresponde ao padrão '{1}'. {2}. - + String '{0}' matches pattern '{1}'. {2} + A cadeia de caracteres '{0}' corresponde ao padrão '{1}'. {2}. + Assert.Equals should not be used for Assertions. Please use Assert.AreEqual & overloads instead. @@ -212,12 +224,12 @@ Real: {2} or the member may be private and defined on a base class. If the latter is true, you need to pass the type that defines the member into PrivateObject's constructor. - - O membro especificado ({0}) não pôde ser encontrado. Talvez seja necessário gerar novamente seu acessador particular - ou o membro pode ser particular e definido em uma classe base. Se o último caso for verdadeiro, será necessário passar o tipo - que define o membro no construtor do PrivateObject. - - + + O membro especificado ({0}) não pôde ser encontrado. Talvez seja necessário gerar novamente seu acessador particular + ou o membro pode ser particular e definido em uma classe base. Se o último caso for verdadeiro, será necessário passar o tipo + que define o membro no construtor do PrivateObject. + + @@ -225,12 +237,12 @@ Real: {2} or the member may be private and defined on a base class. If the latter is true, you need to pass the type that defines the member into PrivateObject's constructor. - - O construtor com a assinatura especificada não pôde ser encontrado. Talvez seja necessário gerar novamente seu acessador particular - ou o membro pode ser particular e definido em uma classe base. Se o último caso for verdadeiro, será necessário passar o tipo - que define o membro para o construtor do PrivateObject. - - + + O construtor com a assinatura especificada não pôde ser encontrado. Talvez seja necessário gerar novamente seu acessador particular + ou o membro pode ser particular e definido em uma classe base. Se o último caso for verdadeiro, será necessário passar o tipo + que define o membro para o construtor do PrivateObject. + + The parameter '{0}' is invalid. The value cannot be null. {1}. @@ -243,9 +255,9 @@ Real: {2} - String '{0}' does not start with string '{1}'. {2}. - A cadeia de caracteres '{0}' não começa com a cadeia de caracteres '{1}'. {2}. - + String '{0}' does not start with string '{1}'. {2} + A cadeia de caracteres '{0}' não começa com a cadeia de caracteres '{1}'. {2}. + The property {0} has type {1}; expected type {2}. @@ -339,7 +351,7 @@ Real: {2} Type '{0}' is not assignable to '{1}'. - Tipo '{0}' não é atribuível a '{1}'. + Tipo '{0}' não é atribuível a '{1}'. - {0} argument name like "applicationType" - {1} fully qualified class name like "Microsoft.UI.Xaml.Application" diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ru.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ru.xlf index 0a7d64ebbc..61bb453d5e 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ru.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ru.xlf @@ -117,6 +117,16 @@ Expected no items to match the predicate. {0} + + String '{0}' ends with string '{1}'. {2} + String '{0}' ends with string '{1}'. {2} + + + + String '{0}' starts with string '{1}'. {2} + String '{0}' starts with string '{1}'. {2} + + Dynamic data method '{0}' should be static, parameterless and non-generic. Метод динамических данных "{0}" должен быть статическим, не иметь параметров и быть неуниверсальным. @@ -141,9 +151,11 @@ Element at index {0} do not match. Expected: {1} Actual: {2} - Элемент по индексу {0} не совпадает. -Ожидается: {1} -Фактическое значение: {2} + + Элемент по индексу {0} не совпадает. + Ожидается: {1} + Фактическое значение: {2} + @@ -152,9 +164,9 @@ Actual: {2} - String '{0}' does not end with string '{1}'. {2}. - Строка "{0}" не оканчивается строкой "{1}". {2}. - + String '{0}' does not end with string '{1}'. {2} + Строка "{0}" не оканчивается строкой "{1}". {2}. + {0} failed. {1} @@ -182,9 +194,9 @@ Actual: {2} - String '{0}' does not match pattern '{1}'. {2}. - Строка "{0}" не соответствует шаблону "{1}". {2}. - + String '{0}' does not match pattern '{1}'. {2} + Строка "{0}" не соответствует шаблону "{1}". {2}. + Expected collection to contain any item but it is empty. {0} @@ -197,9 +209,9 @@ Actual: {2} - String '{0}' matches pattern '{1}'. {2}. - Строка "{0}" соответствует шаблону "{1}". {2}. - + String '{0}' matches pattern '{1}'. {2} + Строка "{0}" соответствует шаблону "{1}". {2}. + Assert.Equals should not be used for Assertions. Please use Assert.AreEqual & overloads instead. @@ -212,12 +224,12 @@ Actual: {2} or the member may be private and defined on a base class. If the latter is true, you need to pass the type that defines the member into PrivateObject's constructor. - - Не удается найти указанный член ({0}). Возможно, требуется снова создать закрытый метод доступа - либо член является закрытым и определенным на основе базового класса. Если справедливо последнее, то - необходимо передать тип, определяющий член, в конструктор для PrivateObject. - - + + Не удается найти указанный член ({0}). Возможно, требуется снова создать закрытый метод доступа + либо член является закрытым и определенным на основе базового класса. Если справедливо последнее, то + необходимо передать тип, определяющий член, в конструктор для PrivateObject. + + @@ -225,12 +237,12 @@ Actual: {2} or the member may be private and defined on a base class. If the latter is true, you need to pass the type that defines the member into PrivateObject's constructor. - - Не удается найти конструктор с указанной сигнатурой. Возможно, требуется снова создать закрытый - метод доступа либо член является закрытым и определенным на основе базового класса. Если - справедливо последнее, то необходимо передать тип, определяющий член, в конструктор для PrivateObject. - - + + Не удается найти конструктор с указанной сигнатурой. Возможно, требуется снова создать закрытый + метод доступа либо член является закрытым и определенным на основе базового класса. Если + справедливо последнее, то необходимо передать тип, определяющий член, в конструктор для PrivateObject. + + The parameter '{0}' is invalid. The value cannot be null. {1}. @@ -243,9 +255,9 @@ Actual: {2} - String '{0}' does not start with string '{1}'. {2}. - Строка "{0}" не начинается со строки "{1}". {2}. - + String '{0}' does not start with string '{1}'. {2} + Строка "{0}" не начинается со строки "{1}". {2}. + The property {0} has type {1}; expected type {2}. @@ -339,7 +351,7 @@ Actual: {2} Type '{0}' is not assignable to '{1}'. - Тип "{0}" не может быть назначен "{1}". + Тип "{0}" не может быть назначен "{1}". - {0} argument name like "applicationType" - {1} fully qualified class name like "Microsoft.UI.Xaml.Application" diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.tr.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.tr.xlf index 6b51802cd0..9d87a6ac8e 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.tr.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.tr.xlf @@ -117,6 +117,16 @@ Expected no items to match the predicate. {0} + + String '{0}' ends with string '{1}'. {2} + String '{0}' ends with string '{1}'. {2} + + + + String '{0}' starts with string '{1}'. {2} + String '{0}' starts with string '{1}'. {2} + + Dynamic data method '{0}' should be static, parameterless and non-generic. '{0}' dinamik veri yöntemi statik ve parametresiz olmalı ve genel olmamalıdır. @@ -141,9 +151,11 @@ Element at index {0} do not match. Expected: {1} Actual: {2} - {0} dizinindeki öğe eşleşmiyor. -Beklenen: {1} -Gerçekte olan: {2} + + {0} dizinindeki öğe eşleşmiyor. + Beklenen: {1} + Gerçekte olan: {2} + @@ -152,9 +164,9 @@ Gerçekte olan: {2} - String '{0}' does not end with string '{1}'. {2}. - '{0}' dizesi, '{1}' dizesi ile sonlanmıyor. {2}. - + String '{0}' does not end with string '{1}'. {2} + '{0}' dizesi, '{1}' dizesi ile sonlanmıyor. {2}. + {0} failed. {1} @@ -182,9 +194,9 @@ Gerçekte olan: {2} - String '{0}' does not match pattern '{1}'. {2}. - '{0}' dizesi, '{1}' deseni ile eşleşmiyor. {2}. - + String '{0}' does not match pattern '{1}'. {2} + '{0}' dizesi, '{1}' deseni ile eşleşmiyor. {2}. + Expected collection to contain any item but it is empty. {0} @@ -197,9 +209,9 @@ Gerçekte olan: {2} - String '{0}' matches pattern '{1}'. {2}. - '{0}' dizesi, '{1}' deseni ile eşleşiyor. {2}. - + String '{0}' matches pattern '{1}'. {2} + '{0}' dizesi, '{1}' deseni ile eşleşiyor. {2}. + Assert.Equals should not be used for Assertions. Please use Assert.AreEqual & overloads instead. @@ -212,12 +224,12 @@ Gerçekte olan: {2} or the member may be private and defined on a base class. If the latter is true, you need to pass the type that defines the member into PrivateObject's constructor. - - Belirtilen üye ({0}) bulunamadı. Özel erişimcinizi yeniden oluşturmanız gerekiyor olabilir - veya üye, özel olabilir ve temel sınıfta tanımlı olabilir. Eğer ikincisi doğru ise, türü geçirmeniz gerekir; - bu tür PrivateObject'in oluşturucusunda üyeyi tanımlar. - - + + Belirtilen üye ({0}) bulunamadı. Özel erişimcinizi yeniden oluşturmanız gerekiyor olabilir + veya üye, özel olabilir ve temel sınıfta tanımlı olabilir. Eğer ikincisi doğru ise, türü geçirmeniz gerekir; + bu tür PrivateObject'in oluşturucusunda üyeyi tanımlar. + + @@ -225,12 +237,12 @@ Gerçekte olan: {2} or the member may be private and defined on a base class. If the latter is true, you need to pass the type that defines the member into PrivateObject's constructor. - - Belirtilmiş imzaya sahip oluşturucu bulunamadı. Özel erişimcinizi yeniden oluşturmanız gerekiyor olabilir - veya üye, özel olabilir ve temel sınıfta tanımlı olabilir. Eğer ikincisi doğru ise, türü geçirmeniz gerekir; - bu tür, PrivateObject'in oluşturucusunda üyeyi tanımlar. - - + + Belirtilmiş imzaya sahip oluşturucu bulunamadı. Özel erişimcinizi yeniden oluşturmanız gerekiyor olabilir + veya üye, özel olabilir ve temel sınıfta tanımlı olabilir. Eğer ikincisi doğru ise, türü geçirmeniz gerekir; + bu tür, PrivateObject'in oluşturucusunda üyeyi tanımlar. + + The parameter '{0}' is invalid. The value cannot be null. {1}. @@ -243,9 +255,9 @@ Gerçekte olan: {2} - String '{0}' does not start with string '{1}'. {2}. - '{0}' dizesi, '{1}' dizesi ile başlamıyor. {2}. - + String '{0}' does not start with string '{1}'. {2} + '{0}' dizesi, '{1}' dizesi ile başlamıyor. {2}. + The property {0} has type {1}; expected type {2}. @@ -339,7 +351,7 @@ Gerçekte olan: {2} Type '{0}' is not assignable to '{1}'. - '{0}' tipi '{1}'ye atanamaz. + '{0}' tipi '{1}'ye atanamaz. - {0} argument name like "applicationType" - {1} fully qualified class name like "Microsoft.UI.Xaml.Application" diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf index 741f48147a..762c39d9f2 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf @@ -117,6 +117,16 @@ Expected no items to match the predicate. {0} + + String '{0}' ends with string '{1}'. {2} + String '{0}' ends with string '{1}'. {2} + + + + String '{0}' starts with string '{1}'. {2} + String '{0}' starts with string '{1}'. {2} + + Dynamic data method '{0}' should be static, parameterless and non-generic. 动态数据方法“{0}”应为静态、无参数和非泛型。 @@ -141,9 +151,11 @@ Element at index {0} do not match. Expected: {1} Actual: {2} - 索引 {0} 处的元素不匹配。 -预计值: {1} -实际值: {2} + + 索引 {0} 处的元素不匹配。 + 预计值: {1} + 实际值: {2} + @@ -152,9 +164,9 @@ Actual: {2} - String '{0}' does not end with string '{1}'. {2}. - 字符串“{0}”不以字符串“{1}”结尾。{2}。 - + String '{0}' does not end with string '{1}'. {2} + 字符串“{0}”不以字符串“{1}”结尾。{2}。 + {0} failed. {1} @@ -182,9 +194,9 @@ Actual: {2} - String '{0}' does not match pattern '{1}'. {2}. - 字符串“{0}”与模式“{1}”不匹配。{2}。 - + String '{0}' does not match pattern '{1}'. {2} + 字符串“{0}”与模式“{1}”不匹配。{2}。 + Expected collection to contain any item but it is empty. {0} @@ -197,9 +209,9 @@ Actual: {2} - String '{0}' matches pattern '{1}'. {2}. - 字符串“{0}”与模式“{1}”匹配。{2}。 - + String '{0}' matches pattern '{1}'. {2} + 字符串“{0}”与模式“{1}”匹配。{2}。 + Assert.Equals should not be used for Assertions. Please use Assert.AreEqual & overloads instead. @@ -212,12 +224,12 @@ Actual: {2} or the member may be private and defined on a base class. If the latter is true, you need to pass the type that defines the member into PrivateObject's constructor. - - 未能找到指定的成员({0})。可能需要重新生成专用访问器, - 或者该成员可能是私有成员并且是在基类上定义的。如果属于后一种情况,则需要将定义 - 该成员的类型传递到 PrivateObject 的构造函数中。 - - + + 未能找到指定的成员({0})。可能需要重新生成专用访问器, + 或者该成员可能是私有成员并且是在基类上定义的。如果属于后一种情况,则需要将定义 + 该成员的类型传递到 PrivateObject 的构造函数中。 + + @@ -225,12 +237,12 @@ Actual: {2} or the member may be private and defined on a base class. If the latter is true, you need to pass the type that defines the member into PrivateObject's constructor. - - 未能找到具有指定签名的构造函数。可能需要重新生成专用访问器, - 或者该成员可能是私有成员并且是在基类上定义的。如果属于后一种情况,则需要将定义 - 该成员的类型传递到 PrivateObject 的构造函数。 - - + + 未能找到具有指定签名的构造函数。可能需要重新生成专用访问器, + 或者该成员可能是私有成员并且是在基类上定义的。如果属于后一种情况,则需要将定义 + 该成员的类型传递到 PrivateObject 的构造函数。 + + The parameter '{0}' is invalid. The value cannot be null. {1}. @@ -243,9 +255,9 @@ Actual: {2} - String '{0}' does not start with string '{1}'. {2}. - 字符串“{0}”没有以字符串“{1}”开头。{2}。 - + String '{0}' does not start with string '{1}'. {2} + 字符串“{0}”没有以字符串“{1}”开头。{2}。 + The property {0} has type {1}; expected type {2}. @@ -339,7 +351,7 @@ Actual: {2} Type '{0}' is not assignable to '{1}'. - 类型“{0}”不能分配给“{1}”。 + 类型“{0}”不能分配给“{1}”。 - {0} argument name like "applicationType" - {1} fully qualified class name like "Microsoft.UI.Xaml.Application" diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf index 1ceae9d222..879cab312e 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf @@ -117,6 +117,16 @@ Expected no items to match the predicate. {0} + + String '{0}' ends with string '{1}'. {2} + String '{0}' ends with string '{1}'. {2} + + + + String '{0}' starts with string '{1}'. {2} + String '{0}' starts with string '{1}'. {2} + + Dynamic data method '{0}' should be static, parameterless and non-generic. 動態資料方法 '{0}' 應為靜態、無參數及非泛型。 @@ -141,9 +151,11 @@ Element at index {0} do not match. Expected: {1} Actual: {2} - 位於索引 {0} 的項目不符。 -預期為: {1} -實際為: {2} + + 位於索引 {0} 的項目不符。 + 預期為: {1} + 實際為: {2} + @@ -152,9 +164,9 @@ Actual: {2} - String '{0}' does not end with string '{1}'. {2}. - 字串 '{0}' 不是以字串 '{1}' 結尾。{2}。 - + String '{0}' does not end with string '{1}'. {2} + 字串 '{0}' 不是以字串 '{1}' 結尾。{2}。 + {0} failed. {1} @@ -182,9 +194,9 @@ Actual: {2} - String '{0}' does not match pattern '{1}'. {2}. - 字串 '{0}' 與模式 '{1}' 不符。{2}。 - + String '{0}' does not match pattern '{1}'. {2} + 字串 '{0}' 與模式 '{1}' 不符。{2}。 + Expected collection to contain any item but it is empty. {0} @@ -197,9 +209,9 @@ Actual: {2} - String '{0}' matches pattern '{1}'. {2}. - 字串 '{0}' 與模式 '{1}' 相符。{2}。 - + String '{0}' matches pattern '{1}'. {2} + 字串 '{0}' 與模式 '{1}' 相符。{2}。 + Assert.Equals should not be used for Assertions. Please use Assert.AreEqual & overloads instead. @@ -212,12 +224,12 @@ Actual: {2} or the member may be private and defined on a base class. If the latter is true, you need to pass the type that defines the member into PrivateObject's constructor. - - 找不到所指定的成員 ({0})。您可能必須重新產生私用存取子, - 或者該成員可能為私用,並且定義在基底類別上。如果是後者, - 您必須將定義該成員的類型傳遞至 PrivateObject 的建構函式。 - - + + 找不到所指定的成員 ({0})。您可能必須重新產生私用存取子, + 或者該成員可能為私用,並且定義在基底類別上。如果是後者, + 您必須將定義該成員的類型傳遞至 PrivateObject 的建構函式。 + + @@ -225,12 +237,12 @@ Actual: {2} or the member may be private and defined on a base class. If the latter is true, you need to pass the type that defines the member into PrivateObject's constructor. - - 找不到具有所指定簽章的建構函式。您可能必須重新產生私用存取子, - 或者該成員可能為私用,並且定義在基底類別上。如果是後者,您必須 - 將定義該成員的類型傳遞至 PrivateObject 的建構函式。 - - + + 找不到具有所指定簽章的建構函式。您可能必須重新產生私用存取子, + 或者該成員可能為私用,並且定義在基底類別上。如果是後者,您必須 + 將定義該成員的類型傳遞至 PrivateObject 的建構函式。 + + The parameter '{0}' is invalid. The value cannot be null. {1}. @@ -243,9 +255,9 @@ Actual: {2} - String '{0}' does not start with string '{1}'. {2}. - 字串 '{0}' 不是以字串 '{1}' 開頭。{2}。 - + String '{0}' does not start with string '{1}'. {2} + 字串 '{0}' 不是以字串 '{1}' 開頭。{2}。 + The property {0} has type {1}; expected type {2}. @@ -339,7 +351,7 @@ Actual: {2} Type '{0}' is not assignable to '{1}'. - 無法將類型 '{0}' {0} 指派給 '{1}。 + 無法將類型 '{0}' {0} 指派給 '{1}。 - {0} argument name like "applicationType" - {1} fully qualified class name like "Microsoft.UI.Xaml.Application" From 423c1db0802d8ea136b8a8c1b7c9a0f248465c95 Mon Sep 17 00:00:00 2001 From: dotnet bot Date: Thu, 19 Jun 2025 10:57:05 +0200 Subject: [PATCH 120/541] Localized file check-in by OneLocBuild Task: Build definition ID 1218: Build ID 2733459 --- .../Resources/xlf/FrameworkMessages.cs.xlf | 38 +++++++++---------- .../Resources/xlf/FrameworkMessages.de.xlf | 14 +++---- .../Resources/xlf/FrameworkMessages.es.xlf | 38 +++++++++---------- .../Resources/xlf/FrameworkMessages.fr.xlf | 38 +++++++++---------- .../Resources/xlf/FrameworkMessages.it.xlf | 38 +++++++++---------- .../Resources/xlf/FrameworkMessages.ja.xlf | 38 +++++++++---------- .../Resources/xlf/FrameworkMessages.ko.xlf | 38 +++++++++---------- .../Resources/xlf/FrameworkMessages.pl.xlf | 38 +++++++++---------- .../Resources/xlf/FrameworkMessages.pt-BR.xlf | 38 +++++++++---------- .../Resources/xlf/FrameworkMessages.ru.xlf | 38 +++++++++---------- .../Resources/xlf/FrameworkMessages.tr.xlf | 38 +++++++++---------- .../xlf/FrameworkMessages.zh-Hans.xlf | 38 +++++++++---------- .../xlf/FrameworkMessages.zh-Hant.xlf | 38 +++++++++---------- 13 files changed, 223 insertions(+), 247 deletions(-) diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.cs.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.cs.xlf index 30903b4759..54e36414d1 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.cs.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.cs.xlf @@ -151,11 +151,9 @@ Element at index {0} do not match. Expected: {1} Actual: {2} - - Element v indexu {0} nesouhlasí. - Očekáváno: {1} - Skutečnost: {2} - + Element v indexu {0} nesouhlasí. +Očekáváno: {1} +Skutečnost: {2} @@ -165,7 +163,7 @@ Actual: {2} String '{0}' does not end with string '{1}'. {2} - Řetězec '{0}' nekončí řetězcem '{1}'. {2}. + String '{0}' does not end with string '{1}'. {2} @@ -195,7 +193,7 @@ Actual: {2} String '{0}' does not match pattern '{1}'. {2} - Řetězec '{0}' neodpovídá vzoru '{1}'. {2}. + String '{0}' does not match pattern '{1}'. {2} @@ -210,7 +208,7 @@ Actual: {2} String '{0}' matches pattern '{1}'. {2} - Řetězec '{0}' odpovídá vzoru '{1}'. {2}. + String '{0}' matches pattern '{1}'. {2} @@ -224,11 +222,11 @@ Actual: {2} or the member may be private and defined on a base class. If the latter is true, you need to pass the type that defines the member into PrivateObject's constructor. - - Zadaný člen ({0}) nemohl být nalezen. Je možné, že bude zapotřebí obnovit soukromý přístupový objekt, - nebo může být člen soukromý a definovaný v základní třídě. Pokud je tvrzení pravdivé, bude zapotřebí předat typ - , který definuje člena do konstruktoru PrivateObject. - + + Zadaný člen ({0}) nemohl být nalezen. Je možné, že bude zapotřebí obnovit soukromý přístupový objekt, + nebo může být člen soukromý a definovaný v základní třídě. Pokud je tvrzení pravdivé, bude zapotřebí předat typ + , který definuje člena do konstruktoru PrivateObject. + @@ -237,11 +235,11 @@ Actual: {2} or the member may be private and defined on a base class. If the latter is true, you need to pass the type that defines the member into PrivateObject's constructor. - - Konstruktor se zadaným podpisem se nepovedlo najít. Je možné, že bude zapotřebí obnovit soukromý přistupující objekt, - nebo může být člen soukromý a definovaný v základní třídě. Pokud je tvrzení pravdivé, bude zapotřebí předat typ - , který definuje člena do konstruktoru PrivateObject. - + + Konstruktor se zadaným podpisem se nepovedlo najít. Je možné, že bude zapotřebí obnovit soukromý přistupující objekt, + nebo může být člen soukromý a definovaný v základní třídě. Pokud je tvrzení pravdivé, bude zapotřebí předat typ + , který definuje člena do konstruktoru PrivateObject. + @@ -256,7 +254,7 @@ Actual: {2} String '{0}' does not start with string '{1}'. {2} - Řetězec '{0}' nezačíná řetězcem '{1}'. {2}. + String '{0}' does not start with string '{1}'. {2} @@ -351,7 +349,7 @@ Actual: {2} Type '{0}' is not assignable to '{1}'. - Typ „{0}“ nelze přiřadit k „{1}“. + Typ „{0}“ nelze přiřadit k „{1}“. - {0} argument name like "applicationType" - {1} fully qualified class name like "Microsoft.UI.Xaml.Application" diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.de.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.de.xlf index 3512ca0350..f5cf712cfc 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.de.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.de.xlf @@ -163,7 +163,7 @@ Tatsächlich: {2} String '{0}' does not end with string '{1}'. {2} - Die Zeichenfolge "{0}" endet nicht auf die Zeichenfolge "{1}". {2}. + String '{0}' does not end with string '{1}'. {2} @@ -193,7 +193,7 @@ Tatsächlich: {2} String '{0}' does not match pattern '{1}'. {2} - Die Zeichenfolge "{0}" stimmt nicht mit dem Muster "{1}" überein. {2}. + String '{0}' does not match pattern '{1}'. {2} @@ -208,7 +208,7 @@ Tatsächlich: {2} String '{0}' matches pattern '{1}'. {2} - Die Zeichenfolge "{0}" stimmt mit dem Muster "{1}" überein. {2}. + String '{0}' matches pattern '{1}'. {2} @@ -227,7 +227,7 @@ Tatsächlich: {2} oder der Member ist möglicherweise privat und für die Basisklasse definiert. Wenn letzteres zutrifft, müssen Sie den Typ, der den Member definiert, an den Konstruktor von PrivateObject übergeben. - + @@ -240,7 +240,7 @@ Tatsächlich: {2} oder der Member ist möglicherweise privat und für die Basisklasse definiert. Wenn letzteres zutrifft, müssen Sie den Typ, der den Member definiert, an den Konstruktor von PrivateObject übergeben. - + The parameter '{0}' is invalid. The value cannot be null. {1}. @@ -254,7 +254,7 @@ Tatsächlich: {2} String '{0}' does not start with string '{1}'. {2} - Die Zeichenfolge "{0}" beginnt nicht mit der Zeichenfolge "{1}". {2}. + String '{0}' does not start with string '{1}'. {2} @@ -387,4 +387,4 @@ Tatsächlich: {2} - + \ No newline at end of file diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.es.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.es.xlf index 89579a0d64..736ca9b71e 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.es.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.es.xlf @@ -151,11 +151,9 @@ Element at index {0} do not match. Expected: {1} Actual: {2} - - El elemento del índice {0} no coincide. - Esperado: {1} - Real: {2} - + El elemento del índice {0} no coincide. +Esperado: {1} +Real: {2} @@ -165,7 +163,7 @@ Actual: {2} String '{0}' does not end with string '{1}'. {2} - La cadena '{0}' no termina con la cadena '{1}'. {2}. + String '{0}' does not end with string '{1}'. {2} @@ -195,7 +193,7 @@ Actual: {2} String '{0}' does not match pattern '{1}'. {2} - La cadena '{0}' no coincide con el patrón '{1}'. {2}. + String '{0}' does not match pattern '{1}'. {2} @@ -210,7 +208,7 @@ Actual: {2} String '{0}' matches pattern '{1}'. {2} - La cadena '{0}' coincide con el patrón '{1}'. {2}. + String '{0}' matches pattern '{1}'. {2} @@ -224,11 +222,11 @@ Actual: {2} or the member may be private and defined on a base class. If the latter is true, you need to pass the type that defines the member into PrivateObject's constructor. - - No se encontró el miembro especificado ({0}). Es posible que tenga que volver a generar el descriptor de acceso privado, - o que el miembro sea privado y esté definido en una clase base. Si esto último es cierto, debe pasar el tipo - que define el miembro al constructor de PrivateObject. - + + No se encontró el miembro especificado ({0}). Es posible que tenga que volver a generar el descriptor de acceso privado, + o que el miembro sea privado y esté definido en una clase base. Si esto último es cierto, debe pasar el tipo + que define el miembro al constructor de PrivateObject. + @@ -237,11 +235,11 @@ Actual: {2} or the member may be private and defined on a base class. If the latter is true, you need to pass the type that defines the member into PrivateObject's constructor. - - No se encontró el constructor con la signatura especificada. Es posible que tenga que volver a generar el descriptor de acceso privado, - o que el miembro sea privado y esté definido en una clase base. Si esto último es cierto, debe pasar el tipo - que define el miembro al constructor de PrivateObject. - + + No se encontró el constructor con la signatura especificada. Es posible que tenga que volver a generar el descriptor de acceso privado, + o que el miembro sea privado y esté definido en una clase base. Si esto último es cierto, debe pasar el tipo + que define el miembro al constructor de PrivateObject. + @@ -256,7 +254,7 @@ Actual: {2} String '{0}' does not start with string '{1}'. {2} - La cadena '{0}' no empieza con la cadena '{1}'. {2}. + String '{0}' does not start with string '{1}'. {2} @@ -351,7 +349,7 @@ Actual: {2} Type '{0}' is not assignable to '{1}'. - Tipo "{0}" no se puede asignar a "{1}". + Tipo "{0}" no se puede asignar a "{1}". - {0} argument name like "applicationType" - {1} fully qualified class name like "Microsoft.UI.Xaml.Application" diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.fr.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.fr.xlf index 4ea1be6613..3f776be2de 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.fr.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.fr.xlf @@ -151,11 +151,9 @@ Element at index {0} do not match. Expected: {1} Actual: {2} - - L’élément au {0} d’index ne correspond pas. - Attendu : {1} - Réel : {2} - + L’élément au {0} d’index ne correspond pas. +Attendu : {1} +Réel : {2} @@ -165,7 +163,7 @@ Actual: {2} String '{0}' does not end with string '{1}'. {2} - La chaîne '{0}' ne se termine pas par la chaîne '{1}'. {2}. + String '{0}' does not end with string '{1}'. {2} @@ -195,7 +193,7 @@ Actual: {2} String '{0}' does not match pattern '{1}'. {2} - La chaîne '{0}' ne correspond pas au modèle '{1}'. {2}. + String '{0}' does not match pattern '{1}'. {2} @@ -210,7 +208,7 @@ Actual: {2} String '{0}' matches pattern '{1}'. {2} - La chaîne '{0}' correspond au modèle '{1}'. {2}. + String '{0}' matches pattern '{1}'. {2} @@ -224,11 +222,11 @@ Actual: {2} or the member may be private and defined on a base class. If the latter is true, you need to pass the type that defines the member into PrivateObject's constructor. - - Le membre spécifié ({0}) est introuvable. Vous devrez peut-être régénérer votre accesseur private, - ou le membre est peut-être private et défini sur une classe de base. Si le dernier cas est vrai, vous devez transmettre le type - qui définit le membre dans le constructeur de PrivateObject. - + + Le membre spécifié ({0}) est introuvable. Vous devrez peut-être régénérer votre accesseur private, + ou le membre est peut-être private et défini sur une classe de base. Si le dernier cas est vrai, vous devez transmettre le type + qui définit le membre dans le constructeur de PrivateObject. + @@ -237,11 +235,11 @@ Actual: {2} or the member may be private and defined on a base class. If the latter is true, you need to pass the type that defines the member into PrivateObject's constructor. - - Le constructeur doté de la signature spécifiée est introuvable. Vous devrez peut-être régénérer votre accesseur private, - ou le membre est peut-être private et défini sur une classe de base. Si le dernier cas est vrai, vous devez transmettre le type - qui définit le membre dans le constructeur de PrivateObject. - + + Le constructeur doté de la signature spécifiée est introuvable. Vous devrez peut-être régénérer votre accesseur private, + ou le membre est peut-être private et défini sur une classe de base. Si le dernier cas est vrai, vous devez transmettre le type + qui définit le membre dans le constructeur de PrivateObject. + @@ -256,7 +254,7 @@ Actual: {2} String '{0}' does not start with string '{1}'. {2} - La chaîne '{0}' ne commence pas par la chaîne '{1}'. {2}. + String '{0}' does not start with string '{1}'. {2} @@ -351,7 +349,7 @@ Actual: {2} Type '{0}' is not assignable to '{1}'. - Impossible d'assigner le type '{0}' à '{1}'. + Impossible d'assigner le type '{0}' à '{1}'. - {0} argument name like "applicationType" - {1} fully qualified class name like "Microsoft.UI.Xaml.Application" diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.it.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.it.xlf index c51115a9b6..7512e6c455 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.it.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.it.xlf @@ -151,11 +151,9 @@ Element at index {0} do not match. Expected: {1} Actual: {2} - - L'elemento nell'indice {0} non corrisponde. - Previsto: {1} - Effettivo: {2} - + L'elemento nell'indice {0} non corrisponde. +Previsto: {1} +Effettivo: {2} @@ -165,7 +163,7 @@ Actual: {2} String '{0}' does not end with string '{1}'. {2} - La stringa '{0}' non termina con la stringa '{1}'. {2}. + String '{0}' does not end with string '{1}'. {2} @@ -195,7 +193,7 @@ Actual: {2} String '{0}' does not match pattern '{1}'. {2} - La stringa '{0}' non corrisponde al criterio '{1}'. {2}. + String '{0}' does not match pattern '{1}'. {2} @@ -210,7 +208,7 @@ Actual: {2} String '{0}' matches pattern '{1}'. {2} - La stringa '{0}' corrisponde al criterio '{1}'. {2}. + String '{0}' matches pattern '{1}'. {2} @@ -224,11 +222,11 @@ Actual: {2} or the member may be private and defined on a base class. If the latter is true, you need to pass the type that defines the member into PrivateObject's constructor. - - Il membro specificato ({0}) non è stato trovato. Potrebbe essere necessario rigenerare la funzione di accesso privata - oppure il membro potrebbe essere privato e definito per una classe base. In quest'ultimo caso, è necessario passare il tipo - che definisce il membro nel costruttore di PrivateObject. - + + Il membro specificato ({0}) non è stato trovato. Potrebbe essere necessario rigenerare la funzione di accesso privata + oppure il membro potrebbe essere privato e definito per una classe base. In quest'ultimo caso, è necessario passare il tipo + che definisce il membro nel costruttore di PrivateObject. + @@ -237,11 +235,11 @@ Actual: {2} or the member may be private and defined on a base class. If the latter is true, you need to pass the type that defines the member into PrivateObject's constructor. - - Il costruttore con la firma specificata non è stato trovato. Potrebbe essere necessario rigenerare la funzione di accesso privata - oppure il membro potrebbe essere privato e definito per una classe base. In quest'ultimo caso, è necessario passare il tipo - che definisce il membro nel costruttore di PrivateObject. - + + Il costruttore con la firma specificata non è stato trovato. Potrebbe essere necessario rigenerare la funzione di accesso privata + oppure il membro potrebbe essere privato e definito per una classe base. In quest'ultimo caso, è necessario passare il tipo + che definisce il membro nel costruttore di PrivateObject. + @@ -256,7 +254,7 @@ Actual: {2} String '{0}' does not start with string '{1}'. {2} - La stringa '{0}' non inizia con la stringa '{1}'. {2}. + String '{0}' does not start with string '{1}'. {2} @@ -351,7 +349,7 @@ Actual: {2} Type '{0}' is not assignable to '{1}'. - Il tipo '{0}' non è assegnabile a '{1}'. + Il tipo '{0}' non è assegnabile a '{1}'. - {0} argument name like "applicationType" - {1} fully qualified class name like "Microsoft.UI.Xaml.Application" diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ja.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ja.xlf index 636ffd5361..acc4aabbc2 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ja.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ja.xlf @@ -151,11 +151,9 @@ Element at index {0} do not match. Expected: {1} Actual: {2} - - インデックス {0} の要素が一致しません。 - 予想: {1} - 実際: {2} - + インデックス {0} の要素が一致しません。 +予想: {1} +実際: {2} @@ -165,7 +163,7 @@ Actual: {2} String '{0}' does not end with string '{1}'. {2} - 文字列 '{0}' は文字列 '{1}' で終わりません。{2}。 + String '{0}' does not end with string '{1}'. {2} @@ -195,7 +193,7 @@ Actual: {2} String '{0}' does not match pattern '{1}'. {2} - 文字列 '{0}' はパターン '{1}' と一致しません。{2}。 + String '{0}' does not match pattern '{1}'. {2} @@ -210,7 +208,7 @@ Actual: {2} String '{0}' matches pattern '{1}'. {2} - 文字列 '{0}' はパターン '{1}' と一致します。{2}。 + String '{0}' matches pattern '{1}'. {2} @@ -224,11 +222,11 @@ Actual: {2} or the member may be private and defined on a base class. If the latter is true, you need to pass the type that defines the member into PrivateObject's constructor. - - 指定されたメンバー ({0}) が見つかりませんでした。プライベート アクセサーを再生成しなければならないか、 - またはメンバーがプライベートであり、基底クラスで定義されている可能性があります。後者である場合は、メンバーを - 定義する型を PrivateObject のコンストラクターに渡す必要があります。 - + + 指定されたメンバー ({0}) が見つかりませんでした。プライベート アクセサーを再生成しなければならないか、 + またはメンバーがプライベートであり、基底クラスで定義されている可能性があります。後者である場合は、メンバーを + 定義する型を PrivateObject のコンストラクターに渡す必要があります。 + @@ -237,11 +235,11 @@ Actual: {2} or the member may be private and defined on a base class. If the latter is true, you need to pass the type that defines the member into PrivateObject's constructor. - - 指定されたシグネチャを使用するコンストラクターが見つかりませんでした。プライベート アクセサーを再生成しなければならないか、 - またはメンバーがプライベートであり、基底クラスで定義されている可能性があります。後者である場合は、メンバーを - 定義する型を PrivateObject のコンストラクターに渡す必要があります。 - + + 指定されたシグネチャを使用するコンストラクターが見つかりませんでした。プライベート アクセサーを再生成しなければならないか、 + またはメンバーがプライベートであり、基底クラスで定義されている可能性があります。後者である場合は、メンバーを + 定義する型を PrivateObject のコンストラクターに渡す必要があります。 + @@ -256,7 +254,7 @@ Actual: {2} String '{0}' does not start with string '{1}'. {2} - 文字列 '{0}' は文字列 '{1}' で始まりません。{2}。 + String '{0}' does not start with string '{1}'. {2} @@ -351,7 +349,7 @@ Actual: {2} Type '{0}' is not assignable to '{1}'. - 型 '{0}' を '{1}' に割り当てることはできません。 + 型 '{0}' を '{1}' に割り当てることはできません。 - {0} argument name like "applicationType" - {1} fully qualified class name like "Microsoft.UI.Xaml.Application" diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ko.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ko.xlf index f0c3cb6646..f7b58e03ac 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ko.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ko.xlf @@ -151,11 +151,9 @@ Element at index {0} do not match. Expected: {1} Actual: {2} - - 인덱스 {0}에 있는 요소가 일치하지 않습니다. - 예상: {1} - 실제: {2} - + 인덱스 {0}에 있는 요소가 일치하지 않습니다. +예상: {1} +실제: {2} @@ -165,7 +163,7 @@ Actual: {2} String '{0}' does not end with string '{1}'. {2} - '{0}' 문자열이 '{1}' 문자열로 끝나지 않습니다. {2} + String '{0}' does not end with string '{1}'. {2} @@ -195,7 +193,7 @@ Actual: {2} String '{0}' does not match pattern '{1}'. {2} - '{0}' 문자열이 '{1}' 패턴과 일치하지 않습니다. {2} + String '{0}' does not match pattern '{1}'. {2} @@ -210,7 +208,7 @@ Actual: {2} String '{0}' matches pattern '{1}'. {2} - '{0}' 문자열이 '{1}' 패턴과 일치합니다. {2} + String '{0}' matches pattern '{1}'. {2} @@ -224,11 +222,11 @@ Actual: {2} or the member may be private and defined on a base class. If the latter is true, you need to pass the type that defines the member into PrivateObject's constructor. - - 지정한 멤버({0})를 찾을 수 없습니다. 프라이빗 접근자를 다시 생성해야 할 수 있습니다. - 또는 멤버가 기본 클래스에 정의된 프라이빗 멤버일 수 있습니다. 기본 클래스에 정의된 전용 멤버인 경우에는 이 멤버를 정의하는 형식을 - PrivateObject의 생성자에 전달해야 합니다. - + + 지정한 멤버({0})를 찾을 수 없습니다. 프라이빗 접근자를 다시 생성해야 할 수 있습니다. + 또는 멤버가 기본 클래스에 정의된 프라이빗 멤버일 수 있습니다. 기본 클래스에 정의된 전용 멤버인 경우에는 이 멤버를 정의하는 형식을 + PrivateObject의 생성자에 전달해야 합니다. + @@ -237,11 +235,11 @@ Actual: {2} or the member may be private and defined on a base class. If the latter is true, you need to pass the type that defines the member into PrivateObject's constructor. - - 지정한 서명을 가진 생성자를 찾을 수 없습니다. 프라이빗 접근자를 다시 생성해야 할 수 있습니다. - 또는 멤버가 기본 클래스에 정의된 프라이빗 멤버일 수 있습니다. 기본 클래스에 정의된 전용 멤버인 경우에는 이 멤버를 정의하는 형식을 - PrivateObject의 생성자에 전달해야 합니다. - + + 지정한 서명을 가진 생성자를 찾을 수 없습니다. 프라이빗 접근자를 다시 생성해야 할 수 있습니다. + 또는 멤버가 기본 클래스에 정의된 프라이빗 멤버일 수 있습니다. 기본 클래스에 정의된 전용 멤버인 경우에는 이 멤버를 정의하는 형식을 + PrivateObject의 생성자에 전달해야 합니다. + @@ -256,7 +254,7 @@ Actual: {2} String '{0}' does not start with string '{1}'. {2} - '{0}' 문자열이 '{1}' 문자열로 시작되지 않습니다. {2} + String '{0}' does not start with string '{1}'. {2} @@ -351,7 +349,7 @@ Actual: {2} Type '{0}' is not assignable to '{1}'. - '{0}' 형식은 '{1}'에 할당할 수 없습니다. + '{0}' 형식은 '{1}'에 할당할 수 없습니다. - {0} argument name like "applicationType" - {1} fully qualified class name like "Microsoft.UI.Xaml.Application" diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pl.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pl.xlf index 567fe8cef7..4580302814 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pl.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pl.xlf @@ -151,11 +151,9 @@ Element at index {0} do not match. Expected: {1} Actual: {2} - - Element w indeksie {0} nie jest zgodny. - Oczekiwano: {1} - Rzeczywiste: {2} - + Element w indeksie {0} nie jest zgodny. +Oczekiwano: {1} +Rzeczywiste: {2} @@ -165,7 +163,7 @@ Actual: {2} String '{0}' does not end with string '{1}'. {2} - Ciąg „{0}” nie kończy się ciągiem „{1}”. {2}. + String '{0}' does not end with string '{1}'. {2} @@ -195,7 +193,7 @@ Actual: {2} String '{0}' does not match pattern '{1}'. {2} - Ciąg „{0}” nie jest zgodny ze wzorcem „{1}”. {2}. + String '{0}' does not match pattern '{1}'. {2} @@ -210,7 +208,7 @@ Actual: {2} String '{0}' matches pattern '{1}'. {2} - Ciąg „{0}” jest zgodny ze wzorcem „{1}”. {2}. + String '{0}' matches pattern '{1}'. {2} @@ -224,11 +222,11 @@ Actual: {2} or the member may be private and defined on a base class. If the latter is true, you need to pass the type that defines the member into PrivateObject's constructor. - - Nie można odnaleźć określonej składowej ({0}). Może być konieczne ponowne wygenerowanie prywatnej metody dostępu - lub składowa może być zdefiniowana jako prywatna w klasie bazowej. W drugim przypadku należy przekazać typ, - który definiuje składową w konstruktorze obiektu PrivateObject. - + + Nie można odnaleźć określonej składowej ({0}). Może być konieczne ponowne wygenerowanie prywatnej metody dostępu + lub składowa może być zdefiniowana jako prywatna w klasie bazowej. W drugim przypadku należy przekazać typ, + który definiuje składową w konstruktorze obiektu PrivateObject. + @@ -237,11 +235,11 @@ Actual: {2} or the member may be private and defined on a base class. If the latter is true, you need to pass the type that defines the member into PrivateObject's constructor. - - Nie można odnaleźć konstruktora z określoną sygnaturą. Może być konieczne ponowne wygenerowanie prywatnej metody dostępu - lub składowa może być zdefiniowana jako prywatna w klasie bazowej. W drugim przypadku należy przekazać typ, - który definiuje składową w konstruktorze obiektu PrivateObject. - + + Nie można odnaleźć konstruktora z określoną sygnaturą. Może być konieczne ponowne wygenerowanie prywatnej metody dostępu + lub składowa może być zdefiniowana jako prywatna w klasie bazowej. W drugim przypadku należy przekazać typ, + który definiuje składową w konstruktorze obiektu PrivateObject. + @@ -256,7 +254,7 @@ Actual: {2} String '{0}' does not start with string '{1}'. {2} - Ciąg „{0}” nie rozpoczyna się od ciągu „{1}”. {2}. + String '{0}' does not start with string '{1}'. {2} @@ -351,7 +349,7 @@ Actual: {2} Type '{0}' is not assignable to '{1}'. - Typu „{0}” nie można przypisać do typu „{1}”. + Typu „{0}” nie można przypisać do typu „{1}”. - {0} argument name like "applicationType" - {1} fully qualified class name like "Microsoft.UI.Xaml.Application" diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf index 5e2eb1ad84..57576c57fa 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf @@ -151,11 +151,9 @@ Element at index {0} do not match. Expected: {1} Actual: {2} - - O elemento no índice {0} não corresponde. - Esperado: {1} - Real: {2} - + O elemento no índice {0} não corresponde. +Esperado: {1} +Real: {2} @@ -165,7 +163,7 @@ Actual: {2} String '{0}' does not end with string '{1}'. {2} - A cadeia de caracteres '{0}' não termina com a cadeia de caracteres '{1}'. {2}. + String '{0}' does not end with string '{1}'. {2} @@ -195,7 +193,7 @@ Actual: {2} String '{0}' does not match pattern '{1}'. {2} - A cadeia de caracteres '{0}' não corresponde ao padrão '{1}'. {2}. + String '{0}' does not match pattern '{1}'. {2} @@ -210,7 +208,7 @@ Actual: {2} String '{0}' matches pattern '{1}'. {2} - A cadeia de caracteres '{0}' corresponde ao padrão '{1}'. {2}. + String '{0}' matches pattern '{1}'. {2} @@ -224,11 +222,11 @@ Actual: {2} or the member may be private and defined on a base class. If the latter is true, you need to pass the type that defines the member into PrivateObject's constructor. - - O membro especificado ({0}) não pôde ser encontrado. Talvez seja necessário gerar novamente seu acessador particular - ou o membro pode ser particular e definido em uma classe base. Se o último caso for verdadeiro, será necessário passar o tipo - que define o membro no construtor do PrivateObject. - + + O membro especificado ({0}) não pôde ser encontrado. Talvez seja necessário gerar novamente seu acessador particular + ou o membro pode ser particular e definido em uma classe base. Se o último caso for verdadeiro, será necessário passar o tipo + que define o membro no construtor do PrivateObject. + @@ -237,11 +235,11 @@ Actual: {2} or the member may be private and defined on a base class. If the latter is true, you need to pass the type that defines the member into PrivateObject's constructor. - - O construtor com a assinatura especificada não pôde ser encontrado. Talvez seja necessário gerar novamente seu acessador particular - ou o membro pode ser particular e definido em uma classe base. Se o último caso for verdadeiro, será necessário passar o tipo - que define o membro para o construtor do PrivateObject. - + + O construtor com a assinatura especificada não pôde ser encontrado. Talvez seja necessário gerar novamente seu acessador particular + ou o membro pode ser particular e definido em uma classe base. Se o último caso for verdadeiro, será necessário passar o tipo + que define o membro para o construtor do PrivateObject. + @@ -256,7 +254,7 @@ Actual: {2} String '{0}' does not start with string '{1}'. {2} - A cadeia de caracteres '{0}' não começa com a cadeia de caracteres '{1}'. {2}. + String '{0}' does not start with string '{1}'. {2} @@ -351,7 +349,7 @@ Actual: {2} Type '{0}' is not assignable to '{1}'. - Tipo '{0}' não é atribuível a '{1}'. + Tipo '{0}' não é atribuível a '{1}'. - {0} argument name like "applicationType" - {1} fully qualified class name like "Microsoft.UI.Xaml.Application" diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ru.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ru.xlf index 61bb453d5e..ba7a6f56ad 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ru.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ru.xlf @@ -151,11 +151,9 @@ Element at index {0} do not match. Expected: {1} Actual: {2} - - Элемент по индексу {0} не совпадает. - Ожидается: {1} - Фактическое значение: {2} - + Элемент по индексу {0} не совпадает. +Ожидается: {1} +Фактическое значение: {2} @@ -165,7 +163,7 @@ Actual: {2} String '{0}' does not end with string '{1}'. {2} - Строка "{0}" не оканчивается строкой "{1}". {2}. + String '{0}' does not end with string '{1}'. {2} @@ -195,7 +193,7 @@ Actual: {2} String '{0}' does not match pattern '{1}'. {2} - Строка "{0}" не соответствует шаблону "{1}". {2}. + String '{0}' does not match pattern '{1}'. {2} @@ -210,7 +208,7 @@ Actual: {2} String '{0}' matches pattern '{1}'. {2} - Строка "{0}" соответствует шаблону "{1}". {2}. + String '{0}' matches pattern '{1}'. {2} @@ -224,11 +222,11 @@ Actual: {2} or the member may be private and defined on a base class. If the latter is true, you need to pass the type that defines the member into PrivateObject's constructor. - - Не удается найти указанный член ({0}). Возможно, требуется снова создать закрытый метод доступа - либо член является закрытым и определенным на основе базового класса. Если справедливо последнее, то - необходимо передать тип, определяющий член, в конструктор для PrivateObject. - + + Не удается найти указанный член ({0}). Возможно, требуется снова создать закрытый метод доступа + либо член является закрытым и определенным на основе базового класса. Если справедливо последнее, то + необходимо передать тип, определяющий член, в конструктор для PrivateObject. + @@ -237,11 +235,11 @@ Actual: {2} or the member may be private and defined on a base class. If the latter is true, you need to pass the type that defines the member into PrivateObject's constructor. - - Не удается найти конструктор с указанной сигнатурой. Возможно, требуется снова создать закрытый - метод доступа либо член является закрытым и определенным на основе базового класса. Если - справедливо последнее, то необходимо передать тип, определяющий член, в конструктор для PrivateObject. - + + Не удается найти конструктор с указанной сигнатурой. Возможно, требуется снова создать закрытый + метод доступа либо член является закрытым и определенным на основе базового класса. Если + справедливо последнее, то необходимо передать тип, определяющий член, в конструктор для PrivateObject. + @@ -256,7 +254,7 @@ Actual: {2} String '{0}' does not start with string '{1}'. {2} - Строка "{0}" не начинается со строки "{1}". {2}. + String '{0}' does not start with string '{1}'. {2} @@ -351,7 +349,7 @@ Actual: {2} Type '{0}' is not assignable to '{1}'. - Тип "{0}" не может быть назначен "{1}". + Тип "{0}" не может быть назначен "{1}". - {0} argument name like "applicationType" - {1} fully qualified class name like "Microsoft.UI.Xaml.Application" diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.tr.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.tr.xlf index 9d87a6ac8e..322e8ce049 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.tr.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.tr.xlf @@ -151,11 +151,9 @@ Element at index {0} do not match. Expected: {1} Actual: {2} - - {0} dizinindeki öğe eşleşmiyor. - Beklenen: {1} - Gerçekte olan: {2} - + {0} dizinindeki öğe eşleşmiyor. +Beklenen: {1} +Gerçekte olan: {2} @@ -165,7 +163,7 @@ Actual: {2} String '{0}' does not end with string '{1}'. {2} - '{0}' dizesi, '{1}' dizesi ile sonlanmıyor. {2}. + String '{0}' does not end with string '{1}'. {2} @@ -195,7 +193,7 @@ Actual: {2} String '{0}' does not match pattern '{1}'. {2} - '{0}' dizesi, '{1}' deseni ile eşleşmiyor. {2}. + String '{0}' does not match pattern '{1}'. {2} @@ -210,7 +208,7 @@ Actual: {2} String '{0}' matches pattern '{1}'. {2} - '{0}' dizesi, '{1}' deseni ile eşleşiyor. {2}. + String '{0}' matches pattern '{1}'. {2} @@ -224,11 +222,11 @@ Actual: {2} or the member may be private and defined on a base class. If the latter is true, you need to pass the type that defines the member into PrivateObject's constructor. - - Belirtilen üye ({0}) bulunamadı. Özel erişimcinizi yeniden oluşturmanız gerekiyor olabilir - veya üye, özel olabilir ve temel sınıfta tanımlı olabilir. Eğer ikincisi doğru ise, türü geçirmeniz gerekir; - bu tür PrivateObject'in oluşturucusunda üyeyi tanımlar. - + + Belirtilen üye ({0}) bulunamadı. Özel erişimcinizi yeniden oluşturmanız gerekiyor olabilir + veya üye, özel olabilir ve temel sınıfta tanımlı olabilir. Eğer ikincisi doğru ise, türü geçirmeniz gerekir; + bu tür PrivateObject'in oluşturucusunda üyeyi tanımlar. + @@ -237,11 +235,11 @@ Actual: {2} or the member may be private and defined on a base class. If the latter is true, you need to pass the type that defines the member into PrivateObject's constructor. - - Belirtilmiş imzaya sahip oluşturucu bulunamadı. Özel erişimcinizi yeniden oluşturmanız gerekiyor olabilir - veya üye, özel olabilir ve temel sınıfta tanımlı olabilir. Eğer ikincisi doğru ise, türü geçirmeniz gerekir; - bu tür, PrivateObject'in oluşturucusunda üyeyi tanımlar. - + + Belirtilmiş imzaya sahip oluşturucu bulunamadı. Özel erişimcinizi yeniden oluşturmanız gerekiyor olabilir + veya üye, özel olabilir ve temel sınıfta tanımlı olabilir. Eğer ikincisi doğru ise, türü geçirmeniz gerekir; + bu tür, PrivateObject'in oluşturucusunda üyeyi tanımlar. + @@ -256,7 +254,7 @@ Actual: {2} String '{0}' does not start with string '{1}'. {2} - '{0}' dizesi, '{1}' dizesi ile başlamıyor. {2}. + String '{0}' does not start with string '{1}'. {2} @@ -351,7 +349,7 @@ Actual: {2} Type '{0}' is not assignable to '{1}'. - '{0}' tipi '{1}'ye atanamaz. + '{0}' tipi '{1}'ye atanamaz. - {0} argument name like "applicationType" - {1} fully qualified class name like "Microsoft.UI.Xaml.Application" diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf index 762c39d9f2..b68cc27c7d 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf @@ -151,11 +151,9 @@ Element at index {0} do not match. Expected: {1} Actual: {2} - - 索引 {0} 处的元素不匹配。 - 预计值: {1} - 实际值: {2} - + 索引 {0} 处的元素不匹配。 +预计值: {1} +实际值: {2} @@ -165,7 +163,7 @@ Actual: {2} String '{0}' does not end with string '{1}'. {2} - 字符串“{0}”不以字符串“{1}”结尾。{2}。 + String '{0}' does not end with string '{1}'. {2} @@ -195,7 +193,7 @@ Actual: {2} String '{0}' does not match pattern '{1}'. {2} - 字符串“{0}”与模式“{1}”不匹配。{2}。 + String '{0}' does not match pattern '{1}'. {2} @@ -210,7 +208,7 @@ Actual: {2} String '{0}' matches pattern '{1}'. {2} - 字符串“{0}”与模式“{1}”匹配。{2}。 + String '{0}' matches pattern '{1}'. {2} @@ -224,11 +222,11 @@ Actual: {2} or the member may be private and defined on a base class. If the latter is true, you need to pass the type that defines the member into PrivateObject's constructor. - - 未能找到指定的成员({0})。可能需要重新生成专用访问器, - 或者该成员可能是私有成员并且是在基类上定义的。如果属于后一种情况,则需要将定义 - 该成员的类型传递到 PrivateObject 的构造函数中。 - + + 未能找到指定的成员({0})。可能需要重新生成专用访问器, + 或者该成员可能是私有成员并且是在基类上定义的。如果属于后一种情况,则需要将定义 + 该成员的类型传递到 PrivateObject 的构造函数中。 + @@ -237,11 +235,11 @@ Actual: {2} or the member may be private and defined on a base class. If the latter is true, you need to pass the type that defines the member into PrivateObject's constructor. - - 未能找到具有指定签名的构造函数。可能需要重新生成专用访问器, - 或者该成员可能是私有成员并且是在基类上定义的。如果属于后一种情况,则需要将定义 - 该成员的类型传递到 PrivateObject 的构造函数。 - + + 未能找到具有指定签名的构造函数。可能需要重新生成专用访问器, + 或者该成员可能是私有成员并且是在基类上定义的。如果属于后一种情况,则需要将定义 + 该成员的类型传递到 PrivateObject 的构造函数。 + @@ -256,7 +254,7 @@ Actual: {2} String '{0}' does not start with string '{1}'. {2} - 字符串“{0}”没有以字符串“{1}”开头。{2}。 + String '{0}' does not start with string '{1}'. {2} @@ -351,7 +349,7 @@ Actual: {2} Type '{0}' is not assignable to '{1}'. - 类型“{0}”不能分配给“{1}”。 + 类型“{0}”不能分配给“{1}”。 - {0} argument name like "applicationType" - {1} fully qualified class name like "Microsoft.UI.Xaml.Application" diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf index 879cab312e..804e8b106f 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf @@ -151,11 +151,9 @@ Element at index {0} do not match. Expected: {1} Actual: {2} - - 位於索引 {0} 的項目不符。 - 預期為: {1} - 實際為: {2} - + 位於索引 {0} 的項目不符。 +預期為: {1} +實際為: {2} @@ -165,7 +163,7 @@ Actual: {2} String '{0}' does not end with string '{1}'. {2} - 字串 '{0}' 不是以字串 '{1}' 結尾。{2}。 + String '{0}' does not end with string '{1}'. {2} @@ -195,7 +193,7 @@ Actual: {2} String '{0}' does not match pattern '{1}'. {2} - 字串 '{0}' 與模式 '{1}' 不符。{2}。 + String '{0}' does not match pattern '{1}'. {2} @@ -210,7 +208,7 @@ Actual: {2} String '{0}' matches pattern '{1}'. {2} - 字串 '{0}' 與模式 '{1}' 相符。{2}。 + String '{0}' matches pattern '{1}'. {2} @@ -224,11 +222,11 @@ Actual: {2} or the member may be private and defined on a base class. If the latter is true, you need to pass the type that defines the member into PrivateObject's constructor. - - 找不到所指定的成員 ({0})。您可能必須重新產生私用存取子, - 或者該成員可能為私用,並且定義在基底類別上。如果是後者, - 您必須將定義該成員的類型傳遞至 PrivateObject 的建構函式。 - + + 找不到所指定的成員 ({0})。您可能必須重新產生私用存取子, + 或者該成員可能為私用,並且定義在基底類別上。如果是後者, + 您必須將定義該成員的類型傳遞至 PrivateObject 的建構函式。 + @@ -237,11 +235,11 @@ Actual: {2} or the member may be private and defined on a base class. If the latter is true, you need to pass the type that defines the member into PrivateObject's constructor. - - 找不到具有所指定簽章的建構函式。您可能必須重新產生私用存取子, - 或者該成員可能為私用,並且定義在基底類別上。如果是後者,您必須 - 將定義該成員的類型傳遞至 PrivateObject 的建構函式。 - + + 找不到具有所指定簽章的建構函式。您可能必須重新產生私用存取子, + 或者該成員可能為私用,並且定義在基底類別上。如果是後者,您必須 + 將定義該成員的類型傳遞至 PrivateObject 的建構函式。 + @@ -256,7 +254,7 @@ Actual: {2} String '{0}' does not start with string '{1}'. {2} - 字串 '{0}' 不是以字串 '{1}' 開頭。{2}。 + String '{0}' does not start with string '{1}'. {2} @@ -351,7 +349,7 @@ Actual: {2} Type '{0}' is not assignable to '{1}'. - 無法將類型 '{0}' {0} 指派給 '{1}。 + 無法將類型 '{0}' {0} 指派給 '{1}。 - {0} argument name like "applicationType" - {1} fully qualified class name like "Microsoft.UI.Xaml.Application" From 77a45835ec047311ba1cc38748aaae7c963fa016 Mon Sep 17 00:00:00 2001 From: Copilot <198982749+Copilot@users.noreply.github.com> Date: Thu, 19 Jun 2025 09:50:48 +0000 Subject: [PATCH 121/541] Obsolete Assert.Equals and add obsolete Assert.ReferenceEquals (#5815) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: Evangelink <11340282+Evangelink@users.noreply.github.com> Co-authored-by: Amaury Levé --- .../Assertions/Assert.AreSame.cs | 4 +- .../TestFramework/Assertions/Assert.cs | 41 +++++++++++-- .../Assertions/CollectionAssert.cs | 60 +++++++++++++++++-- .../TestFramework/Assertions/StringAssert.cs | 50 ++++++++++++++++ .../TestFramework/FrameworkConstants.cs | 6 ++ .../PublicAPI/PublicAPI.Unshipped.txt | 5 ++ .../Resources/FrameworkMessages.Designer.cs | 45 ++++++++++++++ .../Resources/FrameworkMessages.resx | 21 ++++++- .../Resources/xlf/FrameworkMessages.cs.xlf | 35 +++++++++-- .../Resources/xlf/FrameworkMessages.de.xlf | 35 +++++++++-- .../Resources/xlf/FrameworkMessages.es.xlf | 35 +++++++++-- .../Resources/xlf/FrameworkMessages.fr.xlf | 35 +++++++++-- .../Resources/xlf/FrameworkMessages.it.xlf | 35 +++++++++-- .../Resources/xlf/FrameworkMessages.ja.xlf | 35 +++++++++-- .../Resources/xlf/FrameworkMessages.ko.xlf | 35 +++++++++-- .../Resources/xlf/FrameworkMessages.pl.xlf | 35 +++++++++-- .../Resources/xlf/FrameworkMessages.pt-BR.xlf | 35 +++++++++-- .../Resources/xlf/FrameworkMessages.ru.xlf | 35 +++++++++-- .../Resources/xlf/FrameworkMessages.tr.xlf | 35 +++++++++-- .../xlf/FrameworkMessages.zh-Hans.xlf | 35 +++++++++-- .../xlf/FrameworkMessages.zh-Hant.xlf | 35 +++++++++-- .../Assertions/AssertTests.cs | 23 +++++++ .../Assertions/CollectionAssertTests.cs | 23 +++++++ .../Assertions/StringAssertTests.cs | 23 +++++++ 24 files changed, 675 insertions(+), 81 deletions(-) diff --git a/src/TestFramework/TestFramework/Assertions/Assert.AreSame.cs b/src/TestFramework/TestFramework/Assertions/Assert.AreSame.cs index 5a80a9b523..61d0a6700d 100644 --- a/src/TestFramework/TestFramework/Assertions/Assert.AreSame.cs +++ b/src/TestFramework/TestFramework/Assertions/Assert.AreSame.cs @@ -220,7 +220,7 @@ public static void AreSame(T? expected, T? actual, [StringSyntax(StringSyntax } private static bool IsAreSameFailing(T? expected, T? actual) - => !ReferenceEquals(expected, actual); + => !object.ReferenceEquals(expected, actual); [DoesNotReturn] private static void ThrowAssertAreSameFailed(T? expected, T? actual, string userMessage) @@ -325,7 +325,7 @@ public static void AreNotSame(T? notExpected, T? actual, [StringSyntax(String } private static bool IsAreNotSameFailing(T? notExpected, T? actual) - => ReferenceEquals(notExpected, actual); + => object.ReferenceEquals(notExpected, actual); [DoesNotReturn] private static void ThrowAssertAreNotSameFailed(string userMessage) diff --git a/src/TestFramework/TestFramework/Assertions/Assert.cs b/src/TestFramework/TestFramework/Assertions/Assert.cs index 978b77b856..134c3fc841 100644 --- a/src/TestFramework/TestFramework/Assertions/Assert.cs +++ b/src/TestFramework/TestFramework/Assertions/Assert.cs @@ -155,24 +155,53 @@ private static int CompareInternal(string? expected, string? actual, bool ignore => string.Compare(expected, actual, ignoreCase, culture); #pragma warning restore CA1309 // Use ordinal string comparison - #region EqualsAssertion + #region DoNotUse /// /// Static equals overloads are used for comparing instances of two types for reference /// equality. This method should not be used for comparison of two instances for - /// equality. This object will always throw with Assert.Fail. Please use - /// Assert.AreEqual and associated overloads in your unit tests. + /// equality. Please use Assert.AreEqual and associated overloads in your unit tests. /// /// Object A. /// Object B. - /// False, always. + /// Never returns. [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "obj", Justification = "We want to compare 'object A' with 'object B', so it makes sense to have 'obj' in the parameter name")] -#pragma warning disable IDE0060 // Remove unused parameter + [Obsolete( + FrameworkConstants.DoNotUseAssertEquals, +#if DEBUG + error: false)] +#else + error: true)] +#endif + [DoesNotReturn] public static new bool Equals(object? objA, object? objB) -#pragma warning restore IDE0060 // Remove unused parameter { Fail(FrameworkMessages.DoNotUseAssertEquals); return false; } + + /// + /// Static ReferenceEquals overloads are used for comparing instances of two types for reference + /// equality. This method should not be used for comparison of two instances for + /// reference equality. Please use Assert.AreSame and associated overloads in your unit tests. + /// + /// Object A. + /// Object B. + /// Never returns. + [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "obj", Justification = "We want to compare 'object A' with 'object B', so it makes sense to have 'obj' in the parameter name")] + [Obsolete( + FrameworkConstants.DoNotUseAssertReferenceEquals, +#if DEBUG + error: false)] +#else + error: true)] +#endif + [DoesNotReturn] + public static new bool ReferenceEquals(object? objA, object? objB) + { + Fail(FrameworkMessages.DoNotUseAssertReferenceEquals); + return false; + } + #endregion } diff --git a/src/TestFramework/TestFramework/Assertions/CollectionAssert.cs b/src/TestFramework/TestFramework/Assertions/CollectionAssert.cs index 35fd6945bb..8ce10cef9b 100644 --- a/src/TestFramework/TestFramework/Assertions/CollectionAssert.cs +++ b/src/TestFramework/TestFramework/Assertions/CollectionAssert.cs @@ -115,7 +115,7 @@ public static void Contains([NotNull] ICollection? collection, object? element, foreach (object? current in collection) { - if (Equals(current, element)) + if (object.Equals(current, element)) { return; } @@ -192,7 +192,7 @@ public static void DoesNotContain([NotNull] ICollection? collection, object? ele foreach (object? current in collection) { - if (Equals(current, element)) + if (object.Equals(current, element)) { Assert.ThrowAssertFailed("CollectionAssert.DoesNotContain", Assert.BuildUserMessage(message, parameters)); } @@ -707,7 +707,7 @@ public static void AreEquivalent( } // If the references are the same or both collections are null, they are equivalent. - if (ReferenceEquals(expected, actual) || expected == null) + if (object.ReferenceEquals(expected, actual) || expected == null) { return; } @@ -942,7 +942,7 @@ public static void AreNotEquivalent( // If the references are the same or both collections are null, they // are equivalent. object.ReferenceEquals will handle case where both are null. - if (ReferenceEquals(expected, actual)) + if (object.ReferenceEquals(expected, actual)) { string userMessage = Assert.BuildUserMessage(message, parameters); string finalMessage = string.Format( @@ -1614,7 +1614,7 @@ private static bool AreCollectionsEqual(ICollection? expected, ICollection? actu ref string reason) { Assert.CheckParameterNotNull(comparer, "Assert.AreCollectionsEqual", "comparer", string.Empty); - if (ReferenceEquals(expected, actual)) + if (object.ReferenceEquals(expected, actual)) { reason = string.Format(CultureInfo.CurrentCulture, FrameworkMessages.BothCollectionsSameReference, string.Empty); return true; @@ -1701,4 +1701,54 @@ private sealed class ObjectComparer : IComparer int IComparer.Compare(object? x, object? y) => Equals(x, y) ? 0 : -1; } #endregion + + #region DoNotUse + + /// + /// Static equals overloads are used for comparing instances of two types for equality. + /// This method should not be used for comparison of two instances for equality. + /// Please use CollectionAssert.AreEqual and associated overloads in your unit tests. + /// + /// Object A. + /// Object B. + /// Never returns. + [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "obj", Justification = "We want to compare 'object A' with 'object B', so it makes sense to have 'obj' in the parameter name")] + [Obsolete( + FrameworkConstants.DoNotUseCollectionAssertEquals, +#if DEBUG + error: false)] +#else + error: true)] +#endif + [DoesNotReturn] + public static new bool Equals(object? objA, object? objB) + { + Assert.Fail(FrameworkMessages.DoNotUseCollectionAssertEquals); + return false; + } + + /// + /// Static ReferenceEquals overloads are used for comparing instances of two types for reference + /// equality. This method should not be used for comparison of two instances for + /// reference equality. Please use CollectionAssert methods or Assert.AreSame and associated overloads in your unit tests. + /// + /// Object A. + /// Object B. + /// Never returns. + [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "obj", Justification = "We want to compare 'object A' with 'object B', so it makes sense to have 'obj' in the parameter name")] + [Obsolete( + FrameworkConstants.DoNotUseCollectionAssertReferenceEquals, +#if DEBUG + error: false)] +#else + error: true)] +#endif + [DoesNotReturn] + public static new bool ReferenceEquals(object? objA, object? objB) + { + Assert.Fail(FrameworkMessages.DoNotUseCollectionAssertReferenceEquals); + return false; + } + + #endregion } diff --git a/src/TestFramework/TestFramework/Assertions/StringAssert.cs b/src/TestFramework/TestFramework/Assertions/StringAssert.cs index bd9d3ab16c..c5fce3a403 100644 --- a/src/TestFramework/TestFramework/Assertions/StringAssert.cs +++ b/src/TestFramework/TestFramework/Assertions/StringAssert.cs @@ -673,4 +673,54 @@ public static void DoesNotMatch([NotNull] string? value, [NotNull] Regex? patter } #endregion Regular Expressions + + #region DoNotUse + + /// + /// Static equals overloads are used for comparing instances of two types for equality. + /// This method should not be used for comparison of two instances for equality. + /// Please use StringAssert methods or Assert.AreEqual and associated overloads in your unit tests. + /// + /// Object A. + /// Object B. + /// Never returns. + [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "obj", Justification = "We want to compare 'object A' with 'object B', so it makes sense to have 'obj' in the parameter name")] + [Obsolete( + FrameworkConstants.DoNotUseStringAssertEquals, +#if DEBUG + error: false)] +#else + error: true)] +#endif + [DoesNotReturn] + public static new bool Equals(object? objA, object? objB) + { + Assert.Fail(FrameworkMessages.DoNotUseStringAssertEquals); + return false; + } + + /// + /// Static ReferenceEquals overloads are used for comparing instances of two types for reference + /// equality. This method should not be used for comparison of two instances for + /// reference equality. Please use StringAssert methods or Assert.AreSame and associated overloads in your unit tests. + /// + /// Object A. + /// Object B. + /// Never returns. + [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "obj", Justification = "We want to compare 'object A' with 'object B', so it makes sense to have 'obj' in the parameter name")] + [Obsolete( + FrameworkConstants.DoNotUseStringAssertReferenceEquals, +#if DEBUG + error: false)] +#else + error: true)] +#endif + [DoesNotReturn] + public static new bool ReferenceEquals(object? objA, object? objB) + { + Assert.Fail(FrameworkMessages.DoNotUseStringAssertReferenceEquals); + return false; + } + + #endregion } diff --git a/src/TestFramework/TestFramework/FrameworkConstants.cs b/src/TestFramework/TestFramework/FrameworkConstants.cs index a26c0a058f..856f2f948c 100644 --- a/src/TestFramework/TestFramework/FrameworkConstants.cs +++ b/src/TestFramework/TestFramework/FrameworkConstants.cs @@ -10,4 +10,10 @@ internal static class FrameworkConstants { internal const string PublicTypeObsoleteMessage = "We will remove or hide this type starting with v4. If you are using this type, reach out to our team on https://github.com/microsoft/testfx."; internal const string ThatPropertyObsoleteMessage = "The 'That' property is obsolete and will be removed in a future version. Use the 'Instance' property instead."; + internal const string DoNotUseAssertEquals = "Assert.Equals should not be used for Assertions. Please use Assert.AreEqual & overloads instead."; + internal const string DoNotUseAssertReferenceEquals = "Assert.ReferenceEquals should not be used for Assertions. Please use Assert.AreSame & overloads instead."; + internal const string DoNotUseStringAssertEquals = "StringAssert.Equals should not be used for Assertions. Please use StringAssert methods or Assert.AreEqual & overloads instead."; + internal const string DoNotUseStringAssertReferenceEquals = "StringAssert.ReferenceEquals should not be used for Assertions. Please use StringAssert methods or Assert.AreSame & overloads instead."; + internal const string DoNotUseCollectionAssertEquals = "CollectionAssert.Equals should not be used for Assertions. Please use CollectionAssert.AreEqual & overloads instead."; + internal const string DoNotUseCollectionAssertReferenceEquals = "CollectionAssert.ReferenceEquals should not be used for Assertions. Please use CollectionAssert methods or Assert.AreSame & overloads instead."; } diff --git a/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Unshipped.txt b/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Unshipped.txt index 92c6805d6b..6c8d629e1f 100644 --- a/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Unshipped.txt +++ b/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Unshipped.txt @@ -67,3 +67,8 @@ static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.Throws(Sy static Microsoft.VisualStudio.TestTools.UnitTesting.CollectionAssert.Instance.get -> Microsoft.VisualStudio.TestTools.UnitTesting.CollectionAssert! static Microsoft.VisualStudio.TestTools.UnitTesting.StringAssert.Instance.get -> Microsoft.VisualStudio.TestTools.UnitTesting.StringAssert! *REMOVED*static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.Contains(System.Collections.Generic.IEnumerable! collection, System.Func! predicate, string? message) -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.ReferenceEquals(object? objA, object? objB) -> bool +static Microsoft.VisualStudio.TestTools.UnitTesting.CollectionAssert.Equals(object? objA, object? objB) -> bool +static Microsoft.VisualStudio.TestTools.UnitTesting.CollectionAssert.ReferenceEquals(object? objA, object? objB) -> bool +static Microsoft.VisualStudio.TestTools.UnitTesting.StringAssert.Equals(object? objA, object? objB) -> bool +static Microsoft.VisualStudio.TestTools.UnitTesting.StringAssert.ReferenceEquals(object? objA, object? objB) -> bool diff --git a/src/TestFramework/TestFramework/Resources/FrameworkMessages.Designer.cs b/src/TestFramework/TestFramework/Resources/FrameworkMessages.Designer.cs index 7583c35788..a29e1a07eb 100644 --- a/src/TestFramework/TestFramework/Resources/FrameworkMessages.Designer.cs +++ b/src/TestFramework/TestFramework/Resources/FrameworkMessages.Designer.cs @@ -303,6 +303,51 @@ internal static string DoNotUseAssertEquals { } } + /// + /// Looks up a localized string similar to Assert.ReferenceEquals should not be used for Assertions. Please use Assert.AreSame & overloads instead.. + /// + internal static string DoNotUseAssertReferenceEquals { + get { + return ResourceManager.GetString("DoNotUseAssertReferenceEquals", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to CollectionAssert.Equals should not be used for Assertions. Please use CollectionAssert.AreEqual & overloads instead.. + /// + internal static string DoNotUseCollectionAssertEquals { + get { + return ResourceManager.GetString("DoNotUseCollectionAssertEquals", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to CollectionAssert.ReferenceEquals should not be used for Assertions. Please use CollectionAssert methods or Assert.AreSame & overloads instead.. + /// + internal static string DoNotUseCollectionAssertReferenceEquals { + get { + return ResourceManager.GetString("DoNotUseCollectionAssertReferenceEquals", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to StringAssert.Equals should not be used for Assertions. Please use StringAssert methods or Assert.AreEqual & overloads instead.. + /// + internal static string DoNotUseStringAssertEquals { + get { + return ResourceManager.GetString("DoNotUseStringAssertEquals", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to StringAssert.ReferenceEquals should not be used for Assertions. Please use StringAssert methods or Assert.AreSame & overloads instead.. + /// + internal static string DoNotUseStringAssertReferenceEquals { + get { + return ResourceManager.GetString("DoNotUseStringAssertReferenceEquals", resourceCulture); + } + } + /// /// Looks up a localized string similar to Method {0} must match the expected signature: public static {1} {0}({2}).. /// diff --git a/src/TestFramework/TestFramework/Resources/FrameworkMessages.resx b/src/TestFramework/TestFramework/Resources/FrameworkMessages.resx index f1eee89b5c..b14092e3f4 100644 --- a/src/TestFramework/TestFramework/Resources/FrameworkMessages.resx +++ b/src/TestFramework/TestFramework/Resources/FrameworkMessages.resx @@ -197,9 +197,6 @@ Actual: {2} String '{0}' matches pattern '{1}'. {2} - - Assert.Equals should not be used for Assertions. Please use Assert.AreEqual & overloads instead. - The member specified ({0}) could not be found. You might need to regenerate your private accessor, @@ -347,4 +344,22 @@ Actual: {2} String '{0}' starts with string '{1}'. {2} + + Assert.Equals should not be used for Assertions. Please use Assert.AreEqual & overloads instead. + + + Assert.ReferenceEquals should not be used for Assertions. Please use Assert.AreSame & overloads instead. + + + StringAssert.Equals should not be used for Assertions. Please use StringAssert methods or Assert.AreEqual & overloads instead. + + + StringAssert.ReferenceEquals should not be used for Assertions. Please use StringAssert methods or Assert.AreSame & overloads instead. + + + CollectionAssert.Equals should not be used for Assertions. Please use CollectionAssert.AreEqual & overloads instead. + + + CollectionAssert.ReferenceEquals should not be used for Assertions. Please use CollectionAssert methods or Assert.AreSame & overloads instead. + diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.cs.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.cs.xlf index 54e36414d1..772245466c 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.cs.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.cs.xlf @@ -211,11 +211,6 @@ Skutečnost: {2} String '{0}' matches pattern '{1}'. {2} - - Assert.Equals should not be used for Assertions. Please use Assert.AreEqual & overloads instead. - Assert.Equals by neměla být pro kontrolní výrazy používána. Použijte prosím místo toho Assert.AreEqual a její přetížení. - - The member specified ({0}) could not be found. You might need to regenerate your private accessor, @@ -385,6 +380,36 @@ Skutečnost: {2} Expected value <{1}> to be negative. {0} + + Assert.Equals should not be used for Assertions. Please use Assert.AreEqual & overloads instead. + Assert.Equals should not be used for Assertions. Please use Assert.AreEqual & overloads instead. + + + + Assert.ReferenceEquals should not be used for Assertions. Please use Assert.AreSame & overloads instead. + Assert.ReferenceEquals should not be used for Assertions. Please use Assert.AreSame & overloads instead. + + + + StringAssert.Equals should not be used for Assertions. Please use StringAssert methods or Assert.AreEqual & overloads instead. + StringAssert.Equals should not be used for Assertions. Please use StringAssert methods or Assert.AreEqual & overloads instead. + + + + StringAssert.ReferenceEquals should not be used for Assertions. Please use StringAssert methods or Assert.AreSame & overloads instead. + StringAssert.ReferenceEquals should not be used for Assertions. Please use StringAssert methods or Assert.AreSame & overloads instead. + + + + CollectionAssert.Equals should not be used for Assertions. Please use CollectionAssert.AreEqual & overloads instead. + CollectionAssert.Equals should not be used for Assertions. Please use CollectionAssert.AreEqual & overloads instead. + + + + CollectionAssert.ReferenceEquals should not be used for Assertions. Please use CollectionAssert methods or Assert.AreSame & overloads instead. + CollectionAssert.ReferenceEquals should not be used for Assertions. Please use CollectionAssert methods or Assert.AreSame & overloads instead. + + \ No newline at end of file diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.de.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.de.xlf index f5cf712cfc..4a672fd32c 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.de.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.de.xlf @@ -211,11 +211,6 @@ Tatsächlich: {2} String '{0}' matches pattern '{1}'. {2} - - Assert.Equals should not be used for Assertions. Please use Assert.AreEqual & overloads instead. - Assert.Equals sollte nicht für Assertions verwendet werden. Verwenden Sie stattdessen Assert.AreEqual und Überladungen. - - The member specified ({0}) could not be found. You might need to regenerate your private accessor, @@ -385,6 +380,36 @@ Tatsächlich: {2} Expected value <{1}> to be negative. {0} + + Assert.Equals should not be used for Assertions. Please use Assert.AreEqual & overloads instead. + Assert.Equals should not be used for Assertions. Please use Assert.AreEqual & overloads instead. + + + + Assert.ReferenceEquals should not be used for Assertions. Please use Assert.AreSame & overloads instead. + Assert.ReferenceEquals should not be used for Assertions. Please use Assert.AreSame & overloads instead. + + + + StringAssert.Equals should not be used for Assertions. Please use StringAssert methods or Assert.AreEqual & overloads instead. + StringAssert.Equals should not be used for Assertions. Please use StringAssert methods or Assert.AreEqual & overloads instead. + + + + StringAssert.ReferenceEquals should not be used for Assertions. Please use StringAssert methods or Assert.AreSame & overloads instead. + StringAssert.ReferenceEquals should not be used for Assertions. Please use StringAssert methods or Assert.AreSame & overloads instead. + + + + CollectionAssert.Equals should not be used for Assertions. Please use CollectionAssert.AreEqual & overloads instead. + CollectionAssert.Equals should not be used for Assertions. Please use CollectionAssert.AreEqual & overloads instead. + + + + CollectionAssert.ReferenceEquals should not be used for Assertions. Please use CollectionAssert methods or Assert.AreSame & overloads instead. + CollectionAssert.ReferenceEquals should not be used for Assertions. Please use CollectionAssert methods or Assert.AreSame & overloads instead. + + \ No newline at end of file diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.es.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.es.xlf index 736ca9b71e..59a8de12db 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.es.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.es.xlf @@ -211,11 +211,6 @@ Real: {2} String '{0}' matches pattern '{1}'. {2} - - Assert.Equals should not be used for Assertions. Please use Assert.AreEqual & overloads instead. - No se debe usar Assert.Equals para aserciones. Use Assert.AreEqual y Overloads en su lugar. - - The member specified ({0}) could not be found. You might need to regenerate your private accessor, @@ -385,6 +380,36 @@ Real: {2} Expected value <{1}> to be negative. {0} + + Assert.Equals should not be used for Assertions. Please use Assert.AreEqual & overloads instead. + Assert.Equals should not be used for Assertions. Please use Assert.AreEqual & overloads instead. + + + + Assert.ReferenceEquals should not be used for Assertions. Please use Assert.AreSame & overloads instead. + Assert.ReferenceEquals should not be used for Assertions. Please use Assert.AreSame & overloads instead. + + + + StringAssert.Equals should not be used for Assertions. Please use StringAssert methods or Assert.AreEqual & overloads instead. + StringAssert.Equals should not be used for Assertions. Please use StringAssert methods or Assert.AreEqual & overloads instead. + + + + StringAssert.ReferenceEquals should not be used for Assertions. Please use StringAssert methods or Assert.AreSame & overloads instead. + StringAssert.ReferenceEquals should not be used for Assertions. Please use StringAssert methods or Assert.AreSame & overloads instead. + + + + CollectionAssert.Equals should not be used for Assertions. Please use CollectionAssert.AreEqual & overloads instead. + CollectionAssert.Equals should not be used for Assertions. Please use CollectionAssert.AreEqual & overloads instead. + + + + CollectionAssert.ReferenceEquals should not be used for Assertions. Please use CollectionAssert methods or Assert.AreSame & overloads instead. + CollectionAssert.ReferenceEquals should not be used for Assertions. Please use CollectionAssert methods or Assert.AreSame & overloads instead. + + \ No newline at end of file diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.fr.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.fr.xlf index 3f776be2de..558ff63d2b 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.fr.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.fr.xlf @@ -211,11 +211,6 @@ Réel : {2} String '{0}' matches pattern '{1}'. {2} - - Assert.Equals should not be used for Assertions. Please use Assert.AreEqual & overloads instead. - Assert.Equals ne doit pas être utilisé pour les assertions. Utilisez Assert.AreEqual & overloads à la place. - - The member specified ({0}) could not be found. You might need to regenerate your private accessor, @@ -385,6 +380,36 @@ Réel : {2} Expected value <{1}> to be negative. {0} + + Assert.Equals should not be used for Assertions. Please use Assert.AreEqual & overloads instead. + Assert.Equals should not be used for Assertions. Please use Assert.AreEqual & overloads instead. + + + + Assert.ReferenceEquals should not be used for Assertions. Please use Assert.AreSame & overloads instead. + Assert.ReferenceEquals should not be used for Assertions. Please use Assert.AreSame & overloads instead. + + + + StringAssert.Equals should not be used for Assertions. Please use StringAssert methods or Assert.AreEqual & overloads instead. + StringAssert.Equals should not be used for Assertions. Please use StringAssert methods or Assert.AreEqual & overloads instead. + + + + StringAssert.ReferenceEquals should not be used for Assertions. Please use StringAssert methods or Assert.AreSame & overloads instead. + StringAssert.ReferenceEquals should not be used for Assertions. Please use StringAssert methods or Assert.AreSame & overloads instead. + + + + CollectionAssert.Equals should not be used for Assertions. Please use CollectionAssert.AreEqual & overloads instead. + CollectionAssert.Equals should not be used for Assertions. Please use CollectionAssert.AreEqual & overloads instead. + + + + CollectionAssert.ReferenceEquals should not be used for Assertions. Please use CollectionAssert methods or Assert.AreSame & overloads instead. + CollectionAssert.ReferenceEquals should not be used for Assertions. Please use CollectionAssert methods or Assert.AreSame & overloads instead. + + \ No newline at end of file diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.it.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.it.xlf index 7512e6c455..67f3bc4739 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.it.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.it.xlf @@ -211,11 +211,6 @@ Effettivo: {2} String '{0}' matches pattern '{1}'. {2} - - Assert.Equals should not be used for Assertions. Please use Assert.AreEqual & overloads instead. - Non è possibile usare Assert.Equals per le asserzioni. Usare Assert.AreEqual e gli overload. - - The member specified ({0}) could not be found. You might need to regenerate your private accessor, @@ -385,6 +380,36 @@ Effettivo: {2} Expected value <{1}> to be negative. {0} + + Assert.Equals should not be used for Assertions. Please use Assert.AreEqual & overloads instead. + Assert.Equals should not be used for Assertions. Please use Assert.AreEqual & overloads instead. + + + + Assert.ReferenceEquals should not be used for Assertions. Please use Assert.AreSame & overloads instead. + Assert.ReferenceEquals should not be used for Assertions. Please use Assert.AreSame & overloads instead. + + + + StringAssert.Equals should not be used for Assertions. Please use StringAssert methods or Assert.AreEqual & overloads instead. + StringAssert.Equals should not be used for Assertions. Please use StringAssert methods or Assert.AreEqual & overloads instead. + + + + StringAssert.ReferenceEquals should not be used for Assertions. Please use StringAssert methods or Assert.AreSame & overloads instead. + StringAssert.ReferenceEquals should not be used for Assertions. Please use StringAssert methods or Assert.AreSame & overloads instead. + + + + CollectionAssert.Equals should not be used for Assertions. Please use CollectionAssert.AreEqual & overloads instead. + CollectionAssert.Equals should not be used for Assertions. Please use CollectionAssert.AreEqual & overloads instead. + + + + CollectionAssert.ReferenceEquals should not be used for Assertions. Please use CollectionAssert methods or Assert.AreSame & overloads instead. + CollectionAssert.ReferenceEquals should not be used for Assertions. Please use CollectionAssert methods or Assert.AreSame & overloads instead. + + \ No newline at end of file diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ja.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ja.xlf index acc4aabbc2..3581f36a10 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ja.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ja.xlf @@ -211,11 +211,6 @@ Actual: {2} String '{0}' matches pattern '{1}'. {2} - - Assert.Equals should not be used for Assertions. Please use Assert.AreEqual & overloads instead. - アサーションには Assert.Equals を使用せずに、Assert.AreEqual とオーバーロードを使用してください。(& ) - - The member specified ({0}) could not be found. You might need to regenerate your private accessor, @@ -385,6 +380,36 @@ Actual: {2} Expected value <{1}> to be negative. {0} + + Assert.Equals should not be used for Assertions. Please use Assert.AreEqual & overloads instead. + Assert.Equals should not be used for Assertions. Please use Assert.AreEqual & overloads instead. + + + + Assert.ReferenceEquals should not be used for Assertions. Please use Assert.AreSame & overloads instead. + Assert.ReferenceEquals should not be used for Assertions. Please use Assert.AreSame & overloads instead. + + + + StringAssert.Equals should not be used for Assertions. Please use StringAssert methods or Assert.AreEqual & overloads instead. + StringAssert.Equals should not be used for Assertions. Please use StringAssert methods or Assert.AreEqual & overloads instead. + + + + StringAssert.ReferenceEquals should not be used for Assertions. Please use StringAssert methods or Assert.AreSame & overloads instead. + StringAssert.ReferenceEquals should not be used for Assertions. Please use StringAssert methods or Assert.AreSame & overloads instead. + + + + CollectionAssert.Equals should not be used for Assertions. Please use CollectionAssert.AreEqual & overloads instead. + CollectionAssert.Equals should not be used for Assertions. Please use CollectionAssert.AreEqual & overloads instead. + + + + CollectionAssert.ReferenceEquals should not be used for Assertions. Please use CollectionAssert methods or Assert.AreSame & overloads instead. + CollectionAssert.ReferenceEquals should not be used for Assertions. Please use CollectionAssert methods or Assert.AreSame & overloads instead. + + \ No newline at end of file diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ko.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ko.xlf index f7b58e03ac..80b2c076b9 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ko.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ko.xlf @@ -211,11 +211,6 @@ Actual: {2} String '{0}' matches pattern '{1}'. {2} - - Assert.Equals should not be used for Assertions. Please use Assert.AreEqual & overloads instead. - 어설션에 Assert.Equals를 사용할 수 없습니다. 대신 Assert.AreEqual 및 오버로드를 사용하세요. - - The member specified ({0}) could not be found. You might need to regenerate your private accessor, @@ -385,6 +380,36 @@ Actual: {2} Expected value <{1}> to be negative. {0} + + Assert.Equals should not be used for Assertions. Please use Assert.AreEqual & overloads instead. + Assert.Equals should not be used for Assertions. Please use Assert.AreEqual & overloads instead. + + + + Assert.ReferenceEquals should not be used for Assertions. Please use Assert.AreSame & overloads instead. + Assert.ReferenceEquals should not be used for Assertions. Please use Assert.AreSame & overloads instead. + + + + StringAssert.Equals should not be used for Assertions. Please use StringAssert methods or Assert.AreEqual & overloads instead. + StringAssert.Equals should not be used for Assertions. Please use StringAssert methods or Assert.AreEqual & overloads instead. + + + + StringAssert.ReferenceEquals should not be used for Assertions. Please use StringAssert methods or Assert.AreSame & overloads instead. + StringAssert.ReferenceEquals should not be used for Assertions. Please use StringAssert methods or Assert.AreSame & overloads instead. + + + + CollectionAssert.Equals should not be used for Assertions. Please use CollectionAssert.AreEqual & overloads instead. + CollectionAssert.Equals should not be used for Assertions. Please use CollectionAssert.AreEqual & overloads instead. + + + + CollectionAssert.ReferenceEquals should not be used for Assertions. Please use CollectionAssert methods or Assert.AreSame & overloads instead. + CollectionAssert.ReferenceEquals should not be used for Assertions. Please use CollectionAssert methods or Assert.AreSame & overloads instead. + + \ No newline at end of file diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pl.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pl.xlf index 4580302814..0e58e77c53 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pl.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pl.xlf @@ -211,11 +211,6 @@ Rzeczywiste: {2} String '{0}' matches pattern '{1}'. {2} - - Assert.Equals should not be used for Assertions. Please use Assert.AreEqual & overloads instead. - Assert.Equals nie powinno być używane do potwierdzania. Zamiast tego użyj Assert.AreEqual i przeciążeń. - - The member specified ({0}) could not be found. You might need to regenerate your private accessor, @@ -385,6 +380,36 @@ Rzeczywiste: {2} Expected value <{1}> to be negative. {0} + + Assert.Equals should not be used for Assertions. Please use Assert.AreEqual & overloads instead. + Assert.Equals should not be used for Assertions. Please use Assert.AreEqual & overloads instead. + + + + Assert.ReferenceEquals should not be used for Assertions. Please use Assert.AreSame & overloads instead. + Assert.ReferenceEquals should not be used for Assertions. Please use Assert.AreSame & overloads instead. + + + + StringAssert.Equals should not be used for Assertions. Please use StringAssert methods or Assert.AreEqual & overloads instead. + StringAssert.Equals should not be used for Assertions. Please use StringAssert methods or Assert.AreEqual & overloads instead. + + + + StringAssert.ReferenceEquals should not be used for Assertions. Please use StringAssert methods or Assert.AreSame & overloads instead. + StringAssert.ReferenceEquals should not be used for Assertions. Please use StringAssert methods or Assert.AreSame & overloads instead. + + + + CollectionAssert.Equals should not be used for Assertions. Please use CollectionAssert.AreEqual & overloads instead. + CollectionAssert.Equals should not be used for Assertions. Please use CollectionAssert.AreEqual & overloads instead. + + + + CollectionAssert.ReferenceEquals should not be used for Assertions. Please use CollectionAssert methods or Assert.AreSame & overloads instead. + CollectionAssert.ReferenceEquals should not be used for Assertions. Please use CollectionAssert methods or Assert.AreSame & overloads instead. + + \ No newline at end of file diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf index 57576c57fa..edcbb7fb2b 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf @@ -211,11 +211,6 @@ Real: {2} String '{0}' matches pattern '{1}'. {2} - - Assert.Equals should not be used for Assertions. Please use Assert.AreEqual & overloads instead. - Assert.Equals não deveria ser usado para Declarações. Use Assert.AreEqual e sobrecargas em seu lugar. - - The member specified ({0}) could not be found. You might need to regenerate your private accessor, @@ -385,6 +380,36 @@ Real: {2} Expected value <{1}> to be negative. {0} + + Assert.Equals should not be used for Assertions. Please use Assert.AreEqual & overloads instead. + Assert.Equals should not be used for Assertions. Please use Assert.AreEqual & overloads instead. + + + + Assert.ReferenceEquals should not be used for Assertions. Please use Assert.AreSame & overloads instead. + Assert.ReferenceEquals should not be used for Assertions. Please use Assert.AreSame & overloads instead. + + + + StringAssert.Equals should not be used for Assertions. Please use StringAssert methods or Assert.AreEqual & overloads instead. + StringAssert.Equals should not be used for Assertions. Please use StringAssert methods or Assert.AreEqual & overloads instead. + + + + StringAssert.ReferenceEquals should not be used for Assertions. Please use StringAssert methods or Assert.AreSame & overloads instead. + StringAssert.ReferenceEquals should not be used for Assertions. Please use StringAssert methods or Assert.AreSame & overloads instead. + + + + CollectionAssert.Equals should not be used for Assertions. Please use CollectionAssert.AreEqual & overloads instead. + CollectionAssert.Equals should not be used for Assertions. Please use CollectionAssert.AreEqual & overloads instead. + + + + CollectionAssert.ReferenceEquals should not be used for Assertions. Please use CollectionAssert methods or Assert.AreSame & overloads instead. + CollectionAssert.ReferenceEquals should not be used for Assertions. Please use CollectionAssert methods or Assert.AreSame & overloads instead. + + \ No newline at end of file diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ru.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ru.xlf index ba7a6f56ad..916db728c9 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ru.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ru.xlf @@ -211,11 +211,6 @@ Actual: {2} String '{0}' matches pattern '{1}'. {2} - - Assert.Equals should not be used for Assertions. Please use Assert.AreEqual & overloads instead. - Нельзя использовать Assert.Equals для Assertions. Вместо этого используйте Assert.AreEqual и перегрузки. - - The member specified ({0}) could not be found. You might need to regenerate your private accessor, @@ -385,6 +380,36 @@ Actual: {2} Expected value <{1}> to be negative. {0} + + Assert.Equals should not be used for Assertions. Please use Assert.AreEqual & overloads instead. + Assert.Equals should not be used for Assertions. Please use Assert.AreEqual & overloads instead. + + + + Assert.ReferenceEquals should not be used for Assertions. Please use Assert.AreSame & overloads instead. + Assert.ReferenceEquals should not be used for Assertions. Please use Assert.AreSame & overloads instead. + + + + StringAssert.Equals should not be used for Assertions. Please use StringAssert methods or Assert.AreEqual & overloads instead. + StringAssert.Equals should not be used for Assertions. Please use StringAssert methods or Assert.AreEqual & overloads instead. + + + + StringAssert.ReferenceEquals should not be used for Assertions. Please use StringAssert methods or Assert.AreSame & overloads instead. + StringAssert.ReferenceEquals should not be used for Assertions. Please use StringAssert methods or Assert.AreSame & overloads instead. + + + + CollectionAssert.Equals should not be used for Assertions. Please use CollectionAssert.AreEqual & overloads instead. + CollectionAssert.Equals should not be used for Assertions. Please use CollectionAssert.AreEqual & overloads instead. + + + + CollectionAssert.ReferenceEquals should not be used for Assertions. Please use CollectionAssert methods or Assert.AreSame & overloads instead. + CollectionAssert.ReferenceEquals should not be used for Assertions. Please use CollectionAssert methods or Assert.AreSame & overloads instead. + + \ No newline at end of file diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.tr.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.tr.xlf index 322e8ce049..5dbd2c2826 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.tr.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.tr.xlf @@ -211,11 +211,6 @@ Gerçekte olan: {2} String '{0}' matches pattern '{1}'. {2} - - Assert.Equals should not be used for Assertions. Please use Assert.AreEqual & overloads instead. - Assert.Equals, Onaylama için kullanılmamalı. Lütfen yerine Assert.AreEqual & aşırı yüklemeleri kullanın. - - The member specified ({0}) could not be found. You might need to regenerate your private accessor, @@ -385,6 +380,36 @@ Gerçekte olan: {2} Expected value <{1}> to be negative. {0} + + Assert.Equals should not be used for Assertions. Please use Assert.AreEqual & overloads instead. + Assert.Equals should not be used for Assertions. Please use Assert.AreEqual & overloads instead. + + + + Assert.ReferenceEquals should not be used for Assertions. Please use Assert.AreSame & overloads instead. + Assert.ReferenceEquals should not be used for Assertions. Please use Assert.AreSame & overloads instead. + + + + StringAssert.Equals should not be used for Assertions. Please use StringAssert methods or Assert.AreEqual & overloads instead. + StringAssert.Equals should not be used for Assertions. Please use StringAssert methods or Assert.AreEqual & overloads instead. + + + + StringAssert.ReferenceEquals should not be used for Assertions. Please use StringAssert methods or Assert.AreSame & overloads instead. + StringAssert.ReferenceEquals should not be used for Assertions. Please use StringAssert methods or Assert.AreSame & overloads instead. + + + + CollectionAssert.Equals should not be used for Assertions. Please use CollectionAssert.AreEqual & overloads instead. + CollectionAssert.Equals should not be used for Assertions. Please use CollectionAssert.AreEqual & overloads instead. + + + + CollectionAssert.ReferenceEquals should not be used for Assertions. Please use CollectionAssert methods or Assert.AreSame & overloads instead. + CollectionAssert.ReferenceEquals should not be used for Assertions. Please use CollectionAssert methods or Assert.AreSame & overloads instead. + + \ No newline at end of file diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf index b68cc27c7d..a787aa4473 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf @@ -211,11 +211,6 @@ Actual: {2} String '{0}' matches pattern '{1}'. {2} - - Assert.Equals should not be used for Assertions. Please use Assert.AreEqual & overloads instead. - Assert.Equals 不应用于断言。请改用 Assert.AreEqual 和重载。 - - The member specified ({0}) could not be found. You might need to regenerate your private accessor, @@ -385,6 +380,36 @@ Actual: {2} Expected value <{1}> to be negative. {0} + + Assert.Equals should not be used for Assertions. Please use Assert.AreEqual & overloads instead. + Assert.Equals should not be used for Assertions. Please use Assert.AreEqual & overloads instead. + + + + Assert.ReferenceEquals should not be used for Assertions. Please use Assert.AreSame & overloads instead. + Assert.ReferenceEquals should not be used for Assertions. Please use Assert.AreSame & overloads instead. + + + + StringAssert.Equals should not be used for Assertions. Please use StringAssert methods or Assert.AreEqual & overloads instead. + StringAssert.Equals should not be used for Assertions. Please use StringAssert methods or Assert.AreEqual & overloads instead. + + + + StringAssert.ReferenceEquals should not be used for Assertions. Please use StringAssert methods or Assert.AreSame & overloads instead. + StringAssert.ReferenceEquals should not be used for Assertions. Please use StringAssert methods or Assert.AreSame & overloads instead. + + + + CollectionAssert.Equals should not be used for Assertions. Please use CollectionAssert.AreEqual & overloads instead. + CollectionAssert.Equals should not be used for Assertions. Please use CollectionAssert.AreEqual & overloads instead. + + + + CollectionAssert.ReferenceEquals should not be used for Assertions. Please use CollectionAssert methods or Assert.AreSame & overloads instead. + CollectionAssert.ReferenceEquals should not be used for Assertions. Please use CollectionAssert methods or Assert.AreSame & overloads instead. + + \ No newline at end of file diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf index 804e8b106f..7bc115810e 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf @@ -211,11 +211,6 @@ Actual: {2} String '{0}' matches pattern '{1}'. {2} - - Assert.Equals should not be used for Assertions. Please use Assert.AreEqual & overloads instead. - Assert.Equals 不應使用於判斷提示。請改用 Assert.AreEqual 及多載。 - - The member specified ({0}) could not be found. You might need to regenerate your private accessor, @@ -385,6 +380,36 @@ Actual: {2} Expected value <{1}> to be negative. {0} + + Assert.Equals should not be used for Assertions. Please use Assert.AreEqual & overloads instead. + Assert.Equals should not be used for Assertions. Please use Assert.AreEqual & overloads instead. + + + + Assert.ReferenceEquals should not be used for Assertions. Please use Assert.AreSame & overloads instead. + Assert.ReferenceEquals should not be used for Assertions. Please use Assert.AreSame & overloads instead. + + + + StringAssert.Equals should not be used for Assertions. Please use StringAssert methods or Assert.AreEqual & overloads instead. + StringAssert.Equals should not be used for Assertions. Please use StringAssert methods or Assert.AreEqual & overloads instead. + + + + StringAssert.ReferenceEquals should not be used for Assertions. Please use StringAssert methods or Assert.AreSame & overloads instead. + StringAssert.ReferenceEquals should not be used for Assertions. Please use StringAssert methods or Assert.AreSame & overloads instead. + + + + CollectionAssert.Equals should not be used for Assertions. Please use CollectionAssert.AreEqual & overloads instead. + CollectionAssert.Equals should not be used for Assertions. Please use CollectionAssert.AreEqual & overloads instead. + + + + CollectionAssert.ReferenceEquals should not be used for Assertions. Please use CollectionAssert methods or Assert.AreSame & overloads instead. + CollectionAssert.ReferenceEquals should not be used for Assertions. Please use CollectionAssert methods or Assert.AreSame & overloads instead. + + \ No newline at end of file diff --git a/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.cs b/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.cs index e2dbd35660..c14d13fe4c 100644 --- a/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.cs +++ b/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.cs @@ -38,6 +38,29 @@ public void BuildUserMessageDoesNotThrowWhenMessageContainsInvalidStringFormatCo } #endregion + #region Obsolete methods tests +#if DEBUG + public void ObsoleteEqualsMethodThrowsAssertFailedException() + { +#pragma warning disable CS0618 // Type or member is obsolete + Exception ex = VerifyThrows(() => Assert.Equals("test", "test")); +#pragma warning restore CS0618 // Type or member is obsolete + Verify(ex is AssertFailedException); + Verify(ex.Message.Contains("Assert.Equals should not be used for Assertions")); + } + + public void ObsoleteReferenceEqualsMethodThrowsAssertFailedException() + { + object obj = new(); +#pragma warning disable CS0618 // Type or member is obsolete + Exception ex = VerifyThrows(() => Assert.ReferenceEquals(obj, obj)); +#pragma warning restore CS0618 // Type or member is obsolete + Verify(ex is AssertFailedException); + Verify(ex.Message.Contains("Assert.ReferenceEquals should not be used for Assertions")); + } +#endif + #endregion + private static Task GetHelloStringAsync() => Task.FromResult("Hello"); diff --git a/test/UnitTests/TestFramework.UnitTests/Assertions/CollectionAssertTests.cs b/test/UnitTests/TestFramework.UnitTests/Assertions/CollectionAssertTests.cs index 8341740393..66131b5ec1 100644 --- a/test/UnitTests/TestFramework.UnitTests/Assertions/CollectionAssertTests.cs +++ b/test/UnitTests/TestFramework.UnitTests/Assertions/CollectionAssertTests.cs @@ -561,4 +561,27 @@ private class CaseInsensitiveNotEqualityComparer : IEqualityComparer public int GetHashCode(string obj) => obj.ToUpperInvariant().GetHashCode(); } + + #region Obsolete methods tests +#if DEBUG + public void ObsoleteEqualsMethodThrowsAssertFailedException() + { +#pragma warning disable CS0618 // Type or member is obsolete + Exception ex = VerifyThrows(() => CollectionAssert.Equals("test", "test")); +#pragma warning restore CS0618 // Type or member is obsolete + Verify(ex is AssertFailedException); + Verify(ex.Message.Contains("CollectionAssert.Equals should not be used for Assertions")); + } + + public void ObsoleteReferenceEqualsMethodThrowsAssertFailedException() + { + object obj = new(); +#pragma warning disable CS0618 // Type or member is obsolete + Exception ex = VerifyThrows(() => CollectionAssert.ReferenceEquals(obj, obj)); +#pragma warning restore CS0618 // Type or member is obsolete + Verify(ex is AssertFailedException); + Verify(ex.Message.Contains("CollectionAssert.ReferenceEquals should not be used for Assertions")); + } +#endif + #endregion } diff --git a/test/UnitTests/TestFramework.UnitTests/Assertions/StringAssertTests.cs b/test/UnitTests/TestFramework.UnitTests/Assertions/StringAssertTests.cs index 245950a7d3..0f9469d391 100644 --- a/test/UnitTests/TestFramework.UnitTests/Assertions/StringAssertTests.cs +++ b/test/UnitTests/TestFramework.UnitTests/Assertions/StringAssertTests.cs @@ -311,4 +311,27 @@ public void StringAssertDoesNotMatchMessageParametersNullabilitiesPostConditions private Regex? GetMatchingPattern() => new("some*"); private Regex? GetNonMatchingPattern() => new("something"); + + #region Obsolete methods tests +#if DEBUG + public void ObsoleteEqualsMethodThrowsAssertFailedException() + { +#pragma warning disable CS0618 // Type or member is obsolete + Exception ex = VerifyThrows(() => StringAssert.Equals("test", "test")); +#pragma warning restore CS0618 // Type or member is obsolete + Verify(ex is AssertFailedException); + Verify(ex.Message.Contains("StringAssert.Equals should not be used for Assertions")); + } + + public void ObsoleteReferenceEqualsMethodThrowsAssertFailedException() + { + object obj = new(); +#pragma warning disable CS0618 // Type or member is obsolete + Exception ex = VerifyThrows(() => StringAssert.ReferenceEquals(obj, obj)); +#pragma warning restore CS0618 // Type or member is obsolete + Verify(ex is AssertFailedException); + Verify(ex.Message.Contains("StringAssert.ReferenceEquals should not be used for Assertions")); + } +#endif + #endregion } From defb53b8eedb3fa365f0c7c17764879c401696f3 Mon Sep 17 00:00:00 2001 From: dotnet bot Date: Thu, 19 Jun 2025 12:07:46 +0200 Subject: [PATCH 122/541] Localized file check-in by OneLocBuild Task: Build definition ID 1218: Build ID 2733488 --- .../TestFramework/Resources/xlf/FrameworkMessages.cs.xlf | 2 +- .../TestFramework/Resources/xlf/FrameworkMessages.de.xlf | 2 +- .../TestFramework/Resources/xlf/FrameworkMessages.es.xlf | 2 +- .../TestFramework/Resources/xlf/FrameworkMessages.fr.xlf | 2 +- .../TestFramework/Resources/xlf/FrameworkMessages.it.xlf | 2 +- .../TestFramework/Resources/xlf/FrameworkMessages.ja.xlf | 2 +- .../TestFramework/Resources/xlf/FrameworkMessages.ko.xlf | 2 +- .../TestFramework/Resources/xlf/FrameworkMessages.pl.xlf | 2 +- .../TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf | 2 +- .../TestFramework/Resources/xlf/FrameworkMessages.ru.xlf | 2 +- .../TestFramework/Resources/xlf/FrameworkMessages.tr.xlf | 2 +- .../TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf | 2 +- .../TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf | 2 +- 13 files changed, 13 insertions(+), 13 deletions(-) diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.cs.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.cs.xlf index 772245466c..4f8d7b5eaf 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.cs.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.cs.xlf @@ -382,7 +382,7 @@ Skutečnost: {2} Assert.Equals should not be used for Assertions. Please use Assert.AreEqual & overloads instead. - Assert.Equals should not be used for Assertions. Please use Assert.AreEqual & overloads instead. + Assert.Equals by neměla být pro kontrolní výrazy používána. Použijte prosím místo toho Assert.AreEqual a její přetížení. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.de.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.de.xlf index 4a672fd32c..4a3af78cc1 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.de.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.de.xlf @@ -382,7 +382,7 @@ Tatsächlich: {2} Assert.Equals should not be used for Assertions. Please use Assert.AreEqual & overloads instead. - Assert.Equals should not be used for Assertions. Please use Assert.AreEqual & overloads instead. + Assert.Equals sollte nicht für Assertions verwendet werden. Verwenden Sie stattdessen Assert.AreEqual und Überladungen. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.es.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.es.xlf index 59a8de12db..a93c90cd17 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.es.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.es.xlf @@ -382,7 +382,7 @@ Real: {2} Assert.Equals should not be used for Assertions. Please use Assert.AreEqual & overloads instead. - Assert.Equals should not be used for Assertions. Please use Assert.AreEqual & overloads instead. + No se debe usar Assert.Equals para aserciones. Use Assert.AreEqual y Overloads en su lugar. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.fr.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.fr.xlf index 558ff63d2b..b5688b3969 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.fr.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.fr.xlf @@ -382,7 +382,7 @@ Réel : {2} Assert.Equals should not be used for Assertions. Please use Assert.AreEqual & overloads instead. - Assert.Equals should not be used for Assertions. Please use Assert.AreEqual & overloads instead. + Assert.Equals ne doit pas être utilisé pour les assertions. Utilisez Assert.AreEqual & overloads à la place. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.it.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.it.xlf index 67f3bc4739..920db09a6c 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.it.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.it.xlf @@ -382,7 +382,7 @@ Effettivo: {2} Assert.Equals should not be used for Assertions. Please use Assert.AreEqual & overloads instead. - Assert.Equals should not be used for Assertions. Please use Assert.AreEqual & overloads instead. + Non è possibile usare Assert.Equals per le asserzioni. Usare Assert.AreEqual e gli overload. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ja.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ja.xlf index 3581f36a10..e3b48c305c 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ja.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ja.xlf @@ -382,7 +382,7 @@ Actual: {2} Assert.Equals should not be used for Assertions. Please use Assert.AreEqual & overloads instead. - Assert.Equals should not be used for Assertions. Please use Assert.AreEqual & overloads instead. + アサーションには Assert.Equals を使用せずに、Assert.AreEqual とオーバーロードを使用してください。(& ) diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ko.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ko.xlf index 80b2c076b9..0ea1d92159 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ko.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ko.xlf @@ -382,7 +382,7 @@ Actual: {2} Assert.Equals should not be used for Assertions. Please use Assert.AreEqual & overloads instead. - Assert.Equals should not be used for Assertions. Please use Assert.AreEqual & overloads instead. + 어설션에 Assert.Equals를 사용할 수 없습니다. 대신 Assert.AreEqual 및 오버로드를 사용하세요. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pl.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pl.xlf index 0e58e77c53..c2547c031e 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pl.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pl.xlf @@ -382,7 +382,7 @@ Rzeczywiste: {2} Assert.Equals should not be used for Assertions. Please use Assert.AreEqual & overloads instead. - Assert.Equals should not be used for Assertions. Please use Assert.AreEqual & overloads instead. + Assert.Equals nie powinno być używane do potwierdzania. Zamiast tego użyj Assert.AreEqual i przeciążeń. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf index edcbb7fb2b..7839c81f10 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf @@ -382,7 +382,7 @@ Real: {2} Assert.Equals should not be used for Assertions. Please use Assert.AreEqual & overloads instead. - Assert.Equals should not be used for Assertions. Please use Assert.AreEqual & overloads instead. + Assert.Equals não deveria ser usado para Declarações. Use Assert.AreEqual e sobrecargas em seu lugar. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ru.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ru.xlf index 916db728c9..1419629d43 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ru.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ru.xlf @@ -382,7 +382,7 @@ Actual: {2} Assert.Equals should not be used for Assertions. Please use Assert.AreEqual & overloads instead. - Assert.Equals should not be used for Assertions. Please use Assert.AreEqual & overloads instead. + Нельзя использовать Assert.Equals для Assertions. Вместо этого используйте Assert.AreEqual и перегрузки. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.tr.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.tr.xlf index 5dbd2c2826..2dca06ed92 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.tr.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.tr.xlf @@ -382,7 +382,7 @@ Gerçekte olan: {2} Assert.Equals should not be used for Assertions. Please use Assert.AreEqual & overloads instead. - Assert.Equals should not be used for Assertions. Please use Assert.AreEqual & overloads instead. + Assert.Equals, Onaylama için kullanılmamalı. Lütfen yerine Assert.AreEqual & aşırı yüklemeleri kullanın. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf index a787aa4473..6507fc239e 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf @@ -382,7 +382,7 @@ Actual: {2} Assert.Equals should not be used for Assertions. Please use Assert.AreEqual & overloads instead. - Assert.Equals should not be used for Assertions. Please use Assert.AreEqual & overloads instead. + Assert.Equals 不应用于断言。请改用 Assert.AreEqual 和重载。 diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf index 7bc115810e..cf022768e8 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf @@ -382,7 +382,7 @@ Actual: {2} Assert.Equals should not be used for Assertions. Please use Assert.AreEqual & overloads instead. - Assert.Equals should not be used for Assertions. Please use Assert.AreEqual & overloads instead. + Assert.Equals 不應使用於判斷提示。請改用 Assert.AreEqual 及多載。 From 07b6ec149a6d603f37fa5da780694a576770e1a1 Mon Sep 17 00:00:00 2001 From: Jamie Magee Date: Tue, 24 Jun 2025 00:03:31 -0700 Subject: [PATCH 123/541] Add Dependabot configuration for .NET SDK updates (#5861) --- .github/dependabot.yml | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 07e9451eef..25bc4f05d6 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -10,4 +10,14 @@ updates: - dependency-name: "Microsoft.DotNet.Arcade.Sdk" - dependency-name: Moq commit-message: - prefix: '[main] ' \ No newline at end of file + prefix: '[main] ' + - package-ecosystem: dotnet-sdk + directory: / + schedule: + interval: weekly + day: wednesday + ignore: + - dependency-name: '*' + update-types: + - version-update:semver-major + - version-update:semver-minor From a351cfaa1d117ece0c96f20e4ffd2fe271d63192 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Tue, 24 Jun 2025 21:23:26 +0200 Subject: [PATCH 124/541] Bump AvoidExpectedExceptionAttributeAnalyzer to warning (#5864) --- .../MSTest.Analyzers/AnalyzerReleases.Unshipped.md | 7 +++++++ .../AvoidExpectedExceptionAttributeAnalyzer.cs | 2 +- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/src/Analyzers/MSTest.Analyzers/AnalyzerReleases.Unshipped.md b/src/Analyzers/MSTest.Analyzers/AnalyzerReleases.Unshipped.md index 213270ba16..e2dae0b108 100644 --- a/src/Analyzers/MSTest.Analyzers/AnalyzerReleases.Unshipped.md +++ b/src/Analyzers/MSTest.Analyzers/AnalyzerReleases.Unshipped.md @@ -7,3 +7,10 @@ Rule ID | Category | Severity | Notes --------|----------|----------|------- MSTEST0044 | Design | Warning | PreferTestMethodOverDataTestMethodAnalyzer, [Documentation](https://learn.microsoft.com/dotnet/core/testing/mstest-analyzers/mstest0044) MSTEST0045 | Usage | Info | UseCooperativeCancellationForTimeoutAnalyzer, [Documentation](https://learn.microsoft.com/dotnet/core/testing/mstest-analyzers/mstest0045) + + +### Changed Rules + +Rule ID | New Category | New Severity | Old Category | Old Severity | Notes +--------|--------------|--------------|--------------|--------------|------- +MSTEST0006 | Design | Warning | Design | Info | AvoidExpectedExceptionAttributeAnalyzer diff --git a/src/Analyzers/MSTest.Analyzers/AvoidExpectedExceptionAttributeAnalyzer.cs b/src/Analyzers/MSTest.Analyzers/AvoidExpectedExceptionAttributeAnalyzer.cs index 57d24831f3..df19f7f3e5 100644 --- a/src/Analyzers/MSTest.Analyzers/AvoidExpectedExceptionAttributeAnalyzer.cs +++ b/src/Analyzers/MSTest.Analyzers/AvoidExpectedExceptionAttributeAnalyzer.cs @@ -30,7 +30,7 @@ public sealed class AvoidExpectedExceptionAttributeAnalyzer : DiagnosticAnalyzer MessageFormat, Description, Category.Design, - DiagnosticSeverity.Info, + DiagnosticSeverity.Warning, isEnabledByDefault: true); /// From 521414eee1750e357572e1747c6f54a1264b67d6 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Tue, 24 Jun 2025 21:51:21 +0200 Subject: [PATCH 125/541] Adjust new assert APIs before shipping (#5866) --- .../Assertions/Assert.Contains.cs | 38 +--- .../Assertions/Assert.EndsWith.cs | 123 +---------- .../Assertions/Assert.IComparable.cs | 192 ++---------------- .../Assertions/Assert.Matches.cs | 118 +---------- .../Assertions/Assert.StartsWith.cs | 121 +---------- .../PublicAPI/PublicAPI.Unshipped.txt | 28 +-- .../Assertions/AssertTests.Contains.cs | 8 +- .../AssertTests.IComparableTests.cs | 60 ------ .../Assertions/AssertTests.IsInRange.cs | 11 +- .../Assertions/AssertTests.Items.cs | 8 +- 10 files changed, 58 insertions(+), 649 deletions(-) diff --git a/src/TestFramework/TestFramework/Assertions/Assert.Contains.cs b/src/TestFramework/TestFramework/Assertions/Assert.Contains.cs index 6290035726..ab8040aa77 100644 --- a/src/TestFramework/TestFramework/Assertions/Assert.Contains.cs +++ b/src/TestFramework/TestFramework/Assertions/Assert.Contains.cs @@ -152,18 +152,7 @@ public static T ContainsSingle(IEnumerable collection, [StringSyntax(Strin /// The collection. /// The item that matches the predicate. public static T ContainsSingle(Func predicate, IEnumerable collection) - => ContainsSingle(predicate, collection, string.Empty, null); - - /// - /// Tests whether the specified collection contains exactly one element that matches the given predicate. - /// - /// The type of the collection items. - /// A function to test each element for a condition. - /// The collection. - /// The message to display when the assertion fails. - /// The item that matches the predicate. - public static T ContainsSingle(Func predicate, IEnumerable collection, string? message) - => ContainsSingle(predicate, collection, message, null); + => ContainsSingle(predicate, collection, string.Empty); /// /// Tests whether the specified collection contains exactly one element that matches the given predicate. @@ -172,9 +161,8 @@ public static T ContainsSingle(Func predicate, IEnumerable collec /// A function to test each element for a condition. /// The collection. /// The message format to display when the assertion fails. - /// The parameters to format the message. /// The item that matches the predicate. - public static T ContainsSingle(Func predicate, IEnumerable collection, [StringSyntax(StringSyntaxAttribute.CompositeFormat)] string? message, params object?[]? parameters) + public static T ContainsSingle(Func predicate, IEnumerable collection, string? message) { var matchingElements = collection.Where(predicate).ToList(); int actualCount = matchingElements.Count; @@ -184,7 +172,7 @@ public static T ContainsSingle(Func predicate, IEnumerable collec return matchingElements[0]; } - string userMessage = BuildUserMessage(message, parameters); + string userMessage = BuildUserMessage(message); ThrowAssertSingleMatchFailed(actualCount, userMessage); // Unreachable code but compiler cannot work it out @@ -745,20 +733,7 @@ public static void DoesNotContain(string substring, string value, StringComparis /// The value to test. public static void IsInRange(T minValue, T maxValue, T value) where T : struct, IComparable - => IsInRange(minValue, maxValue, value, string.Empty, null); - - /// - /// Tests whether the specified value is within the expected range (inclusive). - /// The range includes both the minimum and maximum values. - /// - /// The type of the values to compare. - /// The minimum value of the expected range (inclusive). - /// The maximum value of the expected range (inclusive). - /// The value to test. - /// The message to display when the assertion fails. - public static void IsInRange(T minValue, T maxValue, T value, string? message) - where T : struct, IComparable - => IsInRange(minValue, maxValue, value, message, null); + => IsInRange(minValue, maxValue, value, string.Empty); /// /// Tests whether the specified value is within the expected range (inclusive). @@ -769,8 +744,7 @@ public static void IsInRange(T minValue, T maxValue, T value, string? message /// The maximum value of the expected range (inclusive). /// The value to test. /// The message format to display when the assertion fails. - /// The parameters to format the message. - public static void IsInRange(T minValue, T maxValue, T value, [StringSyntax(StringSyntaxAttribute.CompositeFormat)] string? message, params object?[]? parameters) + public static void IsInRange(T minValue, T maxValue, T value, string? message) where T : struct, IComparable { if (maxValue.CompareTo(minValue) <= 0) @@ -780,7 +754,7 @@ public static void IsInRange(T minValue, T maxValue, T value, [StringSyntax(S if (value.CompareTo(minValue) < 0 || value.CompareTo(maxValue) > 0) { - string userMessage = BuildUserMessage(message, parameters); + string userMessage = BuildUserMessage(message); string finalMessage = string.Format(CultureInfo.CurrentCulture, FrameworkMessages.IsInRangeFail, value, minValue, maxValue, userMessage); ThrowAssertFailed("IsInRange", finalMessage); } diff --git a/src/TestFramework/TestFramework/Assertions/Assert.EndsWith.cs b/src/TestFramework/TestFramework/Assertions/Assert.EndsWith.cs index 43057b46e2..9632c1cdac 100644 --- a/src/TestFramework/TestFramework/Assertions/Assert.EndsWith.cs +++ b/src/TestFramework/TestFramework/Assertions/Assert.EndsWith.cs @@ -48,32 +48,6 @@ public static void EndsWith([NotNull] string? substring, [NotNull] string? value public static void EndsWith([NotNull] string? substring, [NotNull] string? value, string? message) => EndsWith(substring, value, StringComparison.Ordinal, message); - /// - /// Tests whether the specified string ends with the specified substring - /// and throws an exception if the test string does not end with the - /// substring. - /// - /// - /// The string expected to be a suffix of . - /// - /// - /// The string that is expected to end with . - /// - /// - /// The message to include in the exception when - /// does not end with . The message is - /// shown in test results. - /// - /// - /// An array of parameters to use when formatting . - /// - /// - /// is null, or is null, - /// or does not end with . - /// - public static void EndsWith([NotNull] string? substring, [NotNull] string? value, [StringSyntax(StringSyntaxAttribute.CompositeFormat)] string? message, params object?[]? parameters) - => EndsWith(substring, value, StringComparison.Ordinal, message, parameters); - /// /// Tests whether the specified string ends with the specified substring /// and throws an exception if the test string does not end with the @@ -93,33 +67,7 @@ public static void EndsWith([NotNull] string? substring, [NotNull] string? value /// or does not end with . /// public static void EndsWith([NotNull] string? substring, [NotNull] string? value, StringComparison comparisonType) - => EndsWith(substring, value, comparisonType, string.Empty, null); - - /// - /// Tests whether the specified string ends with the specified substring - /// and throws an exception if the test string does not end with the - /// substring. - /// - /// - /// The string expected to be a suffix of . - /// - /// - /// The string that is expected to end with . - /// - /// - /// The message to include in the exception when - /// does not end with . The message is - /// shown in test results. - /// - /// - /// The comparison method to compare strings . - /// - /// - /// is null, or is null, - /// or does not end with . - /// - public static void EndsWith([NotNull] string? substring, [NotNull] string? value, string? message, StringComparison comparisonType) - => EndsWith(substring, value, comparisonType, message, null); + => EndsWith(substring, value, comparisonType, string.Empty); /// /// Tests whether the specified string ends with the specified substring @@ -140,20 +88,17 @@ public static void EndsWith([NotNull] string? substring, [NotNull] string? value /// does not end with . The message is /// shown in test results. /// - /// - /// An array of parameters to use when formatting . - /// /// /// is null, or is null, /// or does not start with . /// - public static void EndsWith([NotNull] string? substring, [NotNull] string? value, StringComparison comparisonType, [StringSyntax(StringSyntaxAttribute.CompositeFormat)] string? message, params object?[]? parameters) + public static void EndsWith([NotNull] string? substring, [NotNull] string? value, StringComparison comparisonType, string? message) { CheckParameterNotNull(value, "Assert.EndsWith", "value", string.Empty); CheckParameterNotNull(substring, "Assert.EndsWith", "substring", string.Empty); if (!value.EndsWith(substring, comparisonType)) { - string userMessage = BuildUserMessage(message, parameters); + string userMessage = BuildUserMessage(message); string finalMessage = string.Format(CultureInfo.CurrentCulture, FrameworkMessages.EndsWithFail, value, substring, userMessage); ThrowAssertFailed("Assert.EndsWith", finalMessage); } @@ -204,32 +149,6 @@ public static void DoesNotEndWith([NotNull] string? substring, [NotNull] string? public static void DoesNotEndWith([NotNull] string? substring, [NotNull] string? value, string? message) => DoesNotEndWith(substring, value, StringComparison.Ordinal, message); - /// - /// Tests whether the specified string does not end with the specified substring - /// and throws an exception if the test string does not end with the - /// substring. - /// - /// - /// The string expected not to be a suffix of . - /// - /// - /// The string that is expected not to end with . - /// - /// - /// The message to include in the exception when - /// ends with . The message is - /// shown in test results. - /// - /// - /// An array of parameters to use when formatting . - /// - /// - /// is null, or is null, - /// or ends with . - /// - public static void DoesNotEndWith([NotNull] string? substring, [NotNull] string? value, [StringSyntax(StringSyntaxAttribute.CompositeFormat)] string? message, params object?[]? parameters) - => DoesNotEndWith(substring, value, StringComparison.Ordinal, message, parameters); - /// /// Tests whether the specified string does not end with the specified substring /// and throws an exception if the test string does not end with the @@ -249,33 +168,7 @@ public static void DoesNotEndWith([NotNull] string? substring, [NotNull] string? /// or ends with . /// public static void DoesNotEndWith([NotNull] string? substring, [NotNull] string? value, StringComparison comparisonType) - => DoesNotEndWith(substring, value, comparisonType, string.Empty, null); - - /// - /// Tests whether the specified string does not end with the specified substring - /// and throws an exception if the test string does not end with the - /// substring. - /// - /// - /// The string expected not to be a suffix of . - /// - /// - /// The string that is expected not to end with . - /// - /// - /// The message to include in the exception when - /// ends with . The message is - /// shown in test results. - /// - /// - /// The comparison method to compare strings . - /// - /// - /// is null, or is null, - /// or ends with . - /// - public static void DoesNotEndWith([NotNull] string? substring, [NotNull] string? value, string? message, StringComparison comparisonType) - => DoesNotEndWith(substring, value, comparisonType, message, null); + => DoesNotEndWith(substring, value, comparisonType, string.Empty); /// /// Tests whether the specified string does not end with the specified substring @@ -296,21 +189,17 @@ public static void DoesNotEndWith([NotNull] string? substring, [NotNull] string? /// ends with . The message is /// shown in test results. /// - /// - /// An array of parameters to use when formatting . - /// /// /// is null, or is null, /// or ends with . /// - public static void DoesNotEndWith([NotNull] string? substring, [NotNull] string? value, StringComparison comparisonType, - [StringSyntax(StringSyntaxAttribute.CompositeFormat)] string? message, params object?[]? parameters) + public static void DoesNotEndWith([NotNull] string? substring, [NotNull] string? value, StringComparison comparisonType, string? message) { CheckParameterNotNull(value, "Assert.DoesNotEndWith", "value", string.Empty); CheckParameterNotNull(substring, "Assert.DoesNotEndWith", "substring", string.Empty); if (value.EndsWith(substring, comparisonType)) { - string userMessage = BuildUserMessage(message, parameters); + string userMessage = BuildUserMessage(message); string finalMessage = string.Format(CultureInfo.CurrentCulture, FrameworkMessages.DoesNotEndWithFail, value, substring, userMessage); ThrowAssertFailed("Assert.DoesNotEndWith", finalMessage); } diff --git a/src/TestFramework/TestFramework/Assertions/Assert.IComparable.cs b/src/TestFramework/TestFramework/Assertions/Assert.IComparable.cs index 84b3ac4051..fd8ccdbb98 100644 --- a/src/TestFramework/TestFramework/Assertions/Assert.IComparable.cs +++ b/src/TestFramework/TestFramework/Assertions/Assert.IComparable.cs @@ -30,7 +30,7 @@ public sealed partial class Assert /// public static void IsGreaterThan(T lowerBound, T value) where T : IComparable - => IsGreaterThan(lowerBound, value, string.Empty, null); + => IsGreaterThan(lowerBound, value, string.Empty); /// /// Tests whether the value is greater than the lower bound and throws an exception @@ -55,41 +55,13 @@ public static void IsGreaterThan(T lowerBound, T value) /// public static void IsGreaterThan(T lowerBound, T value, string? message) where T : IComparable - => IsGreaterThan(lowerBound, value, message, null); - - /// - /// Tests whether the value is greater than the lower bound and throws an exception - /// if it is not. - /// - /// - /// The type of values to compare. - /// - /// - /// The lower bound value that the value should exceed. - /// - /// - /// The value to compare. This is the value produced by the code under test. - /// - /// - /// The message to include in the exception when - /// is not greater than . The message is shown in - /// test results. - /// - /// - /// An array of parameters to use when formatting . - /// - /// - /// Thrown if is not greater than . - /// - public static void IsGreaterThan(T lowerBound, T value, [StringSyntax(StringSyntaxAttribute.CompositeFormat)] string? message, params object?[]? parameters) - where T : IComparable { if (value.CompareTo(lowerBound) > 0) { return; } - string userMessage = BuildUserMessage(message, parameters); + string userMessage = BuildUserMessage(message); ThrowAssertIsGreaterThanFailed(lowerBound, value, userMessage); } @@ -115,7 +87,7 @@ public static void IsGreaterThan(T lowerBound, T value, [StringSyntax(StringS /// public static void IsGreaterThanOrEqualTo(T lowerBound, T value) where T : IComparable - => IsGreaterThanOrEqualTo(lowerBound, value, string.Empty, null); + => IsGreaterThanOrEqualTo(lowerBound, value, string.Empty); /// /// Tests whether the value is greater than or equal to the lower bound and throws an exception @@ -140,41 +112,13 @@ public static void IsGreaterThanOrEqualTo(T lowerBound, T value) /// public static void IsGreaterThanOrEqualTo(T lowerBound, T value, string? message) where T : IComparable - => IsGreaterThanOrEqualTo(lowerBound, value, message, null); - - /// - /// Tests whether the value is greater than or equal to the lower bound and throws an exception - /// if it is not. - /// - /// - /// The type of values to compare. - /// - /// - /// The lower bound value that the value should meet or exceed. - /// - /// - /// The value to compare. This is the value produced by the code under test. - /// - /// - /// The message to include in the exception when - /// is not greater than or equal to . The message is shown in - /// test results. - /// - /// - /// An array of parameters to use when formatting . - /// - /// - /// Thrown if is not greater than or equal to . - /// - public static void IsGreaterThanOrEqualTo(T lowerBound, T value, [StringSyntax(StringSyntaxAttribute.CompositeFormat)] string? message, params object?[]? parameters) - where T : IComparable { if (value.CompareTo(lowerBound) >= 0) { return; } - string userMessage = BuildUserMessage(message, parameters); + string userMessage = BuildUserMessage(message); ThrowAssertIsGreaterThanOrEqualToFailed(lowerBound, value, userMessage); } @@ -200,7 +144,7 @@ public static void IsGreaterThanOrEqualTo(T lowerBound, T value, [StringSynta /// public static void IsLessThan(T upperBound, T value) where T : IComparable - => IsLessThan(upperBound, value, string.Empty, null); + => IsLessThan(upperBound, value, string.Empty); /// /// Tests whether the value is less than the upper bound and throws an exception @@ -225,41 +169,13 @@ public static void IsLessThan(T upperBound, T value) /// public static void IsLessThan(T upperBound, T value, string? message) where T : IComparable - => IsLessThan(upperBound, value, message, null); - - /// - /// Tests whether the value is less than the upper bound and throws an exception - /// if it is not. - /// - /// - /// The type of values to compare. - /// - /// - /// The upper bound value that the value should be less than. - /// - /// - /// The value to compare. This is the value produced by the code under test. - /// - /// - /// The message to include in the exception when - /// is not less than . The message is shown in - /// test results. - /// - /// - /// An array of parameters to use when formatting . - /// - /// - /// Thrown if is not less than . - /// - public static void IsLessThan(T upperBound, T value, [StringSyntax(StringSyntaxAttribute.CompositeFormat)] string? message, params object?[]? parameters) - where T : IComparable { if (value.CompareTo(upperBound) < 0) { return; } - string userMessage = BuildUserMessage(message, parameters); + string userMessage = BuildUserMessage(message); ThrowAssertIsLessThanFailed(upperBound, value, userMessage); } @@ -285,7 +201,7 @@ public static void IsLessThan(T upperBound, T value, [StringSyntax(StringSynt /// public static void IsLessThanOrEqualTo(T upperBound, T value) where T : IComparable - => IsLessThanOrEqualTo(upperBound, value, string.Empty, null); + => IsLessThanOrEqualTo(upperBound, value, string.Empty); /// /// Tests whether the value is less than or equal to the upper bound and throws an exception @@ -310,41 +226,13 @@ public static void IsLessThanOrEqualTo(T upperBound, T value) /// public static void IsLessThanOrEqualTo(T upperBound, T value, string? message) where T : IComparable - => IsLessThanOrEqualTo(upperBound, value, message, null); - - /// - /// Tests whether the value is less than or equal to the upper bound and throws an exception - /// if it is not. - /// - /// - /// The type of values to compare. - /// - /// - /// The upper bound value that the value should not exceed. - /// - /// - /// The value to compare. This is the value produced by the code under test. - /// - /// - /// The message to include in the exception when - /// is not less than or equal to . The message is shown in - /// test results. - /// - /// - /// An array of parameters to use when formatting . - /// - /// - /// Thrown if is not less than or equal to . - /// - public static void IsLessThanOrEqualTo(T upperBound, T value, [StringSyntax(StringSyntaxAttribute.CompositeFormat)] string? message, params object?[]? parameters) - where T : IComparable { if (value.CompareTo(upperBound) <= 0) { return; } - string userMessage = BuildUserMessage(message, parameters); + string userMessage = BuildUserMessage(message); ThrowAssertIsLessThanOrEqualToFailed(upperBound, value, userMessage); } @@ -367,7 +255,7 @@ public static void IsLessThanOrEqualTo(T upperBound, T value, [StringSyntax(S /// public static void IsPositive(T value) where T : struct, IComparable - => IsPositive(value, string.Empty, null); + => IsPositive(value, string.Empty); /// /// Tests whether the specified value is positive and throws an exception @@ -388,44 +276,20 @@ public static void IsPositive(T value) /// public static void IsPositive(T value, string? message) where T : struct, IComparable - => IsPositive(value, message, null); - - /// - /// Tests whether the specified value is positive and throws an exception - /// if it is not. - /// - /// - /// The type of value to test. - /// - /// - /// The value to test. - /// - /// - /// The message to include in the exception when - /// is not positive. The message is shown in test results. - /// - /// - /// An array of parameters to use when formatting . - /// - /// - /// Thrown if is not positive. - /// - public static void IsPositive(T value, [StringSyntax(StringSyntaxAttribute.CompositeFormat)] string? message, params object?[]? parameters) - where T : struct, IComparable { var zero = default(T); // Handle special case for floating point NaN values if (value is float floatValue && float.IsNaN(floatValue)) { - string userMessage = BuildUserMessage(message, parameters); + string userMessage = BuildUserMessage(message); ThrowAssertIsPositiveFailed(value, userMessage); return; } if (value is double doubleValue && double.IsNaN(doubleValue)) { - string userMessage = BuildUserMessage(message, parameters); + string userMessage = BuildUserMessage(message); ThrowAssertIsPositiveFailed(value, userMessage); return; } @@ -435,7 +299,7 @@ public static void IsPositive(T value, [StringSyntax(StringSyntaxAttribute.Co return; } - string userMessage2 = BuildUserMessage(message, parameters); + string userMessage2 = BuildUserMessage(message); ThrowAssertIsPositiveFailed(value, userMessage2); } @@ -458,7 +322,7 @@ public static void IsPositive(T value, [StringSyntax(StringSyntaxAttribute.Co /// public static void IsNegative(T value) where T : struct, IComparable - => IsNegative(value, string.Empty, null); + => IsNegative(value, string.Empty); /// /// Tests whether the specified value is negative and throws an exception @@ -479,44 +343,20 @@ public static void IsNegative(T value) /// public static void IsNegative(T value, string? message) where T : struct, IComparable - => IsNegative(value, message, null); - - /// - /// Tests whether the specified value is negative and throws an exception - /// if it is not. - /// - /// - /// The type of value to test. - /// - /// - /// The value to test. - /// - /// - /// The message to include in the exception when - /// is not negative. The message is shown in test results. - /// - /// - /// An array of parameters to use when formatting . - /// - /// - /// Thrown if is not negative. - /// - public static void IsNegative(T value, [StringSyntax(StringSyntaxAttribute.CompositeFormat)] string? message, params object?[]? parameters) - where T : struct, IComparable { var zero = default(T); // Handle special case for floating point NaN values if (value is float floatValue && float.IsNaN(floatValue)) { - string userMessage = BuildUserMessage(message, parameters); + string userMessage = BuildUserMessage(message); ThrowAssertIsNegativeFailed(value, userMessage); return; } if (value is double doubleValue && double.IsNaN(doubleValue)) { - string userMessage = BuildUserMessage(message, parameters); + string userMessage = BuildUserMessage(message); ThrowAssertIsNegativeFailed(value, userMessage); return; } @@ -526,7 +366,7 @@ public static void IsNegative(T value, [StringSyntax(StringSyntaxAttribute.Co return; } - string userMessage2 = BuildUserMessage(message, parameters); + string userMessage2 = BuildUserMessage(message); ThrowAssertIsNegativeFailed(value, userMessage2); } diff --git a/src/TestFramework/TestFramework/Assertions/Assert.Matches.cs b/src/TestFramework/TestFramework/Assertions/Assert.Matches.cs index df2c0d9b4e..f6725e27f4 100644 --- a/src/TestFramework/TestFramework/Assertions/Assert.Matches.cs +++ b/src/TestFramework/TestFramework/Assertions/Assert.Matches.cs @@ -23,7 +23,7 @@ public sealed partial class Assert /// or does not match . /// public static void MatchesRegex([NotNull] Regex? pattern, [NotNull] string? value) - => MatchesRegex(pattern, value, string.Empty, null); + => MatchesRegex(pattern, value, string.Empty); /// /// Tests whether the specified string MatchesRegex a regular expression and @@ -46,39 +46,13 @@ public static void MatchesRegex([NotNull] Regex? pattern, [NotNull] string? valu /// or does not match . /// public static void MatchesRegex([NotNull] Regex? pattern, [NotNull] string? value, string? message) - => MatchesRegex(pattern, value, message, null); - - /// - /// Tests whether the specified string MatchesRegex a regular expression and - /// throws an exception if the string does not match the expression. - /// - /// - /// The regular expression that is - /// expected to match. - /// - /// - /// The string that is expected to match . - /// - /// - /// The message to include in the exception when - /// does not match . The message is shown in - /// test results. - /// - /// - /// An array of parameters to use when formatting . - /// - /// - /// is null, or is null, - /// or does not match . - /// - public static void MatchesRegex([NotNull] Regex? pattern, [NotNull] string? value, [StringSyntax(StringSyntaxAttribute.CompositeFormat)] string? message, params object?[]? parameters) { CheckParameterNotNull(value, "Assert.MatchesRegex", "value", string.Empty); CheckParameterNotNull(pattern, "Assert.MatchesRegex", "pattern", string.Empty); if (!pattern.IsMatch(value)) { - string userMessage = BuildUserMessage(message, parameters); + string userMessage = BuildUserMessage(message); string finalMessage = string.Format(CultureInfo.CurrentCulture, FrameworkMessages.IsMatchFail, value, pattern, userMessage); ThrowAssertFailed("Assert.MatchesRegex", finalMessage); } @@ -100,7 +74,7 @@ public static void MatchesRegex([NotNull] Regex? pattern, [NotNull] string? valu /// or does not match . /// public static void MatchesRegex([NotNull] string? pattern, [NotNull] string? value) - => MatchesRegex(ToRegex(pattern), value, string.Empty, null); + => MatchesRegex(ToRegex(pattern), value, string.Empty); /// /// Tests whether the specified string MatchesRegex a regular expression and @@ -123,33 +97,7 @@ public static void MatchesRegex([NotNull] string? pattern, [NotNull] string? val /// or does not match . /// public static void MatchesRegex([NotNull] string? pattern, [NotNull] string? value, string? message) - => MatchesRegex(ToRegex(pattern), value, message, null); - - /// - /// Tests whether the specified string MatchesRegex a regular expression and - /// throws an exception if the string does not match the expression. - /// - /// - /// The regular expression that is - /// expected to match. - /// - /// - /// The string that is expected to match . - /// - /// - /// The message to include in the exception when - /// does not match . The message is shown in - /// test results. - /// - /// - /// An array of parameters to use when formatting . - /// - /// - /// is null, or is null, - /// or does not match . - /// - public static void MatchesRegex([NotNull] string? pattern, [NotNull] string? value, [StringSyntax(StringSyntaxAttribute.CompositeFormat)] string? message, params object?[]? parameters) - => MatchesRegex(ToRegex(pattern), value, message, parameters); + => MatchesRegex(ToRegex(pattern), value, message); #endregion // MatchesRegex @@ -194,39 +142,13 @@ public static void DoesNotMatchRegex([NotNull] Regex? pattern, [NotNull] string? /// or MatchesRegex . /// public static void DoesNotMatchRegex([NotNull] Regex? pattern, [NotNull] string? value, string? message) - => DoesNotMatchRegex(pattern, value, message, null); - - /// - /// Tests whether the specified string does not match a regular expression - /// and throws an exception if the string MatchesRegex the expression. - /// - /// - /// The regular expression that is - /// expected to not match. - /// - /// - /// The string that is expected not to match . - /// - /// - /// The message to include in the exception when - /// MatchesRegex . The message is shown in test - /// results. - /// - /// - /// An array of parameters to use when formatting . - /// - /// - /// is null, or is null, - /// or MatchesRegex . - /// - public static void DoesNotMatchRegex([NotNull] Regex? pattern, [NotNull] string? value, [StringSyntax(StringSyntaxAttribute.CompositeFormat)] string? message, params object?[]? parameters) { CheckParameterNotNull(value, "Assert.DoesNotMatchRegex", "value", string.Empty); CheckParameterNotNull(pattern, "Assert.DoesNotMatchRegex", "pattern", string.Empty); if (pattern.IsMatch(value)) { - string userMessage = BuildUserMessage(message, parameters); + string userMessage = BuildUserMessage(message); string finalMessage = string.Format(CultureInfo.CurrentCulture, FrameworkMessages.IsNotMatchFail, value, pattern, userMessage); ThrowAssertFailed("Assert.DoesNotMatchRegex", finalMessage); } @@ -248,7 +170,7 @@ public static void DoesNotMatchRegex([NotNull] Regex? pattern, [NotNull] string? /// or MatchesRegex . /// public static void DoesNotMatchRegex([NotNull] string? pattern, [NotNull] string? value) - => DoesNotMatchRegex(ToRegex(pattern), value, string.Empty, null); + => DoesNotMatchRegex(ToRegex(pattern), value, string.Empty); /// /// Tests whether the specified string does not match a regular expression @@ -271,33 +193,7 @@ public static void DoesNotMatchRegex([NotNull] string? pattern, [NotNull] string /// or MatchesRegex . /// public static void DoesNotMatchRegex([NotNull] string? pattern, [NotNull] string? value, string? message) - => DoesNotMatchRegex(ToRegex(pattern), value, message, null); - - /// - /// Tests whether the specified string does not match a regular expression - /// and throws an exception if the string MatchesRegex the expression. - /// - /// - /// The regular expression that is - /// expected to not match. - /// - /// - /// The string that is expected not to match . - /// - /// - /// The message to include in the exception when - /// MatchesRegex . The message is shown in test - /// results. - /// - /// - /// An array of parameters to use when formatting . - /// - /// - /// is null, or is null, - /// or MatchesRegex . - /// - public static void DoesNotMatchRegex([NotNull] string? pattern, [NotNull] string? value, [StringSyntax(StringSyntaxAttribute.CompositeFormat)] string? message, params object?[]? parameters) - => DoesNotMatchRegex(ToRegex(pattern), value, message, parameters); + => DoesNotMatchRegex(ToRegex(pattern), value, message); #endregion // DoesNotMatchRegex diff --git a/src/TestFramework/TestFramework/Assertions/Assert.StartsWith.cs b/src/TestFramework/TestFramework/Assertions/Assert.StartsWith.cs index abbae94d2b..57f9000b69 100644 --- a/src/TestFramework/TestFramework/Assertions/Assert.StartsWith.cs +++ b/src/TestFramework/TestFramework/Assertions/Assert.StartsWith.cs @@ -48,32 +48,6 @@ public static void StartsWith([NotNull] string? substring, [NotNull] string? val public static void StartsWith([NotNull] string? substring, [NotNull] string? value, string? message) => StartsWith(substring, value, StringComparison.Ordinal, message); - /// - /// Tests whether the specified string begins with the specified substring - /// and throws an exception if the test string does not start with the - /// substring. - /// - /// - /// The string expected to be a prefix of . - /// - /// - /// The string that is expected to begin with . - /// - /// - /// The message to include in the exception when - /// does not begin with . The message is - /// shown in test results. - /// - /// - /// An array of parameters to use when formatting . - /// - /// - /// is null, or is null, - /// or does not start with . - /// - public static void StartsWith([NotNull] string? substring, [NotNull] string? value, [StringSyntax(StringSyntaxAttribute.CompositeFormat)] string? message, params object?[]? parameters) - => StartsWith(substring, value, StringComparison.Ordinal, message, parameters); - /// /// Tests whether the specified string begins with the specified substring /// and throws an exception if the test string does not start with the @@ -93,33 +67,7 @@ public static void StartsWith([NotNull] string? substring, [NotNull] string? val /// or does not start with . /// public static void StartsWith([NotNull] string? substring, [NotNull] string? value, StringComparison comparisonType) - => StartsWith(substring, value, comparisonType, string.Empty, null); - - /// - /// Tests whether the specified string begins with the specified substring - /// and throws an exception if the test string does not start with the - /// substring. - /// - /// - /// The string expected to be a prefix of . - /// - /// - /// The string that is expected to begin with . - /// - /// - /// The message to include in the exception when - /// does not begin with . The message is - /// shown in test results. - /// - /// - /// The comparison method to compare strings . - /// - /// - /// is null, or is null, - /// or does not start with . - /// - public static void StartsWith([NotNull] string? substring, [NotNull] string? value, string? message, StringComparison comparisonType) - => StartsWith(substring, value, comparisonType, message, null); + => StartsWith(substring, value, comparisonType, string.Empty); /// /// Tests whether the specified string begins with the specified substring @@ -140,20 +88,17 @@ public static void StartsWith([NotNull] string? substring, [NotNull] string? val /// does not begin with . The message is /// shown in test results. /// - /// - /// An array of parameters to use when formatting . - /// /// /// is null, or is null, /// or does not start with . /// - public static void StartsWith([NotNull] string? substring, [NotNull] string? value, StringComparison comparisonType, [StringSyntax(StringSyntaxAttribute.CompositeFormat)] string? message, params object?[]? parameters) + public static void StartsWith([NotNull] string? substring, [NotNull] string? value, StringComparison comparisonType, string? message) { CheckParameterNotNull(value, "Assert.StartsWith", "value", string.Empty); CheckParameterNotNull(substring, "Assert.StartsWith", "substring", string.Empty); if (!value.StartsWith(substring, comparisonType)) { - string userMessage = BuildUserMessage(message, parameters); + string userMessage = BuildUserMessage(message); string finalMessage = string.Format(CultureInfo.CurrentCulture, FrameworkMessages.StartsWithFail, value, substring, userMessage); ThrowAssertFailed("Assert.StartsWith", finalMessage); } @@ -202,31 +147,6 @@ public static void DoesNotStartWith([NotNull] string? substring, [NotNull] strin public static void DoesNotStartWith([NotNull] string? substring, [NotNull] string? value, string? message) => DoesNotStartWith(substring, value, StringComparison.Ordinal, message); - /// - /// Tests whether the specified string does not begin with the specified substring - /// and throws an exception if the test string does start with the substring. - /// - /// - /// The string expected to be a prefix of . - /// - /// - /// The string that is expected to begin with . - /// - /// - /// The message to include in the exception when - /// does not begin with . The message is - /// shown in test results. - /// - /// - /// An array of parameters to use when formatting . - /// - /// - /// is null, or is null, - /// or does not start with . - /// - public static void DoesNotStartWith([NotNull] string? substring, [NotNull] string? value, [StringSyntax(StringSyntaxAttribute.CompositeFormat)] string? message, params object?[]? parameters) - => DoesNotStartWith(substring, value, StringComparison.Ordinal, message, parameters); - /// /// Tests whether the specified string does not begin with the specified substring /// and throws an exception if the test string does start with the substring. @@ -245,32 +165,7 @@ public static void DoesNotStartWith([NotNull] string? substring, [NotNull] strin /// or does not start with . /// public static void DoesNotStartWith([NotNull] string? substring, [NotNull] string? value, StringComparison comparisonType) - => DoesNotStartWith(substring, value, comparisonType, string.Empty, null); - - /// - /// Tests whether the specified string does not begin with the specified substring - /// and throws an exception if the test string does start with the substring. - /// - /// - /// The string expected to be a prefix of . - /// - /// - /// The string that is expected to begin with . - /// - /// - /// The message to include in the exception when - /// does not begin with . The message is - /// shown in test results. - /// - /// - /// The comparison method to compare strings . - /// - /// - /// is null, or is null, - /// or does not start with . - /// - public static void DoesNotStartWith([NotNull] string? substring, [NotNull] string? value, string? message, StringComparison comparisonType) - => DoesNotStartWith(substring, value, comparisonType, message, null); + => DoesNotStartWith(substring, value, comparisonType, string.Empty); /// /// Tests whether the specified string does not begin with the specified substring @@ -290,21 +185,17 @@ public static void DoesNotStartWith([NotNull] string? substring, [NotNull] strin /// does not begin with . The message is /// shown in test results. /// - /// - /// An array of parameters to use when formatting . - /// /// /// is null, or is null, /// or does not start with . /// - public static void DoesNotStartWith([NotNull] string? substring, [NotNull] string? value, StringComparison comparisonType, - [StringSyntax(StringSyntaxAttribute.CompositeFormat)] string? message, params object?[]? parameters) + public static void DoesNotStartWith([NotNull] string? substring, [NotNull] string? value, StringComparison comparisonType, string? message) { CheckParameterNotNull(value, "Assert.DoesNotStartWith", "value", string.Empty); CheckParameterNotNull(substring, "Assert.DoesNotStartWith", "substring", string.Empty); if (value.StartsWith(substring, comparisonType)) { - string userMessage = BuildUserMessage(message, parameters); + string userMessage = BuildUserMessage(message); string finalMessage = string.Format(CultureInfo.CurrentCulture, FrameworkMessages.DoesNotStartWithFail, value, substring, userMessage); ThrowAssertFailed("Assert.DoesNotStartWith", finalMessage); } diff --git a/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Unshipped.txt b/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Unshipped.txt index 6c8d629e1f..1ba4542dc0 100644 --- a/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Unshipped.txt +++ b/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Unshipped.txt @@ -3,66 +3,46 @@ Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AssertNonStrictThrowsInterpo Microsoft.VisualStudio.TestTools.UnitTesting.ConditionBaseAttribute.Mode.get -> Microsoft.VisualStudio.TestTools.UnitTesting.ConditionMode static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsGreaterThan(T lowerBound, T value) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsGreaterThan(T lowerBound, T value, string? message) -> void -static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsGreaterThan(T lowerBound, T value, string? message, params object?[]? parameters) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsGreaterThanOrEqualTo(T lowerBound, T value) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsGreaterThanOrEqualTo(T lowerBound, T value, string? message) -> void -static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsGreaterThanOrEqualTo(T lowerBound, T value, string? message, params object?[]? parameters) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.Instance.get -> Microsoft.VisualStudio.TestTools.UnitTesting.Assert! static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.Contains(System.Func! predicate, System.Collections.Generic.IEnumerable! collection, string? message) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.DoesNotEndWith(string? substring, string? value) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.DoesNotEndWith(string? substring, string? value, string? message) -> void -static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.DoesNotEndWith(string? substring, string? value, string? message, params object?[]? parameters) -> void -static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.DoesNotEndWith(string? substring, string? value, string? message, System.StringComparison comparisonType) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.DoesNotEndWith(string? substring, string? value, System.StringComparison comparisonType) -> void -static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.DoesNotEndWith(string? substring, string? value, System.StringComparison comparisonType, string? message, params object?[]? parameters) -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.DoesNotEndWith(string? substring, string? value, System.StringComparison comparisonType, string? message) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.DoesNotMatchRegex(string? pattern, string? value) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.DoesNotMatchRegex(string? pattern, string? value, string? message) -> void -static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.DoesNotMatchRegex(string? pattern, string? value, string? message, params object?[]? parameters) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.DoesNotMatchRegex(System.Text.RegularExpressions.Regex? pattern, string? value) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.DoesNotMatchRegex(System.Text.RegularExpressions.Regex? pattern, string? value, string? message) -> void -static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.DoesNotMatchRegex(System.Text.RegularExpressions.Regex? pattern, string? value, string? message, params object?[]? parameters) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.DoesNotStartWith(string? substring, string? value) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.DoesNotStartWith(string? substring, string? value, string? message) -> void -static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.DoesNotStartWith(string? substring, string? value, string? message, params object?[]? parameters) -> void -static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.DoesNotStartWith(string? substring, string? value, string? message, System.StringComparison comparisonType) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.DoesNotStartWith(string? substring, string? value, System.StringComparison comparisonType) -> void -static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.DoesNotStartWith(string? substring, string? value, System.StringComparison comparisonType, string? message, params object?[]? parameters) -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.DoesNotStartWith(string? substring, string? value, System.StringComparison comparisonType, string? message) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.EndsWith(string? substring, string? value) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.EndsWith(string? substring, string? value, string? message) -> void -static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.EndsWith(string? substring, string? value, string? message, params object?[]? parameters) -> void -static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.EndsWith(string? substring, string? value, string? message, System.StringComparison comparisonType) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.EndsWith(string? substring, string? value, System.StringComparison comparisonType) -> void -static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.EndsWith(string? substring, string? value, System.StringComparison comparisonType, string? message, params object?[]? parameters) -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.EndsWith(string? substring, string? value, System.StringComparison comparisonType, string? message) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsInRange(T minValue, T maxValue, T value) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsInRange(T minValue, T maxValue, T value, string? message) -> void -static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsInRange(T minValue, T maxValue, T value, string? message, params object?[]? parameters) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.ContainsSingle(System.Func! predicate, System.Collections.Generic.IEnumerable! collection) -> T static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.ContainsSingle(System.Func! predicate, System.Collections.Generic.IEnumerable! collection, string? message) -> T -static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.ContainsSingle(System.Func! predicate, System.Collections.Generic.IEnumerable! collection, string? message, params object?[]? parameters) -> T static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsLessThan(T upperBound, T value) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsLessThan(T upperBound, T value, string? message) -> void -static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsLessThan(T upperBound, T value, string? message, params object?[]? parameters) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsLessThanOrEqualTo(T upperBound, T value) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsLessThanOrEqualTo(T upperBound, T value, string? message) -> void -static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsLessThanOrEqualTo(T upperBound, T value, string? message, params object?[]? parameters) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsNegative(T value) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsNegative(T value, string? message) -> void -static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsNegative(T value, string? message, params object?[]? parameters) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsPositive(T value) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsPositive(T value, string? message) -> void -static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsPositive(T value, string? message, params object?[]? parameters) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.MatchesRegex(string? pattern, string? value) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.MatchesRegex(string? pattern, string? value, string? message) -> void -static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.MatchesRegex(string? pattern, string? value, string? message, params object?[]? parameters) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.MatchesRegex(System.Text.RegularExpressions.Regex? pattern, string? value) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.MatchesRegex(System.Text.RegularExpressions.Regex? pattern, string? value, string? message) -> void -static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.MatchesRegex(System.Text.RegularExpressions.Regex? pattern, string? value, string? message, params object?[]? parameters) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.StartsWith(string? substring, string? value) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.StartsWith(string? substring, string? value, string? message) -> void -static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.StartsWith(string? substring, string? value, string? message, params object?[]? parameters) -> void -static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.StartsWith(string? substring, string? value, string? message, System.StringComparison comparisonType) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.StartsWith(string? substring, string? value, System.StringComparison comparisonType) -> void -static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.StartsWith(string? substring, string? value, System.StringComparison comparisonType, string? message, params object?[]? parameters) -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.StartsWith(string? substring, string? value, System.StringComparison comparisonType, string? message) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.Throws(System.Func! action, ref Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AssertNonStrictThrowsInterpolatedStringHandler message) -> TException! static Microsoft.VisualStudio.TestTools.UnitTesting.CollectionAssert.Instance.get -> Microsoft.VisualStudio.TestTools.UnitTesting.CollectionAssert! static Microsoft.VisualStudio.TestTools.UnitTesting.StringAssert.Instance.get -> Microsoft.VisualStudio.TestTools.UnitTesting.StringAssert! diff --git a/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.Contains.cs b/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.Contains.cs index 6d885b74fc..a652e9aa40 100644 --- a/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.Contains.cs +++ b/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.Contains.cs @@ -665,13 +665,13 @@ public void ContainsSinglePredicate_MultipleItemsMatch_ThrowsException() /// Tests the ContainsSingle method with predicate and formatted message when no elements match. /// Expects an exception with the custom message. /// - public void ContainsSinglePredicate_WithMessageAndParams_NoItemMatches_ThrowsException() + public void ContainsSinglePredicate_WithMessage_NoItemMatches_ThrowsException() { // Arrange var collection = new List { 1, 3, 5 }; // Act - Action action = () => Assert.ContainsSingle(x => x % 2 == 0, collection, "No even numbers found in collection with {0} items", collection.Count); + Action action = () => Assert.ContainsSingle(x => x % 2 == 0, collection, $"No even numbers found in collection with {collection.Count} items"); // Assert action.Should().Throw().WithMessage("*No even numbers found in collection with 3 items*"); @@ -681,13 +681,13 @@ public void ContainsSinglePredicate_WithMessageAndParams_NoItemMatches_ThrowsExc /// Tests the ContainsSingle method with predicate and formatted message when multiple elements match. /// Expects an exception with the custom message. /// - public void ContainsSinglePredicate_WithMessageAndParams_MultipleItemsMatch_ThrowsException() + public void ContainsSinglePredicate_WithMessage_MultipleItemsMatch_ThrowsException() { // Arrange var collection = new List { 2, 4, 6 }; // Act - Action action = () => Assert.ContainsSingle(x => x % 2 == 0, collection, "Too many even numbers found: {0}", collection.Count); + Action action = () => Assert.ContainsSingle(x => x % 2 == 0, collection, $"Too many even numbers found: {collection.Count}"); // Assert action.Should().Throw().WithMessage("*Too many even numbers found: 3*"); diff --git a/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.IComparableTests.cs b/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.IComparableTests.cs index 113d6cfc05..33267fd00f 100644 --- a/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.IComparableTests.cs +++ b/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.IComparableTests.cs @@ -45,16 +45,6 @@ public void IsGreaterThanShouldThrowWithMessage() .WithMessage("Assert.IsGreaterThan failed. Actual value <5> is not greater than expected value <10>. A Message"); } - public void IsGreaterThanShouldThrowWithMessageAndParameters() - { - // Act - Action action = () => Assert.IsGreaterThan(10, 5, "A Message {0}", "param"); - - // Assert - action.Should().Throw() - .WithMessage("Assert.IsGreaterThan failed. Actual value <5> is not greater than expected value <10>. A Message param"); - } - public void IsGreaterThanShouldWorkWithDoubles() => Assert.IsGreaterThan(5.0, 5.5); @@ -99,16 +89,6 @@ public void IsGreaterThanOrEqualToShouldThrowWithMessage() .WithMessage("Assert.IsGreaterThanOrEqualTo failed. Actual value <5> is not greater than or equal to expected value <10>. A Message"); } - public void IsGreaterThanOrEqualToShouldThrowWithMessageAndParameters() - { - // Act - Action action = () => Assert.IsGreaterThanOrEqualTo(10, 5, "A Message {0}", "param"); - - // Assert - action.Should().Throw() - .WithMessage("Assert.IsGreaterThanOrEqualTo failed. Actual value <5> is not greater than or equal to expected value <10>. A Message param"); - } - public void IsGreaterThanOrEqualToShouldWorkWithDoubles() => Assert.IsGreaterThanOrEqualTo(5.0, 5.5); @@ -153,16 +133,6 @@ public void IsLessThanShouldThrowWithMessage() .WithMessage("Assert.IsLessThan failed. Actual value <10> is not less than expected value <5>. A Message"); } - public void IsLessThanShouldThrowWithMessageAndParameters() - { - // Act - Action action = () => Assert.IsLessThan(5, 10, "A Message {0}", "param"); - - // Assert - action.Should().Throw() - .WithMessage("Assert.IsLessThan failed. Actual value <10> is not less than expected value <5>. A Message param"); - } - public void IsLessThanShouldWorkWithDoubles() => Assert.IsLessThan(5.5, 5.0); @@ -207,16 +177,6 @@ public void IsLessThanOrEqualToShouldThrowWithMessage() .WithMessage("Assert.IsLessThanOrEqualTo failed. Actual value <10> is not less than or equal to expected value <5>. A Message"); } - public void IsLessThanOrEqualToShouldThrowWithMessageAndParameters() - { - // Act - Action action = () => Assert.IsLessThanOrEqualTo(5, 10, "A Message {0}", "param"); - - // Assert - action.Should().Throw() - .WithMessage("Assert.IsLessThanOrEqualTo failed. Actual value <10> is not less than or equal to expected value <5>. A Message param"); - } - public void IsLessThanOrEqualToShouldWorkWithDoubles() => Assert.IsLessThanOrEqualTo(5.5, 5.0); @@ -276,16 +236,6 @@ public void IsPositiveShouldThrowWithMessage() .WithMessage("Assert.IsPositive failed. Expected value <-5> to be positive. A Message"); } - public void IsPositiveShouldThrowWithMessageAndParameters() - { - // Act - Action action = () => Assert.IsPositive(-5, "A Message {0}", "param"); - - // Assert - action.Should().Throw() - .WithMessage("Assert.IsPositive failed. Expected value <-5> to be positive. A Message param"); - } - public void IsPositiveShouldWorkWithDoubles() => Assert.IsPositive(5.5); @@ -351,16 +301,6 @@ public void IsNegativeShouldThrowWithMessage() .WithMessage("Assert.IsNegative failed. Expected value <5> to be negative. A Message"); } - public void IsNegativeShouldThrowWithMessageAndParameters() - { - // Act - Action action = () => Assert.IsNegative(5, "A Message {0}", "param"); - - // Assert - action.Should().Throw() - .WithMessage("Assert.IsNegative failed. Expected value <5> to be negative. A Message param"); - } - public void IsNegativeShouldWorkWithDoubles() => Assert.IsNegative(-5.5); diff --git a/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.IsInRange.cs b/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.IsInRange.cs index 16922019d8..ece5567727 100644 --- a/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.IsInRange.cs +++ b/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.IsInRange.cs @@ -88,17 +88,16 @@ public void IsInRange_WithCustomMessage_IncludesCustomMessage() .And.Contain(customMessage); } - public void IsInRange_WithMessageAndParameters_FormatsMessage() + public void IsInRange_WithMessage_FormatsMessage() { // Arrange int minValue = 1; int maxValue = 5; int value = 10; - string messageFormat = "Test with parameter: {0}"; - string parameter = "TestValue"; + string message = "Test with parameter: TestValue"; // Act - Action action = () => Assert.IsInRange(minValue, maxValue, value, messageFormat, parameter); + Action action = () => Assert.IsInRange(minValue, maxValue, value, message); // Assert action.Should().ThrowExactly() @@ -176,7 +175,7 @@ public void IsInRange_WithEmptyMessage_DoesNotThrow() Assert.IsInRange(minValue, maxValue, value, string.Empty); } - public void IsInRange_WithNullParameters_DoesNotThrow() + public void IsInRange_WithMessage_DoesNotThrow() { // Arrange int minValue = 1; @@ -184,7 +183,7 @@ public void IsInRange_WithNullParameters_DoesNotThrow() int value = 3; // Act & Assert - Assert.IsInRange(minValue, maxValue, value, "Test message", null); + Assert.IsInRange(minValue, maxValue, value, "Test message"); } public void IsInRange_WithAllNegativeValuesInRange_DoesNotThrow() diff --git a/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.Items.cs b/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.Items.cs index 2f5ece1027..46dba4d95f 100644 --- a/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.Items.cs +++ b/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.Items.cs @@ -161,17 +161,17 @@ public void SinglePredicate_WhenMultipleItemsMatch_ShouldFail() Verify(ex.Message == "Assert.ContainsSingle failed. Expected exactly one item to match the predicate but found 3 item(s). "); } - public void SinglePredicate_MessageArgs_WhenNoItemMatches_ShouldFail() + public void SinglePredicate_Message_WhenNoItemMatches_ShouldFail() { var collection = new List { 1, 3, 5 }; - Exception ex = VerifyThrows(() => Assert.ContainsSingle(x => x % 2 == 0, collection, "No even numbers found: {0}", "test")); + Exception ex = VerifyThrows(() => Assert.ContainsSingle(x => x % 2 == 0, collection, "No even numbers found: test")); Verify(ex.Message == "Assert.ContainsSingle failed. Expected exactly one item to match the predicate but found 0 item(s). No even numbers found: test"); } - public void SinglePredicate_MessageArgs_WhenMultipleItemsMatch_ShouldFail() + public void SinglePredicate_Message_WhenMultipleItemsMatch_ShouldFail() { var collection = new List { 2, 4, 6 }; - Exception ex = VerifyThrows(() => Assert.ContainsSingle(x => x % 2 == 0, collection, "Too many even numbers: {0}", "test")); + Exception ex = VerifyThrows(() => Assert.ContainsSingle(x => x % 2 == 0, collection, "Too many even numbers: test")); Verify(ex.Message == "Assert.ContainsSingle failed. Expected exactly one item to match the predicate but found 3 item(s). Too many even numbers: test"); } From bfd49ef4f34334c0cc6b13d164f834913577427c Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Tue, 24 Jun 2025 22:22:36 +0200 Subject: [PATCH 126/541] Bump UseNewerAssertThrowsAnalyzer to warning (#5863) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Amaury Levé --- src/Analyzers/MSTest.Analyzers/AnalyzerReleases.Unshipped.md | 1 + src/Analyzers/MSTest.Analyzers/UseNewerAssertThrowsAnalyzer.cs | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/src/Analyzers/MSTest.Analyzers/AnalyzerReleases.Unshipped.md b/src/Analyzers/MSTest.Analyzers/AnalyzerReleases.Unshipped.md index e2dae0b108..a3ed571d22 100644 --- a/src/Analyzers/MSTest.Analyzers/AnalyzerReleases.Unshipped.md +++ b/src/Analyzers/MSTest.Analyzers/AnalyzerReleases.Unshipped.md @@ -14,3 +14,4 @@ MSTEST0045 | Usage | Info | UseCooperativeCancellationForTimeoutAnalyzer, [Docum Rule ID | New Category | New Severity | Old Category | Old Severity | Notes --------|--------------|--------------|--------------|--------------|------- MSTEST0006 | Design | Warning | Design | Info | AvoidExpectedExceptionAttributeAnalyzer +MSTEST0039 | Usage | Warning | Usage | Info | UseNewerAssertThrowsAnalyzer diff --git a/src/Analyzers/MSTest.Analyzers/UseNewerAssertThrowsAnalyzer.cs b/src/Analyzers/MSTest.Analyzers/UseNewerAssertThrowsAnalyzer.cs index d28aa7890f..0888a9d72d 100644 --- a/src/Analyzers/MSTest.Analyzers/UseNewerAssertThrowsAnalyzer.cs +++ b/src/Analyzers/MSTest.Analyzers/UseNewerAssertThrowsAnalyzer.cs @@ -28,7 +28,7 @@ internal sealed class UseNewerAssertThrowsAnalyzer : DiagnosticAnalyzer MessageFormat, null, Category.Usage, - DiagnosticSeverity.Info, + DiagnosticSeverity.Warning, isEnabledByDefault: true); public override ImmutableArray SupportedDiagnostics { get; } From a9a538aac5f47fd6cab4d0ff45b41bb38825d4ae Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Wed, 25 Jun 2025 09:33:01 +0200 Subject: [PATCH 127/541] Remove unused internal property TestMethod.UniqueName (#5872) --- .../MSTestAdapter.PlatformServices/ObjectModel/TestMethod.cs | 5 ----- 1 file changed, 5 deletions(-) diff --git a/src/Adapter/MSTestAdapter.PlatformServices/ObjectModel/TestMethod.cs b/src/Adapter/MSTestAdapter.PlatformServices/ObjectModel/TestMethod.cs index 47a5affb94..92eaf123e3 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/ObjectModel/TestMethod.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/ObjectModel/TestMethod.cs @@ -171,10 +171,5 @@ public string? DeclaringClassFullName /// internal string DisplayName { get; } - internal string UniqueName - => HasManagedMethodAndTypeProperties - ? $"{ManagedTypeName}.{ManagedMethodName}->{string.Join(", ", SerializedData ?? [])}" - : $"{FullClassName}.{Name}->{string.Join(", ", SerializedData ?? [])}"; - internal TestMethod Clone() => (TestMethod)MemberwiseClone(); } From 302590cff8c54e6109ab7b1bdef8535568f0a52e Mon Sep 17 00:00:00 2001 From: dotnet bot Date: Wed, 25 Jun 2025 11:35:18 +0200 Subject: [PATCH 128/541] Localized file check-in by OneLocBuild Task: Build definition ID 1218: Build ID 2737072 --- .../MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ja.xlf | 2 +- .../xlf/CodeFixResources.pt-BR.xlf | 2 +- .../MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ru.xlf | 2 +- .../xlf/CodeFixResources.zh-Hant.xlf | 2 +- src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf | 6 +++--- src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf | 6 +++--- src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf | 6 +++--- src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf | 6 +++--- 8 files changed, 16 insertions(+), 16 deletions(-) diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ja.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ja.xlf index 8b5bea42f0..0201230d7f 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ja.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ja.xlf @@ -99,7 +99,7 @@ Use 'CooperativeCancellation = true' - Use 'CooperativeCancellation = true' + 'CooperativeCancellation = true' を使用する diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pt-BR.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pt-BR.xlf index 13b834c897..778df4c30c 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pt-BR.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pt-BR.xlf @@ -99,7 +99,7 @@ Use 'CooperativeCancellation = true' - Use 'CooperativeCancellation = true' + Usar “CooperativoCancellation = true” diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ru.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ru.xlf index 938bb14017..f8c0562a03 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ru.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ru.xlf @@ -99,7 +99,7 @@ Use 'CooperativeCancellation = true' - Use 'CooperativeCancellation = true' + Использовать "CooperativeCancellation = true" diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hant.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hant.xlf index f09f986525..fe3a40e80f 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hant.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hant.xlf @@ -99,7 +99,7 @@ Use 'CooperativeCancellation = true' - Use 'CooperativeCancellation = true' + 使用 'CooperativeCancellation = true' diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf index dc2f115821..8ee1495b52 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf @@ -781,17 +781,17 @@ Anche il tipo che dichiara questi metodi deve rispettare le regole seguenti: Using '[Timeout]' without explicitly setting 'CooperativeCancellation = true' is discouraged. In a future version, cooperative cancellation will become the default behavior. Set 'CooperativeCancellation = true' to opt into the recommended behavior and avoid breaking changes. - Using '[Timeout]' without explicitly setting 'CooperativeCancellation = true' is discouraged. In a future version, cooperative cancellation will become the default behavior. Set 'CooperativeCancellation = true' to opt into the recommended behavior and avoid breaking changes. + L'uso di "[Timeout]" senza impostare esplicitamente "CooperativeCancellation = true" è sconsigliato. In una versione futura l'annullamento cooperativo diventerà il comportamento predefinito. Impostare "CooperativeCancellation = true" per acconsentire esplicitamente al comportamento consigliato ed evitare modifiche che causano un'interruzione. Use 'CooperativeCancellation = true' with '[Timeout]' to enable cooperative cancellation behavior - Use 'CooperativeCancellation = true' with '[Timeout]' to enable cooperative cancellation behavior + Usare "CooperativeCancellation = true" con "[Timeout]" per abilitare il comportamento di annullamento cooperativo Use 'CooperativeCancellation = true' with '[Timeout]' - Use 'CooperativeCancellation = true' with '[Timeout]' + Usa "CooperativeCancellation = true" con "[Timeout]" diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf index dedfbc8403..21bde27a71 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf @@ -781,17 +781,17 @@ The type declaring these methods should also respect the following rules: Using '[Timeout]' without explicitly setting 'CooperativeCancellation = true' is discouraged. In a future version, cooperative cancellation will become the default behavior. Set 'CooperativeCancellation = true' to opt into the recommended behavior and avoid breaking changes. - Using '[Timeout]' without explicitly setting 'CooperativeCancellation = true' is discouraged. In a future version, cooperative cancellation will become the default behavior. Set 'CooperativeCancellation = true' to opt into the recommended behavior and avoid breaking changes. + 'CooperativeCancellation = true' を明示的にを設定せずに '[Timeout]' を使用することは推奨されません。将来のバージョンでは、協調的キャンセルが既定の動作になります。推奨される動作をオプトインし、破壊的な変更を避けるために、'CooperativeCancellation = true' を設定します。 Use 'CooperativeCancellation = true' with '[Timeout]' to enable cooperative cancellation behavior - Use 'CooperativeCancellation = true' with '[Timeout]' to enable cooperative cancellation behavior + '[Timeout]' と共に 'CooperativeCancellation = true' を使用して、協調的キャンセルの動作を有効にします Use 'CooperativeCancellation = true' with '[Timeout]' - Use 'CooperativeCancellation = true' with '[Timeout]' + '[Timeout]' と共に 'CooperativeCancellation = true' を使用する diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf index 11a5dd39a3..89f45468d0 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf @@ -793,17 +793,17 @@ The type declaring these methods should also respect the following rules: Using '[Timeout]' without explicitly setting 'CooperativeCancellation = true' is discouraged. In a future version, cooperative cancellation will become the default behavior. Set 'CooperativeCancellation = true' to opt into the recommended behavior and avoid breaking changes. - Using '[Timeout]' without explicitly setting 'CooperativeCancellation = true' is discouraged. In a future version, cooperative cancellation will become the default behavior. Set 'CooperativeCancellation = true' to opt into the recommended behavior and avoid breaking changes. + Использование "[Timeout]" без явной настройки "CooperativeCancellation = true" не рекомендуется. В будущей версии кооперативная отмена станет поведением по умолчанию. Настройте "CooperativeCancellation = true", чтобы согласиться с рекомендуемым поведением и избежать критических изменений. Use 'CooperativeCancellation = true' with '[Timeout]' to enable cooperative cancellation behavior - Use 'CooperativeCancellation = true' with '[Timeout]' to enable cooperative cancellation behavior + Используйте "CooperativeCancellation = true" с "[Timeout]", чтобы включить поведение кооперативной отмены Use 'CooperativeCancellation = true' with '[Timeout]' - Use 'CooperativeCancellation = true' with '[Timeout]' + Использовать "CooperativeCancellation = true" с "[Timeout]" diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf index 9e6690d134..b653fa674b 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf @@ -781,17 +781,17 @@ The type declaring these methods should also respect the following rules: Using '[Timeout]' without explicitly setting 'CooperativeCancellation = true' is discouraged. In a future version, cooperative cancellation will become the default behavior. Set 'CooperativeCancellation = true' to opt into the recommended behavior and avoid breaking changes. - Using '[Timeout]' without explicitly setting 'CooperativeCancellation = true' is discouraged. In a future version, cooperative cancellation will become the default behavior. Set 'CooperativeCancellation = true' to opt into the recommended behavior and avoid breaking changes. + 在未明確設定 'CooperativeCancellation = true' 的情況下,不建議使用 '[Timeout]'。在未來的版本中,合作取消將成為預設行為。請設定 'CooperativeCancellation = true' 以選擇加入推薦的行為,並避免破壞性變更。 Use 'CooperativeCancellation = true' with '[Timeout]' to enable cooperative cancellation behavior - Use 'CooperativeCancellation = true' with '[Timeout]' to enable cooperative cancellation behavior + 使用 'CooperativeCancellation = true' 搭配 '[Timeout]' 以啟用合作取消行為 Use 'CooperativeCancellation = true' with '[Timeout]' - Use 'CooperativeCancellation = true' with '[Timeout]' + 使用 'CellCancellation = true' 搭配 '[Timeout]' From 7049918f669c2d1c5a8a79b71b8316690cb6a735 Mon Sep 17 00:00:00 2001 From: dotnet bot Date: Wed, 25 Jun 2025 11:39:26 +0200 Subject: [PATCH 129/541] Localized file check-in by OneLocBuild Task: Build definition ID 1218: Build ID 2737072 --- .../Resources/xlf/FrameworkMessages.ru.xlf | 46 +++++++++---------- 1 file changed, 23 insertions(+), 23 deletions(-) diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ru.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ru.xlf index 1419629d43..3b53ea9cad 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ru.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ru.xlf @@ -84,22 +84,22 @@ Expected collection to contain the specified item. {0} - Expected collection to contain the specified item. {0} + Ожидалось, что коллекция будет содержать указанный элемент. {0} Expected at least one item to match the predicate. {0} - Expected at least one item to match the predicate. {0} + Ожидался по крайней мере один элемент, соответствующий предикату. {0} Expected collection to contain exactly one element but found {1} element(s). {0} - Expected collection to contain exactly one element but found {1} element(s). {0} + Ожидалось, что коллекция будет содержать ровно один элемент, но найдено элементов: {1}. {0} Expected exactly one item to match the predicate but found {1} item(s). {0} - Expected exactly one item to match the predicate but found {1} item(s). {0} + Ожидался ровно один элемент, соответствующий предикату, но найдено элементов: {1}. {0} @@ -109,22 +109,22 @@ Expected collection to not contain the specified item. {0} - Expected collection to not contain the specified item. {0} + Ожидалось, что коллекция не будет содержать указанный элемент. {0} Expected no items to match the predicate. {0} - Expected no items to match the predicate. {0} + Ожидалось, что ни один элемент не будет соответствовать предикату. {0} String '{0}' ends with string '{1}'. {2} - String '{0}' ends with string '{1}'. {2} + Строка "{0}" заканчивается строкой "{1}". {2} String '{0}' starts with string '{1}'. {2} - String '{0}' starts with string '{1}'. {2} + Строка "{0}" начинается со строки "{1}". {2} @@ -163,7 +163,7 @@ Actual: {2} String '{0}' does not end with string '{1}'. {2} - String '{0}' does not end with string '{1}'. {2} + Строка "{0}" не заканчивается строкой "{1}". {2} @@ -193,7 +193,7 @@ Actual: {2} String '{0}' does not match pattern '{1}'. {2} - String '{0}' does not match pattern '{1}'. {2} + Строка "{0}" не соответствует шаблону "{1}". {2} @@ -208,7 +208,7 @@ Actual: {2} String '{0}' matches pattern '{1}'. {2} - String '{0}' matches pattern '{1}'. {2} + Строка "{0}" соответствует шаблону "{1}". {2} @@ -249,7 +249,7 @@ Actual: {2} String '{0}' does not start with string '{1}'. {2} - String '{0}' does not start with string '{1}'. {2} + Строка "{0}" не начинается со строки "{1}". {2} @@ -352,32 +352,32 @@ Actual: {2} Actual value <{2}> is not greater than expected value <{1}>. {0} - Actual value <{2}> is not greater than expected value <{1}>. {0} + Действительное значение <{2}> не больше ожидаемого значения <{1}>. {0} Actual value <{2}> is not greater than or equal to expected value <{1}>. {0} - Actual value <{2}> is not greater than or equal to expected value <{1}>. {0} + Действительное значение <{2}> не больше или не равно ожидаемому значению <{1}>. {0} Actual value <{2}> is not less than expected value <{1}>. {0} - Actual value <{2}> is not less than expected value <{1}>. {0} + Действительное значение <{2}> не меньше ожидаемого значения <{1}>. {0} Actual value <{2}> is not less than or equal to expected value <{1}>. {0} - Actual value <{2}> is not less than or equal to expected value <{1}>. {0} + Действительное значение <{2}> не меньше или не равно ожидаемому значению <{1}>. {0} Expected value <{1}> to be positive. {0} - Expected value <{1}> to be positive. {0} + Ожидалось, что значение <{1}> будет положительным. {0} Expected value <{1}> to be negative. {0} - Expected value <{1}> to be negative. {0} + Ожидалось, что значение <{1}> будет отрицательным. {0} @@ -387,27 +387,27 @@ Actual: {2} Assert.ReferenceEquals should not be used for Assertions. Please use Assert.AreSame & overloads instead. - Assert.ReferenceEquals should not be used for Assertions. Please use Assert.AreSame & overloads instead. + Нельзя использовать Assert.ReferenceEquals для Assertions. Вместо этого используйте Assert.AreSame и перегрузки. StringAssert.Equals should not be used for Assertions. Please use StringAssert methods or Assert.AreEqual & overloads instead. - StringAssert.Equals should not be used for Assertions. Please use StringAssert methods or Assert.AreEqual & overloads instead. + Нельзя использовать StringAssert.Equals для Assertions. Вместо этого используйте методы StringAssert или Assert.AreEqual и перегрузки. StringAssert.ReferenceEquals should not be used for Assertions. Please use StringAssert methods or Assert.AreSame & overloads instead. - StringAssert.ReferenceEquals should not be used for Assertions. Please use StringAssert methods or Assert.AreSame & overloads instead. + Нельзя использовать StringAssert.ReferenceEquals для Assertions. Вместо этого используйте методы StringAssert или Assert.AreSame и перегрузки. CollectionAssert.Equals should not be used for Assertions. Please use CollectionAssert.AreEqual & overloads instead. - CollectionAssert.Equals should not be used for Assertions. Please use CollectionAssert.AreEqual & overloads instead. + Нельзя использовать CollectionAssert.Equals для Assertions. Вместо этого используйте CollectionAssert.AreEqual и перегрузки. CollectionAssert.ReferenceEquals should not be used for Assertions. Please use CollectionAssert methods or Assert.AreSame & overloads instead. - CollectionAssert.ReferenceEquals should not be used for Assertions. Please use CollectionAssert methods or Assert.AreSame & overloads instead. + Нельзя использовать CollectionAssert.ReferenceEquals для Assertions. Вместо этого используйте методы CollectionAssert или Assert.AreSame и перегрузки. From 88907b48df237a4a510d9fb5941aeed08fdc42e9 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Wed, 25 Jun 2025 22:14:50 +0200 Subject: [PATCH 130/541] Cleanup new assert APIs (#5883) --- .../Assertions/Assert.Contains.cs | 32 +---- .../Assertions/Assert.EndsWith.cs | 88 +----------- .../Assertions/Assert.IComparable.cs | 126 +----------------- .../Assertions/Assert.Matches.cs | 82 +----------- .../Assertions/Assert.StartsWith.cs | 86 +----------- .../PublicAPI/PublicAPI.Unshipped.txt | 60 +++------ .../Assertions/AssertTests.IsInRange.cs | 2 +- 7 files changed, 49 insertions(+), 427 deletions(-) diff --git a/src/TestFramework/TestFramework/Assertions/Assert.Contains.cs b/src/TestFramework/TestFramework/Assertions/Assert.Contains.cs index ab8040aa77..849d9a4bac 100644 --- a/src/TestFramework/TestFramework/Assertions/Assert.Contains.cs +++ b/src/TestFramework/TestFramework/Assertions/Assert.Contains.cs @@ -5,6 +5,8 @@ namespace Microsoft.VisualStudio.TestTools.UnitTesting; +#pragma warning disable RS0027 // API with optional parameter(s) should have the most parameters amongst its public overloads + /// /// A collection of helper classes to test various conditions within /// unit tests. If the condition being tested is not met, an exception @@ -55,10 +57,8 @@ public void AppendFormatted(T value) public void AppendFormatted(ReadOnlySpan value) => _builder!.Append(value); -#pragma warning disable RS0027 // API with optional parameter(s) should have the most parameters amongst its public overloads public void AppendFormatted(ReadOnlySpan value, int alignment = 0, string? format = null) => AppendFormatted(value.ToString(), alignment, format); -#pragma warning restore RS0027 // API with optional parameter(s) should have the most parameters amongst its public overloads #endif // NOTE: All the overloads involving format and/or alignment are not super efficient. @@ -79,14 +79,12 @@ public void AppendFormatted(string? value) => _builder!.Append(value); #pragma warning disable RS0026 // Do not add multiple public overloads with optional parameters -#pragma warning disable RS0027 // API with optional parameter(s) should have the most parameters amongst its public overloads public void AppendFormatted(string? value, int alignment = 0, string? format = null) => _builder!.AppendFormat(null, $"{{0,{alignment}:{format}}}", value); public void AppendFormatted(object? value, int alignment = 0, string? format = null) => _builder!.AppendFormat(null, $"{{0,{alignment}:{format}}}", value); #pragma warning restore RS0026 // Do not add multiple public overloads with optional parameters -#pragma warning restore RS0027 // API with optional parameter(s) should have the most parameters amongst its public overloads } #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member @@ -144,16 +142,6 @@ public static T ContainsSingle(IEnumerable collection, [StringSyntax(Strin return default; } - /// - /// Tests whether the specified collection contains exactly one element that matches the given predicate. - /// - /// The type of the collection items. - /// A function to test each element for a condition. - /// The collection. - /// The item that matches the predicate. - public static T ContainsSingle(Func predicate, IEnumerable collection) - => ContainsSingle(predicate, collection, string.Empty); - /// /// Tests whether the specified collection contains exactly one element that matches the given predicate. /// @@ -162,7 +150,7 @@ public static T ContainsSingle(Func predicate, IEnumerable collec /// The collection. /// The message format to display when the assertion fails. /// The item that matches the predicate. - public static T ContainsSingle(Func predicate, IEnumerable collection, string? message) + public static T ContainsSingle(Func predicate, IEnumerable collection, string message = "") { var matchingElements = collection.Where(predicate).ToList(); int actualCount = matchingElements.Count; @@ -723,18 +711,6 @@ public static void DoesNotContain(string substring, string value, StringComparis #region IsInRange - /// - /// Tests whether the specified value is within the expected range (inclusive). - /// The range includes both the minimum and maximum values. - /// - /// The type of the values to compare. - /// The minimum value of the expected range (inclusive). - /// The maximum value of the expected range (inclusive). - /// The value to test. - public static void IsInRange(T minValue, T maxValue, T value) - where T : struct, IComparable - => IsInRange(minValue, maxValue, value, string.Empty); - /// /// Tests whether the specified value is within the expected range (inclusive). /// The range includes both the minimum and maximum values. @@ -744,7 +720,7 @@ public static void IsInRange(T minValue, T maxValue, T value) /// The maximum value of the expected range (inclusive). /// The value to test. /// The message format to display when the assertion fails. - public static void IsInRange(T minValue, T maxValue, T value, string? message) + public static void IsInRange(T minValue, T maxValue, T value, string message = "") where T : struct, IComparable { if (maxValue.CompareTo(minValue) <= 0) diff --git a/src/TestFramework/TestFramework/Assertions/Assert.EndsWith.cs b/src/TestFramework/TestFramework/Assertions/Assert.EndsWith.cs index 9632c1cdac..43a93fe0c9 100644 --- a/src/TestFramework/TestFramework/Assertions/Assert.EndsWith.cs +++ b/src/TestFramework/TestFramework/Assertions/Assert.EndsWith.cs @@ -3,28 +3,12 @@ namespace Microsoft.VisualStudio.TestTools.UnitTesting; +#pragma warning disable RS0026 // Do not add multiple public overloads with optional parameters + public sealed partial class Assert { #region EndsWith - /// - /// Tests whether the specified string ends with the specified substring - /// and throws an exception if the test string does not end with the - /// substring. - /// - /// - /// The string expected to be a suffix of . - /// - /// - /// The string that is expected to end with . - /// - /// - /// is null, or is null, - /// or does not end with . - /// - public static void EndsWith([NotNull] string? substring, [NotNull] string? value) - => EndsWith(substring, value, StringComparison.Ordinal, string.Empty); - /// /// Tests whether the specified string ends with the specified substring /// and throws an exception if the test string does not end with the @@ -45,30 +29,9 @@ public static void EndsWith([NotNull] string? substring, [NotNull] string? value /// is null, or is null, /// or does not end with . /// - public static void EndsWith([NotNull] string? substring, [NotNull] string? value, string? message) + public static void EndsWith([NotNull] string? substring, [NotNull] string? value, string message = "") => EndsWith(substring, value, StringComparison.Ordinal, message); - /// - /// Tests whether the specified string ends with the specified substring - /// and throws an exception if the test string does not end with the - /// substring. - /// - /// - /// The string expected to be a suffix of . - /// - /// - /// The string that is expected to end with . - /// - /// - /// The comparison method to compare strings . - /// - /// - /// is null, or is null, - /// or does not end with . - /// - public static void EndsWith([NotNull] string? substring, [NotNull] string? value, StringComparison comparisonType) - => EndsWith(substring, value, comparisonType, string.Empty); - /// /// Tests whether the specified string ends with the specified substring /// and throws an exception if the test string does not end with the @@ -92,7 +55,7 @@ public static void EndsWith([NotNull] string? substring, [NotNull] string? value /// is null, or is null, /// or does not start with . /// - public static void EndsWith([NotNull] string? substring, [NotNull] string? value, StringComparison comparisonType, string? message) + public static void EndsWith([NotNull] string? substring, [NotNull] string? value, StringComparison comparisonType, string message = "") { CheckParameterNotNull(value, "Assert.EndsWith", "value", string.Empty); CheckParameterNotNull(substring, "Assert.EndsWith", "substring", string.Empty); @@ -108,24 +71,6 @@ public static void EndsWith([NotNull] string? substring, [NotNull] string? value #region DoesNotEndWith - /// - /// Tests whether the specified string does not end with the specified substring - /// and throws an exception if the test string does not end with the - /// substring. - /// - /// - /// The string expected not to be a suffix of . - /// - /// - /// The string that is expected not to end with . - /// - /// - /// is null, or is null, - /// or ends with . - /// - public static void DoesNotEndWith([NotNull] string? substring, [NotNull] string? value) - => DoesNotEndWith(substring, value, StringComparison.Ordinal, string.Empty); - /// /// Tests whether the specified string does not end with the specified substring /// and throws an exception if the test string does not end with the @@ -146,30 +91,9 @@ public static void DoesNotEndWith([NotNull] string? substring, [NotNull] string? /// is null, or is null, /// or ends with . /// - public static void DoesNotEndWith([NotNull] string? substring, [NotNull] string? value, string? message) + public static void DoesNotEndWith([NotNull] string? substring, [NotNull] string? value, string message = "") => DoesNotEndWith(substring, value, StringComparison.Ordinal, message); - /// - /// Tests whether the specified string does not end with the specified substring - /// and throws an exception if the test string does not end with the - /// substring. - /// - /// - /// The string expected not to be a suffix of . - /// - /// - /// The string that is expected not to end with . - /// - /// - /// The comparison method to compare strings . - /// - /// - /// is null, or is null, - /// or ends with . - /// - public static void DoesNotEndWith([NotNull] string? substring, [NotNull] string? value, StringComparison comparisonType) - => DoesNotEndWith(substring, value, comparisonType, string.Empty); - /// /// Tests whether the specified string does not end with the specified substring /// and throws an exception if the test string does not end with the @@ -193,7 +117,7 @@ public static void DoesNotEndWith([NotNull] string? substring, [NotNull] string? /// is null, or is null, /// or ends with . /// - public static void DoesNotEndWith([NotNull] string? substring, [NotNull] string? value, StringComparison comparisonType, string? message) + public static void DoesNotEndWith([NotNull] string? substring, [NotNull] string? value, StringComparison comparisonType, string message = "") { CheckParameterNotNull(value, "Assert.DoesNotEndWith", "value", string.Empty); CheckParameterNotNull(substring, "Assert.DoesNotEndWith", "substring", string.Empty); diff --git a/src/TestFramework/TestFramework/Assertions/Assert.IComparable.cs b/src/TestFramework/TestFramework/Assertions/Assert.IComparable.cs index fd8ccdbb98..3a59a112d9 100644 --- a/src/TestFramework/TestFramework/Assertions/Assert.IComparable.cs +++ b/src/TestFramework/TestFramework/Assertions/Assert.IComparable.cs @@ -12,26 +12,6 @@ public sealed partial class Assert { #region IsGreaterThan - /// - /// Tests whether the value is greater than the lower bound and throws an exception - /// if it is not. - /// - /// - /// The type of values to compare. - /// - /// - /// The lower bound value that the value should exceed. - /// - /// - /// The value to compare. This is the value produced by the code under test. - /// - /// - /// Thrown if is not greater than . - /// - public static void IsGreaterThan(T lowerBound, T value) - where T : IComparable - => IsGreaterThan(lowerBound, value, string.Empty); - /// /// Tests whether the value is greater than the lower bound and throws an exception /// if it is not. @@ -53,7 +33,7 @@ public static void IsGreaterThan(T lowerBound, T value) /// /// Thrown if is not greater than . /// - public static void IsGreaterThan(T lowerBound, T value, string? message) + public static void IsGreaterThan(T lowerBound, T value, string message = "") where T : IComparable { if (value.CompareTo(lowerBound) > 0) @@ -69,26 +49,6 @@ public static void IsGreaterThan(T lowerBound, T value, string? message) #region IsGreaterThanOrEqualTo - /// - /// Tests whether the value is greater than or equal to the lower bound and throws an exception - /// if it is not. - /// - /// - /// The type of values to compare. - /// - /// - /// The lower bound value that the value should meet or exceed. - /// - /// - /// The value to compare. This is the value produced by the code under test. - /// - /// - /// Thrown if is not greater than or equal to . - /// - public static void IsGreaterThanOrEqualTo(T lowerBound, T value) - where T : IComparable - => IsGreaterThanOrEqualTo(lowerBound, value, string.Empty); - /// /// Tests whether the value is greater than or equal to the lower bound and throws an exception /// if it is not. @@ -110,7 +70,7 @@ public static void IsGreaterThanOrEqualTo(T lowerBound, T value) /// /// Thrown if is not greater than or equal to . /// - public static void IsGreaterThanOrEqualTo(T lowerBound, T value, string? message) + public static void IsGreaterThanOrEqualTo(T lowerBound, T value, string message = "") where T : IComparable { if (value.CompareTo(lowerBound) >= 0) @@ -126,26 +86,6 @@ public static void IsGreaterThanOrEqualTo(T lowerBound, T value, string? mess #region IsLessThan - /// - /// Tests whether the value is less than the upper bound and throws an exception - /// if it is not. - /// - /// - /// The type of values to compare. - /// - /// - /// The upper bound value that the value should be less than. - /// - /// - /// The value to compare. This is the value produced by the code under test. - /// - /// - /// Thrown if is not less than . - /// - public static void IsLessThan(T upperBound, T value) - where T : IComparable - => IsLessThan(upperBound, value, string.Empty); - /// /// Tests whether the value is less than the upper bound and throws an exception /// if it is not. @@ -167,7 +107,7 @@ public static void IsLessThan(T upperBound, T value) /// /// Thrown if is not less than . /// - public static void IsLessThan(T upperBound, T value, string? message) + public static void IsLessThan(T upperBound, T value, string message = "") where T : IComparable { if (value.CompareTo(upperBound) < 0) @@ -183,26 +123,6 @@ public static void IsLessThan(T upperBound, T value, string? message) #region IsLessThanOrEqualTo - /// - /// Tests whether the value is less than or equal to the upper bound and throws an exception - /// if it is not. - /// - /// - /// The type of values to compare. - /// - /// - /// The upper bound value that the value should not exceed. - /// - /// - /// The value to compare. This is the value produced by the code under test. - /// - /// - /// Thrown if is not less than or equal to . - /// - public static void IsLessThanOrEqualTo(T upperBound, T value) - where T : IComparable - => IsLessThanOrEqualTo(upperBound, value, string.Empty); - /// /// Tests whether the value is less than or equal to the upper bound and throws an exception /// if it is not. @@ -224,7 +144,7 @@ public static void IsLessThanOrEqualTo(T upperBound, T value) /// /// Thrown if is not less than or equal to . /// - public static void IsLessThanOrEqualTo(T upperBound, T value, string? message) + public static void IsLessThanOrEqualTo(T upperBound, T value, string message = "") where T : IComparable { if (value.CompareTo(upperBound) <= 0) @@ -240,23 +160,6 @@ public static void IsLessThanOrEqualTo(T upperBound, T value, string? message #region IsPositive - /// - /// Tests whether the specified value is positive and throws an exception - /// if it is not. - /// - /// - /// The type of value to test. - /// - /// - /// The value to test. - /// - /// - /// Thrown if is not positive. - /// - public static void IsPositive(T value) - where T : struct, IComparable - => IsPositive(value, string.Empty); - /// /// Tests whether the specified value is positive and throws an exception /// if it is not. @@ -274,7 +177,7 @@ public static void IsPositive(T value) /// /// Thrown if is not positive. /// - public static void IsPositive(T value, string? message) + public static void IsPositive(T value, string message = "") where T : struct, IComparable { var zero = default(T); @@ -307,23 +210,6 @@ public static void IsPositive(T value, string? message) #region IsNegative - /// - /// Tests whether the specified value is negative and throws an exception - /// if it is not. - /// - /// - /// The type of value to test. - /// - /// - /// The value to test. - /// - /// - /// Thrown if is not negative. - /// - public static void IsNegative(T value) - where T : struct, IComparable - => IsNegative(value, string.Empty); - /// /// Tests whether the specified value is negative and throws an exception /// if it is not. @@ -341,7 +227,7 @@ public static void IsNegative(T value) /// /// Thrown if is not negative. /// - public static void IsNegative(T value, string? message) + public static void IsNegative(T value, string message = "") where T : struct, IComparable { var zero = default(T); diff --git a/src/TestFramework/TestFramework/Assertions/Assert.Matches.cs b/src/TestFramework/TestFramework/Assertions/Assert.Matches.cs index f6725e27f4..224c4ecb86 100644 --- a/src/TestFramework/TestFramework/Assertions/Assert.Matches.cs +++ b/src/TestFramework/TestFramework/Assertions/Assert.Matches.cs @@ -3,28 +3,12 @@ namespace Microsoft.VisualStudio.TestTools.UnitTesting; +#pragma warning disable RS0026 // Do not add multiple public overloads with optional parameters + public sealed partial class Assert { #region MatchesRegex - /// - /// Tests whether the specified string MatchesRegex a regular expression and - /// throws an exception if the string does not match the expression. - /// - /// - /// The regular expression that is - /// expected to match. - /// - /// - /// The string that is expected to match . - /// - /// - /// is null, or is null, - /// or does not match . - /// - public static void MatchesRegex([NotNull] Regex? pattern, [NotNull] string? value) - => MatchesRegex(pattern, value, string.Empty); - /// /// Tests whether the specified string MatchesRegex a regular expression and /// throws an exception if the string does not match the expression. @@ -45,7 +29,7 @@ public static void MatchesRegex([NotNull] Regex? pattern, [NotNull] string? valu /// is null, or is null, /// or does not match . /// - public static void MatchesRegex([NotNull] Regex? pattern, [NotNull] string? value, string? message) + public static void MatchesRegex([NotNull] Regex? pattern, [NotNull] string? value, string message = "") { CheckParameterNotNull(value, "Assert.MatchesRegex", "value", string.Empty); CheckParameterNotNull(pattern, "Assert.MatchesRegex", "pattern", string.Empty); @@ -58,24 +42,6 @@ public static void MatchesRegex([NotNull] Regex? pattern, [NotNull] string? valu } } - /// - /// Tests whether the specified string MatchesRegex a regular expression and - /// throws an exception if the string does not match the expression. - /// - /// - /// The regular expression that is - /// expected to match. - /// - /// - /// The string that is expected to match . - /// - /// - /// is null, or is null, - /// or does not match . - /// - public static void MatchesRegex([NotNull] string? pattern, [NotNull] string? value) - => MatchesRegex(ToRegex(pattern), value, string.Empty); - /// /// Tests whether the specified string MatchesRegex a regular expression and /// throws an exception if the string does not match the expression. @@ -96,31 +62,13 @@ public static void MatchesRegex([NotNull] string? pattern, [NotNull] string? val /// is null, or is null, /// or does not match . /// - public static void MatchesRegex([NotNull] string? pattern, [NotNull] string? value, string? message) + public static void MatchesRegex([NotNull] string? pattern, [NotNull] string? value, string message = "") => MatchesRegex(ToRegex(pattern), value, message); #endregion // MatchesRegex #region DoesNotMatchRegex - /// - /// Tests whether the specified string does not match a regular expression - /// and throws an exception if the string MatchesRegex the expression. - /// - /// - /// The regular expression that is - /// expected to not match. - /// - /// - /// The string that is expected not to match . - /// - /// - /// is null, or is null, - /// or MatchesRegex . - /// - public static void DoesNotMatchRegex([NotNull] Regex? pattern, [NotNull] string? value) - => DoesNotMatchRegex(pattern, value, string.Empty); - /// /// Tests whether the specified string does not match a regular expression /// and throws an exception if the string MatchesRegex the expression. @@ -141,7 +89,7 @@ public static void DoesNotMatchRegex([NotNull] Regex? pattern, [NotNull] string? /// is null, or is null, /// or MatchesRegex . /// - public static void DoesNotMatchRegex([NotNull] Regex? pattern, [NotNull] string? value, string? message) + public static void DoesNotMatchRegex([NotNull] Regex? pattern, [NotNull] string? value, string message = "") { CheckParameterNotNull(value, "Assert.DoesNotMatchRegex", "value", string.Empty); CheckParameterNotNull(pattern, "Assert.DoesNotMatchRegex", "pattern", string.Empty); @@ -154,24 +102,6 @@ public static void DoesNotMatchRegex([NotNull] Regex? pattern, [NotNull] string? } } - /// - /// Tests whether the specified string does not match a regular expression - /// and throws an exception if the string MatchesRegex the expression. - /// - /// - /// The regular expression that is - /// expected to not match. - /// - /// - /// The string that is expected not to match . - /// - /// - /// is null, or is null, - /// or MatchesRegex . - /// - public static void DoesNotMatchRegex([NotNull] string? pattern, [NotNull] string? value) - => DoesNotMatchRegex(ToRegex(pattern), value, string.Empty); - /// /// Tests whether the specified string does not match a regular expression /// and throws an exception if the string MatchesRegex the expression. @@ -192,7 +122,7 @@ public static void DoesNotMatchRegex([NotNull] string? pattern, [NotNull] string /// is null, or is null, /// or MatchesRegex . /// - public static void DoesNotMatchRegex([NotNull] string? pattern, [NotNull] string? value, string? message) + public static void DoesNotMatchRegex([NotNull] string? pattern, [NotNull] string? value, string message = "") => DoesNotMatchRegex(ToRegex(pattern), value, message); #endregion // DoesNotMatchRegex diff --git a/src/TestFramework/TestFramework/Assertions/Assert.StartsWith.cs b/src/TestFramework/TestFramework/Assertions/Assert.StartsWith.cs index 57f9000b69..9f6904a939 100644 --- a/src/TestFramework/TestFramework/Assertions/Assert.StartsWith.cs +++ b/src/TestFramework/TestFramework/Assertions/Assert.StartsWith.cs @@ -3,28 +3,12 @@ namespace Microsoft.VisualStudio.TestTools.UnitTesting; +#pragma warning disable RS0026 // Do not add multiple public overloads with optional parameters + public sealed partial class Assert { #region StartsWith - /// - /// Tests whether the specified string begins with the specified substring - /// and throws an exception if the test string does not start with the - /// substring. - /// - /// - /// The string expected to be a prefix of . - /// - /// - /// The string that is expected to begin with . - /// - /// - /// is null, or is null, - /// or does not start with . - /// - public static void StartsWith([NotNull] string? substring, [NotNull] string? value) - => StartsWith(substring, value, StringComparison.Ordinal, string.Empty); - /// /// Tests whether the specified string begins with the specified substring /// and throws an exception if the test string does not start with the @@ -45,30 +29,9 @@ public static void StartsWith([NotNull] string? substring, [NotNull] string? val /// is null, or is null, /// or does not start with . /// - public static void StartsWith([NotNull] string? substring, [NotNull] string? value, string? message) + public static void StartsWith([NotNull] string? substring, [NotNull] string? value, string message = "") => StartsWith(substring, value, StringComparison.Ordinal, message); - /// - /// Tests whether the specified string begins with the specified substring - /// and throws an exception if the test string does not start with the - /// substring. - /// - /// - /// The string expected to be a prefix of . - /// - /// - /// The string that is expected to begin with . - /// - /// - /// The comparison method to compare strings . - /// - /// - /// is null, or is null, - /// or does not start with . - /// - public static void StartsWith([NotNull] string? substring, [NotNull] string? value, StringComparison comparisonType) - => StartsWith(substring, value, comparisonType, string.Empty); - /// /// Tests whether the specified string begins with the specified substring /// and throws an exception if the test string does not start with the @@ -92,7 +55,7 @@ public static void StartsWith([NotNull] string? substring, [NotNull] string? val /// is null, or is null, /// or does not start with . /// - public static void StartsWith([NotNull] string? substring, [NotNull] string? value, StringComparison comparisonType, string? message) + public static void StartsWith([NotNull] string? substring, [NotNull] string? value, StringComparison comparisonType, string message = "") { CheckParameterNotNull(value, "Assert.StartsWith", "value", string.Empty); CheckParameterNotNull(substring, "Assert.StartsWith", "substring", string.Empty); @@ -108,23 +71,6 @@ public static void StartsWith([NotNull] string? substring, [NotNull] string? val #region DoesNotStartWith - /// - /// Tests whether the specified string does not begin with the specified substring - /// and throws an exception if the test string does start with the substring. - /// - /// - /// The string expected to be a prefix of . - /// - /// - /// The string that is expected to begin with . - /// - /// - /// is null, or is null, - /// or does not start with . - /// - public static void DoesNotStartWith([NotNull] string? substring, [NotNull] string? value) - => DoesNotStartWith(substring, value, StringComparison.Ordinal, string.Empty); - /// /// Tests whether the specified string does not begin with the specified substring /// and throws an exception if the test string does start with the substring. @@ -144,29 +90,9 @@ public static void DoesNotStartWith([NotNull] string? substring, [NotNull] strin /// is null, or is null, /// or does not start with . /// - public static void DoesNotStartWith([NotNull] string? substring, [NotNull] string? value, string? message) + public static void DoesNotStartWith([NotNull] string? substring, [NotNull] string? value, string message = "") => DoesNotStartWith(substring, value, StringComparison.Ordinal, message); - /// - /// Tests whether the specified string does not begin with the specified substring - /// and throws an exception if the test string does start with the substring. - /// - /// - /// The string expected to be a prefix of . - /// - /// - /// The string that is expected to begin with . - /// - /// - /// The comparison method to compare strings . - /// - /// - /// is null, or is null, - /// or does not start with . - /// - public static void DoesNotStartWith([NotNull] string? substring, [NotNull] string? value, StringComparison comparisonType) - => DoesNotStartWith(substring, value, comparisonType, string.Empty); - /// /// Tests whether the specified string does not begin with the specified substring /// and throws an exception if the test string does start with the substring. @@ -189,7 +115,7 @@ public static void DoesNotStartWith([NotNull] string? substring, [NotNull] strin /// is null, or is null, /// or does not start with . /// - public static void DoesNotStartWith([NotNull] string? substring, [NotNull] string? value, StringComparison comparisonType, string? message) + public static void DoesNotStartWith([NotNull] string? substring, [NotNull] string? value, StringComparison comparisonType, string message = "") { CheckParameterNotNull(value, "Assert.DoesNotStartWith", "value", string.Empty); CheckParameterNotNull(substring, "Assert.DoesNotStartWith", "substring", string.Empty); diff --git a/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Unshipped.txt b/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Unshipped.txt index 1ba4542dc0..1535883112 100644 --- a/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Unshipped.txt +++ b/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Unshipped.txt @@ -1,48 +1,28 @@ #nullable enable Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AssertNonStrictThrowsInterpolatedStringHandler.AssertNonStrictThrowsInterpolatedStringHandler(int literalLength, int formattedCount, System.Func! action, out bool shouldAppend) -> void Microsoft.VisualStudio.TestTools.UnitTesting.ConditionBaseAttribute.Mode.get -> Microsoft.VisualStudio.TestTools.UnitTesting.ConditionMode -static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsGreaterThan(T lowerBound, T value) -> void -static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsGreaterThan(T lowerBound, T value, string? message) -> void -static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsGreaterThanOrEqualTo(T lowerBound, T value) -> void -static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsGreaterThanOrEqualTo(T lowerBound, T value, string? message) -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.ContainsSingle(System.Func! predicate, System.Collections.Generic.IEnumerable! collection, string! message = "") -> T +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.DoesNotEndWith(string? substring, string? value, string! message = "") -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.DoesNotEndWith(string? substring, string? value, System.StringComparison comparisonType, string! message = "") -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.DoesNotMatchRegex(string? pattern, string? value, string! message = "") -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.DoesNotMatchRegex(System.Text.RegularExpressions.Regex? pattern, string? value, string! message = "") -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.DoesNotStartWith(string? substring, string? value, string! message = "") -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.DoesNotStartWith(string? substring, string? value, System.StringComparison comparisonType, string! message = "") -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.EndsWith(string? substring, string? value, string! message = "") -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.EndsWith(string? substring, string? value, System.StringComparison comparisonType, string! message = "") -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsGreaterThan(T lowerBound, T value, string! message = "") -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsGreaterThanOrEqualTo(T lowerBound, T value, string! message = "") -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.Instance.get -> Microsoft.VisualStudio.TestTools.UnitTesting.Assert! static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.Contains(System.Func! predicate, System.Collections.Generic.IEnumerable! collection, string? message) -> void -static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.DoesNotEndWith(string? substring, string? value) -> void -static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.DoesNotEndWith(string? substring, string? value, string? message) -> void -static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.DoesNotEndWith(string? substring, string? value, System.StringComparison comparisonType) -> void -static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.DoesNotEndWith(string? substring, string? value, System.StringComparison comparisonType, string? message) -> void -static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.DoesNotMatchRegex(string? pattern, string? value) -> void -static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.DoesNotMatchRegex(string? pattern, string? value, string? message) -> void -static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.DoesNotMatchRegex(System.Text.RegularExpressions.Regex? pattern, string? value) -> void -static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.DoesNotMatchRegex(System.Text.RegularExpressions.Regex? pattern, string? value, string? message) -> void -static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.DoesNotStartWith(string? substring, string? value) -> void -static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.DoesNotStartWith(string? substring, string? value, string? message) -> void -static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.DoesNotStartWith(string? substring, string? value, System.StringComparison comparisonType) -> void -static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.DoesNotStartWith(string? substring, string? value, System.StringComparison comparisonType, string? message) -> void -static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.EndsWith(string? substring, string? value) -> void -static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.EndsWith(string? substring, string? value, string? message) -> void -static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.EndsWith(string? substring, string? value, System.StringComparison comparisonType) -> void -static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.EndsWith(string? substring, string? value, System.StringComparison comparisonType, string? message) -> void -static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsInRange(T minValue, T maxValue, T value) -> void -static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsInRange(T minValue, T maxValue, T value, string? message) -> void -static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.ContainsSingle(System.Func! predicate, System.Collections.Generic.IEnumerable! collection) -> T -static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.ContainsSingle(System.Func! predicate, System.Collections.Generic.IEnumerable! collection, string? message) -> T -static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsLessThan(T upperBound, T value) -> void -static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsLessThan(T upperBound, T value, string? message) -> void -static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsLessThanOrEqualTo(T upperBound, T value) -> void -static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsLessThanOrEqualTo(T upperBound, T value, string? message) -> void -static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsNegative(T value) -> void -static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsNegative(T value, string? message) -> void -static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsPositive(T value) -> void -static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsPositive(T value, string? message) -> void -static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.MatchesRegex(string? pattern, string? value) -> void -static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.MatchesRegex(string? pattern, string? value, string? message) -> void -static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.MatchesRegex(System.Text.RegularExpressions.Regex? pattern, string? value) -> void -static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.MatchesRegex(System.Text.RegularExpressions.Regex? pattern, string? value, string? message) -> void -static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.StartsWith(string? substring, string? value) -> void -static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.StartsWith(string? substring, string? value, string? message) -> void -static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.StartsWith(string? substring, string? value, System.StringComparison comparisonType) -> void -static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.StartsWith(string? substring, string? value, System.StringComparison comparisonType, string? message) -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsInRange(T minValue, T maxValue, T value, string! message = "") -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsLessThan(T upperBound, T value, string! message = "") -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsLessThanOrEqualTo(T upperBound, T value, string! message = "") -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsNegative(T value, string! message = "") -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsPositive(T value, string! message = "") -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.MatchesRegex(string? pattern, string? value, string! message = "") -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.MatchesRegex(System.Text.RegularExpressions.Regex? pattern, string? value, string! message = "") -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.StartsWith(string? substring, string? value, string! message = "") -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.StartsWith(string? substring, string? value, System.StringComparison comparisonType, string! message = "") -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.Throws(System.Func! action, ref Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AssertNonStrictThrowsInterpolatedStringHandler message) -> TException! static Microsoft.VisualStudio.TestTools.UnitTesting.CollectionAssert.Instance.get -> Microsoft.VisualStudio.TestTools.UnitTesting.CollectionAssert! static Microsoft.VisualStudio.TestTools.UnitTesting.StringAssert.Instance.get -> Microsoft.VisualStudio.TestTools.UnitTesting.StringAssert! diff --git a/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.IsInRange.cs b/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.IsInRange.cs index ece5567727..016b02a799 100644 --- a/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.IsInRange.cs +++ b/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.IsInRange.cs @@ -161,7 +161,7 @@ public void IsInRange_WithNullMessage_DoesNotThrow() int value = 3; // Act & Assert - Assert.IsInRange(minValue, maxValue, value, null); + Assert.IsInRange(minValue, maxValue, value, null!); } public void IsInRange_WithEmptyMessage_DoesNotThrow() From ac7b80718b5ad69f209ac5ad4fa39fb6ed73c317 Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Thu, 26 Jun 2025 09:36:25 +0000 Subject: [PATCH 131/541] [main] Update dependencies from devdiv/DevDiv/vs-code-coverage, dotnet/arcade (#5839) [main] Update dependencies from devdiv/DevDiv/vs-code-coverage, dotnet/arcade --- eng/Version.Details.xml | 16 ++++++++-------- eng/Versions.props | 4 ++-- .../steps/install-microbuild.yml | 4 ++++ .../core-templates/steps/source-build.yml | 6 ------ eng/common/internal/NuGet.config | 3 +++ eng/common/templates/vmr-build-pr.yml | 18 ++++++++++++++++++ global.json | 6 +++--- 7 files changed, 38 insertions(+), 19 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index 394621bfb6..381b5d8eb9 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -1,21 +1,21 @@ - + https://github.com/dotnet/arcade - d9d02d858b71562509f72ea84409853e4deffc8f + f70d32d77df8544117bd659512a9087619c1de6e - + https://github.com/dotnet/arcade - d9d02d858b71562509f72ea84409853e4deffc8f + f70d32d77df8544117bd659512a9087619c1de6e - + https://github.com/dotnet/arcade - d9d02d858b71562509f72ea84409853e4deffc8f + f70d32d77df8544117bd659512a9087619c1de6e - + https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage - 67cf10b2f0c18fb045326765e14c7d2304b6c0c1 + 4830bb0c99d9a9788f6023bf3d3b89e7267aec72 diff --git a/eng/Versions.props b/eng/Versions.props index 5fd948ff56..41178e2208 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -7,7 +7,7 @@ preview - 10.0.0-beta.25316.2 - 17.15.0-preview.25318.1 + 10.0.0-beta.25325.3 + 17.15.0-preview.25325.3 diff --git a/eng/common/core-templates/steps/install-microbuild.yml b/eng/common/core-templates/steps/install-microbuild.yml index a3540ba00c..f3064a7834 100644 --- a/eng/common/core-templates/steps/install-microbuild.yml +++ b/eng/common/core-templates/steps/install-microbuild.yml @@ -30,6 +30,10 @@ steps: ${{ if and(eq(parameters.enableMicrobuildForMacAndLinux, 'true'), ne(variables['Agent.Os'], 'Windows_NT')) }}: azureSubscription: 'MicroBuild Signing Task (DevDiv)' useEsrpCli: true + ${{ elseif eq(variables['System.TeamProject'], 'DevDiv') }}: + ConnectedPMEServiceName: 6cc74545-d7b9-4050-9dfa-ebefcc8961ea + ${{ else }}: + ConnectedPMEServiceName: 248d384a-b39b-46e3-8ad5-c2c210d5e7ca env: TeamName: $(_TeamName) MicroBuildOutputFolderOverride: ${{ parameters.microBuildOutputFolder }} diff --git a/eng/common/core-templates/steps/source-build.yml b/eng/common/core-templates/steps/source-build.yml index 0dde553c3e..acf16ed349 100644 --- a/eng/common/core-templates/steps/source-build.yml +++ b/eng/common/core-templates/steps/source-build.yml @@ -38,11 +38,6 @@ steps: targetRidArgs='/p:TargetRid=${{ parameters.platform.targetRID }}' fi - baseRidArgs= - if [ '${{ parameters.platform.baseRID }}' != '' ]; then - baseRidArgs='/p:BaseRid=${{ parameters.platform.baseRID }}' - fi - portableBuildArgs= if [ '${{ parameters.platform.portableBuild }}' != '' ]; then portableBuildArgs='/p:PortableBuild=${{ parameters.platform.portableBuild }}' @@ -55,7 +50,6 @@ steps: ${{ parameters.platform.buildArguments }} \ $internalRuntimeDownloadArgs \ $targetRidArgs \ - $baseRidArgs \ $portableBuildArgs \ displayName: Build diff --git a/eng/common/internal/NuGet.config b/eng/common/internal/NuGet.config index 19d3d311b1..f70261ed68 100644 --- a/eng/common/internal/NuGet.config +++ b/eng/common/internal/NuGet.config @@ -4,4 +4,7 @@ + + + diff --git a/eng/common/templates/vmr-build-pr.yml b/eng/common/templates/vmr-build-pr.yml index c1b6fec458..ce3c29a62f 100644 --- a/eng/common/templates/vmr-build-pr.yml +++ b/eng/common/templates/vmr-build-pr.yml @@ -1,3 +1,21 @@ +# This pipeline is used for running the VMR verification of the PR changes in repo-level PRs. +# +# It will run a full set of verification jobs defined in: +# https://github.com/dotnet/dotnet/blob/10060d128e3f470e77265f8490f5e4f72dae738e/eng/pipelines/templates/stages/vmr-build.yml#L27-L38 +# +# For repos that do not need to run the full set, you would do the following: +# +# 1. Copy this YML file to a repo-specific location, i.e. outside of eng/common. +# +# 2. Add `verifications` parameter to VMR template reference +# +# Examples: +# - For source-build stage 1 verification, add the following: +# verifications: [ "source-build-stage1" ] +# +# - For Windows only verifications, add the following: +# verifications: [ "unified-build-windows-x64", "unified-build-windows-x86" ] + trigger: none pr: none diff --git a/global.json b/global.json index c014537571..672df3d2ea 100644 --- a/global.json +++ b/global.json @@ -1,6 +1,6 @@ { "tools": { - "dotnet": "10.0.100-preview.6.25309.101", + "dotnet": "10.0.100-preview.6.25315.102", "runtimes": { "dotnet": [ "3.1.32", @@ -23,7 +23,7 @@ } }, "sdk": { - "version": "10.0.100-preview.6.25309.101", + "version": "10.0.100-preview.6.25315.102", "paths": [ ".dotnet", "$host$" @@ -33,7 +33,7 @@ "rollForward": "latestFeature" }, "msbuild-sdks": { - "Microsoft.DotNet.Arcade.Sdk": "10.0.0-beta.25316.2", + "Microsoft.DotNet.Arcade.Sdk": "10.0.0-beta.25325.3", "MSBuild.Sdk.Extras": "3.0.44" } } From 13eee3856010fe8e345e869b9f19f7644f5a70f3 Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Fri, 27 Jun 2025 04:55:16 +0000 Subject: [PATCH 132/541] [main] Update dependencies from devdiv/DevDiv/vs-code-coverage, dotnet/arcade (#5888) [main] Update dependencies from devdiv/DevDiv/vs-code-coverage, dotnet/arcade --- eng/Version.Details.xml | 16 ++++++++-------- eng/Versions.props | 4 ++-- global.json | 2 +- 3 files changed, 11 insertions(+), 11 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index 381b5d8eb9..e0c5e6d089 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -1,21 +1,21 @@ - + https://github.com/dotnet/arcade - f70d32d77df8544117bd659512a9087619c1de6e + 0e335649fe2d2f98ea51e55cc1a0899af3617eba - + https://github.com/dotnet/arcade - f70d32d77df8544117bd659512a9087619c1de6e + 0e335649fe2d2f98ea51e55cc1a0899af3617eba - + https://github.com/dotnet/arcade - f70d32d77df8544117bd659512a9087619c1de6e + 0e335649fe2d2f98ea51e55cc1a0899af3617eba - + https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage - 4830bb0c99d9a9788f6023bf3d3b89e7267aec72 + cb7db38a1d9e653ddee769b6667520d88a872fea diff --git a/eng/Versions.props b/eng/Versions.props index 41178e2208..ba0a555efd 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -7,7 +7,7 @@ preview - 10.0.0-beta.25325.3 - 17.15.0-preview.25325.3 + 10.0.0-beta.25326.3 + 17.15.0-preview.25326.2 diff --git a/global.json b/global.json index 672df3d2ea..8c03d17456 100644 --- a/global.json +++ b/global.json @@ -33,7 +33,7 @@ "rollForward": "latestFeature" }, "msbuild-sdks": { - "Microsoft.DotNet.Arcade.Sdk": "10.0.0-beta.25325.3", + "Microsoft.DotNet.Arcade.Sdk": "10.0.0-beta.25326.3", "MSBuild.Sdk.Extras": "3.0.44" } } From 4ead5a1d1ee4354430da6428a364f645ac4de130 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Fri, 27 Jun 2025 13:35:55 +0200 Subject: [PATCH 133/541] [MTP] Handle metadata properties in TrxReport (#5891) --- .../TrxReportEngine.cs | 60 +++++++++++++++++++ .../TrxTests.cs | 45 ++++++++++++++ 2 files changed, 105 insertions(+) diff --git a/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxReportEngine.cs b/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxReportEngine.cs index b739de4800..c2e0a63ace 100644 --- a/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxReportEngine.cs +++ b/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxReportEngine.cs @@ -555,6 +555,66 @@ private void AddResults(string testAppModule, XElement testRun, out XElement tes unitTest.Add(new XElement("Execution", new XAttribute("id", executionId))); + XElement? properties = null; + XElement? owners = null; + foreach (TestMetadataProperty property in testNode.Properties.OfType()) + { + switch (property.Key) + { + case "Owner": + owners ??= new XElement("Owners", new XElement("Owner", new XAttribute("name", property.Value))); + break; + + case "Priority": + if (int.TryParse(property.Value, out _)) + { + unitTest.SetAttributeValue("priority", property.Value); + } + + break; + + default: + // NOTE: VSTest doesn't produce Properties as of writing this. + // It was historically fixed, but the fix wasn't correct and the fix was reverted and never revisited to be properly fixed. + // Revert PR: https://github.com/microsoft/vstest/pull/15080 + // The original implementation (buggy) was setting "Key" and "Value" as attributes on "Property" element. + // However, Visual Studio will validate the TRX file against vstst.xsd file in + // C:\Program Files\Microsoft Visual Studio\2022\Enterprise\Xml\Schemas\vstst.xsd + // In xsd, "Properties" element is defined as: + // + // + // + // + // + // + // + // + // + // + // + // + // + // + // So, Key and Value are **elements**, not attributes. + // In MTP, we do the right thing and follow the XSD definition. + properties ??= new XElement("Properties"); + properties.Add(new XElement( + "Property", + new XElement("Key", property.Key), new XElement("Value", property.Value))); + break; + } + } + + if (owners is not null) + { + unitTest.Add(owners); + } + + if (properties is not null) + { + unitTest.Add(properties); + } + var testMethod = new XElement( "TestMethod", new XAttribute("codeBase", testAppModule), diff --git a/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/TrxTests.cs b/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/TrxTests.cs index 6e94f8fe07..e5b424f038 100644 --- a/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/TrxTests.cs +++ b/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/TrxTests.cs @@ -503,6 +503,51 @@ public async Task TrxReportEngine_GenerateReportAsync_FileAlreadyExists_WillRetr Assert.AreEqual(4, retryCount); } + [TestMethod] + public async Task TrxReportEngine_GenerateReportAsync_WithMetadataProperties_TrxHandlesProperties() + { + // Arrange + using MemoryFileStream memoryStream = new(); + TrxReportEngine trxReportEngine = GenerateTrxReportEngine(1, 0, + new( + new PassedTestNodeStateProperty(), + new TestMetadataProperty("Owner", "ValueOfOwner"), + new TestMetadataProperty("Priority", "5"), + new TestMetadataProperty("MyProperty1", "MyValue1"), + new TestMetadataProperty("MyProperty2", "MyValue2")), memoryStream); + + // Act + (string fileName, string? warning) = await trxReportEngine.GenerateReportAsync(); + + // Assert + Assert.IsNull(warning); + AssertExpectedTrxFileName(fileName); + Assert.IsNotNull(memoryStream.TrxContent); + XDocument xml = memoryStream.TrxContent; + AssertTrxOutcome(xml, "Completed"); + string trxContent = xml.ToString(); + string trxContentsPattern = @" + + + + + + + + MyProperty2 + MyValue2 + + + MyProperty1 + MyValue1 + + + + + "; + Assert.IsTrue(Regex.IsMatch(trxContent, trxContentsPattern)); + } + private static void AssertTrxOutcome(XDocument xml, string expectedOutcome) { Assert.IsNotNull(xml); From cbfab62e9a389eb84f9c3afdecd85221cc3e03a3 Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Fri, 27 Jun 2025 21:58:30 +1000 Subject: [PATCH 134/541] projects should inherit defined constants (#5893) --- samples/FxExtensibility/FxExtensibility.csproj | 2 +- src/Adapter/MSTest.TestAdapter/MSTest.TestAdapter.csproj | 2 +- .../MSTestAdapter.PlatformServices.csproj | 2 +- .../Microsoft.Testing.Platform.MSBuild.csproj | 2 +- .../TestFramework.Extensions/TestFramework.Extensions.csproj | 2 +- src/TestFramework/TestFramework/TestFramework.csproj | 2 +- .../TestAssets/TestProject/TestProjectForDiscovery.csproj | 2 +- 7 files changed, 7 insertions(+), 7 deletions(-) diff --git a/samples/FxExtensibility/FxExtensibility.csproj b/samples/FxExtensibility/FxExtensibility.csproj index 13face57bd..152e1d9d23 100644 --- a/samples/FxExtensibility/FxExtensibility.csproj +++ b/samples/FxExtensibility/FxExtensibility.csproj @@ -8,7 +8,7 @@ MSTest.Extensibility.Samples MSTest.Extensibility.Samples - TRACE + $(DefineConstants);TRACE prompt 4 diff --git a/src/Adapter/MSTest.TestAdapter/MSTest.TestAdapter.csproj b/src/Adapter/MSTest.TestAdapter/MSTest.TestAdapter.csproj index 74b07934a7..2dcf69d6e8 100644 --- a/src/Adapter/MSTest.TestAdapter/MSTest.TestAdapter.csproj +++ b/src/Adapter/MSTest.TestAdapter/MSTest.TestAdapter.csproj @@ -42,7 +42,7 @@ Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter - TRACE + $(DefineConstants);TRACE true diff --git a/src/Adapter/MSTestAdapter.PlatformServices/MSTestAdapter.PlatformServices.csproj b/src/Adapter/MSTestAdapter.PlatformServices/MSTestAdapter.PlatformServices.csproj index 6d3a74107d..e3a37a6b2d 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/MSTestAdapter.PlatformServices.csproj +++ b/src/Adapter/MSTestAdapter.PlatformServices/MSTestAdapter.PlatformServices.csproj @@ -13,7 +13,7 @@ Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices - TRACE + $(DefineConstants);TRACE diff --git a/src/Platform/Microsoft.Testing.Platform.MSBuild/Microsoft.Testing.Platform.MSBuild.csproj b/src/Platform/Microsoft.Testing.Platform.MSBuild/Microsoft.Testing.Platform.MSBuild.csproj index 807811070c..d8cadaf227 100644 --- a/src/Platform/Microsoft.Testing.Platform.MSBuild/Microsoft.Testing.Platform.MSBuild.csproj +++ b/src/Platform/Microsoft.Testing.Platform.MSBuild/Microsoft.Testing.Platform.MSBuild.csproj @@ -1,7 +1,7 @@  $(MicrosoftTestingTargetFrameworks);netstandard2.0 - PLATFORM_MSBUILD + $(DefineConstants);PLATFORM_MSBUILD $(NoWarn);NU5100 diff --git a/src/TestFramework/TestFramework.Extensions/TestFramework.Extensions.csproj b/src/TestFramework/TestFramework.Extensions/TestFramework.Extensions.csproj index 85515dfec2..71181d2f51 100644 --- a/src/TestFramework/TestFramework.Extensions/TestFramework.Extensions.csproj +++ b/src/TestFramework/TestFramework.Extensions/TestFramework.Extensions.csproj @@ -36,7 +36,7 @@ Microsoft.VisualStudio.TestTools.UnitTesting Microsoft.VisualStudio.TestPlatform.TestFramework.Extensions - TRACE + $(DefineConstants);TRACE diff --git a/src/TestFramework/TestFramework/TestFramework.csproj b/src/TestFramework/TestFramework/TestFramework.csproj index cce5f87580..265bc3d974 100644 --- a/src/TestFramework/TestFramework/TestFramework.csproj +++ b/src/TestFramework/TestFramework/TestFramework.csproj @@ -8,7 +8,7 @@ Microsoft.VisualStudio.TestTools.UnitTesting Microsoft.VisualStudio.TestPlatform.TestFramework - TRACE + $(DefineConstants);TRACE diff --git a/test/IntegrationTests/TestAssets/TestProject/TestProjectForDiscovery.csproj b/test/IntegrationTests/TestAssets/TestProject/TestProjectForDiscovery.csproj index c243ff45e2..47fb7b1742 100644 --- a/test/IntegrationTests/TestAssets/TestProject/TestProjectForDiscovery.csproj +++ b/test/IntegrationTests/TestAssets/TestProject/TestProjectForDiscovery.csproj @@ -5,7 +5,7 @@ - TRACE + $(DefineConstants);TRACE prompt 4 False From 906f199ed91811e2d4ef19d898599ab1fe97b6a8 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Fri, 27 Jun 2025 14:49:18 +0200 Subject: [PATCH 135/541] Fix race in artifact publishing in PRs (#5890) --- azure-pipelines.yml | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/azure-pipelines.yml b/azure-pipelines.yml index 9184b3e60a..c0b8470e87 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -96,11 +96,19 @@ stages: - script: eng\common\CIBuild.cmd -configuration $(_BuildConfig) -prepareMachine + /p:Publish=false /p:Test=false /p:FastAcceptanceTest=true name: Build displayName: Build + - task: PublishBuildArtifacts@1 + displayName: 'Publish NuGet packages' + inputs: + PathtoPublish: '$(Build.SourcesDirectory)/artifacts/packages/$(_BuildConfig)/Shipping' + ArtifactName: '$(Agent.Os)_$(Agent.JobName)_Attempt$(System.JobAttempt)' + condition: always() + - ${{ if eq(parameters.SkipTests, False) }}: # Because the build step is using -ci flag, restore is done in a local .packages directory. @@ -169,10 +177,18 @@ stages: -configuration $(_BuildConfig) -prepareMachine /p:Test=false + /p:Publish=false /p:NonWindowsBuild=true /p:FastAcceptanceTest=true displayName: Build + - task: PublishBuildArtifacts@1 + displayName: 'Publish NuGet packages' + inputs: + PathtoPublish: '$(Build.SourcesDirectory)/artifacts/packages/$(_BuildConfig)/Shipping' + ArtifactName: '$(Agent.Os)_$(Agent.JobName)_Attempt$(System.JobAttempt)' + condition: always() + - ${{ if eq(parameters.SkipTests, False) }}: # Because the build step is using -ci flag, restore is done in a local .packages directory. # We need to pass NUGET_PACKAGES so that when dotnet test is doing evaluation phase on the projects, it can resolve .props/.targets from packages and import them. @@ -226,10 +242,18 @@ stages: -configuration $(_BuildConfig) -prepareMachine /p:Test=false + /p:Publish=false /p:NonWindowsBuild=true /p:FastAcceptanceTest=true displayName: Build + - task: PublishBuildArtifacts@1 + displayName: 'Publish NuGet packages' + inputs: + PathtoPublish: '$(Build.SourcesDirectory)/artifacts/packages/$(_BuildConfig)/Shipping' + ArtifactName: '$(Agent.Os)_$(Agent.JobName)_Attempt$(System.JobAttempt)' + condition: always() + - ${{ if eq(parameters.SkipTests, False) }}: # Because the build step is using -ci flag, restore is done in a local .packages directory. # We need to pass NUGET_PACKAGES so that when dotnet test is doing evaluation phase on the projects, it can resolve .props/.targets from packages and import them. From c4945353dfd75e28284c5cdc3f21f7e117ce6952 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Fri, 27 Jun 2025 15:38:24 +0200 Subject: [PATCH 136/541] Build v4 (#5897) --- azure-pipelines-official.yml | 1 + azure-pipelines.yml | 1 + 2 files changed, 2 insertions(+) diff --git a/azure-pipelines-official.yml b/azure-pipelines-official.yml index f7f7cdd446..c522b12d3f 100644 --- a/azure-pipelines-official.yml +++ b/azure-pipelines-official.yml @@ -4,6 +4,7 @@ trigger: include: - main - rel/* + - dev/v4 exclude: - rel/2.* - rel/3.0.* diff --git a/azure-pipelines.yml b/azure-pipelines.yml index c0b8470e87..d90ec2997b 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -4,6 +4,7 @@ pr: include: - main - rel/* + - dev/v4 paths: exclude: - .github/* From 9ce8f2133c13c51e7f9c75e479788c894186f39b Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Fri, 27 Jun 2025 15:52:28 +0200 Subject: [PATCH 137/541] Remove unused internal method (#5898) --- .../Extensions/TestCaseExtensions.cs | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Extensions/TestCaseExtensions.cs b/src/Adapter/MSTestAdapter.PlatformServices/Extensions/TestCaseExtensions.cs index b4f6fc6366..1cd8d5a324 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Extensions/TestCaseExtensions.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Extensions/TestCaseExtensions.cs @@ -152,8 +152,6 @@ internal static UnitTestElement ToUnitTestElement(this TestCase testCase, string internal static string? GetManagedMethod(this TestCase testCase) => testCase.GetPropertyValue(ManagedMethodProperty, null); - internal static void SetManagedMethod(this TestCase testCase, string value) => testCase.SetPropertyValue(ManagedMethodProperty, value); - internal static bool ContainsManagedMethodAndType(this TestCase testCase) => !StringEx.IsNullOrWhiteSpace(testCase.GetManagedMethod()) && !StringEx.IsNullOrWhiteSpace(testCase.GetManagedType()); internal static string[]? GetHierarchy(this TestCase testCase) => testCase.GetPropertyValue(HierarchyProperty, null); From cfda752dc65d88161300b2092d737a626bb20af6 Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Sat, 28 Jun 2025 00:29:37 +1000 Subject: [PATCH 138/541] missing usings in DebuggerUtility (#5895) --- samples/Playground/DebuggerUtility.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/samples/Playground/DebuggerUtility.cs b/samples/Playground/DebuggerUtility.cs index 83103fd2fd..57f8bdf769 100644 --- a/samples/Playground/DebuggerUtility.cs +++ b/samples/Playground/DebuggerUtility.cs @@ -28,7 +28,7 @@ private static bool AttachVSToProcess(int? pid, int? vsPid, bool enableLog = fal using var process = Process.GetProcessById(pid.Value); Trace($"Starting with pid '{pid}({process.ProcessName})', and vsPid '{vsPid}'", enabled: enableLog); Trace($"Using pid: {pid} to get parent VS.", enabled: enableLog); - Process? vs = GetVsFromPid(Process.GetProcessById(vsPid ?? process.Id)); + using Process? vs = GetVsFromPid(Process.GetProcessById(vsPid ?? process.Id)); if (vs != null) { @@ -38,7 +38,7 @@ private static bool AttachVSToProcess(int? pid, int? vsPid, bool enableLog = fal } Trace("Parent VS not found, finding the first VS that started.", enabled: enableLog); - Process? firstVsProcess = GetFirstVsProcess(); + using Process? firstVsProcess = GetFirstVsProcess(); if (firstVsProcess != null) { From 82f0d684f2a9cacb6f9101aa1494dd6359a18fc9 Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Sat, 28 Jun 2025 05:14:56 +0000 Subject: [PATCH 139/541] [main] Update dependencies from devdiv/DevDiv/vs-code-coverage (#5902) [main] Update dependencies from devdiv/DevDiv/vs-code-coverage --- eng/Version.Details.xml | 4 ++-- eng/Versions.props | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index e0c5e6d089..ec67afa156 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -13,9 +13,9 @@ https://github.com/dotnet/arcade 0e335649fe2d2f98ea51e55cc1a0899af3617eba - + https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage - cb7db38a1d9e653ddee769b6667520d88a872fea + 90b433bee335be4224f0e2b5106027181b4af52b diff --git a/eng/Versions.props b/eng/Versions.props index ba0a555efd..2e5fe3d1a3 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -8,6 +8,6 @@ 10.0.0-beta.25326.3 - 17.15.0-preview.25326.2 + 17.15.0-preview.25327.4 From f72e9c3704f01e3cfa122bd7a0b8917e5c4b5844 Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Sun, 29 Jun 2025 17:14:12 +1000 Subject: [PATCH 140/541] check logging level in BridgedTraceLogger fixes #5903 --- .../BridgedTraceLogger.cs | 21 ++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/src/Adapter/MSTest.TestAdapter/TestingPlatformAdapter/BridgedTraceLogger.cs b/src/Adapter/MSTest.TestAdapter/TestingPlatformAdapter/BridgedTraceLogger.cs index e5332169f0..86cdf28df1 100644 --- a/src/Adapter/MSTest.TestAdapter/TestingPlatformAdapter/BridgedTraceLogger.cs +++ b/src/Adapter/MSTest.TestAdapter/TestingPlatformAdapter/BridgedTraceLogger.cs @@ -16,12 +16,27 @@ public BridgedTraceLogger(ILogger logger) => _logger = logger; public void LogError(string format, params object?[] args) - => _logger.LogError(string.Format(CultureInfo.CurrentCulture, format, args)); + { + if (_logger.IsEnabled(LogLevel.Error)) + { + _logger.LogError(string.Format(CultureInfo.CurrentCulture, format, args)); + } + } public void LogInfo(string format, params object?[] args) - => _logger.LogInformation(string.Format(CultureInfo.CurrentCulture, format, args)); + { + if (_logger.IsEnabled(LogLevel.Information)) + { + _logger.LogInformation(string.Format(CultureInfo.CurrentCulture, format, args)); + } + } public void LogWarning(string format, params object?[] args) - => _logger.LogWarning(string.Format(CultureInfo.CurrentCulture, format, args)); + { + if (_logger.IsEnabled(LogLevel.Warning)) + { + _logger.LogWarning(string.Format(CultureInfo.CurrentCulture, format, args)); + } + } } #endif From 2d8e19217fefb86d5afc6ad5cf51546b7c019da1 Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Sun, 29 Jun 2025 17:35:26 +1000 Subject: [PATCH 141/541] avoid redundant string builder instance in ValidateTestHostEnvironmentVariablesAsync --- .../CrashDumpEnvironmentVariableProvider.cs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Extensions.CrashDump/CrashDumpEnvironmentVariableProvider.cs b/src/Platform/Microsoft.Testing.Extensions.CrashDump/CrashDumpEnvironmentVariableProvider.cs index e23f9491ca..2dfd370a18 100644 --- a/src/Platform/Microsoft.Testing.Extensions.CrashDump/CrashDumpEnvironmentVariableProvider.cs +++ b/src/Platform/Microsoft.Testing.Extensions.CrashDump/CrashDumpEnvironmentVariableProvider.cs @@ -132,11 +132,10 @@ public Task UpdateAsync(IEnvironmentVariables environmentVariables) public Task ValidateTestHostEnvironmentVariablesAsync(IReadOnlyEnvironmentVariables environmentVariables) { - StringBuilder errors = new(); - #if !NETCOREAPP return ValidationResult.InvalidTask(CrashDumpResources.CrashDumpNotSupportedInNonNetCoreErrorMessage); #else + StringBuilder errors = new(); foreach (string prefix in _prefixes) { if (!environmentVariables.TryGetVariable($"{prefix}{EnableMiniDumpVariable}", out OwnedEnvironmentVariable? enableMiniDump) From b5494378eda23d3a4d1fe1e8f8707346f4d83ffc Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Sun, 29 Jun 2025 21:22:37 +1000 Subject: [PATCH 142/541] remove redundant assignment in TryGetOptionArgumentList --- .../CommandLine/CommandLineHandler.cs | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Platform/CommandLine/CommandLineHandler.cs b/src/Platform/Microsoft.Testing.Platform/CommandLine/CommandLineHandler.cs index f4980eed01..c8a9f3c128 100644 --- a/src/Platform/Microsoft.Testing.Platform/CommandLine/CommandLineHandler.cs +++ b/src/Platform/Microsoft.Testing.Platform/CommandLine/CommandLineHandler.cs @@ -212,11 +212,8 @@ async Task DisplayRegisteredToolsInfoAsync(IOutputDevice outputDevice, IReadOnly public bool IsOptionSet(string optionName) => ParseResult.IsOptionSet(optionName); - public bool TryGetOptionArgumentList(string optionName, [NotNullWhen(true)] out string[]? arguments) - { - arguments = null; - return ParseResult is not null && ParseResult.TryGetOptionArgumentList(optionName, out arguments); - } + public bool TryGetOptionArgumentList(string optionName, [NotNullWhen(true)] out string[]? arguments) => + ParseResult.TryGetOptionArgumentList(optionName, out arguments); public Task IsEnabledAsync() => Task.FromResult(false); From e1f32efc48c1b0c3cccee04da48847af69bf97aa Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Mon, 30 Jun 2025 06:57:32 +1000 Subject: [PATCH 143/541] fix nullability of CreateBindCtx (#5907) --- .../Microsoft.Testing.TestInfrastructure/DebuggerUtility.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Utilities/Microsoft.Testing.TestInfrastructure/DebuggerUtility.cs b/test/Utilities/Microsoft.Testing.TestInfrastructure/DebuggerUtility.cs index 9af5032a7c..435e2f2d3d 100644 --- a/test/Utilities/Microsoft.Testing.TestInfrastructure/DebuggerUtility.cs +++ b/test/Utilities/Microsoft.Testing.TestInfrastructure/DebuggerUtility.cs @@ -323,5 +323,5 @@ private static extern int NtQueryInformationProcess( out int returnLength); [DllImport("ole32.dll")] - private static extern int CreateBindCtx(uint reserved, out IBindCtx ppbc); + private static extern int CreateBindCtx(uint reserved, out IBindCtx? ppbc); } From 8262ded84af95293c08d51577924b9f5f7493890 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Sun, 29 Jun 2025 22:58:30 +0200 Subject: [PATCH 144/541] Obsolete `ITestApplicationLifecycleCallbacks` and add `ITestHostApplicationLifetime` (#5889) --- .../MSBuildExtensions.cs | 2 +- ...SBuildTestApplicationLifecycleCallbacks.cs | 2 +- .../RetryExtensions.cs | 2 +- .../RetryLifecycleCallbacks.cs | 2 +- .../TrxReportExtensions.cs | 2 +- .../TrxTestApplicationLifecycleCallbacks.cs | 2 +- .../Hosts/CommonTestHost.cs | 7 +++++ .../Hosts/TestHostBuilder.cs | 2 ++ .../Hosts/TestHostControllersTestHost.cs | 2 +- .../PublicAPI/PublicAPI.Unshipped.txt | 2 ++ .../Services/ServiceProvider.cs | 3 +++ ...cks.cs => ITestHostApplicationLifetime.cs} | 11 ++++++++ .../TestHost/ITestHostManager.cs | 7 +++++ .../TestHost/TestHostManager.cs | 13 ++++++++++ .../ServerMode/ServerTests.cs | 6 ++--- .../Services/ServiceProviderTests.cs | 26 ++++++++++++++++++- .../TestApplicationBuilderTests.cs | 6 ++--- 17 files changed, 83 insertions(+), 14 deletions(-) rename src/Platform/Microsoft.Testing.Platform/TestHost/{ITestApplicationLifecycleCallbacks.cs => ITestHostApplicationLifetime.cs} (66%) diff --git a/src/Platform/Microsoft.Testing.Extensions.MSBuild/MSBuildExtensions.cs b/src/Platform/Microsoft.Testing.Extensions.MSBuild/MSBuildExtensions.cs index 57b93bb738..5f9509761c 100644 --- a/src/Platform/Microsoft.Testing.Extensions.MSBuild/MSBuildExtensions.cs +++ b/src/Platform/Microsoft.Testing.Extensions.MSBuild/MSBuildExtensions.cs @@ -20,7 +20,7 @@ public static class MSBuildExtensions public static void AddMSBuild(this ITestApplicationBuilder builder) { builder.CommandLine.AddProvider(() => new MSBuildCommandLineProvider()); - builder.TestHost.AddTestApplicationLifecycleCallbacks( + builder.TestHost.AddTestHostApplicationLifetime( serviceProvider => new MSBuildTestApplicationLifecycleCallbacks( serviceProvider.GetConfiguration(), serviceProvider.GetCommandLineOptions(), diff --git a/src/Platform/Microsoft.Testing.Extensions.MSBuild/MSBuildTestApplicationLifecycleCallbacks.cs b/src/Platform/Microsoft.Testing.Extensions.MSBuild/MSBuildTestApplicationLifecycleCallbacks.cs index 411274ac3c..b8b91ecb4f 100644 --- a/src/Platform/Microsoft.Testing.Extensions.MSBuild/MSBuildTestApplicationLifecycleCallbacks.cs +++ b/src/Platform/Microsoft.Testing.Extensions.MSBuild/MSBuildTestApplicationLifecycleCallbacks.cs @@ -13,7 +13,7 @@ namespace Microsoft.Testing.Extensions.MSBuild; -internal sealed class MSBuildTestApplicationLifecycleCallbacks : ITestApplicationLifecycleCallbacks, IDisposable +internal sealed class MSBuildTestApplicationLifecycleCallbacks : ITestHostApplicationLifetime, IDisposable { private readonly IConfiguration _configuration; private readonly ICommandLineOptions _commandLineOptions; diff --git a/src/Platform/Microsoft.Testing.Extensions.Retry/RetryExtensions.cs b/src/Platform/Microsoft.Testing.Extensions.Retry/RetryExtensions.cs index 0a048a39c9..544672fc03 100644 --- a/src/Platform/Microsoft.Testing.Extensions.Retry/RetryExtensions.cs +++ b/src/Platform/Microsoft.Testing.Extensions.Retry/RetryExtensions.cs @@ -23,7 +23,7 @@ public static void AddRetryProvider(this ITestApplicationBuilder builder) { builder.CommandLine.AddProvider(() => new RetryCommandLineOptionsProvider()); - builder.TestHost.AddTestApplicationLifecycleCallbacks(serviceProvider + builder.TestHost.AddTestHostApplicationLifetime(serviceProvider => new RetryLifecycleCallbacks(serviceProvider)); CompositeExtensionFactory compositeExtensionFactory diff --git a/src/Platform/Microsoft.Testing.Extensions.Retry/RetryLifecycleCallbacks.cs b/src/Platform/Microsoft.Testing.Extensions.Retry/RetryLifecycleCallbacks.cs index 5bfdd7d039..91c7fda0a1 100644 --- a/src/Platform/Microsoft.Testing.Extensions.Retry/RetryLifecycleCallbacks.cs +++ b/src/Platform/Microsoft.Testing.Extensions.Retry/RetryLifecycleCallbacks.cs @@ -16,7 +16,7 @@ namespace Microsoft.Testing.Extensions.Policy; -internal sealed class RetryLifecycleCallbacks : ITestApplicationLifecycleCallbacks, +internal sealed class RetryLifecycleCallbacks : ITestHostApplicationLifetime, #if NETCOREAPP IAsyncDisposable #else diff --git a/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxReportExtensions.cs b/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxReportExtensions.cs index eb769731a0..dd204c9611 100644 --- a/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxReportExtensions.cs +++ b/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxReportExtensions.cs @@ -47,7 +47,7 @@ public static void AddTrxReportProvider(this ITestApplicationBuilder builder) serviceProvider.GetService(), serviceProvider.GetLoggerFactory().CreateLogger())); - builder.TestHost.AddTestApplicationLifecycleCallbacks(serviceProvider => + builder.TestHost.AddTestHostApplicationLifetime(serviceProvider => new TrxTestApplicationLifecycleCallbacks( serviceProvider.GetCommandLineOptions(), serviceProvider.GetEnvironment())); diff --git a/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxTestApplicationLifecycleCallbacks.cs b/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxTestApplicationLifecycleCallbacks.cs index e48d67ca91..a9dfbcbe49 100644 --- a/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxTestApplicationLifecycleCallbacks.cs +++ b/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxTestApplicationLifecycleCallbacks.cs @@ -12,7 +12,7 @@ namespace Microsoft.Testing.Extensions.TrxReport.Abstractions; -internal sealed class TrxTestApplicationLifecycleCallbacks : ITestApplicationLifecycleCallbacks, IDisposable +internal sealed class TrxTestApplicationLifecycleCallbacks : ITestHostApplicationLifetime, IDisposable { private readonly bool _isEnabled; private readonly IEnvironment _environment; diff --git a/src/Platform/Microsoft.Testing.Platform/Hosts/CommonTestHost.cs b/src/Platform/Microsoft.Testing.Platform/Hosts/CommonTestHost.cs index 44c99a83b1..f9145a8c8d 100644 --- a/src/Platform/Microsoft.Testing.Platform/Hosts/CommonTestHost.cs +++ b/src/Platform/Microsoft.Testing.Platform/Hosts/CommonTestHost.cs @@ -101,21 +101,25 @@ private async Task RunTestAppAsync(CancellationToken testApplicationCancell if (RunTestApplicationLifeCycleCallbacks) { // Get the test application lifecycle callbacks to be able to call the before run +#pragma warning disable CS0618 // Type or member is obsolete foreach (ITestApplicationLifecycleCallbacks testApplicationLifecycleCallbacks in ServiceProvider.GetServicesInternal()) { await testApplicationLifecycleCallbacks.BeforeRunAsync(testApplicationCancellationToken).ConfigureAwait(false); } +#pragma warning restore CS0618 // Type or member is obsolete } int exitCode = await InternalRunAsync().ConfigureAwait(false); if (RunTestApplicationLifeCycleCallbacks) { +#pragma warning disable CS0618 // Type or member is obsolete foreach (ITestApplicationLifecycleCallbacks testApplicationLifecycleCallbacks in ServiceProvider.GetServicesInternal()) { await testApplicationLifecycleCallbacks.AfterRunAsync(exitCode, testApplicationCancellationToken).ConfigureAwait(false); await DisposeHelper.DisposeAsync(testApplicationLifecycleCallbacks).ConfigureAwait(false); } +#pragma warning restore CS0618 // Type or member is obsolete } return exitCode; @@ -239,13 +243,16 @@ protected static async Task DisposeServiceProviderAsync(ServiceProvider serviceP } // We need to ensure that we won't dispose special services till the shutdown +#pragma warning disable CS0618 // Type or member is obsolete if (!isProcessShutdown && service is ITelemetryCollector or ITestApplicationLifecycleCallbacks or + ITestHostApplicationLifetime or IPushOnlyProtocol) { continue; } +#pragma warning restore CS0618 // Type or member is obsolete if (!alreadyDisposed.Contains(service)) { diff --git a/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostBuilder.cs b/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostBuilder.cs index 90e9b551c1..5091f98f92 100644 --- a/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostBuilder.cs +++ b/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostBuilder.cs @@ -441,8 +441,10 @@ await LogTestHostCreatedAsync( systemEnvironment).ConfigureAwait(false); // Build and register the test application lifecycle callbacks. +#pragma warning disable CS0618 // Type or member is obsolete ITestApplicationLifecycleCallbacks[] testApplicationLifecycleCallback = await ((TestHostManager)TestHost).BuildTestApplicationLifecycleCallbackAsync(serviceProvider).ConfigureAwait(false); +#pragma warning restore CS0618 // Type or member is obsolete serviceProvider.AddServices(testApplicationLifecycleCallback); // ServerMode and Console mode uses different host diff --git a/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostControllersTestHost.cs b/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostControllersTestHost.cs index 7508633fb4..5ed3207de1 100644 --- a/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostControllersTestHost.cs +++ b/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostControllersTestHost.cs @@ -290,7 +290,7 @@ protected override async Task InternalRunAsync() if (_testHostsInformation.LifetimeHandlers.Length > 0) { // We don't block the host during the 'OnTestHostProcessStartedAsync' by-design, if 'ITestHostProcessLifetimeHandler' extensions needs - // to block the execution of the test host should add an in-process extension like an 'ITestApplicationLifecycleCallbacks' and + // to block the execution of the test host should add an in-process extension like an 'ITestHostApplicationLifetime' and // wait for a connection/signal to return. TestHostProcessInformation testHostProcessInformation = new(_testHostPID.Value); foreach (ITestHostProcessLifetimeHandler lifetimeHandler in _testHostsInformation.LifetimeHandlers) diff --git a/src/Platform/Microsoft.Testing.Platform/PublicAPI/PublicAPI.Unshipped.txt b/src/Platform/Microsoft.Testing.Platform/PublicAPI/PublicAPI.Unshipped.txt index eed1e2d100..200755b523 100644 --- a/src/Platform/Microsoft.Testing.Platform/PublicAPI/PublicAPI.Unshipped.txt +++ b/src/Platform/Microsoft.Testing.Platform/PublicAPI/PublicAPI.Unshipped.txt @@ -1,3 +1,5 @@ #nullable enable Microsoft.Testing.Platform.Builder.ITestApplicationBuilder.RegisterTestFramework(System.Func! capabilitiesFactory, System.Func! frameworkFactory) -> Microsoft.Testing.Platform.Builder.ITestApplicationBuilder! *REMOVED*Microsoft.Testing.Platform.Builder.ITestApplicationBuilder.RegisterTestFramework(System.Func! capabilitiesFactory, System.Func! adapterFactory) -> Microsoft.Testing.Platform.Builder.ITestApplicationBuilder! +Microsoft.Testing.Platform.Extensions.TestHost.ITestHostApplicationLifetime +Microsoft.Testing.Platform.TestHost.ITestHostManager.AddTestHostApplicationLifetime(System.Func! testHostApplicationLifetimeFactory) -> void diff --git a/src/Platform/Microsoft.Testing.Platform/Services/ServiceProvider.cs b/src/Platform/Microsoft.Testing.Platform/Services/ServiceProvider.cs index 556e89cc09..c85d18a92b 100644 --- a/src/Platform/Microsoft.Testing.Platform/Services/ServiceProvider.cs +++ b/src/Platform/Microsoft.Testing.Platform/Services/ServiceProvider.cs @@ -17,10 +17,12 @@ internal sealed class ServiceProvider : IServiceProvider, ICloneable public bool AllowTestAdapterFrameworkRegistration { get; set; } +#pragma warning disable CS0618 // Type or member is obsolete private static Type[] InternalOnlyExtensions => [ // TestHost typeof(ITestApplicationLifecycleCallbacks), + typeof(ITestHostApplicationLifetime), typeof(IDataConsumer), typeof(ITestSessionLifetimeHandler), @@ -28,6 +30,7 @@ internal sealed class ServiceProvider : IServiceProvider, ICloneable typeof(ITestHostEnvironmentVariableProvider), typeof(ITestHostProcessLifetimeHandler) ]; +#pragma warning restore CS0618 // Type or member is obsolete public void AddService(object service, bool throwIfSameInstanceExit = true) { diff --git a/src/Platform/Microsoft.Testing.Platform/TestHost/ITestApplicationLifecycleCallbacks.cs b/src/Platform/Microsoft.Testing.Platform/TestHost/ITestHostApplicationLifetime.cs similarity index 66% rename from src/Platform/Microsoft.Testing.Platform/TestHost/ITestApplicationLifecycleCallbacks.cs rename to src/Platform/Microsoft.Testing.Platform/TestHost/ITestHostApplicationLifetime.cs index e81a4b7128..e21bb9ee44 100644 --- a/src/Platform/Microsoft.Testing.Platform/TestHost/ITestApplicationLifecycleCallbacks.cs +++ b/src/Platform/Microsoft.Testing.Platform/TestHost/ITestHostApplicationLifetime.cs @@ -6,6 +6,7 @@ namespace Microsoft.Testing.Platform.Extensions.TestHost; /// /// Represents the interface for test application lifecycle callbacks. /// +[Obsolete("Use ITestHostApplicationLifetime instead. This interface will be removed in v2.")] public interface ITestApplicationLifecycleCallbacks : ITestHostExtension { /// @@ -23,3 +24,13 @@ public interface ITestApplicationLifecycleCallbacks : ITestHostExtension /// A task representing the asynchronous operation. Task AfterRunAsync(int exitCode, CancellationToken cancellation); } + +/// +/// Represents the interface for test application lifecycle callbacks. +/// +#pragma warning disable CS0618 // Type or member is obsolete +public interface ITestHostApplicationLifetime : ITestHostExtension, ITestApplicationLifecycleCallbacks +#pragma warning restore CS0618 // Type or member is obsolete +{ + // In v2, move BeforeRunAsync and AfterRunAsync to ITestHostApplicationLifetime directly +} diff --git a/src/Platform/Microsoft.Testing.Platform/TestHost/ITestHostManager.cs b/src/Platform/Microsoft.Testing.Platform/TestHost/ITestHostManager.cs index 4be1bccb84..4fd70a7844 100644 --- a/src/Platform/Microsoft.Testing.Platform/TestHost/ITestHostManager.cs +++ b/src/Platform/Microsoft.Testing.Platform/TestHost/ITestHostManager.cs @@ -15,8 +15,15 @@ public interface ITestHostManager /// Adds a test application lifecycle callbacks. /// /// The factory method for creating the test application lifecycle callbacks. + [Obsolete("Use 'AddTestHostApplicationLifetime' instead.")] void AddTestApplicationLifecycleCallbacks(Func testApplicationLifecycleCallbacks); + /// + /// Adds a test application lifecycle callbacks. + /// + /// The factory method for creating the test host application lifetime callbacks. + void AddTestHostApplicationLifetime(Func testHostApplicationLifetimeFactory); + /// /// Adds a data consumer. /// diff --git a/src/Platform/Microsoft.Testing.Platform/TestHost/TestHostManager.cs b/src/Platform/Microsoft.Testing.Platform/TestHost/TestHostManager.cs index 0e7aeed6ee..eeae8a09a4 100644 --- a/src/Platform/Microsoft.Testing.Platform/TestHost/TestHostManager.cs +++ b/src/Platform/Microsoft.Testing.Platform/TestHost/TestHostManager.cs @@ -16,7 +16,9 @@ internal sealed class TestHostManager : ITestHostManager private readonly List _factoryOrdering = []; // Exposed extension points +#pragma warning disable CS0618 // Type or member is obsolete private readonly List> _testApplicationLifecycleCallbacksFactories = []; +#pragma warning restore CS0618 // Type or member is obsolete private readonly List> _dataConsumerFactories = []; private readonly List> _testSessionLifetimeHandlerFactories = []; private readonly List _dataConsumersCompositeServiceFactories = []; @@ -88,12 +90,22 @@ internal async Task> TryBuildTestExecu return ActionResult.Fail(); } + [Obsolete] public void AddTestApplicationLifecycleCallbacks(Func testApplicationLifecycleCallbacks) { Guard.NotNull(testApplicationLifecycleCallbacks); _testApplicationLifecycleCallbacksFactories.Add(testApplicationLifecycleCallbacks); } + public void AddTestHostApplicationLifetime(Func testHostApplicationLifetime) + { + Guard.NotNull(testHostApplicationLifetime); +#pragma warning disable CS0612 // Type or member is obsolete + _testApplicationLifecycleCallbacksFactories.Add(testHostApplicationLifetime); +#pragma warning restore CS0612 // Type or member is obsolete + } + +#pragma warning disable CS0618 // Type or member is obsolete internal async Task BuildTestApplicationLifecycleCallbackAsync(ServiceProvider serviceProvider) { List testApplicationLifecycleCallbacks = []; @@ -120,6 +132,7 @@ internal async Task BuildTestApplicationLi return [.. testApplicationLifecycleCallbacks]; } +#pragma warning restore CS0618 // Type or member is obsolete public void AddDataConsumer(Func dataConsumerFactory) { diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/ServerMode/ServerTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/ServerMode/ServerTests.cs index 6d14e1a477..f3c215d8c8 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/ServerMode/ServerTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/ServerMode/ServerTests.cs @@ -38,7 +38,7 @@ public async Task ServerCanBeStartedAndAborted_TcpIp() => await RetryHelper.Retr TestApplicationHooks testApplicationHooks = new(); string[] args = ["--no-banner", "--server", "--client-host", "localhost", "--client-port", $"{server.Port}", "--internal-testingplatform-skipbuildercheck"]; ITestApplicationBuilder builder = await TestApplication.CreateBuilderAsync(args); - builder.TestHost.AddTestApplicationLifecycleCallbacks(_ => testApplicationHooks); + builder.TestHost.AddTestHostApplicationLifetime(_ => testApplicationHooks); builder.RegisterTestFramework(_ => new TestFrameworkCapabilities(), (_, __) => new MockTestAdapter()); var testApplication = (TestApplication)await builder.BuildAsync(); testApplication.ServiceProvider.GetRequiredService().SuppressOutput(); @@ -59,7 +59,7 @@ public async Task ServerCanInitialize() string[] args = ["--no-banner", "--server", "--client-port", $"{server.Port}", "--internal-testingplatform-skipbuildercheck"]; TestApplicationHooks testApplicationHooks = new(); ITestApplicationBuilder builder = await TestApplication.CreateBuilderAsync(args); - builder.TestHost.AddTestApplicationLifecycleCallbacks(_ => testApplicationHooks); + builder.TestHost.AddTestHostApplicationLifetime(_ => testApplicationHooks); builder.RegisterTestFramework(_ => new TestFrameworkCapabilities(), (_, __) => new MockTestAdapter()); var testApplication = (TestApplication)await builder.BuildAsync(); testApplication.ServiceProvider.GetRequiredService().SuppressOutput(); @@ -252,7 +252,7 @@ private static async Task WriteMessageAsync(StreamWriter writer, string message) await writer.FlushAsync(); } - private sealed class TestApplicationHooks : ITestApplicationLifecycleCallbacks, IDisposable + private sealed class TestApplicationHooks : ITestHostApplicationLifetime, IDisposable { private readonly SemaphoreSlim _waitForBeforeRunAsync = new(0, 1); diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Services/ServiceProviderTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Services/ServiceProviderTests.cs index 1ad71b8e80..6ebf2a49b4 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Services/ServiceProviderTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Services/ServiceProviderTests.cs @@ -32,7 +32,10 @@ public void GetService_InternalExtension_ShouldNotReturn() Assert.IsNull(_serviceProvider.GetService()); _serviceProvider.AddService(new TestApplicationLifecycleCallbacks()); +#pragma warning disable CS0618 // Type or member is obsolete Assert.IsNull(_serviceProvider.GetService()); +#pragma warning restore CS0618 // Type or member is obsolete + Assert.IsNull(_serviceProvider.GetService()); } [TestMethod] @@ -51,7 +54,10 @@ public void GetServiceInternal_InternalExtension_ShouldReturn() Assert.IsNotNull(_serviceProvider.GetServiceInternal()); _serviceProvider.AddService(new TestApplicationLifecycleCallbacks()); +#pragma warning disable CS0618 // Type or member is obsolete Assert.IsNotNull(_serviceProvider.GetServiceInternal()); +#pragma warning restore CS0618 // Type or member is obsolete + Assert.IsNotNull(_serviceProvider.GetServiceInternal()); } [TestMethod] @@ -155,7 +161,10 @@ public void GetServicesInternal_ExtensionMethod_InternalExtension_ShouldReturn() _serviceProvider.AddService(new TestApplicationLifecycleCallbacks()); _serviceProvider.AddService(new TestApplicationLifecycleCallbacks()); +#pragma warning disable CS0618 // Type or member is obsolete Assert.AreEqual(2, _serviceProvider.GetServicesInternal().Count()); +#pragma warning restore CS0618 // Type or member is obsolete + Assert.AreEqual(2, _serviceProvider.GetServicesInternal().Count()); } [TestMethod] @@ -164,7 +173,10 @@ public void GetServicesInternal_InternalExtension_ShouldNotReturn() _serviceProvider.AddService(new TestApplicationLifecycleCallbacks()); _serviceProvider.AddService(new TestApplicationLifecycleCallbacks()); +#pragma warning disable CS0618 // Type or member is obsolete Assert.AreEqual(0, _serviceProvider.GetServicesInternal(typeof(ITestApplicationLifecycleCallbacks), stopAtFirst: false, skipInternalOnlyExtensions: true).Count()); +#pragma warning restore CS0618 // Type or member is obsolete + Assert.AreEqual(0, _serviceProvider.GetServicesInternal(typeof(ITestHostApplicationLifetime), stopAtFirst: false, skipInternalOnlyExtensions: true).Count()); } [TestMethod] @@ -173,7 +185,10 @@ public void GetServicesInternal_InternalExtension_ShouldReturn() _serviceProvider.AddService(new TestApplicationLifecycleCallbacks()); _serviceProvider.AddService(new TestApplicationLifecycleCallbacks()); +#pragma warning disable CS0618 // Type or member is obsolete Assert.AreEqual(2, _serviceProvider.GetServicesInternal(typeof(ITestApplicationLifecycleCallbacks), stopAtFirst: false, skipInternalOnlyExtensions: false).Count()); +#pragma warning restore CS0618 // Type or member is obsolete + Assert.AreEqual(2, _serviceProvider.GetServicesInternal(typeof(ITestHostApplicationLifetime), stopAtFirst: false, skipInternalOnlyExtensions: false).Count()); } [TestMethod] @@ -182,7 +197,10 @@ public void GetServicesInternal_InternalExtension_FirstOnly_ShouldReturnOne() _serviceProvider.AddService(new TestApplicationLifecycleCallbacks()); _serviceProvider.AddService(new TestApplicationLifecycleCallbacks()); +#pragma warning disable CS0618 // Type or member is obsolete Assert.AreEqual(1, _serviceProvider.GetServicesInternal(typeof(ITestApplicationLifecycleCallbacks), stopAtFirst: true, skipInternalOnlyExtensions: false).Count()); +#pragma warning restore CS0618 // Type or member is obsolete + Assert.AreEqual(1, _serviceProvider.GetServicesInternal(typeof(ITestHostApplicationLifetime), stopAtFirst: true, skipInternalOnlyExtensions: false).Count()); } [TestMethod] @@ -191,7 +209,10 @@ public void GetServiceInternal_InternalExtension_ShouldReturnOne() _serviceProvider.AddService(new TestApplicationLifecycleCallbacks()); _serviceProvider.AddService(new TestApplicationLifecycleCallbacks()); +#pragma warning disable CS0618 // Type or member is obsolete Assert.IsNotNull(_serviceProvider.GetServiceInternal(typeof(ITestApplicationLifecycleCallbacks), skipInternalOnlyExtensions: false)); +#pragma warning restore CS0618 // Type or member is obsolete + Assert.IsNotNull(_serviceProvider.GetServiceInternal(typeof(ITestHostApplicationLifetime), skipInternalOnlyExtensions: false)); } [TestMethod] @@ -200,7 +221,10 @@ public void GetServiceInternal_InternalExtension_SkipInternalOnlyExtensions_Shou _serviceProvider.AddService(new TestApplicationLifecycleCallbacks()); _serviceProvider.AddService(new TestApplicationLifecycleCallbacks()); +#pragma warning disable CS0618 // Type or member is obsolete Assert.IsNull(_serviceProvider.GetServiceInternal(typeof(ITestApplicationLifecycleCallbacks), skipInternalOnlyExtensions: true)); +#pragma warning restore CS0618 // Type or member is obsolete + Assert.IsNull(_serviceProvider.GetServiceInternal(typeof(ITestHostApplicationLifetime), skipInternalOnlyExtensions: true)); } private sealed class TestFramework : ITestFramework @@ -294,7 +318,7 @@ private sealed class DataConsumer : IDataConsumer public Task IsEnabledAsync() => throw new NotImplementedException(); } - private sealed class TestApplicationLifecycleCallbacks : ITestApplicationLifecycleCallbacks + private sealed class TestApplicationLifecycleCallbacks : ITestHostApplicationLifetime { public string Uid => throw new NotImplementedException(); diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/TestApplicationBuilderTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/TestApplicationBuilderTests.cs index 152e35d6e3..b59d31106a 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/TestApplicationBuilderTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/TestApplicationBuilderTests.cs @@ -30,8 +30,8 @@ public TestApplicationBuilderTests() public async Task TestApplicationLifecycleCallbacks_DuplicatedId_ShouldFail() { TestHostManager testHostManager = new(); - testHostManager.AddTestApplicationLifecycleCallbacks(_ => new ApplicationLifecycleCallbacks("duplicatedId")); - testHostManager.AddTestApplicationLifecycleCallbacks(_ => new ApplicationLifecycleCallbacks("duplicatedId")); + testHostManager.AddTestHostApplicationLifetime(_ => new ApplicationLifecycleCallbacks("duplicatedId")); + testHostManager.AddTestHostApplicationLifetime(_ => new ApplicationLifecycleCallbacks("duplicatedId")); InvalidOperationException invalidOperationException = await Assert.ThrowsExceptionAsync(() => testHostManager.BuildTestApplicationLifecycleCallbackAsync(_serviceProvider)); Assert.IsTrue(invalidOperationException.Message.Contains("duplicatedId") && invalidOperationException.Message.Contains(typeof(ApplicationLifecycleCallbacks).ToString())); } @@ -345,7 +345,7 @@ private sealed class Consumer : IDataConsumer public Task ConsumeAsync(IDataProducer dataProducer, IData value, CancellationToken cancellationToken) => throw new NotImplementedException(); } - private sealed class ApplicationLifecycleCallbacks : ITestApplicationLifecycleCallbacks + private sealed class ApplicationLifecycleCallbacks : ITestHostApplicationLifetime { public ApplicationLifecycleCallbacks(string id) => Uid = id; From 0c6f1b077f0453987df3269cb71560bee9f3b75d Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Mon, 30 Jun 2025 08:25:22 +1000 Subject: [PATCH 145/541] update polyfill (#5906) --- Directory.Build.props | 1 + Directory.Packages.props | 2 +- .../MSTestAdapter.PlatformServices/MSTestSettings.cs | 10 +++++----- .../Services/TestDataSource.cs | 2 +- .../Utilities/DeploymentUtility.cs | 4 ---- .../Tasks/InvokeTestingPlatformTask.cs | 4 ++-- .../Builder/TestApplication.cs | 2 +- .../ObjectModel/UnitTestElementTests.cs | 6 +++--- 8 files changed, 14 insertions(+), 17 deletions(-) diff --git a/Directory.Build.props b/Directory.Build.props index 81e8489fd4..bde2c77e9a 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -68,6 +68,7 @@ true + true diff --git a/Directory.Packages.props b/Directory.Packages.props index 458b3be720..a3261aad80 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -54,7 +54,7 @@ - + diff --git a/src/Adapter/MSTestAdapter.PlatformServices/MSTestSettings.cs b/src/Adapter/MSTestAdapter.PlatformServices/MSTestSettings.cs index 3e43158323..bd3cbcc16a 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/MSTestSettings.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/MSTestSettings.cs @@ -495,7 +495,7 @@ private static MSTestSettings ToSettings(XmlReader reader, IMessageLogger? logge CultureInfo.CurrentCulture, Resource.InvalidClassCleanupLifecycleValue, value, - string.Join(", ", EnumPolyfill.GetNames()))); + string.Join(", ", Enum.GetNames()))); break; } @@ -822,7 +822,7 @@ private static void SetParallelSettings(XmlReader reader, MSTestSettings setting CultureInfo.CurrentCulture, Resource.InvalidParallelScopeValue, value, - string.Join(", ", EnumPolyfill.GetNames()))); + string.Join(", ", Enum.GetNames()))); break; } @@ -849,7 +849,7 @@ private static void SetParallelSettings(XmlReader reader, MSTestSettings setting private static bool TryParseEnum(string value, out T result) where T : struct, Enum => Enum.TryParse(value, true, out result) - && EnumPolyfill.IsDefined(result); + && Enum.IsDefined(result); private static void SetGlobalSettings( [StringSyntax(StringSyntaxAttribute.Xml, nameof(runsettingsXml))] string runsettingsXml, @@ -978,7 +978,7 @@ internal static void SetSettingsFromConfig(IConfiguration configuration, IMessag CultureInfo.CurrentCulture, Resource.InvalidClassCleanupLifecycleValue, classCleanupLifecycle, - string.Join(", ", EnumPolyfill.GetNames()))); + string.Join(", ", Enum.GetNames()))); } settings.ClassCleanupLifecycle = lifecycle; @@ -1011,7 +1011,7 @@ internal static void SetSettingsFromConfig(IConfiguration configuration, IMessag CultureInfo.CurrentCulture, Resource.InvalidParallelScopeValue, value, - string.Join(", ", EnumPolyfill.GetNames()))); + string.Join(", ", Enum.GetNames()))); } settings.ParallelizationScope = scope; diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Services/TestDataSource.cs b/src/Adapter/MSTestAdapter.PlatformServices/Services/TestDataSource.cs index d5c02e07cf..328576496c 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Services/TestDataSource.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Services/TestDataSource.cs @@ -147,7 +147,7 @@ private static void GetConnectionProperties(DataSourceAttribute dataSourceAttrib providerNameInvariant = ConfigurationManager.ConnectionStrings[element.ConnectionString].ProviderName; connectionString = ConfigurationManager.ConnectionStrings[element.ConnectionString].ConnectionString; tableName = element.DataTableName; - dataAccessMethod = EnumPolyfill.Parse(element.DataAccessMethod); + dataAccessMethod = Enum.Parse(element.DataAccessMethod); } #endif } diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Utilities/DeploymentUtility.cs b/src/Adapter/MSTestAdapter.PlatformServices/Utilities/DeploymentUtility.cs index af43490bde..e7f32535b3 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Utilities/DeploymentUtility.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Utilities/DeploymentUtility.cs @@ -62,11 +62,7 @@ public override void AddDeploymentItemsBasedOnMsTestSetting(string testSource, I /// Root deployment directory. public override string GetRootDeploymentDirectory(string baseDirectory) { -#if NETFRAMEWORK || NETSTANDARD || NETCOREAPP3_1 - string dateTimeSuffix = $"{DateTime.Now.ToString("yyyyMMddTHHmmss", DateTimeFormatInfo.InvariantInfo)}_{Process.GetCurrentProcess().Id}"; -#else string dateTimeSuffix = $"{DateTime.Now.ToString("yyyyMMddTHHmmss", DateTimeFormatInfo.InvariantInfo)}_{Environment.ProcessId}"; -#endif string directoryName = string.Format(CultureInfo.InvariantCulture, Resource.TestRunName, DeploymentFolderPrefix, #if NETFRAMEWORK Environment.UserName, diff --git a/src/Platform/Microsoft.Testing.Platform.MSBuild/Tasks/InvokeTestingPlatformTask.cs b/src/Platform/Microsoft.Testing.Platform.MSBuild/Tasks/InvokeTestingPlatformTask.cs index a10ac2eed5..67c20441c5 100644 --- a/src/Platform/Microsoft.Testing.Platform.MSBuild/Tasks/InvokeTestingPlatformTask.cs +++ b/src/Platform/Microsoft.Testing.Platform.MSBuild/Tasks/InvokeTestingPlatformTask.cs @@ -207,7 +207,7 @@ protected override string ToolName } Log.LogMessage(MessageImportance.Low, $"Current process architecture '{_currentProcessArchitecture}'. Requested test architecture '{TestArchitecture.ItemSpec}'"); - PlatformArchitecture targetArchitecture = EnumPolyfill.Parse(TestArchitecture.ItemSpec, ignoreCase: true); + PlatformArchitecture targetArchitecture = Enum.Parse(TestArchitecture.ItemSpec, ignoreCase: true); StringBuilder resolutionLog = new(); DotnetMuxerLocator dotnetMuxerLocator = new(log => resolutionLog.AppendLine(log)); if (dotnetMuxerLocator.TryGetDotnetPathByArchitecture(targetArchitecture, out string? dotnetPath)) @@ -241,7 +241,7 @@ protected override string ToolName } private bool IsCurrentProcessArchitectureCompatible() => - _currentProcessArchitecture == EnumPolyfill.Parse(TestArchitecture.ItemSpec, ignoreCase: true); + _currentProcessArchitecture == Enum.Parse(TestArchitecture.ItemSpec, ignoreCase: true); private string? TryGetRunCommand() { diff --git a/src/Platform/Microsoft.Testing.Platform/Builder/TestApplication.cs b/src/Platform/Microsoft.Testing.Platform/Builder/TestApplication.cs index e28553653c..b676230b17 100644 --- a/src/Platform/Microsoft.Testing.Platform/Builder/TestApplication.cs +++ b/src/Platform/Microsoft.Testing.Platform/Builder/TestApplication.cs @@ -286,7 +286,7 @@ private static ApplicationLoggingState CreateFileLoggerIfDiagnosticIsEnabled( if (result.TryGetOptionArgumentList(PlatformCommandLineProvider.DiagnosticVerbosityOptionKey, out string[]? verbosity)) { - logLevel = EnumPolyfill.Parse(verbosity[0], true); + logLevel = Enum.Parse(verbosity[0], true); } // Override the log level if the environment variable is set diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/ObjectModel/UnitTestElementTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/ObjectModel/UnitTestElementTests.cs index 688de5c88e..77fa92c814 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/ObjectModel/UnitTestElementTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/ObjectModel/UnitTestElementTests.cs @@ -173,7 +173,7 @@ public void ToTestCaseShouldSetDeploymentItemPropertyIfPresent() public void ToTestCase_WhenStrategyIsLegacy_UsesDefaultTestCaseId() { #pragma warning disable CA2263 // Prefer generic overload when type is known - foreach (DynamicDataType dataType in EnumPolyfill.GetValues()) + foreach (DynamicDataType dataType in Enum.GetValues()) { var testCase = new UnitTestElement(new("MyMethod", "MyProduct.MyNamespace.MyClass", "MyAssembly", null, TestIdGenerationStrategy.Legacy) { DataType = dataType }).ToTestCase(); var expectedTestCase = new TestCase(testCase.FullyQualifiedName, testCase.ExecutorUri, testCase.Source); @@ -187,7 +187,7 @@ public void ToTestCase_WhenStrategyIsLegacy_UsesDefaultTestCaseId() public void ToTestCase_WhenStrategyIsDisplayName_DoesNotUseDefaultTestCaseId() { #pragma warning disable CA2263 // Prefer generic overload when type is known - foreach (DynamicDataType dataType in EnumPolyfill.GetValues()) + foreach (DynamicDataType dataType in Enum.GetValues()) { var testCase = new UnitTestElement(new("MyMethod", "MyProduct.MyNamespace.MyClass", "MyAssembly", null, TestIdGenerationStrategy.DisplayName) { DataType = dataType }).ToTestCase(); var expectedTestCase = new TestCase(testCase.FullyQualifiedName, testCase.ExecutorUri, testCase.Source); @@ -208,7 +208,7 @@ public void ToTestCase_WhenStrategyIsDisplayName_DoesNotUseDefaultTestCaseId() public void ToTestCase_WhenStrategyIsData_DoesNotUseDefaultTestCaseId() { #pragma warning disable CA2263 // Prefer generic overload when type is known - foreach (DynamicDataType dataType in EnumPolyfill.GetValues()) + foreach (DynamicDataType dataType in Enum.GetValues()) { var testCase = new UnitTestElement(new("MyMethod", "MyProduct.MyNamespace.MyClass", "MyAssembly", null, TestIdGenerationStrategy.FullyQualified) { DataType = dataType }).ToTestCase(); var expectedTestCase = new TestCase(testCase.FullyQualifiedName, testCase.ExecutorUri, testCase.Source); From 3b0373298b6fd5444b6fbfcd2f600f35501d7c59 Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Mon, 30 Jun 2025 15:28:41 +1000 Subject: [PATCH 146/541] missing using in WindowsMiniDumpWriteDump (#5910) --- .../WindowsMiniDumpWriteDump.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Platform/Microsoft.Testing.Extensions.HangDump/WindowsMiniDumpWriteDump.cs b/src/Platform/Microsoft.Testing.Extensions.HangDump/WindowsMiniDumpWriteDump.cs index 41f2c6586d..d069d6e9f1 100644 --- a/src/Platform/Microsoft.Testing.Extensions.HangDump/WindowsMiniDumpWriteDump.cs +++ b/src/Platform/Microsoft.Testing.Extensions.HangDump/WindowsMiniDumpWriteDump.cs @@ -9,7 +9,7 @@ internal static class MiniDumpWriteDump { public static void CollectDumpUsingMiniDumpWriteDump(int pid, string outputFile, MiniDumpTypeOption type) { - var process = Process.GetProcessById(pid); + using var process = Process.GetProcessById(pid); // Open the file for writing using var stream = new FileStream(outputFile, FileMode.Create, FileAccess.ReadWrite, FileShare.None); From 2d4960874b06e569d1eb9299c3c749752805b3f4 Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Mon, 30 Jun 2025 15:29:25 +1000 Subject: [PATCH 147/541] remove redundant environment instance in TestHostBuilder (#5914) --- src/Platform/Microsoft.Testing.Platform/Hosts/TestHostBuilder.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostBuilder.cs b/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostBuilder.cs index 5091f98f92..f8da931a4b 100644 --- a/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostBuilder.cs +++ b/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostBuilder.cs @@ -134,7 +134,6 @@ public async Task BuildAsync( // Current test platform is picky on unhandled exception, we will tear down the process in that case. // This mode can be too aggressive especially compared to the old framework, so we allow the user to disable it if their suite // relies on unhandled exception. - IEnvironment environment = serviceProvider.GetEnvironment(); // Check the config file, by default is not specified the policy is false. _ = bool.TryParse(configuration[PlatformConfigurationConstants.PlatformExitProcessOnUnhandledException]!, out bool isFileConfiguredToFailFast); From e9d7169e3ad459f7ecc01e04df6efd9e0d6c8f7d Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Mon, 30 Jun 2025 16:35:20 +1000 Subject: [PATCH 148/541] Avoid keeping instance of process in DotnetMuxerLocator (#5911) --- .../Tasks/DotnetMuxerLocator.cs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Platform.MSBuild/Tasks/DotnetMuxerLocator.cs b/src/Platform/Microsoft.Testing.Platform.MSBuild/Tasks/DotnetMuxerLocator.cs index 0b3beddffd..28b8da2477 100644 --- a/src/Platform/Microsoft.Testing.Platform.MSBuild/Tasks/DotnetMuxerLocator.cs +++ b/src/Platform/Microsoft.Testing.Platform.MSBuild/Tasks/DotnetMuxerLocator.cs @@ -9,13 +9,14 @@ namespace Microsoft.Testing.Platform.MSBuild.Tasks; internal sealed class DotnetMuxerLocator { private readonly string _muxerName; - private readonly Process _currentProcess; private readonly Action _resolutionLog; + private readonly string _currentProcessFileName; internal DotnetMuxerLocator(Action resolutionLog) { _muxerName = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "dotnet.exe" : "dotnet"; - _currentProcess = Process.GetCurrentProcess(); + using var currentProcess = Process.GetCurrentProcess(); + _currentProcessFileName = currentProcess.MainModule!.FileName!; _resolutionLog = resolutionLog; } @@ -52,15 +53,14 @@ public bool TryGetDotnetPathByArchitecture( // If current process is the same as the target architecture we return the current process filename. if (GetCurrentProcessArchitecture() == targetArchitecture) { - string currentProcessFileName = _currentProcess.MainModule!.FileName!; - if (Path.GetFileName(currentProcessFileName) == _muxerName) + if (Path.GetFileName(_currentProcessFileName) == _muxerName) { - muxerPath = currentProcessFileName; + muxerPath = _currentProcessFileName; _resolutionLog($"DotnetHostHelper.TryGetDotnetPathByArchitecture: Target architecture is the same as the current process architecture '{targetArchitecture}', and the current process is a muxer, using that: '{muxerPath}'"); return true; } - _resolutionLog($"DotnetHostHelper.TryGetDotnetPathByArchitecture: Target architecture is the same as the current process architecture '{targetArchitecture}', but the current process is not a muxer: '{currentProcessFileName}'"); + _resolutionLog($"DotnetHostHelper.TryGetDotnetPathByArchitecture: Target architecture is the same as the current process architecture '{targetArchitecture}', but the current process is not a muxer: '{_currentProcessFileName}'"); } // We used similar approach as the runtime resolver. From 2e25e6fd7403640a6b60805706b28d97aa8320b3 Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Mon, 30 Jun 2025 16:36:41 +1000 Subject: [PATCH 149/541] remove-zero-width-spaces-from-banned-symbols (#5912) --- src/Adapter/MSTest.Engine/BannedSymbols.txt | 2 +- .../BannedSymbols.txt | 2 +- .../Microsoft.Testing.Extensions.CrashDump/BannedSymbols.txt | 2 +- .../Microsoft.Testing.Extensions.HangDump/BannedSymbols.txt | 2 +- .../Microsoft.Testing.Extensions.HotReload/BannedSymbols.txt | 2 +- .../Microsoft.Testing.Extensions.Retry/BannedSymbols.txt | 2 +- .../Microsoft.Testing.Extensions.Telemetry/BannedSymbols.txt | 2 +- .../BannedSymbols.txt | 2 +- .../Microsoft.Testing.Extensions.TrxReport/BannedSymbols.txt | 2 +- .../Microsoft.Testing.Extensions.VSTestBridge/BannedSymbols.txt | 2 +- src/Platform/Microsoft.Testing.Platform/BannedSymbols.txt | 2 +- 11 files changed, 11 insertions(+), 11 deletions(-) diff --git a/src/Adapter/MSTest.Engine/BannedSymbols.txt b/src/Adapter/MSTest.Engine/BannedSymbols.txt index 8c5d85ec6d..f7256d3c54 100644 --- a/src/Adapter/MSTest.Engine/BannedSymbols.txt +++ b/src/Adapter/MSTest.Engine/BannedSymbols.txt @@ -2,5 +2,5 @@ M:System.Threading.Tasks.Task.Run(System.Func{System.Threading.Tasks.Task},System.Threading.CancellationToken); Use 'ITask' instead M:System.String.IsNullOrEmpty(System.String); Use 'RoslynString.IsNullOrEmpty' instead M:System.String.IsNullOrWhiteSpace(System.String); Use 'RoslynString.IsNullOrWhiteSpace' instead -M:System.Diagnostics.Debug.Assert(System.Boolean); Use 'RoslynDebug.Assert' instead +M:System.Diagnostics.Debug.Assert(System.Boolean); Use 'RoslynDebug.Assert' instead M:System.Diagnostics.Debug.Assert(System.Boolean,System.String); Use 'RoslynDebug.Assert' instead diff --git a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/BannedSymbols.txt b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/BannedSymbols.txt index ea8617fcb0..09d715c49c 100644 --- a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/BannedSymbols.txt +++ b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/BannedSymbols.txt @@ -6,5 +6,5 @@ M:System.Threading.Tasks.Task.WhenAll(System.Threading.Tasks.Task[]); Use 'ITask M:System.Threading.Tasks.Task.WhenAll(System.Collections.Generic.IEnumerable{System.Threading.Tasks.Task}); Use 'ITask' instead M:System.String.IsNullOrEmpty(System.String); Use 'RoslynString.IsNullOrEmpty' instead M:System.String.IsNullOrWhiteSpace(System.String); Use 'RoslynString.IsNullOrWhiteSpace' instead -M:System.Diagnostics.Debug.Assert(System.Boolean); Use 'RoslynDebug.Assert' instead +M:System.Diagnostics.Debug.Assert(System.Boolean); Use 'RoslynDebug.Assert' instead M:System.Diagnostics.Debug.Assert(System.Boolean,System.String); Use 'RoslynDebug.Assert' instead diff --git a/src/Platform/Microsoft.Testing.Extensions.CrashDump/BannedSymbols.txt b/src/Platform/Microsoft.Testing.Extensions.CrashDump/BannedSymbols.txt index ea8617fcb0..09d715c49c 100644 --- a/src/Platform/Microsoft.Testing.Extensions.CrashDump/BannedSymbols.txt +++ b/src/Platform/Microsoft.Testing.Extensions.CrashDump/BannedSymbols.txt @@ -6,5 +6,5 @@ M:System.Threading.Tasks.Task.WhenAll(System.Threading.Tasks.Task[]); Use 'ITask M:System.Threading.Tasks.Task.WhenAll(System.Collections.Generic.IEnumerable{System.Threading.Tasks.Task}); Use 'ITask' instead M:System.String.IsNullOrEmpty(System.String); Use 'RoslynString.IsNullOrEmpty' instead M:System.String.IsNullOrWhiteSpace(System.String); Use 'RoslynString.IsNullOrWhiteSpace' instead -M:System.Diagnostics.Debug.Assert(System.Boolean); Use 'RoslynDebug.Assert' instead +M:System.Diagnostics.Debug.Assert(System.Boolean); Use 'RoslynDebug.Assert' instead M:System.Diagnostics.Debug.Assert(System.Boolean,System.String); Use 'RoslynDebug.Assert' instead diff --git a/src/Platform/Microsoft.Testing.Extensions.HangDump/BannedSymbols.txt b/src/Platform/Microsoft.Testing.Extensions.HangDump/BannedSymbols.txt index ea8617fcb0..09d715c49c 100644 --- a/src/Platform/Microsoft.Testing.Extensions.HangDump/BannedSymbols.txt +++ b/src/Platform/Microsoft.Testing.Extensions.HangDump/BannedSymbols.txt @@ -6,5 +6,5 @@ M:System.Threading.Tasks.Task.WhenAll(System.Threading.Tasks.Task[]); Use 'ITask M:System.Threading.Tasks.Task.WhenAll(System.Collections.Generic.IEnumerable{System.Threading.Tasks.Task}); Use 'ITask' instead M:System.String.IsNullOrEmpty(System.String); Use 'RoslynString.IsNullOrEmpty' instead M:System.String.IsNullOrWhiteSpace(System.String); Use 'RoslynString.IsNullOrWhiteSpace' instead -M:System.Diagnostics.Debug.Assert(System.Boolean); Use 'RoslynDebug.Assert' instead +M:System.Diagnostics.Debug.Assert(System.Boolean); Use 'RoslynDebug.Assert' instead M:System.Diagnostics.Debug.Assert(System.Boolean,System.String); Use 'RoslynDebug.Assert' instead diff --git a/src/Platform/Microsoft.Testing.Extensions.HotReload/BannedSymbols.txt b/src/Platform/Microsoft.Testing.Extensions.HotReload/BannedSymbols.txt index 5bc5c2fb96..6b0c437d6e 100644 --- a/src/Platform/Microsoft.Testing.Extensions.HotReload/BannedSymbols.txt +++ b/src/Platform/Microsoft.Testing.Extensions.HotReload/BannedSymbols.txt @@ -6,5 +6,5 @@ M:System.Threading.Tasks.Task.WhenAll(System.Threading.Tasks.Task[]); Use 'ITask M:System.Threading.Tasks.Task.WhenAll(System.Collections.Generic.IEnumerable{System.Threading.Tasks.Task}); Use 'ITask' instead M:System.String.IsNullOrEmpty(System.String); Use 'RoslynString.IsNullOrEmpty' instead M:System.String.IsNullOrWhiteSpace(System.String); Use 'RoslynString.IsNullOrWhiteSpace' instead -M:System.Diagnostics.Debug.Assert(System.Boolean); Use 'RoslynDebug.Assert' instead +M:System.Diagnostics.Debug.Assert(System.Boolean); Use 'RoslynDebug.Assert' instead M:System.Diagnostics.Debug.Assert(System.Boolean,System.String); Use 'RoslynDebug.Assert' instead diff --git a/src/Platform/Microsoft.Testing.Extensions.Retry/BannedSymbols.txt b/src/Platform/Microsoft.Testing.Extensions.Retry/BannedSymbols.txt index 5bc5c2fb96..6b0c437d6e 100644 --- a/src/Platform/Microsoft.Testing.Extensions.Retry/BannedSymbols.txt +++ b/src/Platform/Microsoft.Testing.Extensions.Retry/BannedSymbols.txt @@ -6,5 +6,5 @@ M:System.Threading.Tasks.Task.WhenAll(System.Threading.Tasks.Task[]); Use 'ITask M:System.Threading.Tasks.Task.WhenAll(System.Collections.Generic.IEnumerable{System.Threading.Tasks.Task}); Use 'ITask' instead M:System.String.IsNullOrEmpty(System.String); Use 'RoslynString.IsNullOrEmpty' instead M:System.String.IsNullOrWhiteSpace(System.String); Use 'RoslynString.IsNullOrWhiteSpace' instead -M:System.Diagnostics.Debug.Assert(System.Boolean); Use 'RoslynDebug.Assert' instead +M:System.Diagnostics.Debug.Assert(System.Boolean); Use 'RoslynDebug.Assert' instead M:System.Diagnostics.Debug.Assert(System.Boolean,System.String); Use 'RoslynDebug.Assert' instead diff --git a/src/Platform/Microsoft.Testing.Extensions.Telemetry/BannedSymbols.txt b/src/Platform/Microsoft.Testing.Extensions.Telemetry/BannedSymbols.txt index 469bd16cf9..0fcaeeec4b 100644 --- a/src/Platform/Microsoft.Testing.Extensions.Telemetry/BannedSymbols.txt +++ b/src/Platform/Microsoft.Testing.Extensions.Telemetry/BannedSymbols.txt @@ -1,4 +1,4 @@ M:System.String.IsNullOrEmpty(System.String); Use 'TAString.IsNullOrEmpty' instead M:System.String.IsNullOrWhiteSpace(System.String); Use 'TAString.IsNullOrWhiteSpace' instead -M:System.Diagnostics.Debug.Assert(System.Boolean); Use 'RoslynDebug.Assert' instead +M:System.Diagnostics.Debug.Assert(System.Boolean); Use 'RoslynDebug.Assert' instead M:System.Diagnostics.Debug.Assert(System.Boolean,System.String); Use 'RoslynDebug.Assert' instead diff --git a/src/Platform/Microsoft.Testing.Extensions.TrxReport.Abstractions/BannedSymbols.txt b/src/Platform/Microsoft.Testing.Extensions.TrxReport.Abstractions/BannedSymbols.txt index ea8617fcb0..09d715c49c 100644 --- a/src/Platform/Microsoft.Testing.Extensions.TrxReport.Abstractions/BannedSymbols.txt +++ b/src/Platform/Microsoft.Testing.Extensions.TrxReport.Abstractions/BannedSymbols.txt @@ -6,5 +6,5 @@ M:System.Threading.Tasks.Task.WhenAll(System.Threading.Tasks.Task[]); Use 'ITask M:System.Threading.Tasks.Task.WhenAll(System.Collections.Generic.IEnumerable{System.Threading.Tasks.Task}); Use 'ITask' instead M:System.String.IsNullOrEmpty(System.String); Use 'RoslynString.IsNullOrEmpty' instead M:System.String.IsNullOrWhiteSpace(System.String); Use 'RoslynString.IsNullOrWhiteSpace' instead -M:System.Diagnostics.Debug.Assert(System.Boolean); Use 'RoslynDebug.Assert' instead +M:System.Diagnostics.Debug.Assert(System.Boolean); Use 'RoslynDebug.Assert' instead M:System.Diagnostics.Debug.Assert(System.Boolean,System.String); Use 'RoslynDebug.Assert' instead diff --git a/src/Platform/Microsoft.Testing.Extensions.TrxReport/BannedSymbols.txt b/src/Platform/Microsoft.Testing.Extensions.TrxReport/BannedSymbols.txt index ea8617fcb0..09d715c49c 100644 --- a/src/Platform/Microsoft.Testing.Extensions.TrxReport/BannedSymbols.txt +++ b/src/Platform/Microsoft.Testing.Extensions.TrxReport/BannedSymbols.txt @@ -6,5 +6,5 @@ M:System.Threading.Tasks.Task.WhenAll(System.Threading.Tasks.Task[]); Use 'ITask M:System.Threading.Tasks.Task.WhenAll(System.Collections.Generic.IEnumerable{System.Threading.Tasks.Task}); Use 'ITask' instead M:System.String.IsNullOrEmpty(System.String); Use 'RoslynString.IsNullOrEmpty' instead M:System.String.IsNullOrWhiteSpace(System.String); Use 'RoslynString.IsNullOrWhiteSpace' instead -M:System.Diagnostics.Debug.Assert(System.Boolean); Use 'RoslynDebug.Assert' instead +M:System.Diagnostics.Debug.Assert(System.Boolean); Use 'RoslynDebug.Assert' instead M:System.Diagnostics.Debug.Assert(System.Boolean,System.String); Use 'RoslynDebug.Assert' instead diff --git a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/BannedSymbols.txt b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/BannedSymbols.txt index 13daece7e1..6c52641180 100644 --- a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/BannedSymbols.txt +++ b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/BannedSymbols.txt @@ -1,5 +1,5 @@ T:System.ArgumentNullException; Use 'ArgumentGuard' class instead M:System.String.IsNullOrEmpty(System.String); Use 'RoslynString.IsNullOrEmpty' instead M:System.String.IsNullOrWhiteSpace(System.String); Use 'RoslynString.IsNullOrWhiteSpace' instead -M:System.Diagnostics.Debug.Assert(System.Boolean); Use 'RoslynDebug.Assert' instead +M:System.Diagnostics.Debug.Assert(System.Boolean); Use 'RoslynDebug.Assert' instead M:System.Diagnostics.Debug.Assert(System.Boolean,System.String); Use 'RoslynDebug.Assert' instead diff --git a/src/Platform/Microsoft.Testing.Platform/BannedSymbols.txt b/src/Platform/Microsoft.Testing.Platform/BannedSymbols.txt index dde632bded..96906f3552 100644 --- a/src/Platform/Microsoft.Testing.Platform/BannedSymbols.txt +++ b/src/Platform/Microsoft.Testing.Platform/BannedSymbols.txt @@ -7,5 +7,5 @@ M:System.Diagnostics.Process.GetCurrentProcess(); Use 'IProcess' instead M:System.Diagnostics.Process.Start(System.Diagnostics.ProcessStartInfo); Use 'IProcess' instead M:System.String.IsNullOrEmpty(System.String); Use 'RoslynString.IsNullOrEmpty' instead M:System.String.IsNullOrWhiteSpace(System.String); Use 'RoslynString.IsNullOrWhiteSpace' instead -M:System.Diagnostics.Debug.Assert(System.Boolean); Use 'RoslynDebug.Assert' instead +M:System.Diagnostics.Debug.Assert(System.Boolean); Use 'RoslynDebug.Assert' instead M:System.Diagnostics.Debug.Assert(System.Boolean,System.String); Use 'RoslynDebug.Assert' instead From f319a124380a489e853f1de54c3df970744647fe Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Mon, 30 Jun 2025 16:39:53 +1000 Subject: [PATCH 150/541] Add ProcessId to IEnvironment (#5913) --- .../Builder/TestApplication.cs | 5 ++--- .../Helpers/System/IEnvironment.cs | 2 ++ .../Helpers/System/SystemEnvironment.cs | 2 ++ .../Hosts/ServerTestHost.cs | 2 +- .../Hosts/TestHostBuilder.cs | 9 +++------ .../Hosts/TestHostControllersTestHost.cs | 19 +++++++++---------- .../DotnetTest/DotnetTestConnection.cs | 6 ++---- .../ServerMode/JsonRpc/PassiveNode.cs | 8 ++++---- 8 files changed, 25 insertions(+), 28 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Platform/Builder/TestApplication.cs b/src/Platform/Microsoft.Testing.Platform/Builder/TestApplication.cs index b676230b17..aea7efebe8 100644 --- a/src/Platform/Microsoft.Testing.Platform/Builder/TestApplication.cs +++ b/src/Platform/Microsoft.Testing.Platform/Builder/TestApplication.cs @@ -125,8 +125,7 @@ private static async Task LogInformationAsync( await logger.LogInformationAsync("Logging mode: " + (syncWrite ? "synchronous" : "asynchronous")).ConfigureAwait(false); await logger.LogInformationAsync($"Logging level: {loggerLevel}").ConfigureAwait(false); await logger.LogInformationAsync($"CreateBuilderAsync entry time: {createBuilderEntryTime}").ConfigureAwait(false); - using IProcess currentProcess = processHandler.GetCurrentProcess(); - await logger.LogInformationAsync($"PID: {currentProcess.Id}").ConfigureAwait(false); + await logger.LogInformationAsync($"PID: {environment.ProcessId}").ConfigureAwait(false); #if NETCOREAPP string runtimeInformation = $"{RuntimeInformation.RuntimeIdentifier} - {RuntimeInformation.FrameworkDescription}"; @@ -237,7 +236,7 @@ private static void AttachDebuggerIfNeeded(SystemEnvironment environment, System if (environment.GetEnvironmentVariable(EnvironmentVariableConstants.TESTINGPLATFORM_WAIT_ATTACH_DEBUGGER) == "1") { IProcess currentProcess = systemProcess.GetCurrentProcess(); - console.WriteLine($"Waiting for debugger to attach... Process Id: {currentProcess.Id}, Name: {currentProcess.Name}"); + console.WriteLine($"Waiting for debugger to attach... Process Id: {environment.ProcessId}, Name: {currentProcess.Name}"); while (!Debugger.IsAttached) { diff --git a/src/Platform/Microsoft.Testing.Platform/Helpers/System/IEnvironment.cs b/src/Platform/Microsoft.Testing.Platform/Helpers/System/IEnvironment.cs index b44afb7377..dfcab15fbb 100644 --- a/src/Platform/Microsoft.Testing.Platform/Helpers/System/IEnvironment.cs +++ b/src/Platform/Microsoft.Testing.Platform/Helpers/System/IEnvironment.cs @@ -11,6 +11,8 @@ internal interface IEnvironment string NewLine { get; } + int ProcessId { get; } + string OsVersion { get; } #if NETCOREAPP diff --git a/src/Platform/Microsoft.Testing.Platform/Helpers/System/SystemEnvironment.cs b/src/Platform/Microsoft.Testing.Platform/Helpers/System/SystemEnvironment.cs index a7ea4efe62..5723b9cfa5 100644 --- a/src/Platform/Microsoft.Testing.Platform/Helpers/System/SystemEnvironment.cs +++ b/src/Platform/Microsoft.Testing.Platform/Helpers/System/SystemEnvironment.cs @@ -12,6 +12,8 @@ internal sealed class SystemEnvironment : IEnvironment public string NewLine => Environment.NewLine; + public int ProcessId => Environment.ProcessId; + public string OsVersion => Environment.OSVersion.ToString(); #if NETCOREAPP diff --git a/src/Platform/Microsoft.Testing.Platform/Hosts/ServerTestHost.cs b/src/Platform/Microsoft.Testing.Platform/Hosts/ServerTestHost.cs index bc5168c5c5..84874e8296 100644 --- a/src/Platform/Microsoft.Testing.Platform/Hosts/ServerTestHost.cs +++ b/src/Platform/Microsoft.Testing.Platform/Hosts/ServerTestHost.cs @@ -405,7 +405,7 @@ private async Task HandleRequestCoreAsync(RequestMessage message, RpcInv INamedFeatureCapability? namedFeatureCapability = ServiceProvider.GetTestFrameworkCapabilities().GetCapability(); return new InitializeResponseArgs( - ProcessId: ServiceProvider.GetProcessHandler().GetCurrentProcess().Id, + ProcessId: ServiceProvider.GetEnvironment().ProcessId, ServerInfo: new ServerInfo("test-anywhere", Version: ProtocolVersion), Capabilities: new ServerCapabilities( new ServerTestingCapabilities( diff --git a/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostBuilder.cs b/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostBuilder.cs index f8da931a4b..a0301d1535 100644 --- a/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostBuilder.cs +++ b/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostBuilder.cs @@ -328,7 +328,7 @@ await LogTestHostCreatedAsync( return toolsTestHost; } - var pushOnlyProtocol = new DotnetTestConnection(commandLineHandler, processHandler, environment, _testApplicationModuleInfo, testApplicationCancellationTokenSource); + var pushOnlyProtocol = new DotnetTestConnection(commandLineHandler, environment, _testApplicationModuleInfo, testApplicationCancellationTokenSource); await pushOnlyProtocol.AfterCommonServiceSetupAsync().ConfigureAwait(false); if (pushOnlyProtocol.IsServerMode) { @@ -387,7 +387,7 @@ await LogTestHostCreatedAsync( passiveNode = new PassiveNode( messageHandlerFactory, testApplicationCancellationTokenSource, - processHandler, + systemEnvironment, systemMonitorAsyncFactory, loggerFactory.CreateLogger()); } @@ -432,7 +432,6 @@ await LogTestHostCreatedAsync( // If we're under test controllers and currently we're inside the started test host we connect to the out of process // test controller manager. NamedPipeClient? testControllerConnection = await ConnectToTestHostProcessMonitorIfAvailableAsync( - processHandler, testApplicationCancellationTokenSource, loggerFactory.CreateLogger(nameof(ConnectToTestHostProcessMonitorIfAvailableAsync)), testHostControllerInfo, @@ -521,7 +520,6 @@ await LogTestHostCreatedAsync( } private static async Task ConnectToTestHostProcessMonitorIfAvailableAsync( - IProcessHandler processHandler, CTRLPlusCCancellationTokenSource testApplicationCancellationTokenSource, ILogger logger, TestHostControllerInfo testHostControllerInfo, @@ -555,9 +553,8 @@ await LogTestHostCreatedAsync( await logger.LogDebugAsync($"Connected to named pipe '{pipeName}'").ConfigureAwait(false); // Send the PID - using IProcess currentProcess = processHandler.GetCurrentProcess(); await client.RequestReplyAsync( - new TestHostProcessPIDRequest(currentProcess.Id), + new TestHostProcessPIDRequest(environment.ProcessId), testApplicationCancellationTokenSource.CancellationToken).ConfigureAwait(false); return client; } diff --git a/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostControllersTestHost.cs b/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostControllersTestHost.cs index 5ed3207de1..42965ff6b4 100644 --- a/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostControllersTestHost.cs +++ b/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostControllersTestHost.cs @@ -76,9 +76,8 @@ protected override async Task InternalRunAsync() IConfiguration configuration = ServiceProvider.GetConfiguration(); try { - using IProcess currentProcess = process.GetCurrentProcess(); - int currentPID = currentProcess.Id; - string processIdString = currentPID.ToString(CultureInfo.InvariantCulture); + int currentPid = environment.ProcessId; + string processIdString = currentPid.ToString(CultureInfo.InvariantCulture); ExecutableInfo executableInfo = testApplicationModuleInfo.GetCurrentExecutableInfo(); await _logger.LogDebugAsync($"Test host controller process info: {executableInfo}").ConfigureAwait(false); @@ -92,7 +91,7 @@ protected override async Task InternalRunAsync() // Prepare the environment variables used by the test host string processCorrelationId = Guid.NewGuid().ToString("N"); - await _logger.LogDebugAsync($"{EnvironmentVariableConstants.TESTINGPLATFORM_TESTHOSTCONTROLLER_CORRELATIONID}_{currentPID} '{processCorrelationId}'").ConfigureAwait(false); + await _logger.LogDebugAsync($"{EnvironmentVariableConstants.TESTINGPLATFORM_TESTHOSTCONTROLLER_CORRELATIONID}_{currentPid} '{processCorrelationId}'").ConfigureAwait(false); NamedPipeServer testHostControllerIpc = new( $"MONITORTOHOST_{Guid.NewGuid():N}", @@ -115,10 +114,10 @@ protected override async Task InternalRunAsync() { EnvironmentVariables = { - { $"{EnvironmentVariableConstants.TESTINGPLATFORM_TESTHOSTCONTROLLER_CORRELATIONID}_{currentPID}", processCorrelationId }, - { $"{EnvironmentVariableConstants.TESTINGPLATFORM_TESTHOSTCONTROLLER_PARENTPID}_{currentPID}", processIdString }, - { $"{EnvironmentVariableConstants.TESTINGPLATFORM_TESTHOSTCONTROLLER_SKIPEXTENSION}_{currentPID}", "1" }, - { $"{EnvironmentVariableConstants.TESTINGPLATFORM_TESTHOSTCONTROLLER_PIPENAME}_{currentPID}", testHostControllerIpc.PipeName.Name }, + { $"{EnvironmentVariableConstants.TESTINGPLATFORM_TESTHOSTCONTROLLER_CORRELATIONID}_{currentPid}", processCorrelationId }, + { $"{EnvironmentVariableConstants.TESTINGPLATFORM_TESTHOSTCONTROLLER_PARENTPID}_{currentPid}", processIdString }, + { $"{EnvironmentVariableConstants.TESTINGPLATFORM_TESTHOSTCONTROLLER_SKIPEXTENSION}_{currentPid}", "1" }, + { $"{EnvironmentVariableConstants.TESTINGPLATFORM_TESTHOSTCONTROLLER_PIPENAME}_{currentPid}", testHostControllerIpc.PipeName.Name }, }, #if !NETCOREAPP UseShellExecute = false, @@ -230,9 +229,9 @@ protected override async Task InternalRunAsync() // Launch the test host process string testHostProcessStartupTime = _clock.UtcNow.ToString("HH:mm:ss.fff", CultureInfo.InvariantCulture); #pragma warning disable CA1416 // Validate platform compatibility - processStartInfo.EnvironmentVariables.Add($"{EnvironmentVariableConstants.TESTINGPLATFORM_TESTHOSTCONTROLLER_TESTHOSTPROCESSSTARTTIME}_{currentPID}", testHostProcessStartupTime); + processStartInfo.EnvironmentVariables.Add($"{EnvironmentVariableConstants.TESTINGPLATFORM_TESTHOSTCONTROLLER_TESTHOSTPROCESSSTARTTIME}_{currentPid}", testHostProcessStartupTime); #pragma warning restore CA1416 - await _logger.LogDebugAsync($"{EnvironmentVariableConstants.TESTINGPLATFORM_TESTHOSTCONTROLLER_TESTHOSTPROCESSSTARTTIME}_{currentPID} '{testHostProcessStartupTime}'").ConfigureAwait(false); + await _logger.LogDebugAsync($"{EnvironmentVariableConstants.TESTINGPLATFORM_TESTHOSTCONTROLLER_TESTHOSTPROCESSSTARTTIME}_{currentPid} '{testHostProcessStartupTime}'").ConfigureAwait(false); #pragma warning disable CA1416 // Validate platform compatibility await _logger.LogDebugAsync($"Starting test host process '{processStartInfo.FileName}' with args '{processStartInfo.Arguments}'").ConfigureAwait(false); #pragma warning restore CA1416 diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/DotnetTestConnection.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/DotnetTestConnection.cs index d69a7c0220..faeea63c18 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/DotnetTestConnection.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/DotnetTestConnection.cs @@ -20,7 +20,6 @@ internal sealed class DotnetTestConnection : IPushOnlyProtocol, IDisposable { private readonly CommandLineHandler _commandLineHandler; - private readonly IProcessHandler _processHandler; private readonly IEnvironment _environment; private readonly ITestApplicationModuleInfo _testApplicationModuleInfo; private readonly ITestApplicationCancellationTokenSource _cancellationTokenSource; @@ -29,10 +28,9 @@ internal sealed class DotnetTestConnection : IPushOnlyProtocol, public static string InstanceId { get; } = Guid.NewGuid().ToString("N"); - public DotnetTestConnection(CommandLineHandler commandLineHandler, IProcessHandler processHandler, IEnvironment environment, ITestApplicationModuleInfo testApplicationModuleInfo, ITestApplicationCancellationTokenSource cancellationTokenSource) + public DotnetTestConnection(CommandLineHandler commandLineHandler, IEnvironment environment, ITestApplicationModuleInfo testApplicationModuleInfo, ITestApplicationCancellationTokenSource cancellationTokenSource) { _commandLineHandler = commandLineHandler; - _processHandler = processHandler; _environment = environment; _testApplicationModuleInfo = testApplicationModuleInfo; _cancellationTokenSource = cancellationTokenSource; @@ -97,7 +95,7 @@ public async Task IsCompatibleProtocolAsync(string hostType) string supportedProtocolVersions = ProtocolConstants.Version; HandshakeMessage handshakeMessage = new(new Dictionary { - { HandshakeMessagePropertyNames.PID, _processHandler.GetCurrentProcess().Id.ToString(CultureInfo.InvariantCulture) }, + { HandshakeMessagePropertyNames.PID, _environment.ProcessId.ToString(CultureInfo.InvariantCulture) }, { HandshakeMessagePropertyNames.Architecture, RuntimeInformation.ProcessArchitecture.ToString() }, { HandshakeMessagePropertyNames.Framework, RuntimeInformation.FrameworkDescription }, { HandshakeMessagePropertyNames.OS, RuntimeInformation.OSDescription }, diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/PassiveNode.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/PassiveNode.cs index 9bd65b9908..931755233f 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/PassiveNode.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/PassiveNode.cs @@ -11,7 +11,7 @@ internal sealed class PassiveNode : IDisposable { private readonly IMessageHandlerFactory _messageHandlerFactory; private readonly ITestApplicationCancellationTokenSource _testApplicationCancellationTokenSource; - private readonly IProcessHandler _processHandler; + private readonly IEnvironment _environment; private readonly ILogger _logger; private readonly IAsyncMonitor _messageMonitor; private IMessageHandler? _messageHandler; @@ -19,13 +19,13 @@ internal sealed class PassiveNode : IDisposable public PassiveNode( IMessageHandlerFactory messageHandlerFactory, ITestApplicationCancellationTokenSource testApplicationCancellationTokenSource, - IProcessHandler processHandler, + IEnvironment environment, IAsyncMonitorFactory asyncMonitorFactory, ILogger logger) { _messageHandlerFactory = messageHandlerFactory; _testApplicationCancellationTokenSource = testApplicationCancellationTokenSource; - _processHandler = processHandler; + _environment = environment; _messageMonitor = asyncMonitorFactory.Create(); _logger = logger; } @@ -61,7 +61,7 @@ public async Task ConnectAsync() var requestMessage = (RequestMessage)message; var responseObject = new InitializeResponseArgs( - ProcessId: _processHandler.GetCurrentProcess().Id, + ProcessId: _environment.ProcessId, ServerInfo: new ServerInfo("test-anywhere", Version: PlatformVersion.Version), Capabilities: new ServerCapabilities( new ServerTestingCapabilities( From 7c6569b6b023f1048e58164ed51662e621a285e0 Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Mon, 30 Jun 2025 17:11:01 +1000 Subject: [PATCH 151/541] CrashDumpEnvironmentVariableProvider prefixes can be static (#5909) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Amaury Levé --- .../CrashDumpEnvironmentVariableProvider.cs | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Extensions.CrashDump/CrashDumpEnvironmentVariableProvider.cs b/src/Platform/Microsoft.Testing.Extensions.CrashDump/CrashDumpEnvironmentVariableProvider.cs index 2dfd370a18..8ca9a523cb 100644 --- a/src/Platform/Microsoft.Testing.Extensions.CrashDump/CrashDumpEnvironmentVariableProvider.cs +++ b/src/Platform/Microsoft.Testing.Extensions.CrashDump/CrashDumpEnvironmentVariableProvider.cs @@ -21,7 +21,7 @@ internal sealed class CrashDumpEnvironmentVariableProvider : ITestHostEnvironmen private const string CreateDumpVerboseDiagnosticsVariable = "CreateDumpVerboseDiagnostics"; private const string EnableMiniDumpValue = "1"; - private readonly string[] _prefixes = ["DOTNET_", "COMPlus_"]; + private static readonly string[] Prefixes = ["DOTNET_", "COMPlus_"]; private readonly IConfiguration _configuration; private readonly ICommandLineOptions _commandLineOptions; private readonly ITestApplicationModuleInfo _testApplicationModuleInfo; @@ -62,7 +62,7 @@ public Task IsEnabledAsync() public Task UpdateAsync(IEnvironmentVariables environmentVariables) { - foreach (string prefix in _prefixes) + foreach (string prefix in Prefixes) { environmentVariables.SetVariable(new($"{prefix}{EnableMiniDumpVariable}", EnableMiniDumpValue, false, true)); environmentVariables.SetVariable(new($"{prefix}{CreateDumpDiagnosticsVariable}", EnableMiniDumpValue, false, true)); @@ -107,7 +107,7 @@ public Task UpdateAsync(IEnvironmentVariables environmentVariables) } } - foreach (string prefix in _prefixes) + foreach (string prefix in Prefixes) { environmentVariables.SetVariable(new($"{prefix}{MiniDumpTypeVariable}", miniDumpTypeValue, false, true)); } @@ -116,7 +116,7 @@ public Task UpdateAsync(IEnvironmentVariables environmentVariables) ? Path.Combine(_configuration.GetTestResultDirectory(), dumpFileName[0]) : Path.Combine(_configuration.GetTestResultDirectory(), $"{Path.GetFileNameWithoutExtension(_testApplicationModuleInfo.GetCurrentTestApplicationFullPath())}_%p_crash.dmp"); _crashDumpGeneratorConfiguration.DumpFileNamePattern = _miniDumpNameValue; - foreach (string prefix in _prefixes) + foreach (string prefix in Prefixes) { environmentVariables.SetVariable(new($"{prefix}{MiniDumpNameVariable}", _miniDumpNameValue, false, true)); } @@ -136,7 +136,7 @@ public Task ValidateTestHostEnvironmentVariablesAsync(IReadOnl return ValidationResult.InvalidTask(CrashDumpResources.CrashDumpNotSupportedInNonNetCoreErrorMessage); #else StringBuilder errors = new(); - foreach (string prefix in _prefixes) + foreach (string prefix in Prefixes) { if (!environmentVariables.TryGetVariable($"{prefix}{EnableMiniDumpVariable}", out OwnedEnvironmentVariable? enableMiniDump) || enableMiniDump.Value != EnableMiniDumpValue) @@ -145,7 +145,7 @@ public Task ValidateTestHostEnvironmentVariablesAsync(IReadOnl } } - foreach (string prefix in _prefixes) + foreach (string prefix in Prefixes) { if (!environmentVariables.TryGetVariable($"{prefix}{CreateDumpDiagnosticsVariable}", out OwnedEnvironmentVariable? enableMiniDump) || enableMiniDump.Value != EnableMiniDumpValue) @@ -154,7 +154,7 @@ public Task ValidateTestHostEnvironmentVariablesAsync(IReadOnl } } - foreach (string prefix in _prefixes) + foreach (string prefix in Prefixes) { if (!environmentVariables.TryGetVariable($"{prefix}{CreateDumpVerboseDiagnosticsVariable}", out OwnedEnvironmentVariable? enableMiniDump) || enableMiniDump.Value != EnableMiniDumpValue) @@ -163,7 +163,7 @@ public Task ValidateTestHostEnvironmentVariablesAsync(IReadOnl } } - foreach (string prefix in _prefixes) + foreach (string prefix in Prefixes) { if (!environmentVariables.TryGetVariable($"{prefix}{MiniDumpTypeVariable}", out OwnedEnvironmentVariable? miniDumpType)) { @@ -186,7 +186,7 @@ public Task ValidateTestHostEnvironmentVariablesAsync(IReadOnl } } - foreach (string prefix in _prefixes) + foreach (string prefix in Prefixes) { if (!environmentVariables.TryGetVariable($"{prefix}{MiniDumpNameVariable}", out OwnedEnvironmentVariable? miniDumpName) || miniDumpName.Value != _miniDumpNameValue) From ea6bb35ffc4d0b236ddb43377dada8b361b34f2e Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Mon, 30 Jun 2025 18:11:13 +1000 Subject: [PATCH 152/541] use some string interpolation (#5915) --- .../Extensions/TestResultExtensions.cs | 16 ++++++++++++++-- .../ObjectModel/Condition.cs | 9 ++++----- .../ObjectModel/ContextAdapterBase.cs | 7 +------ .../ObjectModel/FastFilter.cs | 2 +- .../Terminal/TerminalTestReporter.cs | 4 ++-- .../TestDataSourceExTests.cs | 6 +++--- 6 files changed, 25 insertions(+), 19 deletions(-) diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Extensions/TestResultExtensions.cs b/src/Adapter/MSTestAdapter.PlatformServices/Extensions/TestResultExtensions.cs index a92ccf186a..b6e54ec833 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Extensions/TestResultExtensions.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Extensions/TestResultExtensions.cs @@ -70,14 +70,26 @@ internal static VSTestTestResult ToTestResult(this TestResult frameworkTestResul if (!StringEx.IsNullOrEmpty(frameworkTestResult.DebugTrace)) { - string debugTraceMessagesInStdOut = string.Format(CultureInfo.CurrentCulture, "{2}{2}{0}{2}{1}", Resource.DebugTraceBanner, frameworkTestResult.DebugTrace, Environment.NewLine); + string debugTraceMessagesInStdOut = + $""" + + + {Resource.DebugTraceBanner} + {frameworkTestResult.DebugTrace} + """; VSTestTestResultMessage debugTraceMessage = new(VSTestTestResultMessage.StandardOutCategory, debugTraceMessagesInStdOut); testResult.Messages.Add(debugTraceMessage); } if (!StringEx.IsNullOrEmpty(frameworkTestResult.TestContextMessages)) { - string testContextMessagesInStdOut = string.Format(CultureInfo.InvariantCulture, "{2}{2}{0}{2}{1}", Resource.TestContextMessageBanner, frameworkTestResult.TestContextMessages, Environment.NewLine); + string testContextMessagesInStdOut = + $""" + + + {Resource.TestContextMessageBanner} + {frameworkTestResult.TestContextMessages} + """; VSTestTestResultMessage testContextMessage = new(VSTestTestResultMessage.StandardOutCategory, testContextMessagesInStdOut); testResult.Messages.Add(testContextMessage); } diff --git a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/Condition.cs b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/Condition.cs index e5b628d9b4..9c072cdb0f 100644 --- a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/Condition.cs +++ b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/Condition.cs @@ -193,9 +193,9 @@ internal static Condition Parse(string? conditionString) } [DoesNotReturn] - private static void ThrownFormatExceptionForInvalidCondition(string? conditionString) => throw new FormatException( - string.Format(CultureInfo.CurrentCulture, "Incorrect format for TestCaseFilter {0}. Specify the correct format and try again. Note that the incorrect format can lead to no test getting executed..", - string.Format(CultureInfo.CurrentCulture, "Error: Invalid Condition '{0}'", conditionString))); + private static void ThrownFormatExceptionForInvalidCondition(string? conditionString) => + throw new FormatException( + $"Incorrect format for TestCaseFilter Error: Invalid Condition '{conditionString}'. Specify the correct format and try again. Note that the incorrect format can lead to no test getting executed.."); /// /// Check if condition validates any property in properties. @@ -247,8 +247,7 @@ private bool ValidForContainsOperation(Func? propertyProv "~" => Operation.Contains, "!~" => Operation.NotContains, _ => throw new FormatException( - string.Format(CultureInfo.CurrentCulture, "Incorrect format for TestCaseFilter {0}. Specify the correct format and try again. Note that the incorrect format can lead to no test getting executed..", - string.Format(CultureInfo.CurrentCulture, "Error: Invalid operator '{0}'", operationString))), + $"Incorrect format for TestCaseFilter Error: Invalid operator '{operationString}'. Specify the correct format and try again. Note that the incorrect format can lead to no test getting executed.."), }; /// diff --git a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/ContextAdapterBase.cs b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/ContextAdapterBase.cs index 7121115b98..49579940eb 100644 --- a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/ContextAdapterBase.cs +++ b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/ContextAdapterBase.cs @@ -61,14 +61,9 @@ protected ContextAdapterBase(ICommandLineOptions commandLineOptions, IRunSetting string validPropertiesString = supportedProperties == null ? string.Empty : string.Join(", ", supportedProperties); - string errorMessage = string.Format( - CultureInfo.CurrentCulture, - "No tests matched the filter because it contains one or more properties that are not valid ({0}). Specify filter expression containing valid properties ({1}).", - string.Join(", ", invalidProperties), - validPropertiesString); // For unsupported property don’t throw exception, just log the message. Later it is going to handle properly with TestCaseFilterExpression.MatchTestCase(). - EqtTrace.Info(errorMessage); + EqtTrace.Info($"No tests matched the filter because it contains one or more properties that are not valid ({string.Join(", ", invalidProperties)}). Specify filter expression containing valid properties ({validPropertiesString})."); } return adapterSpecificTestCaseFilter; diff --git a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/FastFilter.cs b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/FastFilter.cs index aab3a4cf06..1a8c3ebdb1 100644 --- a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/FastFilter.cs +++ b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/FastFilter.cs @@ -21,7 +21,7 @@ internal FastFilter(ImmutableDictionary> filterProperties, (filterOperation != Operation.Equal || (filterOperator != Operator.Or && filterOperator != Operator.None)) && (filterOperation == Operation.NotEqual && (filterOperator == Operator.And || filterOperator == Operator.None) ? true - : throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "An error occurred while creating Fast filter."))); + : throw new ArgumentException("An error occurred while creating Fast filter.")); } internal ImmutableDictionary> FilterProperties { get; } diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporter.cs b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporter.cs index 9582462fda..017fcbe6e2 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporter.cs +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporter.cs @@ -206,11 +206,11 @@ private void AppendTestRunSummary(ITerminal terminal) } else if (anyTestFailed) { - terminal.Append(string.Format(CultureInfo.CurrentCulture, "{0}!", PlatformResources.Failed)); + terminal.Append($"{PlatformResources.Failed}!"); } else { - terminal.Append(string.Format(CultureInfo.CurrentCulture, "{0}!", PlatformResources.Passed)); + terminal.Append($"{PlatformResources.Passed}!"); } if (!_options.ShowAssembly && _assemblies.Count == 1) diff --git a/test/IntegrationTests/TestAssets/FxExtensibilityTestProject/TestDataSourceExTests.cs b/test/IntegrationTests/TestAssets/FxExtensibilityTestProject/TestDataSourceExTests.cs index 10dc340e8d..3f35f70cfb 100644 --- a/test/IntegrationTests/TestAssets/FxExtensibilityTestProject/TestDataSourceExTests.cs +++ b/test/IntegrationTests/TestAssets/FxExtensibilityTestProject/TestDataSourceExTests.cs @@ -39,7 +39,7 @@ public class CustomTestDataSourceAttribute : Attribute, ITestDataSource public IEnumerable GetData(MethodInfo methodInfo) => [[1, 2, 3], [4, 5, 6]]; public string? GetDisplayName(MethodInfo methodInfo, object?[]? data) - => data != null ? string.Format(CultureInfo.CurrentCulture, "{0} ({1})", methodInfo.Name, string.Join(",", data)) : null; + => data != null ? $"{methodInfo.Name} ({string.Join(",", data)})" : null; } [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] @@ -48,7 +48,7 @@ public class CustomEmptyTestDataSourceAttribute : Attribute, ITestDataSource public IEnumerable GetData(MethodInfo methodInfo) => []; public string? GetDisplayName(MethodInfo methodInfo, object?[]? data) - => data != null ? string.Format(CultureInfo.CurrentCulture, "{0} ({1})", methodInfo.Name, string.Join(",", data)) : null; + => data != null ? $"{methodInfo.Name} ({string.Join(",", data)})" : null; } [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] @@ -59,5 +59,5 @@ public class CustomDisableExpansionTestDataSourceAttribute : Attribute, ITestDat public IEnumerable GetData(MethodInfo methodInfo) => [[1, 2, 3], [4, 5, 6]]; public string? GetDisplayName(MethodInfo methodInfo, object?[]? data) - => data != null ? string.Format(CultureInfo.CurrentCulture, "{0} ({1})", methodInfo.Name, string.Join(",", data)) : null; + => data != null ? $"{methodInfo.Name} ({string.Join(",", data)})" : null; } From 704c98350566255b30a1c8605d3c55079dd8a0fc Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Mon, 30 Jun 2025 23:07:43 +1000 Subject: [PATCH 153/541] remove unused SystemProcessHandler parameter (#5918) --- .../Microsoft.Testing.Platform/Builder/TestApplication.cs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Platform/Builder/TestApplication.cs b/src/Platform/Microsoft.Testing.Platform/Builder/TestApplication.cs index aea7efebe8..fb629da635 100644 --- a/src/Platform/Microsoft.Testing.Platform/Builder/TestApplication.cs +++ b/src/Platform/Microsoft.Testing.Platform/Builder/TestApplication.cs @@ -93,7 +93,7 @@ public static async Task CreateBuilderAsync(string[] ar { ILogger logger = loggingState.FileLoggerProvider.CreateLogger(typeof(TestApplication).ToString()); s_unhandledExceptionHandler.SetLogger(logger); - await LogInformationAsync(logger, testApplicationModuleInfo, testHostControllerInfo, systemProcess, systemEnvironment, createBuilderEntryTime, loggingState.IsSynchronousWrite, loggingState.LogLevel, args).ConfigureAwait(false); + await LogInformationAsync(logger, testApplicationModuleInfo, testHostControllerInfo, systemEnvironment, createBuilderEntryTime, loggingState.IsSynchronousWrite, loggingState.LogLevel, args).ConfigureAwait(false); } // All checks are fine, create the TestApplication. @@ -104,7 +104,6 @@ private static async Task LogInformationAsync( ILogger logger, CurrentTestApplicationModuleInfo testApplicationModuleInfo, TestHostControllerInfo testHostControllerInfo, - SystemProcessHandler processHandler, SystemEnvironment environment, string createBuilderEntryTime, bool syncWrite, From 291a0b9bd6f6e611aec6e1962348798ef0ac1505 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Mon, 30 Jun 2025 15:54:59 +0200 Subject: [PATCH 154/541] [MTP] Fix TrxReport not including test ignore reason (#5896) --- .../TrxReportEngine.cs | 3 +-- .../ObjectModel/ObjectModelConverters.cs | 5 ++++- .../ObjectModel/ObjectModelConvertersTests.cs | 2 +- 3 files changed, 6 insertions(+), 4 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxReportEngine.cs b/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxReportEngine.cs index c2e0a63ace..d3f0b3f66e 100644 --- a/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxReportEngine.cs +++ b/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxReportEngine.cs @@ -518,8 +518,7 @@ private void AddResults(string testAppModule, XElement testRun, out XElement tes output.Add(errorInfoElement); } - // add collectorDataEntries details - if (output.HasElements && outcome != "NotExecuted") + if (output.HasElements) { unitTestResult.Add(output); } diff --git a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/ObjectModelConverters.cs b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/ObjectModelConverters.cs index 02352b25bb..46a63890ef 100644 --- a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/ObjectModelConverters.cs +++ b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/ObjectModelConverters.cs @@ -154,7 +154,10 @@ public static TestNode ToTestNode( if (isTrxEnabled) { - testNode.Properties.Add(new TrxExceptionProperty(testResult.ErrorMessage, testResult.ErrorStackTrace)); + if (!RoslynString.IsNullOrEmpty(testResult.ErrorMessage) || !RoslynString.IsNullOrEmpty(testResult.ErrorStackTrace)) + { + testNode.Properties.Add(new TrxExceptionProperty(testResult.ErrorMessage, testResult.ErrorStackTrace)); + } if (TryParseFullyQualifiedType(testResult.TestCase.FullyQualifiedName, out string? fullyQualifiedType)) { diff --git a/test/UnitTests/Microsoft.Testing.Extensions.VSTestBridge.UnitTests/ObjectModel/ObjectModelConvertersTests.cs b/test/UnitTests/Microsoft.Testing.Extensions.VSTestBridge.UnitTests/ObjectModel/ObjectModelConvertersTests.cs index 999813a0db..2ffea4396a 100644 --- a/test/UnitTests/Microsoft.Testing.Extensions.VSTestBridge.UnitTests/ObjectModel/ObjectModelConvertersTests.cs +++ b/test/UnitTests/Microsoft.Testing.Extensions.VSTestBridge.UnitTests/ObjectModel/ObjectModelConvertersTests.cs @@ -133,7 +133,7 @@ public void ToTestNode_WhenTestResultHasFullyQualifiedTypeAndTrxEnabled_TestNode var testNode = testResult.ToTestNode(isTrxEnabled: true, useFullyQualifiedNameAsUid: false, null, new ConsoleCommandLineOptions(), ClientInfo); - Assert.AreEqual(1, testNode.Properties.OfType()?.Length); + Assert.AreEqual(0, testNode.Properties.OfType()?.Length); Assert.AreEqual("assembly.class", testNode.Properties.Single().FullyQualifiedTypeName); } From af1e8c993eb4c18fefa7906fcbbcbbc8f54cc934 Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Mon, 30 Jun 2025 23:59:32 +1000 Subject: [PATCH 155/541] use char based overloads (#5916) --- Directory.Packages.props | 2 +- .../Discovery/AssemblyEnumerator.cs | 2 +- .../Services/TestSourceHost.cs | 4 ++-- .../DynamicDataTestMethodArgumentsInfo.cs | 4 ++-- .../Hosts/TestHostControllersTestHost.cs | 2 +- .../OutputDevice/TerminalOutputDevice.cs | 11 ++++++----- .../ServerMode/JsonRpc/Json/Json.cs | 2 +- .../ServerMode/JsonRpc/SerializerUtilities.cs | 2 +- .../Services/ExecutableInfo.cs | 2 +- .../TestFramework/Internal/TestDataSourceUtilities.cs | 4 ++-- .../ReflectionUtilityTests.cs | 4 ++-- .../Helpers/SyntaxExtensions.cs | 2 +- .../CommandLine.cs | 2 +- .../TargetFrameworks.cs | 2 +- 14 files changed, 23 insertions(+), 22 deletions(-) diff --git a/Directory.Packages.props b/Directory.Packages.props index a3261aad80..62fbf8a6e9 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -54,7 +54,7 @@ - + diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Discovery/AssemblyEnumerator.cs b/src/Adapter/MSTestAdapter.PlatformServices/Discovery/AssemblyEnumerator.cs index 1f9e26cc47..b941df9a67 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Discovery/AssemblyEnumerator.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Discovery/AssemblyEnumerator.cs @@ -321,7 +321,7 @@ static string GetMethodName(MethodInfo methodInfo) { ParameterInfo[] args = methodInfo.GetParameters(); return args.Length > 0 - ? $"{methodInfo.Name}({string.Join(",", args.Select(a => a.ParameterType.FullName))})" + ? $"{methodInfo.Name}({string.Join(',', args.Select(a => a.ParameterType.FullName))})" : methodInfo.Name; } diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Services/TestSourceHost.cs b/src/Adapter/MSTestAdapter.PlatformServices/Services/TestSourceHost.cs index ec7f34c21d..377dc36889 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Services/TestSourceHost.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Services/TestSourceHost.cs @@ -120,7 +120,7 @@ public void SetupHost() if (EqtTrace.IsInfoEnabled) { - EqtTrace.Info("DesktopTestSourceHost.SetupHost(): Creating assembly resolver with resolution paths {0}.", string.Join(",", resolutionPaths)); + EqtTrace.Info("DesktopTestSourceHost.SetupHost(): Creating assembly resolver with resolution paths {0}.", string.Join(',', resolutionPaths)); } var assemblyResolver = new AssemblyResolver(resolutionPaths); @@ -137,7 +137,7 @@ public void SetupHost() if (EqtTrace.IsInfoEnabled) { - EqtTrace.Info("DesktopTestSourceHost.SetupHost(): Creating assembly resolver with resolution paths {0}.", string.Join(",", resolutionPaths)); + EqtTrace.Info("DesktopTestSourceHost.SetupHost(): Creating assembly resolver with resolution paths {0}.", string.Join(',', resolutionPaths)); } // NOTE: These 2 lines are super important, see https://github.com/microsoft/testfx/issues/2922 diff --git a/src/Analyzers/MSTest.SourceGeneration/ObjectModels/DynamicDataTestMethodArgumentsInfo.cs b/src/Analyzers/MSTest.SourceGeneration/ObjectModels/DynamicDataTestMethodArgumentsInfo.cs index e40db92762..1f520350ae 100644 --- a/src/Analyzers/MSTest.SourceGeneration/ObjectModels/DynamicDataTestMethodArgumentsInfo.cs +++ b/src/Analyzers/MSTest.SourceGeneration/ObjectModels/DynamicDataTestMethodArgumentsInfo.cs @@ -205,7 +205,7 @@ public void AppendArguments(IndentedStringBuilder nodeBuilder) nodeBuilder.Append("()"); } - nodeBuilder.AppendLine(";"); + nodeBuilder.AppendLine(';'); if (!_targetMethodReturnsCollectionOfTestArgumentsEntry) { @@ -225,6 +225,6 @@ public void AppendArguments(IndentedStringBuilder nodeBuilder) } } - nodeBuilder.AppendLine(","); + nodeBuilder.AppendLine(','); } } diff --git a/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostControllersTestHost.cs b/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostControllersTestHost.cs index 42965ff6b4..c27cd00e26 100644 --- a/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostControllersTestHost.cs +++ b/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostControllersTestHost.cs @@ -104,7 +104,7 @@ protected override async Task InternalRunAsync() #if NET8_0_OR_GREATER IEnumerable arguments = partialCommandLine; #else - string arguments = string.Join(" ", partialCommandLine); + string arguments = string.Join(' ', partialCommandLine); #endif #pragma warning disable CA1416 // Validate platform compatibility diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/TerminalOutputDevice.cs b/src/Platform/Microsoft.Testing.Platform/OutputDevice/TerminalOutputDevice.cs index 9a244d087b..68f2a24227 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/TerminalOutputDevice.cs +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/TerminalOutputDevice.cs @@ -31,6 +31,8 @@ internal sealed partial class TerminalOutputDevice : IHotReloadPlatformOutputDev private const string TESTINGPLATFORM_CONSOLEOUTPUTDEVICE_SKIP_BANNER = nameof(TESTINGPLATFORM_CONSOLEOUTPUTDEVICE_SKIP_BANNER); #pragma warning restore SA1310 // Field names should not contain underscore + private const char Dash = '-'; + private readonly IConsole _console; private readonly ITestHostControllerInfo _testHostControllerInfo; private readonly IAsyncMonitor _asyncMonitor; @@ -51,7 +53,6 @@ internal sealed partial class TerminalOutputDevice : IHotReloadPlatformOutputDev // The targeted framework, .NET 8 when application specifies net8.0 private readonly string? _targetFramework; private readonly string _assemblyName; - private readonly char[] _dash = ['-']; private TerminalTestReporter? _terminalTestReporter; private bool _firstCallTo_OnSessionStartingAsync = true; @@ -87,7 +88,7 @@ public TerminalOutputDevice( #else // RID has the operating system, we want to see that in the banner, but not next to every dll. _longArchitecture = RuntimeInformation.RuntimeIdentifier; - _shortArchitecture = GetShortArchitecture(RuntimeInformation.RuntimeIdentifier); + _shortArchitecture = TerminalOutputDevice.GetShortArchitecture(RuntimeInformation.RuntimeIdentifier); #endif _runtimeFramework = TargetFrameworkParser.GetShortTargetFramework(RuntimeInformation.FrameworkDescription); _targetFramework = TargetFrameworkParser.GetShortTargetFramework(Assembly.GetEntryAssembly()?.GetCustomAttribute()?.FrameworkDisplayName) ?? _runtimeFramework; @@ -164,9 +165,9 @@ await _policiesService.RegisterOnAbortCallbackAsync( }); } - private string GetShortArchitecture(string runtimeIdentifier) - => runtimeIdentifier.Contains('-') - ? runtimeIdentifier.Split(_dash, 2)[1] + private static string GetShortArchitecture(string runtimeIdentifier) + => runtimeIdentifier.Contains(Dash) + ? runtimeIdentifier.Split(Dash, 2)[1] : runtimeIdentifier; public Type[] DataTypesConsumed { get; } = diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/Json/Json.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/Json/Json.cs index 10d0771284..0b8952079c 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/Json/Json.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/Json/Json.cs @@ -154,7 +154,7 @@ public Json(Dictionary? serializers = null, Dictionary 0 - ? $"{testMethodIdentifierProperty.MethodName}({string.Join(",", testMethodIdentifierProperty.ParameterTypeFullNames)})" + ? $"{testMethodIdentifierProperty.MethodName}({string.Join(',', testMethodIdentifierProperty.ParameterTypeFullNames)})" : testMethodIdentifierProperty.MethodName)); properties.Add(("location.method-arity", testMethodIdentifierProperty.MethodArity)); diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/SerializerUtilities.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/SerializerUtilities.cs index 97b5733507..a8a9f11a6b 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/SerializerUtilities.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/SerializerUtilities.cs @@ -224,7 +224,7 @@ static SerializerUtilities() : $"{testMethodIdentifierProperty.Namespace}.{testMethodIdentifierProperty.TypeName}"; properties["location.method"] = testMethodIdentifierProperty.ParameterTypeFullNames.Length > 0 - ? $"{testMethodIdentifierProperty.MethodName}({string.Join(",", testMethodIdentifierProperty.ParameterTypeFullNames)})" + ? $"{testMethodIdentifierProperty.MethodName}({string.Join(',', testMethodIdentifierProperty.ParameterTypeFullNames)})" : testMethodIdentifierProperty.MethodName; properties["location.method-arity"] = testMethodIdentifierProperty.MethodArity; diff --git a/src/Platform/Microsoft.Testing.Platform/Services/ExecutableInfo.cs b/src/Platform/Microsoft.Testing.Platform/Services/ExecutableInfo.cs index 80b35d1441..17b6023e2b 100644 --- a/src/Platform/Microsoft.Testing.Platform/Services/ExecutableInfo.cs +++ b/src/Platform/Microsoft.Testing.Platform/Services/ExecutableInfo.cs @@ -12,5 +12,5 @@ internal sealed class ExecutableInfo(string filePath, IEnumerable argume public string Workspace { get; } = workspace; public override string ToString() - => $"Process: {FilePath}, Arguments: {string.Join(" ", Arguments)}, Workspace: {Workspace}"; + => $"Process: {FilePath}, Arguments: {string.Join(' ', Arguments)}, Workspace: {Workspace}"; } diff --git a/src/TestFramework/TestFramework/Internal/TestDataSourceUtilities.cs b/src/TestFramework/TestFramework/Internal/TestDataSourceUtilities.cs index 525f25fda2..d594f38ad4 100644 --- a/src/TestFramework/TestFramework/Internal/TestDataSourceUtilities.cs +++ b/src/TestFramework/TestFramework/Internal/TestDataSourceUtilities.cs @@ -29,7 +29,7 @@ internal static class TestDataSourceUtilities CultureInfo.CurrentCulture, FrameworkMessages.DataDrivenResultDisplayName, methodDisplayName, - string.Join(",", displayData.Select(x => GetHumanizedArguments(x, testIdGenerationStrategy)))); + string.Join(',', displayData.Select(x => GetHumanizedArguments(x, testIdGenerationStrategy)))); } /// @@ -65,6 +65,6 @@ internal static class TestDataSourceUtilities // We need to box the object here so that we can support value types IEnumerable boxedObjectEnumerable = ((IEnumerable)data).Cast(); IEnumerable elementStrings = boxedObjectEnumerable.Select(x => GetHumanizedArguments(x, testIdGenerationStrategy)); - return $"[{string.Join(",", elementStrings)}]"; + return $"[{string.Join(',', elementStrings)}]"; } } diff --git a/test/IntegrationTests/PlatformServices.Desktop.IntegrationTests/ReflectionUtilityTests.cs b/test/IntegrationTests/PlatformServices.Desktop.IntegrationTests/ReflectionUtilityTests.cs index bb1425fb6d..bad20b6f9d 100644 --- a/test/IntegrationTests/PlatformServices.Desktop.IntegrationTests/ReflectionUtilityTests.cs +++ b/test/IntegrationTests/PlatformServices.Desktop.IntegrationTests/ReflectionUtilityTests.cs @@ -263,7 +263,7 @@ private static string[] GetAttributeValuePairs(IEnumerable attributes) } else if (attribute is TestCategoryAttribute categoryAttribute) { - attributeValuePairs.Add("TestCategory : " + categoryAttribute.TestCategories.Aggregate((i, j) => i + "," + j)); + attributeValuePairs.Add("TestCategory : " + categoryAttribute.TestCategories.Aggregate((i, j) => i + ',' + j)); } else if (attribute is DurationAttribute durationAttribute) { @@ -271,7 +271,7 @@ private static string[] GetAttributeValuePairs(IEnumerable attributes) } else if (attribute is CategoryArrayAttribute arrayAttribute) { - attributeValuePairs.Add("CategoryAttribute : " + arrayAttribute.Value.Aggregate((i, j) => i + "," + j)); + attributeValuePairs.Add("CategoryAttribute : " + arrayAttribute.Value.Aggregate((i, j) => i + ',' + j)); } } diff --git a/test/UnitTests/MSTest.SourceGeneration.UnitTests/Helpers/SyntaxExtensions.cs b/test/UnitTests/MSTest.SourceGeneration.UnitTests/Helpers/SyntaxExtensions.cs index 5b7a153773..17133da1c3 100644 --- a/test/UnitTests/MSTest.SourceGeneration.UnitTests/Helpers/SyntaxExtensions.cs +++ b/test/UnitTests/MSTest.SourceGeneration.UnitTests/Helpers/SyntaxExtensions.cs @@ -32,7 +32,7 @@ public static string ShowWhitespace(this string text) { " ", "·" }, }; - var regex = new Regex(string.Join("|", map.Keys)); + var regex = new Regex(string.Join('|', map.Keys)); return regex.Replace(text, m => map[m.Value]); } diff --git a/test/Utilities/Microsoft.Testing.TestInfrastructure/CommandLine.cs b/test/Utilities/Microsoft.Testing.TestInfrastructure/CommandLine.cs index 883e1f367d..8594a61021 100644 --- a/test/Utilities/Microsoft.Testing.TestInfrastructure/CommandLine.cs +++ b/test/Utilities/Microsoft.Testing.TestInfrastructure/CommandLine.cs @@ -60,7 +60,7 @@ private static (string Command, string Arguments) GetCommandAndArguments(string if (!commandLine.StartsWith('"')) { string[] tokens = commandLine.Split(' '); - return (tokens[0], string.Join(" ", tokens.Skip(1))); + return (tokens[0], string.Join(' ', tokens.Skip(1))); } int endQuote = commandLine.IndexOf('"', 1); diff --git a/test/Utilities/Microsoft.Testing.TestInfrastructure/TargetFrameworks.cs b/test/Utilities/Microsoft.Testing.TestInfrastructure/TargetFrameworks.cs index 6a8e91de1f..824e2f1676 100644 --- a/test/Utilities/Microsoft.Testing.TestInfrastructure/TargetFrameworks.cs +++ b/test/Utilities/Microsoft.Testing.TestInfrastructure/TargetFrameworks.cs @@ -31,5 +31,5 @@ public static class TargetFrameworks All.Select(tfm => new object[] { tfm }); public static string ToMSBuildTargetFrameworks(this string[] targetFrameworksEntries) - => string.Join(";", targetFrameworksEntries); + => string.Join(';', targetFrameworksEntries); } From 71ef7cc0236225f59324c1b1826614dc7d7bbcb0 Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Tue, 1 Jul 2025 02:35:25 +1000 Subject: [PATCH 156/541] missing using in AttachDebuggerIfNeeded (#5919) --- .../Microsoft.Testing.Platform/Builder/TestApplication.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Platform/Microsoft.Testing.Platform/Builder/TestApplication.cs b/src/Platform/Microsoft.Testing.Platform/Builder/TestApplication.cs index fb629da635..c65700153f 100644 --- a/src/Platform/Microsoft.Testing.Platform/Builder/TestApplication.cs +++ b/src/Platform/Microsoft.Testing.Platform/Builder/TestApplication.cs @@ -234,7 +234,7 @@ private static void AttachDebuggerIfNeeded(SystemEnvironment environment, System if (environment.GetEnvironmentVariable(EnvironmentVariableConstants.TESTINGPLATFORM_WAIT_ATTACH_DEBUGGER) == "1") { - IProcess currentProcess = systemProcess.GetCurrentProcess(); + using IProcess currentProcess = systemProcess.GetCurrentProcess(); console.WriteLine($"Waiting for debugger to attach... Process Id: {environment.ProcessId}, Name: {currentProcess.Name}"); while (!Debugger.IsAttached) From ab511b69b6e84512849de727d6a0014b5636d073 Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Wed, 2 Jul 2025 05:17:49 +0000 Subject: [PATCH 157/541] [main] Update dependencies from dotnet/arcade (#5926) Co-authored-by: dotnet-maestro[bot] --- eng/Version.Details.xml | 12 ++++++------ eng/Versions.props | 2 +- global.json | 2 +- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index ec67afa156..c63223258c 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -1,17 +1,17 @@ - + https://github.com/dotnet/arcade - 0e335649fe2d2f98ea51e55cc1a0899af3617eba + e554a518e2d93daee29a8aad27fd471a8804d8e1 - + https://github.com/dotnet/arcade - 0e335649fe2d2f98ea51e55cc1a0899af3617eba + e554a518e2d93daee29a8aad27fd471a8804d8e1 - + https://github.com/dotnet/arcade - 0e335649fe2d2f98ea51e55cc1a0899af3617eba + e554a518e2d93daee29a8aad27fd471a8804d8e1 https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage diff --git a/eng/Versions.props b/eng/Versions.props index 2e5fe3d1a3..344a536129 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -7,7 +7,7 @@ preview - 10.0.0-beta.25326.3 + 10.0.0-beta.25351.1 17.15.0-preview.25327.4 diff --git a/global.json b/global.json index 8c03d17456..ec648eb34f 100644 --- a/global.json +++ b/global.json @@ -33,7 +33,7 @@ "rollForward": "latestFeature" }, "msbuild-sdks": { - "Microsoft.DotNet.Arcade.Sdk": "10.0.0-beta.25326.3", + "Microsoft.DotNet.Arcade.Sdk": "10.0.0-beta.25351.1", "MSBuild.Sdk.Extras": "3.0.44" } } From a99b2ce586ad7dd45ebae5b5dbed492ef55959e1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Jare=C5=A1?= Date: Wed, 2 Jul 2025 07:45:33 +0200 Subject: [PATCH 158/541] Show whole error with stack trace (#5925) --- azure-pipelines.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/azure-pipelines.yml b/azure-pipelines.yml index d90ec2997b..235191a093 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -121,6 +121,7 @@ stages: env: DOTNET_ROOT: $(Build.SourcesDirectory)/.dotnet NUGET_PACKAGES: $(Build.SourcesDirectory)/.packages + DOTNET_CLI_CONTEXT_VERBOSE: 1 # This step is only helpful for diagnosing some issues with vstest/test host that would not appear # through the console or trx @@ -200,6 +201,7 @@ stages: env: DOTNET_ROOT: $(Build.SourcesDirectory)/.dotnet NUGET_PACKAGES: $(Build.SourcesDirectory)/.packages + DOTNET_CLI_CONTEXT_VERBOSE: 1 # This step is only helpful for diagnosing some issues with vstest/test host that would not appear # through the console or trx @@ -265,6 +267,7 @@ stages: env: DOTNET_ROOT: $(Build.SourcesDirectory)/.dotnet NUGET_PACKAGES: $(Build.SourcesDirectory)/.packages + DOTNET_CLI_CONTEXT_VERBOSE: 1 # This step is only helpful for diagnosing some issues with vstest/test host that would not appear # through the console or trx From 492cf5e341fc9f9dea64225a1ba7a79718ef33a7 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Wed, 2 Jul 2025 11:07:11 +0200 Subject: [PATCH 159/541] Fix STA regression when async method completes asynchronously between sync methods (#5922) --- .../Execution/TestExecutionManager.cs | 7 ++++++- .../ThreadingTests.cs | 11 ++++++++++- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestExecutionManager.cs b/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestExecutionManager.cs index 6185a94829..5f88bfbea8 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestExecutionManager.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestExecutionManager.cs @@ -553,10 +553,15 @@ private async Task ExecuteTestsWithTestRunnerAsync( Dictionary testContextProperties = GetTestContextProperties(tcmProperties, sourceLevelParameters); TestTools.UnitTesting.TestResult[] unitTestResult; - if (usesAppDomains) + if (usesAppDomains || Thread.CurrentThread.GetApartmentState() == ApartmentState.STA) { #pragma warning disable VSTHRD103 // Call async methods when in an async method - We cannot do right now because we are crossing app domains. // TODO: When app domains support is dropped, we can finally always be calling the async version. + // In addition to app domains, if we are STA thread (e.g, because runsettings setting ExecutionApartmentState to STA), we want to preserve that. + // If we await, we could end up in a thread pool thread, which is not what we want. + // Alternatively, if we want to use RunSingleTestAsync for the case of STA, we should have: + // 1. A custom single threaded synchronization context that keeps us in STA. + // 2. Use ConfigureAwait(true). unitTestResult = testRunner.RunSingleTest(unitTestElement.TestMethod, testContextProperties, remotingMessageLogger); #pragma warning restore VSTHRD103 // Call async methods when in an async method } diff --git a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/ThreadingTests.cs b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/ThreadingTests.cs index f3e2d9d531..5ab221a469 100644 --- a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/ThreadingTests.cs +++ b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/ThreadingTests.cs @@ -342,12 +342,21 @@ public void TestMethod1() public async Task TestMethod2() { AssertCorrectThreadApartmentState(); - await Task.CompletedTask; + // Ensure that we continue on a thread pool thread after this await. + await Task.Yield(); + Assert.IsTrue(Thread.CurrentThread.IsThreadPoolThread); } [TestMethod] public Task TestMethod3() { + if (Environment.GetEnvironmentVariable("MSTEST_THREAD_STATE_IS_STA") == "1") + { + // TestMethod2 finished on a thread pool thread. + // However, here in this method we should still start on STA thread. + Assert.IsFalse(Thread.CurrentThread.IsThreadPoolThread); + } + AssertCorrectThreadApartmentState(); return Task.CompletedTask; } From 52947bb75620ac5f6be58303aac0b84fd3c715df Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Wed, 2 Jul 2025 11:14:26 +0200 Subject: [PATCH 160/541] Handle framework's Logger to write to test context (#5927) --- .../MSTestAdapter.PlatformServices/Execution/UnitTestRunner.cs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Execution/UnitTestRunner.cs b/src/Adapter/MSTestAdapter.PlatformServices/Execution/UnitTestRunner.cs index 9adcb833e9..0afe682950 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Execution/UnitTestRunner.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Execution/UnitTestRunner.cs @@ -12,6 +12,7 @@ using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Interface; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging; using Microsoft.VisualStudio.TestTools.UnitTesting; +using Microsoft.VisualStudio.TestTools.UnitTesting.Logging; using UnitTestOutcome = Microsoft.VisualStudio.TestTools.UnitTesting.UnitTestOutcome; using UTF = Microsoft.VisualStudio.TestTools.UnitTesting; @@ -52,6 +53,7 @@ internal UnitTestRunner(MSTestSettings settings, UnitTestElement[] testsToRun, i // This would just be resetting the settings to itself in non desktop workflows. MSTestSettings.PopulateSettings(settings); + Logger.OnLogMessage += message => TestContextImplementation.CurrentTestContext?.WriteConsoleOut(message); if (MSTestSettings.CurrentSettings.CaptureDebugTraces) { Console.SetOut(new ConsoleOutRouter(Console.Out)); From c0de310facb7bc8a091ed083fcef201ba9eded2d Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Wed, 2 Jul 2025 16:45:05 +0200 Subject: [PATCH 161/541] Call GetDisplayName with the right arguments when tuples are used (#5929) --- .../Discovery/AssemblyEnumerator.cs | 23 ++++++++++++++++++- .../Execution/TestMethodRunner.cs | 20 ++++++++-------- .../TestDiscoveryTests.cs | 21 +++++++++++++++++ 3 files changed, 52 insertions(+), 12 deletions(-) diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Discovery/AssemblyEnumerator.cs b/src/Adapter/MSTestAdapter.PlatformServices/Discovery/AssemblyEnumerator.cs index b941df9a67..65ae31ca6d 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Discovery/AssemblyEnumerator.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Discovery/AssemblyEnumerator.cs @@ -439,10 +439,31 @@ private static bool TryUnfoldITestDataSource(ITestDataSource dataSource, TestDat foreach (object?[] dataOrTestDataRow in data) { object?[] d = dataOrTestDataRow; - if (TestDataSourceHelpers.TryHandleITestDataRow(d, methodInfo.GetParameters(), out d, out string? ignoreMessageFromTestDataRow, out string? displayNameFromTestDataRow)) + ParameterInfo[] parameters = methodInfo.GetParameters(); + if (TestDataSourceHelpers.TryHandleITestDataRow(d, parameters, out d, out string? ignoreMessageFromTestDataRow, out string? displayNameFromTestDataRow)) { testDataSourceIgnoreMessage = ignoreMessageFromTestDataRow ?? testDataSourceIgnoreMessage; } + else if (TestDataSourceHelpers.IsDataConsideredSingleArgumentValue(d, parameters)) + { + // SPECIAL CASE: + // This condition is a duplicate of the condition in InvokeAsSynchronousTask. + // + // The known scenario we know of that shows importance of that check is if we have DynamicData using this member + // + // public static IEnumerable GetData() + // { + // yield return new object[] { ("Hello", "World") }; + // } + // + // If the test method has a single parameter which is 'object[]', then we should pass the tuple array as is. + // Note that normally, the array in this code path represents the arguments of the test method. + // However, InvokeAsSynchronousTask uses the above check to mean "the whole array is the single argument to the test method" + } + else if (d?.Length == 1 && TestDataSourceHelpers.TryHandleTupleDataSource(d[0], parameters, out object?[] tupleExpandedToArray)) + { + d = tupleExpandedToArray; + } UnitTestElement discoveredTest = test.Clone(); discoveredTest.DisplayName = displayNameFromTestDataRow ?? dataSource.GetDisplayName(methodInfo, d) ?? discoveredTest.DisplayName; diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestMethodRunner.cs b/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestMethodRunner.cs index 9714daeafe..443e2443c7 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestMethodRunner.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestMethodRunner.cs @@ -180,7 +180,7 @@ internal async Task RunTestMethodAsync() } object?[]? data = _test.ActualData ?? DataSerializationHelper.Deserialize(_test.SerializedData); - TestResult[] testResults = await ExecuteTestWithDataSourceAsync(null, data).ConfigureAwait(false); + TestResult[] testResults = await ExecuteTestWithDataSourceAsync(null, data, actualDataAlreadyHandledDuringDiscovery: true).ConfigureAwait(false); results.AddRange(testResults); } else if (await TryExecuteDataSourceBasedTestsAsync(results).ConfigureAwait(false)) @@ -303,7 +303,7 @@ private async Task TryExecuteFoldedDataDrivenTestsAsync(List r { try { - TestResult[] testResults = await ExecuteTestWithDataSourceAsync(testDataSource, data).ConfigureAwait(false); + TestResult[] testResults = await ExecuteTestWithDataSourceAsync(testDataSource, data, actualDataAlreadyHandledDuringDiscovery: false).ConfigureAwait(false); results.AddRange(testResults); } @@ -364,7 +364,7 @@ private async Task ExecuteTestFromDataSourceAttributeAsync(List resu } } - private async Task ExecuteTestWithDataSourceAsync(UTF.ITestDataSource? testDataSource, object?[]? data) + private async Task ExecuteTestWithDataSourceAsync(UTF.ITestDataSource? testDataSource, object?[]? data, bool actualDataAlreadyHandledDuringDiscovery) { string? displayName = StringEx.IsNullOrWhiteSpace(_test.DisplayName) ? _test.Name @@ -372,12 +372,12 @@ private async Task ExecuteTestWithDataSourceAsync(UTF.ITestDataSou string? displayNameFromTestDataRow = null; string? ignoreFromTestDataRow = null; - if (data is not null && + if (!actualDataAlreadyHandledDuringDiscovery && data is not null && TestDataSourceHelpers.TryHandleITestDataRow(data, _testMethodInfo.ParameterTypes, out data, out ignoreFromTestDataRow, out displayNameFromTestDataRow)) { // Handled already. } - else if (TestDataSourceHelpers.IsDataConsideredSingleArgumentValue(data, _testMethodInfo.ParameterTypes)) + else if (!actualDataAlreadyHandledDuringDiscovery && TestDataSourceHelpers.IsDataConsideredSingleArgumentValue(data, _testMethodInfo.ParameterTypes)) { // SPECIAL CASE: // This condition is a duplicate of the condition in InvokeAsSynchronousTask. @@ -393,16 +393,14 @@ private async Task ExecuteTestWithDataSourceAsync(UTF.ITestDataSou // Note that normally, the array in this code path represents the arguments of the test method. // However, InvokeAsSynchronousTask uses the above check to mean "the whole array is the single argument to the test method" } - else if (data?.Length == 1 && TestDataSourceHelpers.TryHandleTupleDataSource(data[0], _testMethodInfo.ParameterTypes, out object?[] tupleExpandedToArray)) + else if (!actualDataAlreadyHandledDuringDiscovery && data?.Length == 1 && TestDataSourceHelpers.TryHandleTupleDataSource(data[0], _testMethodInfo.ParameterTypes, out object?[] tupleExpandedToArray)) { data = tupleExpandedToArray; } - displayName = testDataSource != null - ? displayNameFromTestDataRow - ?? testDataSource.GetDisplayName(new ReflectionTestMethodInfo(_testMethodInfo.MethodInfo, _test.DisplayName), data) - ?? displayName - : displayNameFromTestDataRow ?? displayName; + displayName = displayNameFromTestDataRow + ?? testDataSource?.GetDisplayName(new ReflectionTestMethodInfo(_testMethodInfo.MethodInfo, _test.DisplayName), data) + ?? displayName; var stopwatch = Stopwatch.StartNew(); _testMethodInfo.SetArguments(data); diff --git a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/TestDiscoveryTests.cs b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/TestDiscoveryTests.cs index bec1c9dd3a..9aa8097128 100644 --- a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/TestDiscoveryTests.cs +++ b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/TestDiscoveryTests.cs @@ -23,6 +23,8 @@ public async Task DiscoverTests_FindsAllTests(string currentTfm) testHostResult.AssertExitCodeIs(ExitCodes.Success); testHostResult.AssertOutputContains("Test1"); testHostResult.AssertOutputContains("Test2"); + testHostResult.AssertOutputContains("Display name: 1, one"); + testHostResult.AssertOutputContains("Display name: 2, two"); } [TestMethod] @@ -70,6 +72,8 @@ public sealed class TestAssetFixture() : TestAssetFixtureBase(AcceptanceFixture. #file UnitTest1.cs using System; +using System.Collections.Generic; +using System.Reflection; using System.Threading.Tasks; using Microsoft.VisualStudio.TestTools.UnitTesting; @@ -81,6 +85,23 @@ public void Test1() {} [TestMethod] public void Test2() {} + + [DynamicData(nameof(GetData), DynamicDataDisplayName = nameof(GetDisplayName))] + [TestMethod] + public void TestWithData(int _1, string _2) + { + } + + public static IEnumerable<(int, string)> GetData() + { + yield return (1, "one"); + yield return (2, "two"); + } + + public static string GetDisplayName(MethodInfo methodInfo, object[] data) + { + return $"Display name: {data[0]}, {data[1]}"; + } } """; } From 97137bdc544f35c9de5a09010741dac23160c261 Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Thu, 3 Jul 2025 05:58:56 +0000 Subject: [PATCH 162/541] [main] Update dependencies from devdiv/DevDiv/vs-code-coverage, dotnet/arcade (#5930) [main] Update dependencies from devdiv/DevDiv/vs-code-coverage, dotnet/arcade --- eng/Version.Details.xml | 16 ++++++++-------- eng/Versions.props | 4 ++-- global.json | 2 +- 3 files changed, 11 insertions(+), 11 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index c63223258c..ccb96aaf5c 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -1,21 +1,21 @@ - + https://github.com/dotnet/arcade - e554a518e2d93daee29a8aad27fd471a8804d8e1 + d1834121068b0df7974a380cebadb781e58ff098 - + https://github.com/dotnet/arcade - e554a518e2d93daee29a8aad27fd471a8804d8e1 + d1834121068b0df7974a380cebadb781e58ff098 - + https://github.com/dotnet/arcade - e554a518e2d93daee29a8aad27fd471a8804d8e1 + d1834121068b0df7974a380cebadb781e58ff098 - + https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage - 90b433bee335be4224f0e2b5106027181b4af52b + 910a5566a1c5a9d179c58b3497e763aa888a1b1c diff --git a/eng/Versions.props b/eng/Versions.props index 344a536129..f1134fa78f 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -7,7 +7,7 @@ preview - 10.0.0-beta.25351.1 - 17.15.0-preview.25327.4 + 10.0.0-beta.25352.1 + 17.15.0-preview.25352.2 diff --git a/global.json b/global.json index ec648eb34f..615e42a0fa 100644 --- a/global.json +++ b/global.json @@ -33,7 +33,7 @@ "rollForward": "latestFeature" }, "msbuild-sdks": { - "Microsoft.DotNet.Arcade.Sdk": "10.0.0-beta.25351.1", + "Microsoft.DotNet.Arcade.Sdk": "10.0.0-beta.25352.1", "MSBuild.Sdk.Extras": "3.0.44" } } From ef30251cf754c1c5fd0d44c46e891540fc17cbd3 Mon Sep 17 00:00:00 2001 From: Copilot <198982749+Copilot@users.noreply.github.com> Date: Thu, 3 Jul 2025 12:13:15 +0200 Subject: [PATCH 163/541] Add analyzer and code fix to migrate from StringAssert to Assert APIs (#5792) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: Evangelink <11340282+Evangelink@users.noreply.github.com> Co-authored-by: Youssef1313 <31348972+Youssef1313@users.noreply.github.com> Co-authored-by: Amaury Levé --- .../CodeFixResources.Designer.cs | 9 + .../CodeFixResources.resx | 3 + .../PublicAPI.Unshipped.txt | 5 + .../StringAssertToAssertFixer.cs | 99 ++++++ .../xlf/CodeFixResources.cs.xlf | 5 + .../xlf/CodeFixResources.de.xlf | 5 + .../xlf/CodeFixResources.es.xlf | 5 + .../xlf/CodeFixResources.fr.xlf | 5 + .../xlf/CodeFixResources.it.xlf | 5 + .../xlf/CodeFixResources.ja.xlf | 5 + .../xlf/CodeFixResources.ko.xlf | 5 + .../xlf/CodeFixResources.pl.xlf | 5 + .../xlf/CodeFixResources.pt-BR.xlf | 5 + .../xlf/CodeFixResources.ru.xlf | 5 + .../xlf/CodeFixResources.tr.xlf | 5 + .../xlf/CodeFixResources.zh-Hans.xlf | 5 + .../xlf/CodeFixResources.zh-Hant.xlf | 5 + .../AnalyzerReleases.Unshipped.md | 2 +- .../MSTest.Analyzers/Helpers/DiagnosticIds.cs | 1 + .../MSTest.Analyzers/Resources.Designer.cs | 18 + src/Analyzers/MSTest.Analyzers/Resources.resx | 6 + .../StringAssertToAssertAnalyzer.cs | 128 +++++++ .../MSTest.Analyzers/xlf/Resources.cs.xlf | 10 + .../MSTest.Analyzers/xlf/Resources.de.xlf | 10 + .../MSTest.Analyzers/xlf/Resources.es.xlf | 10 + .../MSTest.Analyzers/xlf/Resources.fr.xlf | 10 + .../MSTest.Analyzers/xlf/Resources.it.xlf | 10 + .../MSTest.Analyzers/xlf/Resources.ja.xlf | 10 + .../MSTest.Analyzers/xlf/Resources.ko.xlf | 10 + .../MSTest.Analyzers/xlf/Resources.pl.xlf | 10 + .../MSTest.Analyzers/xlf/Resources.pt-BR.xlf | 10 + .../MSTest.Analyzers/xlf/Resources.ru.xlf | 10 + .../MSTest.Analyzers/xlf/Resources.tr.xlf | 10 + .../xlf/Resources.zh-Hans.xlf | 10 + .../xlf/Resources.zh-Hant.xlf | 10 + .../MSBuildTests.Test.cs | 12 +- .../StringAssertToAssertAnalyzerTests.cs | 311 ++++++++++++++++++ 37 files changed, 782 insertions(+), 7 deletions(-) create mode 100644 src/Analyzers/MSTest.Analyzers.CodeFixes/StringAssertToAssertFixer.cs create mode 100644 src/Analyzers/MSTest.Analyzers/StringAssertToAssertAnalyzer.cs create mode 100644 test/UnitTests/MSTest.Analyzers.UnitTests/StringAssertToAssertAnalyzerTests.cs diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/CodeFixResources.Designer.cs b/src/Analyzers/MSTest.Analyzers.CodeFixes/CodeFixResources.Designer.cs index 89110576fc..127d898b5d 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/CodeFixResources.Designer.cs +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/CodeFixResources.Designer.cs @@ -257,5 +257,14 @@ internal static string UseCooperativeCancellationForTimeoutFix { return ResourceManager.GetString("UseCooperativeCancellationForTimeoutFix", resourceCulture); } } + + /// + /// Looks up a localized string similar to Use 'Assert.{0}' instead of 'StringAssert'. + /// + internal static string StringAssertToAssertTitle { + get { + return ResourceManager.GetString("StringAssertToAssertTitle", resourceCulture); + } + } } } diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/CodeFixResources.resx b/src/Analyzers/MSTest.Analyzers.CodeFixes/CodeFixResources.resx index 008d1922fb..6f73aa7fd7 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/CodeFixResources.resx +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/CodeFixResources.resx @@ -183,4 +183,7 @@ Use 'CooperativeCancellation = true' + + Use 'Assert.{0}' instead of 'StringAssert' + diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/PublicAPI.Unshipped.txt b/src/Analyzers/MSTest.Analyzers.CodeFixes/PublicAPI.Unshipped.txt index eff3fb1deb..79fa2eb4ff 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/PublicAPI.Unshipped.txt +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/PublicAPI.Unshipped.txt @@ -1,6 +1,10 @@ #nullable enable +MSTest.Analyzers.CodeFixes.StringAssertToAssertFixer +MSTest.Analyzers.CodeFixes.StringAssertToAssertFixer.StringAssertToAssertFixer() -> void MSTest.Analyzers.PreferTestMethodOverDataTestMethodFixer MSTest.Analyzers.PreferTestMethodOverDataTestMethodFixer.PreferTestMethodOverDataTestMethodFixer() -> void +override MSTest.Analyzers.CodeFixes.StringAssertToAssertFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray +override MSTest.Analyzers.CodeFixes.StringAssertToAssertFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! override MSTest.Analyzers.PreferTestMethodOverDataTestMethodFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray override MSTest.Analyzers.PreferTestMethodOverDataTestMethodFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! override MSTest.Analyzers.PreferTestMethodOverDataTestMethodFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! @@ -9,3 +13,4 @@ MSTest.Analyzers.UseCooperativeCancellationForTimeoutFixer.UseCooperativeCancell override MSTest.Analyzers.UseCooperativeCancellationForTimeoutFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! override sealed MSTest.Analyzers.UseCooperativeCancellationForTimeoutFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray override sealed MSTest.Analyzers.UseCooperativeCancellationForTimeoutFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! +override sealed MSTest.Analyzers.CodeFixes.StringAssertToAssertFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/StringAssertToAssertFixer.cs b/src/Analyzers/MSTest.Analyzers.CodeFixes/StringAssertToAssertFixer.cs new file mode 100644 index 0000000000..735626a8d1 --- /dev/null +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/StringAssertToAssertFixer.cs @@ -0,0 +1,99 @@ +// 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.Immutable; +using System.Composition; + +using Analyzer.Utilities; + +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CodeActions; +using Microsoft.CodeAnalysis.CodeFixes; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Editing; + +using MSTest.Analyzers.Helpers; + +namespace MSTest.Analyzers.CodeFixes; + +/// +/// Code fixer for . +/// +[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(StringAssertToAssertFixer))] +[Shared] +public sealed class StringAssertToAssertFixer : CodeFixProvider +{ + /// + public override ImmutableArray FixableDiagnosticIds { get; } + = ImmutableArray.Create(DiagnosticIds.StringAssertToAssertRuleId); + + /// + public sealed override FixAllProvider GetFixAllProvider() + // See https://github.com/dotnet/roslyn/blob/main/docs/analyzers/FixAllProvider.md for more information on Fix All Providers + => WellKnownFixAllProviders.BatchFixer; + + /// + public override async Task RegisterCodeFixesAsync(CodeFixContext context) + { + SyntaxNode? root = await context.Document.GetRequiredSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); + + Diagnostic diagnostic = context.Diagnostics[0]; + if (!diagnostic.Properties.TryGetValue(StringAssertToAssertAnalyzer.ProperAssertMethodNameKey, out string? properAssertMethodName) + || properAssertMethodName == null) + { + return; + } + + if (root.FindNode(diagnostic.Location.SourceSpan, getInnermostNodeForTie: true) is not InvocationExpressionSyntax invocationExpressionSyntax) + { + return; + } + + // Register a code fix that will invoke the fix operation. + string title = string.Format(CultureInfo.InvariantCulture, CodeFixResources.StringAssertToAssertTitle, properAssertMethodName); + var action = CodeAction.Create( + title: title, + createChangedDocument: ct => FixStringAssertAsync(context.Document, invocationExpressionSyntax, properAssertMethodName, ct), + equivalenceKey: title); + + context.RegisterCodeFix(action, diagnostic); + } + + private static async Task FixStringAssertAsync( + Document document, + InvocationExpressionSyntax invocationExpr, + string properAssertMethodName, + CancellationToken cancellationToken) + { + // Check if the invocation expression has a member access expression + if (invocationExpr.Expression is not MemberAccessExpressionSyntax memberAccessExpr) + { + return document; + } + + SeparatedSyntaxList arguments = invocationExpr.ArgumentList.Arguments; + if (arguments.Count < 2) + { + return document; + } + + DocumentEditor editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false); + + // Create new argument list with swapped first two arguments + ArgumentSyntax[] newArguments = [.. arguments]; + (newArguments[0], newArguments[1]) = (newArguments[1], newArguments[0]); + + ArgumentListSyntax newArgumentList = SyntaxFactory.ArgumentList(SyntaxFactory.SeparatedList(newArguments)); + InvocationExpressionSyntax newInvocationExpr = invocationExpr.WithArgumentList(newArgumentList); + + // Replace StringAssert with Assert in the member access expression + // Change StringAssert.MethodName to Assert.ProperMethodName + MemberAccessExpressionSyntax newMemberAccess = memberAccessExpr.WithExpression(SyntaxFactory.IdentifierName("Assert")) + .WithName(SyntaxFactory.IdentifierName(properAssertMethodName)); + newInvocationExpr = newInvocationExpr.WithExpression(newMemberAccess); + + editor.ReplaceNode(invocationExpr, newInvocationExpr); + return editor.GetChangedDocument(); + } +} diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.cs.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.cs.xlf index b1fa26c3dd..549c922f8e 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.cs.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.cs.xlf @@ -72,6 +72,11 @@ Nahradit konstruktor metodou TestInitialize + + Use 'Assert.{0}' instead of 'StringAssert' + Use 'Assert.{0}' instead of 'StringAssert' + + Fix test class signature Oprava podpisu testovací třídy diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.de.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.de.xlf index ff96bdfeab..82bf84d0fc 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.de.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.de.xlf @@ -72,6 +72,11 @@ Konstruktor durch TestInitialize-Methode ersetzen + + Use 'Assert.{0}' instead of 'StringAssert' + Use 'Assert.{0}' instead of 'StringAssert' + + Fix test class signature Testklassensignatur korrigieren diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.es.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.es.xlf index ed2a4544bf..a29ae7658a 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.es.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.es.xlf @@ -72,6 +72,11 @@ Reemplazar constructor por el método TestInitialize + + Use 'Assert.{0}' instead of 'StringAssert' + Use 'Assert.{0}' instead of 'StringAssert' + + Fix test class signature Corregir firma de clase de prueba diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.fr.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.fr.xlf index 12098b7ede..820d2bf494 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.fr.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.fr.xlf @@ -72,6 +72,11 @@ Remplacer le constructeur par la méthode TestInitialize + + Use 'Assert.{0}' instead of 'StringAssert' + Use 'Assert.{0}' instead of 'StringAssert' + + Fix test class signature Correction de la signature de classe de test diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.it.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.it.xlf index 029c82d292..852cafb489 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.it.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.it.xlf @@ -72,6 +72,11 @@ Sostituisci costruttore con metodo TestInitialize + + Use 'Assert.{0}' instead of 'StringAssert' + Use 'Assert.{0}' instead of 'StringAssert' + + Fix test class signature Correggi la firma della classe di test diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ja.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ja.xlf index 0201230d7f..98feef9225 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ja.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ja.xlf @@ -72,6 +72,11 @@ コンストラクターを TestInitialize メソッドに置き換える + + Use 'Assert.{0}' instead of 'StringAssert' + Use 'Assert.{0}' instead of 'StringAssert' + + Fix test class signature テスト クラスのシグネチャの修正 diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ko.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ko.xlf index a696d30d84..6bb69a31f3 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ko.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ko.xlf @@ -72,6 +72,11 @@ 생성자를 TestInitialize 메서드로 바꾸기 + + Use 'Assert.{0}' instead of 'StringAssert' + Use 'Assert.{0}' instead of 'StringAssert' + + Fix test class signature 테스트 클래스 서명 수정 diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pl.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pl.xlf index 7aa82ebaea..a3a0769c2d 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pl.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pl.xlf @@ -72,6 +72,11 @@ Zastąp konstruktor metodą TestInitialize + + Use 'Assert.{0}' instead of 'StringAssert' + Use 'Assert.{0}' instead of 'StringAssert' + + Fix test class signature Napraw podpis klasy testowej diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pt-BR.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pt-BR.xlf index 778df4c30c..705260fc18 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pt-BR.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pt-BR.xlf @@ -72,6 +72,11 @@ Substitua o construtor pelo método TestInitialize. + + Use 'Assert.{0}' instead of 'StringAssert' + Use 'Assert.{0}' instead of 'StringAssert' + + Fix test class signature Correção da assinatura de classe do teste diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ru.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ru.xlf index f8c0562a03..2a4bcf0f43 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ru.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ru.xlf @@ -72,6 +72,11 @@ Заменить конструктор на метод TestInitialize + + Use 'Assert.{0}' instead of 'StringAssert' + Use 'Assert.{0}' instead of 'StringAssert' + + Fix test class signature Исправить подпись класса теста diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.tr.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.tr.xlf index 4e8c21035e..74efb9a749 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.tr.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.tr.xlf @@ -72,6 +72,11 @@ Oluşturucuyu TestInitialize yöntemiyle değiştir + + Use 'Assert.{0}' instead of 'StringAssert' + Use 'Assert.{0}' instead of 'StringAssert' + + Fix test class signature Test sınıfı imzasını düzeltme diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hans.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hans.xlf index b9e86e472f..bd5dd14172 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hans.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hans.xlf @@ -72,6 +72,11 @@ 将构造函数替换为 TestInitialize 方法 + + Use 'Assert.{0}' instead of 'StringAssert' + Use 'Assert.{0}' instead of 'StringAssert' + + Fix test class signature 修复测试类签名 diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hant.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hant.xlf index fe3a40e80f..ea6323de02 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hant.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hant.xlf @@ -72,6 +72,11 @@ 使用 TestInitialize 方法取代建構函式 + + Use 'Assert.{0}' instead of 'StringAssert' + Use 'Assert.{0}' instead of 'StringAssert' + + Fix test class signature 修正測試類別簽章 diff --git a/src/Analyzers/MSTest.Analyzers/AnalyzerReleases.Unshipped.md b/src/Analyzers/MSTest.Analyzers/AnalyzerReleases.Unshipped.md index a3ed571d22..0adb7548d8 100644 --- a/src/Analyzers/MSTest.Analyzers/AnalyzerReleases.Unshipped.md +++ b/src/Analyzers/MSTest.Analyzers/AnalyzerReleases.Unshipped.md @@ -7,7 +7,7 @@ Rule ID | Category | Severity | Notes --------|----------|----------|------- MSTEST0044 | Design | Warning | PreferTestMethodOverDataTestMethodAnalyzer, [Documentation](https://learn.microsoft.com/dotnet/core/testing/mstest-analyzers/mstest0044) MSTEST0045 | Usage | Info | UseCooperativeCancellationForTimeoutAnalyzer, [Documentation](https://learn.microsoft.com/dotnet/core/testing/mstest-analyzers/mstest0045) - +MSTEST0046 | Usage | Info | StringAssertToAssertAnalyzer, [Documentation](https://learn.microsoft.com/dotnet/core/testing/mstest-analyzers/mstest0046) ### Changed Rules diff --git a/src/Analyzers/MSTest.Analyzers/Helpers/DiagnosticIds.cs b/src/Analyzers/MSTest.Analyzers/Helpers/DiagnosticIds.cs index 24ae712f8a..dd310737ac 100644 --- a/src/Analyzers/MSTest.Analyzers/Helpers/DiagnosticIds.cs +++ b/src/Analyzers/MSTest.Analyzers/Helpers/DiagnosticIds.cs @@ -50,4 +50,5 @@ internal static class DiagnosticIds public const string UseRetryWithTestMethodRuleId = "MSTEST0043"; public const string PreferTestMethodOverDataTestMethodRuleId = "MSTEST0044"; public const string UseCooperativeCancellationForTimeoutRuleId = "MSTEST0045"; + public const string StringAssertToAssertRuleId = "MSTEST0046"; } diff --git a/src/Analyzers/MSTest.Analyzers/Resources.Designer.cs b/src/Analyzers/MSTest.Analyzers/Resources.Designer.cs index 23d0723ad0..12df6a0491 100644 --- a/src/Analyzers/MSTest.Analyzers/Resources.Designer.cs +++ b/src/Analyzers/MSTest.Analyzers/Resources.Designer.cs @@ -1266,5 +1266,23 @@ internal static string UseCooperativeCancellationForTimeoutTitle { return ResourceManager.GetString("UseCooperativeCancellationForTimeoutTitle", resourceCulture); } } + + /// + /// Looks up a localized string similar to Use 'Assert.{0}' instead of 'StringAssert.{1}'. + /// + internal static string StringAssertToAssertMessageFormat { + get { + return ResourceManager.GetString("StringAssertToAssertMessageFormat", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Use 'Assert' instead of 'StringAssert'. + /// + internal static string StringAssertToAssertTitle { + get { + return ResourceManager.GetString("StringAssertToAssertTitle", resourceCulture); + } + } } } diff --git a/src/Analyzers/MSTest.Analyzers/Resources.resx b/src/Analyzers/MSTest.Analyzers/Resources.resx index eacef2a1ab..50ba58dda1 100644 --- a/src/Analyzers/MSTest.Analyzers/Resources.resx +++ b/src/Analyzers/MSTest.Analyzers/Resources.resx @@ -534,6 +534,12 @@ The type declaring these methods should also respect the following rules: Use 'Assert.{0}' instead of 'Assert.{1}' + + Use 'Assert' instead of 'StringAssert' + + + Use 'Assert.{0}' instead of 'StringAssert.{1}' + The type of the generic parameter '{0}' could not be inferred. diff --git a/src/Analyzers/MSTest.Analyzers/StringAssertToAssertAnalyzer.cs b/src/Analyzers/MSTest.Analyzers/StringAssertToAssertAnalyzer.cs new file mode 100644 index 0000000000..a1a689fd4a --- /dev/null +++ b/src/Analyzers/MSTest.Analyzers/StringAssertToAssertAnalyzer.cs @@ -0,0 +1,128 @@ +// 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.Immutable; + +using Analyzer.Utilities.Extensions; + +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Diagnostics; +using Microsoft.CodeAnalysis.Operations; + +using MSTest.Analyzers.Helpers; + +namespace MSTest.Analyzers; + +/// +/// MSTEST0045: Use 'Assert' instead of 'StringAssert'. +/// +/// +/// The analyzer captures StringAssert method calls and suggests using equivalent Assert methods: +/// +/// +/// +/// StringAssert.Contains(value, substring)Assert.Contains(substring, value) +/// +/// +/// +/// +/// StringAssert.StartsWith(value, substring)Assert.StartsWith(substring, value) +/// +/// +/// +/// +/// StringAssert.EndsWith(value, substring)Assert.EndsWith(substring, value) +/// +/// +/// +/// +/// StringAssert.Matches(value, pattern)Assert.Matches(pattern, value) +/// +/// +/// +/// +/// StringAssert.DoesNotMatch(value, pattern)Assert.DoesNotMatch(pattern, value) +/// +/// +/// +/// +[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] +internal sealed class StringAssertToAssertAnalyzer : DiagnosticAnalyzer +{ + /// + /// Key to retrieve the proper assert method name from the properties bag. + /// + internal const string ProperAssertMethodNameKey = nameof(ProperAssertMethodNameKey); + + private static readonly LocalizableResourceString Title = new(nameof(Resources.StringAssertToAssertTitle), Resources.ResourceManager, typeof(Resources)); + private static readonly LocalizableResourceString MessageFormat = new(nameof(Resources.StringAssertToAssertMessageFormat), Resources.ResourceManager, typeof(Resources)); + + internal static readonly DiagnosticDescriptor Rule = DiagnosticDescriptorHelper.Create( + DiagnosticIds.StringAssertToAssertRuleId, + Title, + MessageFormat, + null, + Category.Usage, + DiagnosticSeverity.Info, + isEnabledByDefault: true); + + public override ImmutableArray SupportedDiagnostics { get; } + = ImmutableArray.Create(Rule); + + public override void Initialize(AnalysisContext context) + { + context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); + context.EnableConcurrentExecution(); + + context.RegisterCompilationStartAction(context => + { + if (!context.Compilation.TryGetOrCreateTypeByMetadataName(WellKnownTypeNames.MicrosoftVisualStudioTestToolsUnitTestingStringAssert, out INamedTypeSymbol? stringAssertTypeSymbol)) + { + return; + } + + context.RegisterOperationAction(context => AnalyzeInvocationOperation(context, stringAssertTypeSymbol), OperationKind.Invocation); + }); + } + + private static void AnalyzeInvocationOperation(OperationAnalysisContext context, INamedTypeSymbol stringAssertTypeSymbol) + { + var operation = (IInvocationOperation)context.Operation; + IMethodSymbol targetMethod = operation.TargetMethod; + + if (!SymbolEqualityComparer.Default.Equals(targetMethod.ContainingType, stringAssertTypeSymbol)) + { + return; + } + + // Map StringAssert methods to their equivalent Assert methods + string? assertMethodName = targetMethod.Name switch + { + "Contains" => "Contains", + "StartsWith" => "StartsWith", + "EndsWith" => "EndsWith", + "Matches" => "MatchesRegex", + "DoesNotMatch" => "DoesNotMatchRegex", + _ => null, + }; + + if (assertMethodName == null) + { + return; + } + + // StringAssert methods all have at least 2 arguments that need to be swapped + if (operation.Arguments.Length < 2) + { + return; + } + + ImmutableDictionary properties = ImmutableDictionary.Empty.Add(ProperAssertMethodNameKey, assertMethodName); + + context.ReportDiagnostic(context.Operation.CreateDiagnostic( + Rule, + properties: properties, + assertMethodName, + targetMethod.Name)); + } +} diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf index 22063a35b8..10063fbe40 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf @@ -532,6 +532,16 @@ Typ deklarující tyto metody by měl také respektovat následující pravidla: Veřejné typy by měly být testovací třídy. + + Use 'Assert.{0}' instead of 'StringAssert.{1}' + Use 'Assert.{0}' instead of 'StringAssert.{1}' + + + + Use 'Assert' instead of 'StringAssert' + Use 'Assert' instead of 'StringAssert' + + Test class '{0}' should be valid Testovací třída {0} by měla být platná. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf index fe75593577..fdfd8a31ef 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf @@ -533,6 +533,16 @@ Der Typ, der diese Methoden deklariert, sollte auch die folgenden Regeln beachte Öffentliche Typen sollten Testklassen sein. + + Use 'Assert.{0}' instead of 'StringAssert.{1}' + Use 'Assert.{0}' instead of 'StringAssert.{1}' + + + + Use 'Assert' instead of 'StringAssert' + Use 'Assert' instead of 'StringAssert' + + Test class '{0}' should be valid Die Testklasse „{0}“ muss gültig sein diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf index 87bf00ca81..f016e9e9ae 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf @@ -532,6 +532,16 @@ El tipo que declara estos métodos también debe respetar las reglas siguientes: Los tipos públicos deben ser clases de prueba + + Use 'Assert.{0}' instead of 'StringAssert.{1}' + Use 'Assert.{0}' instead of 'StringAssert.{1}' + + + + Use 'Assert' instead of 'StringAssert' + Use 'Assert' instead of 'StringAssert' + + Test class '{0}' should be valid La clase de prueba '{0}' debe ser válida diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf index 6d8124a4cf..5c115631af 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf @@ -532,6 +532,16 @@ Le type doit être une classe Les types publics doivent être des classes de test + + Use 'Assert.{0}' instead of 'StringAssert.{1}' + Use 'Assert.{0}' instead of 'StringAssert.{1}' + + + + Use 'Assert' instead of 'StringAssert' + Use 'Assert' instead of 'StringAssert' + + Test class '{0}' should be valid La classe de test « {0} » doit être valide diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf index 8ee1495b52..84ae7020a8 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf @@ -532,6 +532,16 @@ Anche il tipo che dichiara questi metodi deve rispettare le regole seguenti: I tipi di pubblico dovrebbero essere classi di test + + Use 'Assert.{0}' instead of 'StringAssert.{1}' + Use 'Assert.{0}' instead of 'StringAssert.{1}' + + + + Use 'Assert' instead of 'StringAssert' + Use 'Assert' instead of 'StringAssert' + + Test class '{0}' should be valid La classe di test '{0}' deve essere valida diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf index 21bde27a71..d68db618d1 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf @@ -532,6 +532,16 @@ The type declaring these methods should also respect the following rules: パブリック型はテスト クラスである必要があります + + Use 'Assert.{0}' instead of 'StringAssert.{1}' + Use 'Assert.{0}' instead of 'StringAssert.{1}' + + + + Use 'Assert' instead of 'StringAssert' + Use 'Assert' instead of 'StringAssert' + + Test class '{0}' should be valid テスト クラス '{0}' は有効である必要があります diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf index 601f5c7c93..f193113ee7 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf @@ -532,6 +532,16 @@ The type declaring these methods should also respect the following rules: 공용 형식은 테스트 클래스여야 합니다. + + Use 'Assert.{0}' instead of 'StringAssert.{1}' + Use 'Assert.{0}' instead of 'StringAssert.{1}' + + + + Use 'Assert' instead of 'StringAssert' + Use 'Assert' instead of 'StringAssert' + + Test class '{0}' should be valid 테스트 클래스 '{0}'은(는) 유효해야 합니다. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf index 6ffcf37698..14f9189e78 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf @@ -532,6 +532,16 @@ Typ deklarujący te metody powinien również przestrzegać następujących regu Typy publiczne powinny być klasami testowymi + + Use 'Assert.{0}' instead of 'StringAssert.{1}' + Use 'Assert.{0}' instead of 'StringAssert.{1}' + + + + Use 'Assert' instead of 'StringAssert' + Use 'Assert' instead of 'StringAssert' + + Test class '{0}' should be valid Klasa testowa „{0}” powinna być prawidłowa diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf index ae5fcb582b..563fd9b73b 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf @@ -532,6 +532,16 @@ O tipo que declara esses métodos também deve respeitar as seguintes regras: Os tipos públicos devem ser classes de teste + + Use 'Assert.{0}' instead of 'StringAssert.{1}' + Use 'Assert.{0}' instead of 'StringAssert.{1}' + + + + Use 'Assert' instead of 'StringAssert' + Use 'Assert' instead of 'StringAssert' + + Test class '{0}' should be valid A classe de teste ''{0}'' deve ser válida diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf index 89f45468d0..c5fbd517cf 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf @@ -538,6 +538,16 @@ The type declaring these methods should also respect the following rules: Общедоступные типы должны быть тестовыми классами + + Use 'Assert.{0}' instead of 'StringAssert.{1}' + Use 'Assert.{0}' instead of 'StringAssert.{1}' + + + + Use 'Assert' instead of 'StringAssert' + Use 'Assert' instead of 'StringAssert' + + Test class '{0}' should be valid Тестовый класс "{0}" должен быть допустимым diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf index 89633f209d..c2af3aefb0 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf @@ -532,6 +532,16 @@ Bu yöntemleri bildiren tipin ayrıca aşağıdaki kurallara uyması gerekir: Genel türler test sınıfları olmalıdır + + Use 'Assert.{0}' instead of 'StringAssert.{1}' + Use 'Assert.{0}' instead of 'StringAssert.{1}' + + + + Use 'Assert' instead of 'StringAssert' + Use 'Assert' instead of 'StringAssert' + + Test class '{0}' should be valid '{0}' test sınıfı geçerli olmalıdır diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf index 56f36c52f0..61075a0c1d 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf @@ -532,6 +532,16 @@ The type declaring these methods should also respect the following rules: 公共类型应为测试类 + + Use 'Assert.{0}' instead of 'StringAssert.{1}' + Use 'Assert.{0}' instead of 'StringAssert.{1}' + + + + Use 'Assert' instead of 'StringAssert' + Use 'Assert' instead of 'StringAssert' + + Test class '{0}' should be valid 测试类“{0}”应该有效 diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf index b653fa674b..ef520dba33 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf @@ -532,6 +532,16 @@ The type declaring these methods should also respect the following rules: 公用類型應為測試類別 + + Use 'Assert.{0}' instead of 'StringAssert.{1}' + Use 'Assert.{0}' instead of 'StringAssert.{1}' + + + + Use 'Assert' instead of 'StringAssert' + Use 'Assert' instead of 'StringAssert' + + Test class '{0}' should be valid 測試類別 '{0}' 應為有效 diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/MSBuildTests.Test.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/MSBuildTests.Test.cs index 18454fe46c..cd8eb9e5dd 100644 --- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/MSBuildTests.Test.cs +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/MSBuildTests.Test.cs @@ -50,7 +50,7 @@ private async Task InvokeTestingPlatform_Target_Should_Execute_Tests_Without_Sho AssetName, SourceCode .PatchCodeWithReplace("$PlatformTarget$", "x64") - .PatchCodeWithReplace("$TargetFrameworks$", isMultiTfm ? $"{tfm}" : $"{tfm}") + .PatchCodeWithReplace("$TargetFrameworks$", isMultiTfm ? $"{tfm}" : $"{tfm}") .PatchCodeWithReplace("$AssertValue$", testSucceeded.ToString().ToLowerInvariant()) .PatchCodeWithReplace("$MicrosoftTestingPlatformVersion$", MicrosoftTestingPlatformVersion)); string testResultFolder = Path.Combine(testAsset.TargetAssetPath, Guid.NewGuid().ToString("N")); @@ -78,7 +78,7 @@ private async Task InvokeTestingPlatform_Target_Should_Build_Without_Warnings_An AssetName, SourceCode .PatchCodeWithReplace("$PlatformTarget$", "x64") - .PatchCodeWithReplace("$TargetFrameworks$", isMultiTfm ? $"{tfm}" : $"{tfm}") + .PatchCodeWithReplace("$TargetFrameworks$", isMultiTfm ? $"{tfm}" : $"{tfm}") .PatchCodeWithReplace("$AssertValue$", testSucceeded.ToString().ToLowerInvariant()) .PatchCodeWithReplace("$MicrosoftTestingPlatformVersion$", MicrosoftTestingPlatformVersion)); string testResultFolder = Path.Combine(testAsset.TargetAssetPath, Guid.NewGuid().ToString("N")); @@ -107,7 +107,7 @@ public async Task RunUsingTestTargetWithNetfxMSBuild() AssetName, SourceCode .PatchCodeWithReplace("$PlatformTarget$", string.Empty) - .PatchCodeWithReplace("$TargetFrameworks$", $"{TargetFrameworks.NetCurrent}") + .PatchCodeWithReplace("$TargetFrameworks$", $"{TargetFrameworks.NetCurrent}") .PatchCodeWithReplace("$AssertValue$", bool.TrueString.ToLowerInvariant()) .PatchCodeWithReplace("$MicrosoftTestingPlatformVersion$", MicrosoftTestingPlatformVersion)); @@ -175,7 +175,7 @@ public async Task Invoke_DotnetTest_With_Incompatible_Arch() AssetName, SourceCode .PatchCodeWithReplace("$PlatformTarget$", string.Empty) - .PatchCodeWithReplace("$TargetFrameworks$", $"{TargetFrameworks.NetCurrent}") + .PatchCodeWithReplace("$TargetFrameworks$", $"{TargetFrameworks.NetCurrent}") .PatchCodeWithReplace("$AssertValue$", bool.TrueString.ToLowerInvariant()) .PatchCodeWithReplace("$MicrosoftTestingPlatformVersion$", MicrosoftTestingPlatformVersion)); DotnetMuxerResult result = await DotnetCli.RunAsync( @@ -281,7 +281,7 @@ public async Task InvokeTestingPlatform_Target_Showing_Error_And_Do_Not_Capture_ AssetName, SourceCode .PatchCodeWithReplace("$PlatformTarget$", "x64") - .PatchCodeWithReplace("$TargetFrameworks$", $"{tfm}") + .PatchCodeWithReplace("$TargetFrameworks$", $"{tfm}") .PatchCodeWithReplace("$AssertValue$", testSucceeded.ToString().ToLowerInvariant()) .PatchCodeWithReplace("$MicrosoftTestingPlatformVersion$", MicrosoftTestingPlatformVersion)); DotnetMuxerResult compilationResult = await DotnetCli.RunAsync($"{testCommand} -p:TestingPlatformShowTestsFailure=True -p:TestingPlatformCaptureOutput=False -p:Configuration={compilationMode} -p:nodeReuse=false {testAsset.TargetAssetPath}", AcceptanceFixture.NuGetGlobalPackagesFolder.Path, workingDirectory: testAsset.TargetAssetPath, failIfReturnValueIsNotZero: false); @@ -298,7 +298,7 @@ public async Task TestingPlatformDisableCustomTestTarget_Should_Cause_UserDefine AssetName, SourceCode .PatchCodeWithReplace("$PlatformTarget$", "x64") - .PatchCodeWithReplace("$TargetFrameworks$", $"{TargetFrameworks.NetCurrent}") + .PatchCodeWithReplace("$TargetFrameworks$", $"{TargetFrameworks.NetCurrent}") .PatchCodeWithReplace("$AssertValue$", "true") .PatchCodeWithReplace("$MicrosoftTestingPlatformVersion$", MicrosoftTestingPlatformVersion)); DotnetMuxerResult compilationResult = await DotnetCli.RunAsync($"build {testAsset.TargetAssetPath} -p:TestingPlatformDisableCustomTestTarget=true -p:ImportUserDefinedTestTarget=true -t:\"Build;Test\"", AcceptanceFixture.NuGetGlobalPackagesFolder.Path, failIfReturnValueIsNotZero: false); diff --git a/test/UnitTests/MSTest.Analyzers.UnitTests/StringAssertToAssertAnalyzerTests.cs b/test/UnitTests/MSTest.Analyzers.UnitTests/StringAssertToAssertAnalyzerTests.cs new file mode 100644 index 0000000000..8930230794 --- /dev/null +++ b/test/UnitTests/MSTest.Analyzers.UnitTests/StringAssertToAssertAnalyzerTests.cs @@ -0,0 +1,311 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using VerifyCS = MSTest.Analyzers.Test.CSharpCodeFixVerifier< + MSTest.Analyzers.StringAssertToAssertAnalyzer, + MSTest.Analyzers.CodeFixes.StringAssertToAssertFixer>; + +namespace MSTest.Analyzers.Test; + +[TestClass] +public sealed class StringAssertToAssertAnalyzerTests +{ + [TestMethod] + public async Task WhenStringAssertContains() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + string value = "Hello World"; + string substring = "World"; + {|#0:StringAssert.Contains(value, substring)|}; + } + } + """; + + string fixedCode = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + string value = "Hello World"; + string substring = "World"; + Assert.Contains(substring, value); + } + } + """; + + await VerifyCS.VerifyCodeFixAsync( + code, + // /0/Test0.cs(11,9): info MSTEST0045: Use 'Assert.Contains' instead of 'StringAssert.Contains' + VerifyCS.DiagnosticIgnoringAdditionalLocations().WithLocation(0).WithArguments("Contains", "Contains"), + fixedCode); + } + + [TestMethod] + public async Task WhenStringAssertStartsWith() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + string value = "Hello World"; + string substring = "Hello"; + {|#0:StringAssert.StartsWith(value, substring)|}; + } + } + """; + + string fixedCode = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + string value = "Hello World"; + string substring = "Hello"; + Assert.StartsWith(substring, value); + } + } + """; + + await VerifyCS.VerifyCodeFixAsync( + code, + // /0/Test0.cs(11,9): info MSTEST0045: Use 'Assert.StartsWith' instead of 'StringAssert.StartsWith' + VerifyCS.DiagnosticIgnoringAdditionalLocations().WithLocation(0).WithArguments("StartsWith", "StartsWith"), + fixedCode); + } + + [TestMethod] + public async Task WhenStringAssertEndsWith() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + string value = "Hello World"; + string substring = "World"; + {|#0:StringAssert.EndsWith(value, substring)|}; + } + } + """; + + string fixedCode = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + string value = "Hello World"; + string substring = "World"; + Assert.EndsWith(substring, value); + } + } + """; + + await VerifyCS.VerifyCodeFixAsync( + code, + // /0/Test0.cs(11,9): info MSTEST0045: Use 'Assert.EndsWith' instead of 'StringAssert.EndsWith' + VerifyCS.DiagnosticIgnoringAdditionalLocations().WithLocation(0).WithArguments("EndsWith", "EndsWith"), + fixedCode); + } + + [TestMethod] + public async Task WhenStringAssertMatches() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + using System.Text.RegularExpressions; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + string value = "Hello World"; + Regex pattern = new Regex("Hello.*"); + {|#0:StringAssert.Matches(value, pattern)|}; + } + } + """; + + string fixedCode = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + using System.Text.RegularExpressions; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + string value = "Hello World"; + Regex pattern = new Regex("Hello.*"); + Assert.MatchesRegex(pattern, value); + } + } + """; + + await VerifyCS.VerifyCodeFixAsync( + code, + // /0/Test0.cs(12,9): info MSTEST0045: Use 'Assert.MatchesRegex' instead of 'StringAssert.Matches' + VerifyCS.DiagnosticIgnoringAdditionalLocations().WithLocation(0).WithArguments("MatchesRegex", "Matches"), + fixedCode); + } + + [TestMethod] + public async Task WhenStringAssertDoesNotMatch() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + using System.Text.RegularExpressions; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + string value = "Hello World"; + Regex pattern = new Regex("Goodbye.*"); + {|#0:StringAssert.DoesNotMatch(value, pattern)|}; + } + } + """; + + string fixedCode = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + using System.Text.RegularExpressions; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + string value = "Hello World"; + Regex pattern = new Regex("Goodbye.*"); + Assert.DoesNotMatchRegex(pattern, value); + } + } + """; + + await VerifyCS.VerifyCodeFixAsync( + code, + // /0/Test0.cs(12,9): info MSTEST0045: Use 'Assert.DoesNotMatchRegex' instead of 'StringAssert.DoesNotMatch' + VerifyCS.DiagnosticIgnoringAdditionalLocations().WithLocation(0).WithArguments("DoesNotMatchRegex", "DoesNotMatch"), + fixedCode); + } + + [TestMethod] + public async Task WhenStringAssertContainsWithMessage() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + string value = "Hello World"; + string substring = "World"; + {|#0:StringAssert.Contains(value, substring, "Custom message")|}; + } + } + """; + + string fixedCode = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + string value = "Hello World"; + string substring = "World"; + Assert.Contains(substring, value, "Custom message"); + } + } + """; + + await VerifyCS.VerifyCodeFixAsync( + code, + // /0/Test0.cs(11,9): info MSTEST0045: Use 'Assert.Contains' instead of 'StringAssert.Contains' + VerifyCS.DiagnosticIgnoringAdditionalLocations().WithLocation(0).WithArguments("Contains", "Contains"), + fixedCode); + } + + [TestMethod] + public async Task WhenNotStringAssertMethod_NoDiagnostic() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + string value = "Hello World"; + Assert.AreEqual("expected", value); + } + } + """; + + await VerifyCS.VerifyAnalyzerAsync(code); + } + + [TestMethod] + public async Task WhenStringAssertMethodWithInsufficientArguments_NoDiagnostic() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + // This won't compile but should not crash the analyzer + // error CS1501: No overload for method 'Contains' takes 1 arguments + StringAssert.{|CS1501:Contains|}("single"); + } + } + """; + + await VerifyCS.VerifyAnalyzerAsync(code); + } +} From b1edce21fa74ac0444f92355d230a498196a3382 Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Fri, 4 Jul 2025 06:04:20 +0000 Subject: [PATCH 164/541] [main] Update dependencies from dotnet/arcade (#5933) [main] Update dependencies from dotnet/arcade --- eng/Version.Details.xml | 12 ++++++------ eng/Versions.props | 2 +- global.json | 2 +- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index ccb96aaf5c..2500a84cd2 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -1,17 +1,17 @@ - + https://github.com/dotnet/arcade - d1834121068b0df7974a380cebadb781e58ff098 + aea743edf7c9345cfdbdf9593756973baadc6b37 - + https://github.com/dotnet/arcade - d1834121068b0df7974a380cebadb781e58ff098 + aea743edf7c9345cfdbdf9593756973baadc6b37 - + https://github.com/dotnet/arcade - d1834121068b0df7974a380cebadb781e58ff098 + aea743edf7c9345cfdbdf9593756973baadc6b37 https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage diff --git a/eng/Versions.props b/eng/Versions.props index f1134fa78f..a0596001d8 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -7,7 +7,7 @@ preview - 10.0.0-beta.25352.1 + 10.0.0-beta.25353.1 17.15.0-preview.25352.2 diff --git a/global.json b/global.json index 615e42a0fa..eca2b03774 100644 --- a/global.json +++ b/global.json @@ -33,7 +33,7 @@ "rollForward": "latestFeature" }, "msbuild-sdks": { - "Microsoft.DotNet.Arcade.Sdk": "10.0.0-beta.25352.1", + "Microsoft.DotNet.Arcade.Sdk": "10.0.0-beta.25353.1", "MSBuild.Sdk.Extras": "3.0.44" } } From f9259522124b89d281d365e93824890e65d88f91 Mon Sep 17 00:00:00 2001 From: Copilot <198982749+Copilot@users.noreply.github.com> Date: Mon, 7 Jul 2025 10:30:49 +0200 Subject: [PATCH 165/541] Fix MSTEST0020 codefix placing code in static constructors (#5935) Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: Youssef1313 <31348972+Youssef1313@users.noreply.github.com> Co-authored-by: Youssef Victor --- ...referConstructorOverTestInitializeFixer.cs | 2 +- ...structorOverTestInitializeAnalyzerTests.cs | 44 +++++++++++++++++++ 2 files changed, 45 insertions(+), 1 deletion(-) diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/PreferConstructorOverTestInitializeFixer.cs b/src/Analyzers/MSTest.Analyzers.CodeFixes/PreferConstructorOverTestInitializeFixer.cs index b2005cc8c6..de7cb2e8e8 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/PreferConstructorOverTestInitializeFixer.cs +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/PreferConstructorOverTestInitializeFixer.cs @@ -68,7 +68,7 @@ private static async Task ReplaceTestInitializeWithConstructorAsync(Do { ConstructorDeclarationSyntax? existingConstructor = containingClass.Members .OfType() - .FirstOrDefault(); + .FirstOrDefault(c => !c.Modifiers.Any(SyntaxKind.StaticKeyword)); // Move the body of the TestInitialize method BlockSyntax? testInitializeBody = testInitializeMethod.Body; diff --git a/test/UnitTests/MSTest.Analyzers.UnitTests/PreferConstructorOverTestInitializeAnalyzerTests.cs b/test/UnitTests/MSTest.Analyzers.UnitTests/PreferConstructorOverTestInitializeAnalyzerTests.cs index f6335eedb7..b5d581b88f 100644 --- a/test/UnitTests/MSTest.Analyzers.UnitTests/PreferConstructorOverTestInitializeAnalyzerTests.cs +++ b/test/UnitTests/MSTest.Analyzers.UnitTests/PreferConstructorOverTestInitializeAnalyzerTests.cs @@ -251,4 +251,48 @@ public MyTestClass(int y) await VerifyCS.VerifyCodeFixAsync(code, fixedCode); } + + [TestMethod] + public async Task WhenTestClassHasStaticCtorAndTestInitialize_Diagnostic() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + private object _instanceVariable; + + static MyTestClass() + { + } + + [TestInitialize] + public void [|MyTestInit|]() + { + _instanceVariable = new object(); + } + } + """; + string fixedCode = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + private object _instanceVariable; + + static MyTestClass() + { + } + + public MyTestClass() + { + _instanceVariable = new object(); + } + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, fixedCode); + } } From 5f68c32577a976e1d878700f1abb3a6a27e1e803 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Mon, 7 Jul 2025 14:00:09 +0200 Subject: [PATCH 166/541] Avoid potential clash with default TRX file name (#5939) --- .../Microsoft.Testing.Extensions.TrxReport/TrxReportEngine.cs | 2 +- .../Microsoft.Testing.Extensions.UnitTests/TrxTests.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxReportEngine.cs b/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxReportEngine.cs index d3f0b3f66e..ba05207d56 100644 --- a/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxReportEngine.cs +++ b/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxReportEngine.cs @@ -678,7 +678,7 @@ private static string FormatDateTimeForRunName(DateTimeOffset date) => // We use custom format string to make sure that runs are sorted in the same way on all intl machines. // This is both for directory names and for Data Warehouse. - date.ToString("yyyy-MM-dd HH:mm:ss.fff", DateTimeFormatInfo.InvariantInfo); + date.ToString("yyyy-MM-dd HH:mm:ss.fffffff", DateTimeFormatInfo.InvariantInfo); private static string ReplaceInvalidFileNameChars(string fileName) { diff --git a/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/TrxTests.cs b/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/TrxTests.cs index e5b424f038..e718088fef 100644 --- a/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/TrxTests.cs +++ b/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/TrxTests.cs @@ -561,7 +561,7 @@ private static void AssertTrxOutcome(XDocument xml, string expectedOutcome) } private static void AssertExpectedTrxFileName(string fileName) - => Assert.IsTrue(fileName.Equals("_MachineName_0001-01-01_00_00_00.000.trx", StringComparison.Ordinal)); + => Assert.IsTrue(fileName.Equals("_MachineName_0001-01-01_00_00_00.0000000.trx", StringComparison.Ordinal)); private TrxReportEngine GenerateTrxReportEngine(int passedTestsCount, int failedTestsCount, PropertyBag propertyBag, MemoryFileStream memoryStream, bool? adapterSupportTrxCapability = null, int notExecutedTestsCount = 0, int timeoutTestsCount = 0, From 27b2ce52ece3ef0d32fed143eaa2e9d2b1d0e70f Mon Sep 17 00:00:00 2001 From: dotnet bot Date: Mon, 7 Jul 2025 16:41:48 +0200 Subject: [PATCH 167/541] Localized file check-in by OneLocBuild Task: Build definition ID 1218: Build ID 2744317 --- .../MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.cs.xlf | 2 +- .../MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.de.xlf | 2 +- .../MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.es.xlf | 2 +- .../MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.fr.xlf | 2 +- .../MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.it.xlf | 2 +- .../MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ko.xlf | 2 +- .../MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pl.xlf | 2 +- .../MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.tr.xlf | 2 +- .../xlf/CodeFixResources.zh-Hans.xlf | 2 +- src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf | 6 +++--- src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf | 6 +++--- src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf | 6 +++--- src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf | 6 +++--- src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf | 6 +++--- src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf | 6 +++--- src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf | 6 +++--- src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf | 6 +++--- src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf | 6 +++--- 18 files changed, 36 insertions(+), 36 deletions(-) diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.cs.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.cs.xlf index 549c922f8e..2cd7939a05 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.cs.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.cs.xlf @@ -104,7 +104,7 @@ Use 'CooperativeCancellation = true' - Use 'CooperativeCancellation = true' + Použijte „CooperativeCancellation = true“ diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.de.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.de.xlf index 82bf84d0fc..c33af08a87 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.de.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.de.xlf @@ -104,7 +104,7 @@ Use 'CooperativeCancellation = true' - Use 'CooperativeCancellation = true' + Verwenden Sie „CooperativeCancellation = true“. diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.es.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.es.xlf index a29ae7658a..3334ac5b90 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.es.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.es.xlf @@ -104,7 +104,7 @@ Use 'CooperativeCancellation = true' - Use 'CooperativeCancellation = true' + Usa "CooperativeCancellation = true" diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.fr.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.fr.xlf index 820d2bf494..2895be63f5 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.fr.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.fr.xlf @@ -104,7 +104,7 @@ Use 'CooperativeCancellation = true' - Use 'CooperativeCancellation = true' + Utilisez 'CooperativeCancellation = true' diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.it.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.it.xlf index 852cafb489..357be76d30 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.it.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.it.xlf @@ -104,7 +104,7 @@ Use 'CooperativeCancellation = true' - Use 'CooperativeCancellation = true' + Usa "CooperativeCancellation = true" diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ko.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ko.xlf index 6bb69a31f3..bc4bb12aab 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ko.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ko.xlf @@ -104,7 +104,7 @@ Use 'CooperativeCancellation = true' - Use 'CooperativeCancellation = true' + 'CooperativeCancellation = true'를 사용하세요. diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pl.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pl.xlf index a3a0769c2d..17422a475f 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pl.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pl.xlf @@ -104,7 +104,7 @@ Use 'CooperativeCancellation = true' - Use 'CooperativeCancellation = true' + Użyj opcji „CooperativeCancellation = true” diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.tr.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.tr.xlf index 74efb9a749..f6b61b99f2 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.tr.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.tr.xlf @@ -104,7 +104,7 @@ Use 'CooperativeCancellation = true' - Use 'CooperativeCancellation = true' + 'CooperativeCancellation = true' kullanın diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hans.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hans.xlf index bd5dd14172..adf31e8ee4 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hans.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hans.xlf @@ -104,7 +104,7 @@ Use 'CooperativeCancellation = true' - Use 'CooperativeCancellation = true' + 使用 'CooperativeCancellation = true' diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf index 10063fbe40..69713927ae 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf @@ -791,17 +791,17 @@ Typ deklarující tyto metody by měl také respektovat následující pravidla: Using '[Timeout]' without explicitly setting 'CooperativeCancellation = true' is discouraged. In a future version, cooperative cancellation will become the default behavior. Set 'CooperativeCancellation = true' to opt into the recommended behavior and avoid breaking changes. - Using '[Timeout]' without explicitly setting 'CooperativeCancellation = true' is discouraged. In a future version, cooperative cancellation will become the default behavior. Set 'CooperativeCancellation = true' to opt into the recommended behavior and avoid breaking changes. + Použití „[Timeout]“ bez explicitního nastavení „CooperativeCancellation = true“ se nedoporučuje. V budoucí verzi se kooperativní zrušení stane výchozím chováním. Nastavte „CooperativeCancellation = true“, abyste zapnuli doporučené chování a vyhnuli se změnám, které by mohly způsobit problémy. Use 'CooperativeCancellation = true' with '[Timeout]' to enable cooperative cancellation behavior - Use 'CooperativeCancellation = true' with '[Timeout]' to enable cooperative cancellation behavior + Použijte „CooperativeCancellation = true“ s „[Timeout]“, abyste povolili chování kooperativního zrušení Use 'CooperativeCancellation = true' with '[Timeout]' - Use 'CooperativeCancellation = true' with '[Timeout]' + Použijte „CooperativeCancellation = true“ s „[Timeout]“ diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf index fdfd8a31ef..c61b7c45b8 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf @@ -792,17 +792,17 @@ Der Typ, der diese Methoden deklariert, sollte auch die folgenden Regeln beachte Using '[Timeout]' without explicitly setting 'CooperativeCancellation = true' is discouraged. In a future version, cooperative cancellation will become the default behavior. Set 'CooperativeCancellation = true' to opt into the recommended behavior and avoid breaking changes. - Using '[Timeout]' without explicitly setting 'CooperativeCancellation = true' is discouraged. In a future version, cooperative cancellation will become the default behavior. Set 'CooperativeCancellation = true' to opt into the recommended behavior and avoid breaking changes. + Es wird davon abgeraten, „[Timeout]“ ohne die explizite Festlegung von „CooperativeCancellation = true“ zu verwenden. In einer zukünftigen Version wird der kooperative Abbruch das Standardverhalten sein. Legen Sie „CooperativeCancellation = true“ fest, um das empfohlene Verhalten zu aktivieren und Breaking Changes zu vermeiden. Use 'CooperativeCancellation = true' with '[Timeout]' to enable cooperative cancellation behavior - Use 'CooperativeCancellation = true' with '[Timeout]' to enable cooperative cancellation behavior + Verwenden Sie „CooperativeCancellation = true“ mit „[Timeout]“, um das kooperative Abbruchverhalten zu aktivieren. Use 'CooperativeCancellation = true' with '[Timeout]' - Use 'CooperativeCancellation = true' with '[Timeout]' + Verwenden Sie „CooperativeCancellation = true“ mit „[Timeout]“. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf index f016e9e9ae..8fb03d3c5f 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf @@ -791,17 +791,17 @@ El tipo que declara estos métodos también debe respetar las reglas siguientes: Using '[Timeout]' without explicitly setting 'CooperativeCancellation = true' is discouraged. In a future version, cooperative cancellation will become the default behavior. Set 'CooperativeCancellation = true' to opt into the recommended behavior and avoid breaking changes. - Using '[Timeout]' without explicitly setting 'CooperativeCancellation = true' is discouraged. In a future version, cooperative cancellation will become the default behavior. Set 'CooperativeCancellation = true' to opt into the recommended behavior and avoid breaking changes. + No se recomienda usar "[Timeout]" sin establecer explícitamente "CooperativeCancellation = true". En una versión futura, la cancelación cooperativa se convertirá en el comportamiento predeterminado. Establece "CooperativeCancellation = true" para participar en el comportamiento recomendado y evitar cambios importantes. Use 'CooperativeCancellation = true' with '[Timeout]' to enable cooperative cancellation behavior - Use 'CooperativeCancellation = true' with '[Timeout]' to enable cooperative cancellation behavior + Usa "CooperativeCancellation = true" con "[Timeout]" para habilitar el comportamiento de cancelación cooperativa. Use 'CooperativeCancellation = true' with '[Timeout]' - Use 'CooperativeCancellation = true' with '[Timeout]' + Usa "CooperativeCancellation = true" con "[Timeout]" diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf index 5c115631af..ab6c48bc2a 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf @@ -791,17 +791,17 @@ Le type doit être une classe Using '[Timeout]' without explicitly setting 'CooperativeCancellation = true' is discouraged. In a future version, cooperative cancellation will become the default behavior. Set 'CooperativeCancellation = true' to opt into the recommended behavior and avoid breaking changes. - Using '[Timeout]' without explicitly setting 'CooperativeCancellation = true' is discouraged. In a future version, cooperative cancellation will become the default behavior. Set 'CooperativeCancellation = true' to opt into the recommended behavior and avoid breaking changes. + L’utilisation de '[Timeout]' sans définir explicitement 'CooperativeCancellation = true' est déconseillée. Dans une future version, l’annulation coopérative deviendra le comportement par défaut. Définissez 'CooperativeCancellation = true' pour adopter le comportement recommandé et éviter les changements incompatibles. Use 'CooperativeCancellation = true' with '[Timeout]' to enable cooperative cancellation behavior - Use 'CooperativeCancellation = true' with '[Timeout]' to enable cooperative cancellation behavior + Utilisez 'CooperativeCancellation = true' avec '[Timeout]' pour activer le comportement d’annulation coopératif Use 'CooperativeCancellation = true' with '[Timeout]' - Use 'CooperativeCancellation = true' with '[Timeout]' + Utiliser 'CooperativeCancellation = true' avec '[Timeout]' diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf index f193113ee7..48843f3e9d 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf @@ -791,17 +791,17 @@ The type declaring these methods should also respect the following rules: Using '[Timeout]' without explicitly setting 'CooperativeCancellation = true' is discouraged. In a future version, cooperative cancellation will become the default behavior. Set 'CooperativeCancellation = true' to opt into the recommended behavior and avoid breaking changes. - Using '[Timeout]' without explicitly setting 'CooperativeCancellation = true' is discouraged. In a future version, cooperative cancellation will become the default behavior. Set 'CooperativeCancellation = true' to opt into the recommended behavior and avoid breaking changes. + 'CooperativeCancellation = true'를 명시적으로 설정하지 않고 '[Timeout]'을 사용하는 것은 권장되지 않습니다. 향후 버전에서는 협동 취소가 기본 동작으로 설정될 것입니다. 권장 동작을 선택하고 변경 사항으로 인한 문제를 피하려면 'CooperativeCancellation = true'를 설정하세요. Use 'CooperativeCancellation = true' with '[Timeout]' to enable cooperative cancellation behavior - Use 'CooperativeCancellation = true' with '[Timeout]' to enable cooperative cancellation behavior + '[Timeout]'와 함께 'CooperativeCancellation = true'를 사용하여 협동 취소 동작을 활성화하세요. Use 'CooperativeCancellation = true' with '[Timeout]' - Use 'CooperativeCancellation = true' with '[Timeout]' + '[Timeout]'와 함께 'CooperativeCancellation = true'를 사용하세요. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf index 14f9189e78..561d662746 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf @@ -791,17 +791,17 @@ Typ deklarujący te metody powinien również przestrzegać następujących regu Using '[Timeout]' without explicitly setting 'CooperativeCancellation = true' is discouraged. In a future version, cooperative cancellation will become the default behavior. Set 'CooperativeCancellation = true' to opt into the recommended behavior and avoid breaking changes. - Using '[Timeout]' without explicitly setting 'CooperativeCancellation = true' is discouraged. In a future version, cooperative cancellation will become the default behavior. Set 'CooperativeCancellation = true' to opt into the recommended behavior and avoid breaking changes. + Nie rekomenduje się używania elementu „[Timeout]” bez jawnego ustawiania wartości „CooperativeCancellation = true”. W przyszłej wersji anulowanie trybu współpracy będzie zachowaniem domyślnym. Ustaw opcję „CooperativeCancellation = true”, aby włączyć rekomendowane zachowanie i uniknąć zmian powodujących niezgodność. Use 'CooperativeCancellation = true' with '[Timeout]' to enable cooperative cancellation behavior - Use 'CooperativeCancellation = true' with '[Timeout]' to enable cooperative cancellation behavior + Użyj opcji „CooperativeCancellation = true” z limitem czasu „[Timeout]”, aby włączyć zachowanie anulowania trybu współpracy Use 'CooperativeCancellation = true' with '[Timeout]' - Use 'CooperativeCancellation = true' with '[Timeout]' + Użyj opcji „CooperativeCancellation = true” w limitem czasu „[Timeout]” diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf index 563fd9b73b..3ae1e7736c 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf @@ -791,17 +791,17 @@ O tipo que declara esses métodos também deve respeitar as seguintes regras: Using '[Timeout]' without explicitly setting 'CooperativeCancellation = true' is discouraged. In a future version, cooperative cancellation will become the default behavior. Set 'CooperativeCancellation = true' to opt into the recommended behavior and avoid breaking changes. - Using '[Timeout]' without explicitly setting 'CooperativeCancellation = true' is discouraged. In a future version, cooperative cancellation will become the default behavior. Set 'CooperativeCancellation = true' to opt into the recommended behavior and avoid breaking changes. + Usar '\[Timeout]' sem definir explicitamente 'CooperativeCancellation = true' não é recomendado. Em uma versão futura, o cancelamento cooperativo se tornará o comportamento padrão. Defina 'CooperativeCancellation = true' para optar pelo comportamento recomendado e evitar quebras. Use 'CooperativeCancellation = true' with '[Timeout]' to enable cooperative cancellation behavior - Use 'CooperativeCancellation = true' with '[Timeout]' to enable cooperative cancellation behavior + Use 'CooperativeCancellation = true' com '\[Timeout]' para habilitar o comportamento de cancelamento cooperativo Use 'CooperativeCancellation = true' with '[Timeout]' - Use 'CooperativeCancellation = true' with '[Timeout]' + Use 'CooperativeCancellation = true' com '\[Timeout]' diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf index c2af3aefb0..e579f7a193 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf @@ -793,17 +793,17 @@ Bu yöntemleri bildiren tipin ayrıca aşağıdaki kurallara uyması gerekir: Using '[Timeout]' without explicitly setting 'CooperativeCancellation = true' is discouraged. In a future version, cooperative cancellation will become the default behavior. Set 'CooperativeCancellation = true' to opt into the recommended behavior and avoid breaking changes. - Using '[Timeout]' without explicitly setting 'CooperativeCancellation = true' is discouraged. In a future version, cooperative cancellation will become the default behavior. Set 'CooperativeCancellation = true' to opt into the recommended behavior and avoid breaking changes. + '[Timeout]' ayarını 'CooperativeCancellation = true' olarak açıkça ayarlamadan kullanmak önerilmez. Gelecek bir sürümde, birlikte iptal etme varsayılan davranış haline gelecektir. Önerilen davranışı kabul etmek ve uyumsuzlukları önlemek için 'CooperativeCancellation = true' değerini ayarlayın. Use 'CooperativeCancellation = true' with '[Timeout]' to enable cooperative cancellation behavior - Use 'CooperativeCancellation = true' with '[Timeout]' to enable cooperative cancellation behavior + '[Timeout]' ile 'CooperativeCancellation = true' kullanarak birlikte iptal etme davranışını etkinleştirin Use 'CooperativeCancellation = true' with '[Timeout]' - Use 'CooperativeCancellation = true' with '[Timeout]' + '[Timeout]' ile 'CooperativeCancellation = true' kullanın diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf index 61075a0c1d..a57538a4df 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf @@ -791,17 +791,17 @@ The type declaring these methods should also respect the following rules: Using '[Timeout]' without explicitly setting 'CooperativeCancellation = true' is discouraged. In a future version, cooperative cancellation will become the default behavior. Set 'CooperativeCancellation = true' to opt into the recommended behavior and avoid breaking changes. - Using '[Timeout]' without explicitly setting 'CooperativeCancellation = true' is discouraged. In a future version, cooperative cancellation will become the default behavior. Set 'CooperativeCancellation = true' to opt into the recommended behavior and avoid breaking changes. + 不建议在不显式设置 'CooperativeCancellation = true' 的情况下使用 '[Timeout]'。在将来的版本中,协作取消将成为默认行为。设置 'CooperativeCancellation = true' 以选择加入建议的行为,并避免中断性变更。 Use 'CooperativeCancellation = true' with '[Timeout]' to enable cooperative cancellation behavior - Use 'CooperativeCancellation = true' with '[Timeout]' to enable cooperative cancellation behavior + 将 'CooperativeCancellation = true' 与 '[Timeout]' 配合使用以启用协作取消行为 Use 'CooperativeCancellation = true' with '[Timeout]' - Use 'CooperativeCancellation = true' with '[Timeout]' + 将 'CooperativeCancellation = true' 与 '[Timeout]' 配合使用 From 7e7ce6bcefda8980e60f8812a78131dae3836200 Mon Sep 17 00:00:00 2001 From: dotnet bot Date: Mon, 7 Jul 2025 16:46:06 +0200 Subject: [PATCH 168/541] Localized file check-in by OneLocBuild Task: Build definition ID 1218: Build ID 2744317 --- .../Resources/xlf/FrameworkMessages.cs.xlf | 46 +++++++++---------- .../Resources/xlf/FrameworkMessages.de.xlf | 46 +++++++++---------- .../Resources/xlf/FrameworkMessages.es.xlf | 46 +++++++++---------- .../Resources/xlf/FrameworkMessages.fr.xlf | 46 +++++++++---------- .../Resources/xlf/FrameworkMessages.it.xlf | 46 +++++++++---------- .../Resources/xlf/FrameworkMessages.ja.xlf | 46 +++++++++---------- .../Resources/xlf/FrameworkMessages.ko.xlf | 46 +++++++++---------- .../Resources/xlf/FrameworkMessages.pl.xlf | 46 +++++++++---------- .../Resources/xlf/FrameworkMessages.pt-BR.xlf | 46 +++++++++---------- .../Resources/xlf/FrameworkMessages.tr.xlf | 46 +++++++++---------- .../xlf/FrameworkMessages.zh-Hans.xlf | 46 +++++++++---------- .../xlf/FrameworkMessages.zh-Hant.xlf | 46 +++++++++---------- 12 files changed, 276 insertions(+), 276 deletions(-) diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.cs.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.cs.xlf index 4f8d7b5eaf..6061aab620 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.cs.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.cs.xlf @@ -84,22 +84,22 @@ Expected collection to contain the specified item. {0} - Expected collection to contain the specified item. {0} + Očekávala se kolekce, která bude obsahovat zadanou položku. {0} Expected at least one item to match the predicate. {0} - Expected at least one item to match the predicate. {0} + Očekávala se alespoň jedna položka odpovídající predikátu. {0} Expected collection to contain exactly one element but found {1} element(s). {0} - Expected collection to contain exactly one element but found {1} element(s). {0} + Očekávalo se, že kolekce bude obsahovat přesně jeden prvek, ale našlo se tolik elementů: {1}. {0} Expected exactly one item to match the predicate but found {1} item(s). {0} - Expected exactly one item to match the predicate but found {1} item(s). {0} + Očekávala se přesně jedna položka odpovídající predikátu, ale našlo se tolik položek: {1}. {0} @@ -109,22 +109,22 @@ Expected collection to not contain the specified item. {0} - Expected collection to not contain the specified item. {0} + Očekávalo se, že kolekce nebude obsahovat zadanou položku. {0} Expected no items to match the predicate. {0} - Expected no items to match the predicate. {0} + Očekávaly se žádné položky, které by odpovídaly predikátu. {0} String '{0}' ends with string '{1}'. {2} - String '{0}' ends with string '{1}'. {2} + Řetězec „{0}“ končí řetězcem „{1}“. {2} String '{0}' starts with string '{1}'. {2} - String '{0}' starts with string '{1}'. {2} + Řetězec „{0}“ začíná řetězcem „{1}“. {2} @@ -163,7 +163,7 @@ Skutečnost: {2} String '{0}' does not end with string '{1}'. {2} - String '{0}' does not end with string '{1}'. {2} + Řetězec „{0}“ nekončí řetězcem „{1}“. {2} @@ -193,7 +193,7 @@ Skutečnost: {2} String '{0}' does not match pattern '{1}'. {2} - String '{0}' does not match pattern '{1}'. {2} + Řetězec „{0}“ neodpovídá vzoru „{1}“. {2} @@ -208,7 +208,7 @@ Skutečnost: {2} String '{0}' matches pattern '{1}'. {2} - String '{0}' matches pattern '{1}'. {2} + Řetězec „{0}“ odpovídá vzoru „{1}“. {2} @@ -249,7 +249,7 @@ Skutečnost: {2} String '{0}' does not start with string '{1}'. {2} - String '{0}' does not start with string '{1}'. {2} + Řetězec „{0}“ nezačíná řetězcem „{1}“. {2} @@ -352,32 +352,32 @@ Skutečnost: {2} Actual value <{2}> is not greater than expected value <{1}>. {0} - Actual value <{2}> is not greater than expected value <{1}>. {0} + Skutečná hodnota <{2}> není větší než očekávaná hodnota <{1}>. {0} Actual value <{2}> is not greater than or equal to expected value <{1}>. {0} - Actual value <{2}> is not greater than or equal to expected value <{1}>. {0} + Skutečná hodnota <{2}> není větší nebo rovna očekávané hodnotě <{1}>. {0} Actual value <{2}> is not less than expected value <{1}>. {0} - Actual value <{2}> is not less than expected value <{1}>. {0} + Skutečná hodnota <{2}> není menší než očekávaná hodnota <{1}>. {0} Actual value <{2}> is not less than or equal to expected value <{1}>. {0} - Actual value <{2}> is not less than or equal to expected value <{1}>. {0} + Skutečná hodnota <{2}> není menší nebo rovna očekávané hodnotě <{1}>. {0} Expected value <{1}> to be positive. {0} - Expected value <{1}> to be positive. {0} + Očekávaná hodnota <{1}> má být kladná. {0} Expected value <{1}> to be negative. {0} - Expected value <{1}> to be negative. {0} + Očekávaná hodnota <{1}> má být záporná. {0} @@ -387,27 +387,27 @@ Skutečnost: {2} Assert.ReferenceEquals should not be used for Assertions. Please use Assert.AreSame & overloads instead. - Assert.ReferenceEquals should not be used for Assertions. Please use Assert.AreSame & overloads instead. + Assert.ReferenceEquals se nemá používat pro kontrolní výrazy. Použijte prosím místo toho Assert.AreEqual & overloads. StringAssert.Equals should not be used for Assertions. Please use StringAssert methods or Assert.AreEqual & overloads instead. - StringAssert.Equals should not be used for Assertions. Please use StringAssert methods or Assert.AreEqual & overloads instead. + StringAssert.Equals se nemá používat pro kontrolní výrazy. Místo toho použijte metody StringAssert nebo Assert.AreEqual & overloads. StringAssert.ReferenceEquals should not be used for Assertions. Please use StringAssert methods or Assert.AreSame & overloads instead. - StringAssert.ReferenceEquals should not be used for Assertions. Please use StringAssert methods or Assert.AreSame & overloads instead. + StringAssert.ReferenceEquals se nemá používat pro kontrolní výrazy. Místo toho použijte metody StringAssert nebo Assert.AreSame & overloads. CollectionAssert.Equals should not be used for Assertions. Please use CollectionAssert.AreEqual & overloads instead. - CollectionAssert.Equals should not be used for Assertions. Please use CollectionAssert.AreEqual & overloads instead. + CollectionAssert.Equals se nemá používat pro kontrolní výrazy. Místo toho použijte CollectionAssert.AreEqual & overloads. CollectionAssert.ReferenceEquals should not be used for Assertions. Please use CollectionAssert methods or Assert.AreSame & overloads instead. - CollectionAssert.ReferenceEquals should not be used for Assertions. Please use CollectionAssert methods or Assert.AreSame & overloads instead. + CollectionAssert.ReferenceEquals se nemá používat pro kontrolní výrazy. Místo toho použijte metody CollectionAssert nebo Assert.AreSame & overloads. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.de.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.de.xlf index 4a3af78cc1..a3b2e5236b 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.de.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.de.xlf @@ -84,22 +84,22 @@ Expected collection to contain the specified item. {0} - Expected collection to contain the specified item. {0} + Es wurde erwartet, dass die Sammlung das angegebene Element enthält. {0} Expected at least one item to match the predicate. {0} - Expected at least one item to match the predicate. {0} + Es wurde erwartet, dass mindestens ein Element mit dem Prädikat übereinstimmt. {0} Expected collection to contain exactly one element but found {1} element(s). {0} - Expected collection to contain exactly one element but found {1} element(s). {0} + Es wurde erwartet, dass die Sammlung genau ein Element enthält, es wurden jedoch {1} gefunden. {0} Expected exactly one item to match the predicate but found {1} item(s). {0} - Expected exactly one item to match the predicate but found {1} item(s). {0} + Es wurde erwartet, dass genau ein Element mit dem Prädikat übereinstimmt, es wurden jedoch {1} Element(e) gefunden. {0} @@ -109,22 +109,22 @@ Expected collection to not contain the specified item. {0} - Expected collection to not contain the specified item. {0} + Es wurde erwartet, dass die Sammlung das angegebene Element nicht enthält. {0} Expected no items to match the predicate. {0} - Expected no items to match the predicate. {0} + Es wurden erwartet, dass keine Elemente mit dem Prädikat übereinstimmen. {0} String '{0}' ends with string '{1}'. {2} - String '{0}' ends with string '{1}'. {2} + Die Zeichenfolge „{0}“ endet mit der Zeichenfolge „{1}“. {2} String '{0}' starts with string '{1}'. {2} - String '{0}' starts with string '{1}'. {2} + Die Zeichenfolge „{0}“ beginnt mit der Zeichenfolge „{1}“. {2} @@ -163,7 +163,7 @@ Tatsächlich: {2} String '{0}' does not end with string '{1}'. {2} - String '{0}' does not end with string '{1}'. {2} + Die Zeichenfolge „{0}“ endet nicht auf die Zeichenfolge „{1}“. {2} @@ -193,7 +193,7 @@ Tatsächlich: {2} String '{0}' does not match pattern '{1}'. {2} - String '{0}' does not match pattern '{1}'. {2} + Die Zeichenfolge „{0}“ stimmt nicht mit dem Muster „{1}“ überein. {2} @@ -208,7 +208,7 @@ Tatsächlich: {2} String '{0}' matches pattern '{1}'. {2} - String '{0}' matches pattern '{1}'. {2} + Die Zeichenfolge „{0}“ stimmt mit dem Muster „{1}“ überein. {2} @@ -249,7 +249,7 @@ Tatsächlich: {2} String '{0}' does not start with string '{1}'. {2} - String '{0}' does not start with string '{1}'. {2} + Die Zeichenfolge „{0}“ beginnt nicht mit der Zeichenfolge „{1}“. {2} @@ -352,32 +352,32 @@ Tatsächlich: {2} Actual value <{2}> is not greater than expected value <{1}>. {0} - Actual value <{2}> is not greater than expected value <{1}>. {0} + Der tatsächliche Wert <{2}> ist nicht größer als der erwartete Wert <{1}>. {0} Actual value <{2}> is not greater than or equal to expected value <{1}>. {0} - Actual value <{2}> is not greater than or equal to expected value <{1}>. {0} + Der tatsächliche Wert <{2}> ist nicht größer oder gleich dem erwarteten Wert <{1}>. {0} Actual value <{2}> is not less than expected value <{1}>. {0} - Actual value <{2}> is not less than expected value <{1}>. {0} + Der tatsächliche Wert <{2}> ist nicht kleiner als der erwartete Wert <{1}>. {0} Actual value <{2}> is not less than or equal to expected value <{1}>. {0} - Actual value <{2}> is not less than or equal to expected value <{1}>. {0} + Der tatsächliche Wert <{2}> ist nicht kleiner oder gleich dem erwarteten Wert <{1}>. {0} Expected value <{1}> to be positive. {0} - Expected value <{1}> to be positive. {0} + Es wurde erwartet, dass der Wert <{1}> positiv ist. {0} Expected value <{1}> to be negative. {0} - Expected value <{1}> to be negative. {0} + Es wurde erwartet, dass der Wert <{1}> negativ ist. {0} @@ -387,27 +387,27 @@ Tatsächlich: {2} Assert.ReferenceEquals should not be used for Assertions. Please use Assert.AreSame & overloads instead. - Assert.ReferenceEquals should not be used for Assertions. Please use Assert.AreSame & overloads instead. + Assert.ReferenceEquals sollte nicht für Assertions verwendet werden. Verwenden Sie stattdessen Assert.AreSame und Überladungen. StringAssert.Equals should not be used for Assertions. Please use StringAssert methods or Assert.AreEqual & overloads instead. - StringAssert.Equals should not be used for Assertions. Please use StringAssert methods or Assert.AreEqual & overloads instead. + StringAssert.Equals sollte nicht für Assertions verwendet werden. Verwenden Sie stattdessen StringAssert-Methoden oder Assert.AreEqual und Überladungen. StringAssert.ReferenceEquals should not be used for Assertions. Please use StringAssert methods or Assert.AreSame & overloads instead. - StringAssert.ReferenceEquals should not be used for Assertions. Please use StringAssert methods or Assert.AreSame & overloads instead. + StringAssert.ReferenceEquals darf nicht für Assertions verwendet werden. Verwenden Sie stattdessen StringAssert-Methoden oder Assert.AreSame und Überladungen. CollectionAssert.Equals should not be used for Assertions. Please use CollectionAssert.AreEqual & overloads instead. - CollectionAssert.Equals should not be used for Assertions. Please use CollectionAssert.AreEqual & overloads instead. + CollectionAssert.Equals sollte nicht für Assertions verwendet werden. Verwenden Sie stattdessen CollectionAssert.AreEqual und Überladungen. CollectionAssert.ReferenceEquals should not be used for Assertions. Please use CollectionAssert methods or Assert.AreSame & overloads instead. - CollectionAssert.ReferenceEquals should not be used for Assertions. Please use CollectionAssert methods or Assert.AreSame & overloads instead. + CollectionAssert.ReferenceEquals darf nicht für Assertions verwendet werden. Verwenden Sie stattdessen CollectionAssert-Methoden oder Assert.AreSame und Überladungen. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.es.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.es.xlf index a93c90cd17..ffe46db07b 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.es.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.es.xlf @@ -84,22 +84,22 @@ Expected collection to contain the specified item. {0} - Expected collection to contain the specified item. {0} + Se esperaba que la colección contuviera el elemento especificado. {0} Expected at least one item to match the predicate. {0} - Expected at least one item to match the predicate. {0} + Se esperaba al menos un elemento para que coincida con el predicado. {0} Expected collection to contain exactly one element but found {1} element(s). {0} - Expected collection to contain exactly one element but found {1} element(s). {0} + Se esperaba que la colección contuviera exactamente un elemento, pero se encontraron {1} elementos. {0} Expected exactly one item to match the predicate but found {1} item(s). {0} - Expected exactly one item to match the predicate but found {1} item(s). {0} + Se esperaba exactamente un elemento para que coincida con el predicado, pero se encontraron {1} elementos. {0} @@ -109,22 +109,22 @@ Expected collection to not contain the specified item. {0} - Expected collection to not contain the specified item. {0} + Se esperaba que la colección no contenga el elemento especificado. {0} Expected no items to match the predicate. {0} - Expected no items to match the predicate. {0} + No se esperaba que ningún elemento coincidía con el predicado. {0} String '{0}' ends with string '{1}'. {2} - String '{0}' ends with string '{1}'. {2} + La cadena "{0}" termina con la cadena "{1}". {2} String '{0}' starts with string '{1}'. {2} - String '{0}' starts with string '{1}'. {2} + La cadena "{0}" comienza con la cadena "{1}". {2} @@ -163,7 +163,7 @@ Real: {2} String '{0}' does not end with string '{1}'. {2} - String '{0}' does not end with string '{1}'. {2} + La cadena "{0}" no termina con la cadena "{1}". {2} @@ -193,7 +193,7 @@ Real: {2} String '{0}' does not match pattern '{1}'. {2} - String '{0}' does not match pattern '{1}'. {2} + La cadena "{0}" no coincide con el patrón "{1}". {2} @@ -208,7 +208,7 @@ Real: {2} String '{0}' matches pattern '{1}'. {2} - String '{0}' matches pattern '{1}'. {2} + La cadena "{0}" coincide con el patrón "{1}". {2} @@ -249,7 +249,7 @@ Real: {2} String '{0}' does not start with string '{1}'. {2} - String '{0}' does not start with string '{1}'. {2} + La cadena "{0}" no empieza con la cadena "{1}". {2} @@ -352,32 +352,32 @@ Real: {2} Actual value <{2}> is not greater than expected value <{1}>. {0} - Actual value <{2}> is not greater than expected value <{1}>. {0} + El valor real <{2}> no es mayor que el valor esperado <{1}>. {0} Actual value <{2}> is not greater than or equal to expected value <{1}>. {0} - Actual value <{2}> is not greater than or equal to expected value <{1}>. {0} + El valor real <{2}> no es mayor o igual que el valor esperado <{1}>. {0} Actual value <{2}> is not less than expected value <{1}>. {0} - Actual value <{2}> is not less than expected value <{1}>. {0} + El valor real <{2}> no es menor que el valor esperado <{1}>. {0} Actual value <{2}> is not less than or equal to expected value <{1}>. {0} - Actual value <{2}> is not less than or equal to expected value <{1}>. {0} + El valor real <{2}> no es menor o igual que el valor esperado <{1}>. {0} Expected value <{1}> to be positive. {0} - Expected value <{1}> to be positive. {0} + Se esperaba que el valor <{1}> ser positivo. {0} Expected value <{1}> to be negative. {0} - Expected value <{1}> to be negative. {0} + Se esperaba que el valor <{1}> ser negativo. {0} @@ -387,27 +387,27 @@ Real: {2} Assert.ReferenceEquals should not be used for Assertions. Please use Assert.AreSame & overloads instead. - Assert.ReferenceEquals should not be used for Assertions. Please use Assert.AreSame & overloads instead. + Assert.ReferenceEquals no se debe usar para las aserciones. Use Assert.AreSame & sobrecargas en su lugar. StringAssert.Equals should not be used for Assertions. Please use StringAssert methods or Assert.AreEqual & overloads instead. - StringAssert.Equals should not be used for Assertions. Please use StringAssert methods or Assert.AreEqual & overloads instead. + StringAssert.Equals no se debe usar para las aserciones. Use los métodos StringAssert o las sobrecargas Assert.AreEqual & en su lugar. StringAssert.ReferenceEquals should not be used for Assertions. Please use StringAssert methods or Assert.AreSame & overloads instead. - StringAssert.ReferenceEquals should not be used for Assertions. Please use StringAssert methods or Assert.AreSame & overloads instead. + StringAssert.ReferenceEquals no se debe usar para las aserciones. Use los métodos StringAssert o las sobrecargas Assert.AreSame & en su lugar. CollectionAssert.Equals should not be used for Assertions. Please use CollectionAssert.AreEqual & overloads instead. - CollectionAssert.Equals should not be used for Assertions. Please use CollectionAssert.AreEqual & overloads instead. + CollectionAssert.Equals no se debe usar para las aserciones. Use CollectionAssert.AreEqual y sobrecargas en su lugar. CollectionAssert.ReferenceEquals should not be used for Assertions. Please use CollectionAssert methods or Assert.AreSame & overloads instead. - CollectionAssert.ReferenceEquals should not be used for Assertions. Please use CollectionAssert methods or Assert.AreSame & overloads instead. + CollectionAssert.ReferenceEquals no se debe usar para las aserciones. Use los métodos CollectionAssert o las sobrecargas Assert.AreSame & en su lugar. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.fr.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.fr.xlf index b5688b3969..f92dade652 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.fr.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.fr.xlf @@ -84,22 +84,22 @@ Expected collection to contain the specified item. {0} - Expected collection to contain the specified item. {0} + Collection attendue pour contenir l’élément spécifié. {0} Expected at least one item to match the predicate. {0} - Expected at least one item to match the predicate. {0} + Au moins un élément doit correspondre au prédicat. {0} Expected collection to contain exactly one element but found {1} element(s). {0} - Expected collection to contain exactly one element but found {1} element(s). {0} + Collection attendue pour contenir exactement un élément mais {1} élément(s) trouvé(s). {0} Expected exactly one item to match the predicate but found {1} item(s). {0} - Expected exactly one item to match the predicate but found {1} item(s). {0} + Un seul élément était attendu pour correspondre au prédicat, mais {1} élément(s) trouvé(s). {0} @@ -109,22 +109,22 @@ Expected collection to not contain the specified item. {0} - Expected collection to not contain the specified item. {0} + Collection attendue pour ne pas contenir l’élément spécifié. {0} Expected no items to match the predicate. {0} - Expected no items to match the predicate. {0} + Aucun élément ne doit correspondre au prédicat. {0} String '{0}' ends with string '{1}'. {2} - String '{0}' ends with string '{1}'. {2} + La chaîne '{0}' se termine par la chaîne '{1}'. {2} String '{0}' starts with string '{1}'. {2} - String '{0}' starts with string '{1}'. {2} + La chaîne '{0}' commence par la chaîne '{1}'. {2} @@ -163,7 +163,7 @@ Réel : {2} String '{0}' does not end with string '{1}'. {2} - String '{0}' does not end with string '{1}'. {2} + La chaîne '{0}' ne se termine pas par la chaîne '{1}'. {2} @@ -193,7 +193,7 @@ Réel : {2} String '{0}' does not match pattern '{1}'. {2} - String '{0}' does not match pattern '{1}'. {2} + La chaîne '{0}' ne correspond pas au modèle '{1}'. {2} @@ -208,7 +208,7 @@ Réel : {2} String '{0}' matches pattern '{1}'. {2} - String '{0}' matches pattern '{1}'. {2} + La chaîne '{0}' correspond au modèle '{1}'. {2} @@ -249,7 +249,7 @@ Réel : {2} String '{0}' does not start with string '{1}'. {2} - String '{0}' does not start with string '{1}'. {2} + La chaîne '{0}' ne commence pas par la chaîne '{1}'. {2} @@ -352,32 +352,32 @@ Réel : {2} Actual value <{2}> is not greater than expected value <{1}>. {0} - Actual value <{2}> is not greater than expected value <{1}>. {0} + La valeur réelle <{2}> n’est pas supérieure à la valeur attendue <{1}>. {0} Actual value <{2}> is not greater than or equal to expected value <{1}>. {0} - Actual value <{2}> is not greater than or equal to expected value <{1}>. {0} + La valeur réelle <{2}> n’est pas supérieure ou égale à la valeur attendue <{1}>. {0} Actual value <{2}> is not less than expected value <{1}>. {0} - Actual value <{2}> is not less than expected value <{1}>. {0} + La valeur réelle <{2}> n’est pas inférieure à la valeur attendue <{1}>. {0} Actual value <{2}> is not less than or equal to expected value <{1}>. {0} - Actual value <{2}> is not less than or equal to expected value <{1}>. {0} + La valeur réelle <{2}> n’est pas inférieure ou égale à la valeur attendue <{1}>. {0} Expected value <{1}> to be positive. {0} - Expected value <{1}> to be positive. {0} + La valeur attendue <{1}> doit être positive. {0} Expected value <{1}> to be negative. {0} - Expected value <{1}> to be negative. {0} + La valeur attendue <{1}> doit être négative. {0} @@ -387,27 +387,27 @@ Réel : {2} Assert.ReferenceEquals should not be used for Assertions. Please use Assert.AreSame & overloads instead. - Assert.ReferenceEquals should not be used for Assertions. Please use Assert.AreSame & overloads instead. + Assert.ReferenceEquals ne doit pas être utilisé pour les assertions. Utilisez Assert.AreEqual & overloads à la place. StringAssert.Equals should not be used for Assertions. Please use StringAssert methods or Assert.AreEqual & overloads instead. - StringAssert.Equals should not be used for Assertions. Please use StringAssert methods or Assert.AreEqual & overloads instead. + StringAssert.Equals ne doit pas être utilisé pour les assertions. Utilisez plutôt les méthodes StringAssert ou Assert.AreEqual & overloads. StringAssert.ReferenceEquals should not be used for Assertions. Please use StringAssert methods or Assert.AreSame & overloads instead. - StringAssert.ReferenceEquals should not be used for Assertions. Please use StringAssert methods or Assert.AreSame & overloads instead. + StringAssert.ReferenceEquals ne doit pas être utilisé pour les assertions. Utilisez plutôt les méthodes StringAssert ou Assert.AreSame & overloads. CollectionAssert.Equals should not be used for Assertions. Please use CollectionAssert.AreEqual & overloads instead. - CollectionAssert.Equals should not be used for Assertions. Please use CollectionAssert.AreEqual & overloads instead. + Assert.Equals ne doit pas être utilisé pour les assertions. Utilisez plutôt CollectionAssert.AreEqual & overloads. CollectionAssert.ReferenceEquals should not be used for Assertions. Please use CollectionAssert methods or Assert.AreSame & overloads instead. - CollectionAssert.ReferenceEquals should not be used for Assertions. Please use CollectionAssert methods or Assert.AreSame & overloads instead. + CollectionAssert.ReferenceEquals ne doit pas être utilisé pour les assertions. Utilisez plutôt les méthodes CollectionAssert ou Assert.AreSame & overloads. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.it.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.it.xlf index 920db09a6c..6b7c97798d 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.it.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.it.xlf @@ -84,22 +84,22 @@ Expected collection to contain the specified item. {0} - Expected collection to contain the specified item. {0} + La raccolta dovrebbe contenere l'elemento specificato. {0} Expected at least one item to match the predicate. {0} - Expected at least one item to match the predicate. {0} + Almeno un elemento dovrebbe corrispondere al predicato. {0} Expected collection to contain exactly one element but found {1} element(s). {0} - Expected collection to contain exactly one element but found {1} element(s). {0} + La raccolta dovrebbe contenere un unico elemento, ma ne sono stati trovati {1}. {0} Expected exactly one item to match the predicate but found {1} item(s). {0} - Expected exactly one item to match the predicate but found {1} item(s). {0} + Un unico elemento dovrebbe corrispondere al predicato, ma ne sono stati trovati {1}. {0} @@ -109,22 +109,22 @@ Expected collection to not contain the specified item. {0} - Expected collection to not contain the specified item. {0} + La raccolta non dovrebbe contenere l'elemento specificato. {0} Expected no items to match the predicate. {0} - Expected no items to match the predicate. {0} + Nessun elemento dovrebbe corrispondere al predicato. {0} String '{0}' ends with string '{1}'. {2} - String '{0}' ends with string '{1}'. {2} + La stringa '{0}' termina con la stringa '{1}'. {2} String '{0}' starts with string '{1}'. {2} - String '{0}' starts with string '{1}'. {2} + La stringa '{0}' inizia con la stringa '{1}'. {2} @@ -163,7 +163,7 @@ Effettivo: {2} String '{0}' does not end with string '{1}'. {2} - String '{0}' does not end with string '{1}'. {2} + La stringa '{0}' non termina con la stringa '{1}'. {2} @@ -193,7 +193,7 @@ Effettivo: {2} String '{0}' does not match pattern '{1}'. {2} - String '{0}' does not match pattern '{1}'. {2} + La stringa '{0}' non corrisponde al criterio '{1}'. {2} @@ -208,7 +208,7 @@ Effettivo: {2} String '{0}' matches pattern '{1}'. {2} - String '{0}' matches pattern '{1}'. {2} + La stringa '{0}' corrisponde al criterio '{1}'. {2} @@ -249,7 +249,7 @@ Effettivo: {2} String '{0}' does not start with string '{1}'. {2} - String '{0}' does not start with string '{1}'. {2} + La stringa '{0}' non inizia con la stringa '{1}'. {2} @@ -352,32 +352,32 @@ Effettivo: {2} Actual value <{2}> is not greater than expected value <{1}>. {0} - Actual value <{2}> is not greater than expected value <{1}>. {0} + Il valore effettivo <{2}> non è maggiore del valore previsto <{1}>. {0} Actual value <{2}> is not greater than or equal to expected value <{1}>. {0} - Actual value <{2}> is not greater than or equal to expected value <{1}>. {0} + Il valore effettivo <{2}> non è maggiore o uguale al valore previsto <{1}>. {0} Actual value <{2}> is not less than expected value <{1}>. {0} - Actual value <{2}> is not less than expected value <{1}>. {0} + Il valore effettivo <{2}> non è minore del valore previsto <{1}>. {0} Actual value <{2}> is not less than or equal to expected value <{1}>. {0} - Actual value <{2}> is not less than or equal to expected value <{1}>. {0} + Il valore effettivo <{2}> non è minore o uguale al valore previsto <{1}>. {0} Expected value <{1}> to be positive. {0} - Expected value <{1}> to be positive. {0} + Il valore <{1}{0}> dovrebbe essere positivo. Expected value <{1}> to be negative. {0} - Expected value <{1}> to be negative. {0} + Il valore <{1}{0}> dovrebbe essere negativo. @@ -387,27 +387,27 @@ Effettivo: {2} Assert.ReferenceEquals should not be used for Assertions. Please use Assert.AreSame & overloads instead. - Assert.ReferenceEquals should not be used for Assertions. Please use Assert.AreSame & overloads instead. + Non è possibile usare Assert.ReferenceEquals per le asserzioni. In alternativa, usare Assert.AreSame e gli overload. StringAssert.Equals should not be used for Assertions. Please use StringAssert methods or Assert.AreEqual & overloads instead. - StringAssert.Equals should not be used for Assertions. Please use StringAssert methods or Assert.AreEqual & overloads instead. + Non è possibile usare StringAssert.Equals per le asserzioni. In alternativa, usare i metodi StringAssert o Assert.AreEqual e gli overload. StringAssert.ReferenceEquals should not be used for Assertions. Please use StringAssert methods or Assert.AreSame & overloads instead. - StringAssert.ReferenceEquals should not be used for Assertions. Please use StringAssert methods or Assert.AreSame & overloads instead. + Non è possibile usare StringAssert.ReferenceEquals per le asserzioni. In alternativa, usare i metodi StringAssert o Assert.AreSame e gli overload. CollectionAssert.Equals should not be used for Assertions. Please use CollectionAssert.AreEqual & overloads instead. - CollectionAssert.Equals should not be used for Assertions. Please use CollectionAssert.AreEqual & overloads instead. + Non è possibile usare CollectionAssert.Equals per le asserzioni. In alternativa, usare CollectionAssert.AreEqual e gli overload. CollectionAssert.ReferenceEquals should not be used for Assertions. Please use CollectionAssert methods or Assert.AreSame & overloads instead. - CollectionAssert.ReferenceEquals should not be used for Assertions. Please use CollectionAssert methods or Assert.AreSame & overloads instead. + Non è possibile usare CollectionAssert.ReferenceEquals per le asserzioni. In alternativa, usare i metodi CollectionAssert o Assert.AreSame e gli overload. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ja.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ja.xlf index e3b48c305c..a2ff722169 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ja.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ja.xlf @@ -84,22 +84,22 @@ Expected collection to contain the specified item. {0} - Expected collection to contain the specified item. {0} + 指定された項目を含むコレクションが必要です。{0} Expected at least one item to match the predicate. {0} - Expected at least one item to match the predicate. {0} + 述語と一致する項目が少なくとも 1 つ必要です。{0} Expected collection to contain exactly one element but found {1} element(s). {0} - Expected collection to contain exactly one element but found {1} element(s). {0} + コレクションには 1 つの要素だけを含める必要がありますが、{1} 要素が見つかりました。{0} Expected exactly one item to match the predicate but found {1} item(s). {0} - Expected exactly one item to match the predicate but found {1} item(s). {0} + 述語と一致する項目が 1 つだけ必要ですが、{1} 項目が見つかりました。{0} @@ -109,22 +109,22 @@ Expected collection to not contain the specified item. {0} - Expected collection to not contain the specified item. {0} + 指定された項目を含まないコレクションが必要です。{0} Expected no items to match the predicate. {0} - Expected no items to match the predicate. {0} + 述語に一致する項目が必要ありません。{0} String '{0}' ends with string '{1}'. {2} - String '{0}' ends with string '{1}'. {2} + 文字列 '{0}' の末尾は文字列 '{1}' です。{2} String '{0}' starts with string '{1}'. {2} - String '{0}' starts with string '{1}'. {2} + 文字列 '{0}' は文字列 '{1}' で始まります。 {2} @@ -163,7 +163,7 @@ Actual: {2} String '{0}' does not end with string '{1}'. {2} - String '{0}' does not end with string '{1}'. {2} + 文字列 '{0}' は文字列 '{1}' で終わりません。{2} @@ -193,7 +193,7 @@ Actual: {2} String '{0}' does not match pattern '{1}'. {2} - String '{0}' does not match pattern '{1}'. {2} + 文字列 '{0}' はパターン '{1}' と一致しません。{2} @@ -208,7 +208,7 @@ Actual: {2} String '{0}' matches pattern '{1}'. {2} - String '{0}' matches pattern '{1}'. {2} + 文字列 '{0}' はパターン '{1}' と一致します。{2} @@ -249,7 +249,7 @@ Actual: {2} String '{0}' does not start with string '{1}'. {2} - String '{0}' does not start with string '{1}'. {2} + 文字列 '{0}' は文字列 '{1}' で始まりません。{2} @@ -352,32 +352,32 @@ Actual: {2} Actual value <{2}> is not greater than expected value <{1}>. {0} - Actual value <{2}> is not greater than expected value <{1}>. {0} + 実際の値 <{2}> は、予期された値 <{1}> より大きくありません。{0} Actual value <{2}> is not greater than or equal to expected value <{1}>. {0} - Actual value <{2}> is not greater than or equal to expected value <{1}>. {0} + 実際の値 <{2}> は、予期された値 <{1}> 以上ではありません。{0} Actual value <{2}> is not less than expected value <{1}>. {0} - Actual value <{2}> is not less than expected value <{1}>. {0} + 実際の値 <{2}> は、予期された値 <{1}> より小さくありません。{0} Actual value <{2}> is not less than or equal to expected value <{1}>. {0} - Actual value <{2}> is not less than or equal to expected value <{1}>. {0} + 実際の値 <{2}> は、予期された値 <{1}> 以下ではありません。{0} Expected value <{1}> to be positive. {0} - Expected value <{1}> to be positive. {0} + 正の値 <{1}> が必要です。{0} Expected value <{1}> to be negative. {0} - Expected value <{1}> to be negative. {0} + 負の値 <{1}> が必要です。{0} @@ -387,27 +387,27 @@ Actual: {2} Assert.ReferenceEquals should not be used for Assertions. Please use Assert.AreSame & overloads instead. - Assert.ReferenceEquals should not be used for Assertions. Please use Assert.AreSame & overloads instead. + アサーションには Assert.ReferenceEquals を使用しないでください。Assert.AreSame およびオーバーロードを使用してください。 StringAssert.Equals should not be used for Assertions. Please use StringAssert methods or Assert.AreEqual & overloads instead. - StringAssert.Equals should not be used for Assertions. Please use StringAssert methods or Assert.AreEqual & overloads instead. + アサーションには StringAssert.Equals を使用しないでください。代わりに StringAssert メソッドまたは Assert.AreEqual およびオーバーロードを使用してください。 StringAssert.ReferenceEquals should not be used for Assertions. Please use StringAssert methods or Assert.AreSame & overloads instead. - StringAssert.ReferenceEquals should not be used for Assertions. Please use StringAssert methods or Assert.AreSame & overloads instead. + アサーションには StringAssert.ReferenceEquals を使用しないでください。代わりに StringAssert メソッドまたは Assert.AreSame およびオーバーロードを使用してください。 CollectionAssert.Equals should not be used for Assertions. Please use CollectionAssert.AreEqual & overloads instead. - CollectionAssert.Equals should not be used for Assertions. Please use CollectionAssert.AreEqual & overloads instead. + アサーションには CollectionAssert.Equals を使用しないでください。代わりに CollectionAssert.AreEqual およびオーバーロードを使用してください。 CollectionAssert.ReferenceEquals should not be used for Assertions. Please use CollectionAssert methods or Assert.AreSame & overloads instead. - CollectionAssert.ReferenceEquals should not be used for Assertions. Please use CollectionAssert methods or Assert.AreSame & overloads instead. + アサーションには CollectionAssert.ReferenceEquals を使用しないでください。代わりに CollectionAssert メソッドまたは Assert.AreSame およびオーバーロードを使用してください。 diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ko.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ko.xlf index 0ea1d92159..02189b3259 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ko.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ko.xlf @@ -84,22 +84,22 @@ Expected collection to contain the specified item. {0} - Expected collection to contain the specified item. {0} + 지정한 항목을 포함할 컬렉션이 필요합니다. {0} Expected at least one item to match the predicate. {0} - Expected at least one item to match the predicate. {0} + 조건자와 일치하는 항목이 하나 이상 필요합니다. {0} Expected collection to contain exactly one element but found {1} element(s). {0} - Expected collection to contain exactly one element but found {1} element(s). {0} + 정확히 하나의 요소를 포함할 컬렉션이 필요하지만 {1}개 요소가 발견되었습니다. {0} Expected exactly one item to match the predicate but found {1} item(s). {0} - Expected exactly one item to match the predicate but found {1} item(s). {0} + 조건자에 일치하는 항목이 하나만 필요하지만 {1}개 항목이 발견되었습니다. {0} @@ -109,22 +109,22 @@ Expected collection to not contain the specified item. {0} - Expected collection to not contain the specified item. {0} + 지정한 항목을 포함하지 않을 컬렉션이 필요합니다. {0} Expected no items to match the predicate. {0} - Expected no items to match the predicate. {0} + 조건자와 일치하는 항목이 필요하지 않습니다. {0} String '{0}' ends with string '{1}'. {2} - String '{0}' ends with string '{1}'. {2} + 문자열 '{0}'은 문자열 '{1}'(으)로 끝납니다. {2} String '{0}' starts with string '{1}'. {2} - String '{0}' starts with string '{1}'. {2} + 문자열 '{0}'은 문자열 '{1}'(으)로 시작합니다. {2} @@ -163,7 +163,7 @@ Actual: {2} String '{0}' does not end with string '{1}'. {2} - String '{0}' does not end with string '{1}'. {2} + '{0}' 문자열이 '{1}' 문자열로 끝나지 않습니다. {2} @@ -193,7 +193,7 @@ Actual: {2} String '{0}' does not match pattern '{1}'. {2} - String '{0}' does not match pattern '{1}'. {2} + '{0}' 문자열이 '{1}' 패턴과 일치하지 않습니다. {2} @@ -208,7 +208,7 @@ Actual: {2} String '{0}' matches pattern '{1}'. {2} - String '{0}' matches pattern '{1}'. {2} + '{0}' 문자열이 '{1}' 패턴과 일치합니다. {2} @@ -249,7 +249,7 @@ Actual: {2} String '{0}' does not start with string '{1}'. {2} - String '{0}' does not start with string '{1}'. {2} + '{0}' 문자열이 '{1}' 문자열로 시작되지 않습니다. {2} @@ -352,32 +352,32 @@ Actual: {2} Actual value <{2}> is not greater than expected value <{1}>. {0} - Actual value <{2}> is not greater than expected value <{1}>. {0} + 실제 값 <{2}>은(는)는 예상 값 <{1}>보다 크지 않습니다. {0} Actual value <{2}> is not greater than or equal to expected value <{1}>. {0} - Actual value <{2}> is not greater than or equal to expected value <{1}>. {0} + 실제 값 <{2}>은(는)는 예상 값 <{1}>보다 크거나 같지 않습니다. {0} Actual value <{2}> is not less than expected value <{1}>. {0} - Actual value <{2}> is not less than expected value <{1}>. {0} + 실제 값 <{2}>은(는)는 예상 값 <{1}>보다 작지 않습니다. {0} Actual value <{2}> is not less than or equal to expected value <{1}>. {0} - Actual value <{2}> is not less than or equal to expected value <{1}>. {0} + 실제 값 <{2}>은(는)는 예상 값 <{1}>보다 작거나 같지 않습니다. {0} Expected value <{1}> to be positive. {0} - Expected value <{1}> to be positive. {0} + 예상 값 <{1}>은(는) 양수일 것으로 예상합니다. {0} Expected value <{1}> to be negative. {0} - Expected value <{1}> to be negative. {0} + 예상 값 <{1}>은(는) 음수일 것으로 예상합니다. {0} @@ -387,27 +387,27 @@ Actual: {2} Assert.ReferenceEquals should not be used for Assertions. Please use Assert.AreSame & overloads instead. - Assert.ReferenceEquals should not be used for Assertions. Please use Assert.AreSame & overloads instead. + 어설션에 Assert.ReferenceEquals를 사용할 수 없습니다. 대신 Assert.AreSame 및 오버로드를 사용하세요. StringAssert.Equals should not be used for Assertions. Please use StringAssert methods or Assert.AreEqual & overloads instead. - StringAssert.Equals should not be used for Assertions. Please use StringAssert methods or Assert.AreEqual & overloads instead. + 어설션에 StringAssert.Equals를 사용할 수 없습니다. 대신 StringAssert 메서드 또는 Assert.AreEqual 및 오버로드를 사용하세요. StringAssert.ReferenceEquals should not be used for Assertions. Please use StringAssert methods or Assert.AreSame & overloads instead. - StringAssert.ReferenceEquals should not be used for Assertions. Please use StringAssert methods or Assert.AreSame & overloads instead. + StringAssert.ReferenceEquals는 Assertions에 사용할 수 없습니다. 대신 StringAssert 메서드 또는 Assert.AreSame 및 오버로드를 사용하세요. CollectionAssert.Equals should not be used for Assertions. Please use CollectionAssert.AreEqual & overloads instead. - CollectionAssert.Equals should not be used for Assertions. Please use CollectionAssert.AreEqual & overloads instead. + 어설션에 CollectionAssert.Equals를 사용할 수 없습니다. 대신 CollectionAssert.AreEqual 및 오버로드를 사용하세요. CollectionAssert.ReferenceEquals should not be used for Assertions. Please use CollectionAssert methods or Assert.AreSame & overloads instead. - CollectionAssert.ReferenceEquals should not be used for Assertions. Please use CollectionAssert methods or Assert.AreSame & overloads instead. + CollectionAssert.ReferenceEquals는 Assertions에 사용할 수 없습니다. 대신 CollectionAssert 메서드 또는 Assert.AreSame 및 오버로드를 사용하세요. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pl.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pl.xlf index c2547c031e..ed5702458b 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pl.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pl.xlf @@ -84,22 +84,22 @@ Expected collection to contain the specified item. {0} - Expected collection to contain the specified item. {0} + Oczekiwano, że kolekcja będzie zawierać określony element. {0} Expected at least one item to match the predicate. {0} - Expected at least one item to match the predicate. {0} + Oczekiwano co najmniej jednego elementu zgodnego z predykatem. {0} Expected collection to contain exactly one element but found {1} element(s). {0} - Expected collection to contain exactly one element but found {1} element(s). {0} + Oczekiwano, że kolekcja będzie zawierać dokładnie jeden element, ale znaleziono {1} elementów. {0} Expected exactly one item to match the predicate but found {1} item(s). {0} - Expected exactly one item to match the predicate but found {1} item(s). {0} + Oczekiwano dokładnie jednego elementu zgodnego z predykatem, ale znaleziono {1} elementów. {0} @@ -109,22 +109,22 @@ Expected collection to not contain the specified item. {0} - Expected collection to not contain the specified item. {0} + Oczekiwano, że kolekcja nie będzie zawierać określonego elementu. {0} Expected no items to match the predicate. {0} - Expected no items to match the predicate. {0} + Nie oczekiwano elementów zgodnych z predykatem. {0} String '{0}' ends with string '{1}'. {2} - String '{0}' ends with string '{1}'. {2} + Ciąg „{0}” kończy się ciągiem „{1}”. {2} String '{0}' starts with string '{1}'. {2} - String '{0}' starts with string '{1}'. {2} + Ciąg „{0}” rozpoczyna się od ciągu „{1}”. {2} @@ -163,7 +163,7 @@ Rzeczywiste: {2} String '{0}' does not end with string '{1}'. {2} - String '{0}' does not end with string '{1}'. {2} + Ciąg „{0}” nie kończy się ciągiem „{1}”. {2} @@ -193,7 +193,7 @@ Rzeczywiste: {2} String '{0}' does not match pattern '{1}'. {2} - String '{0}' does not match pattern '{1}'. {2} + Ciąg „{0}” nie jest zgodny ze wzorcem „{1}”. {2} @@ -208,7 +208,7 @@ Rzeczywiste: {2} String '{0}' matches pattern '{1}'. {2} - String '{0}' matches pattern '{1}'. {2} + Ciąg „{0}” jest zgodny ze wzorcem „{1}”. {2} @@ -249,7 +249,7 @@ Rzeczywiste: {2} String '{0}' does not start with string '{1}'. {2} - String '{0}' does not start with string '{1}'. {2} + Ciąg „{0}” nie rozpoczyna się od ciągu „{1}”. {2} @@ -352,32 +352,32 @@ Rzeczywiste: {2} Actual value <{2}> is not greater than expected value <{1}>. {0} - Actual value <{2}> is not greater than expected value <{1}>. {0} + Wartość rzeczywista <{2}> nie jest większa niż oczekiwana wartość <{1}>. {0} Actual value <{2}> is not greater than or equal to expected value <{1}>. {0} - Actual value <{2}> is not greater than or equal to expected value <{1}>. {0} + Wartość rzeczywista <{2}> nie jest większa lub równa oczekiwanej wartości <{1}>. {0} Actual value <{2}> is not less than expected value <{1}>. {0} - Actual value <{2}> is not less than expected value <{1}>. {0} + Wartość rzeczywista <{2}> nie jest mniejsza niż oczekiwana wartość <{1}>. {0} Actual value <{2}> is not less than or equal to expected value <{1}>. {0} - Actual value <{2}> is not less than or equal to expected value <{1}>. {0} + Wartość rzeczywista <{2}> nie jest mniejsza lub równa oczekiwanej wartości <{1}>. {0} Expected value <{1}> to be positive. {0} - Expected value <{1}> to be positive. {0} + Oczekiwana wartość <{1}> powinna być dodatnia. {0} Expected value <{1}> to be negative. {0} - Expected value <{1}> to be negative. {0} + Oczekiwana wartość <{1}> powinna być negatywna. {0} @@ -387,27 +387,27 @@ Rzeczywiste: {2} Assert.ReferenceEquals should not be used for Assertions. Please use Assert.AreSame & overloads instead. - Assert.ReferenceEquals should not be used for Assertions. Please use Assert.AreSame & overloads instead. + Element Assert.ReferenceEquals nie powinien być używany dla asercji. Zamiast tego użyj metody Assert.AreSame i przeciążeń. StringAssert.Equals should not be used for Assertions. Please use StringAssert methods or Assert.AreEqual & overloads instead. - StringAssert.Equals should not be used for Assertions. Please use StringAssert methods or Assert.AreEqual & overloads instead. + Element StringAssert.Equals nie powinien być używany dla asercji. Zamiast tego użyj metod StringAssert lub Assert.AreEqual i przeciążeń. StringAssert.ReferenceEquals should not be used for Assertions. Please use StringAssert methods or Assert.AreSame & overloads instead. - StringAssert.ReferenceEquals should not be used for Assertions. Please use StringAssert methods or Assert.AreSame & overloads instead. + Element StringAssert.ReferenceEquals nie powinien być używany dla asercji. Zamiast tego użyj metod StringAssert lub Assert.AreSame i obciążeń. CollectionAssert.Equals should not be used for Assertions. Please use CollectionAssert.AreEqual & overloads instead. - CollectionAssert.Equals should not be used for Assertions. Please use CollectionAssert.AreEqual & overloads instead. + Element CollectionAssert.Equals nie powinien być używany dla asercji. Zamiast tego użyj metody CollectionAssert.AreEqual i przeciążeń. CollectionAssert.ReferenceEquals should not be used for Assertions. Please use CollectionAssert methods or Assert.AreSame & overloads instead. - CollectionAssert.ReferenceEquals should not be used for Assertions. Please use CollectionAssert methods or Assert.AreSame & overloads instead. + Element Assert.ReferenceEquals nie powinien być używany dla asercji. Zamiast tego użyj metod CollectionAssert lub Assert.AreSame oraz ich przeciążeń. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf index 7839c81f10..40f792c33e 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf @@ -84,22 +84,22 @@ Expected collection to contain the specified item. {0} - Expected collection to contain the specified item. {0} + A coleção esperada contém o item especificado. {0} Expected at least one item to match the predicate. {0} - Expected at least one item to match the predicate. {0} + Esperava-se que pelo menos um item correspondesse ao predicado. {0} Expected collection to contain exactly one element but found {1} element(s). {0} - Expected collection to contain exactly one element but found {1} element(s). {0} + A coleção esperada contém exatamente um elemento, mas encontrou {1} elementos. {0} Expected exactly one item to match the predicate but found {1} item(s). {0} - Expected exactly one item to match the predicate but found {1} item(s). {0} + Esperava-se exatamente um item para corresponder ao predicado, mas encontrou {1} itens. {0} @@ -109,22 +109,22 @@ Expected collection to not contain the specified item. {0} - Expected collection to not contain the specified item. {0} + A coleção esperada não contém o item especificado. {0} Expected no items to match the predicate. {0} - Expected no items to match the predicate. {0} + Não era esperado nenhum item que corresponda ao predicado. {0} String '{0}' ends with string '{1}'. {2} - String '{0}' ends with string '{1}'. {2} + A cadeia de caracteres “{0}” termina com cadeia de caracteres “{1}”. {2} String '{0}' starts with string '{1}'. {2} - String '{0}' starts with string '{1}'. {2} + A cadeia de caracteres “{0}” começa com a cadeia de caracteres “{1}”. {2} @@ -163,7 +163,7 @@ Real: {2} String '{0}' does not end with string '{1}'. {2} - String '{0}' does not end with string '{1}'. {2} + A cadeia de caracteres “{0}” não termina com a cadeia de caracteres “{1}”. {2} @@ -193,7 +193,7 @@ Real: {2} String '{0}' does not match pattern '{1}'. {2} - String '{0}' does not match pattern '{1}'. {2} + A cadeia de caracteres “{0}” não corresponde ao padrão “{1}”. {2} @@ -208,7 +208,7 @@ Real: {2} String '{0}' matches pattern '{1}'. {2} - String '{0}' matches pattern '{1}'. {2} + A cadeia de caracteres “{0}” corresponde ao padrão “{1}”. {2} @@ -249,7 +249,7 @@ Real: {2} String '{0}' does not start with string '{1}'. {2} - String '{0}' does not start with string '{1}'. {2} + A cadeia de caracteres “{0}” não começa com a cadeia de caracteres “{1}”. {2} @@ -352,32 +352,32 @@ Real: {2} Actual value <{2}> is not greater than expected value <{1}>. {0} - Actual value <{2}> is not greater than expected value <{1}>. {0} + O valor <{2}> real não é maior que o valor esperado <{1}>. {0} Actual value <{2}> is not greater than or equal to expected value <{1}>. {0} - Actual value <{2}> is not greater than or equal to expected value <{1}>. {0} + O valor <{2}> real não é maior ou igual ao valor esperado <{1}>. {0} Actual value <{2}> is not less than expected value <{1}>. {0} - Actual value <{2}> is not less than expected value <{1}>. {0} + O valor <{2}> real não é menor que o valor esperado <{1}>. {0} Actual value <{2}> is not less than or equal to expected value <{1}>. {0} - Actual value <{2}> is not less than or equal to expected value <{1}>. {0} + O valor <{2}> real não é menor ou igual ao valor esperado <{1}>. {0} Expected value <{1}> to be positive. {0} - Expected value <{1}> to be positive. {0} + O valor <{1}> esperado deve ser positivo. {0} Expected value <{1}> to be negative. {0} - Expected value <{1}> to be negative. {0} + O valor <{1}> esperado deve ser negativo. {0} @@ -387,27 +387,27 @@ Real: {2} Assert.ReferenceEquals should not be used for Assertions. Please use Assert.AreSame & overloads instead. - Assert.ReferenceEquals should not be used for Assertions. Please use Assert.AreSame & overloads instead. + Assert.ReferenceEquals não deve ser usado com as Declarações. Em vez disso, use Assert.AreSame e as sobrecargas. StringAssert.Equals should not be used for Assertions. Please use StringAssert methods or Assert.AreEqual & overloads instead. - StringAssert.Equals should not be used for Assertions. Please use StringAssert methods or Assert.AreEqual & overloads instead. + StringAssert.Equals não deve ser usado com as Declarações. Em vez disso, use os métodos StringAssert ou Assert.AreEqual e as sobrecargas. StringAssert.ReferenceEquals should not be used for Assertions. Please use StringAssert methods or Assert.AreSame & overloads instead. - StringAssert.ReferenceEquals should not be used for Assertions. Please use StringAssert methods or Assert.AreSame & overloads instead. + StringAssert.ReferenceEquals não deve ser usado com as Declarações. Em vez disso, use os métodos StringAssert ou Assert.AreSame e as sobrecargas. CollectionAssert.Equals should not be used for Assertions. Please use CollectionAssert.AreEqual & overloads instead. - CollectionAssert.Equals should not be used for Assertions. Please use CollectionAssert.AreEqual & overloads instead. + CollectionAssert.Equals não deve ser usado com as Declarações. Em vez disso, use CollectionAssert.AreEqual e as sobrecargas. CollectionAssert.ReferenceEquals should not be used for Assertions. Please use CollectionAssert methods or Assert.AreSame & overloads instead. - CollectionAssert.ReferenceEquals should not be used for Assertions. Please use CollectionAssert methods or Assert.AreSame & overloads instead. + CollectionAssert.ReferenceEquals não deve ser usado com as Declarações. Em vez disso, use os métodos CollectionAssert ou Assert.AreSame e as sobrecargas. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.tr.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.tr.xlf index 2dca06ed92..ee3bf19693 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.tr.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.tr.xlf @@ -84,22 +84,22 @@ Expected collection to contain the specified item. {0} - Expected collection to contain the specified item. {0} + Koleksiyonun belirtilen öğeyi içermesi bekleniyordu. {0} Expected at least one item to match the predicate. {0} - Expected at least one item to match the predicate. {0} + En az bir öğenin koşulla eşleşmesi bekleniyordu. {0} Expected collection to contain exactly one element but found {1} element(s). {0} - Expected collection to contain exactly one element but found {1} element(s). {0} + Beklenen koleksiyonun tam olarak bir öğe içermesi beklenirken, {1} öğe bulundu. {0} Expected exactly one item to match the predicate but found {1} item(s). {0} - Expected exactly one item to match the predicate but found {1} item(s). {0} + Özellikle bir öğenin koşulla eşleşmesi beklenirken {1} öğe bulundu. {0} @@ -109,22 +109,22 @@ Expected collection to not contain the specified item. {0} - Expected collection to not contain the specified item. {0} + Koleksiyonun belirtilen öğeyi içermemesi bekleniyordu. {0} Expected no items to match the predicate. {0} - Expected no items to match the predicate. {0} + Hiçbir öğenin koşulla eşleşmesi beklenmiyordu. {0} String '{0}' ends with string '{1}'. {2} - String '{0}' ends with string '{1}'. {2} + '{0}' dizesi '{1}' dizesi ile bitiyor. {2} String '{0}' starts with string '{1}'. {2} - String '{0}' starts with string '{1}'. {2} + '{0}' dizesi '{1}' dizesi ile başlıyor. {2} @@ -163,7 +163,7 @@ Gerçekte olan: {2} String '{0}' does not end with string '{1}'. {2} - String '{0}' does not end with string '{1}'. {2} + '{0}' dizesi, '{1}' dizesi ile sonlanmıyor. {2} @@ -193,7 +193,7 @@ Gerçekte olan: {2} String '{0}' does not match pattern '{1}'. {2} - String '{0}' does not match pattern '{1}'. {2} + '{0}' dizesi, '{1}' deseni ile eşleşmiyor. {2} @@ -208,7 +208,7 @@ Gerçekte olan: {2} String '{0}' matches pattern '{1}'. {2} - String '{0}' matches pattern '{1}'. {2} + '{0}' dizesi, '{1}' deseni ile eşleşiyor. {2} @@ -249,7 +249,7 @@ Gerçekte olan: {2} String '{0}' does not start with string '{1}'. {2} - String '{0}' does not start with string '{1}'. {2} + '{0}' dizesi, '{1}' dizesi ile başlamıyor. {2} @@ -352,32 +352,32 @@ Gerçekte olan: {2} Actual value <{2}> is not greater than expected value <{1}>. {0} - Actual value <{2}> is not greater than expected value <{1}>. {0} + Geçerli <{2}> değeri, beklenen <{1}> değerinden daha büyük değil. {0} Actual value <{2}> is not greater than or equal to expected value <{1}>. {0} - Actual value <{2}> is not greater than or equal to expected value <{1}>. {0} + Geçerli <{2}> değeri, beklenen <{1}> değerinden büyük veya bu değere eşit değil. {0} Actual value <{2}> is not less than expected value <{1}>. {0} - Actual value <{2}> is not less than expected value <{1}>. {0} + Geçerli <{2}> değeri, beklenen <{1}> değerinden daha küçük değil. {0} Actual value <{2}> is not less than or equal to expected value <{1}>. {0} - Actual value <{2}> is not less than or equal to expected value <{1}>. {0} + Geçerli <{2}> değeri, beklenen <{1}> değerinden küçük veya bu değere eşit değil. {0} Expected value <{1}> to be positive. {0} - Expected value <{1}> to be positive. {0} + Beklenen <{1}> değeri pozitif olmalıdır. {0} Expected value <{1}> to be negative. {0} - Expected value <{1}> to be negative. {0} + Beklenen <{1}> değeri negatif olmalıdır. {0} @@ -387,27 +387,27 @@ Gerçekte olan: {2} Assert.ReferenceEquals should not be used for Assertions. Please use Assert.AreSame & overloads instead. - Assert.ReferenceEquals should not be used for Assertions. Please use Assert.AreSame & overloads instead. + Assert.ReferenceEquals, Onaylama için kullanılmamalı. Lütfen yerine Assert.AreSame & aşırı yüklemeleri kullanın. StringAssert.Equals should not be used for Assertions. Please use StringAssert methods or Assert.AreEqual & overloads instead. - StringAssert.Equals should not be used for Assertions. Please use StringAssert methods or Assert.AreEqual & overloads instead. + StringAssert.Equals, Onaylama için kullanılmamalı. Lütfen bunun yerine StringAssert yöntemlerini veya Assert.AreEqual & aşırı yüklemelerini kullanın. StringAssert.ReferenceEquals should not be used for Assertions. Please use StringAssert methods or Assert.AreSame & overloads instead. - StringAssert.ReferenceEquals should not be used for Assertions. Please use StringAssert methods or Assert.AreSame & overloads instead. + StringAssert.ReferenceEquals, Onaylama için kullanılmamalı. Lütfen bunun yerine StringAssert yöntemlerini veya Assert.AreSame & aşırı yüklemelerini kullanın. CollectionAssert.Equals should not be used for Assertions. Please use CollectionAssert.AreEqual & overloads instead. - CollectionAssert.Equals should not be used for Assertions. Please use CollectionAssert.AreEqual & overloads instead. + CollectionAssert.Equals, Onaylama için kullanılmamalı. Lütfen yerine CollectionAssert.AreEqual & aşırı yüklemeleri kullanın. CollectionAssert.ReferenceEquals should not be used for Assertions. Please use CollectionAssert methods or Assert.AreSame & overloads instead. - CollectionAssert.ReferenceEquals should not be used for Assertions. Please use CollectionAssert methods or Assert.AreSame & overloads instead. + CollectionAssert.ReferenceEquals, Onaylama için kullanılmamalı. Lütfen bunun yerine CollectionAssert yöntemlerini veya Assert.AreSame & aşırı yüklemelerini kullanın. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf index 6507fc239e..35d48a2ea6 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf @@ -84,22 +84,22 @@ Expected collection to contain the specified item. {0} - Expected collection to contain the specified item. {0} + 预期集合包含指定项。{0} Expected at least one item to match the predicate. {0} - Expected at least one item to match the predicate. {0} + 应至少有一项与谓词匹配。{0} Expected collection to contain exactly one element but found {1} element(s). {0} - Expected collection to contain exactly one element but found {1} element(s). {0} + 预期集合仅包含一个元素,但找到 {1} 个元素。{0} Expected exactly one item to match the predicate but found {1} item(s). {0} - Expected exactly one item to match the predicate but found {1} item(s). {0} + 应恰好只有一项与谓词匹配,但找到 {1} 项。{0} @@ -109,22 +109,22 @@ Expected collection to not contain the specified item. {0} - Expected collection to not contain the specified item. {0} + 预期集合不包含指定项。{0} Expected no items to match the predicate. {0} - Expected no items to match the predicate. {0} + 预期没有与谓词匹配的项。{0} String '{0}' ends with string '{1}'. {2} - String '{0}' ends with string '{1}'. {2} + 字符串 '{0}' 以字符串 '{1}'结尾。{2} String '{0}' starts with string '{1}'. {2} - String '{0}' starts with string '{1}'. {2} + 字符串 '{0}' 以字符串 '{1}' 开头。{2} @@ -163,7 +163,7 @@ Actual: {2} String '{0}' does not end with string '{1}'. {2} - String '{0}' does not end with string '{1}'. {2} + 字符串 '{0}' 不以字符串 '{1}' 结尾。{2} @@ -193,7 +193,7 @@ Actual: {2} String '{0}' does not match pattern '{1}'. {2} - String '{0}' does not match pattern '{1}'. {2} + 字符串 '{0}' 与模式 '{1}' 不匹配。{2} @@ -208,7 +208,7 @@ Actual: {2} String '{0}' matches pattern '{1}'. {2} - String '{0}' matches pattern '{1}'. {2} + 字符串 '{0}' 与模式 '{1}' 匹配。{2} @@ -249,7 +249,7 @@ Actual: {2} String '{0}' does not start with string '{1}'. {2} - String '{0}' does not start with string '{1}'. {2} + 字符串 '{0}' 不以字符串 '{1}' 开头。{2} @@ -352,32 +352,32 @@ Actual: {2} Actual value <{2}> is not greater than expected value <{1}>. {0} - Actual value <{2}> is not greater than expected value <{1}>. {0} + 实际值 <{2}> 不大于预期值 <{1}>。{0} Actual value <{2}> is not greater than or equal to expected value <{1}>. {0} - Actual value <{2}> is not greater than or equal to expected value <{1}>. {0} + 实际值 <{2}> 不大于或等于预期值 <{1}>。{0} Actual value <{2}> is not less than expected value <{1}>. {0} - Actual value <{2}> is not less than expected value <{1}>. {0} + 实际值 <{2}> 不小于预期值 <{1}>。{0} Actual value <{2}> is not less than or equal to expected value <{1}>. {0} - Actual value <{2}> is not less than or equal to expected value <{1}>. {0} + 实际值 <{2}> 不小于或等于预期值 <{1}>。{0} Expected value <{1}> to be positive. {0} - Expected value <{1}> to be positive. {0} + 预期值 <{1}> 为正值。{0} Expected value <{1}> to be negative. {0} - Expected value <{1}> to be negative. {0} + 预期值 <{1}> 为负值。{0} @@ -387,27 +387,27 @@ Actual: {2} Assert.ReferenceEquals should not be used for Assertions. Please use Assert.AreSame & overloads instead. - Assert.ReferenceEquals should not be used for Assertions. Please use Assert.AreSame & overloads instead. + Assert.ReferenceEquals 不应用于断言。请改用 Assert.AreSame 和重载。 StringAssert.Equals should not be used for Assertions. Please use StringAssert methods or Assert.AreEqual & overloads instead. - StringAssert.Equals should not be used for Assertions. Please use StringAssert methods or Assert.AreEqual & overloads instead. + StringAssert.Equals 不应用于断言。请改用 StringAssert 方法或 Assert.AreEqual 和重载。 StringAssert.ReferenceEquals should not be used for Assertions. Please use StringAssert methods or Assert.AreSame & overloads instead. - StringAssert.ReferenceEquals should not be used for Assertions. Please use StringAssert methods or Assert.AreSame & overloads instead. + StringAssert.ReferenceEquals 不应用于断言。请改用 StringAssert 方法或 Assert.AreSame 和重载。 CollectionAssert.Equals should not be used for Assertions. Please use CollectionAssert.AreEqual & overloads instead. - CollectionAssert.Equals should not be used for Assertions. Please use CollectionAssert.AreEqual & overloads instead. + CollectionAssert.Equals 不应用于断言。请改用 CollectionAssert.AreEqual 和重载。 CollectionAssert.ReferenceEquals should not be used for Assertions. Please use CollectionAssert methods or Assert.AreSame & overloads instead. - CollectionAssert.ReferenceEquals should not be used for Assertions. Please use CollectionAssert methods or Assert.AreSame & overloads instead. + CollectionAssert.ReferenceEquals 不应用于断言。请改用 CollectionAssert 方法或 Assert.AreSame 和重载。 diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf index cf022768e8..d38aea41fb 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf @@ -84,22 +84,22 @@ Expected collection to contain the specified item. {0} - Expected collection to contain the specified item. {0} + 預期集合包含指定的項目。{0} Expected at least one item to match the predicate. {0} - Expected at least one item to match the predicate. {0} + 必須至少有一個項目符合述詞。{0} Expected collection to contain exactly one element but found {1} element(s). {0} - Expected collection to contain exactly one element but found {1} element(s). {0} + 預期集合應僅包含一個元素,但發現 {1} 個元素。{0} Expected exactly one item to match the predicate but found {1} item(s). {0} - Expected exactly one item to match the predicate but found {1} item(s). {0} + 預期只有一個項目符合述詞,但找到 {1} 個項目。{0} @@ -109,22 +109,22 @@ Expected collection to not contain the specified item. {0} - Expected collection to not contain the specified item. {0} + 預期集合不包含指定的項目。{0} Expected no items to match the predicate. {0} - Expected no items to match the predicate. {0} + 預期沒有任何項目符合述詞。{0} String '{0}' ends with string '{1}'. {2} - String '{0}' ends with string '{1}'. {2} + 字串 '{0}' 以字串 '{1}' 結尾。{2} String '{0}' starts with string '{1}'. {2} - String '{0}' starts with string '{1}'. {2} + 字串 '{0}' 以字串 '{1}' 開頭。{2} @@ -163,7 +163,7 @@ Actual: {2} String '{0}' does not end with string '{1}'. {2} - String '{0}' does not end with string '{1}'. {2} + 字串 '{0}' 不是以字串 '{1}' 結尾。{2} @@ -193,7 +193,7 @@ Actual: {2} String '{0}' does not match pattern '{1}'. {2} - String '{0}' does not match pattern '{1}'. {2} + 字串 '{0}' 與模式 '{1}' 不符。{2} @@ -208,7 +208,7 @@ Actual: {2} String '{0}' matches pattern '{1}'. {2} - String '{0}' matches pattern '{1}'. {2} + 字串 '{0}' 與模式 '{1}' 相符。{2} @@ -249,7 +249,7 @@ Actual: {2} String '{0}' does not start with string '{1}'. {2} - String '{0}' does not start with string '{1}'. {2} + 字串 '{0}' 不是以字串 '{1}' 開頭。{2} @@ -352,32 +352,32 @@ Actual: {2} Actual value <{2}> is not greater than expected value <{1}>. {0} - Actual value <{2}> is not greater than expected value <{1}>. {0} + 實際值 <{2}> 不大於預期值 <{1}>。{0} Actual value <{2}> is not greater than or equal to expected value <{1}>. {0} - Actual value <{2}> is not greater than or equal to expected value <{1}>. {0} + 實際值 <{2}> 不大於或等於預期值 <{1}>。{0} Actual value <{2}> is not less than expected value <{1}>. {0} - Actual value <{2}> is not less than expected value <{1}>. {0} + 實際值 <{2}> 不小於預期值 <{1}>。{0} Actual value <{2}> is not less than or equal to expected value <{1}>. {0} - Actual value <{2}> is not less than or equal to expected value <{1}>. {0} + 實際值 <{2}> 不小於或等於預期值 <{1}>。{0} Expected value <{1}> to be positive. {0} - Expected value <{1}> to be positive. {0} + 預期值 <{1}> 為正數。{0} Expected value <{1}> to be negative. {0} - Expected value <{1}> to be negative. {0} + 預期值 <{1}> 為負數。{0} @@ -387,27 +387,27 @@ Actual: {2} Assert.ReferenceEquals should not be used for Assertions. Please use Assert.AreSame & overloads instead. - Assert.ReferenceEquals should not be used for Assertions. Please use Assert.AreSame & overloads instead. + Assert.ReferenceEquals 不應使用於判斷提示。請改用 Assert.AreSame 及多載。 StringAssert.Equals should not be used for Assertions. Please use StringAssert methods or Assert.AreEqual & overloads instead. - StringAssert.Equals should not be used for Assertions. Please use StringAssert methods or Assert.AreEqual & overloads instead. + StringAssert.Equals 不應使用於判斷提示。請改用 StringAssert 方法或 Assert.AreEqual 及其多載。 StringAssert.ReferenceEquals should not be used for Assertions. Please use StringAssert methods or Assert.AreSame & overloads instead. - StringAssert.ReferenceEquals should not be used for Assertions. Please use StringAssert methods or Assert.AreSame & overloads instead. + StringAssert.ReferenceEquals 不應使用於判斷提示。請改用 StringAssert 方法或 Assert.AreSame 及其多載。 CollectionAssert.Equals should not be used for Assertions. Please use CollectionAssert.AreEqual & overloads instead. - CollectionAssert.Equals should not be used for Assertions. Please use CollectionAssert.AreEqual & overloads instead. + CollectionAssert.Equals 不應使用於判斷提示。請改用 CollectionAssert.AreEqual 及多載。 CollectionAssert.ReferenceEquals should not be used for Assertions. Please use CollectionAssert methods or Assert.AreSame & overloads instead. - CollectionAssert.ReferenceEquals should not be used for Assertions. Please use CollectionAssert methods or Assert.AreSame & overloads instead. + CollectionAssert.ReferenceEquals 不應使用於判斷提示。請改用 CollectionAssert 方法或 Assert.AreSame 及其多載。 From 093c672c4dc15c0d4cbbd84c85e0a43774aa82c6 Mon Sep 17 00:00:00 2001 From: Copilot <198982749+Copilot@users.noreply.github.com> Date: Mon, 7 Jul 2025 21:31:40 +0200 Subject: [PATCH 169/541] Improve DataRow type mismatch error messages with descriptive parameter information (#5819) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: Evangelink <11340282+Evangelink@users.noreply.github.com> Co-authored-by: Amaury Levé --- .../DataRowShouldBeValidAnalyzer.cs | 26 +++++++-- .../MSTest.Analyzers/Resources.Designer.cs | 11 +++- src/Analyzers/MSTest.Analyzers/Resources.resx | 5 +- .../MSTest.Analyzers/xlf/Resources.cs.xlf | 9 +++- .../MSTest.Analyzers/xlf/Resources.de.xlf | 9 +++- .../MSTest.Analyzers/xlf/Resources.es.xlf | 9 +++- .../MSTest.Analyzers/xlf/Resources.fr.xlf | 9 +++- .../MSTest.Analyzers/xlf/Resources.it.xlf | 9 +++- .../MSTest.Analyzers/xlf/Resources.ja.xlf | 9 +++- .../MSTest.Analyzers/xlf/Resources.ko.xlf | 9 +++- .../MSTest.Analyzers/xlf/Resources.pl.xlf | 9 +++- .../MSTest.Analyzers/xlf/Resources.pt-BR.xlf | 9 +++- .../MSTest.Analyzers/xlf/Resources.ru.xlf | 9 +++- .../MSTest.Analyzers/xlf/Resources.tr.xlf | 9 +++- .../xlf/Resources.zh-Hans.xlf | 9 +++- .../xlf/Resources.zh-Hant.xlf | 9 +++- .../DataRowShouldBeValidAnalyzerTests.cs | 54 ++++++++++++++++++- 17 files changed, 179 insertions(+), 34 deletions(-) diff --git a/src/Analyzers/MSTest.Analyzers/DataRowShouldBeValidAnalyzer.cs b/src/Analyzers/MSTest.Analyzers/DataRowShouldBeValidAnalyzer.cs index 4e903b6a2b..44d17d7c2d 100644 --- a/src/Analyzers/MSTest.Analyzers/DataRowShouldBeValidAnalyzer.cs +++ b/src/Analyzers/MSTest.Analyzers/DataRowShouldBeValidAnalyzer.cs @@ -184,7 +184,7 @@ private static void AnalyzeAttribute(SymbolAnalysisContext context, AttributeDat AnalyzeGenericMethod(context, dataRowSyntax, methodSymbol, constructorArguments); // Check constructor argument types match method parameter types. - List<(int ConstructorArgumentIndex, int MethodParameterIndex)> typeMismatchIndices = []; + List<(string ParameterName, string ExpectedType, string ActualType)> typeMismatches = []; for (int currentArgumentIndex = 0; currentArgumentIndex < constructorArguments.Length; currentArgumentIndex++) { // Null is considered as default for non-nullable types. @@ -205,16 +205,34 @@ private static void AnalyzeAttribute(SymbolAnalysisContext context, AttributeDat if (argumentType is not null && !argumentType.IsAssignableTo(paramType, context.Compilation)) { - typeMismatchIndices.Add((currentArgumentIndex, Math.Min(currentArgumentIndex, methodSymbol.Parameters.Length - 1))); + int parameterIndex = Math.Min(currentArgumentIndex, methodSymbol.Parameters.Length - 1); + string parameterName = methodSymbol.Parameters[parameterIndex].Name; + string expectedType = paramType.ToDisplayString(); + string actualType = argumentType.ToDisplayString(); + typeMismatches.Add((parameterName, expectedType, actualType)); } } // Report diagnostics if there's any type mismatch. - if (typeMismatchIndices.Count > 0) + if (typeMismatches.Count > 0) { + // Format all mismatches into a single message + string mismatchMessage; + if (typeMismatches.Count == 1) + { + (string parameterName, string expectedType, string actualType) = typeMismatches[0]; + mismatchMessage = string.Format(CultureInfo.InvariantCulture, Resources.DataRowShouldBeValidMessageFormat_ParameterMismatch, parameterName, expectedType, actualType); + } + else + { + IEnumerable mismatchDescriptions = typeMismatches.Select(m => + string.Format(CultureInfo.InvariantCulture, Resources.DataRowShouldBeValidMessageFormat_ParameterMismatch, m.ParameterName, m.ExpectedType, m.ActualType)); + mismatchMessage = string.Join("; ", mismatchDescriptions); + } + context.ReportDiagnostic(dataRowSyntax.CreateDiagnostic( ArgumentTypeMismatchRule, - string.Join(", ", typeMismatchIndices))); + mismatchMessage)); } } diff --git a/src/Analyzers/MSTest.Analyzers/Resources.Designer.cs b/src/Analyzers/MSTest.Analyzers/Resources.Designer.cs index 12df6a0491..380694b48f 100644 --- a/src/Analyzers/MSTest.Analyzers/Resources.Designer.cs +++ b/src/Analyzers/MSTest.Analyzers/Resources.Designer.cs @@ -355,7 +355,7 @@ internal static string DataRowShouldBeValidMessageFormat_ArgumentCountMismatch { } /// - /// Looks up a localized string similar to DataRow argument type should match method parameter type. Mismatches occur at indices: {0}. + /// Looks up a localized string similar to DataRow argument types do not match method parameter types. {0}. /// internal static string DataRowShouldBeValidMessageFormat_ArgumentTypeMismatch { get { @@ -363,6 +363,15 @@ internal static string DataRowShouldBeValidMessageFormat_ArgumentTypeMismatch { } } + /// + /// Looks up a localized string similar to Parameter '{0}' expects type '{1}', but the provided value has type '{2}'. + /// + internal static string DataRowShouldBeValidMessageFormat_ParameterMismatch { + get { + return ResourceManager.GetString("DataRowShouldBeValidMessageFormat_ParameterMismatch", resourceCulture); + } + } + /// /// Looks up a localized string similar to Found two conflicting types for generic parameter '{0}'. The conflicting types are '{1}' and '{2}'.. /// diff --git a/src/Analyzers/MSTest.Analyzers/Resources.resx b/src/Analyzers/MSTest.Analyzers/Resources.resx index 50ba58dda1..fc98d87ff4 100644 --- a/src/Analyzers/MSTest.Analyzers/Resources.resx +++ b/src/Analyzers/MSTest.Analyzers/Resources.resx @@ -251,7 +251,10 @@ The type declaring these methods should also respect the following rules: DataRow argument count should match method parameter count (constructor arguments: {0}, method parameters: {1}) - DataRow argument type should match method parameter type. Mismatches occur at indices: {0} + DataRow argument types do not match method parameter types. {0} + + + Parameter '{0}' expects type '{1}', but the provided value has type '{2}' DataRow should only be set on a test method diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf index 69713927ae..c6dc824ee7 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf @@ -277,8 +277,13 @@ Typ deklarující tyto metody by měl také respektovat následující pravidla: - DataRow argument type should match method parameter type. Mismatches occur at indices: {0} - Typ argumentu DataRow by měl odpovídat typu parametru metody. V indexech dochází k neshodě: {0} + DataRow argument types do not match method parameter types. {0} + DataRow argument types do not match method parameter types. {0} + + + + Parameter '{0}' expects type '{1}', but the provided value has type '{2}' + Parameter '{0}' expects type '{1}', but the provided value has type '{2}' diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf index c61b7c45b8..04ba4c523b 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf @@ -278,8 +278,13 @@ Der Typ, der diese Methoden deklariert, sollte auch die folgenden Regeln beachte - DataRow argument type should match method parameter type. Mismatches occur at indices: {0} - Der DataRow-Argumenttyp muss mit dem Methodenparametertyp übereinstimmen. Nichtübereinstimmungen treten bei Indizes auf: {0} + DataRow argument types do not match method parameter types. {0} + DataRow argument types do not match method parameter types. {0} + + + + Parameter '{0}' expects type '{1}', but the provided value has type '{2}' + Parameter '{0}' expects type '{1}', but the provided value has type '{2}' diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf index 8fb03d3c5f..66a0925739 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf @@ -277,8 +277,13 @@ El tipo que declara estos métodos también debe respetar las reglas siguientes: - DataRow argument type should match method parameter type. Mismatches occur at indices: {0} - El tipo de argumento DataRow debe coincidir con el tipo de parámetro de método. Se producen errores de coincidencia en los índices: {0} + DataRow argument types do not match method parameter types. {0} + DataRow argument types do not match method parameter types. {0} + + + + Parameter '{0}' expects type '{1}', but the provided value has type '{2}' + Parameter '{0}' expects type '{1}', but the provided value has type '{2}' diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf index ab6c48bc2a..9698eb2cc8 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf @@ -277,8 +277,13 @@ Le type doit être une classe - DataRow argument type should match method parameter type. Mismatches occur at indices: {0} - Le type d’argument DataRow doit correspondre au type de paramètre de la méthode. Des incompatibilités se produisent aux index :{0} + DataRow argument types do not match method parameter types. {0} + DataRow argument types do not match method parameter types. {0} + + + + Parameter '{0}' expects type '{1}', but the provided value has type '{2}' + Parameter '{0}' expects type '{1}', but the provided value has type '{2}' diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf index 84ae7020a8..5efb90ca1d 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf @@ -277,8 +277,13 @@ Anche il tipo che dichiara questi metodi deve rispettare le regole seguenti: - DataRow argument type should match method parameter type. Mismatches occur at indices: {0} - Il tipo di argomento di DataRow deve corrispondere al tipo di parametro del metodo. Errori di corrispondenza in corrispondenza degli indici: {0} + DataRow argument types do not match method parameter types. {0} + DataRow argument types do not match method parameter types. {0} + + + + Parameter '{0}' expects type '{1}', but the provided value has type '{2}' + Parameter '{0}' expects type '{1}', but the provided value has type '{2}' diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf index d68db618d1..75fcf251ba 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf @@ -277,8 +277,13 @@ The type declaring these methods should also respect the following rules: - DataRow argument type should match method parameter type. Mismatches occur at indices: {0} - DataRow 引数の型は、メソッド パラメーターの型と一致させる必要があります。インデックスで不一致が発生しました: {0} + DataRow argument types do not match method parameter types. {0} + DataRow argument types do not match method parameter types. {0} + + + + Parameter '{0}' expects type '{1}', but the provided value has type '{2}' + Parameter '{0}' expects type '{1}', but the provided value has type '{2}' diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf index 48843f3e9d..75c3b0081f 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf @@ -277,8 +277,13 @@ The type declaring these methods should also respect the following rules: - DataRow argument type should match method parameter type. Mismatches occur at indices: {0} - DataRow 인수 형식은 메서드 매개 변수 형식과 일치해야 합니다. 인덱스에서 불일치 발생: {0} + DataRow argument types do not match method parameter types. {0} + DataRow argument types do not match method parameter types. {0} + + + + Parameter '{0}' expects type '{1}', but the provided value has type '{2}' + Parameter '{0}' expects type '{1}', but the provided value has type '{2}' diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf index 561d662746..55eff8b796 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf @@ -277,8 +277,13 @@ Typ deklarujący te metody powinien również przestrzegać następujących regu - DataRow argument type should match method parameter type. Mismatches occur at indices: {0} - Typ argumentu DataRow powinien być zgodny z typem parametru metody. W indeksach występują niezgodności: {0} + DataRow argument types do not match method parameter types. {0} + DataRow argument types do not match method parameter types. {0} + + + + Parameter '{0}' expects type '{1}', but the provided value has type '{2}' + Parameter '{0}' expects type '{1}', but the provided value has type '{2}' diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf index 3ae1e7736c..222dd7a9ae 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf @@ -277,8 +277,13 @@ O tipo que declara esses métodos também deve respeitar as seguintes regras: - DataRow argument type should match method parameter type. Mismatches occur at indices: {0} - O tipo de argumento DataRow deve corresponder ao tipo de parâmetro do método. Incompatibilidades ocorrem nos índices: {0} + DataRow argument types do not match method parameter types. {0} + DataRow argument types do not match method parameter types. {0} + + + + Parameter '{0}' expects type '{1}', but the provided value has type '{2}' + Parameter '{0}' expects type '{1}', but the provided value has type '{2}' diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf index c5fbd517cf..c1760782ff 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf @@ -283,8 +283,13 @@ The type declaring these methods should also respect the following rules: - DataRow argument type should match method parameter type. Mismatches occur at indices: {0} - Тип аргумента DataRow должен соответствовать типу параметра метода. Обнаружены несовпадения в следующих индексах: {0} + DataRow argument types do not match method parameter types. {0} + DataRow argument types do not match method parameter types. {0} + + + + Parameter '{0}' expects type '{1}', but the provided value has type '{2}' + Parameter '{0}' expects type '{1}', but the provided value has type '{2}' diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf index e579f7a193..47f6e789cc 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf @@ -277,8 +277,13 @@ Bu yöntemleri bildiren tipin ayrıca aşağıdaki kurallara uyması gerekir: - DataRow argument type should match method parameter type. Mismatches occur at indices: {0} - DataRow bağımsız değişken türü, yöntem parametresinin türüyle eşleşmelidir. Dizinler sırasında uyuşmazlıklar oluştu: {0} + DataRow argument types do not match method parameter types. {0} + DataRow argument types do not match method parameter types. {0} + + + + Parameter '{0}' expects type '{1}', but the provided value has type '{2}' + Parameter '{0}' expects type '{1}', but the provided value has type '{2}' diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf index a57538a4df..262662fb6f 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf @@ -277,8 +277,13 @@ The type declaring these methods should also respect the following rules: - DataRow argument type should match method parameter type. Mismatches occur at indices: {0} - DataRow 参数类型应与方法参数类型匹配。索引处出现不匹配: {0} + DataRow argument types do not match method parameter types. {0} + DataRow argument types do not match method parameter types. {0} + + + + Parameter '{0}' expects type '{1}', but the provided value has type '{2}' + Parameter '{0}' expects type '{1}', but the provided value has type '{2}' diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf index ef520dba33..6113380da4 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf @@ -277,8 +277,13 @@ The type declaring these methods should also respect the following rules: - DataRow argument type should match method parameter type. Mismatches occur at indices: {0} - DataRow 引數類型應符合方法參數類型。索引發生不符: {0} + DataRow argument types do not match method parameter types. {0} + DataRow argument types do not match method parameter types. {0} + + + + Parameter '{0}' expects type '{1}', but the provided value has type '{2}' + Parameter '{0}' expects type '{1}', but the provided value has type '{2}' diff --git a/test/UnitTests/MSTest.Analyzers.UnitTests/DataRowShouldBeValidAnalyzerTests.cs b/test/UnitTests/MSTest.Analyzers.UnitTests/DataRowShouldBeValidAnalyzerTests.cs index a355034f92..e7e334d27f 100644 --- a/test/UnitTests/MSTest.Analyzers.UnitTests/DataRowShouldBeValidAnalyzerTests.cs +++ b/test/UnitTests/MSTest.Analyzers.UnitTests/DataRowShouldBeValidAnalyzerTests.cs @@ -155,7 +155,7 @@ await VerifyCS.VerifyAnalyzerAsync( code, VerifyCS.Diagnostic(DataRowShouldBeValidAnalyzer.ArgumentTypeMismatchRule) .WithLocation(0) - .WithArguments((0, 0))); + .WithArguments("Parameter 'o' expects type 'object[]', but the provided value has type 'int'")); } [TestMethod] @@ -490,7 +490,57 @@ await VerifyCS.VerifyAnalyzerAsync( code, VerifyCS.Diagnostic(DataRowShouldBeValidAnalyzer.ArgumentTypeMismatchRule) .WithLocation(0) - .WithArguments((2, 2))); + .WithArguments("Parameter 's' expects type 'string', but the provided value has type 'int'")); + } + + [TestMethod] + public async Task WhenDataRowHasDecimalDoubleTypeMismatch_Diagnostic() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [{|#0:DataRow("Luxury Car", "Alice Johnson", 1500.00, "https://example.com/luxurycar.jpg", "https://example.com/luxurycar")|}] + [TestMethod] + public void TestMethod1(string name, string reservedBy, decimal price, string imageUrl, string link) + { + } + } + """ + ; + + await VerifyCS.VerifyAnalyzerAsync( + code, + VerifyCS.Diagnostic(DataRowShouldBeValidAnalyzer.ArgumentTypeMismatchRule) + .WithLocation(0) + .WithArguments("Parameter 'price' expects type 'decimal', but the provided value has type 'double'")); + } + + [TestMethod] + public async Task WhenDataRowHasMultipleTypeMismatches_SingleDiagnosticWithAllMismatches() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [{|#0:DataRow(1, 2, 3)|}] + [TestMethod] + public void TestMethod1(string s, decimal d, bool b) + { + } + } + """ + ; + + await VerifyCS.VerifyAnalyzerAsync( + code, + VerifyCS.Diagnostic(DataRowShouldBeValidAnalyzer.ArgumentTypeMismatchRule) + .WithLocation(0) + .WithArguments("Parameter 's' expects type 'string', but the provided value has type 'int'; Parameter 'b' expects type 'bool', but the provided value has type 'int'")); } [TestMethod] From 94360dfccacfc549d3a385300dba6ab40ca4736d Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Tue, 8 Jul 2025 14:24:50 +0200 Subject: [PATCH 170/541] Ensure TestRun id for retries is the same in TRX (#5945) --- .../RetryOrchestrator.cs | 5 ++++- .../TrxReportEngine.cs | 7 ++++++- .../Helpers/EnvironmentVariableConstants.cs | 3 +++ .../RetryFailedTestsTests.cs | 11 ++++++++++- 4 files changed, 23 insertions(+), 3 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Extensions.Retry/RetryOrchestrator.cs b/src/Platform/Microsoft.Testing.Extensions.Retry/RetryOrchestrator.cs index fec544be04..2492649cf1 100644 --- a/src/Platform/Microsoft.Testing.Extensions.Retry/RetryOrchestrator.cs +++ b/src/Platform/Microsoft.Testing.Extensions.Retry/RetryOrchestrator.cs @@ -73,11 +73,14 @@ public async Task OrchestrateTestHostExecutionAsync() throw new InvalidOperationException(ExtensionResources.RetryFailedTestsNotSupportedInServerModeErrorMessage); } - if (IsHotReloadEnabled(_serviceProvider.GetEnvironment())) + IEnvironment environment = _serviceProvider.GetEnvironment(); + if (IsHotReloadEnabled(environment)) { throw new InvalidOperationException(ExtensionResources.RetryFailedTestsNotSupportedInHotReloadErrorMessage); } + environment.SetEnvironmentVariable(EnvironmentVariableConstants.TESTINGPLATFORM_TRX_TESTRUN_ID, Guid.NewGuid().ToString("N")); + ILogger logger = _serviceProvider.GetLoggerFactory().CreateLogger(); IConfiguration configuration = _serviceProvider.GetConfiguration(); diff --git a/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxReportEngine.cs b/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxReportEngine.cs index ba05207d56..c6455f7365 100644 --- a/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxReportEngine.cs +++ b/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxReportEngine.cs @@ -148,7 +148,12 @@ public TrxReportEngine(IFileSystem fileSystem, ITestApplicationModuleInfo testAp // create the xml doc var document = new XDocument(new XDeclaration("1.0", "UTF-8", null)); var testRun = new XElement(_namespaceUri + "TestRun"); - testRun.SetAttributeValue("id", Guid.NewGuid()); + if (!Guid.TryParse(_environment.GetEnvironmentVariable(EnvironmentVariableConstants.TESTINGPLATFORM_TRX_TESTRUN_ID), out Guid testRunId)) + { + testRunId = Guid.NewGuid(); + } + + testRun.SetAttributeValue("id", testRunId); string testRunName = $"{_environment.GetEnvironmentVariable("UserName")}@{_environment.MachineName} {FormatDateTimeForRunName(_clock.UtcNow)}"; testRun.SetAttributeValue("name", testRunName); diff --git a/src/Platform/Microsoft.Testing.Platform/Helpers/EnvironmentVariableConstants.cs b/src/Platform/Microsoft.Testing.Platform/Helpers/EnvironmentVariableConstants.cs index ad3c5291d3..e496cbc3af 100644 --- a/src/Platform/Microsoft.Testing.Platform/Helpers/EnvironmentVariableConstants.cs +++ b/src/Platform/Microsoft.Testing.Platform/Helpers/EnvironmentVariableConstants.cs @@ -39,4 +39,7 @@ internal static class EnvironmentVariableConstants // Unhandled Exception public const string TESTINGPLATFORM_EXIT_PROCESS_ON_UNHANDLED_EXCEPTION = nameof(TESTINGPLATFORM_EXIT_PROCESS_ON_UNHANDLED_EXCEPTION); + + // Trx + public const string TESTINGPLATFORM_TRX_TESTRUN_ID = nameof(TESTINGPLATFORM_TRX_TESTRUN_ID); } diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/RetryFailedTestsTests.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/RetryFailedTestsTests.cs index 610162f739..5e8fa515e7 100644 --- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/RetryFailedTestsTests.cs +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/RetryFailedTestsTests.cs @@ -28,7 +28,7 @@ public async Task RetryFailedTests_OnlyRetryTimes_Succeeds(string tfm, bool fail var testHost = TestInfrastructure.TestHost.LocateFrom(AssetFixture.TargetAssetPath, AssetName, tfm); string resultDirectory = Path.Combine(testHost.DirectoryName, Guid.NewGuid().ToString("N")); TestHostResult testHostResult = await testHost.ExecuteAsync( - $"--retry-failed-tests 3 --results-directory {resultDirectory}", + $"--retry-failed-tests 3 --results-directory {resultDirectory} --report-trx", new() { { EnvironmentVariableConstants.TESTINGPLATFORM_TELEMETRY_OPTOUT, "1" }, @@ -43,6 +43,15 @@ public async Task RetryFailedTests_OnlyRetryTimes_Succeeds(string tfm, bool fail testHostResult.AssertOutputContains("Tests suite completed successfully in 2 attempts"); testHostResult.AssertOutputContains("Failed! -"); testHostResult.AssertOutputContains("Passed! -"); + + string[] trxFiles = Directory.GetFiles(resultDirectory, "*.trx", SearchOption.AllDirectories); + Assert.AreEqual(2, trxFiles.Length); + string trxContents1 = File.ReadAllText(trxFiles[0]); + string trxContents2 = File.ReadAllText(trxFiles[1]); + Assert.AreNotEqual(trxContents1, trxContents2); + string id1 = Regex.Match(trxContents1, " Date: Wed, 9 Jul 2025 17:05:30 +0200 Subject: [PATCH 171/541] Move WinUI-specific resources to test framework extensions assembly (#5950) --- .../Attributes/WinUITestTargetAttribute.cs | 2 +- .../Attributes/WinUI_UITestMethodAttribute.cs | 2 +- .../FrameworkExtensionsMessages.Designer.cs | 81 +++++++++++ .../FrameworkExtensionsMessages.resx | 130 +++++++++++++++++ .../xlf/FrameworkExtensionsMessages.cs.xlf | 20 +++ .../xlf/FrameworkExtensionsMessages.de.xlf | 20 +++ .../xlf/FrameworkExtensionsMessages.es.xlf | 20 +++ .../xlf/FrameworkExtensionsMessages.fr.xlf | 20 +++ .../xlf/FrameworkExtensionsMessages.it.xlf | 20 +++ .../xlf/FrameworkExtensionsMessages.ja.xlf | 20 +++ .../xlf/FrameworkExtensionsMessages.ko.xlf | 20 +++ .../xlf/FrameworkExtensionsMessages.pl.xlf | 20 +++ .../xlf/FrameworkExtensionsMessages.pt-BR.xlf | 20 +++ .../xlf/FrameworkExtensionsMessages.ru.xlf | 20 +++ .../xlf/FrameworkExtensionsMessages.tr.xlf | 20 +++ .../FrameworkExtensionsMessages.zh-Hans.xlf | 20 +++ .../FrameworkExtensionsMessages.zh-Hant.xlf | 20 +++ .../TestFramework.Extensions.csproj | 14 ++ .../Resources/FrameworkMessages.Designer.cs | 135 +++++++----------- .../Resources/FrameworkMessages.resx | 13 -- .../Resources/xlf/FrameworkMessages.cs.xlf | 18 --- .../Resources/xlf/FrameworkMessages.de.xlf | 18 --- .../Resources/xlf/FrameworkMessages.es.xlf | 18 --- .../Resources/xlf/FrameworkMessages.fr.xlf | 18 --- .../Resources/xlf/FrameworkMessages.it.xlf | 18 --- .../Resources/xlf/FrameworkMessages.ja.xlf | 18 --- .../Resources/xlf/FrameworkMessages.ko.xlf | 18 --- .../Resources/xlf/FrameworkMessages.pl.xlf | 18 --- .../Resources/xlf/FrameworkMessages.pt-BR.xlf | 18 --- .../Resources/xlf/FrameworkMessages.ru.xlf | 18 --- .../Resources/xlf/FrameworkMessages.tr.xlf | 18 --- .../xlf/FrameworkMessages.zh-Hans.xlf | 18 --- .../xlf/FrameworkMessages.zh-Hant.xlf | 18 --- 33 files changed, 541 insertions(+), 330 deletions(-) create mode 100644 src/TestFramework/TestFramework.Extensions/Resources/FrameworkExtensionsMessages.Designer.cs create mode 100644 src/TestFramework/TestFramework.Extensions/Resources/FrameworkExtensionsMessages.resx create mode 100644 src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.cs.xlf create mode 100644 src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.de.xlf create mode 100644 src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.es.xlf create mode 100644 src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.fr.xlf create mode 100644 src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.it.xlf create mode 100644 src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.ja.xlf create mode 100644 src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.ko.xlf create mode 100644 src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.pl.xlf create mode 100644 src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.pt-BR.xlf create mode 100644 src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.ru.xlf create mode 100644 src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.tr.xlf create mode 100644 src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.zh-Hans.xlf create mode 100644 src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.zh-Hant.xlf diff --git a/src/TestFramework/TestFramework.Extensions/Attributes/WinUITestTargetAttribute.cs b/src/TestFramework/TestFramework.Extensions/Attributes/WinUITestTargetAttribute.cs index e440b2f31d..d3cd4dd81c 100644 --- a/src/TestFramework/TestFramework.Extensions/Attributes/WinUITestTargetAttribute.cs +++ b/src/TestFramework/TestFramework.Extensions/Attributes/WinUITestTargetAttribute.cs @@ -23,7 +23,7 @@ public WinUITestTargetAttribute(Type applicationType) if (!typeof(UI.Xaml.Application).IsAssignableFrom(applicationType)) { - throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, FrameworkMessages.ArgumentXMustDeriveFromClassY, nameof(applicationType), "Microsoft.UI.Xaml.Application"), nameof(applicationType)); + throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, FrameworkExtensionsMessages.ArgumentXMustDeriveFromClassY, nameof(applicationType), "Microsoft.UI.Xaml.Application"), nameof(applicationType)); } ApplicationType = applicationType; diff --git a/src/TestFramework/TestFramework.Extensions/Attributes/WinUI_UITestMethodAttribute.cs b/src/TestFramework/TestFramework.Extensions/Attributes/WinUI_UITestMethodAttribute.cs index 51eb1189ad..e059339d3a 100644 --- a/src/TestFramework/TestFramework.Extensions/Attributes/WinUI_UITestMethodAttribute.cs +++ b/src/TestFramework/TestFramework.Extensions/Attributes/WinUI_UITestMethodAttribute.cs @@ -62,7 +62,7 @@ internal override async Task ExecuteAsync(ITestMethod testMethod) { // TODO: Code seems to be assuming DeclaringType is never null, but it can be null. // Using 'bang' notation for now to ensure same behavior. - DispatcherQueue dispatcher = GetDispatcherQueue(testMethod.MethodInfo.DeclaringType!.Assembly) ?? throw new InvalidOperationException(FrameworkMessages.AsyncUITestMethodWithNoDispatcherQueue); + DispatcherQueue dispatcher = GetDispatcherQueue(testMethod.MethodInfo.DeclaringType!.Assembly) ?? throw new InvalidOperationException(FrameworkExtensionsMessages.AsyncUITestMethodWithNoDispatcherQueue); if (dispatcher.HasThreadAccess) { try diff --git a/src/TestFramework/TestFramework.Extensions/Resources/FrameworkExtensionsMessages.Designer.cs b/src/TestFramework/TestFramework.Extensions/Resources/FrameworkExtensionsMessages.Designer.cs new file mode 100644 index 0000000000..8591c426b3 --- /dev/null +++ b/src/TestFramework/TestFramework.Extensions/Resources/FrameworkExtensionsMessages.Designer.cs @@ -0,0 +1,81 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace Microsoft.VisualStudio.TestTools.UnitTesting { + using System; + + + /// + /// A strongly-typed resource class, for looking up localized strings, etc. + /// + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class FrameworkExtensionsMessages { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal FrameworkExtensionsMessages() { + } + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager { + get { + if (object.ReferenceEquals(resourceMan, null)) { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Microsoft.VisualStudio.TestTools.UnitTesting.Resources.FrameworkExtensionsMessages", typeof(FrameworkExtensionsMessages).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture { + get { + return resourceCulture; + } + set { + resourceCulture = value; + } + } + + /// + /// Looks up a localized string similar to Type '{0}' is not assignable to '{1}'.. + /// + internal static string ArgumentXMustDeriveFromClassY { + get { + return ResourceManager.GetString("ArgumentXMustDeriveFromClassY", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to UITestMethodAttribute.DispatcherQueue should not be null. To use UITestMethodAttribute within a WinUI Desktop App, remember to set the static UITestMethodAttribute.DispatcherQueue during the test initialization.. + /// + internal static string AsyncUITestMethodWithNoDispatcherQueue { + get { + return ResourceManager.GetString("AsyncUITestMethodWithNoDispatcherQueue", resourceCulture); + } + } + } +} diff --git a/src/TestFramework/TestFramework.Extensions/Resources/FrameworkExtensionsMessages.resx b/src/TestFramework/TestFramework.Extensions/Resources/FrameworkExtensionsMessages.resx new file mode 100644 index 0000000000..7e55257e77 --- /dev/null +++ b/src/TestFramework/TestFramework.Extensions/Resources/FrameworkExtensionsMessages.resx @@ -0,0 +1,130 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Type '{0}' is not assignable to '{1}'. + + - {0} argument name like "applicationType" + - {1} fully qualified class name like "Microsoft.UI.Xaml.Application" + + + + UITestMethodAttribute.DispatcherQueue should not be null. To use UITestMethodAttribute within a WinUI Desktop App, remember to set the static UITestMethodAttribute.DispatcherQueue during the test initialization. + + \ No newline at end of file diff --git a/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.cs.xlf b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.cs.xlf new file mode 100644 index 0000000000..421c707448 --- /dev/null +++ b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.cs.xlf @@ -0,0 +1,20 @@ + + + + + + Type '{0}' is not assignable to '{1}'. + Type '{0}' is not assignable to '{1}'. + + - {0} argument name like "applicationType" + - {1} fully qualified class name like "Microsoft.UI.Xaml.Application" + + + + UITestMethodAttribute.DispatcherQueue should not be null. To use UITestMethodAttribute within a WinUI Desktop App, remember to set the static UITestMethodAttribute.DispatcherQueue during the test initialization. + UITestMethodAttribute.DispatcherQueue nesmí mít hodnotu null. Pokud chcete použít UITestMethodAttribute v desktopové aplikaci WinUI, nezapomeňte během inicializace testu nastavit statický UITestMethodAttribute.DispatcherQueue. + + + + + \ No newline at end of file diff --git a/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.de.xlf b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.de.xlf new file mode 100644 index 0000000000..5f546714df --- /dev/null +++ b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.de.xlf @@ -0,0 +1,20 @@ + + + + + + Type '{0}' is not assignable to '{1}'. + Type '{0}' is not assignable to '{1}'. + + - {0} argument name like "applicationType" + - {1} fully qualified class name like "Microsoft.UI.Xaml.Application" + + + + UITestMethodAttribute.DispatcherQueue should not be null. To use UITestMethodAttribute within a WinUI Desktop App, remember to set the static UITestMethodAttribute.DispatcherQueue during the test initialization. + UITestMethodAttribute.DispatcherQueue darf nicht NULL sein. Um UITestMethodAttribute in einer WinUI-Desktop-App zu verwenden, denken Sie daran, die statische UITestMethodAttribute.DispatcherQueue während der Testinitialisierung festzulegen. + + + + + \ No newline at end of file diff --git a/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.es.xlf b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.es.xlf new file mode 100644 index 0000000000..e41c6e809f --- /dev/null +++ b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.es.xlf @@ -0,0 +1,20 @@ + + + + + + Type '{0}' is not assignable to '{1}'. + Type '{0}' is not assignable to '{1}'. + + - {0} argument name like "applicationType" + - {1} fully qualified class name like "Microsoft.UI.Xaml.Application" + + + + UITestMethodAttribute.DispatcherQueue should not be null. To use UITestMethodAttribute within a WinUI Desktop App, remember to set the static UITestMethodAttribute.DispatcherQueue during the test initialization. + UITestMethodAttribute.DispatcherQueue no debe ser null. Para usar UITestMethodAttribute en una aplicación de escritorio WinUI, recuerde establecer el UITestMethodAttribute.DispatcherQueue estático durante la inicialización de la prueba. + + + + + \ No newline at end of file diff --git a/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.fr.xlf b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.fr.xlf new file mode 100644 index 0000000000..ac782f6a4a --- /dev/null +++ b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.fr.xlf @@ -0,0 +1,20 @@ + + + + + + Type '{0}' is not assignable to '{1}'. + Type '{0}' is not assignable to '{1}'. + + - {0} argument name like "applicationType" + - {1} fully qualified class name like "Microsoft.UI.Xaml.Application" + + + + UITestMethodAttribute.DispatcherQueue should not be null. To use UITestMethodAttribute within a WinUI Desktop App, remember to set the static UITestMethodAttribute.DispatcherQueue during the test initialization. + UITestMethodAttribute.DispatcherQueue ne doit pas avoir la valeur nul. Pour utiliser UITestMethodAttribute dans une application de bureau WinUI, n’oubliez pas de définir l’UITestMethodAttribute.DispatcherQueue statique pendant l’initialisation du test. + + + + + \ No newline at end of file diff --git a/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.it.xlf b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.it.xlf new file mode 100644 index 0000000000..0310e1d695 --- /dev/null +++ b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.it.xlf @@ -0,0 +1,20 @@ + + + + + + Type '{0}' is not assignable to '{1}'. + Type '{0}' is not assignable to '{1}'. + + - {0} argument name like "applicationType" + - {1} fully qualified class name like "Microsoft.UI.Xaml.Application" + + + + UITestMethodAttribute.DispatcherQueue should not be null. To use UITestMethodAttribute within a WinUI Desktop App, remember to set the static UITestMethodAttribute.DispatcherQueue during the test initialization. + UITestMethodAttribute.DispatcherQueue non deve essere Null. Per usare UITestMethodAttribute all'interno di un'app desktop WinUI, ricordarsi di impostare il parametro statico uiTestMethodAttribute.DispatcherQueue durante l'inizializzazione del test. + + + + + \ No newline at end of file diff --git a/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.ja.xlf b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.ja.xlf new file mode 100644 index 0000000000..e34c3b7476 --- /dev/null +++ b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.ja.xlf @@ -0,0 +1,20 @@ + + + + + + Type '{0}' is not assignable to '{1}'. + Type '{0}' is not assignable to '{1}'. + + - {0} argument name like "applicationType" + - {1} fully qualified class name like "Microsoft.UI.Xaml.Application" + + + + UITestMethodAttribute.DispatcherQueue should not be null. To use UITestMethodAttribute within a WinUI Desktop App, remember to set the static UITestMethodAttribute.DispatcherQueue during the test initialization. + UITestMethodAttribute.DispatcherQueue を null にすることはできません。WinUI デスクトップ アプリ内で UITestMethodAttribute を使用するには、テストの初期化中に静的な UITestMethodAttribute.DispatcherQueue を設定してください。 + + + + + \ No newline at end of file diff --git a/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.ko.xlf b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.ko.xlf new file mode 100644 index 0000000000..0fb2720dfd --- /dev/null +++ b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.ko.xlf @@ -0,0 +1,20 @@ + + + + + + Type '{0}' is not assignable to '{1}'. + Type '{0}' is not assignable to '{1}'. + + - {0} argument name like "applicationType" + - {1} fully qualified class name like "Microsoft.UI.Xaml.Application" + + + + UITestMethodAttribute.DispatcherQueue should not be null. To use UITestMethodAttribute within a WinUI Desktop App, remember to set the static UITestMethodAttribute.DispatcherQueue during the test initialization. + UITestMethodAttribute.DispatcherQueue는 null이 아니어야 합니다. WinUI 데스크톱 앱 내에서 UITestMethodAttribute를 사용하려면 테스트 초기화 중에 정적 UITestMethodAttribute.DispatcherQueue를 설정해야 합니다. + + + + + \ No newline at end of file diff --git a/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.pl.xlf b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.pl.xlf new file mode 100644 index 0000000000..f1f0f4e44b --- /dev/null +++ b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.pl.xlf @@ -0,0 +1,20 @@ + + + + + + Type '{0}' is not assignable to '{1}'. + Type '{0}' is not assignable to '{1}'. + + - {0} argument name like "applicationType" + - {1} fully qualified class name like "Microsoft.UI.Xaml.Application" + + + + UITestMethodAttribute.DispatcherQueue should not be null. To use UITestMethodAttribute within a WinUI Desktop App, remember to set the static UITestMethodAttribute.DispatcherQueue during the test initialization. + Element UITestMethodAttribute.DispatcherQueue nie powinien mieć wartości null. Aby użyć atrybutu UITestMethodAttribute w aplikacji klasycznej WinUI, pamiętaj o ustawieniu statycznego atrybutu UITestMethodAttribute.DispatcherQueue podczas inicjowania testu. + + + + + \ No newline at end of file diff --git a/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.pt-BR.xlf b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.pt-BR.xlf new file mode 100644 index 0000000000..9d42ec3cce --- /dev/null +++ b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.pt-BR.xlf @@ -0,0 +1,20 @@ + + + + + + Type '{0}' is not assignable to '{1}'. + Type '{0}' is not assignable to '{1}'. + + - {0} argument name like "applicationType" + - {1} fully qualified class name like "Microsoft.UI.Xaml.Application" + + + + UITestMethodAttribute.DispatcherQueue should not be null. To use UITestMethodAttribute within a WinUI Desktop App, remember to set the static UITestMethodAttribute.DispatcherQueue during the test initialization. + UITestMethodAttribute.DispatcherQueue não deve ser nulo. Para usar UITestMethodAttribute em um aplicativo WinUI Desktop, lembre-se de definir o UITestMethodAttribute.DispatcherQueue estático durante a inicialização do teste. + + + + + \ No newline at end of file diff --git a/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.ru.xlf b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.ru.xlf new file mode 100644 index 0000000000..4f946c550a --- /dev/null +++ b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.ru.xlf @@ -0,0 +1,20 @@ + + + + + + Type '{0}' is not assignable to '{1}'. + Type '{0}' is not assignable to '{1}'. + + - {0} argument name like "applicationType" + - {1} fully qualified class name like "Microsoft.UI.Xaml.Application" + + + + UITestMethodAttribute.DispatcherQueue should not be null. To use UITestMethodAttribute within a WinUI Desktop App, remember to set the static UITestMethodAttribute.DispatcherQueue during the test initialization. + Параметр UITestMethodAttribute.DispatcherQueue не должен иметь значение NULL. Чтобы использовать параметр UITestMethodAttribute в классических приложениях WinUI, не забудьте задать статический параметр UITestMethodAttribute.DispatcherQueue во время инициализации теста. + + + + + \ No newline at end of file diff --git a/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.tr.xlf b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.tr.xlf new file mode 100644 index 0000000000..24d42470da --- /dev/null +++ b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.tr.xlf @@ -0,0 +1,20 @@ + + + + + + Type '{0}' is not assignable to '{1}'. + Type '{0}' is not assignable to '{1}'. + + - {0} argument name like "applicationType" + - {1} fully qualified class name like "Microsoft.UI.Xaml.Application" + + + + UITestMethodAttribute.DispatcherQueue should not be null. To use UITestMethodAttribute within a WinUI Desktop App, remember to set the static UITestMethodAttribute.DispatcherQueue during the test initialization. + UITestMethodAttribute.DispatcherQueue boş olmamalıdır. UITestMethodAttribute'ı bir WinUI Masaüstü Uygulamasında kullanmak için, test başlatma sırasında statik UITestMethodAttribute.DispatcherQueue'yu ayarlamayı unutmayın. + + + + + \ No newline at end of file diff --git a/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.zh-Hans.xlf b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.zh-Hans.xlf new file mode 100644 index 0000000000..85373b311d --- /dev/null +++ b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.zh-Hans.xlf @@ -0,0 +1,20 @@ + + + + + + Type '{0}' is not assignable to '{1}'. + Type '{0}' is not assignable to '{1}'. + + - {0} argument name like "applicationType" + - {1} fully qualified class name like "Microsoft.UI.Xaml.Application" + + + + UITestMethodAttribute.DispatcherQueue should not be null. To use UITestMethodAttribute within a WinUI Desktop App, remember to set the static UITestMethodAttribute.DispatcherQueue during the test initialization. + UITestMethodAttribute.DispatcherQueue 不应为 null。若要在 WinUI 桌面应用中使用 UITestMethodAttribute,请在测试初始化期间设置静态 UITestMethodAttribute.DispatcherQueue。 + + + + + \ No newline at end of file diff --git a/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.zh-Hant.xlf b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.zh-Hant.xlf new file mode 100644 index 0000000000..4296973668 --- /dev/null +++ b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.zh-Hant.xlf @@ -0,0 +1,20 @@ + + + + + + Type '{0}' is not assignable to '{1}'. + Type '{0}' is not assignable to '{1}'. + + - {0} argument name like "applicationType" + - {1} fully qualified class name like "Microsoft.UI.Xaml.Application" + + + + UITestMethodAttribute.DispatcherQueue should not be null. To use UITestMethodAttribute within a WinUI Desktop App, remember to set the static UITestMethodAttribute.DispatcherQueue during the test initialization. + UITestMethodAttribute.DispatcherQueue 不應為 Null。若要在 WinUI 傳統型應用程式內使用 UITestMethodAttribute,請記得在測試初始化期間設定靜態 UITestMethodAttribute.DispatcherQueue。 + + + + + \ No newline at end of file diff --git a/src/TestFramework/TestFramework.Extensions/TestFramework.Extensions.csproj b/src/TestFramework/TestFramework.Extensions/TestFramework.Extensions.csproj index 71181d2f51..3a751c24b1 100644 --- a/src/TestFramework/TestFramework.Extensions/TestFramework.Extensions.csproj +++ b/src/TestFramework/TestFramework.Extensions/TestFramework.Extensions.csproj @@ -96,6 +96,20 @@ + + + True + True + FrameworkExtensionsMessages.resx + + + ResXFileCodeGenerator + FrameworkExtensionsMessages.Designer.cs + Microsoft.VisualStudio.TestTools.UnitTesting + Designer + + + diff --git a/src/TestFramework/TestFramework/Resources/FrameworkMessages.Designer.cs b/src/TestFramework/TestFramework/Resources/FrameworkMessages.Designer.cs index a29e1a07eb..2a8ad9824e 100644 --- a/src/TestFramework/TestFramework/Resources/FrameworkMessages.Designer.cs +++ b/src/TestFramework/TestFramework/Resources/FrameworkMessages.Designer.cs @@ -150,15 +150,6 @@ internal static string AreSameGivenValues { } } - /// - /// Looks up a localized string similar to Type '{0}' is not assignable to '{1}'.. - /// - internal static string ArgumentXMustDeriveFromClassY { - get { - return ResourceManager.GetString("ArgumentXMustDeriveFromClassY", resourceCulture); - } - } - /// /// Looks up a localized string similar to {0} failed. {1}. /// @@ -168,24 +159,6 @@ internal static string AssertionFailed { } } - /// - /// Looks up a localized string similar to async TestMethod with UITestMethodAttribute are not supported. Either remove async or use TestMethodAttribute.. - /// - internal static string AsyncUITestMethodNotSupported { - get { - return ResourceManager.GetString("AsyncUITestMethodNotSupported", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to UITestMethodAttribute.DispatcherQueue should not be null. To use UITestMethodAttribute within a WinUI Desktop App, remember to set the static UITestMethodAttribute.DispatcherQueue during the test initialization.. - /// - internal static string AsyncUITestMethodWithNoDispatcherQueue { - get { - return ResourceManager.GetString("AsyncUITestMethodWithNoDispatcherQueue", resourceCulture); - } - } - /// /// Looks up a localized string similar to Both collections are empty. {0}. /// @@ -258,6 +231,42 @@ internal static string ContainsFail { } } + /// + /// Looks up a localized string similar to Expected collection to contain the specified item. {0}. + /// + internal static string ContainsItemFailMsg { + get { + return ResourceManager.GetString("ContainsItemFailMsg", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Expected at least one item to match the predicate. {0}. + /// + internal static string ContainsPredicateFailMsg { + get { + return ResourceManager.GetString("ContainsPredicateFailMsg", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Expected collection to contain exactly one element but found {1} element(s). {0}. + /// + internal static string ContainsSingleFailMsg { + get { + return ResourceManager.GetString("ContainsSingleFailMsg", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Expected exactly one item to match the predicate but found {1} item(s). {0}. + /// + internal static string ContainsSingleMatchFailMsg { + get { + return ResourceManager.GetString("ContainsSingleMatchFailMsg", resourceCulture); + } + } + /// /// Looks up a localized string similar to {0} ({1}). /// @@ -276,6 +285,24 @@ internal static string DoesNotContainFail { } } + /// + /// Looks up a localized string similar to Expected collection to not contain the specified item. {0}. + /// + internal static string DoesNotContainItemFailMsg { + get { + return ResourceManager.GetString("DoesNotContainItemFailMsg", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Expected no items to match the predicate. {0}. + /// + internal static string DoesNotContainPredicateFailMsg { + get { + return ResourceManager.GetString("DoesNotContainPredicateFailMsg", resourceCulture); + } + } + /// /// Looks up a localized string similar to String '{0}' ends with string '{1}'. {2}. /// @@ -458,60 +485,6 @@ internal static string HasCountFailMsg { } } - /// - /// Looks up a localized string similar to Expected exactly one item to match the predicate. Actual: {1}. {0}. - /// - internal static string ContainsSingleMatchFailMsg { - get { - return ResourceManager.GetString("ContainsSingleMatchFailMsg", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Expected collection to contain exactly one element. Actual: {1}. {0}. - /// - internal static string ContainsSingleFailMsg { - get { - return ResourceManager.GetString("ContainsSingleFailMsg", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Expected collection to contain '{1}'. {0}. - /// - internal static string ContainsItemFailMsg { - get { - return ResourceManager.GetString("ContainsItemFailMsg", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Expected at least one item to match the predicate. {0}. - /// - internal static string ContainsPredicateFailMsg { - get { - return ResourceManager.GetString("ContainsPredicateFailMsg", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Expected collection to not contain '{1}'. {0}. - /// - internal static string DoesNotContainItemFailMsg { - get { - return ResourceManager.GetString("DoesNotContainItemFailMsg", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Expected no items to match the predicate. {0}. - /// - internal static string DoesNotContainPredicateFailMsg { - get { - return ResourceManager.GetString("DoesNotContainPredicateFailMsg", resourceCulture); - } - } - /// /// Looks up a localized string similar to Invalid GitHub ticket URL. /// diff --git a/src/TestFramework/TestFramework/Resources/FrameworkMessages.resx b/src/TestFramework/TestFramework/Resources/FrameworkMessages.resx index b14092e3f4..2306f21622 100644 --- a/src/TestFramework/TestFramework/Resources/FrameworkMessages.resx +++ b/src/TestFramework/TestFramework/Resources/FrameworkMessages.resx @@ -256,12 +256,6 @@ Actual: {2} {0} ({1}) - - async TestMethod with UITestMethodAttribute are not supported. Either remove async or use TestMethodAttribute. - - - UITestMethodAttribute.DispatcherQueue should not be null. To use UITestMethodAttribute within a WinUI Desktop App, remember to set the static UITestMethodAttribute.DispatcherQueue during the test initialization. - Property or method {0} on {1} return type is not assignable to 'IEnumerable'. @@ -274,13 +268,6 @@ Actual: {2} Property or method {0} on {1} returns empty IEnumerable<object[]>. - - Type '{0}' is not assignable to '{1}'. - - - {0} argument name like "applicationType" - - {1} fully qualified class name like "Microsoft.UI.Xaml.Application" - - Dynamic data method '{0}' should be static, parameterless and non-generic. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.cs.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.cs.xlf index 6061aab620..101611f327 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.cs.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.cs.xlf @@ -312,11 +312,6 @@ Skutečnost: {2} {0} ({1}) - - async TestMethod with UITestMethodAttribute are not supported. Either remove async or use TestMethodAttribute. - async TestMethod s atributem UITestMethodAttribute se nepodporují. Buď odeberte async, nebo použijte TestMethodAttribute. - - Property or method {0} on {1} return type is not assignable to 'IEnumerable'. Vlastnost nebo metoda {0} na návratovém typu {1} se nedá přiřadit k „IEnumerable“. @@ -337,19 +332,6 @@ Skutečnost: {2} Vlastnost nebo metoda {0} ve třídě {1} vrací prázdné IEnumerable<object[]>. - - UITestMethodAttribute.DispatcherQueue should not be null. To use UITestMethodAttribute within a WinUI Desktop App, remember to set the static UITestMethodAttribute.DispatcherQueue during the test initialization. - UITestMethodAttribute.DispatcherQueue nesmí mít hodnotu null. Pokud chcete použít UITestMethodAttribute v desktopové aplikaci WinUI, nezapomeňte během inicializace testu nastavit statický UITestMethodAttribute.DispatcherQueue. - - - - Type '{0}' is not assignable to '{1}'. - Typ „{0}“ nelze přiřadit k „{1}“. - - - {0} argument name like "applicationType" - - {1} fully qualified class name like "Microsoft.UI.Xaml.Application" - - Actual value <{2}> is not greater than expected value <{1}>. {0} Skutečná hodnota <{2}> není větší než očekávaná hodnota <{1}>. {0} diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.de.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.de.xlf index a3b2e5236b..5dbd5cc065 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.de.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.de.xlf @@ -312,11 +312,6 @@ Tatsächlich: {2} {0} ({1}) - - async TestMethod with UITestMethodAttribute are not supported. Either remove async or use TestMethodAttribute. - "async TestMethod" wird mit UITestMethodAttribute nicht unterstützt. Entfernen Sie "async", oder verwenden Sie TestMethodAttribute. - - Property or method {0} on {1} return type is not assignable to 'IEnumerable'. Eigenschaft oder Methode {0} für {1} Rückgabetyp kann „IEnumerable“ nicht zugewiesen werden. @@ -337,19 +332,6 @@ Tatsächlich: {2} Eigenschaft oder Methode "{0}" in "{1}" gibt leeres IEnumerable<object[]> zurück. - - UITestMethodAttribute.DispatcherQueue should not be null. To use UITestMethodAttribute within a WinUI Desktop App, remember to set the static UITestMethodAttribute.DispatcherQueue during the test initialization. - UITestMethodAttribute.DispatcherQueue darf nicht NULL sein. Um UITestMethodAttribute in einer WinUI-Desktop-App zu verwenden, denken Sie daran, die statische UITestMethodAttribute.DispatcherQueue während der Testinitialisierung festzulegen. - - - - Type '{0}' is not assignable to '{1}'. - Der Typ "{0}" kann nicht "{1}" zugewiesen werden. - - - {0} argument name like "applicationType" - - {1} fully qualified class name like "Microsoft.UI.Xaml.Application" - - Actual value <{2}> is not greater than expected value <{1}>. {0} Der tatsächliche Wert <{2}> ist nicht größer als der erwartete Wert <{1}>. {0} diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.es.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.es.xlf index ffe46db07b..478263aa43 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.es.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.es.xlf @@ -312,11 +312,6 @@ Real: {2} {0} ({1}) - - async TestMethod with UITestMethodAttribute are not supported. Either remove async or use TestMethodAttribute. - async TestMethod con UITestMethodAttribute no son compatibles. Quite async o use TestMethodAttribute. - - Property or method {0} on {1} return type is not assignable to 'IEnumerable'. La propiedad o el método {0} en el tipo de retorno {1} no se puede asignar a "IEnumerable". @@ -337,19 +332,6 @@ Real: {2} La propiedad o el método {0} en {1} devuelve un elemento IEnumerable<object[]> vacío. - - UITestMethodAttribute.DispatcherQueue should not be null. To use UITestMethodAttribute within a WinUI Desktop App, remember to set the static UITestMethodAttribute.DispatcherQueue during the test initialization. - UITestMethodAttribute.DispatcherQueue no debe ser null. Para usar UITestMethodAttribute en una aplicación de escritorio WinUI, recuerde establecer el UITestMethodAttribute.DispatcherQueue estático durante la inicialización de la prueba. - - - - Type '{0}' is not assignable to '{1}'. - Tipo "{0}" no se puede asignar a "{1}". - - - {0} argument name like "applicationType" - - {1} fully qualified class name like "Microsoft.UI.Xaml.Application" - - Actual value <{2}> is not greater than expected value <{1}>. {0} El valor real <{2}> no es mayor que el valor esperado <{1}>. {0} diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.fr.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.fr.xlf index f92dade652..aa3992bd0d 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.fr.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.fr.xlf @@ -312,11 +312,6 @@ Réel : {2} {0} ({1}) - - async TestMethod with UITestMethodAttribute are not supported. Either remove async or use TestMethodAttribute. - async TestMethod avec UITestMethodAttribute ne sont pas pris en charge. Supprimez async ou utilisez TestMethodAttribute. - - Property or method {0} on {1} return type is not assignable to 'IEnumerable'. La propriété ou la méthode {0} sur le type de retour {1} ne peut pas être attribuée à « IEnumerable ». @@ -337,19 +332,6 @@ Réel : {2} La propriété ou la méthode {0} sur {1} retourne un IEnumerable<object[]> vide. - - UITestMethodAttribute.DispatcherQueue should not be null. To use UITestMethodAttribute within a WinUI Desktop App, remember to set the static UITestMethodAttribute.DispatcherQueue during the test initialization. - UITestMethodAttribute.DispatcherQueue ne doit pas avoir la valeur nul. Pour utiliser UITestMethodAttribute dans une application de bureau WinUI, n’oubliez pas de définir l’UITestMethodAttribute.DispatcherQueue statique pendant l’initialisation du test. - - - - Type '{0}' is not assignable to '{1}'. - Impossible d'assigner le type '{0}' à '{1}'. - - - {0} argument name like "applicationType" - - {1} fully qualified class name like "Microsoft.UI.Xaml.Application" - - Actual value <{2}> is not greater than expected value <{1}>. {0} La valeur réelle <{2}> n’est pas supérieure à la valeur attendue <{1}>. {0} diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.it.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.it.xlf index 6b7c97798d..8f08e8cdf7 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.it.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.it.xlf @@ -312,11 +312,6 @@ Effettivo: {2} {0} ({1}) - - async TestMethod with UITestMethodAttribute are not supported. Either remove async or use TestMethodAttribute. - L'elemento async TestMethod con UITestMethodAttribute non è supportato. Rimuovere async o usare TestMethodAttribute. - - Property or method {0} on {1} return type is not assignable to 'IEnumerable'. La proprietà o il metodo {0} su {1} tipo restituito non è assegnabile a 'IEnumerable'. @@ -337,19 +332,6 @@ Effettivo: {2} La proprietà o il metodo {0} nella classe {1} restituisce un elemento IEnumerable<object[]> vuoto. - - UITestMethodAttribute.DispatcherQueue should not be null. To use UITestMethodAttribute within a WinUI Desktop App, remember to set the static UITestMethodAttribute.DispatcherQueue during the test initialization. - UITestMethodAttribute.DispatcherQueue non deve essere Null. Per usare UITestMethodAttribute all'interno di un'app desktop WinUI, ricordarsi di impostare il parametro statico uiTestMethodAttribute.DispatcherQueue durante l'inizializzazione del test. - - - - Type '{0}' is not assignable to '{1}'. - Il tipo '{0}' non è assegnabile a '{1}'. - - - {0} argument name like "applicationType" - - {1} fully qualified class name like "Microsoft.UI.Xaml.Application" - - Actual value <{2}> is not greater than expected value <{1}>. {0} Il valore effettivo <{2}> non è maggiore del valore previsto <{1}>. {0} diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ja.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ja.xlf index a2ff722169..4caa825f52 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ja.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ja.xlf @@ -312,11 +312,6 @@ Actual: {2} {0} ({1}) - - async TestMethod with UITestMethodAttribute are not supported. Either remove async or use TestMethodAttribute. - UITestMethodAttribute が指定された非同期の TestMethod はサポートされていません。非同期を削除するか、TestMethodAttribute を使用してください。 - - Property or method {0} on {1} return type is not assignable to 'IEnumerable'. {1} 戻り値の型のプロパティまたはメソッド {0} は、'IEnumerable' に割り当てできません。 @@ -337,19 +332,6 @@ Actual: {2} {1} 上のプロパティまたはメソッド {0} は空の IEnumerable<object[]> を返します。 - - UITestMethodAttribute.DispatcherQueue should not be null. To use UITestMethodAttribute within a WinUI Desktop App, remember to set the static UITestMethodAttribute.DispatcherQueue during the test initialization. - UITestMethodAttribute.DispatcherQueue を null にすることはできません。WinUI デスクトップ アプリ内で UITestMethodAttribute を使用するには、テストの初期化中に静的な UITestMethodAttribute.DispatcherQueue を設定してください。 - - - - Type '{0}' is not assignable to '{1}'. - 型 '{0}' を '{1}' に割り当てることはできません。 - - - {0} argument name like "applicationType" - - {1} fully qualified class name like "Microsoft.UI.Xaml.Application" - - Actual value <{2}> is not greater than expected value <{1}>. {0} 実際の値 <{2}> は、予期された値 <{1}> より大きくありません。{0} diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ko.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ko.xlf index 02189b3259..c149d66b93 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ko.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ko.xlf @@ -312,11 +312,6 @@ Actual: {2} {0}({1}) - - async TestMethod with UITestMethodAttribute are not supported. Either remove async or use TestMethodAttribute. - async TestMethod with UITestMethodAttribute는 지원되지 않습니다. async를 제거하거나 TestMethodAttribute를 사용하세요. - - Property or method {0} on {1} return type is not assignable to 'IEnumerable'. {1} 반환 형식의 속성 또는 메서드 {0}은(는) 'IEnumerable'에 할당할 수 없습니다. @@ -337,19 +332,6 @@ Actual: {2} {1}의 속성 또는 메서드 {0}이(가) 빈 IEnumerable<object[]>를 반환합니다. - - UITestMethodAttribute.DispatcherQueue should not be null. To use UITestMethodAttribute within a WinUI Desktop App, remember to set the static UITestMethodAttribute.DispatcherQueue during the test initialization. - UITestMethodAttribute.DispatcherQueue는 null이 아니어야 합니다. WinUI 데스크톱 앱 내에서 UITestMethodAttribute를 사용하려면 테스트 초기화 중에 정적 UITestMethodAttribute.DispatcherQueue를 설정해야 합니다. - - - - Type '{0}' is not assignable to '{1}'. - '{0}' 형식은 '{1}'에 할당할 수 없습니다. - - - {0} argument name like "applicationType" - - {1} fully qualified class name like "Microsoft.UI.Xaml.Application" - - Actual value <{2}> is not greater than expected value <{1}>. {0} 실제 값 <{2}>은(는)는 예상 값 <{1}>보다 크지 않습니다. {0} diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pl.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pl.xlf index ed5702458b..8bd972fb05 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pl.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pl.xlf @@ -312,11 +312,6 @@ Rzeczywiste: {2} {0} ({1}) - - async TestMethod with UITestMethodAttribute are not supported. Either remove async or use TestMethodAttribute. - asynchroniczna metoda TestMethod z elementem UITestMethodAttribute nie są obsługiwane. Usuń element asynchroniczny lub użyj elementu TestMethodAttribute. - - Property or method {0} on {1} return type is not assignable to 'IEnumerable'. Właściwości lub metody {0} dla zwracanego typu {1} nie można przypisać do elementu „IEnumerable”. @@ -337,19 +332,6 @@ Rzeczywiste: {2} Właściwość lub metoda {0} w elemencie {1} zwraca pusty interfejs IEnumerable<object[]>. - - UITestMethodAttribute.DispatcherQueue should not be null. To use UITestMethodAttribute within a WinUI Desktop App, remember to set the static UITestMethodAttribute.DispatcherQueue during the test initialization. - Element UITestMethodAttribute.DispatcherQueue nie powinien mieć wartości null. Aby użyć atrybutu UITestMethodAttribute w aplikacji klasycznej WinUI, pamiętaj o ustawieniu statycznego atrybutu UITestMethodAttribute.DispatcherQueue podczas inicjowania testu. - - - - Type '{0}' is not assignable to '{1}'. - Typu „{0}” nie można przypisać do typu „{1}”. - - - {0} argument name like "applicationType" - - {1} fully qualified class name like "Microsoft.UI.Xaml.Application" - - Actual value <{2}> is not greater than expected value <{1}>. {0} Wartość rzeczywista <{2}> nie jest większa niż oczekiwana wartość <{1}>. {0} diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf index 40f792c33e..517ff7ea57 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf @@ -312,11 +312,6 @@ Real: {2} {0} ({1}) - - async TestMethod with UITestMethodAttribute are not supported. Either remove async or use TestMethodAttribute. - TestMethod assíncrono com UITestMethodAttribute não têm suporte. Remova o assíncrono ou use o TestMethodAttribute. - - Property or method {0} on {1} return type is not assignable to 'IEnumerable'. A propriedade ou o método {0} no tipo de retorno {1} não podem ser atribuídos a "IEnumerable". @@ -337,19 +332,6 @@ Real: {2} A propriedade ou o método {0} em {1} retorna um IEnumerable<object[]> vazio. - - UITestMethodAttribute.DispatcherQueue should not be null. To use UITestMethodAttribute within a WinUI Desktop App, remember to set the static UITestMethodAttribute.DispatcherQueue during the test initialization. - UITestMethodAttribute.DispatcherQueue não deve ser nulo. Para usar UITestMethodAttribute em um aplicativo WinUI Desktop, lembre-se de definir o UITestMethodAttribute.DispatcherQueue estático durante a inicialização do teste. - - - - Type '{0}' is not assignable to '{1}'. - Tipo '{0}' não é atribuível a '{1}'. - - - {0} argument name like "applicationType" - - {1} fully qualified class name like "Microsoft.UI.Xaml.Application" - - Actual value <{2}> is not greater than expected value <{1}>. {0} O valor <{2}> real não é maior que o valor esperado <{1}>. {0} diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ru.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ru.xlf index 3b53ea9cad..30777fbe1c 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ru.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ru.xlf @@ -312,11 +312,6 @@ Actual: {2} {0} ({1}) - - async TestMethod with UITestMethodAttribute are not supported. Either remove async or use TestMethodAttribute. - Асинхронный метод TestMethod с UITestMethodAttribute не поддерживается. Удалите префикс async или используйте TestMethodAttribute. - - Property or method {0} on {1} return type is not assignable to 'IEnumerable'. Свойство или метод {0} в {1} тип возвращаемого значения не может быть назначен "IEnumerable". @@ -337,19 +332,6 @@ Actual: {2} Свойство или метод {0} класса {1} возвращает пустой IEnumerable<object[]>. - - UITestMethodAttribute.DispatcherQueue should not be null. To use UITestMethodAttribute within a WinUI Desktop App, remember to set the static UITestMethodAttribute.DispatcherQueue during the test initialization. - Параметр UITestMethodAttribute.DispatcherQueue не должен иметь значение NULL. Чтобы использовать параметр UITestMethodAttribute в классических приложениях WinUI, не забудьте задать статический параметр UITestMethodAttribute.DispatcherQueue во время инициализации теста. - - - - Type '{0}' is not assignable to '{1}'. - Тип "{0}" не может быть назначен "{1}". - - - {0} argument name like "applicationType" - - {1} fully qualified class name like "Microsoft.UI.Xaml.Application" - - Actual value <{2}> is not greater than expected value <{1}>. {0} Действительное значение <{2}> не больше ожидаемого значения <{1}>. {0} diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.tr.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.tr.xlf index ee3bf19693..30a31a43e5 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.tr.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.tr.xlf @@ -312,11 +312,6 @@ Gerçekte olan: {2} {0} ({1}) - - async TestMethod with UITestMethodAttribute are not supported. Either remove async or use TestMethodAttribute. - UITestMethodAttribute özniteliğine sahip async TestMethod metodu desteklenmiyor. async ifadesini kaldırın ya da TestMethodAttribute özniteliğini kullanın. - - Property or method {0} on {1} return type is not assignable to 'IEnumerable'. {1} dönüş türündeki {0} özelliği veya yöntemi 'IEnumerable' öğesine atanamaz. @@ -337,19 +332,6 @@ Gerçekte olan: {2} {1} üzerindeki {0} özelliği veya metodu boş IEnumerable<object[]> döndürür. - - UITestMethodAttribute.DispatcherQueue should not be null. To use UITestMethodAttribute within a WinUI Desktop App, remember to set the static UITestMethodAttribute.DispatcherQueue during the test initialization. - UITestMethodAttribute.DispatcherQueue boş olmamalıdır. UITestMethodAttribute'ı bir WinUI Masaüstü Uygulamasında kullanmak için, test başlatma sırasında statik UITestMethodAttribute.DispatcherQueue'yu ayarlamayı unutmayın. - - - - Type '{0}' is not assignable to '{1}'. - '{0}' tipi '{1}'ye atanamaz. - - - {0} argument name like "applicationType" - - {1} fully qualified class name like "Microsoft.UI.Xaml.Application" - - Actual value <{2}> is not greater than expected value <{1}>. {0} Geçerli <{2}> değeri, beklenen <{1}> değerinden daha büyük değil. {0} diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf index 35d48a2ea6..84a637d30b 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf @@ -312,11 +312,6 @@ Actual: {2} {0} ({1}) - - async TestMethod with UITestMethodAttribute are not supported. Either remove async or use TestMethodAttribute. - 不支持具有 UITestMethodAttribute 的异步 TestMethod。请删除异步或使用 TestMethodAttribute。 - - Property or method {0} on {1} return type is not assignable to 'IEnumerable'. {1} 返回类型上的属性或方法 {0} 不能分配给 "IEnumerable"。 @@ -337,19 +332,6 @@ Actual: {2} {1} 上的属性或方法 {0} 返回空 IEnumerable<object[]>。 - - UITestMethodAttribute.DispatcherQueue should not be null. To use UITestMethodAttribute within a WinUI Desktop App, remember to set the static UITestMethodAttribute.DispatcherQueue during the test initialization. - UITestMethodAttribute.DispatcherQueue 不应为 null。若要在 WinUI 桌面应用中使用 UITestMethodAttribute,请在测试初始化期间设置静态 UITestMethodAttribute.DispatcherQueue。 - - - - Type '{0}' is not assignable to '{1}'. - 类型“{0}”不能分配给“{1}”。 - - - {0} argument name like "applicationType" - - {1} fully qualified class name like "Microsoft.UI.Xaml.Application" - - Actual value <{2}> is not greater than expected value <{1}>. {0} 实际值 <{2}> 不大于预期值 <{1}>。{0} diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf index d38aea41fb..9a1cb2f02a 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf @@ -312,11 +312,6 @@ Actual: {2} {0} ({1}) - - async TestMethod with UITestMethodAttribute are not supported. Either remove async or use TestMethodAttribute. - 不支援有 UITestMethodAttribute 的 async TestMethod。請移除 async 或使用 TestMethodAttribute。 - - Property or method {0} on {1} return type is not assignable to 'IEnumerable'. {1} 傳回類型上的屬性或方法 {0} 無法指派給 'IEnumerable'。 @@ -337,19 +332,6 @@ Actual: {2} {1} 上的屬性或方法 {0} 傳回空的 IEnumerable<object[]>。 - - UITestMethodAttribute.DispatcherQueue should not be null. To use UITestMethodAttribute within a WinUI Desktop App, remember to set the static UITestMethodAttribute.DispatcherQueue during the test initialization. - UITestMethodAttribute.DispatcherQueue 不應為 Null。若要在 WinUI 傳統型應用程式內使用 UITestMethodAttribute,請記得在測試初始化期間設定靜態 UITestMethodAttribute.DispatcherQueue。 - - - - Type '{0}' is not assignable to '{1}'. - 無法將類型 '{0}' {0} 指派給 '{1}。 - - - {0} argument name like "applicationType" - - {1} fully qualified class name like "Microsoft.UI.Xaml.Application" - - Actual value <{2}> is not greater than expected value <{1}>. {0} 實際值 <{2}> 不大於預期值 <{1}>。{0} From 54d61b355ad07cfb8bc95a7fa09c75affac86ada Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Thu, 10 Jul 2025 01:10:43 +1000 Subject: [PATCH 172/541] update to Polyfill 9.0.0-beta.10 (#5952) --- Directory.Packages.props | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Directory.Packages.props b/Directory.Packages.props index 62fbf8a6e9..f184570289 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -54,7 +54,7 @@ - + From fc1a3f4b422245555feea0b0d23b1d91ba965d7e Mon Sep 17 00:00:00 2001 From: dotnet bot Date: Wed, 9 Jul 2025 17:17:42 +0200 Subject: [PATCH 173/541] Localized file check-in by OneLocBuild Task: Build definition ID 1218: Build ID 2746297 --- .../xlf/CodeFixResources.de.xlf | 2 +- .../xlf/CodeFixResources.ja.xlf | 2 +- src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf | 8 ++++---- src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf | 8 ++++---- src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf | 8 ++++---- src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf | 8 ++++---- 6 files changed, 18 insertions(+), 18 deletions(-) diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.de.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.de.xlf index c33af08a87..e1966e09a0 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.de.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.de.xlf @@ -74,7 +74,7 @@ Use 'Assert.{0}' instead of 'StringAssert' - Use 'Assert.{0}' instead of 'StringAssert' + Verwenden Sie „Assert.{0}“ anstelle von „StringAssert“. diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ja.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ja.xlf index 98feef9225..f5a9896efa 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ja.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ja.xlf @@ -74,7 +74,7 @@ Use 'Assert.{0}' instead of 'StringAssert' - Use 'Assert.{0}' instead of 'StringAssert' + 'StringAssert' の代わりに 'Assert.{0}' を使用 diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf index 04ba4c523b..b0f6603c26 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf @@ -279,12 +279,12 @@ Der Typ, der diese Methoden deklariert, sollte auch die folgenden Regeln beachte DataRow argument types do not match method parameter types. {0} - DataRow argument types do not match method parameter types. {0} + DataRow-Argumenttypen stimmen nicht mit Methodenparametertypen überein. {0} Parameter '{0}' expects type '{1}', but the provided value has type '{2}' - Parameter '{0}' expects type '{1}', but the provided value has type '{2}' + Der Parameter „{0}“ erwartet den Typ „{1}“, aber der übergebene Wert hat den Typ „{2}“. @@ -540,12 +540,12 @@ Der Typ, der diese Methoden deklariert, sollte auch die folgenden Regeln beachte Use 'Assert.{0}' instead of 'StringAssert.{1}' - Use 'Assert.{0}' instead of 'StringAssert.{1}' + Verwenden Sie „Assert.{0}“ anstelle von „StringAssert.{1}“. Use 'Assert' instead of 'StringAssert' - Use 'Assert' instead of 'StringAssert' + Verwenden Sie „Assert“ anstelle von „StringAssert“. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf index 66a0925739..66862bdfae 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf @@ -278,12 +278,12 @@ El tipo que declara estos métodos también debe respetar las reglas siguientes: DataRow argument types do not match method parameter types. {0} - DataRow argument types do not match method parameter types. {0} + Los tipos de argumentos DataRow no coinciden con los tipos de parámetro de método. {0} Parameter '{0}' expects type '{1}', but the provided value has type '{2}' - Parameter '{0}' expects type '{1}', but the provided value has type '{2}' + El parámetro '{0}' espera el tipo '{1}', pero el valor proporcionado tiene el tipo '{2}' @@ -539,12 +539,12 @@ El tipo que declara estos métodos también debe respetar las reglas siguientes: Use 'Assert.{0}' instead of 'StringAssert.{1}' - Use 'Assert.{0}' instead of 'StringAssert.{1}' + Use 'Assert'{0}. en lugar de 'StringAssert.'{1} Use 'Assert' instead of 'StringAssert' - Use 'Assert' instead of 'StringAssert' + Usar 'Assert' en lugar de 'StringAssert' diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf index 9698eb2cc8..ceb5ac37c8 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf @@ -278,12 +278,12 @@ Le type doit être une classe DataRow argument types do not match method parameter types. {0} - DataRow argument types do not match method parameter types. {0} + Les types d’argument DataRow ne correspondent pas aux types de paramètre de la méthode. {0} Parameter '{0}' expects type '{1}', but the provided value has type '{2}' - Parameter '{0}' expects type '{1}', but the provided value has type '{2}' + Le paramètre « {0} » attend un type « {1} », mais la valeur fournie a un type « {2} » @@ -539,12 +539,12 @@ Le type doit être une classe Use 'Assert.{0}' instead of 'StringAssert.{1}' - Use 'Assert.{0}' instead of 'StringAssert.{1}' + Utilisez « Assert.{0} » au lieu de « StringAssert.{1} » Use 'Assert' instead of 'StringAssert' - Use 'Assert' instead of 'StringAssert' + Utilisez « Assert » au lieu de « StringAssert » diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf index 75fcf251ba..7c6f99794c 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf @@ -278,12 +278,12 @@ The type declaring these methods should also respect the following rules: DataRow argument types do not match method parameter types. {0} - DataRow argument types do not match method parameter types. {0} + DataRow 引数の型がメソッド パラメーターの型と一致しません。 {0} Parameter '{0}' expects type '{1}', but the provided value has type '{2}' - Parameter '{0}' expects type '{1}', but the provided value has type '{2}' + パラメーター '{0}' の型は '{1}' が想定されていますが、指定された値の型は '{2}' です @@ -539,12 +539,12 @@ The type declaring these methods should also respect the following rules: Use 'Assert.{0}' instead of 'StringAssert.{1}' - Use 'Assert.{0}' instead of 'StringAssert.{1}' + 'StringAssert.{1}' の代わりに 'Assert.{0}' を使用します Use 'Assert' instead of 'StringAssert' - Use 'Assert' instead of 'StringAssert' + 'StringAssert' の代わりに 'Assert' を使用 From be7baa1ba8ec415f521adfcaf94e97f42633f154 Mon Sep 17 00:00:00 2001 From: dotnet bot Date: Wed, 9 Jul 2025 17:22:03 +0200 Subject: [PATCH 174/541] Localized file check-in by OneLocBuild Task: Build definition ID 1218: Build ID 2746297 --- .../Resources/xlf/FrameworkExtensionsMessages.cs.xlf | 2 +- .../Resources/xlf/FrameworkExtensionsMessages.de.xlf | 2 +- .../Resources/xlf/FrameworkExtensionsMessages.es.xlf | 2 +- .../Resources/xlf/FrameworkExtensionsMessages.fr.xlf | 2 +- .../Resources/xlf/FrameworkExtensionsMessages.it.xlf | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.cs.xlf b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.cs.xlf index 421c707448..2d61b7f825 100644 --- a/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.cs.xlf +++ b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.cs.xlf @@ -12,7 +12,7 @@ UITestMethodAttribute.DispatcherQueue should not be null. To use UITestMethodAttribute within a WinUI Desktop App, remember to set the static UITestMethodAttribute.DispatcherQueue during the test initialization. - UITestMethodAttribute.DispatcherQueue nesmí mít hodnotu null. Pokud chcete použít UITestMethodAttribute v desktopové aplikaci WinUI, nezapomeňte během inicializace testu nastavit statický UITestMethodAttribute.DispatcherQueue. + UITestMethodAttribute.DispatcherQueue should not be null. To use UITestMethodAttribute within a WinUI Desktop App, remember to set the static UITestMethodAttribute.DispatcherQueue during the test initialization. diff --git a/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.de.xlf b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.de.xlf index 5f546714df..519b1af1a4 100644 --- a/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.de.xlf +++ b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.de.xlf @@ -12,7 +12,7 @@ UITestMethodAttribute.DispatcherQueue should not be null. To use UITestMethodAttribute within a WinUI Desktop App, remember to set the static UITestMethodAttribute.DispatcherQueue during the test initialization. - UITestMethodAttribute.DispatcherQueue darf nicht NULL sein. Um UITestMethodAttribute in einer WinUI-Desktop-App zu verwenden, denken Sie daran, die statische UITestMethodAttribute.DispatcherQueue während der Testinitialisierung festzulegen. + UITestMethodAttribute.DispatcherQueue should not be null. To use UITestMethodAttribute within a WinUI Desktop App, remember to set the static UITestMethodAttribute.DispatcherQueue during the test initialization. diff --git a/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.es.xlf b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.es.xlf index e41c6e809f..8ce7712404 100644 --- a/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.es.xlf +++ b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.es.xlf @@ -12,7 +12,7 @@ UITestMethodAttribute.DispatcherQueue should not be null. To use UITestMethodAttribute within a WinUI Desktop App, remember to set the static UITestMethodAttribute.DispatcherQueue during the test initialization. - UITestMethodAttribute.DispatcherQueue no debe ser null. Para usar UITestMethodAttribute en una aplicación de escritorio WinUI, recuerde establecer el UITestMethodAttribute.DispatcherQueue estático durante la inicialización de la prueba. + UITestMethodAttribute.DispatcherQueue should not be null. To use UITestMethodAttribute within a WinUI Desktop App, remember to set the static UITestMethodAttribute.DispatcherQueue during the test initialization. diff --git a/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.fr.xlf b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.fr.xlf index ac782f6a4a..b3995a4086 100644 --- a/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.fr.xlf +++ b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.fr.xlf @@ -12,7 +12,7 @@ UITestMethodAttribute.DispatcherQueue should not be null. To use UITestMethodAttribute within a WinUI Desktop App, remember to set the static UITestMethodAttribute.DispatcherQueue during the test initialization. - UITestMethodAttribute.DispatcherQueue ne doit pas avoir la valeur nul. Pour utiliser UITestMethodAttribute dans une application de bureau WinUI, n’oubliez pas de définir l’UITestMethodAttribute.DispatcherQueue statique pendant l’initialisation du test. + UITestMethodAttribute.DispatcherQueue should not be null. To use UITestMethodAttribute within a WinUI Desktop App, remember to set the static UITestMethodAttribute.DispatcherQueue during the test initialization. diff --git a/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.it.xlf b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.it.xlf index 0310e1d695..870c84f4bc 100644 --- a/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.it.xlf +++ b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.it.xlf @@ -12,7 +12,7 @@ UITestMethodAttribute.DispatcherQueue should not be null. To use UITestMethodAttribute within a WinUI Desktop App, remember to set the static UITestMethodAttribute.DispatcherQueue during the test initialization. - UITestMethodAttribute.DispatcherQueue non deve essere Null. Per usare UITestMethodAttribute all'interno di un'app desktop WinUI, ricordarsi di impostare il parametro statico uiTestMethodAttribute.DispatcherQueue durante l'inizializzazione del test. + UITestMethodAttribute.DispatcherQueue should not be null. To use UITestMethodAttribute within a WinUI Desktop App, remember to set the static UITestMethodAttribute.DispatcherQueue during the test initialization. From 7195ab44005cc05f708bbe30b71b02e956d5412d Mon Sep 17 00:00:00 2001 From: dotnet bot Date: Wed, 9 Jul 2025 17:22:20 +0200 Subject: [PATCH 175/541] Localized file check-in by OneLocBuild Task: Build definition ID 1218: Build ID 2746297 --- .../Resources/xlf/FrameworkExtensionsMessages.ja.xlf | 2 +- .../Resources/xlf/FrameworkExtensionsMessages.ko.xlf | 2 +- .../Resources/xlf/FrameworkExtensionsMessages.pl.xlf | 2 +- .../Resources/xlf/FrameworkExtensionsMessages.pt-BR.xlf | 2 +- .../Resources/xlf/FrameworkExtensionsMessages.ru.xlf | 2 +- .../Resources/xlf/FrameworkExtensionsMessages.tr.xlf | 2 +- .../Resources/xlf/FrameworkExtensionsMessages.zh-Hans.xlf | 2 +- .../Resources/xlf/FrameworkExtensionsMessages.zh-Hant.xlf | 2 +- 8 files changed, 8 insertions(+), 8 deletions(-) diff --git a/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.ja.xlf b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.ja.xlf index e34c3b7476..6bb08aa1d2 100644 --- a/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.ja.xlf +++ b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.ja.xlf @@ -12,7 +12,7 @@ UITestMethodAttribute.DispatcherQueue should not be null. To use UITestMethodAttribute within a WinUI Desktop App, remember to set the static UITestMethodAttribute.DispatcherQueue during the test initialization. - UITestMethodAttribute.DispatcherQueue を null にすることはできません。WinUI デスクトップ アプリ内で UITestMethodAttribute を使用するには、テストの初期化中に静的な UITestMethodAttribute.DispatcherQueue を設定してください。 + UITestMethodAttribute.DispatcherQueue should not be null. To use UITestMethodAttribute within a WinUI Desktop App, remember to set the static UITestMethodAttribute.DispatcherQueue during the test initialization. diff --git a/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.ko.xlf b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.ko.xlf index 0fb2720dfd..c588d65aea 100644 --- a/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.ko.xlf +++ b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.ko.xlf @@ -12,7 +12,7 @@ UITestMethodAttribute.DispatcherQueue should not be null. To use UITestMethodAttribute within a WinUI Desktop App, remember to set the static UITestMethodAttribute.DispatcherQueue during the test initialization. - UITestMethodAttribute.DispatcherQueue는 null이 아니어야 합니다. WinUI 데스크톱 앱 내에서 UITestMethodAttribute를 사용하려면 테스트 초기화 중에 정적 UITestMethodAttribute.DispatcherQueue를 설정해야 합니다. + UITestMethodAttribute.DispatcherQueue should not be null. To use UITestMethodAttribute within a WinUI Desktop App, remember to set the static UITestMethodAttribute.DispatcherQueue during the test initialization. diff --git a/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.pl.xlf b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.pl.xlf index f1f0f4e44b..580d39e0d5 100644 --- a/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.pl.xlf +++ b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.pl.xlf @@ -12,7 +12,7 @@ UITestMethodAttribute.DispatcherQueue should not be null. To use UITestMethodAttribute within a WinUI Desktop App, remember to set the static UITestMethodAttribute.DispatcherQueue during the test initialization. - Element UITestMethodAttribute.DispatcherQueue nie powinien mieć wartości null. Aby użyć atrybutu UITestMethodAttribute w aplikacji klasycznej WinUI, pamiętaj o ustawieniu statycznego atrybutu UITestMethodAttribute.DispatcherQueue podczas inicjowania testu. + UITestMethodAttribute.DispatcherQueue should not be null. To use UITestMethodAttribute within a WinUI Desktop App, remember to set the static UITestMethodAttribute.DispatcherQueue during the test initialization. diff --git a/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.pt-BR.xlf b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.pt-BR.xlf index 9d42ec3cce..f8e93799f7 100644 --- a/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.pt-BR.xlf +++ b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.pt-BR.xlf @@ -12,7 +12,7 @@ UITestMethodAttribute.DispatcherQueue should not be null. To use UITestMethodAttribute within a WinUI Desktop App, remember to set the static UITestMethodAttribute.DispatcherQueue during the test initialization. - UITestMethodAttribute.DispatcherQueue não deve ser nulo. Para usar UITestMethodAttribute em um aplicativo WinUI Desktop, lembre-se de definir o UITestMethodAttribute.DispatcherQueue estático durante a inicialização do teste. + UITestMethodAttribute.DispatcherQueue should not be null. To use UITestMethodAttribute within a WinUI Desktop App, remember to set the static UITestMethodAttribute.DispatcherQueue during the test initialization. diff --git a/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.ru.xlf b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.ru.xlf index 4f946c550a..44c4f3da10 100644 --- a/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.ru.xlf +++ b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.ru.xlf @@ -12,7 +12,7 @@ UITestMethodAttribute.DispatcherQueue should not be null. To use UITestMethodAttribute within a WinUI Desktop App, remember to set the static UITestMethodAttribute.DispatcherQueue during the test initialization. - Параметр UITestMethodAttribute.DispatcherQueue не должен иметь значение NULL. Чтобы использовать параметр UITestMethodAttribute в классических приложениях WinUI, не забудьте задать статический параметр UITestMethodAttribute.DispatcherQueue во время инициализации теста. + UITestMethodAttribute.DispatcherQueue should not be null. To use UITestMethodAttribute within a WinUI Desktop App, remember to set the static UITestMethodAttribute.DispatcherQueue during the test initialization. diff --git a/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.tr.xlf b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.tr.xlf index 24d42470da..3af2d1d095 100644 --- a/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.tr.xlf +++ b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.tr.xlf @@ -12,7 +12,7 @@ UITestMethodAttribute.DispatcherQueue should not be null. To use UITestMethodAttribute within a WinUI Desktop App, remember to set the static UITestMethodAttribute.DispatcherQueue during the test initialization. - UITestMethodAttribute.DispatcherQueue boş olmamalıdır. UITestMethodAttribute'ı bir WinUI Masaüstü Uygulamasında kullanmak için, test başlatma sırasında statik UITestMethodAttribute.DispatcherQueue'yu ayarlamayı unutmayın. + UITestMethodAttribute.DispatcherQueue should not be null. To use UITestMethodAttribute within a WinUI Desktop App, remember to set the static UITestMethodAttribute.DispatcherQueue during the test initialization. diff --git a/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.zh-Hans.xlf b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.zh-Hans.xlf index 85373b311d..873542de87 100644 --- a/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.zh-Hans.xlf +++ b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.zh-Hans.xlf @@ -12,7 +12,7 @@ UITestMethodAttribute.DispatcherQueue should not be null. To use UITestMethodAttribute within a WinUI Desktop App, remember to set the static UITestMethodAttribute.DispatcherQueue during the test initialization. - UITestMethodAttribute.DispatcherQueue 不应为 null。若要在 WinUI 桌面应用中使用 UITestMethodAttribute,请在测试初始化期间设置静态 UITestMethodAttribute.DispatcherQueue。 + UITestMethodAttribute.DispatcherQueue should not be null. To use UITestMethodAttribute within a WinUI Desktop App, remember to set the static UITestMethodAttribute.DispatcherQueue during the test initialization. diff --git a/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.zh-Hant.xlf b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.zh-Hant.xlf index 4296973668..c185c5d236 100644 --- a/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.zh-Hant.xlf +++ b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.zh-Hant.xlf @@ -12,7 +12,7 @@ UITestMethodAttribute.DispatcherQueue should not be null. To use UITestMethodAttribute within a WinUI Desktop App, remember to set the static UITestMethodAttribute.DispatcherQueue during the test initialization. - UITestMethodAttribute.DispatcherQueue 不應為 Null。若要在 WinUI 傳統型應用程式內使用 UITestMethodAttribute,請記得在測試初始化期間設定靜態 UITestMethodAttribute.DispatcherQueue。 + UITestMethodAttribute.DispatcherQueue should not be null. To use UITestMethodAttribute within a WinUI Desktop App, remember to set the static UITestMethodAttribute.DispatcherQueue during the test initialization. From 0fefcfb6ba7945be8072032f123df5d8ce62e279 Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Thu, 10 Jul 2025 18:11:54 +1000 Subject: [PATCH 176/541] use some computed properties (#5961) --- .../TestFrameworkCapabilities.cs | 2 +- .../DataRowTestMethodArgumentsInfo.cs | 2 +- .../AzureDevOpsReporter.cs | 4 +-- .../ToolTrxCompareFactory.cs | 4 +-- .../TrxCommandLine.cs | 4 +-- .../TrxCompareTool.CommandLine.cs | 2 +- .../TrxCompareTool.cs | 2 +- .../TrxDataConsumer.cs | 4 +-- .../TrxTestApplicationLifecycleCallbacks.cs | 4 +-- .../VSTestBridgeExtensionBaseCapabilities.cs | 2 +- .../RunSettingsConfigurationProvider.cs | 8 +++--- .../PlatformCommandLineProvider.cs | 4 +-- .../Configurations/JsonConfigurationSource.cs | 8 +++--- .../AbortForMaxFailedTestsExtension.cs | 6 ++--- .../OutputDevice/BrowserOutputDevice.cs | 8 +++--- ...lTestReporterCommandLineOptionsProvider.cs | 4 +-- .../OutputDevice/TerminalOutputDevice.cs | 8 +++--- .../Services/IPlatformInformation.cs | 2 +- .../Services/TestApplicationResult.cs | 4 +-- .../TestFramework/Assertions/Assert.cs | 2 +- .../Assertions/CollectionAssert.cs | 2 +- .../TestFramework/Assertions/StringAssert.cs | 2 +- .../Discovery/TypeValidatorTests.cs | 26 +++++++++---------- .../Discovery/UnitTestDiscovererTests.cs | 2 +- .../Execution/TestExecutionManagerTests.cs | 2 +- .../Execution/TestMethodFilterTests.cs | 2 +- .../Execution/TestMethodInfoTests.cs | 2 +- .../Execution/TestMethodRunnerTests.cs | 2 +- .../Helpers/TestExtension.cs | 8 +++--- .../Helpers/TestExtension.cs | 8 +++--- .../CommandLine/ArgumentArityTests.cs | 8 +++--- .../CommandLine/CommandLineHandlerTests.cs | 24 ++++++++--------- .../Helpers/TestExtension.cs | 8 +++--- 33 files changed, 90 insertions(+), 90 deletions(-) diff --git a/src/Adapter/MSTest.Engine/TestFramework/TestFrameworkCapabilities.cs b/src/Adapter/MSTest.Engine/TestFramework/TestFrameworkCapabilities.cs index 434251ea82..c7a853b973 100644 --- a/src/Adapter/MSTest.Engine/TestFramework/TestFrameworkCapabilities.cs +++ b/src/Adapter/MSTest.Engine/TestFramework/TestFrameworkCapabilities.cs @@ -39,7 +39,7 @@ public TestFrameworkCapabilitiesSet(ITestNodesBuilder[] testNodesBuilders) public bool IsTrxReportCapabilitySupported { get; } - bool ITestNodesTreeFilterTestFrameworkCapability.IsSupported { get; } = true; + bool ITestNodesTreeFilterTestFrameworkCapability.IsSupported => true; bool ITrxReportCapability.IsSupported => IsTrxReportCapabilitySupported; diff --git a/src/Analyzers/MSTest.SourceGeneration/ObjectModels/DataRowTestMethodArgumentsInfo.cs b/src/Analyzers/MSTest.SourceGeneration/ObjectModels/DataRowTestMethodArgumentsInfo.cs index b085453536..7bc9a24b18 100644 --- a/src/Analyzers/MSTest.SourceGeneration/ObjectModels/DataRowTestMethodArgumentsInfo.cs +++ b/src/Analyzers/MSTest.SourceGeneration/ObjectModels/DataRowTestMethodArgumentsInfo.cs @@ -14,7 +14,7 @@ internal sealed class DataRowTestMethodArgumentsInfo : ITestMethodArgumentsInfo private readonly ImmutableArray> _argumentsRows; private readonly TestMethodParametersInfo _parametersInfo; - public bool IsTestArgumentsEntryReturnType { get; } = true; + public bool IsTestArgumentsEntryReturnType => true; public string? GeneratorMethodFullName { get; } diff --git a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/AzureDevOpsReporter.cs b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/AzureDevOpsReporter.cs index b41c26b3e2..fc52268f08 100644 --- a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/AzureDevOpsReporter.cs +++ b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/AzureDevOpsReporter.cs @@ -51,10 +51,10 @@ public AzureDevOpsReporter( public Type[] DataTypesProduced { get; } = [typeof(SessionFileArtifact)]; /// - public string Uid { get; } = nameof(AzureDevOpsReporter); + public string Uid => nameof(AzureDevOpsReporter); /// - public string Version { get; } = AppVersion.DefaultSemVer; + public string Version => AppVersion.DefaultSemVer; /// public string DisplayName { get; } = AzureDevOpsResources.DisplayName; diff --git a/src/Platform/Microsoft.Testing.Extensions.TrxReport/ToolTrxCompareFactory.cs b/src/Platform/Microsoft.Testing.Extensions.TrxReport/ToolTrxCompareFactory.cs index e88cb5b300..8cd1723dbb 100644 --- a/src/Platform/Microsoft.Testing.Extensions.TrxReport/ToolTrxCompareFactory.cs +++ b/src/Platform/Microsoft.Testing.Extensions.TrxReport/ToolTrxCompareFactory.cs @@ -12,10 +12,10 @@ namespace Microsoft.Testing.Extensions.TrxReport.Abstractions; internal sealed class ToolTrxCompareFactory : IExtension { /// - public string Uid { get; } = nameof(TrxCompareTool); + public string Uid => nameof(TrxCompareTool); /// - public string Version { get; } = AppVersion.DefaultSemVer; + public string Version => AppVersion.DefaultSemVer; /// public string DisplayName { get; } = ExtensionResources.TrxComparerToolDisplayName; diff --git a/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxCommandLine.cs b/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxCommandLine.cs index 51f36f19dc..db827e0d45 100644 --- a/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxCommandLine.cs +++ b/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxCommandLine.cs @@ -16,10 +16,10 @@ internal sealed class TrxReportGeneratorCommandLine : ICommandLineOptionsProvide public const string TrxReportFileNameOptionName = "report-trx-filename"; /// - public string Uid { get; } = nameof(TrxReportGeneratorCommandLine); + public string Uid => nameof(TrxReportGeneratorCommandLine); /// - public string Version { get; } = AppVersion.DefaultSemVer; + public string Version => AppVersion.DefaultSemVer; /// public string DisplayName { get; } = ExtensionResources.TrxReportGeneratorDisplayName; diff --git a/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxCompareTool.CommandLine.cs b/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxCompareTool.CommandLine.cs index bc131ffc4f..294e61c76a 100644 --- a/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxCompareTool.CommandLine.cs +++ b/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxCompareTool.CommandLine.cs @@ -31,7 +31,7 @@ public TrxCompareToolCommandLine(IExtension extension) public string Description => _extension.Description; /// - public string ToolName { get; } = TrxCompareTool.ToolName; + public string ToolName => TrxCompareTool.ToolName; /// public Task IsEnabledAsync() => Task.FromResult(true); diff --git a/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxCompareTool.cs b/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxCompareTool.cs index 17a95a5ea6..6a6069daf2 100644 --- a/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxCompareTool.cs +++ b/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxCompareTool.cs @@ -28,7 +28,7 @@ public TrxCompareTool(ICommandLineOptions commandLineOptions, IExtension extensi } /// - public string Name { get; } = ToolName; + public string Name => ToolName; /// public string Uid => _extension.Uid; diff --git a/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxDataConsumer.cs b/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxDataConsumer.cs index 25a5313c63..7bca22a1ce 100644 --- a/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxDataConsumer.cs +++ b/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxDataConsumer.cs @@ -89,10 +89,10 @@ public TrxReportGenerator( public Type[] DataTypesProduced { get; } = [typeof(SessionFileArtifact)]; /// - public string Uid { get; } = nameof(TrxReportGenerator); + public string Uid => nameof(TrxReportGenerator); /// - public string Version { get; } = AppVersion.DefaultSemVer; + public string Version => AppVersion.DefaultSemVer; /// public string DisplayName { get; } = ExtensionResources.TrxReportGeneratorDisplayName; diff --git a/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxTestApplicationLifecycleCallbacks.cs b/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxTestApplicationLifecycleCallbacks.cs index a9dfbcbe49..d1057fcef1 100644 --- a/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxTestApplicationLifecycleCallbacks.cs +++ b/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxTestApplicationLifecycleCallbacks.cs @@ -34,10 +34,10 @@ public TrxTestApplicationLifecycleCallbacks( public NamedPipeClient? NamedPipeClient { get; private set; } - public string Uid { get; } = nameof(TrxTestApplicationLifecycleCallbacks); + public string Uid => nameof(TrxTestApplicationLifecycleCallbacks); /// - public string Version { get; } = AppVersion.DefaultSemVer; + public string Version => AppVersion.DefaultSemVer; /// public string DisplayName { get; } = ExtensionResources.TrxReportGeneratorDisplayName; diff --git a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/Capabilities/VSTestBridgeExtensionBaseCapabilities.cs b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/Capabilities/VSTestBridgeExtensionBaseCapabilities.cs index 4c17f77738..23558ea6ea 100644 --- a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/Capabilities/VSTestBridgeExtensionBaseCapabilities.cs +++ b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/Capabilities/VSTestBridgeExtensionBaseCapabilities.cs @@ -18,7 +18,7 @@ public sealed class VSTestBridgeExtensionBaseCapabilities : ITrxReportCapability private const string VSTestProviderSupport = "vstestProvider"; /// - bool ITrxReportCapability.IsSupported { get; } = true; + bool ITrxReportCapability.IsSupported => true; /// /// Gets a value indicating whether a flag indicating whether the trx report capability is enabled. diff --git a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/Configurations/RunSettingsConfigurationProvider.cs b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/Configurations/RunSettingsConfigurationProvider.cs index 297dd6e2b6..9f4fef4414 100644 --- a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/Configurations/RunSettingsConfigurationProvider.cs +++ b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/Configurations/RunSettingsConfigurationProvider.cs @@ -15,16 +15,16 @@ internal sealed class RunSettingsConfigurationProvider(IFileSystem fileSystem) : private string? _runSettingsFileContent; /// - public string Uid { get; } = nameof(RunSettingsConfigurationProvider); + public string Uid => nameof(RunSettingsConfigurationProvider); /// - public string Version { get; } = AppVersion.DefaultSemVer; + public string Version => AppVersion.DefaultSemVer; /// - public string DisplayName { get; } = "VSTest Helpers: runsettings configuration"; + public string DisplayName => "VSTest Helpers: runsettings configuration"; /// - public string Description { get; } = "Configuration source to bridge VSTest xml runsettings configuration into Microsoft Testing Platform configuration model."; + public string Description => "Configuration source to bridge VSTest xml runsettings configuration into Microsoft Testing Platform configuration model."; public int Order => 2; diff --git a/src/Platform/Microsoft.Testing.Platform/CommandLine/PlatformCommandLineProvider.cs b/src/Platform/Microsoft.Testing.Platform/CommandLine/PlatformCommandLineProvider.cs index 33029f8f19..ad94138e77 100644 --- a/src/Platform/Microsoft.Testing.Platform/CommandLine/PlatformCommandLineProvider.cs +++ b/src/Platform/Microsoft.Testing.Platform/CommandLine/PlatformCommandLineProvider.cs @@ -70,10 +70,10 @@ internal sealed class PlatformCommandLineProvider : ICommandLineOptionsProvider ]; /// - public string Uid { get; } = nameof(PlatformCommandLineProvider); + public string Uid => nameof(PlatformCommandLineProvider); /// - public string Version { get; } = AppVersion.DefaultSemVer; + public string Version => AppVersion.DefaultSemVer; /// public string DisplayName { get; } = PlatformResources.PlatformCommandLineProviderDisplayName; diff --git a/src/Platform/Microsoft.Testing.Platform/Configurations/JsonConfigurationSource.cs b/src/Platform/Microsoft.Testing.Platform/Configurations/JsonConfigurationSource.cs index 3855c806e8..405d58af87 100644 --- a/src/Platform/Microsoft.Testing.Platform/Configurations/JsonConfigurationSource.cs +++ b/src/Platform/Microsoft.Testing.Platform/Configurations/JsonConfigurationSource.cs @@ -15,18 +15,18 @@ internal sealed partial class JsonConfigurationSource(ITestApplicationModuleInfo private readonly FileLoggerProvider? _fileLoggerProvider = fileLoggerProvider; /// - public string Uid { get; } = nameof(JsonConfigurationSource); + public string Uid => nameof(JsonConfigurationSource); /// - public string Version { get; } = AppVersion.DefaultSemVer; + public string Version => AppVersion.DefaultSemVer; /// // Can be empty string because it's not used in the UI - public string DisplayName { get; } = string.Empty; + public string DisplayName => string.Empty; /// // Can be empty string because it's not used in the UI - public string Description { get; } = string.Empty; + public string Description => string.Empty; public int Order => 3; diff --git a/src/Platform/Microsoft.Testing.Platform/Extensions/AbortForMaxFailedTestsExtension.cs b/src/Platform/Microsoft.Testing.Platform/Extensions/AbortForMaxFailedTestsExtension.cs index b6fd5e23ef..878f3e8dcc 100644 --- a/src/Platform/Microsoft.Testing.Platform/Extensions/AbortForMaxFailedTestsExtension.cs +++ b/src/Platform/Microsoft.Testing.Platform/Extensions/AbortForMaxFailedTestsExtension.cs @@ -41,13 +41,13 @@ public AbortForMaxFailedTestsExtension( public Type[] DataTypesConsumed { get; } = [typeof(TestNodeUpdateMessage)]; /// - public string Uid { get; } = nameof(AbortForMaxFailedTestsExtension); + public string Uid => nameof(AbortForMaxFailedTestsExtension); /// - public string Version { get; } = AppVersion.DefaultSemVer; + public string Version => AppVersion.DefaultSemVer; /// - public string DisplayName { get; } = nameof(AbortForMaxFailedTestsExtension); + public string DisplayName => nameof(AbortForMaxFailedTestsExtension); /// public string Description { get; } = PlatformResources.AbortForMaxFailedTestsDescription; diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/BrowserOutputDevice.cs b/src/Platform/Microsoft.Testing.Platform/OutputDevice/BrowserOutputDevice.cs index 97a63cf078..603c8dc38d 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/BrowserOutputDevice.cs +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/BrowserOutputDevice.cs @@ -103,16 +103,16 @@ public async Task InitializeAsync() ]; /// - public string Uid { get; } = nameof(BrowserOutputDevice); + public string Uid => nameof(BrowserOutputDevice); /// - public string Version { get; } = AppVersion.DefaultSemVer; + public string Version => AppVersion.DefaultSemVer; /// - public string DisplayName { get; } = "Test Platform Browser Console Service"; + public string DisplayName => "Test Platform Browser Console Service"; /// - public string Description { get; } = "Test Platform default browser console service"; + public string Description => "Test Platform default browser console service"; /// public Task IsEnabledAsync() => Task.FromResult(true); diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporterCommandLineOptionsProvider.cs b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporterCommandLineOptionsProvider.cs index 97e965b324..5de9570121 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporterCommandLineOptionsProvider.cs +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporterCommandLineOptionsProvider.cs @@ -18,10 +18,10 @@ internal sealed class TerminalTestReporterCommandLineOptionsProvider : ICommandL public const string OutputOptionDetailedArgument = "detailed"; /// - public string Uid { get; } = nameof(TerminalTestReporterCommandLineOptionsProvider); + public string Uid => nameof(TerminalTestReporterCommandLineOptionsProvider); /// - public string Version { get; } = AppVersion.DefaultSemVer; + public string Version => AppVersion.DefaultSemVer; /// public string DisplayName { get; } = PlatformResources.TerminalTestReporterDisplayName; diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/TerminalOutputDevice.cs b/src/Platform/Microsoft.Testing.Platform/OutputDevice/TerminalOutputDevice.cs index 68f2a24227..3c02b2b997 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/TerminalOutputDevice.cs +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/TerminalOutputDevice.cs @@ -178,16 +178,16 @@ private static string GetShortArchitecture(string runtimeIdentifier) ]; /// - public string Uid { get; } = nameof(TerminalOutputDevice); + public string Uid => nameof(TerminalOutputDevice); /// - public string Version { get; } = AppVersion.DefaultSemVer; + public string Version => AppVersion.DefaultSemVer; /// - public string DisplayName { get; } = "Test Platform Console Service"; + public string DisplayName => "Test Platform Console Service"; /// - public string Description { get; } = "Test Platform default console service"; + public string Description => "Test Platform default console service"; /// public Task IsEnabledAsync() => Task.FromResult(true); diff --git a/src/Platform/Microsoft.Testing.Platform/Services/IPlatformInformation.cs b/src/Platform/Microsoft.Testing.Platform/Services/IPlatformInformation.cs index 8c8f1302fa..98959a6647 100644 --- a/src/Platform/Microsoft.Testing.Platform/Services/IPlatformInformation.cs +++ b/src/Platform/Microsoft.Testing.Platform/Services/IPlatformInformation.cs @@ -64,7 +64,7 @@ public PlatformInformation() } } - public string Name { get; } = "Microsoft.Testing.Platform"; + public string Name => "Microsoft.Testing.Platform"; public DateTimeOffset? BuildDate { get; } diff --git a/src/Platform/Microsoft.Testing.Platform/Services/TestApplicationResult.cs b/src/Platform/Microsoft.Testing.Platform/Services/TestApplicationResult.cs index 4f2d9a7caf..cf3835cee0 100644 --- a/src/Platform/Microsoft.Testing.Platform/Services/TestApplicationResult.cs +++ b/src/Platform/Microsoft.Testing.Platform/Services/TestApplicationResult.cs @@ -36,10 +36,10 @@ public TestApplicationResult( } /// - public string Uid { get; } = nameof(TestApplicationResult); + public string Uid => nameof(TestApplicationResult); /// - public string Version { get; } = AppVersion.DefaultSemVer; + public string Version => AppVersion.DefaultSemVer; /// public string DisplayName { get; } = PlatformResources.TestApplicationResultDisplayName; diff --git a/src/TestFramework/TestFramework/Assertions/Assert.cs b/src/TestFramework/TestFramework/Assertions/Assert.cs index 134c3fc841..ba2c122a2c 100644 --- a/src/TestFramework/TestFramework/Assertions/Assert.cs +++ b/src/TestFramework/TestFramework/Assertions/Assert.cs @@ -39,7 +39,7 @@ private Assert() #else [Obsolete(FrameworkConstants.ThatPropertyObsoleteMessage)] #endif - public static Assert That { get; } = Instance; + public static Assert That => Instance; /// /// Replaces null characters ('\0') with "\\0". diff --git a/src/TestFramework/TestFramework/Assertions/CollectionAssert.cs b/src/TestFramework/TestFramework/Assertions/CollectionAssert.cs index 8ce10cef9b..436ce32d50 100644 --- a/src/TestFramework/TestFramework/Assertions/CollectionAssert.cs +++ b/src/TestFramework/TestFramework/Assertions/CollectionAssert.cs @@ -41,7 +41,7 @@ private CollectionAssert() #else [Obsolete(FrameworkConstants.ThatPropertyObsoleteMessage)] #endif - public static CollectionAssert That { get; } = Instance; + public static CollectionAssert That => Instance; #endregion diff --git a/src/TestFramework/TestFramework/Assertions/StringAssert.cs b/src/TestFramework/TestFramework/Assertions/StringAssert.cs index c5fce3a403..a70c740716 100644 --- a/src/TestFramework/TestFramework/Assertions/StringAssert.cs +++ b/src/TestFramework/TestFramework/Assertions/StringAssert.cs @@ -41,7 +41,7 @@ private StringAssert() #else [Obsolete(FrameworkConstants.ThatPropertyObsoleteMessage)] #endif - public static StringAssert That { get; } = Instance; + public static StringAssert That => Instance; #endregion diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Discovery/TypeValidatorTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Discovery/TypeValidatorTests.cs index 0450385460..7916f355c1 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Discovery/TypeValidatorTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Discovery/TypeValidatorTests.cs @@ -409,7 +409,7 @@ public class GenericClass; public class ClassWithTestContextGetterOnly { - public TestContext TestContext { get; } = null!; + public TestContext TestContext => null!; } public class ClassWithTestContextPrivateSetter @@ -435,7 +435,7 @@ public class ClassWithTestContext public class GenericClassWithProperty { #pragma warning disable CA1000 // Do not declare static members on generic types - public static T ReturnAStableSomething { get; } = default!; + public static T ReturnAStableSomething => default!; #pragma warning restore CA1000 // Do not declare static members on generic types public T ReturnSomething { get; set; } = default!; @@ -446,7 +446,7 @@ public class GenericClassWithProperty public class GenericClassWithTestContext { #pragma warning disable CA1000 // Do not declare static members on generic types - public static T ReturnAStableSomething { get; } = default!; + public static T ReturnAStableSomething => default!; #pragma warning restore CA1000 // Do not declare static members on generic types public T ReturnSomething { get; set; } = default!; @@ -547,25 +547,25 @@ public sealed class PublicClassNestedInPrivateClassNestedInInternalClass; /// internal class PrivateClassNames { - public string ProtectedInteralNestedClassInPublicClass { get; } = null!; + public string ProtectedInteralNestedClassInPublicClass => null!; - public string ProtectedNestedClassInPublicClass { get; } = null!; + public string ProtectedNestedClassInPublicClass => null!; - public string PrivateProtectedNestedClassInPublicClass { get; } = null!; + public string PrivateProtectedNestedClassInPublicClass => null!; - public string PrivateClassNestedInPublicClass { get; } = null!; + public string PrivateClassNestedInPublicClass => null!; - public string ProtectedInteralClassNestedInInternalClass { get; } = null!; + public string ProtectedInteralClassNestedInInternalClass => null!; - public string ProtectedClassNestedInInternalClass { get; } = null!; + public string ProtectedClassNestedInInternalClass => null!; - public string PrivateProtectedClassNestedInInternalClass { get; } = null!; + public string PrivateProtectedClassNestedInInternalClass => null!; - public string PrivateClassNestedInInternalClass { get; } = null!; + public string PrivateClassNestedInInternalClass => null!; - public string PublicClassNestedInPrivateClassNestedInPublicClass { get; } = null!; + public string PublicClassNestedInPrivateClassNestedInPublicClass => null!; - public string PublicClassNestedInPrivateClassNestedInInternalClass { get; } = null!; + public string PublicClassNestedInPrivateClassNestedInInternalClass => null!; } #endregion diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Discovery/UnitTestDiscovererTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Discovery/UnitTestDiscovererTests.cs index 9911a3ddf6..cd441bf364 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Discovery/UnitTestDiscovererTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Discovery/UnitTestDiscovererTests.cs @@ -434,7 +434,7 @@ internal sealed class TestableTestCaseFilterExpression : ITestCaseFilterExpressi public TestableTestCaseFilterExpression(Func matchTestCase) => _matchTest = matchTestCase; - public string TestCaseFilterValue { get; } = null!; + public string TestCaseFilterValue => null!; public bool MatchTestCase(TestCase testCase, Func propertyValueProvider) => _matchTest(testCase); } diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestExecutionManagerTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestExecutionManagerTests.cs index f70d4e8d4c..ecbcbfdfe3 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestExecutionManagerTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestExecutionManagerTests.cs @@ -1119,7 +1119,7 @@ internal sealed class TestableTestCaseFilterExpression : ITestCaseFilterExpressi public TestableTestCaseFilterExpression(Func matchTestCase) => _matchTest = matchTestCase; - public string TestCaseFilterValue { get; } = null!; + public string TestCaseFilterValue => null!; public bool MatchTestCase(TestCase testCase, Func propertyValueProvider) => _matchTest(testCase); } diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestMethodFilterTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestMethodFilterTests.cs index 38c133d45a..28f5710903 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestMethodFilterTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestMethodFilterTests.cs @@ -225,7 +225,7 @@ private class TestableDiscoveryContextWithoutGetTestCaseFilter : IDiscoveryConte private sealed class TestableTestCaseFilterExpression : ITestCaseFilterExpression { - public string TestCaseFilterValue { get; } = null!; + public string TestCaseFilterValue => null!; public bool MatchTestCase(TestCase testCase, Func propertyValueProvider) => throw new NotImplementedException(); } diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestMethodInfoTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestMethodInfoTests.cs index b8c430d7a8..a6f7dea1cc 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestMethodInfoTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestMethodInfoTests.cs @@ -1838,7 +1838,7 @@ public DummyTestClassWithParameterizedCtor(int x) public class DummyTestClassWithTestContextWithoutSetter { - public TestContext TestContext { get; } = null!; + public TestContext TestContext => null!; } public class DummyTestClassWithDisposable : IDisposable diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestMethodRunnerTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestMethodRunnerTests.cs index 473077cfb9..a6a3817026 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestMethodRunnerTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestMethodRunnerTests.cs @@ -532,7 +532,7 @@ public DummyTestClassWithParameterizedCtor(int x) public class DummyTestClassWithTestContextWithoutSetter { - public TestContext TestContext { get; } = null!; + public TestContext TestContext => null!; } public class DummyTestClassEmptyDataSource diff --git a/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/Helpers/TestExtension.cs b/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/Helpers/TestExtension.cs index 85bdd02fc3..5019e8d619 100644 --- a/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/Helpers/TestExtension.cs +++ b/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/Helpers/TestExtension.cs @@ -5,13 +5,13 @@ namespace Microsoft.Testing.Extensions.UnitTests.Helpers; internal sealed class TestExtension : IExtension { - public string Uid { get; } = "Uid"; + public string Uid => "Uid"; - public string Version { get; } = "Version"; + public string Version => "Version"; - public string DisplayName { get; } = "DisplayName"; + public string DisplayName => "DisplayName"; - public string Description { get; } = "Description"; + public string Description => "Description"; public Task IsEnabledAsync() => Task.FromResult(true); } diff --git a/test/UnitTests/Microsoft.Testing.Extensions.VSTestBridge.UnitTests/Helpers/TestExtension.cs b/test/UnitTests/Microsoft.Testing.Extensions.VSTestBridge.UnitTests/Helpers/TestExtension.cs index fd087790e7..71ba44329a 100644 --- a/test/UnitTests/Microsoft.Testing.Extensions.VSTestBridge.UnitTests/Helpers/TestExtension.cs +++ b/test/UnitTests/Microsoft.Testing.Extensions.VSTestBridge.UnitTests/Helpers/TestExtension.cs @@ -5,13 +5,13 @@ namespace Microsoft.Testing.Extensions.VSTestBridge.UnitTests.Helpers; internal sealed class TestExtension : IExtension { - public string Uid { get; } = "Uid"; + public string Uid => "Uid"; - public string Version { get; } = "Version"; + public string Version => "Version"; - public string DisplayName { get; } = "DisplayName"; + public string DisplayName => "DisplayName"; - public string Description { get; } = "Description"; + public string Description => "Description"; public Task IsEnabledAsync() => Task.FromResult(true); } diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/ArgumentArityTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/ArgumentArityTests.cs index 5cada34ede..c688a2062f 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/ArgumentArityTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/ArgumentArityTests.cs @@ -121,16 +121,16 @@ public async Task ParseAndValidate_WhenOptionsGetsTheExpectedNumberOfArguments_R private sealed class ExtensionCommandLineProviderMockOptionsWithDifferentArity : ICommandLineOptionsProvider { - public string Uid { get; } = nameof(PlatformCommandLineProvider); + public string Uid => nameof(PlatformCommandLineProvider); /// - public string Version { get; } = AppVersion.DefaultSemVer; + public string Version => AppVersion.DefaultSemVer; /// - public string DisplayName { get; } = "Microsoft Testing Platform command line provider"; + public string DisplayName => "Microsoft Testing Platform command line provider"; /// - public string Description { get; } = "Built-in command line provider"; + public string Description => "Built-in command line provider"; /// public Task IsEnabledAsync() => Task.FromResult(true); diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/CommandLineHandlerTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/CommandLineHandlerTests.cs index 50462c0cb1..ef9aaa6cca 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/CommandLineHandlerTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/CommandLineHandlerTests.cs @@ -294,16 +294,16 @@ private sealed class ExtensionCommandLineProviderMockReservedOptions : ICommandL { public const string HelpOption = "help"; - public string Uid { get; } = nameof(PlatformCommandLineProvider); + public string Uid => nameof(PlatformCommandLineProvider); /// - public string Version { get; } = AppVersion.DefaultSemVer; + public string Version => AppVersion.DefaultSemVer; /// - public string DisplayName { get; } = "Microsoft Testing Platform command line provider"; + public string DisplayName => "Microsoft Testing Platform command line provider"; /// - public string Description { get; } = "Built-in command line provider"; + public string Description => "Built-in command line provider"; /// public Task IsEnabledAsync() => Task.FromResult(true); @@ -322,16 +322,16 @@ private sealed class ExtensionCommandLineProviderMockUnknownOption : ICommandLin { public const string Option = "option"; - public string Uid { get; } = nameof(PlatformCommandLineProvider); + public string Uid => nameof(PlatformCommandLineProvider); /// - public string Version { get; } = AppVersion.DefaultSemVer; + public string Version => AppVersion.DefaultSemVer; /// - public string DisplayName { get; } = "Microsoft Testing Platform command line provider"; + public string DisplayName => "Microsoft Testing Platform command line provider"; /// - public string Description { get; } = "Built-in command line provider"; + public string Description => "Built-in command line provider"; /// public Task IsEnabledAsync() => Task.FromResult(true); @@ -352,16 +352,16 @@ private sealed class ExtensionCommandLineProviderMockInvalidConfiguration : ICom public ExtensionCommandLineProviderMockInvalidConfiguration(string optionName = "option") => _option = optionName; - public string Uid { get; } = nameof(PlatformCommandLineProvider); + public string Uid => nameof(PlatformCommandLineProvider); /// - public string Version { get; } = AppVersion.DefaultSemVer; + public string Version => AppVersion.DefaultSemVer; /// - public string DisplayName { get; } = "Microsoft Testing Platform command line provider"; + public string DisplayName => "Microsoft Testing Platform command line provider"; /// - public string Description { get; } = "Built-in command line provider"; + public string Description => "Built-in command line provider"; /// public Task IsEnabledAsync() => Task.FromResult(true); diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Helpers/TestExtension.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Helpers/TestExtension.cs index 5d2729a8ab..404f11cd9a 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Helpers/TestExtension.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Helpers/TestExtension.cs @@ -5,13 +5,13 @@ namespace Microsoft.Testing.Platform.UnitTests.Helpers; internal class TestExtension : IExtension { - public string Uid { get; } = "Uid"; + public string Uid => "Uid"; - public string Version { get; } = "Version"; + public string Version => "Version"; - public string DisplayName { get; } = "DisplayName"; + public string DisplayName => "DisplayName"; - public string Description { get; } = "Description"; + public string Description => "Description"; public Task IsEnabledAsync() => Task.FromResult(true); } From c6ca114cc7a09d9b121d3eee699385028d9991bd Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Thu, 10 Jul 2025 18:12:55 +1000 Subject: [PATCH 177/541] redundant null checks in TrxProcessLifetimeHandler (#5960) --- .../TrxProcessLifetimeHandler.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxProcessLifetimeHandler.cs b/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxProcessLifetimeHandler.cs index 6242fd4664..ae3a26358a 100644 --- a/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxProcessLifetimeHandler.cs +++ b/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxProcessLifetimeHandler.cs @@ -236,7 +236,7 @@ public async ValueTask DisposeAsync() await DisposeHelper.DisposeAsync(_singleConnectionNamedPipeServer).ConfigureAwait(false); // Dispose the pipe descriptor after the server to ensure the pipe is closed. - _pipeNameDescription?.Dispose(); + _pipeNameDescription.Dispose(); } #else public void Dispose() @@ -244,7 +244,7 @@ public void Dispose() _singleConnectionNamedPipeServer?.Dispose(); // Dispose the pipe descriptor after the server to ensure the pipe is closed. - _pipeNameDescription?.Dispose(); + _pipeNameDescription.Dispose(); } #endif From 4e4462f987de859addd123793d726571c3c441a2 Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Thu, 10 Jul 2025 18:13:29 +1000 Subject: [PATCH 178/541] remove redundant BuildConsumerProducersAsync (#5962) --- .../Messages/AsynchronousMessageBus.cs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Platform/Messages/AsynchronousMessageBus.cs b/src/Platform/Microsoft.Testing.Platform/Messages/AsynchronousMessageBus.cs index c51baaa3a1..5987a2d91a 100644 --- a/src/Platform/Microsoft.Testing.Platform/Messages/AsynchronousMessageBus.cs +++ b/src/Platform/Microsoft.Testing.Platform/Messages/AsynchronousMessageBus.cs @@ -42,9 +42,7 @@ public AsynchronousMessageBus( public override IDataConsumer[] DataConsumerServices => _dataConsumers; - public override async Task InitAsync() => await BuildConsumerProducersAsync().ConfigureAwait(false); - - private async Task BuildConsumerProducersAsync() + public override async Task InitAsync() { foreach (IDataConsumer consumer in _dataConsumers) { From 00db903ed914bf3be8ccf04e74931d1cea78f5f7 Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Thu, 10 Jul 2025 18:15:40 +1000 Subject: [PATCH 179/541] remove non generic ActionResult (#5959) --- .../Helpers/ActionResult.cs | 26 +++++++------------ 1 file changed, 9 insertions(+), 17 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Platform/Helpers/ActionResult.cs b/src/Platform/Microsoft.Testing.Platform/Helpers/ActionResult.cs index 694daf1ddc..33a26c8c31 100644 --- a/src/Platform/Microsoft.Testing.Platform/Helpers/ActionResult.cs +++ b/src/Platform/Microsoft.Testing.Platform/Helpers/ActionResult.cs @@ -3,19 +3,8 @@ namespace Microsoft.Testing.Platform.Helpers; -internal class ActionResult +internal static class ActionResult { - protected ActionResult(bool isSuccess, object? result) - { - IsSuccess = isSuccess; - Result = result; - } - - [MemberNotNullWhen(true, nameof(Result))] - public bool IsSuccess { get; } - - public object? Result { get; } - public static ActionResult Ok(TResult result) => new(true, result); @@ -23,16 +12,19 @@ public static ActionResult Fail() => new(false, default); } -internal sealed class ActionResult : ActionResult +internal sealed class ActionResult { internal ActionResult(bool isSuccess, TResult? result) - : base(isSuccess, result) => Result = result; + { + IsSuccess = isSuccess; + Result = result; + } [MemberNotNullWhen(true, nameof(Result))] - public new bool IsSuccess => base.IsSuccess; + public bool IsSuccess { get; } - public new TResult? Result { get; } + public TResult? Result { get; } public static implicit operator ActionResult(TResult result) - => Ok(result); + => new(true, result); } From 7b0ac0dc5777af896205b88865d0b4731c74b33b Mon Sep 17 00:00:00 2001 From: dotnet bot Date: Thu, 10 Jul 2025 10:23:22 +0200 Subject: [PATCH 180/541] Localized file check-in by OneLocBuild Task: Build definition ID 1218: Build ID 2747012 --- .../xlf/CodeFixResources.cs.xlf | 2 +- .../xlf/CodeFixResources.es.xlf | 2 +- .../xlf/CodeFixResources.fr.xlf | 2 +- .../xlf/CodeFixResources.it.xlf | 2 +- .../xlf/CodeFixResources.ko.xlf | 2 +- .../xlf/CodeFixResources.pl.xlf | 2 +- .../xlf/CodeFixResources.ru.xlf | 2 +- .../xlf/CodeFixResources.zh-Hans.xlf | 2 +- .../xlf/CodeFixResources.zh-Hant.xlf | 2 +- src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf | 8 ++++---- src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf | 8 ++++---- src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf | 8 ++++---- src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf | 8 ++++---- src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf | 8 ++++---- src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf | 8 ++++---- src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf | 8 ++++---- src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf | 8 ++++---- 17 files changed, 41 insertions(+), 41 deletions(-) diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.cs.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.cs.xlf index 2cd7939a05..f0cdadaa0e 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.cs.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.cs.xlf @@ -74,7 +74,7 @@ Use 'Assert.{0}' instead of 'StringAssert' - Use 'Assert.{0}' instead of 'StringAssert' + Použijte Assert.{0}místo StringAssert diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.es.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.es.xlf index 3334ac5b90..0f1e41ab01 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.es.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.es.xlf @@ -74,7 +74,7 @@ Use 'Assert.{0}' instead of 'StringAssert' - Use 'Assert.{0}' instead of 'StringAssert' + Use "Assert.{0}" en lugar de "StringAssert" diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.fr.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.fr.xlf index 2895be63f5..28032182a6 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.fr.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.fr.xlf @@ -74,7 +74,7 @@ Use 'Assert.{0}' instead of 'StringAssert' - Use 'Assert.{0}' instead of 'StringAssert' + Utilisez « Assert.{0} » au lieu de « StringAssert » diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.it.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.it.xlf index 357be76d30..ce079335fe 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.it.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.it.xlf @@ -74,7 +74,7 @@ Use 'Assert.{0}' instead of 'StringAssert' - Use 'Assert.{0}' instead of 'StringAssert' + Usa 'Assert.{0}' invece di 'StringAssert' diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ko.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ko.xlf index bc4bb12aab..378b6b3129 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ko.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ko.xlf @@ -74,7 +74,7 @@ Use 'Assert.{0}' instead of 'StringAssert' - Use 'Assert.{0}' instead of 'StringAssert' + 'StringAssert' 대신 'Assert.{0}' 사용 diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pl.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pl.xlf index 17422a475f..16a86f9cb5 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pl.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pl.xlf @@ -74,7 +74,7 @@ Use 'Assert.{0}' instead of 'StringAssert' - Use 'Assert.{0}' instead of 'StringAssert' + Użyj ciągu „Assert.{0}” zamiast ciągu „StringAssert” diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ru.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ru.xlf index 2a4bcf0f43..1a166df4bb 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ru.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ru.xlf @@ -74,7 +74,7 @@ Use 'Assert.{0}' instead of 'StringAssert' - Use 'Assert.{0}' instead of 'StringAssert' + Используйте "Assert.{0}" вместо "StringAssert" diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hans.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hans.xlf index adf31e8ee4..e37b91c542 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hans.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hans.xlf @@ -74,7 +74,7 @@ Use 'Assert.{0}' instead of 'StringAssert' - Use 'Assert.{0}' instead of 'StringAssert' + 使用 'Assert.{0}' 而不是 'StringAssert' diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hant.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hant.xlf index ea6323de02..8782e30dca 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hant.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hant.xlf @@ -74,7 +74,7 @@ Use 'Assert.{0}' instead of 'StringAssert' - Use 'Assert.{0}' instead of 'StringAssert' + 使用 'Assert.{0}' 而不是 'StringAssert' diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf index c6dc824ee7..28403c1afc 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf @@ -278,12 +278,12 @@ Typ deklarující tyto metody by měl také respektovat následující pravidla: DataRow argument types do not match method parameter types. {0} - DataRow argument types do not match method parameter types. {0} + Typy argumentů DataRow neodpovídají typům parametrů metody. {0} Parameter '{0}' expects type '{1}', but the provided value has type '{2}' - Parameter '{0}' expects type '{1}', but the provided value has type '{2}' + Parametr '{0}' očekává typ '{1}', ale zadaná hodnota má typ '{2}' @@ -539,12 +539,12 @@ Typ deklarující tyto metody by měl také respektovat následující pravidla: Use 'Assert.{0}' instead of 'StringAssert.{1}' - Use 'Assert.{0}' instead of 'StringAssert.{1}' + Použijte Assert.{0}' místo StringAssert.{1}' Use 'Assert' instead of 'StringAssert' - Use 'Assert' instead of 'StringAssert' + Použijte Assert místo StringAssert diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf index 5efb90ca1d..71e58eaf00 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf @@ -278,12 +278,12 @@ Anche il tipo che dichiara questi metodi deve rispettare le regole seguenti: DataRow argument types do not match method parameter types. {0} - DataRow argument types do not match method parameter types. {0} + Il tipo di argomento di DataRow deve corrispondere ai tipi di parametro del metodo. {0} Parameter '{0}' expects type '{1}', but the provided value has type '{2}' - Parameter '{0}' expects type '{1}', but the provided value has type '{2}' + Il parametro '{0}' prevede il tipo '{1}', ma il tipo del valore specificato è '{2}' @@ -539,12 +539,12 @@ Anche il tipo che dichiara questi metodi deve rispettare le regole seguenti: Use 'Assert.{0}' instead of 'StringAssert.{1}' - Use 'Assert.{0}' instead of 'StringAssert.{1}' + Usa 'Assert.{0}' invece di 'StringAssert.{1}' Use 'Assert' instead of 'StringAssert' - Use 'Assert' instead of 'StringAssert' + Usa 'Assert' invece di 'StringAssert' diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf index 75c3b0081f..b300258adb 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf @@ -278,12 +278,12 @@ The type declaring these methods should also respect the following rules: DataRow argument types do not match method parameter types. {0} - DataRow argument types do not match method parameter types. {0} + DataRow 인수 형식이 메서드 매개 변수 형식과 일치하지 않습니다. {0} Parameter '{0}' expects type '{1}', but the provided value has type '{2}' - Parameter '{0}' expects type '{1}', but the provided value has type '{2}' + '{0}' 매개 변수에는 '{1}' 형식이 필요한데 제공된 값의 형식은 '{2}'입니다. @@ -539,12 +539,12 @@ The type declaring these methods should also respect the following rules: Use 'Assert.{0}' instead of 'StringAssert.{1}' - Use 'Assert.{0}' instead of 'StringAssert.{1}' + 'StringAssert.{1}' 대신 'Assert.{0}' 사용 Use 'Assert' instead of 'StringAssert' - Use 'Assert' instead of 'StringAssert' + 'StringAssert' 대신 'Assert' 사용 diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf index 55eff8b796..113da1e59f 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf @@ -278,12 +278,12 @@ Typ deklarujący te metody powinien również przestrzegać następujących regu DataRow argument types do not match method parameter types. {0} - DataRow argument types do not match method parameter types. {0} + Typy argumentów DataRow nie są zgodne z typami parametrów metody. {0} Parameter '{0}' expects type '{1}', but the provided value has type '{2}' - Parameter '{0}' expects type '{1}', but the provided value has type '{2}' + Parametr „{0}” oczekuje typu „{1}”, ale podana wartość ma typ „{2}” @@ -539,12 +539,12 @@ Typ deklarujący te metody powinien również przestrzegać następujących regu Use 'Assert.{0}' instead of 'StringAssert.{1}' - Use 'Assert.{0}' instead of 'StringAssert.{1}' + Użyj ciągu „Assert.{0}” zamiast ciągu „StringAssert.{1}” Use 'Assert' instead of 'StringAssert' - Use 'Assert' instead of 'StringAssert' + Użyj ciągu „Assert” zamiast ciągu „StringAssert” diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf index c1760782ff..8fdcabbd8a 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf @@ -284,12 +284,12 @@ The type declaring these methods should also respect the following rules: DataRow argument types do not match method parameter types. {0} - DataRow argument types do not match method parameter types. {0} + Типы аргументов DataRow не соответствуют типам параметров метода. {0} Parameter '{0}' expects type '{1}', but the provided value has type '{2}' - Parameter '{0}' expects type '{1}', but the provided value has type '{2}' + Параметр "{0}" ожидает тип "{1}", но предоставленное значение относится к типу "{2}" @@ -545,12 +545,12 @@ The type declaring these methods should also respect the following rules: Use 'Assert.{0}' instead of 'StringAssert.{1}' - Use 'Assert.{0}' instead of 'StringAssert.{1}' + Используйте "Assert.{0}" вместо "StringAssert.{1}" Use 'Assert' instead of 'StringAssert' - Use 'Assert' instead of 'StringAssert' + Используйте "Assert" вместо "StringAssert" diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf index 47f6e789cc..605cfec512 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf @@ -278,12 +278,12 @@ Bu yöntemleri bildiren tipin ayrıca aşağıdaki kurallara uyması gerekir: DataRow argument types do not match method parameter types. {0} - DataRow argument types do not match method parameter types. {0} + DataRow bağımsız değişken türleri, yöntem parametre türleriyle eşleşmiyor. {0} Parameter '{0}' expects type '{1}', but the provided value has type '{2}' - Parameter '{0}' expects type '{1}', but the provided value has type '{2}' + Parametre ‘{0}’ tipi ‘{1}’ bekliyor, ancak verilen değer ‘{2}’ tipindedir @@ -539,12 +539,12 @@ Bu yöntemleri bildiren tipin ayrıca aşağıdaki kurallara uyması gerekir: Use 'Assert.{0}' instead of 'StringAssert.{1}' - Use 'Assert.{0}' instead of 'StringAssert.{1}' + ‘StringAssert.{1}’ yerine ‘Assert.{0}’ kullanın Use 'Assert' instead of 'StringAssert' - Use 'Assert' instead of 'StringAssert' + ‘StringAssert’ yerine ‘Assert’ kullanın diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf index 262662fb6f..35666c9f6e 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf @@ -278,12 +278,12 @@ The type declaring these methods should also respect the following rules: DataRow argument types do not match method parameter types. {0} - DataRow argument types do not match method parameter types. {0} + DataRow 参数类型与方法参数类型不匹配。{0} Parameter '{0}' expects type '{1}', but the provided value has type '{2}' - Parameter '{0}' expects type '{1}', but the provided value has type '{2}' + 参数 ‘{0}’ 需要类型 ‘{1}’,但提供的值类型为 ‘{2}’ @@ -539,12 +539,12 @@ The type declaring these methods should also respect the following rules: Use 'Assert.{0}' instead of 'StringAssert.{1}' - Use 'Assert.{0}' instead of 'StringAssert.{1}' + 使用 'Assert.{0}' 而不是 'StringAssert.{1}' Use 'Assert' instead of 'StringAssert' - Use 'Assert' instead of 'StringAssert' + 使用 'Assert' 而不是 'StringAssert' diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf index 6113380da4..eee571adc5 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf @@ -278,12 +278,12 @@ The type declaring these methods should also respect the following rules: DataRow argument types do not match method parameter types. {0} - DataRow argument types do not match method parameter types. {0} + DataRow 引數類型不符合方法參數類型。{0} Parameter '{0}' expects type '{1}', but the provided value has type '{2}' - Parameter '{0}' expects type '{1}', but the provided value has type '{2}' + 參數 '{0}' 期望類型為 '{1}',但提供的值的類型為 '{2}' @@ -539,12 +539,12 @@ The type declaring these methods should also respect the following rules: Use 'Assert.{0}' instead of 'StringAssert.{1}' - Use 'Assert.{0}' instead of 'StringAssert.{1}' + 使用 'Assert.{0}' 而不是 'StringAssert.{1}' Use 'Assert' instead of 'StringAssert' - Use 'Assert' instead of 'StringAssert' + 使用 'Assert' 而不是 'StringAssert' From 69bc4f2dfa42350ed606c1f1c56f1f2d0d62c427 Mon Sep 17 00:00:00 2001 From: dotnet bot Date: Thu, 10 Jul 2025 10:28:28 +0200 Subject: [PATCH 181/541] Localized file check-in by OneLocBuild Task: Build definition ID 1218: Build ID 2747015 --- .../xlf/CodeFixResources.cs.xlf | 2 +- .../xlf/CodeFixResources.es.xlf | 2 +- .../xlf/CodeFixResources.fr.xlf | 2 +- .../xlf/CodeFixResources.it.xlf | 2 +- .../xlf/CodeFixResources.ko.xlf | 2 +- .../xlf/CodeFixResources.pl.xlf | 2 +- .../xlf/CodeFixResources.ru.xlf | 2 +- .../xlf/CodeFixResources.zh-Hans.xlf | 2 +- .../xlf/CodeFixResources.zh-Hant.xlf | 2 +- src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf | 8 ++++---- src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf | 8 ++++---- src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf | 8 ++++---- src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf | 8 ++++---- src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf | 8 ++++---- src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf | 8 ++++---- src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf | 8 ++++---- src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf | 8 ++++---- 17 files changed, 41 insertions(+), 41 deletions(-) diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.cs.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.cs.xlf index 2cd7939a05..f0cdadaa0e 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.cs.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.cs.xlf @@ -74,7 +74,7 @@ Use 'Assert.{0}' instead of 'StringAssert' - Use 'Assert.{0}' instead of 'StringAssert' + Použijte Assert.{0}místo StringAssert diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.es.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.es.xlf index 3334ac5b90..0f1e41ab01 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.es.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.es.xlf @@ -74,7 +74,7 @@ Use 'Assert.{0}' instead of 'StringAssert' - Use 'Assert.{0}' instead of 'StringAssert' + Use "Assert.{0}" en lugar de "StringAssert" diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.fr.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.fr.xlf index 2895be63f5..28032182a6 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.fr.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.fr.xlf @@ -74,7 +74,7 @@ Use 'Assert.{0}' instead of 'StringAssert' - Use 'Assert.{0}' instead of 'StringAssert' + Utilisez « Assert.{0} » au lieu de « StringAssert » diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.it.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.it.xlf index 357be76d30..ce079335fe 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.it.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.it.xlf @@ -74,7 +74,7 @@ Use 'Assert.{0}' instead of 'StringAssert' - Use 'Assert.{0}' instead of 'StringAssert' + Usa 'Assert.{0}' invece di 'StringAssert' diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ko.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ko.xlf index bc4bb12aab..378b6b3129 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ko.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ko.xlf @@ -74,7 +74,7 @@ Use 'Assert.{0}' instead of 'StringAssert' - Use 'Assert.{0}' instead of 'StringAssert' + 'StringAssert' 대신 'Assert.{0}' 사용 diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pl.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pl.xlf index 17422a475f..16a86f9cb5 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pl.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pl.xlf @@ -74,7 +74,7 @@ Use 'Assert.{0}' instead of 'StringAssert' - Use 'Assert.{0}' instead of 'StringAssert' + Użyj ciągu „Assert.{0}” zamiast ciągu „StringAssert” diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ru.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ru.xlf index 2a4bcf0f43..1a166df4bb 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ru.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ru.xlf @@ -74,7 +74,7 @@ Use 'Assert.{0}' instead of 'StringAssert' - Use 'Assert.{0}' instead of 'StringAssert' + Используйте "Assert.{0}" вместо "StringAssert" diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hans.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hans.xlf index adf31e8ee4..e37b91c542 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hans.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hans.xlf @@ -74,7 +74,7 @@ Use 'Assert.{0}' instead of 'StringAssert' - Use 'Assert.{0}' instead of 'StringAssert' + 使用 'Assert.{0}' 而不是 'StringAssert' diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hant.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hant.xlf index ea6323de02..8782e30dca 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hant.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hant.xlf @@ -74,7 +74,7 @@ Use 'Assert.{0}' instead of 'StringAssert' - Use 'Assert.{0}' instead of 'StringAssert' + 使用 'Assert.{0}' 而不是 'StringAssert' diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf index c6dc824ee7..28403c1afc 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf @@ -278,12 +278,12 @@ Typ deklarující tyto metody by měl také respektovat následující pravidla: DataRow argument types do not match method parameter types. {0} - DataRow argument types do not match method parameter types. {0} + Typy argumentů DataRow neodpovídají typům parametrů metody. {0} Parameter '{0}' expects type '{1}', but the provided value has type '{2}' - Parameter '{0}' expects type '{1}', but the provided value has type '{2}' + Parametr '{0}' očekává typ '{1}', ale zadaná hodnota má typ '{2}' @@ -539,12 +539,12 @@ Typ deklarující tyto metody by měl také respektovat následující pravidla: Use 'Assert.{0}' instead of 'StringAssert.{1}' - Use 'Assert.{0}' instead of 'StringAssert.{1}' + Použijte Assert.{0}' místo StringAssert.{1}' Use 'Assert' instead of 'StringAssert' - Use 'Assert' instead of 'StringAssert' + Použijte Assert místo StringAssert diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf index 5efb90ca1d..71e58eaf00 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf @@ -278,12 +278,12 @@ Anche il tipo che dichiara questi metodi deve rispettare le regole seguenti: DataRow argument types do not match method parameter types. {0} - DataRow argument types do not match method parameter types. {0} + Il tipo di argomento di DataRow deve corrispondere ai tipi di parametro del metodo. {0} Parameter '{0}' expects type '{1}', but the provided value has type '{2}' - Parameter '{0}' expects type '{1}', but the provided value has type '{2}' + Il parametro '{0}' prevede il tipo '{1}', ma il tipo del valore specificato è '{2}' @@ -539,12 +539,12 @@ Anche il tipo che dichiara questi metodi deve rispettare le regole seguenti: Use 'Assert.{0}' instead of 'StringAssert.{1}' - Use 'Assert.{0}' instead of 'StringAssert.{1}' + Usa 'Assert.{0}' invece di 'StringAssert.{1}' Use 'Assert' instead of 'StringAssert' - Use 'Assert' instead of 'StringAssert' + Usa 'Assert' invece di 'StringAssert' diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf index 75c3b0081f..b300258adb 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf @@ -278,12 +278,12 @@ The type declaring these methods should also respect the following rules: DataRow argument types do not match method parameter types. {0} - DataRow argument types do not match method parameter types. {0} + DataRow 인수 형식이 메서드 매개 변수 형식과 일치하지 않습니다. {0} Parameter '{0}' expects type '{1}', but the provided value has type '{2}' - Parameter '{0}' expects type '{1}', but the provided value has type '{2}' + '{0}' 매개 변수에는 '{1}' 형식이 필요한데 제공된 값의 형식은 '{2}'입니다. @@ -539,12 +539,12 @@ The type declaring these methods should also respect the following rules: Use 'Assert.{0}' instead of 'StringAssert.{1}' - Use 'Assert.{0}' instead of 'StringAssert.{1}' + 'StringAssert.{1}' 대신 'Assert.{0}' 사용 Use 'Assert' instead of 'StringAssert' - Use 'Assert' instead of 'StringAssert' + 'StringAssert' 대신 'Assert' 사용 diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf index 55eff8b796..113da1e59f 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf @@ -278,12 +278,12 @@ Typ deklarujący te metody powinien również przestrzegać następujących regu DataRow argument types do not match method parameter types. {0} - DataRow argument types do not match method parameter types. {0} + Typy argumentów DataRow nie są zgodne z typami parametrów metody. {0} Parameter '{0}' expects type '{1}', but the provided value has type '{2}' - Parameter '{0}' expects type '{1}', but the provided value has type '{2}' + Parametr „{0}” oczekuje typu „{1}”, ale podana wartość ma typ „{2}” @@ -539,12 +539,12 @@ Typ deklarujący te metody powinien również przestrzegać następujących regu Use 'Assert.{0}' instead of 'StringAssert.{1}' - Use 'Assert.{0}' instead of 'StringAssert.{1}' + Użyj ciągu „Assert.{0}” zamiast ciągu „StringAssert.{1}” Use 'Assert' instead of 'StringAssert' - Use 'Assert' instead of 'StringAssert' + Użyj ciągu „Assert” zamiast ciągu „StringAssert” diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf index c1760782ff..8fdcabbd8a 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf @@ -284,12 +284,12 @@ The type declaring these methods should also respect the following rules: DataRow argument types do not match method parameter types. {0} - DataRow argument types do not match method parameter types. {0} + Типы аргументов DataRow не соответствуют типам параметров метода. {0} Parameter '{0}' expects type '{1}', but the provided value has type '{2}' - Parameter '{0}' expects type '{1}', but the provided value has type '{2}' + Параметр "{0}" ожидает тип "{1}", но предоставленное значение относится к типу "{2}" @@ -545,12 +545,12 @@ The type declaring these methods should also respect the following rules: Use 'Assert.{0}' instead of 'StringAssert.{1}' - Use 'Assert.{0}' instead of 'StringAssert.{1}' + Используйте "Assert.{0}" вместо "StringAssert.{1}" Use 'Assert' instead of 'StringAssert' - Use 'Assert' instead of 'StringAssert' + Используйте "Assert" вместо "StringAssert" diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf index 47f6e789cc..605cfec512 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf @@ -278,12 +278,12 @@ Bu yöntemleri bildiren tipin ayrıca aşağıdaki kurallara uyması gerekir: DataRow argument types do not match method parameter types. {0} - DataRow argument types do not match method parameter types. {0} + DataRow bağımsız değişken türleri, yöntem parametre türleriyle eşleşmiyor. {0} Parameter '{0}' expects type '{1}', but the provided value has type '{2}' - Parameter '{0}' expects type '{1}', but the provided value has type '{2}' + Parametre ‘{0}’ tipi ‘{1}’ bekliyor, ancak verilen değer ‘{2}’ tipindedir @@ -539,12 +539,12 @@ Bu yöntemleri bildiren tipin ayrıca aşağıdaki kurallara uyması gerekir: Use 'Assert.{0}' instead of 'StringAssert.{1}' - Use 'Assert.{0}' instead of 'StringAssert.{1}' + ‘StringAssert.{1}’ yerine ‘Assert.{0}’ kullanın Use 'Assert' instead of 'StringAssert' - Use 'Assert' instead of 'StringAssert' + ‘StringAssert’ yerine ‘Assert’ kullanın diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf index 262662fb6f..35666c9f6e 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf @@ -278,12 +278,12 @@ The type declaring these methods should also respect the following rules: DataRow argument types do not match method parameter types. {0} - DataRow argument types do not match method parameter types. {0} + DataRow 参数类型与方法参数类型不匹配。{0} Parameter '{0}' expects type '{1}', but the provided value has type '{2}' - Parameter '{0}' expects type '{1}', but the provided value has type '{2}' + 参数 ‘{0}’ 需要类型 ‘{1}’,但提供的值类型为 ‘{2}’ @@ -539,12 +539,12 @@ The type declaring these methods should also respect the following rules: Use 'Assert.{0}' instead of 'StringAssert.{1}' - Use 'Assert.{0}' instead of 'StringAssert.{1}' + 使用 'Assert.{0}' 而不是 'StringAssert.{1}' Use 'Assert' instead of 'StringAssert' - Use 'Assert' instead of 'StringAssert' + 使用 'Assert' 而不是 'StringAssert' diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf index 6113380da4..eee571adc5 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf @@ -278,12 +278,12 @@ The type declaring these methods should also respect the following rules: DataRow argument types do not match method parameter types. {0} - DataRow argument types do not match method parameter types. {0} + DataRow 引數類型不符合方法參數類型。{0} Parameter '{0}' expects type '{1}', but the provided value has type '{2}' - Parameter '{0}' expects type '{1}', but the provided value has type '{2}' + 參數 '{0}' 期望類型為 '{1}',但提供的值的類型為 '{2}' @@ -539,12 +539,12 @@ The type declaring these methods should also respect the following rules: Use 'Assert.{0}' instead of 'StringAssert.{1}' - Use 'Assert.{0}' instead of 'StringAssert.{1}' + 使用 'Assert.{0}' 而不是 'StringAssert.{1}' Use 'Assert' instead of 'StringAssert' - Use 'Assert' instead of 'StringAssert' + 使用 'Assert' 而不是 'StringAssert' From ff001af6d908606cb0137f9c5101fbc42d33d386 Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Thu, 10 Jul 2025 21:44:53 +1000 Subject: [PATCH 182/541] fix nullablity in FromFailedTest (#5971) --- .../Tasks/FailedTestHelper.cs | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Platform.MSBuild/Tasks/FailedTestHelper.cs b/src/Platform/Microsoft.Testing.Platform.MSBuild/Tasks/FailedTestHelper.cs index 0c6e51a65f..138f407108 100644 --- a/src/Platform/Microsoft.Testing.Platform.MSBuild/Tasks/FailedTestHelper.cs +++ b/src/Platform/Microsoft.Testing.Platform.MSBuild/Tasks/FailedTestHelper.cs @@ -71,17 +71,16 @@ internal static void FromFailedTest(this FailedTestInfoRequest failedTestInfoReq string nameAndPlace = place == null ? $"{failedTestInfoRequest.DisplayName} ({failedTestInfoRequest.Duration})" : $"{failedTestInfoRequest.DisplayName} ({failedTestInfoRequest.Duration}): {place}"; - string? singleLineError = JoinSingleLineAndShorten(nameAndPlace, failedTestInfoRequest.ErrorMessage); - message = singleLineError!; + message = JoinSingleLineAndShorten(nameAndPlace, failedTestInfoRequest.ErrorMessage); } } - private static string? JoinSingleLineAndShorten(string first, string? second) + private static string JoinSingleLineAndShorten(string first, string? second) => second == null ? SingleLineAndShorten(first) : SingleLineAndShorten(first) + " " + SingleLineAndShorten(second); - private static string? SingleLineAndShorten(string? text) - => text == null ? null : (text.Length <= 1000 ? text : text[..1000]).Replace('\r', ' ').Replace('\n', ' '); + private static string SingleLineAndShorten(string text) => + (text.Length <= 1000 ? text : text[..1000]).Replace('\r', ' ').Replace('\n', ' '); } From abf78fe511841622cb8ae2243def6838ae083216 Mon Sep 17 00:00:00 2001 From: dotnet bot Date: Thu, 10 Jul 2025 13:56:45 +0200 Subject: [PATCH 183/541] Localized file check-in by OneLocBuild Task: Build definition ID 1218: Build ID 2747122 --- .../xlf/CodeFixResources.pt-BR.xlf | 2 +- .../xlf/CodeFixResources.tr.xlf | 2 +- src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf | 8 ++++---- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pt-BR.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pt-BR.xlf index 705260fc18..2d7501bc44 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pt-BR.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pt-BR.xlf @@ -74,7 +74,7 @@ Use 'Assert.{0}' instead of 'StringAssert' - Use 'Assert.{0}' instead of 'StringAssert' + Use 'Assert'{0}. em vez de 'StringAssert' diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.tr.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.tr.xlf index f6b61b99f2..2ed16a4416 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.tr.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.tr.xlf @@ -74,7 +74,7 @@ Use 'Assert.{0}' instead of 'StringAssert' - Use 'Assert.{0}' instead of 'StringAssert' + ‘StringAssert’ yerine ‘Assert.{0}’ kullanın diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf index 222dd7a9ae..359f90963a 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf @@ -278,12 +278,12 @@ O tipo que declara esses métodos também deve respeitar as seguintes regras: DataRow argument types do not match method parameter types. {0} - DataRow argument types do not match method parameter types. {0} + Os tipos de argumento do DataRow não correspondem aos tipos de parâmetro do método. {0} Parameter '{0}' expects type '{1}', but the provided value has type '{2}' - Parameter '{0}' expects type '{1}', but the provided value has type '{2}' + O parâmetro "{0}" espera o tipo "{1}", mas o valor fornecido tem o tipo "{2}" @@ -539,12 +539,12 @@ O tipo que declara esses métodos também deve respeitar as seguintes regras: Use 'Assert.{0}' instead of 'StringAssert.{1}' - Use 'Assert.{0}' instead of 'StringAssert.{1}' + Use "Assert.{0}" em vez de "StringAssert.{1}" Use 'Assert' instead of 'StringAssert' - Use 'Assert' instead of 'StringAssert' + Usar "Assert" em vez de "StringAssert" From 5a96b05383ad9a9abf2af8172577e1db1cdb700f Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Thu, 10 Jul 2025 22:00:09 +1000 Subject: [PATCH 184/541] make dicts in NamedPipeBase strong typed (#5973) --- .../Microsoft.Testing.Platform/IPC/NamedPipeBase.cs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Platform/IPC/NamedPipeBase.cs b/src/Platform/Microsoft.Testing.Platform/IPC/NamedPipeBase.cs index 4a12606676..c511303584 100644 --- a/src/Platform/Microsoft.Testing.Platform/IPC/NamedPipeBase.cs +++ b/src/Platform/Microsoft.Testing.Platform/IPC/NamedPipeBase.cs @@ -9,8 +9,8 @@ namespace Microsoft.Testing.Platform.IPC; internal abstract class NamedPipeBase { - private readonly Dictionary _typeSerializer = []; - private readonly Dictionary _idSerializer = []; + private readonly Dictionary _typeSerializer = []; + private readonly Dictionary _idSerializer = []; public void RegisterSerializer(INamedPipeSerializer namedPipeSerializer, Type type) { @@ -19,16 +19,16 @@ public void RegisterSerializer(INamedPipeSerializer namedPipeSerializer, Type ty } protected INamedPipeSerializer GetSerializer(int id) - => _idSerializer.TryGetValue(id, out object? serializer) - ? (INamedPipeSerializer)serializer + => _idSerializer.TryGetValue(id, out INamedPipeSerializer? serializer) + ? serializer : throw new ArgumentException(string.Format( CultureInfo.InvariantCulture, PlatformResources.NoSerializerRegisteredWithIdErrorMessage, id)); protected INamedPipeSerializer GetSerializer(Type type) - => _typeSerializer.TryGetValue(type, out object? serializer) - ? (INamedPipeSerializer)serializer + => _typeSerializer.TryGetValue(type, out INamedPipeSerializer? serializer) + ? serializer : throw new ArgumentException(string.Format( CultureInfo.InvariantCulture, PlatformResources.NoSerializerRegisteredWithTypeErrorMessage, From 9a0ec1723ab84d2ceac9c6025900ffb7f2073954 Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Thu, 10 Jul 2025 22:00:56 +1000 Subject: [PATCH 185/541] remove some dead consts in EngineConstants (#5967) --- .../MSTestAdapter.PlatformServices/EngineConstants.cs | 6 ------ 1 file changed, 6 deletions(-) diff --git a/src/Adapter/MSTestAdapter.PlatformServices/EngineConstants.cs b/src/Adapter/MSTestAdapter.PlatformServices/EngineConstants.cs index 4b4bff2115..0659af433f 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/EngineConstants.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/EngineConstants.cs @@ -28,12 +28,6 @@ internal static class EngineConstants #if NETFRAMEWORK internal const string PhoneAppxPackageExtension = ".appx"; - - // These are tied to a specific VS version. Can be changed to have a list of supported version instead. - internal const string VisualStudioRootRegKey32ForDev14 = @"SOFTWARE\Microsoft\VisualStudio\" + VisualStudioVersion; - internal const string VisualStudioRootRegKey64ForDev14 = @"SOFTWARE\Wow6432Node\Microsoft\VisualStudio\" + VisualStudioVersion; - - internal const string VisualStudioVersion = "14.0"; #endif /// From 320d72530b7385f38d8748f7c8b054ecdf53b2b6 Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Thu, 10 Jul 2025 23:01:43 +1000 Subject: [PATCH 186/541] redundant null check in TryAddSearchDirectoriesSpecifiedInRunSettingsToAssemblyResolver (#5966) --- .../MSTestAdapter.PlatformServices/Services/TestSourceHost.cs | 4 ---- 1 file changed, 4 deletions(-) diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Services/TestSourceHost.cs b/src/Adapter/MSTestAdapter.PlatformServices/Services/TestSourceHost.cs index 377dc36889..fc24400fec 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Services/TestSourceHost.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Services/TestSourceHost.cs @@ -428,10 +428,6 @@ private static bool TryAddSearchDirectoriesSpecifiedInRunSettingsToAssemblyResol { // Check if user specified any adapter settings MSTestAdapterSettings adapterSettings = MSTestSettingsProvider.Settings; - if (adapterSettings == null) - { - return false; - } try { From 59e2a582cba86f67d538a4096d77c9d9fba1c7e7 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Thu, 10 Jul 2025 16:57:49 +0200 Subject: [PATCH 187/541] Update .NET SDK (#5954) --- global.json | 4 ++-- .../Services/TestSourceHost.cs | 15 +++++---------- 2 files changed, 7 insertions(+), 12 deletions(-) diff --git a/global.json b/global.json index eca2b03774..fa4d243f01 100644 --- a/global.json +++ b/global.json @@ -1,6 +1,6 @@ { "tools": { - "dotnet": "10.0.100-preview.6.25315.102", + "dotnet": "10.0.100-preview.7.25359.101", "runtimes": { "dotnet": [ "3.1.32", @@ -23,7 +23,7 @@ } }, "sdk": { - "version": "10.0.100-preview.6.25315.102", + "version": "10.0.100-preview.7.25359.101", "paths": [ ".dotnet", "$host$" diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Services/TestSourceHost.cs b/src/Adapter/MSTestAdapter.PlatformServices/Services/TestSourceHost.cs index fc24400fec..ec92e515ce 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Services/TestSourceHost.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Services/TestSourceHost.cs @@ -221,19 +221,14 @@ public void SetupHost() public void Dispose() { #if NETFRAMEWORK || (NET && !WINDOWS_UWP) - if (_parentDomainAssemblyResolver != null) - { - _parentDomainAssemblyResolver.Dispose(); - _parentDomainAssemblyResolver = null; - } + _parentDomainAssemblyResolver?.Dispose(); + _parentDomainAssemblyResolver = null; + #endif #if NETFRAMEWORK - if (_childDomainAssemblyResolver != null) - { - _childDomainAssemblyResolver.Dispose(); - _childDomainAssemblyResolver = null; - } + _childDomainAssemblyResolver?.Dispose(); + _childDomainAssemblyResolver = null; if (AppDomain != null) { From e6d18f4b5692ebc88f7b3b5d585b10a8a0b5c798 Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Fri, 11 Jul 2025 06:36:26 +1000 Subject: [PATCH 188/541] simplify reading installLocation content (#5968) --- .../Tasks/DotnetMuxerLocator.cs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Platform.MSBuild/Tasks/DotnetMuxerLocator.cs b/src/Platform/Microsoft.Testing.Platform.MSBuild/Tasks/DotnetMuxerLocator.cs index 28b8da2477..187797b51b 100644 --- a/src/Platform/Microsoft.Testing.Platform.MSBuild/Tasks/DotnetMuxerLocator.cs +++ b/src/Platform/Microsoft.Testing.Platform.MSBuild/Tasks/DotnetMuxerLocator.cs @@ -287,9 +287,7 @@ public bool TryGetDotnetPathByArchitecture( try { - using Stream stream = new FileStream(installLocation, FileMode.Open, FileAccess.Read); - using StreamReader streamReader = new(stream); - string content = streamReader.ReadToEnd().Trim(); + string content = File.ReadAllText(installLocation).Trim(); _resolutionLog($"DotnetHostHelper: '{installLocation}' content '{content}'"); string path = Path.Combine(content, _muxerName); _resolutionLog($"DotnetHostHelper: Muxer resolved using '{installLocation}' in '{path}'"); From 0626897e64c3c0c21dbad31bc3afa0ba6e8b8cca Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Fri, 11 Jul 2025 06:41:15 +1000 Subject: [PATCH 189/541] update Polyfill and use Process.Kill (#5943) --- .../Helpers/System/SystemProcess.cs | 5 ----- 1 file changed, 5 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Platform/Helpers/System/SystemProcess.cs b/src/Platform/Microsoft.Testing.Platform/Helpers/System/SystemProcess.cs index d38a5e75a9..13999b22be 100644 --- a/src/Platform/Microsoft.Testing.Platform/Helpers/System/SystemProcess.cs +++ b/src/Platform/Microsoft.Testing.Platform/Helpers/System/SystemProcess.cs @@ -43,13 +43,8 @@ public void WaitForExit() public Task WaitForExitAsync() => _process.WaitForExitAsync(); -#if NETCOREAPP public void Kill() => _process.Kill(true); -#else - public void Kill() - => _process.Kill(); -#endif public void Dispose() => _process.Dispose(); #pragma warning restore CA1416 From 24f094b08976aecf28cfc38411c15656ad6b0543 Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Fri, 11 Jul 2025 17:14:36 +1000 Subject: [PATCH 190/541] avoid dictionary lookups using TryAdd (#5983) --- src/Adapter/MSTest.Engine/Engine/TestArgumentsManager.cs | 6 +++--- .../Discovery/AssemblyEnumerator.cs | 3 +-- .../ServerMode/JsonRpc/SerializerUtilities.cs | 5 +---- .../TestFramework/Assertions/CollectionAssert.cs | 8 +------- 4 files changed, 6 insertions(+), 16 deletions(-) diff --git a/src/Adapter/MSTest.Engine/Engine/TestArgumentsManager.cs b/src/Adapter/MSTest.Engine/Engine/TestArgumentsManager.cs index d193d1871d..727a017a2a 100644 --- a/src/Adapter/MSTest.Engine/Engine/TestArgumentsManager.cs +++ b/src/Adapter/MSTest.Engine/Engine/TestArgumentsManager.cs @@ -3,6 +3,8 @@ using Microsoft.Testing.Platform; +using Polyfills; + namespace Microsoft.Testing.Framework; internal sealed class TestArgumentsManager : ITestArgumentsManager @@ -19,12 +21,10 @@ public void RegisterTestArgumentsEntryProvider( throw new InvalidOperationException("Cannot register TestArgumentsEntry provider after registration is frozen."); } - if (_testArgumentsEntryProviders.ContainsKey(testNodeStableUid)) + if (!_testArgumentsEntryProviders.TryAdd(testNodeStableUid, argumentPropertiesProviderCallback)) { throw new InvalidOperationException($"TestArgumentsEntry provider is already registered for test node with UID '{testNodeStableUid}'."); } - - _testArgumentsEntryProviders.Add(testNodeStableUid, argumentPropertiesProviderCallback); } internal void FreezeRegistration() => _isRegistrationFrozen = true; diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Discovery/AssemblyEnumerator.cs b/src/Adapter/MSTestAdapter.PlatformServices/Discovery/AssemblyEnumerator.cs index 65ae31ca6d..c4f93526f5 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Discovery/AssemblyEnumerator.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Discovery/AssemblyEnumerator.cs @@ -173,9 +173,8 @@ internal static string GetLoadExceptionDetails(ReflectionTypeLoadException ex) { DebugEx.Assert(loaderException != null, "loader exception should not be null."); string line = string.Format(CultureInfo.CurrentCulture, Resource.EnumeratorLoadTypeErrorFormat, loaderException.GetType(), loaderException.Message); - if (!map.ContainsKey(line)) + if (map.TryAdd(line, null)) { - map.Add(line, null); errorDetails.AppendLine(line); } } diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/SerializerUtilities.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/SerializerUtilities.cs index a8a9f11a6b..1a47c209e4 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/SerializerUtilities.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/SerializerUtilities.cs @@ -354,10 +354,7 @@ static SerializerUtilities() } } - if (!properties.ContainsKey("node-type")) - { - properties["node-type"] = "group"; - } + properties.TryAdd("node-type", "group"); return properties; }); diff --git a/src/TestFramework/TestFramework/Assertions/CollectionAssert.cs b/src/TestFramework/TestFramework/Assertions/CollectionAssert.cs index 436ce32d50..bb65e2780e 100644 --- a/src/TestFramework/TestFramework/Assertions/CollectionAssert.cs +++ b/src/TestFramework/TestFramework/Assertions/CollectionAssert.cs @@ -343,8 +343,7 @@ public static void AllItemsAreUnique([NotNull] ICollection? collection, [StringS } else { -#pragma warning disable CA1864 // Prefer the 'IDictionary.TryAdd(TKey, TValue)' method - if (table.ContainsKey(current)) + if (!table.TryAdd(current, true)) { string userMessage = Assert.BuildUserMessage(message, parameters); string finalMessage = string.Format( @@ -355,11 +354,6 @@ public static void AllItemsAreUnique([NotNull] ICollection? collection, [StringS Assert.ThrowAssertFailed("CollectionAssert.AllItemsAreUnique", finalMessage); } - else - { - table.Add(current, true); - } -#pragma warning restore CA1864 // Prefer the 'IDictionary.TryAdd(TKey, TValue)' method } } } From 5ab9fe7c600c56bb8792edf3ad9867aae73e3d22 Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Fri, 11 Jul 2025 18:08:50 +1000 Subject: [PATCH 191/541] Simplify IProcess.MainModule (#5955) Co-authored-by: Youssef Victor --- .../Helpers/System/IProcess.cs | 5 ----- .../Helpers/System/SystemProcess.cs | 7 +------ .../Services/CurrentTestApplicationModuleInfo.cs | 14 ++++++-------- 3 files changed, 7 insertions(+), 19 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Platform/Helpers/System/IProcess.cs b/src/Platform/Microsoft.Testing.Platform/Helpers/System/IProcess.cs index df8a966669..49f677afd2 100644 --- a/src/Platform/Microsoft.Testing.Platform/Helpers/System/IProcess.cs +++ b/src/Platform/Microsoft.Testing.Platform/Helpers/System/IProcess.cs @@ -19,13 +19,8 @@ internal interface IProcess : IDisposable /// bool HasExited { get; } -#if NETCOREAPP /// IMainModule? MainModule { get; } -#else - /// - IMainModule MainModule { get; } -#endif /// /// Instructs the Process component to wait for the associated process to exit, or for the cancellationToken to be canceled. diff --git a/src/Platform/Microsoft.Testing.Platform/Helpers/System/SystemProcess.cs b/src/Platform/Microsoft.Testing.Platform/Helpers/System/SystemProcess.cs index 13999b22be..17f6caa6bc 100644 --- a/src/Platform/Microsoft.Testing.Platform/Helpers/System/SystemProcess.cs +++ b/src/Platform/Microsoft.Testing.Platform/Helpers/System/SystemProcess.cs @@ -24,15 +24,10 @@ public SystemProcess(Process process) public int ExitCode => _process.ExitCode; -#if NETCOREAPP public IMainModule? MainModule => _process.MainModule is null ? null - : (IMainModule)new SystemMainModule(_process.MainModule); -#else - public IMainModule MainModule - => new SystemMainModule(_process.MainModule); -#endif + : new SystemMainModule(_process.MainModule); private void OnProcessExited(object? sender, EventArgs e) => Exited?.Invoke(sender, e); diff --git a/src/Platform/Microsoft.Testing.Platform/Services/CurrentTestApplicationModuleInfo.cs b/src/Platform/Microsoft.Testing.Platform/Services/CurrentTestApplicationModuleInfo.cs index 8af8270867..8f8fffd0ed 100644 --- a/src/Platform/Microsoft.Testing.Platform/Services/CurrentTestApplicationModuleInfo.cs +++ b/src/Platform/Microsoft.Testing.Platform/Services/CurrentTestApplicationModuleInfo.cs @@ -85,20 +85,18 @@ public string GetProcessPath() => GetProcessPath(_environment, _process, throwOnNull: true)!; private static string? GetProcessPath(IEnvironment environment, IProcessHandler process, bool throwOnNull = false) -#if NETCOREAPP { +#if NETCOREAPP string? processPath = environment.ProcessPath; - ApplicationStateGuard.Ensure(processPath is not null || !throwOnNull); - - return processPath; - } #else - { using IProcess currentProcess = process.GetCurrentProcess(); - return currentProcess.MainModule.FileName; - } + string? processPath = currentProcess.MainModule?.FileName; #endif + ApplicationStateGuard.Ensure(processPath is not null || !throwOnNull); + return processPath; + } + public ExecutableInfo GetCurrentExecutableInfo() { bool isDotnetMuxer = IsCurrentTestApplicationHostDotnetMuxer; From 45cfde31112658ef9c31223452269518fa035470 Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Fri, 11 Jul 2025 18:22:02 +1000 Subject: [PATCH 192/541] use ReadExactly from Polyfill (#5972) --- Directory.Packages.props | 2 +- .../IPC/Serializers/BaseSerializer.cs | 28 ------------------- 2 files changed, 1 insertion(+), 29 deletions(-) diff --git a/Directory.Packages.props b/Directory.Packages.props index f184570289..36a006caaf 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -54,7 +54,7 @@ - + diff --git a/src/Platform/Microsoft.Testing.Platform/IPC/Serializers/BaseSerializer.cs b/src/Platform/Microsoft.Testing.Platform/IPC/Serializers/BaseSerializer.cs index ee10295eae..5847336210 100644 --- a/src/Platform/Microsoft.Testing.Platform/IPC/Serializers/BaseSerializer.cs +++ b/src/Platform/Microsoft.Testing.Platform/IPC/Serializers/BaseSerializer.cs @@ -18,20 +18,12 @@ internal abstract class BaseSerializer protected static string ReadString(Stream stream) { Span len = stackalloc byte[sizeof(int)]; -#if NET7_0_OR_GREATER stream.ReadExactly(len); -#else - _ = stream.Read(len); -#endif int stringLen = BitConverter.ToInt32(len); byte[] bytes = ArrayPool.Shared.Rent(stringLen); try { -#if NET7_0_OR_GREATER stream.ReadExactly(bytes, 0, stringLen); -#else - _ = stream.Read(bytes, 0, stringLen); -#endif return Encoding.UTF8.GetString(bytes, 0, stringLen); } finally @@ -45,11 +37,7 @@ protected static string ReadStringValue(Stream stream, int size) byte[] bytes = ArrayPool.Shared.Rent(size); try { -#if NET7_0_OR_GREATER stream.ReadExactly(bytes, 0, size); -#else - _ = stream.Read(bytes, 0, size); -#endif return Encoding.UTF8.GetString(bytes, 0, size); } finally @@ -148,44 +136,28 @@ protected static void WriteBool(Stream stream, bool value) protected static int ReadInt(Stream stream) { Span bytes = stackalloc byte[sizeof(int)]; -#if NET7_0_OR_GREATER stream.ReadExactly(bytes); -#else - _ = stream.Read(bytes); -#endif return BitConverter.ToInt32(bytes); } protected static long ReadLong(Stream stream) { Span bytes = stackalloc byte[sizeof(long)]; -#if NET7_0_OR_GREATER stream.ReadExactly(bytes); -#else - _ = stream.Read(bytes); -#endif return BitConverter.ToInt64(bytes); } protected static ushort ReadShort(Stream stream) { Span bytes = stackalloc byte[sizeof(ushort)]; -#if NET7_0_OR_GREATER stream.ReadExactly(bytes); -#else - _ = stream.Read(bytes); -#endif return BitConverter.ToUInt16(bytes); } protected static bool ReadBool(Stream stream) { Span bytes = stackalloc byte[sizeof(bool)]; -#if NET7_0_OR_GREATER stream.ReadExactly(bytes); -#else - _ = stream.Read(bytes); -#endif return BitConverter.ToBoolean(bytes); } From 69ed5b21fea794d50e479cd4999e01981f9a6622 Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Fri, 11 Jul 2025 18:23:25 +1000 Subject: [PATCH 193/541] suppress TPEXP warning for solution (#5984) --- Directory.Build.props | 3 +++ src/Adapter/MSTest.Engine/Engine/BFSTestNodeVisitor.cs | 1 - .../TestingPlatformAdapter/MSTestBannerCapability.cs | 2 -- .../MSTestGracefulStopTestExecutionCapability.cs | 3 --- .../TestApplicationBuilderExtensions.cs | 4 ---- .../HotReloadTestHostTestFrameworkInvoker.cs | 2 -- .../ObjectModel/FrameworkHandlerAdapter.cs | 2 -- .../ObjectModel/RunSettingsAdapter.cs | 2 -- .../ObjectModel/RunSettingsPatcher.cs | 2 -- .../ObjectModel/TestCaseDiscoverySinkAdapter.cs | 2 -- .../VSTestBridgedTestFrameworkBase.cs | 2 -- .../Adapter_ExecuteRequestAsyncTests.cs | 6 ------ .../MSTest.Engine.UnitTests/BFSTestNodeVisitorTests.cs | 1 - .../ObjectModel/ObjectModelConvertersTests.cs | 2 -- .../Requests/TreeNodeFilterTests.cs | 1 - .../ServerMode/FormatterUtilitiesTests.cs | 2 -- 16 files changed, 3 insertions(+), 34 deletions(-) diff --git a/Directory.Build.props b/Directory.Build.props index bde2c77e9a..92b7d2dad5 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -36,6 +36,9 @@ embedded 0024000004800000940000000602000000240000525341310004000001000100c547cac37abd99c8db225ef2f6c8a3602f3b3606cc9891605d02baa56104f4cfc0734aa39b93bf7852f7d9266654753cc297e7d2edfe0bac1cdcf9f717241550e0a7b191195b7667bb4f64bcb8e2121380fd1d9d46ad2d92d2d15605093924cceaf74c4861eff62abf69b9291ed0a340e113be11e6a7d3113e92484cf7045cc7 + + + $(NoWarn);TPEXP diff --git a/src/Adapter/MSTest.Engine/Engine/BFSTestNodeVisitor.cs b/src/Adapter/MSTest.Engine/Engine/BFSTestNodeVisitor.cs index a4111e8f36..faa7301a1b 100644 --- a/src/Adapter/MSTest.Engine/Engine/BFSTestNodeVisitor.cs +++ b/src/Adapter/MSTest.Engine/Engine/BFSTestNodeVisitor.cs @@ -9,7 +9,6 @@ namespace Microsoft.Testing.Framework; -#pragma warning disable TPEXP // Type is for evaluation purposes only and is subject to change or removal in future updates. Suppress this diagnostic to proceed. internal sealed class BFSTestNodeVisitor { private readonly IEnumerable _rootTestNodes; diff --git a/src/Adapter/MSTest.TestAdapter/TestingPlatformAdapter/MSTestBannerCapability.cs b/src/Adapter/MSTest.TestAdapter/TestingPlatformAdapter/MSTestBannerCapability.cs index 3ebc32ee6d..f00335287c 100644 --- a/src/Adapter/MSTest.TestAdapter/TestingPlatformAdapter/MSTestBannerCapability.cs +++ b/src/Adapter/MSTest.TestAdapter/TestingPlatformAdapter/MSTestBannerCapability.cs @@ -7,8 +7,6 @@ namespace Microsoft.VisualStudio.TestTools.UnitTesting; -#pragma warning disable TPEXP // Type is for evaluation purposes only and is subject to change or removal in future updates. Suppress this diagnostic to proceed. - [SuppressMessage("ApiDesign", "RS0030:Do not use banned APIs", Justification = "We can use MTP from this folder")] internal sealed class MSTestBannerCapability : IBannerMessageOwnerCapability { diff --git a/src/Adapter/MSTest.TestAdapter/TestingPlatformAdapter/MSTestGracefulStopTestExecutionCapability.cs b/src/Adapter/MSTest.TestAdapter/TestingPlatformAdapter/MSTestGracefulStopTestExecutionCapability.cs index ea80488cb6..01bce0f496 100644 --- a/src/Adapter/MSTest.TestAdapter/TestingPlatformAdapter/MSTestGracefulStopTestExecutionCapability.cs +++ b/src/Adapter/MSTest.TestAdapter/TestingPlatformAdapter/MSTestGracefulStopTestExecutionCapability.cs @@ -7,11 +7,8 @@ namespace Microsoft.VisualStudio.TestTools.UnitTesting; -#pragma warning disable TPEXP // Type is for evaluation purposes only and is subject to change or removal in future updates. Suppress this diagnostic to proceed. - [SuppressMessage("ApiDesign", "RS0030:Do not use banned APIs", Justification = "We can use MTP from this folder")] internal sealed class MSTestGracefulStopTestExecutionCapability : IGracefulStopTestExecutionCapability -#pragma warning restore TPEXP // Type is for evaluation purposes only and is subject to change or removal in future updates. Suppress this diagnostic to proceed. { private MSTestGracefulStopTestExecutionCapability() { diff --git a/src/Adapter/MSTest.TestAdapter/TestingPlatformAdapter/TestApplicationBuilderExtensions.cs b/src/Adapter/MSTest.TestAdapter/TestingPlatformAdapter/TestApplicationBuilderExtensions.cs index 326c85f88f..4166a55daa 100644 --- a/src/Adapter/MSTest.TestAdapter/TestingPlatformAdapter/TestApplicationBuilderExtensions.cs +++ b/src/Adapter/MSTest.TestAdapter/TestingPlatformAdapter/TestApplicationBuilderExtensions.cs @@ -39,17 +39,13 @@ public static void AddMSTest(this ITestApplicationBuilder testApplicationBuilder testApplicationBuilder.AddRunSettingsService(extension); testApplicationBuilder.AddTestCaseFilterService(extension); testApplicationBuilder.AddTestRunParametersService(extension); -#pragma warning disable TPEXP // Type is for evaluation purposes only and is subject to change or removal in future updates. Suppress this diagnostic to proceed. testApplicationBuilder.AddMaximumFailedTestsService(extension); -#pragma warning restore TPEXP // Type is for evaluation purposes only and is subject to change or removal in future updates. Suppress this diagnostic to proceed. testApplicationBuilder.AddRunSettingsEnvironmentVariableProvider(extension); testApplicationBuilder.RegisterTestFramework( serviceProvider => new TestFrameworkCapabilities( new MSTestCapabilities(), -#pragma warning disable TPEXP // Type is for evaluation purposes only and is subject to change or removal in future updates. Suppress this diagnostic to proceed. new MSTestBannerCapability(serviceProvider.GetRequiredService()), MSTestGracefulStopTestExecutionCapability.Instance), -#pragma warning restore TPEXP // Type is for evaluation purposes only and is subject to change or removal in future updates. Suppress this diagnostic to proceed. (capabilities, serviceProvider) => new MSTestBridgedTestFramework(extension, getTestAssemblies, serviceProvider, capabilities)); } } diff --git a/src/Platform/Microsoft.Testing.Extensions.HotReload/HotReloadTestHostTestFrameworkInvoker.cs b/src/Platform/Microsoft.Testing.Extensions.HotReload/HotReloadTestHostTestFrameworkInvoker.cs index 72278a0a33..f28b457c82 100644 --- a/src/Platform/Microsoft.Testing.Extensions.HotReload/HotReloadTestHostTestFrameworkInvoker.cs +++ b/src/Platform/Microsoft.Testing.Extensions.HotReload/HotReloadTestHostTestFrameworkInvoker.cs @@ -51,9 +51,7 @@ public override async Task ExecuteRequestAsync(ITestFramework testFrameworkAdapt await hotReloadOutputDevice.DisplayBeforeHotReloadSessionStartAsync().ConfigureAwait(false); } -#pragma warning disable TPEXP // Type is for evaluation purposes only and is subject to change or removal in future updates. Suppress this diagnostic to proceed. await testFrameworkAdapter.ExecuteRequestAsync(new(request, messageBus, new SemaphoreSlimRequestCompleteNotifier(requestSemaphore), cancellationToken)).ConfigureAwait(false); -#pragma warning restore TPEXP // Type is for evaluation purposes only and is subject to change or removal in future updates. Suppress this diagnostic to proceed. await requestSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false); await ServiceProvider.GetBaseMessageBus().DrainDataAsync().ConfigureAwait(false); diff --git a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/FrameworkHandlerAdapter.cs b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/FrameworkHandlerAdapter.cs index d5406b4ed8..c0c58665a8 100644 --- a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/FrameworkHandlerAdapter.cs +++ b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/FrameworkHandlerAdapter.cs @@ -1,8 +1,6 @@ // 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 TPEXP // Type is for evaluation purposes only and is subject to change or removal in future updates. Suppress this diagnostic to proceed. - using Microsoft.Testing.Extensions.VSTestBridge.Helpers; using Microsoft.Testing.Platform.Capabilities.TestFramework; using Microsoft.Testing.Platform.CommandLine; diff --git a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/RunSettingsAdapter.cs b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/RunSettingsAdapter.cs index 912eaa084a..0c535f13e4 100644 --- a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/RunSettingsAdapter.cs +++ b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/RunSettingsAdapter.cs @@ -1,8 +1,6 @@ // 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 TPEXP // Type is for evaluation purposes only and is subject to change or removal in future updates. Suppress this diagnostic to proceed. - using Microsoft.Testing.Extensions.VSTestBridge.CommandLine; using Microsoft.Testing.Extensions.VSTestBridge.Resources; using Microsoft.Testing.Platform; diff --git a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/RunSettingsPatcher.cs b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/RunSettingsPatcher.cs index 75ec2efa0e..7a7dceecd5 100644 --- a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/RunSettingsPatcher.cs +++ b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/RunSettingsPatcher.cs @@ -1,8 +1,6 @@ // 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 TPEXP // Type is for evaluation purposes only and is subject to change or removal in future updates. Suppress this diagnostic to proceed. - using Microsoft.Testing.Extensions.VSTestBridge.CommandLine; using Microsoft.Testing.Extensions.VSTestBridge.Resources; using Microsoft.Testing.Platform; diff --git a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/TestCaseDiscoverySinkAdapter.cs b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/TestCaseDiscoverySinkAdapter.cs index 390b979878..f3d7226158 100644 --- a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/TestCaseDiscoverySinkAdapter.cs +++ b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/TestCaseDiscoverySinkAdapter.cs @@ -1,8 +1,6 @@ // 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 TPEXP // Type is for evaluation purposes only and is subject to change or removal in future updates. Suppress this diagnostic to proceed. - using Microsoft.Testing.Extensions.VSTestBridge.Helpers; using Microsoft.Testing.Platform.Capabilities.TestFramework; using Microsoft.Testing.Platform.CommandLine; diff --git a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/VSTestBridgedTestFrameworkBase.cs b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/VSTestBridgedTestFrameworkBase.cs index 346c5d230e..b52022ecd0 100644 --- a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/VSTestBridgedTestFrameworkBase.cs +++ b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/VSTestBridgedTestFrameworkBase.cs @@ -1,8 +1,6 @@ // 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 TPEXP // Type is for evaluation purposes only and is subject to change or removal in future updates. Suppress this diagnostic to proceed. - using Microsoft.Testing.Extensions.TrxReport.Abstractions; using Microsoft.Testing.Extensions.VSTestBridge.Helpers; using Microsoft.Testing.Extensions.VSTestBridge.ObjectModel; diff --git a/test/UnitTests/MSTest.Engine.UnitTests/Adapter_ExecuteRequestAsyncTests.cs b/test/UnitTests/MSTest.Engine.UnitTests/Adapter_ExecuteRequestAsyncTests.cs index 5b7e1a422b..620cce4afd 100644 --- a/test/UnitTests/MSTest.Engine.UnitTests/Adapter_ExecuteRequestAsyncTests.cs +++ b/test/UnitTests/MSTest.Engine.UnitTests/Adapter_ExecuteRequestAsyncTests.cs @@ -33,13 +33,11 @@ public async Task ExecutableNode_ThatDoesNotThrow_ShouldReportPassed() CancellationToken cancellationToken = CancellationToken.None; // Act -#pragma warning disable TPEXP // Type is for evaluation purposes only and is subject to change or removal in future updates. Suppress this diagnostic to proceed. await adapter.ExecuteRequestAsync(new( new RunTestExecutionRequest(new(new("id"), new ClientInfo(string.Empty, string.Empty))), services.ServiceProvider.GetRequiredService(), new SemaphoreSlimRequestCompleteNotifier(new SemaphoreSlim(1)), cancellationToken)); -#pragma warning restore TPEXP // Type is for evaluation purposes only and is subject to change or removal in future updates. Suppress this diagnostic to proceed. // Assert IEnumerable nodeStateChanges = services.MessageBus.Messages.OfType(); @@ -67,13 +65,11 @@ public async Task ExecutableNode_ThatThrows_ShouldReportError() CancellationToken cancellationToken = CancellationToken.None; // Act -#pragma warning disable TPEXP // Type is for evaluation purposes only and is subject to change or removal in future updates. Suppress this diagnostic to proceed. await adapter.ExecuteRequestAsync(new( new RunTestExecutionRequest(new(new("id"), new ClientInfo(string.Empty, string.Empty))), services.ServiceProvider.GetRequiredService(), new SemaphoreSlimRequestCompleteNotifier(new SemaphoreSlim(1)), cancellationToken)); -#pragma warning restore TPEXP // Type is for evaluation purposes only and is subject to change or removal in future updates. Suppress this diagnostic to proceed. // Assert IEnumerable nodeStateChanges = services.MessageBus.Messages.OfType(); @@ -115,9 +111,7 @@ public Services() ServiceProvider.AddService(new LoggerFactory()); ServiceProvider.AddService(new FakeClock()); ServiceProvider.AddService(new SystemTask()); -#pragma warning disable TPEXP // Type is for evaluation purposes only and is subject to change or removal in future updates. Suppress this diagnostic to proceed. ServiceProvider.AddService(new AggregatedConfiguration([], new CurrentTestApplicationModuleInfo(new SystemEnvironment(), new SystemProcessHandler()), new SystemFileSystem(), new(null, [], []))); -#pragma warning restore TPEXP // Type is for evaluation purposes only and is subject to change or removal in future updates. Suppress this diagnostic to proceed. } public MessageBus MessageBus { get; } diff --git a/test/UnitTests/MSTest.Engine.UnitTests/BFSTestNodeVisitorTests.cs b/test/UnitTests/MSTest.Engine.UnitTests/BFSTestNodeVisitorTests.cs index 6ff2840b2a..da775f0875 100644 --- a/test/UnitTests/MSTest.Engine.UnitTests/BFSTestNodeVisitorTests.cs +++ b/test/UnitTests/MSTest.Engine.UnitTests/BFSTestNodeVisitorTests.cs @@ -4,7 +4,6 @@ using Microsoft.Testing.Platform.Extensions.Messages; using Microsoft.Testing.Platform.Requests; -#pragma warning disable TPEXP // Type is for evaluation purposes only and is subject to change or removal in future updates. Suppress this diagnostic to proceed. namespace Microsoft.Testing.Framework.UnitTests; [TestClass] diff --git a/test/UnitTests/Microsoft.Testing.Extensions.VSTestBridge.UnitTests/ObjectModel/ObjectModelConvertersTests.cs b/test/UnitTests/Microsoft.Testing.Extensions.VSTestBridge.UnitTests/ObjectModel/ObjectModelConvertersTests.cs index 2ffea4396a..a2e8c73d20 100644 --- a/test/UnitTests/Microsoft.Testing.Extensions.VSTestBridge.UnitTests/ObjectModel/ObjectModelConvertersTests.cs +++ b/test/UnitTests/Microsoft.Testing.Extensions.VSTestBridge.UnitTests/ObjectModel/ObjectModelConvertersTests.cs @@ -1,8 +1,6 @@ // 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 TPEXP // Type is for evaluation purposes only and is subject to change or removal in future updates. Suppress this diagnostic to proceed. - using Microsoft.Testing.Extensions.TrxReport.Abstractions; using Microsoft.Testing.Extensions.VSTestBridge.ObjectModel; using Microsoft.Testing.Platform.Capabilities.TestFramework; diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Requests/TreeNodeFilterTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Requests/TreeNodeFilterTests.cs index 5f9e229e99..59862917ab 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Requests/TreeNodeFilterTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Requests/TreeNodeFilterTests.cs @@ -5,7 +5,6 @@ using Microsoft.Testing.Platform.Requests; #pragma warning disable CS0618 // Type or member is obsolete -#pragma warning disable TPEXP // Type is for evaluation purposes only and is subject to change or removal in future updates. Suppress this diagnostic to proceed. namespace Microsoft.Testing.Platform.UnitTests; [TestClass] diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/ServerMode/FormatterUtilitiesTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/ServerMode/FormatterUtilitiesTests.cs index b400dcd61a..6fff45047f 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/ServerMode/FormatterUtilitiesTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/ServerMode/FormatterUtilitiesTests.cs @@ -1,8 +1,6 @@ // 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 TPEXP // Type is for evaluation purposes only and is subject to change or removal in future updates. Suppress this diagnostic to proceed. - using Microsoft.Testing.Platform.Extensions.Messages; using Microsoft.Testing.Platform.ServerMode; From cab3e7f50cc67dea83614a46edcbf766035faa55 Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Fri, 11 Jul 2025 19:21:41 +1000 Subject: [PATCH 194/541] use ReadAllTextAsync from polyfill (#5953) --- .../Helpers/System/SystemFileSystem.cs | 9 --------- 1 file changed, 9 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Platform/Helpers/System/SystemFileSystem.cs b/src/Platform/Microsoft.Testing.Platform/Helpers/System/SystemFileSystem.cs index 564aaf3173..731b81bb9b 100644 --- a/src/Platform/Microsoft.Testing.Platform/Helpers/System/SystemFileSystem.cs +++ b/src/Platform/Microsoft.Testing.Platform/Helpers/System/SystemFileSystem.cs @@ -17,14 +17,5 @@ internal sealed class SystemFileSystem : IFileSystem public string ReadAllText(string path) => File.ReadAllText(path); -#if NETCOREAPP public Task ReadAllTextAsync(string path) => File.ReadAllTextAsync(path); -#else - public async Task ReadAllTextAsync(string path) - { - using FileStream stream = new(path, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, FileOptions.Asynchronous | FileOptions.SequentialScan); - using StreamReader reader = new(stream); - return await reader.ReadToEndAsync().ConfigureAwait(false); - } -#endif } From 96f6b1cc6138cd5a3166355b54547bae6df0c2b4 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Fri, 11 Jul 2025 18:17:29 +0200 Subject: [PATCH 195/541] Use --no-progress (#5987) --- azure-pipelines.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/azure-pipelines.yml b/azure-pipelines.yml index 235191a093..956517d250 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -115,7 +115,7 @@ stages: # Because the build step is using -ci flag, restore is done in a local .packages directory. # We need to pass NUGET_PACKAGES so that when dotnet test is doing evaluation phase on the projects, it can resolve .props/.targets from packages and import them. # Otherwise, props/targets are not imported. It's important that they are imported so that IsTestingPlatformApplication ends up being set. - - script: dotnet test -c $(_BuildConfig) --no-build -bl:$(BUILD.SOURCESDIRECTORY)\artifacts\log\$(_BuildConfig)\TestStep.binlog + - script: dotnet test -c $(_BuildConfig) --no-build -bl:$(BUILD.SOURCESDIRECTORY)\artifacts\log\$(_BuildConfig)\TestStep.binlog --no-progress name: Test displayName: Test env: @@ -195,7 +195,7 @@ stages: # Because the build step is using -ci flag, restore is done in a local .packages directory. # We need to pass NUGET_PACKAGES so that when dotnet test is doing evaluation phase on the projects, it can resolve .props/.targets from packages and import them. # Otherwise, props/targets are not imported. It's important that they are imported so that IsTestingPlatformApplication ends up being set. - - script: dotnet test --solution NonWindowsTests.slnf -c $(_BuildConfig) --no-build -bl:$(BUILD.SOURCESDIRECTORY)\artifacts\log\$(_BuildConfig)\TestStep.binlog + - script: dotnet test --solution NonWindowsTests.slnf -c $(_BuildConfig) --no-build -bl:$(BUILD.SOURCESDIRECTORY)\artifacts\log\$(_BuildConfig)\TestStep.binlog --no-progress name: Test displayName: Test env: @@ -261,7 +261,7 @@ stages: # Because the build step is using -ci flag, restore is done in a local .packages directory. # We need to pass NUGET_PACKAGES so that when dotnet test is doing evaluation phase on the projects, it can resolve .props/.targets from packages and import them. # Otherwise, props/targets are not imported. It's important that they are imported so that IsTestingPlatformApplication ends up being set. - - script: dotnet test --solution NonWindowsTests.slnf -c $(_BuildConfig) --no-build -bl:$(BUILD.SOURCESDIRECTORY)\artifacts\log\$(_BuildConfig)\TestStep.binlog + - script: dotnet test --solution NonWindowsTests.slnf -c $(_BuildConfig) --no-build -bl:$(BUILD.SOURCESDIRECTORY)\artifacts\log\$(_BuildConfig)\TestStep.binlog --no-progress name: Test displayName: Test env: From 8a35f59192e641267790b7b9195dddbd291ee41c Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Sat, 12 Jul 2025 22:13:00 +1000 Subject: [PATCH 196/541] use TryAdd instead of TryGetValue and Add in Async MessageBus (#5963) --- .../Messages/AsynchronousMessageBus.cs | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Platform/Messages/AsynchronousMessageBus.cs b/src/Platform/Microsoft.Testing.Platform/Messages/AsynchronousMessageBus.cs index 5987a2d91a..973fc74926 100644 --- a/src/Platform/Microsoft.Testing.Platform/Messages/AsynchronousMessageBus.cs +++ b/src/Platform/Microsoft.Testing.Platform/Messages/AsynchronousMessageBus.cs @@ -163,10 +163,7 @@ public override async Task DrainDataAsync() { foreach (AsyncConsumerDataProcessor asyncMultiProducerMultiConsumerDataProcessor in dataProcessors) { - if (!consumerToDrain.TryGetValue(asyncMultiProducerMultiConsumerDataProcessor, out long _)) - { - consumerToDrain.Add(asyncMultiProducerMultiConsumerDataProcessor, 0); - } + consumerToDrain.TryAdd(asyncMultiProducerMultiConsumerDataProcessor, 0); long totalPayloadReceived = await asyncMultiProducerMultiConsumerDataProcessor.DrainDataAsync().ConfigureAwait(false); if (consumerToDrain[asyncMultiProducerMultiConsumerDataProcessor] != totalPayloadReceived) From 6b5e4801d790b9e48184273c091f1f9c64575c75 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Sun, 13 Jul 2025 14:17:04 +0200 Subject: [PATCH 197/541] Cleanup PipeNameDescription (#6000) --- .../IPC/PipeNameDescription.cs | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Platform/IPC/PipeNameDescription.cs b/src/Platform/Microsoft.Testing.Platform/IPC/PipeNameDescription.cs index d272b7f8ce..b8b6214612 100644 --- a/src/Platform/Microsoft.Testing.Platform/IPC/PipeNameDescription.cs +++ b/src/Platform/Microsoft.Testing.Platform/IPC/PipeNameDescription.cs @@ -10,20 +10,13 @@ internal sealed class PipeNameDescription(string name, bool isDirectory) : IDisp public string Name { get; } = name; - public void Dispose() => Dispose(true); - - public void Dispose(bool disposing) + public void Dispose() { if (_disposed) { return; } - if (disposing) - { - // TODO: dispose managed state (managed objects). - } - if (_isDirectory) { try From 25e8745f8699eadb3df8d790d7e4406499eb0f2f Mon Sep 17 00:00:00 2001 From: Copilot <198982749+Copilot@users.noreply.github.com> Date: Mon, 14 Jul 2025 09:49:03 +0200 Subject: [PATCH 198/541] Fix MSTEST0020 codefix constructor placement - position after fields/static constructors (#5944) Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: Youssef1313 <31348972+Youssef1313@users.noreply.github.com> Co-authored-by: Youssef Victor --- ...referConstructorOverTestInitializeFixer.cs | 11 +- ...structorOverTestInitializeAnalyzerTests.cs | 108 ++++++++++++++++++ 2 files changed, 114 insertions(+), 5 deletions(-) diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/PreferConstructorOverTestInitializeFixer.cs b/src/Analyzers/MSTest.Analyzers.CodeFixes/PreferConstructorOverTestInitializeFixer.cs index de7cb2e8e8..2c0f2df3fb 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/PreferConstructorOverTestInitializeFixer.cs +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/PreferConstructorOverTestInitializeFixer.cs @@ -90,19 +90,20 @@ private static async Task ReplaceTestInitializeWithConstructorAsync(Do } editor.ReplaceNode(existingConstructor, newConstructor); + + // Remove the TestInitialize method + editor.RemoveNode(testInitializeMethod); } else { // Create a new constructor with the TestInitialize body if one doesn't exist - ConstructorDeclarationSyntax constructor = SyntaxFactory.ConstructorDeclaration(containingClass.Identifier) + ConstructorDeclarationSyntax constructor = SyntaxFactory.ConstructorDeclaration(containingClass.Identifier.WithoutTrivia()) .WithModifiers(SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.PublicKeyword))) .WithBody(testInitializeBody); - editor.AddMember(containingClass, constructor); + // Insert the constructor at the position of the existing TestInitialize method + editor.ReplaceNode(testInitializeMethod, constructor); } - - // Remove the TestInitialize method - editor.RemoveNode(testInitializeMethod); } return editor.GetChangedDocument(); diff --git a/test/UnitTests/MSTest.Analyzers.UnitTests/PreferConstructorOverTestInitializeAnalyzerTests.cs b/test/UnitTests/MSTest.Analyzers.UnitTests/PreferConstructorOverTestInitializeAnalyzerTests.cs index b5d581b88f..7e265f7aa1 100644 --- a/test/UnitTests/MSTest.Analyzers.UnitTests/PreferConstructorOverTestInitializeAnalyzerTests.cs +++ b/test/UnitTests/MSTest.Analyzers.UnitTests/PreferConstructorOverTestInitializeAnalyzerTests.cs @@ -295,4 +295,112 @@ public MyTestClass() await VerifyCS.VerifyCodeFixAsync(code, fixedCode); } + + [TestMethod] + public async Task WhenTestClassHasFieldsAndMethods_ConstructorPlacedAfterFields() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public sealed class Test1 + { + private object _instanceVariable; + + [TestInitialize] + public void [|Initialize|]() + { + _instanceVariable = new object(); + } + + [TestMethod] + public void TestMethod1() + { + } + + private void SomePrivateMethod() + { + } + } + """; + string fixedCode = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public sealed class Test1 + { + private object _instanceVariable; + + public Test1() + { + _instanceVariable = new object(); + } + + [TestMethod] + public void TestMethod1() + { + } + + private void SomePrivateMethod() + { + } + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, fixedCode); + } + + [TestMethod] + public async Task WhenTestClassHasFieldsAndTestMethodBeforeTestInitialize_ConstructorPlacedAfterFields() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public sealed class Test1 + { + private object _instanceVariable; + + [TestMethod] + public void TestMethod1() + { + } + + [TestInitialize] + public void [|Initialize|]() + { + _instanceVariable = new object(); + } + + private void SomePrivateMethod() + { + } + } + """; + string fixedCode = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public sealed class Test1 + { + private object _instanceVariable; + + [TestMethod] + public void TestMethod1() + { + } + + public Test1() + { + _instanceVariable = new object(); + } + + private void SomePrivateMethod() + { + } + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, fixedCode); + } } From 2c4dd6db1a560d77a9653722ec73eec1a1111c50 Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Mon, 14 Jul 2025 17:50:16 +1000 Subject: [PATCH 199/541] use XElement.LoadAsync in TrxCompareTool (#5975) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Amaury Levé --- .../TrxCompareTool.cs | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxCompareTool.cs b/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxCompareTool.cs index 6a6069daf2..af1bddf91f 100644 --- a/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxCompareTool.cs +++ b/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxCompareTool.cs @@ -60,8 +60,9 @@ public async Task RunAsync() List<(string TestName, string Outcome, string Storage)> comparedResults = []; List comparedIssues = []; await _task.WhenAll( - _task.Run(() => CollectEntriesAndErrors(baselineFilePaths[0], trxNamespace, baseLineResults, baseLineIssues)), - _task.Run(() => CollectEntriesAndErrors(comparedFilePaths[0], trxNamespace, comparedResults, comparedIssues))).ConfigureAwait(false); + CollectEntriesAndErrorsAsync(baselineFilePaths[0], trxNamespace, baseLineResults, baseLineIssues), + CollectEntriesAndErrorsAsync(comparedFilePaths[0], trxNamespace, comparedResults, comparedIssues)) + .ConfigureAwait(false); StringBuilder outputBuilder = new(); AppendResultsAndIssues("Baseline", baselineFilePaths[0], baseLineResults, baseLineIssues, outputBuilder); @@ -174,9 +175,10 @@ private static void AppendResultsAndIssues(string category, string filePath, outputBuilder.AppendLine(); } - private static void CollectEntriesAndErrors(string trxFile, XNamespace ns, List<(string TestName, string Outcome, string Storage)> results, List issues) + private static async Task CollectEntriesAndErrorsAsync(string trxFile, XNamespace ns, List<(string TestName, string Outcome, string Storage)> results, List issues) { - var trxTestRun = XElement.Parse(File.ReadAllText(trxFile)); + using FileStream stream = File.OpenRead(trxFile); + XElement trxTestRun = await XElement.LoadAsync(stream, LoadOptions.None, CancellationToken.None).ConfigureAwait(false); int testResultIndex = 0; foreach (XElement testResult in trxTestRun.Elements(ns + "Results").Elements(ns + "UnitTestResult")) { From ad90815c3000f49b310707d78c054400f5b8b214 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Mon, 14 Jul 2025 12:08:41 +0200 Subject: [PATCH 200/541] Support `--filter-uid` on console (#6002) --- .../PlatformCommandLineProvider.cs | 2 + .../ConsoleTestExecutionFilterFactory.cs | 19 ++++- .../Requests/ITestExecutionFilterFactory.cs | 2 +- .../Resources/PlatformResources.resx | 6 ++ .../Resources/xlf/PlatformResources.cs.xlf | 10 +++ .../Resources/xlf/PlatformResources.de.xlf | 10 +++ .../Resources/xlf/PlatformResources.es.xlf | 10 +++ .../Resources/xlf/PlatformResources.fr.xlf | 10 +++ .../Resources/xlf/PlatformResources.it.xlf | 10 +++ .../Resources/xlf/PlatformResources.ja.xlf | 10 +++ .../Resources/xlf/PlatformResources.ko.xlf | 10 +++ .../Resources/xlf/PlatformResources.pl.xlf | 10 +++ .../Resources/xlf/PlatformResources.pt-BR.xlf | 10 +++ .../Resources/xlf/PlatformResources.ru.xlf | 10 +++ .../Resources/xlf/PlatformResources.tr.xlf | 10 +++ .../xlf/PlatformResources.zh-Hans.xlf | 10 +++ .../xlf/PlatformResources.zh-Hant.xlf | 10 +++ .../HelpInfoTests.cs | 2 + .../ExecutionTests.cs | 74 +++++++++++++++++-- .../HelpInfoTests.cs | 12 +++ 20 files changed, 237 insertions(+), 10 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Platform/CommandLine/PlatformCommandLineProvider.cs b/src/Platform/Microsoft.Testing.Platform/CommandLine/PlatformCommandLineProvider.cs index ad94138e77..5f1b3f192b 100644 --- a/src/Platform/Microsoft.Testing.Platform/CommandLine/PlatformCommandLineProvider.cs +++ b/src/Platform/Microsoft.Testing.Platform/CommandLine/PlatformCommandLineProvider.cs @@ -28,6 +28,7 @@ internal sealed class PlatformCommandLineProvider : ICommandLineOptionsProvider public const string TestHostControllerPIDOptionKey = "internal-testhostcontroller-pid"; public const string ExitOnProcessExitOptionKey = "exit-on-process-exit"; public const string ConfigFileOptionKey = "config-file"; + public const string FilterUidOptionKey = "filter-uid"; public const string ServerOptionKey = "server"; public const string ClientPortOptionKey = "client-port"; @@ -57,6 +58,7 @@ internal sealed class PlatformCommandLineProvider : ICommandLineOptionsProvider new(IgnoreExitCodeOptionKey, PlatformResources.PlatformCommandLineIgnoreExitCodeOptionDescription, ArgumentArity.ExactlyOne, false, isBuiltIn: true), new(ExitOnProcessExitOptionKey, PlatformResources.PlatformCommandLineExitOnProcessExitOptionDescription, ArgumentArity.ExactlyOne, false, isBuiltIn: true), new(ConfigFileOptionKey, PlatformResources.PlatformCommandLineConfigFileOptionDescription, ArgumentArity.ExactlyOne, false, isBuiltIn: true), + new(FilterUidOptionKey, PlatformResources.PlatformCommandLineFilterUidOptionDescription, ArgumentArity.OneOrMore, false, isBuiltIn: true), // Hidden options new(HelpOptionQuestionMark, PlatformResources.PlatformCommandLineHelpOptionDescription, ArgumentArity.Zero, true, isBuiltIn: true), diff --git a/src/Platform/Microsoft.Testing.Platform/Requests/ConsoleTestExecutionFilterFactory.cs b/src/Platform/Microsoft.Testing.Platform/Requests/ConsoleTestExecutionFilterFactory.cs index 14f7305ec4..5e7ef78150 100644 --- a/src/Platform/Microsoft.Testing.Platform/Requests/ConsoleTestExecutionFilterFactory.cs +++ b/src/Platform/Microsoft.Testing.Platform/Requests/ConsoleTestExecutionFilterFactory.cs @@ -2,6 +2,7 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.Testing.Platform.CommandLine; +using Microsoft.Testing.Platform.Extensions.Messages; using Microsoft.Testing.Platform.Helpers; using Microsoft.Testing.Platform.Resources; @@ -21,8 +22,18 @@ internal sealed class ConsoleTestExecutionFilterFactory(ICommandLineOptions comm public Task IsEnabledAsync() => Task.FromResult(true); - public Task<(bool Success, ITestExecutionFilter? TestExecutionFilter)> TryCreateAsync() => - _commandLineService.TryGetOptionArgumentList(TreeNodeFilterCommandLineOptionsProvider.TreenodeFilter, out string[]? filter) - ? Task.FromResult((true, (ITestExecutionFilter?)new TreeNodeFilter(filter[0]))) - : Task.FromResult((true, (ITestExecutionFilter?)new NopFilter())); + public Task<(bool Success, ITestExecutionFilter? TestExecutionFilter)> TryCreateAsync() + { + bool hasTreenodeFilter = _commandLineService.TryGetOptionArgumentList(TreeNodeFilterCommandLineOptionsProvider.TreenodeFilter, out string[]? treenodeFilter); + bool hasTestNodeUidFilter = _commandLineService.TryGetOptionArgumentList(PlatformCommandLineProvider.FilterUidOptionKey, out string[]? uidFilter); + ITestExecutionFilter filter = (hasTreenodeFilter, hasTestNodeUidFilter) switch + { + (true, true) => throw new NotSupportedException(PlatformResources.OnlyOneFilterSupported), + (true, false) => new TreeNodeFilter(treenodeFilter![0]), + (false, true) => new TestNodeUidListFilter([.. uidFilter!.Select(x => new TestNodeUid(x))]), + (false, false) => new NopFilter(), + }; + + return Task.FromResult<(bool, ITestExecutionFilter?)>((true, filter)); + } } diff --git a/src/Platform/Microsoft.Testing.Platform/Requests/ITestExecutionFilterFactory.cs b/src/Platform/Microsoft.Testing.Platform/Requests/ITestExecutionFilterFactory.cs index cc80518805..37b51a3d82 100644 --- a/src/Platform/Microsoft.Testing.Platform/Requests/ITestExecutionFilterFactory.cs +++ b/src/Platform/Microsoft.Testing.Platform/Requests/ITestExecutionFilterFactory.cs @@ -7,5 +7,5 @@ namespace Microsoft.Testing.Platform.Requests; internal interface ITestExecutionFilterFactory : IExtension { - public Task<(bool Success, ITestExecutionFilter? TestExecutionFilter)> TryCreateAsync(); + Task<(bool Success, ITestExecutionFilter? TestExecutionFilter)> TryCreateAsync(); } diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/PlatformResources.resx b/src/Platform/Microsoft.Testing.Platform/Resources/PlatformResources.resx index 51ec6ea19f..12d70f5348 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/PlatformResources.resx +++ b/src/Platform/Microsoft.Testing.Platform/Resources/PlatformResources.resx @@ -707,4 +707,10 @@ Takes one argument as string in the format <value>[h|m|s] where 'value' is The current test framework does not implement 'IGracefulStopTestExecutionCapability' which is required for '--maximum-failed-tests' feature. + + Provides a list of test node UIDs to filter by. + + + Passing both '--treenode-filter' and '--filter-uid' is unsupported. + diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.cs.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.cs.xlf index bf97e9b009..7574cd18b9 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.cs.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.cs.xlf @@ -431,6 +431,11 @@ Nenalezeno + + Passing both '--treenode-filter' and '--filter-uid' is unsupported. + Passing both '--treenode-filter' and '--filter-uid' is unsupported. + + Out of process file artifacts produced: Vytvořené artefakty souboru mimo proces: @@ -533,6 +538,11 @@ Dostupné hodnoty jsou Trace, Debug, Information, Warning, Error a Critical.„ --{0}“ očekává jeden argument int PID. + + Provides a list of test node UIDs to filter by. + Provides a list of test node UIDs to filter by. + + Show the command line help. Umožňuje zobrazit nápovědu příkazového řádku. diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.de.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.de.xlf index d657755538..4517511eff 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.de.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.de.xlf @@ -431,6 +431,11 @@ Nicht gefunden + + Passing both '--treenode-filter' and '--filter-uid' is unsupported. + Passing both '--treenode-filter' and '--filter-uid' is unsupported. + + Out of process file artifacts produced: Nicht verarbeitete Dateiartefakte erstellt: @@ -533,6 +538,11 @@ Die verfügbaren Werte sind "Trace", "Debug", "Information", "Warning", "Error" "--{0}" erwartet ein einzelnes int-PID-Argument. + + Provides a list of test node UIDs to filter by. + Provides a list of test node UIDs to filter by. + + Show the command line help. Zeigen Sie die Hilfe zur Befehlszeile an. diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.es.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.es.xlf index 493fe65d2a..d0d63bebd0 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.es.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.es.xlf @@ -431,6 +431,11 @@ No se encontró + + Passing both '--treenode-filter' and '--filter-uid' is unsupported. + Passing both '--treenode-filter' and '--filter-uid' is unsupported. + + Out of process file artifacts produced: Artefactos de archivo fuera de proceso producidos: @@ -533,6 +538,11 @@ Los valores disponibles son 'Seguimiento', 'Depurar', 'Información', 'Advertenc '--{0}' espera un único argumento PID entero + + Provides a list of test node UIDs to filter by. + Provides a list of test node UIDs to filter by. + + Show the command line help. Muestre la ayuda de la línea de comandos. diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.fr.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.fr.xlf index f82ac26b64..5a705374cd 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.fr.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.fr.xlf @@ -431,6 +431,11 @@ Introuvable + + Passing both '--treenode-filter' and '--filter-uid' is unsupported. + Passing both '--treenode-filter' and '--filter-uid' is unsupported. + + Out of process file artifacts produced: Artefacts de fichier hors processus produits : @@ -533,6 +538,11 @@ Les valeurs disponibles sont « Trace », « Debug », « Information », « --{0} » attend un seul argument PID int + + Provides a list of test node UIDs to filter by. + Provides a list of test node UIDs to filter by. + + Show the command line help. Afficher l’aide de la ligne de commande. diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.it.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.it.xlf index 0f9e8cf771..b08a309ae3 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.it.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.it.xlf @@ -431,6 +431,11 @@ Non trovato + + Passing both '--treenode-filter' and '--filter-uid' is unsupported. + Passing both '--treenode-filter' and '--filter-uid' is unsupported. + + Out of process file artifacts produced: Artefatti file non in elaborazione prodotti: @@ -533,6 +538,11 @@ I valori disponibili sono 'Trace', 'Debug', 'Information', 'Warning', 'Error' e '--{0}' prevede un singolo argomento PID int + + Provides a list of test node UIDs to filter by. + Provides a list of test node UIDs to filter by. + + Show the command line help. Mostra la Guida della riga di comando. diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ja.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ja.xlf index 52d494a080..5a06691f95 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ja.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ja.xlf @@ -431,6 +431,11 @@ 見つかりません + + Passing both '--treenode-filter' and '--filter-uid' is unsupported. + Passing both '--treenode-filter' and '--filter-uid' is unsupported. + + Out of process file artifacts produced: アウトプロセスのファイル成果物が生成されました: @@ -534,6 +539,11 @@ The available values are 'Trace', 'Debug', 'Information', 'Warning', 'Error', an '--{0}' には 1 つの int PID 引数が必要です + + Provides a list of test node UIDs to filter by. + Provides a list of test node UIDs to filter by. + + Show the command line help. コマンド ラインヘルプを表示します。 diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ko.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ko.xlf index 2bddcfd54c..6ed7dc2c13 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ko.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ko.xlf @@ -431,6 +431,11 @@ 찾을 수 없음 + + Passing both '--treenode-filter' and '--filter-uid' is unsupported. + Passing both '--treenode-filter' and '--filter-uid' is unsupported. + + Out of process file artifacts produced: 생성된 Out of process 파일 아티팩트: @@ -533,6 +538,11 @@ The available values are 'Trace', 'Debug', 'Information', 'Warning', 'Error', an '--{0}'에는 단일 int PID 인수가 필요합니다. + + Provides a list of test node UIDs to filter by. + Provides a list of test node UIDs to filter by. + + Show the command line help. 명령줄 도움말을 표시합니다. diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pl.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pl.xlf index 9fa4232e0d..eaafb3599b 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pl.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pl.xlf @@ -431,6 +431,11 @@ Nie znaleziono + + Passing both '--treenode-filter' and '--filter-uid' is unsupported. + Passing both '--treenode-filter' and '--filter-uid' is unsupported. + + Out of process file artifacts produced: Wygenerowane artefakty pliku poza procesem: @@ -533,6 +538,11 @@ Dostępne wartości to „Trace”, „Debug”, „Information”, „Warning „--{0}” oczekuje pojedynczego argumentu int identyfikatora PID + + Provides a list of test node UIDs to filter by. + Provides a list of test node UIDs to filter by. + + Show the command line help. Pokaż pomoc wiersza polecenia. diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pt-BR.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pt-BR.xlf index c24d1413ab..8683d75595 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pt-BR.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pt-BR.xlf @@ -431,6 +431,11 @@ Não encontrado + + Passing both '--treenode-filter' and '--filter-uid' is unsupported. + Passing both '--treenode-filter' and '--filter-uid' is unsupported. + + Out of process file artifacts produced: Artefatos de arquivo fora do processo produzidos: @@ -533,6 +538,11 @@ Os valores disponíveis são 'Rastreamento', 'Depuração', 'Informação', 'Avi "--{0}" espera um único argumento int PID + + Provides a list of test node UIDs to filter by. + Provides a list of test node UIDs to filter by. + + Show the command line help. Mostrar a ajuda da linha de comando. diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ru.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ru.xlf index 089434cc81..5567e817a8 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ru.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ru.xlf @@ -431,6 +431,11 @@ Не найдено + + Passing both '--treenode-filter' and '--filter-uid' is unsupported. + Passing both '--treenode-filter' and '--filter-uid' is unsupported. + + Out of process file artifacts produced: Созданные вне процесса артефакты файлов: @@ -533,6 +538,11 @@ The available values are 'Trace', 'Debug', 'Information', 'Warning', 'Error', an "--{0}" ожидает один аргумент int PID + + Provides a list of test node UIDs to filter by. + Provides a list of test node UIDs to filter by. + + Show the command line help. Показать справку по командной строке. diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.tr.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.tr.xlf index 67ff90a823..39c2e84d16 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.tr.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.tr.xlf @@ -431,6 +431,11 @@ Bulunamadı + + Passing both '--treenode-filter' and '--filter-uid' is unsupported. + Passing both '--treenode-filter' and '--filter-uid' is unsupported. + + Out of process file artifacts produced: Üretilen işlem dışı dosya yapıtları: @@ -533,6 +538,11 @@ Kullanılabilir değerler: 'Trace', 'Debug', 'Information', 'Warning', 'Error' v '--{0}', tek bir int PID bağımsız değişkeni bekliyor + + Provides a list of test node UIDs to filter by. + Provides a list of test node UIDs to filter by. + + Show the command line help. Komut satırı yardımını gösterir. diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hans.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hans.xlf index 5e2dfad71d..b3a323045d 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hans.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hans.xlf @@ -431,6 +431,11 @@ 未找到 + + Passing both '--treenode-filter' and '--filter-uid' is unsupported. + Passing both '--treenode-filter' and '--filter-uid' is unsupported. + + Out of process file artifacts produced: 生成的进程外文件项目: @@ -533,6 +538,11 @@ The available values are 'Trace', 'Debug', 'Information', 'Warning', 'Error', an “--{0}”需要单个 int PID 参数 + + Provides a list of test node UIDs to filter by. + Provides a list of test node UIDs to filter by. + + Show the command line help. 显示命令行帮助。 diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hant.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hant.xlf index 8bf8789838..17f154bcbd 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hant.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hant.xlf @@ -431,6 +431,11 @@ 找不到 + + Passing both '--treenode-filter' and '--filter-uid' is unsupported. + Passing both '--treenode-filter' and '--filter-uid' is unsupported. + + Out of process file artifacts produced: 產生的流程外檔案成品: @@ -533,6 +538,11 @@ The available values are 'Trace', 'Debug', 'Information', 'Warning', 'Error', an '--{0}' 需要單一 int PID 引數 + + Provides a list of test node UIDs to filter by. + Provides a list of test node UIDs to filter by. + + Show the command line help. 顯示命令列說明。 diff --git a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/HelpInfoTests.cs b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/HelpInfoTests.cs index d43193af01..f65ad6d7c4 100644 --- a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/HelpInfoTests.cs +++ b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/HelpInfoTests.cs @@ -45,6 +45,8 @@ Output directory of the diagnostic logging. The available values are 'Trace', 'Debug', 'Information', 'Warning', 'Error', and 'Critical'. --exit-on-process-exit Exit the test process if dependent process exits. PID must be provided. + --filter-uid + Provides a list of test node UIDs to filter by. --help Show the command line help. --ignore-exit-code diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/ExecutionTests.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/ExecutionTests.cs index 0f4857f6e8..0f60919345 100644 --- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/ExecutionTests.cs +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/ExecutionTests.cs @@ -40,6 +40,60 @@ public async Task Exec_WhenOnlyAssetNameIsSpecified_AllTestsAreRun(string tfm) testHostResult.AssertOutputMatchesRegex($"Passed! - .*\\.(dll|exe) \\(net.+\\|.+\\)"); } + [DynamicData(nameof(TargetFrameworks.AllForDynamicData), typeof(TargetFrameworks))] + [TestMethod] + public async Task Exec_WhenUsingUidFilterForRun(string tfm) + { + var testHost = TestInfrastructure.TestHost.LocateFrom(AssetFixture.TargetAssetPath, AssetName, tfm); + + TestHostResult testHostResult = await testHost.ExecuteAsync("--filter-uid NonExistingUid"); + testHostResult.AssertExitCodeIs(ExitCodes.ZeroTests); + + testHostResult = await testHost.ExecuteAsync("--filter-uid 0"); + testHostResult.AssertExitCodeIs(ExitCodes.Success); + testHostResult.AssertOutputContainsSummary(failed: 0, passed: 1, skipped: 0); + + testHostResult = await testHost.ExecuteAsync("--filter-uid 1"); + testHostResult.AssertExitCodeIs(ExitCodes.Success); + testHostResult.AssertOutputContainsSummary(failed: 0, passed: 1, skipped: 0); + + testHostResult = await testHost.ExecuteAsync("--filter-uid 0 --filter-uid 1"); + testHostResult.AssertExitCodeIs(ExitCodes.Success); + testHostResult.AssertOutputContainsSummary(failed: 0, passed: 2, skipped: 0); + } + + [DynamicData(nameof(TargetFrameworks.AllForDynamicData), typeof(TargetFrameworks))] + [TestMethod] + public async Task Exec_WhenUsingUidFilterForDiscovery(string tfm) + { + var testHost = TestInfrastructure.TestHost.LocateFrom(AssetFixture.TargetAssetPath, AssetName, tfm); + + TestHostResult testHostResult = await testHost.ExecuteAsync("--list-tests --filter-uid NonExistingUid"); + testHostResult.AssertExitCodeIs(ExitCodes.ZeroTests); + + testHostResult = await testHost.ExecuteAsync("--list-tests --filter-uid 0"); + testHostResult.AssertExitCodeIs(ExitCodes.Success); + testHostResult.AssertOutputMatchesRegex(""" + Test1 + Test discovery summary: found 1 test\(s\) + """); + + testHostResult = await testHost.ExecuteAsync("--list-tests --filter-uid 1"); + testHostResult.AssertExitCodeIs(ExitCodes.Success); + testHostResult.AssertOutputMatchesRegex(""" + Test2 + Test discovery summary: found 1 test\(s\) + """); + + testHostResult = await testHost.ExecuteAsync("--list-tests --filter-uid 0 --filter-uid 1"); + testHostResult.AssertExitCodeIs(ExitCodes.Success); + testHostResult.AssertOutputMatchesRegex(""" + Test1 + Test2 + Test discovery summary: found 2 test\(s\) + """); + } + [DynamicData(nameof(TargetFrameworks.AllForDynamicData), typeof(TargetFrameworks))] [TestMethod] public async Task Exec_WhenListTestsAndFilterAreSpecified_OnlyFilteredTestsAreFound(string tfm) @@ -138,12 +192,14 @@ public sealed class TestAssetFixture() : TestAssetFixtureBase(AcceptanceFixture. #file Program.cs +using System.Linq; using Microsoft.Testing.Platform.Builder; using Microsoft.Testing.Platform.Capabilities.TestFramework; using Microsoft.Testing.Platform.Extensions; using Microsoft.Testing.Platform.Extensions.Messages; using Microsoft.Testing.Platform.Extensions.TestFramework; using Microsoft.Testing.Platform.Helpers; +using Microsoft.Testing.Platform.Requests; using Microsoft.Testing.Platform.Services; public class Program @@ -205,17 +261,25 @@ public async Task ExecuteRequestAsync(ExecuteRequestContext context) // Simulate that here. bool isDiscovery = _sp.GetCommandLineOptions().TryGetOptionArgumentList("--list-tests", out _); - - await context.MessageBus.PublishAsync(this, new TestNodeUpdateMessage(context.Request.Session.SessionUid, - new TestNode() { Uid = "0", DisplayName = "Test1", Properties = new(DiscoveredTestNodeStateProperty.CachedInstance) })); + var uidListFilter = ((TestExecutionRequest)context.Request).Filter as TestNodeUidListFilter; + + // If --filter-uid is used, but it doesn't contain a given Uid, then don't publish TestNodeUpdateMessage for that Uid. + var excludeUid0 = uidListFilter is not null && !uidListFilter.TestNodeUids.Any(n => n.Value == "0"); + var excludeUid1 = uidListFilter is not null && !uidListFilter.TestNodeUids.Any(n => n.Value == "1"); + + if (!excludeUid0) + { + await context.MessageBus.PublishAsync(this, new TestNodeUpdateMessage(context.Request.Session.SessionUid, + new TestNode() { Uid = "0", DisplayName = "Test1", Properties = new(DiscoveredTestNodeStateProperty.CachedInstance) })); + } - if (!isDiscovery) + if (!isDiscovery && !excludeUid0) { await context.MessageBus.PublishAsync(this, new TestNodeUpdateMessage(context.Request.Session.SessionUid, new TestNode() { Uid = "0", DisplayName = "Test1", Properties = new(PassedTestNodeStateProperty.CachedInstance) })); } - if (!_sp.GetCommandLineOptions().TryGetOptionArgumentList("--treenode-filter", out _)) + if (!_sp.GetCommandLineOptions().TryGetOptionArgumentList("--treenode-filter", out _) && !excludeUid1) { await context.MessageBus.PublishAsync(this, new TestNodeUpdateMessage(context.Request.Session.SessionUid, new TestNode() { Uid = "1", DisplayName = "Test2", Properties = new(DiscoveredTestNodeStateProperty.CachedInstance) })); diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/HelpInfoTests.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/HelpInfoTests.cs index f4b19b2e50..49ec524d6f 100644 --- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/HelpInfoTests.cs +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/HelpInfoTests.cs @@ -39,6 +39,8 @@ Output directory of the diagnostic logging. The available values are 'Trace', 'Debug', 'Information', 'Warning', 'Error', and 'Critical'. --exit-on-process-exit Exit the test process if dependent process exits. PID must be provided. + --filter-uid + Provides a list of test node UIDs to filter by. --help Show the command line help. --ignore-exit-code @@ -183,6 +185,10 @@ Note that this is slowing down the test execution\. Arity: 1 Hidden: False Description: Exit the test process if dependent process exits\. PID must be provided\. + --filter-uid + Arity: 1\.\.N + Hidden: False + Description: Provides a list of test node UIDs to filter by\. --help Arity: 0 Hidden: False @@ -290,6 +296,8 @@ Output directory of the diagnostic logging. The available values are 'Trace', 'Debug', 'Information', 'Warning', 'Error', and 'Critical'. --exit-on-process-exit Exit the test process if dependent process exits. PID must be provided. + --filter-uid + Provides a list of test node UIDs to filter by. --help Show the command line help. --ignore-exit-code @@ -445,6 +453,10 @@ Note that this is slowing down the test execution. Arity: 1 Hidden: False Description: Exit the test process if dependent process exits. PID must be provided. + --filter-uid + Arity: 1..N + Hidden: False + Description: Provides a list of test node UIDs to filter by. --help Arity: 0 Hidden: False From a15e054c17406f66e61ebfa97845390b4768138f Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Tue, 15 Jul 2025 14:01:51 +1000 Subject: [PATCH 201/541] remove redundnant escapedClassFullName in AppendAssemblyTestNodeBuilderContent (#6012) --- .../MSTest.SourceGeneration/Generators/TestNodesGenerator.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/Analyzers/MSTest.SourceGeneration/Generators/TestNodesGenerator.cs b/src/Analyzers/MSTest.SourceGeneration/Generators/TestNodesGenerator.cs index aa42fbb24a..a1ca1ed89c 100644 --- a/src/Analyzers/MSTest.SourceGeneration/Generators/TestNodesGenerator.cs +++ b/src/Analyzers/MSTest.SourceGeneration/Generators/TestNodesGenerator.cs @@ -158,7 +158,6 @@ private static void AppendAssemblyTestNodeBuilderContent(IndentedStringBuilder s foreach (TestTypeInfo testClassInfo in namespaceClasses) { - string escapedClassFullName = TestNodeHelpers.GenerateEscapedName(testClassInfo.FullyQualifiedName); sourceStringBuilder.AppendLine($"{namespaceTestsVariableName}.Add({testClassInfo.GeneratedTypeName}.TestNode);"); } From e602dcd3233e6c39f268f0c3cd3202066637ca86 Mon Sep 17 00:00:00 2001 From: dotnet bot Date: Tue, 15 Jul 2025 06:17:30 +0200 Subject: [PATCH 202/541] Localized file check-in by OneLocBuild Task: Build definition ID 1218: Build ID 2750158 --- .../Resources/xlf/FrameworkExtensionsMessages.cs.xlf | 4 ++-- .../Resources/xlf/FrameworkExtensionsMessages.de.xlf | 4 ++-- .../Resources/xlf/FrameworkExtensionsMessages.es.xlf | 4 ++-- .../Resources/xlf/FrameworkExtensionsMessages.fr.xlf | 4 ++-- .../Resources/xlf/FrameworkExtensionsMessages.it.xlf | 4 ++-- 5 files changed, 10 insertions(+), 10 deletions(-) diff --git a/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.cs.xlf b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.cs.xlf index 2d61b7f825..df112b7c30 100644 --- a/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.cs.xlf +++ b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.cs.xlf @@ -4,7 +4,7 @@ Type '{0}' is not assignable to '{1}'. - Type '{0}' is not assignable to '{1}'. + Typ „{0}“ nelze přiřadit k „{1}“. - {0} argument name like "applicationType" - {1} fully qualified class name like "Microsoft.UI.Xaml.Application" @@ -12,7 +12,7 @@ UITestMethodAttribute.DispatcherQueue should not be null. To use UITestMethodAttribute within a WinUI Desktop App, remember to set the static UITestMethodAttribute.DispatcherQueue during the test initialization. - UITestMethodAttribute.DispatcherQueue should not be null. To use UITestMethodAttribute within a WinUI Desktop App, remember to set the static UITestMethodAttribute.DispatcherQueue during the test initialization. + UITestMethodAttribute.DispatcherQueue nesmí mít hodnotu null. Pokud chcete použít UITestMethodAttribute v desktopové aplikaci WinUI, nezapomeňte během inicializace testu nastavit statický UITestMethodAttribute.DispatcherQueue. diff --git a/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.de.xlf b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.de.xlf index 519b1af1a4..a764dda7b3 100644 --- a/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.de.xlf +++ b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.de.xlf @@ -4,7 +4,7 @@ Type '{0}' is not assignable to '{1}'. - Type '{0}' is not assignable to '{1}'. + Der Typ "{0}" kann nicht "{1}" zugewiesen werden. - {0} argument name like "applicationType" - {1} fully qualified class name like "Microsoft.UI.Xaml.Application" @@ -12,7 +12,7 @@ UITestMethodAttribute.DispatcherQueue should not be null. To use UITestMethodAttribute within a WinUI Desktop App, remember to set the static UITestMethodAttribute.DispatcherQueue during the test initialization. - UITestMethodAttribute.DispatcherQueue should not be null. To use UITestMethodAttribute within a WinUI Desktop App, remember to set the static UITestMethodAttribute.DispatcherQueue during the test initialization. + UITestMethodAttribute.DispatcherQueue darf nicht NULL sein. Um UITestMethodAttribute in einer WinUI-Desktop-App zu verwenden, denken Sie daran, die statische UITestMethodAttribute.DispatcherQueue während der Testinitialisierung festzulegen. diff --git a/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.es.xlf b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.es.xlf index 8ce7712404..17912d03f1 100644 --- a/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.es.xlf +++ b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.es.xlf @@ -4,7 +4,7 @@ Type '{0}' is not assignable to '{1}'. - Type '{0}' is not assignable to '{1}'. + Tipo "{0}" no se puede asignar a "{1}". - {0} argument name like "applicationType" - {1} fully qualified class name like "Microsoft.UI.Xaml.Application" @@ -12,7 +12,7 @@ UITestMethodAttribute.DispatcherQueue should not be null. To use UITestMethodAttribute within a WinUI Desktop App, remember to set the static UITestMethodAttribute.DispatcherQueue during the test initialization. - UITestMethodAttribute.DispatcherQueue should not be null. To use UITestMethodAttribute within a WinUI Desktop App, remember to set the static UITestMethodAttribute.DispatcherQueue during the test initialization. + UITestMethodAttribute.DispatcherQueue no debe ser null. Para usar UITestMethodAttribute en una aplicación de escritorio WinUI, recuerde establecer el UITestMethodAttribute.DispatcherQueue estático durante la inicialización de la prueba. diff --git a/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.fr.xlf b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.fr.xlf index b3995a4086..6a4b6f969e 100644 --- a/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.fr.xlf +++ b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.fr.xlf @@ -4,7 +4,7 @@ Type '{0}' is not assignable to '{1}'. - Type '{0}' is not assignable to '{1}'. + Impossible d'assigner le type '{0}' à '{1}'. - {0} argument name like "applicationType" - {1} fully qualified class name like "Microsoft.UI.Xaml.Application" @@ -12,7 +12,7 @@ UITestMethodAttribute.DispatcherQueue should not be null. To use UITestMethodAttribute within a WinUI Desktop App, remember to set the static UITestMethodAttribute.DispatcherQueue during the test initialization. - UITestMethodAttribute.DispatcherQueue should not be null. To use UITestMethodAttribute within a WinUI Desktop App, remember to set the static UITestMethodAttribute.DispatcherQueue during the test initialization. + UITestMethodAttribute.DispatcherQueue ne doit pas avoir la valeur nul. Pour utiliser UITestMethodAttribute dans une application de bureau WinUI, n’oubliez pas de définir l’UITestMethodAttribute.DispatcherQueue statique pendant l’initialisation du test. diff --git a/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.it.xlf b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.it.xlf index 870c84f4bc..5cd8d9568a 100644 --- a/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.it.xlf +++ b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.it.xlf @@ -4,7 +4,7 @@ Type '{0}' is not assignable to '{1}'. - Type '{0}' is not assignable to '{1}'. + Il tipo '{0}' non è assegnabile a '{1}'. - {0} argument name like "applicationType" - {1} fully qualified class name like "Microsoft.UI.Xaml.Application" @@ -12,7 +12,7 @@ UITestMethodAttribute.DispatcherQueue should not be null. To use UITestMethodAttribute within a WinUI Desktop App, remember to set the static UITestMethodAttribute.DispatcherQueue during the test initialization. - UITestMethodAttribute.DispatcherQueue should not be null. To use UITestMethodAttribute within a WinUI Desktop App, remember to set the static UITestMethodAttribute.DispatcherQueue during the test initialization. + UITestMethodAttribute.DispatcherQueue non deve essere Null. Per usare UITestMethodAttribute all'interno di un'app desktop WinUI, ricordarsi di impostare il parametro statico uiTestMethodAttribute.DispatcherQueue durante l'inizializzazione del test. From b9cb27cc21a91f35dd8c255442445d52a8ed5833 Mon Sep 17 00:00:00 2001 From: dotnet bot Date: Tue, 15 Jul 2025 06:17:46 +0200 Subject: [PATCH 203/541] Localized file check-in by OneLocBuild Task: Build definition ID 1218: Build ID 2750158 --- .../Resources/xlf/FrameworkExtensionsMessages.ja.xlf | 4 ++-- .../Resources/xlf/FrameworkExtensionsMessages.ko.xlf | 4 ++-- .../Resources/xlf/FrameworkExtensionsMessages.pl.xlf | 4 ++-- .../Resources/xlf/FrameworkExtensionsMessages.pt-BR.xlf | 4 ++-- .../Resources/xlf/FrameworkExtensionsMessages.ru.xlf | 4 ++-- .../Resources/xlf/FrameworkExtensionsMessages.tr.xlf | 4 ++-- .../Resources/xlf/FrameworkExtensionsMessages.zh-Hans.xlf | 4 ++-- .../Resources/xlf/FrameworkExtensionsMessages.zh-Hant.xlf | 4 ++-- 8 files changed, 16 insertions(+), 16 deletions(-) diff --git a/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.ja.xlf b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.ja.xlf index 6bb08aa1d2..4d3d045657 100644 --- a/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.ja.xlf +++ b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.ja.xlf @@ -4,7 +4,7 @@ Type '{0}' is not assignable to '{1}'. - Type '{0}' is not assignable to '{1}'. + 型 '{0}' を '{1}' に割り当てることはできません。 - {0} argument name like "applicationType" - {1} fully qualified class name like "Microsoft.UI.Xaml.Application" @@ -12,7 +12,7 @@ UITestMethodAttribute.DispatcherQueue should not be null. To use UITestMethodAttribute within a WinUI Desktop App, remember to set the static UITestMethodAttribute.DispatcherQueue during the test initialization. - UITestMethodAttribute.DispatcherQueue should not be null. To use UITestMethodAttribute within a WinUI Desktop App, remember to set the static UITestMethodAttribute.DispatcherQueue during the test initialization. + UITestMethodAttribute.DispatcherQueue を null にすることはできません。WinUI デスクトップ アプリ内で UITestMethodAttribute を使用するには、テストの初期化中に静的な UITestMethodAttribute.DispatcherQueue を設定してください。 diff --git a/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.ko.xlf b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.ko.xlf index c588d65aea..7749a50ad7 100644 --- a/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.ko.xlf +++ b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.ko.xlf @@ -4,7 +4,7 @@ Type '{0}' is not assignable to '{1}'. - Type '{0}' is not assignable to '{1}'. + '{0}' 형식은 '{1}'에 할당할 수 없습니다. - {0} argument name like "applicationType" - {1} fully qualified class name like "Microsoft.UI.Xaml.Application" @@ -12,7 +12,7 @@ UITestMethodAttribute.DispatcherQueue should not be null. To use UITestMethodAttribute within a WinUI Desktop App, remember to set the static UITestMethodAttribute.DispatcherQueue during the test initialization. - UITestMethodAttribute.DispatcherQueue should not be null. To use UITestMethodAttribute within a WinUI Desktop App, remember to set the static UITestMethodAttribute.DispatcherQueue during the test initialization. + UITestMethodAttribute.DispatcherQueue는 null이 아니어야 합니다. WinUI 데스크톱 앱 내에서 UITestMethodAttribute를 사용하려면 테스트 초기화 중에 정적 UITestMethodAttribute.DispatcherQueue를 설정해야 합니다. diff --git a/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.pl.xlf b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.pl.xlf index 580d39e0d5..cacee965b7 100644 --- a/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.pl.xlf +++ b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.pl.xlf @@ -4,7 +4,7 @@ Type '{0}' is not assignable to '{1}'. - Type '{0}' is not assignable to '{1}'. + Typu „{0}” nie można przypisać do typu „{1}”. - {0} argument name like "applicationType" - {1} fully qualified class name like "Microsoft.UI.Xaml.Application" @@ -12,7 +12,7 @@ UITestMethodAttribute.DispatcherQueue should not be null. To use UITestMethodAttribute within a WinUI Desktop App, remember to set the static UITestMethodAttribute.DispatcherQueue during the test initialization. - UITestMethodAttribute.DispatcherQueue should not be null. To use UITestMethodAttribute within a WinUI Desktop App, remember to set the static UITestMethodAttribute.DispatcherQueue during the test initialization. + Element UITestMethodAttribute.DispatcherQueue nie powinien mieć wartości null. Aby użyć atrybutu UITestMethodAttribute w aplikacji klasycznej WinUI, pamiętaj o ustawieniu statycznego atrybutu UITestMethodAttribute.DispatcherQueue podczas inicjowania testu. diff --git a/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.pt-BR.xlf b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.pt-BR.xlf index f8e93799f7..abd65e40f5 100644 --- a/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.pt-BR.xlf +++ b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.pt-BR.xlf @@ -4,7 +4,7 @@ Type '{0}' is not assignable to '{1}'. - Type '{0}' is not assignable to '{1}'. + Tipo '{0}' não é atribuível a '{1}'. - {0} argument name like "applicationType" - {1} fully qualified class name like "Microsoft.UI.Xaml.Application" @@ -12,7 +12,7 @@ UITestMethodAttribute.DispatcherQueue should not be null. To use UITestMethodAttribute within a WinUI Desktop App, remember to set the static UITestMethodAttribute.DispatcherQueue during the test initialization. - UITestMethodAttribute.DispatcherQueue should not be null. To use UITestMethodAttribute within a WinUI Desktop App, remember to set the static UITestMethodAttribute.DispatcherQueue during the test initialization. + UITestMethodAttribute.DispatcherQueue não deve ser nulo. Para usar UITestMethodAttribute em um aplicativo WinUI Desktop, lembre-se de definir o UITestMethodAttribute.DispatcherQueue estático durante a inicialização do teste. diff --git a/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.ru.xlf b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.ru.xlf index 44c4f3da10..36e3e0934c 100644 --- a/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.ru.xlf +++ b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.ru.xlf @@ -4,7 +4,7 @@ Type '{0}' is not assignable to '{1}'. - Type '{0}' is not assignable to '{1}'. + Тип "{0}" не может быть назначен "{1}". - {0} argument name like "applicationType" - {1} fully qualified class name like "Microsoft.UI.Xaml.Application" @@ -12,7 +12,7 @@ UITestMethodAttribute.DispatcherQueue should not be null. To use UITestMethodAttribute within a WinUI Desktop App, remember to set the static UITestMethodAttribute.DispatcherQueue during the test initialization. - UITestMethodAttribute.DispatcherQueue should not be null. To use UITestMethodAttribute within a WinUI Desktop App, remember to set the static UITestMethodAttribute.DispatcherQueue during the test initialization. + Параметр UITestMethodAttribute.DispatcherQueue не должен иметь значение NULL. Чтобы использовать параметр UITestMethodAttribute в классических приложениях WinUI, не забудьте задать статический параметр UITestMethodAttribute.DispatcherQueue во время инициализации теста. diff --git a/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.tr.xlf b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.tr.xlf index 3af2d1d095..60c31e4c21 100644 --- a/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.tr.xlf +++ b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.tr.xlf @@ -4,7 +4,7 @@ Type '{0}' is not assignable to '{1}'. - Type '{0}' is not assignable to '{1}'. + '{0}' tipi '{1}'ye atanamaz. - {0} argument name like "applicationType" - {1} fully qualified class name like "Microsoft.UI.Xaml.Application" @@ -12,7 +12,7 @@ UITestMethodAttribute.DispatcherQueue should not be null. To use UITestMethodAttribute within a WinUI Desktop App, remember to set the static UITestMethodAttribute.DispatcherQueue during the test initialization. - UITestMethodAttribute.DispatcherQueue should not be null. To use UITestMethodAttribute within a WinUI Desktop App, remember to set the static UITestMethodAttribute.DispatcherQueue during the test initialization. + UITestMethodAttribute.DispatcherQueue boş olmamalıdır. UITestMethodAttribute'ı bir WinUI Masaüstü Uygulamasında kullanmak için, test başlatma sırasında statik UITestMethodAttribute.DispatcherQueue'yu ayarlamayı unutmayın. diff --git a/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.zh-Hans.xlf b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.zh-Hans.xlf index 873542de87..0d2a247a4d 100644 --- a/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.zh-Hans.xlf +++ b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.zh-Hans.xlf @@ -4,7 +4,7 @@ Type '{0}' is not assignable to '{1}'. - Type '{0}' is not assignable to '{1}'. + 类型“{0}”不能分配给“{1}”。 - {0} argument name like "applicationType" - {1} fully qualified class name like "Microsoft.UI.Xaml.Application" @@ -12,7 +12,7 @@ UITestMethodAttribute.DispatcherQueue should not be null. To use UITestMethodAttribute within a WinUI Desktop App, remember to set the static UITestMethodAttribute.DispatcherQueue during the test initialization. - UITestMethodAttribute.DispatcherQueue should not be null. To use UITestMethodAttribute within a WinUI Desktop App, remember to set the static UITestMethodAttribute.DispatcherQueue during the test initialization. + UITestMethodAttribute.DispatcherQueue 不应为 null。若要在 WinUI 桌面应用中使用 UITestMethodAttribute,请在测试初始化期间设置静态 UITestMethodAttribute.DispatcherQueue。 diff --git a/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.zh-Hant.xlf b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.zh-Hant.xlf index c185c5d236..90f4e3bb61 100644 --- a/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.zh-Hant.xlf +++ b/src/TestFramework/TestFramework.Extensions/Resources/xlf/FrameworkExtensionsMessages.zh-Hant.xlf @@ -4,7 +4,7 @@ Type '{0}' is not assignable to '{1}'. - Type '{0}' is not assignable to '{1}'. + 無法將類型 '{0}' {0} 指派給 '{1}。 - {0} argument name like "applicationType" - {1} fully qualified class name like "Microsoft.UI.Xaml.Application" @@ -12,7 +12,7 @@ UITestMethodAttribute.DispatcherQueue should not be null. To use UITestMethodAttribute within a WinUI Desktop App, remember to set the static UITestMethodAttribute.DispatcherQueue during the test initialization. - UITestMethodAttribute.DispatcherQueue should not be null. To use UITestMethodAttribute within a WinUI Desktop App, remember to set the static UITestMethodAttribute.DispatcherQueue during the test initialization. + UITestMethodAttribute.DispatcherQueue 不應為 Null。若要在 WinUI 傳統型應用程式內使用 UITestMethodAttribute,請記得在測試初始化期間設定靜態 UITestMethodAttribute.DispatcherQueue。 From 8692f1a192034dd825aa0962aebb03bffd131175 Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Tue, 15 Jul 2025 15:46:06 +1000 Subject: [PATCH 204/541] use the in built StringBuilder append char count (#6013) --- .../MSTest.SourceGeneration/Helpers/IndentedStringBuilder.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Analyzers/MSTest.SourceGeneration/Helpers/IndentedStringBuilder.cs b/src/Analyzers/MSTest.SourceGeneration/Helpers/IndentedStringBuilder.cs index 39fdb20ba0..a9b2c407f4 100644 --- a/src/Analyzers/MSTest.SourceGeneration/Helpers/IndentedStringBuilder.cs +++ b/src/Analyzers/MSTest.SourceGeneration/Helpers/IndentedStringBuilder.cs @@ -76,7 +76,7 @@ private StringBuilder MaybeAppendIndent() { if (_needsIndent) { - _builder.Append(new string(' ', IndentationLevel * 4)); + _builder.Append(' ', IndentationLevel * 4); } return _builder; From 1e6660adeb52d6121fd4fad02c74a0520834e9f2 Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Tue, 15 Jul 2025 16:27:29 +1000 Subject: [PATCH 205/541] fix RunSettingsEnvironmentVariableProvider file name (#6007) --- ...ableProvider .cs => RunSettingsEnvironmentVariableProvider.cs} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename src/Platform/Microsoft.Testing.Extensions.VSTestBridge/TestHostControllers/{RunSettingsEnvironmentVariableProvider .cs => RunSettingsEnvironmentVariableProvider.cs} (100%) diff --git a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/TestHostControllers/RunSettingsEnvironmentVariableProvider .cs b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/TestHostControllers/RunSettingsEnvironmentVariableProvider.cs similarity index 100% rename from src/Platform/Microsoft.Testing.Extensions.VSTestBridge/TestHostControllers/RunSettingsEnvironmentVariableProvider .cs rename to src/Platform/Microsoft.Testing.Extensions.VSTestBridge/TestHostControllers/RunSettingsEnvironmentVariableProvider.cs From 4b082ae23f0746298914432715f416484cb7b5b3 Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Tue, 15 Jul 2025 16:30:52 +1000 Subject: [PATCH 206/541] remove some un-used variables (#6010) --- src/Adapter/MSTest.Engine/Engine/TestArgumentsManager.cs | 2 -- .../PreferDisposeOverTestCleanupFixer.cs | 1 - .../TestContextShouldBeValidFixer.cs | 3 --- .../TestMethodShouldBeValidCodeFix.cs | 1 - .../MSTest.Analyzers/DynamicDataShouldBeValidAnalyzer.cs | 2 +- .../Microsoft.Testing.Platform/Hosts/CommonTestHost.cs | 1 - 6 files changed, 1 insertion(+), 9 deletions(-) diff --git a/src/Adapter/MSTest.Engine/Engine/TestArgumentsManager.cs b/src/Adapter/MSTest.Engine/Engine/TestArgumentsManager.cs index 727a017a2a..1fb6ec6235 100644 --- a/src/Adapter/MSTest.Engine/Engine/TestArgumentsManager.cs +++ b/src/Adapter/MSTest.Engine/Engine/TestArgumentsManager.cs @@ -37,8 +37,6 @@ internal async Task ExpandTestNodeAsync(TestNode currentNode) { RoslynDebug.Assert(IsExpandableTestNode(currentNode), "Test node is not expandable"); - var expandableTestNode = (IExpandableTestNode)currentNode; - int argumentsRowIndex = -1; bool isIndexArgumentPropertiesProvider = false; if (!_testArgumentsEntryProviders.TryGetValue( diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/PreferDisposeOverTestCleanupFixer.cs b/src/Analyzers/MSTest.Analyzers.CodeFixes/PreferDisposeOverTestCleanupFixer.cs index 0f47efc748..af071e4a07 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/PreferDisposeOverTestCleanupFixer.cs +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/PreferDisposeOverTestCleanupFixer.cs @@ -82,7 +82,6 @@ private static async Task AddDisposeAndBaseClassAsync( SyntaxGenerator generator = editor.Generator; TypeDeclarationSyntax newParent = containingType; INamedTypeSymbol? iDisposableSymbol = semanticModel.Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemIDisposable); - INamedTypeSymbol? testCleanupAttributeSymbol = semanticModel.Compilation.GetTypeByMetadataName(WellKnownTypeNames.MicrosoftVisualStudioTestToolsUnitTestingTestCleanupAttribute); // Move the code from TestCleanup to Dispose method MethodDeclarationSyntax? existingDisposeMethod = containingType.Members diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/TestContextShouldBeValidFixer.cs b/src/Analyzers/MSTest.Analyzers.CodeFixes/TestContextShouldBeValidFixer.cs index a504d42fb0..14639ce961 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/TestContextShouldBeValidFixer.cs +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/TestContextShouldBeValidFixer.cs @@ -62,9 +62,6 @@ private static async Task FixMemberDeclarationAsync(Document document, { cancellationToken.ThrowIfCancellationRequested(); - // Get the SemanticModel and Compilation - SemanticModel semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); - DocumentEditor editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false); // Remove the static and readonly modifiers if it exists diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/TestMethodShouldBeValidCodeFix.cs b/src/Analyzers/MSTest.Analyzers.CodeFixes/TestMethodShouldBeValidCodeFix.cs index 0facc4173f..f7bf2b94e9 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/TestMethodShouldBeValidCodeFix.cs +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/TestMethodShouldBeValidCodeFix.cs @@ -98,7 +98,6 @@ private static async Task FixTestMethodAsync(Document document, Method // Ensure the method returns void or Task/ValueTask. SemanticModel semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); - Compilation compilation = semanticModel.Compilation; var wellKnownTypeProvider = WellKnownTypeProvider.GetOrCreate(semanticModel.Compilation); INamedTypeSymbol? taskSymbol = wellKnownTypeProvider.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemThreadingTasksTask); INamedTypeSymbol? valueTaskSymbol = wellKnownTypeProvider.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemThreadingTasksValueTask); diff --git a/src/Analyzers/MSTest.Analyzers/DynamicDataShouldBeValidAnalyzer.cs b/src/Analyzers/MSTest.Analyzers/DynamicDataShouldBeValidAnalyzer.cs index d5af2d294f..3ac8f69fca 100644 --- a/src/Analyzers/MSTest.Analyzers/DynamicDataShouldBeValidAnalyzer.cs +++ b/src/Analyzers/MSTest.Analyzers/DynamicDataShouldBeValidAnalyzer.cs @@ -272,7 +272,7 @@ private static void AnalyzeDataSource(SymbolAnalysisContext context, AttributeDa // Validate member return type. ITypeSymbol? memberTypeSymbol = member.GetMemberType(); - if (memberTypeSymbol is IArrayTypeSymbol arrayType) + if (memberTypeSymbol is IArrayTypeSymbol) { return; } diff --git a/src/Platform/Microsoft.Testing.Platform/Hosts/CommonTestHost.cs b/src/Platform/Microsoft.Testing.Platform/Hosts/CommonTestHost.cs index f9145a8c8d..656b2aaf84 100644 --- a/src/Platform/Microsoft.Testing.Platform/Hosts/CommonTestHost.cs +++ b/src/Platform/Microsoft.Testing.Platform/Hosts/CommonTestHost.cs @@ -45,7 +45,6 @@ public async Task RunAsync() { RoslynDebug.Assert(PushOnlyProtocol is not null); - ITestApplicationModuleInfo testApplicationModuleInfo = serviceProvider.GetTestApplicationModuleInfo(); bool isValidProtocol = await PushOnlyProtocol.IsCompatibleProtocolAsync(GetHostType()).ConfigureAwait(false); exitCode = isValidProtocol From b6693e2c57d941c98113827e57c5c7f8f191a207 Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Tue, 15 Jul 2025 17:16:25 +1000 Subject: [PATCH 207/541] fix nullability of TestProgressState.DiscoveredTests (#6011) --- .../OutputDevice/Terminal/TerminalTestReporter.cs | 13 +++++-------- .../OutputDevice/Terminal/TestProgressState.cs | 2 +- 2 files changed, 6 insertions(+), 9 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporter.cs b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporter.cs index 017fcbe6e2..a24a154e01 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporter.cs +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporter.cs @@ -865,8 +865,8 @@ internal void TestDiscovered( string assembly, string? targetFramework, string? architecture, - string? displayName, - string? uid) + string displayName, + string uid) { TestProgressState asm = _assemblies[$"{assembly}|{targetFramework}|{architecture}"]; @@ -902,13 +902,10 @@ public void AppendTestDiscoverySummary(ITerminal terminal) terminal.AppendLine(); } - foreach ((string? displayName, string? uid) in assembly.DiscoveredTests) + foreach ((string displayName, string? uid) in assembly.DiscoveredTests) { - if (displayName is not null) - { - terminal.Append(SingleIndentation); - terminal.AppendLine(displayName); - } + terminal.Append(SingleIndentation); + terminal.AppendLine(displayName); } terminal.AppendLine(); diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TestProgressState.cs b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TestProgressState.cs index 73a8aff848..66c4dfe712 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TestProgressState.cs +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TestProgressState.cs @@ -45,7 +45,7 @@ public TestProgressState(long id, string assembly, string? targetFramework, stri public long Version { get; internal set; } - public List<(string? DisplayName, string? UID)> DiscoveredTests { get; internal set; } = []; + public List<(string DisplayName, string UID)> DiscoveredTests { get; internal set; } = []; internal void AddError(string text) => Messages.Add(new ErrorMessage(text)); From 9f345122c97eee4751c951b94a473d4138ab1ee2 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Tue, 15 Jul 2025 09:26:14 +0200 Subject: [PATCH 208/541] Inherit DescriptionAttribute from TestPropertyAttribute (#6004) --- .../Discovery/TypeEnumerator.cs | 4 ---- .../MSTestAdapter.PlatformServices/EngineConstants.cs | 2 -- .../Extensions/TestCaseExtensions.cs | 6 ------ .../ObjectModel/UnitTestElement.cs | 5 ----- .../MSTest.Analyzers/UseAttributeOnTestMethodAnalyzer.cs | 6 +++--- .../Attributes/TestMethod/DescriptionAttribute.cs | 9 ++++++--- .../Discovery/TypeEnumeratorTests.cs | 3 ++- .../ObjectModel/UnitTestElementTests.cs | 2 -- 8 files changed, 11 insertions(+), 26 deletions(-) diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Discovery/TypeEnumerator.cs b/src/Adapter/MSTestAdapter.PlatformServices/Discovery/TypeEnumerator.cs index 78342edf83..8b7e0db86c 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Discovery/TypeEnumerator.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Discovery/TypeEnumerator.cs @@ -174,10 +174,6 @@ internal UnitTestElement GetTestFromMethod(MethodInfo method, bool isDeclaredInT { testElement.CssProjectStructure = cssProjectStructure.CssProjectStructure; } - else if (attributes[i] is DescriptionAttribute descriptionAttribute) - { - testElement.Description = descriptionAttribute.Description; - } } IEnumerable workItemAttributes = attributes.OfType(); diff --git a/src/Adapter/MSTestAdapter.PlatformServices/EngineConstants.cs b/src/Adapter/MSTestAdapter.PlatformServices/EngineConstants.cs index 0659af433f..d7b3b0e940 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/EngineConstants.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/EngineConstants.cs @@ -66,7 +66,6 @@ internal static class EngineConstants internal const string TestRunParametersName = "TestRunParameters"; #region Test Property registration - internal static readonly TestProperty DescriptionProperty = TestProperty.Register("Description", DescriptionLabel, typeof(string), TestPropertyAttributes.Hidden, typeof(TestCase)); internal static readonly TestProperty WorkItemIdsProperty = TestProperty.Register("WorkItemIds", WorkItemIdsLabel, typeof(string[]), TestPropertyAttributes.Hidden, typeof(TestCase)); @@ -149,7 +148,6 @@ internal static class EngineConstants private const string ExecutionIdLabel = "ExecutionId"; private const string ParentExecIdLabel = "ParentExecId"; private const string InnerResultsCountLabel = "InnerResultsCount"; - private const string DescriptionLabel = "Description"; private const string CssIterationLabel = "CssIteration"; private const string CssProjectStructureLabel = "CssProjectStructure"; private const string WorkItemIdsLabel = "WorkItemIds"; diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Extensions/TestCaseExtensions.cs b/src/Adapter/MSTestAdapter.PlatformServices/Extensions/TestCaseExtensions.cs index 1cd8d5a324..a016393e82 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Extensions/TestCaseExtensions.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Extensions/TestCaseExtensions.cs @@ -123,12 +123,6 @@ internal static UnitTestElement ToUnitTestElement(this TestCase testCase, string testElement.CssProjectStructure = cssProjectStructure; } - string? description = testCase.GetPropertyValue(EngineConstants.DescriptionProperty, null); - if (!StringEx.IsNullOrWhiteSpace(description)) - { - testElement.Description = description; - } - string[]? workItemIds = testCase.GetPropertyValue(EngineConstants.WorkItemIdsProperty, null); if (workItemIds is { Length: > 0 }) { diff --git a/src/Adapter/MSTestAdapter.PlatformServices/ObjectModel/UnitTestElement.cs b/src/Adapter/MSTestAdapter.PlatformServices/ObjectModel/UnitTestElement.cs index ea8e011ae4..aa7fd4ec74 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/ObjectModel/UnitTestElement.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/ObjectModel/UnitTestElement.cs @@ -163,11 +163,6 @@ internal TestCase ToTestCase() testCase.SetPropertyValue(EngineConstants.CssProjectStructureProperty, CssProjectStructure); } - if (!StringEx.IsNullOrEmpty(Description)) - { - testCase.SetPropertyValue(EngineConstants.DescriptionProperty, Description); - } - if (WorkItemIds != null) { testCase.SetPropertyValue(EngineConstants.WorkItemIdsProperty, WorkItemIds); diff --git a/src/Analyzers/MSTest.Analyzers/UseAttributeOnTestMethodAnalyzer.cs b/src/Analyzers/MSTest.Analyzers/UseAttributeOnTestMethodAnalyzer.cs index f26f04834e..f3f8b2a28f 100644 --- a/src/Analyzers/MSTest.Analyzers/UseAttributeOnTestMethodAnalyzer.cs +++ b/src/Analyzers/MSTest.Analyzers/UseAttributeOnTestMethodAnalyzer.cs @@ -127,15 +127,15 @@ public sealed class UseAttributeOnTestMethodAnalyzer : DiagnosticAnalyzer isEnabledByDefault: true); // IMPORTANT: Remember to add any new rule to the rule tuple. - // IMPORTANT: The order is important. For example, Owner is also TestProperty. We report the first violation and then bail-out. - // It may be a better idea to consolidate OwnerRule, PriorityRule, and TestPropertyRule into a single rule. + // IMPORTANT: The order is important. For example, Owner, Priority, and Description are also TestProperty. We report the first violation and then bail-out. + // It may be a better idea to consolidate OwnerRule, PriorityRule, DescriptionRule, and TestPropertyRule into a single rule. private static readonly List<(string AttributeFullyQualifiedName, DiagnosticDescriptor Rule)> RuleTuples = [ (WellKnownTypeNames.MicrosoftVisualStudioTestToolsUnitTestingOwnerAttribute, OwnerRule), (WellKnownTypeNames.MicrosoftVisualStudioTestToolsUnitTestingPriorityAttribute, PriorityRule), + (WellKnownTypeNames.MicrosoftVisualStudioTestToolsUnitTestingDescriptionAttribute, DescriptionRule), (WellKnownTypeNames.MicrosoftVisualStudioTestToolsUnitTestingTestPropertyAttribute, TestPropertyRule), (WellKnownTypeNames.MicrosoftVisualStudioTestToolsUnitTestingWorkItemAttribute, WorkItemRule), - (WellKnownTypeNames.MicrosoftVisualStudioTestToolsUnitTestingDescriptionAttribute, DescriptionRule), (WellKnownTypeNames.MicrosoftVisualStudioTestToolsUnitTestingExpectedExceptionBaseAttribute, ExpectedExceptionRule), (WellKnownTypeNames.MicrosoftVisualStudioTestToolsUnitTestingCssIterationAttribute, CssIterationRule), (WellKnownTypeNames.MicrosoftVisualStudioTestToolsUnitTestingCssProjectStructureAttribute, CssProjectStructureRule), diff --git a/src/TestFramework/TestFramework/Attributes/TestMethod/DescriptionAttribute.cs b/src/TestFramework/TestFramework/Attributes/TestMethod/DescriptionAttribute.cs index 7917128c42..60fa6e5efb 100644 --- a/src/TestFramework/TestFramework/Attributes/TestMethod/DescriptionAttribute.cs +++ b/src/TestFramework/TestFramework/Attributes/TestMethod/DescriptionAttribute.cs @@ -7,16 +7,19 @@ namespace Microsoft.VisualStudio.TestTools.UnitTesting; /// Description of the test. /// [AttributeUsage(AttributeTargets.Method)] -public sealed class DescriptionAttribute : Attribute +public sealed class DescriptionAttribute : TestPropertyAttribute { /// /// Initializes a new instance of the class to describe a test. /// /// The description. - public DescriptionAttribute(string? description) => Description = description; + public DescriptionAttribute(string? description) + : base("Description", description ?? string.Empty) + { + } /// /// Gets the description of a test. /// - public string? Description { get; } + public string? Description => Value; } diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Discovery/TypeEnumeratorTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Discovery/TypeEnumeratorTests.cs index a6f584291e..8def534a6f 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Discovery/TypeEnumeratorTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Discovery/TypeEnumeratorTests.cs @@ -403,7 +403,8 @@ public void GetTestFromMethodShouldSetDescription() MSTest.TestAdapter.ObjectModel.UnitTestElement testElement = typeEnumerator.GetTestFromMethod(methodInfo, true, _warnings); - Verify(testElement.Description == "Dummy description"); + Verify(testElement.Traits is not null); + Verify(testElement.Traits.Any(t => t.Name == "Description" && t.Value == "Dummy description")); } public void GetTestFromMethodShouldSetWorkItemIds() diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/ObjectModel/UnitTestElementTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/ObjectModel/UnitTestElementTests.cs index 77fa92c814..27dc52885b 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/ObjectModel/UnitTestElementTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/ObjectModel/UnitTestElementTests.cs @@ -140,14 +140,12 @@ public void ToTestCaseShouldSetPropertiesIfPresent() { _unitTestElement.CssIteration = "12"; _unitTestElement.CssProjectStructure = "ProjectStructure"; - _unitTestElement.Description = "I am a dummy test"; _unitTestElement.WorkItemIds = ["2312", "22332"]; var testCase = _unitTestElement.ToTestCase(); Verify((testCase.GetPropertyValue(EngineConstants.CssIterationProperty) as string) == "12"); Verify((testCase.GetPropertyValue(EngineConstants.CssProjectStructureProperty) as string) == "ProjectStructure"); - Verify((testCase.GetPropertyValue(EngineConstants.DescriptionProperty) as string) == "I am a dummy test"); Verify(new string[] { "2312", "22332" }.SequenceEqual((string[])testCase.GetPropertyValue(EngineConstants.WorkItemIdsProperty)!)); } From 3d3ad857d537add532b1b0918b6f5547a61192c7 Mon Sep 17 00:00:00 2001 From: Copilot <198982749+Copilot@users.noreply.github.com> Date: Tue, 15 Jul 2025 09:39:50 +0200 Subject: [PATCH 209/541] Add CIConditionAttribute to support CI-specific test execution control (#5797) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: Evangelink <11340282+Evangelink@users.noreply.github.com> Co-authored-by: Youssef1313 <31348972+Youssef1313@users.noreply.github.com> Co-authored-by: Youssef Victor Co-authored-by: Amaury Levé --- .../Helpers/EnvironmentWrapper.cs | 9 - .../Helpers/IEnvironment.cs | 15 - .../Services/TestSourceHost.cs | 1 - .../TestMethod/CIConditionAttribute.cs | 135 +++++++++ .../TestFramework/Internal/IEnvironment.cs | 30 ++ .../PublicAPI/PublicAPI.Unshipped.txt | 5 + .../Execution/TestExecutionManagerTests.cs | 1 - .../Attributes/CIConditionAttributeTests.cs | 273 ++++++++++++++++++ 8 files changed, 443 insertions(+), 26 deletions(-) delete mode 100644 src/Adapter/MSTestAdapter.PlatformServices/Helpers/EnvironmentWrapper.cs delete mode 100644 src/Adapter/MSTestAdapter.PlatformServices/Helpers/IEnvironment.cs create mode 100644 src/TestFramework/TestFramework/Attributes/TestMethod/CIConditionAttribute.cs create mode 100644 src/TestFramework/TestFramework/Internal/IEnvironment.cs create mode 100644 test/UnitTests/TestFramework.UnitTests/Attributes/CIConditionAttributeTests.cs diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Helpers/EnvironmentWrapper.cs b/src/Adapter/MSTestAdapter.PlatformServices/Helpers/EnvironmentWrapper.cs deleted file mode 100644 index 792366d479..0000000000 --- a/src/Adapter/MSTestAdapter.PlatformServices/Helpers/EnvironmentWrapper.cs +++ /dev/null @@ -1,9 +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. - -namespace Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Helpers; - -internal sealed class EnvironmentWrapper : IEnvironment -{ - public string MachineName => Environment.MachineName; -} diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Helpers/IEnvironment.cs b/src/Adapter/MSTestAdapter.PlatformServices/Helpers/IEnvironment.cs deleted file mode 100644 index 96395c6bc4..0000000000 --- a/src/Adapter/MSTestAdapter.PlatformServices/Helpers/IEnvironment.cs +++ /dev/null @@ -1,15 +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. - -namespace Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Helpers; - -/// -/// Interface to abstract environment related information. -/// -internal interface IEnvironment -{ - /// - /// Gets the machine name. - /// - string MachineName { get; } -} diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Services/TestSourceHost.cs b/src/Adapter/MSTestAdapter.PlatformServices/Services/TestSourceHost.cs index ec92e515ce..a88a8d463e 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Services/TestSourceHost.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Services/TestSourceHost.cs @@ -223,7 +223,6 @@ public void Dispose() #if NETFRAMEWORK || (NET && !WINDOWS_UWP) _parentDomainAssemblyResolver?.Dispose(); _parentDomainAssemblyResolver = null; - #endif #if NETFRAMEWORK diff --git a/src/TestFramework/TestFramework/Attributes/TestMethod/CIConditionAttribute.cs b/src/TestFramework/TestFramework/Attributes/TestMethod/CIConditionAttribute.cs new file mode 100644 index 0000000000..89bf7ace40 --- /dev/null +++ b/src/TestFramework/TestFramework/Attributes/TestMethod/CIConditionAttribute.cs @@ -0,0 +1,135 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +namespace Microsoft.VisualStudio.TestTools.UnitTesting; + +/// +/// This attribute is used to conditionally control whether a test class or a test method will run or be ignored based on whether the test is running in a CI environment. +/// +/// +/// This attribute isn't inherited. Applying it to a base class will not affect derived classes. +/// +[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = false, AllowMultiple = false)] +public sealed class CIConditionAttribute : ConditionBaseAttribute +{ + private readonly IEnvironment _environment; + + /// + /// Initializes a new instance of the class. + /// + /// Decides whether the test should be included or excluded in CI environments. + public CIConditionAttribute(ConditionMode mode) + : this(mode, new EnvironmentWrapper()) + { + } + + internal CIConditionAttribute(ConditionMode mode, IEnvironment environment) + : base(mode) + { + _environment = environment; + IgnoreMessage = mode == ConditionMode.Include + ? "Test is only supported in CI environments" + : "Test is not supported in CI environments"; + } + + /// + /// Gets a value indicating whether the test method or test class should run. + /// + public override bool ShouldRun => IsCIEnvironment(); + + /// + /// Gets the ignore message (in case returns ). + /// + public override string? IgnoreMessage { get; } + + /// + /// Gets the group name for this attribute. + /// + public override string GroupName => nameof(CIConditionAttribute); + + // CI Detection logic based on https://learn.microsoft.com/dotnet/core/tools/telemetry#continuous-integration-detection + // From: https://github.com/dotnet/sdk/blob/main/src/Cli/dotnet/Telemetry/CIEnvironmentDetectorForTelemetry.cs + private bool IsCIEnvironment() + { + // Systems that provide boolean values only, so we can simply parse and check for true + string[] booleanVariables = + [ + // Azure Pipelines - https://docs.microsoft.com/azure/devops/pipelines/build/variables#system-variables-devops-services + "TF_BUILD", + + // GitHub Actions - https://docs.github.com/en/actions/learn-github-actions/environment-variables#default-environment-variables + "GITHUB_ACTIONS", + + // AppVeyor - https://www.appveyor.com/docs/environment-variables/ + "APPVEYOR", + + // A general-use flag - Many of the major players support this: AzDo, GitHub, GitLab, AppVeyor, Travis CI, CircleCI. + "CI", + + // Travis CI - https://docs.travis-ci.com/user/environment-variables/#default-environment-variables + "TRAVIS", + + // CircleCI - https://circleci.com/docs/2.0/env-vars/#built-in-environment-variables + "CIRCLECI" + ]; + + // Systems where every variable must be present and not-null before returning true + string[][] allNotNullVariables = + [ + // AWS CodeBuild - https://docs.aws.amazon.com/codebuild/latest/userguide/build-env-ref-env-vars.html + ["CODEBUILD_BUILD_ID", "AWS_REGION"], + + // Jenkins - https://github.com/jenkinsci/jenkins/blob/master/core/src/main/resources/jenkins/model/CoreEnvironmentContributor/buildEnv.groovy + ["BUILD_ID", "BUILD_URL"], + + // Google Cloud Build - https://cloud.google.com/build/docs/configuring-builds/substitute-variable-values#using_default_substitutions + ["BUILD_ID", "PROJECT_ID"], + ]; + + // Systems where the variable must be present and not-null + string[] ifNonNullVariables = + [ + // TeamCity - https://www.jetbrains.com/help/teamcity/predefined-build-parameters.html#Predefined+Server+Build+Parameters + "TEAMCITY_VERSION", + + // JetBrains Space - https://www.jetbrains.com/help/space/automation-environment-variables.html#general + "JB_SPACE_API_URL" + ]; + + foreach (string booleanVariable in booleanVariables) + { + if (bool.TryParse(_environment.GetEnvironmentVariable(booleanVariable), out bool envVar) && envVar) + { + return true; + } + } + + foreach (string[] variables in allNotNullVariables) + { + bool allVariablesPresent = true; + foreach (string variable in variables) + { + if (string.IsNullOrEmpty(_environment.GetEnvironmentVariable(variable))) + { + allVariablesPresent = false; + break; + } + } + + if (allVariablesPresent) + { + return true; + } + } + + foreach (string variable in ifNonNullVariables) + { + if (!string.IsNullOrEmpty(_environment.GetEnvironmentVariable(variable))) + { + return true; + } + } + + return false; + } +} diff --git a/src/TestFramework/TestFramework/Internal/IEnvironment.cs b/src/TestFramework/TestFramework/Internal/IEnvironment.cs new file mode 100644 index 0000000000..6624207d3e --- /dev/null +++ b/src/TestFramework/TestFramework/Internal/IEnvironment.cs @@ -0,0 +1,30 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +namespace Microsoft.VisualStudio.TestTools.UnitTesting; + +/// +/// Interface to abstract environment related information. +/// +internal interface IEnvironment +{ + /// + /// Gets the machine name. + /// + string MachineName { get; } + + /// + void SetEnvironmentVariable(string variable, string? value); + + /// + string? GetEnvironmentVariable(string name); +} + +internal sealed class EnvironmentWrapper : IEnvironment +{ + public string MachineName => Environment.MachineName; + + public string? GetEnvironmentVariable(string name) => Environment.GetEnvironmentVariable(name); + + public void SetEnvironmentVariable(string variable, string? value) => Environment.SetEnvironmentVariable(variable, value); +} diff --git a/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Unshipped.txt b/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Unshipped.txt index 1535883112..65701549f5 100644 --- a/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Unshipped.txt +++ b/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Unshipped.txt @@ -1,6 +1,11 @@ #nullable enable Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AssertNonStrictThrowsInterpolatedStringHandler.AssertNonStrictThrowsInterpolatedStringHandler(int literalLength, int formattedCount, System.Func! action, out bool shouldAppend) -> void +Microsoft.VisualStudio.TestTools.UnitTesting.CIConditionAttribute +Microsoft.VisualStudio.TestTools.UnitTesting.CIConditionAttribute.CIConditionAttribute(Microsoft.VisualStudio.TestTools.UnitTesting.ConditionMode mode) -> void Microsoft.VisualStudio.TestTools.UnitTesting.ConditionBaseAttribute.Mode.get -> Microsoft.VisualStudio.TestTools.UnitTesting.ConditionMode +override Microsoft.VisualStudio.TestTools.UnitTesting.CIConditionAttribute.GroupName.get -> string! +override Microsoft.VisualStudio.TestTools.UnitTesting.CIConditionAttribute.IgnoreMessage.get -> string? +override Microsoft.VisualStudio.TestTools.UnitTesting.CIConditionAttribute.ShouldRun.get -> bool static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.ContainsSingle(System.Func! predicate, System.Collections.Generic.IEnumerable! collection, string! message = "") -> T static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.DoesNotEndWith(string? substring, string? value, string! message = "") -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.DoesNotEndWith(string? substring, string? value, System.StringComparison comparisonType, string! message = "") -> void diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestExecutionManagerTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestExecutionManagerTests.cs index ecbcbfdfe3..7c10d74213 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestExecutionManagerTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestExecutionManagerTests.cs @@ -3,7 +3,6 @@ using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter; using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution; -using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Helpers; using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel; using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Discovery; diff --git a/test/UnitTests/TestFramework.UnitTests/Attributes/CIConditionAttributeTests.cs b/test/UnitTests/TestFramework.UnitTests/Attributes/CIConditionAttributeTests.cs new file mode 100644 index 0000000000..701a1f4ca7 --- /dev/null +++ b/test/UnitTests/TestFramework.UnitTests/Attributes/CIConditionAttributeTests.cs @@ -0,0 +1,273 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using FluentAssertions; + +using Moq; + +using TestFramework.ForTestingMSTest; + +namespace UnitTestFramework.Tests; + +/// +/// Tests for class CIConditionAttribute. +/// +public class CIConditionAttributeTests : TestContainer +{ + public void Constructor_SetsCorrectMode() + { + // Arrange + var mockEnvironment = new Mock(); + + // Act + var includeAttribute = new CIConditionAttribute(ConditionMode.Include, mockEnvironment.Object); + var excludeAttribute = new CIConditionAttribute(ConditionMode.Exclude, mockEnvironment.Object); + + // Assert + includeAttribute.Mode.Should().Be(ConditionMode.Include); + excludeAttribute.Mode.Should().Be(ConditionMode.Exclude); + } + + public void GroupName_ReturnsCorrectValue() + { + // Arrange + var mockEnvironment = new Mock(); + var attribute = new CIConditionAttribute(ConditionMode.Include, mockEnvironment.Object); + + // Act & Assert + attribute.GroupName.Should().Be(nameof(CIConditionAttribute)); + } + + public void IgnoreMessage_IncludeMode_ReturnsCorrectMessage() + { + // Arrange + var mockEnvironment = new Mock(); + var attribute = new CIConditionAttribute(ConditionMode.Include, mockEnvironment.Object); + + // Act & Assert + attribute.IgnoreMessage.Should().Be("Test is only supported in CI environments"); + } + + public void IgnoreMessage_ExcludeMode_ReturnsCorrectMessage() + { + // Arrange + var mockEnvironment = new Mock(); + var attribute = new CIConditionAttribute(ConditionMode.Exclude, mockEnvironment.Object); + + // Act & Assert + attribute.IgnoreMessage.Should().Be("Test is not supported in CI environments"); + } + + public void ShouldRun_IncludeMode_WhenNotInCI_ReturnsFalse() + { + // Arrange + var mockEnvironment = new Mock(); + var attribute = new CIConditionAttribute(ConditionMode.Include, mockEnvironment.Object); + + // Act & Assert + attribute.ShouldRun.Should().BeFalse(); + } + + public void ShouldRun_ExcludeMode_WhenNotInCI_ReturnsFalse() + { + // Arrange + var mockEnvironment = new Mock(); + var attribute = new CIConditionAttribute(ConditionMode.Exclude, mockEnvironment.Object); + + // Act & Assert + attribute.ShouldRun.Should().BeFalse(); + } + + public void ShouldRun_IncludeMode_WhenInCI_GitHub_ReturnsTrue() + { + // Arrange + var mockEnvironment = new Mock(); + mockEnvironment.Setup(e => e.GetEnvironmentVariable("GITHUB_ACTIONS")).Returns("true"); + var attribute = new CIConditionAttribute(ConditionMode.Include, mockEnvironment.Object); + + // Act & Assert + attribute.ShouldRun.Should().BeTrue(); + } + + public void ShouldRun_ExcludeMode_WhenInCI_GitHub_ReturnsTrue() + { + // Arrange + var mockEnvironment = new Mock(); + mockEnvironment.Setup(e => e.GetEnvironmentVariable("GITHUB_ACTIONS")).Returns("true"); + var attribute = new CIConditionAttribute(ConditionMode.Exclude, mockEnvironment.Object); + + // Act & Assert + attribute.ShouldRun.Should().BeTrue(); + } + + public void ShouldRun_IncludeMode_WhenInCI_AzurePipelines_ReturnsTrue() + { + // Arrange + var mockEnvironment = new Mock(); + mockEnvironment.Setup(e => e.GetEnvironmentVariable("TF_BUILD")).Returns("true"); + var attribute = new CIConditionAttribute(ConditionMode.Include, mockEnvironment.Object); + + // Act & Assert + attribute.ShouldRun.Should().BeTrue(); + } + + public void ShouldRun_IncludeMode_WhenInCI_AppVeyor_ReturnsTrue() + { + // Arrange + var mockEnvironment = new Mock(); + mockEnvironment.Setup(e => e.GetEnvironmentVariable("APPVEYOR")).Returns("true"); + var attribute = new CIConditionAttribute(ConditionMode.Include, mockEnvironment.Object); + + // Act & Assert + attribute.ShouldRun.Should().BeTrue(); + } + + public void ShouldRun_IncludeMode_WhenInCI_Travis_ReturnsTrue() + { + // Arrange + var mockEnvironment = new Mock(); + mockEnvironment.Setup(e => e.GetEnvironmentVariable("TRAVIS")).Returns("true"); + var attribute = new CIConditionAttribute(ConditionMode.Include, mockEnvironment.Object); + + // Act & Assert + attribute.ShouldRun.Should().BeTrue(); + } + + public void ShouldRun_IncludeMode_WhenInCI_CircleCI_ReturnsTrue() + { + // Arrange + var mockEnvironment = new Mock(); + mockEnvironment.Setup(e => e.GetEnvironmentVariable("CIRCLECI")).Returns("true"); + var attribute = new CIConditionAttribute(ConditionMode.Include, mockEnvironment.Object); + + // Act & Assert + attribute.ShouldRun.Should().BeTrue(); + } + + public void ShouldRun_IncludeMode_WhenInCI_Generic_ReturnsTrue() + { + // Arrange + var mockEnvironment = new Mock(); + mockEnvironment.Setup(e => e.GetEnvironmentVariable("CI")).Returns("true"); + var attribute = new CIConditionAttribute(ConditionMode.Include, mockEnvironment.Object); + + // Act & Assert + attribute.ShouldRun.Should().BeTrue(); + } + + public void ShouldRun_IncludeMode_WhenInCI_TeamCity_ReturnsTrue() + { + // Arrange + var mockEnvironment = new Mock(); + mockEnvironment.Setup(e => e.GetEnvironmentVariable("TEAMCITY_VERSION")).Returns("2023.11"); + var attribute = new CIConditionAttribute(ConditionMode.Include, mockEnvironment.Object); + + // Act & Assert + attribute.ShouldRun.Should().BeTrue(); + } + + public void ShouldRun_IncludeMode_WhenInCI_Jenkins_ReturnsTrue() + { + // Arrange + var mockEnvironment = new Mock(); + mockEnvironment.Setup(e => e.GetEnvironmentVariable("BUILD_ID")).Returns("123"); + mockEnvironment.Setup(e => e.GetEnvironmentVariable("BUILD_URL")).Returns("http://jenkins.example.com/job/test/123/"); + var attribute = new CIConditionAttribute(ConditionMode.Include, mockEnvironment.Object); + + // Act & Assert + attribute.ShouldRun.Should().BeTrue(); + } + + public void ShouldRun_IncludeMode_WhenInCI_AWSCodeBuild_ReturnsTrue() + { + // Arrange + var mockEnvironment = new Mock(); + mockEnvironment.Setup(e => e.GetEnvironmentVariable("CODEBUILD_BUILD_ID")).Returns("codebuild-demo-project:b1e6661e-e4f2-4156-9ab9-82a19EXAMPLE"); + mockEnvironment.Setup(e => e.GetEnvironmentVariable("AWS_REGION")).Returns("us-east-1"); + var attribute = new CIConditionAttribute(ConditionMode.Include, mockEnvironment.Object); + + // Act & Assert + attribute.ShouldRun.Should().BeTrue(); + } + + public void ShouldRun_IncludeMode_WhenInCI_GoogleCloudBuild_ReturnsTrue() + { + // Arrange + var mockEnvironment = new Mock(); + mockEnvironment.Setup(e => e.GetEnvironmentVariable("BUILD_ID")).Returns("abc-123-def-456"); + mockEnvironment.Setup(e => e.GetEnvironmentVariable("PROJECT_ID")).Returns("my-project"); + var attribute = new CIConditionAttribute(ConditionMode.Include, mockEnvironment.Object); + + // Act & Assert + attribute.ShouldRun.Should().BeTrue(); + } + + public void ShouldRun_IncludeMode_WhenInCI_JetBrainsSpace_ReturnsTrue() + { + // Arrange + var mockEnvironment = new Mock(); + mockEnvironment.Setup(e => e.GetEnvironmentVariable("JB_SPACE_API_URL")).Returns("https://mycompany.jetbrains.space"); + var attribute = new CIConditionAttribute(ConditionMode.Include, mockEnvironment.Object); + + // Act & Assert + attribute.ShouldRun.Should().BeTrue(); + } + + public void ShouldRun_Jenkins_RequiresBothVariables() + { + // Arrange + var mockEnvironment = new Mock(); + mockEnvironment.Setup(e => e.GetEnvironmentVariable("BUILD_ID")).Returns("123"); + // BUILD_URL not set - should return null by default + var attribute = new CIConditionAttribute(ConditionMode.Include, mockEnvironment.Object); + + // Act & Assert - Should not detect as CI since both variables are required + attribute.ShouldRun.Should().BeFalse(); + } + + public void ShouldRun_AWSCodeBuild_RequiresBothVariables() + { + // Arrange + var mockEnvironment = new Mock(); + mockEnvironment.Setup(e => e.GetEnvironmentVariable("CODEBUILD_BUILD_ID")).Returns("codebuild-demo-project:b1e6661e-e4f2-4156-9ab9-82a19EXAMPLE"); + // AWS_REGION not set - should return null by default + var attribute = new CIConditionAttribute(ConditionMode.Include, mockEnvironment.Object); + + // Act & Assert - Should not detect as CI since both variables are required + attribute.ShouldRun.Should().BeFalse(); + } + + public void ShouldRun_GoogleCloudBuild_RequiresBothVariables() + { + // Arrange + var mockEnvironment = new Mock(); + mockEnvironment.Setup(e => e.GetEnvironmentVariable("BUILD_ID")).Returns("abc-123-def-456"); + // PROJECT_ID not set - should return null by default + var attribute = new CIConditionAttribute(ConditionMode.Include, mockEnvironment.Object); + + // Act & Assert - Should not detect as CI since both variables are required + attribute.ShouldRun.Should().BeFalse(); + } + + public void ShouldRun_BooleanVariable_RequiresTrueValue() + { + // Arrange + var mockEnvironment = new Mock(); + mockEnvironment.Setup(e => e.GetEnvironmentVariable("CI")).Returns("false"); + var attribute = new CIConditionAttribute(ConditionMode.Include, mockEnvironment.Object); + + // Act & Assert - Should not detect as CI since value is false + attribute.ShouldRun.Should().BeFalse(); + } + + public void ShouldRun_BooleanVariable_RequiresValidBooleanValue() + { + // Arrange + var mockEnvironment = new Mock(); + mockEnvironment.Setup(e => e.GetEnvironmentVariable("CI")).Returns("invalid"); + var attribute = new CIConditionAttribute(ConditionMode.Include, mockEnvironment.Object); + + // Act & Assert - Should not detect as CI since value is not a valid boolean + attribute.ShouldRun.Should().BeFalse(); + } +} From cbb86b99c7bd93337598c55722b27f35d66afc4c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Tue, 15 Jul 2025 10:42:17 +0200 Subject: [PATCH 210/541] Ban Directory and File from retry (#6018) --- .../AzureDevOpsReporter.cs | 2 +- .../BannedSymbols.txt | 2 ++ .../RetryOrchestrator.cs | 18 ++++++++++-------- .../TrxReportEngine.cs | 2 +- .../RunSettingsCommandLineOptionsProvider.cs | 2 +- .../RunSettingsConfigurationProvider.cs | 2 +- .../ObjectModel/RunSettingsAdapter.cs | 2 +- .../RunSettingsEnvironmentVariableProvider.cs | 2 +- .../JsonConfigurationProvider.cs | 4 ++-- .../Helpers/System/IFileSystem.cs | 12 ++++++++++-- .../Helpers/System/SystemFileSystem.cs | 12 ++++++++++-- .../Logging/FileLogger.cs | 2 +- .../Logging/FileLoggerProvider.cs | 2 +- .../Telemetry/TelemetryManager.cs | 2 +- .../Steps/MoveFiles.cs | 2 +- .../TrxTests.cs | 4 ++-- ...nSettingsCommandLineOptionsProviderTests.cs | 6 +++--- .../Configuration/ConfigurationManagerTests.cs | 6 +++--- .../Logging/FileLoggerTests.cs | 6 +++--- .../Telemetry/TelemetryManagerTests.cs | 12 ++++++------ 20 files changed, 61 insertions(+), 41 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/AzureDevOpsReporter.cs b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/AzureDevOpsReporter.cs index fc52268f08..08d2667545 100644 --- a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/AzureDevOpsReporter.cs +++ b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/AzureDevOpsReporter.cs @@ -263,7 +263,7 @@ private async Task WriteExceptionAsync(string? explanation, Exception? exception // Combine with repo root, to be able to resolve deterministic build paths. string fullPath = Path.Combine(repoRoot, relativePath); - if (!fileSystem.Exists(fullPath)) + if (!fileSystem.ExistFile(fullPath)) { // Path does not belong to current repository or does not exist, no need to report it because it will not show up in the PR error, we will only see it details of the run, which is the same // as not reporting it this way. Maybe there can be 2 modes, but right now we want this to be usable for GitHub + AzDo, not for pure AzDo. diff --git a/src/Platform/Microsoft.Testing.Extensions.Retry/BannedSymbols.txt b/src/Platform/Microsoft.Testing.Extensions.Retry/BannedSymbols.txt index 6b0c437d6e..7be39f73d1 100644 --- a/src/Platform/Microsoft.Testing.Extensions.Retry/BannedSymbols.txt +++ b/src/Platform/Microsoft.Testing.Extensions.Retry/BannedSymbols.txt @@ -8,3 +8,5 @@ M:System.String.IsNullOrEmpty(System.String); Use 'RoslynString.IsNullOrEmpty' i M:System.String.IsNullOrWhiteSpace(System.String); Use 'RoslynString.IsNullOrWhiteSpace' instead M:System.Diagnostics.Debug.Assert(System.Boolean); Use 'RoslynDebug.Assert' instead M:System.Diagnostics.Debug.Assert(System.Boolean,System.String); Use 'RoslynDebug.Assert' instead +T:System.File; Use 'IFileSystem' instead +T:System.Directory; Use 'IFileSystem' instead diff --git a/src/Platform/Microsoft.Testing.Extensions.Retry/RetryOrchestrator.cs b/src/Platform/Microsoft.Testing.Extensions.Retry/RetryOrchestrator.cs index 2492649cf1..e06210513d 100644 --- a/src/Platform/Microsoft.Testing.Extensions.Retry/RetryOrchestrator.cs +++ b/src/Platform/Microsoft.Testing.Extensions.Retry/RetryOrchestrator.cs @@ -17,11 +17,13 @@ internal sealed class RetryOrchestrator : ITestHostOrchestrator, IOutputDeviceDa { private readonly IServiceProvider _serviceProvider; private readonly ICommandLineOptions _commandLineOptions; + private readonly IFileSystem _fileSystem; public RetryOrchestrator(IServiceProvider serviceProvider) { _serviceProvider = serviceProvider; _commandLineOptions = _serviceProvider.GetCommandLineOptions(); + _fileSystem = _serviceProvider.GetFileSystem(); } public string Uid => nameof(RetryOrchestrator); @@ -35,21 +37,21 @@ public RetryOrchestrator(IServiceProvider serviceProvider) public Task IsEnabledAsync() => Task.FromResult(_commandLineOptions.IsOptionSet(RetryCommandLineOptionsProvider.RetryFailedTestsOptionName)); - private static string CreateRetriesDirectory(string resultDirectory) + private string CreateRetriesDirectory(string resultDirectory) { Exception? lastException = null; // Quite arbitrary. Keep trying to create the directory for 10 times. for (int i = 0; i < 10; i++) { string retryRootFolder = Path.Combine(resultDirectory, "Retries", RandomId.Next()); - if (Directory.Exists(retryRootFolder)) + if (_fileSystem.ExistDirectory(retryRootFolder)) { continue; } try { - Directory.CreateDirectory(retryRootFolder); + _fileSystem.CreateDirectory(retryRootFolder); return retryRootFolder; } catch (IOException ex) @@ -301,7 +303,7 @@ public async Task OrchestrateTestHostExecutionAsync() ApplicationStateGuard.Ensure(currentTryResultFolder is not null); - string[] filesToMove = Directory.GetFiles(currentTryResultFolder, "*.*", SearchOption.AllDirectories); + string[] filesToMove = _fileSystem.GetFiles(currentTryResultFolder, "*.*", SearchOption.AllDirectories); if (filesToMove.Length > 0) { await outputDevice.DisplayAsync(this, new TextOutputDeviceData(ExtensionResources.MoveFiles)).ConfigureAwait(false); @@ -312,14 +314,14 @@ public async Task OrchestrateTestHostExecutionAsync() string finalFileLocation = file.Replace(currentTryResultFolder, resultDirectory); // Create the directory if missing - Directory.CreateDirectory(Path.GetDirectoryName(finalFileLocation)!); + fileSystem.CreateDirectory(Path.GetDirectoryName(finalFileLocation)!); await outputDevice.DisplayAsync(this, new TextOutputDeviceData(string.Format(CultureInfo.InvariantCulture, ExtensionResources.MovingFileToLocation, file, finalFileLocation))).ConfigureAwait(false); #if NETCOREAPP - File.Move(file, finalFileLocation, overwrite: true); + fileSystem.MoveFile(file, finalFileLocation, overwrite: true); #else - File.Copy(file, finalFileLocation, overwrite: true); - File.Delete(file); + fileSystem.CopyFile(file, finalFileLocation, overwrite: true); + fileSystem.DeleteFile(file); #endif } } diff --git a/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxReportEngine.cs b/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxReportEngine.cs index c6455f7365..191dfdb278 100644 --- a/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxReportEngine.cs +++ b/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxReportEngine.cs @@ -203,7 +203,7 @@ public TrxReportEngine(IFileSystem fileSystem, ITestApplicationModuleInfo testAp string outputDirectory = _configuration.GetTestResultDirectory(); // add var for this string finalFileName = Path.Combine(outputDirectory, trxFileName); - bool isFileNameExplicitlyProvidedAndFileExists = isFileNameExplicitlyProvided && _fileSystem.Exists(finalFileName); + bool isFileNameExplicitlyProvidedAndFileExists = isFileNameExplicitlyProvided && _fileSystem.ExistFile(finalFileName); // Note that we need to dispose the IFileStream, not the inner stream. // IFileStream implementations will be responsible to dispose their inner stream. diff --git a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/CommandLine/RunSettingsCommandLineOptionsProvider.cs b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/CommandLine/RunSettingsCommandLineOptionsProvider.cs index 261f1e58d5..8affc8e609 100644 --- a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/CommandLine/RunSettingsCommandLineOptionsProvider.cs +++ b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/CommandLine/RunSettingsCommandLineOptionsProvider.cs @@ -57,7 +57,7 @@ public Task ValidateOptionArgumentsAsync(CommandLineOption com RoslynDebug.Assert(commandOption.Name == RunSettingsOptionName); string filePath = arguments[0]; - if (!_fileSystem.Exists(filePath)) + if (!_fileSystem.ExistFile(filePath)) { return ValidationResult.InvalidTask(string.Format(CultureInfo.InvariantCulture, ExtensionResources.RunsettingsFileDoesNotExist, filePath)); } diff --git a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/Configurations/RunSettingsConfigurationProvider.cs b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/Configurations/RunSettingsConfigurationProvider.cs index 9f4fef4414..d61233e864 100644 --- a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/Configurations/RunSettingsConfigurationProvider.cs +++ b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/Configurations/RunSettingsConfigurationProvider.cs @@ -62,7 +62,7 @@ public async Task BuildAsync(CommandLineParseResult comm { if (commandLineParseResult.TryGetOptionArgumentList(RunSettingsCommandLineOptionsProvider.RunSettingsOptionName, out string[]? runSettingsFilePath)) { - if (_fileSystem.Exists(runSettingsFilePath[0])) + if (_fileSystem.ExistFile(runSettingsFilePath[0])) { _runSettingsFileContent = await _fileSystem.ReadAllTextAsync(runSettingsFilePath[0]).ConfigureAwait(false); } diff --git a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/RunSettingsAdapter.cs b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/RunSettingsAdapter.cs index 0c535f13e4..76dc6dc0ab 100644 --- a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/RunSettingsAdapter.cs +++ b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/RunSettingsAdapter.cs @@ -43,7 +43,7 @@ public RunSettingsAdapter( if (commandLineOptions.TryGetOptionArgumentList(RunSettingsCommandLineOptionsProvider.RunSettingsOptionName, out string[]? fileNames) && fileNames is not null && fileNames.Length == 1 - && fileSystem.Exists(fileNames[0])) + && fileSystem.ExistFile(fileNames[0])) { runSettingsXml = fileSystem.ReadAllText(fileNames[0]); } diff --git a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/TestHostControllers/RunSettingsEnvironmentVariableProvider.cs b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/TestHostControllers/RunSettingsEnvironmentVariableProvider.cs index a0d9366494..72a5fd8152 100644 --- a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/TestHostControllers/RunSettingsEnvironmentVariableProvider.cs +++ b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/TestHostControllers/RunSettingsEnvironmentVariableProvider.cs @@ -38,7 +38,7 @@ public async Task IsEnabledAsync() return false; } - if (!_fileSystem.Exists(runsettings[0])) + if (!_fileSystem.ExistFile(runsettings[0])) { return false; } diff --git a/src/Platform/Microsoft.Testing.Platform/Configurations/JsonConfigurationProvider.cs b/src/Platform/Microsoft.Testing.Platform/Configurations/JsonConfigurationProvider.cs index e1b481d43b..a4227726e0 100644 --- a/src/Platform/Microsoft.Testing.Platform/Configurations/JsonConfigurationProvider.cs +++ b/src/Platform/Microsoft.Testing.Platform/Configurations/JsonConfigurationProvider.cs @@ -40,7 +40,7 @@ public async Task LoadAsync() if (_commandLineParseResult.TryGetOptionArgumentList(PlatformCommandLineProvider.ConfigFileOptionKey, out string[]? configOptions)) { configFileName = configOptions[0]; - if (!_fileSystem.Exists(configFileName)) + if (!_fileSystem.ExistFile(configFileName)) { try { @@ -63,7 +63,7 @@ public async Task LoadAsync() Path.GetFileNameWithoutExtension(fullPath))}{PlatformConfigurationConstants.PlatformConfigSuffixFileName}" : $"{_testApplicationModuleInfo.TryGetAssemblyName()}{PlatformConfigurationConstants.PlatformConfigSuffixFileName}"; - if (!_fileSystem.Exists(configFileName)) + if (!_fileSystem.ExistFile(configFileName)) { return; } diff --git a/src/Platform/Microsoft.Testing.Platform/Helpers/System/IFileSystem.cs b/src/Platform/Microsoft.Testing.Platform/Helpers/System/IFileSystem.cs index a191266c3b..ca8e8fd431 100644 --- a/src/Platform/Microsoft.Testing.Platform/Helpers/System/IFileSystem.cs +++ b/src/Platform/Microsoft.Testing.Platform/Helpers/System/IFileSystem.cs @@ -5,11 +5,13 @@ namespace Microsoft.Testing.Platform.Helpers; internal interface IFileSystem { - bool Exists(string path); + bool ExistFile(string path); + + bool ExistDirectory(string? path); string CreateDirectory(string path); - void Move(string sourceFileName, string destFileName); + void MoveFile(string sourceFileName, string destFileName, bool overwrite = false); IFileStream NewFileStream(string path, FileMode mode); @@ -18,4 +20,10 @@ internal interface IFileSystem string ReadAllText(string path); Task ReadAllTextAsync(string path); + + void CopyFile(string sourceFileName, string destFileName, bool overwrite = false); + + void DeleteFile(string path); + + string[] GetFiles(string path, string searchPattern, SearchOption searchOption); } diff --git a/src/Platform/Microsoft.Testing.Platform/Helpers/System/SystemFileSystem.cs b/src/Platform/Microsoft.Testing.Platform/Helpers/System/SystemFileSystem.cs index 731b81bb9b..d88cbf742a 100644 --- a/src/Platform/Microsoft.Testing.Platform/Helpers/System/SystemFileSystem.cs +++ b/src/Platform/Microsoft.Testing.Platform/Helpers/System/SystemFileSystem.cs @@ -5,11 +5,11 @@ namespace Microsoft.Testing.Platform.Helpers; internal sealed class SystemFileSystem : IFileSystem { - public bool Exists(string path) => File.Exists(path); + public bool ExistFile(string path) => File.Exists(path); public string CreateDirectory(string path) => Directory.CreateDirectory(path).FullName; - public void Move(string sourceFileName, string destFileName) => File.Move(sourceFileName, destFileName); + public void MoveFile(string sourceFileName, string destFileName, bool overwrite = false) => File.Move(sourceFileName, destFileName, overwrite); public IFileStream NewFileStream(string path, FileMode mode) => new SystemFileStream(path, mode); @@ -18,4 +18,12 @@ internal sealed class SystemFileSystem : IFileSystem public string ReadAllText(string path) => File.ReadAllText(path); public Task ReadAllTextAsync(string path) => File.ReadAllTextAsync(path); + + public void CopyFile(string sourceFileName, string destFileName, bool overwrite = false) => File.Copy(sourceFileName, destFileName, overwrite); + + public void DeleteFile(string path) => File.Delete(path); + + public bool ExistDirectory(string? path) => Directory.Exists(path); + + public string[] GetFiles(string path, string searchPattern, SearchOption searchOption) => Directory.GetFiles(path, searchPattern, searchOption); } diff --git a/src/Platform/Microsoft.Testing.Platform/Logging/FileLogger.cs b/src/Platform/Microsoft.Testing.Platform/Logging/FileLogger.cs index ba8d0da941..bd824d507f 100644 --- a/src/Platform/Microsoft.Testing.Platform/Logging/FileLogger.cs +++ b/src/Platform/Microsoft.Testing.Platform/Logging/FileLogger.cs @@ -71,7 +71,7 @@ public FileLogger( if (_options.FileName is not null) { string fileNameFullPath = Path.Combine(_options.LogFolder, _options.FileName); - _fileStream = fileSystem.Exists(fileNameFullPath) + _fileStream = fileSystem.ExistFile(fileNameFullPath) ? OpenFileStreamForAppend(fileStreamFactory, fileNameFullPath) : CreateFileStream(fileStreamFactory, fileNameFullPath); } diff --git a/src/Platform/Microsoft.Testing.Platform/Logging/FileLoggerProvider.cs b/src/Platform/Microsoft.Testing.Platform/Logging/FileLoggerProvider.cs index f6cabc8ffe..b59a9bce0a 100644 --- a/src/Platform/Microsoft.Testing.Platform/Logging/FileLoggerProvider.cs +++ b/src/Platform/Microsoft.Testing.Platform/Logging/FileLoggerProvider.cs @@ -56,7 +56,7 @@ public async Task CheckLogFolderAndMoveToTheNewIfNeededAsync(string testResultDi await DisposeHelper.DisposeAsync(FileLogger).ConfigureAwait(false); // Move the log file to the new directory - _fileSystem.Move(FileLogger.FileName, Path.Combine(testResultDirectory, fileName)); + _fileSystem.MoveFile(FileLogger.FileName, Path.Combine(testResultDirectory, fileName)); FileLogger = new FileLogger( new FileLoggerOptions(testResultDirectory, _options.LogPrefixName, fileName, _options.SyncFlush), diff --git a/src/Platform/Microsoft.Testing.Platform/Telemetry/TelemetryManager.cs b/src/Platform/Microsoft.Testing.Platform/Telemetry/TelemetryManager.cs index f2227455b4..eeaeb0fa56 100644 --- a/src/Platform/Microsoft.Testing.Platform/Telemetry/TelemetryManager.cs +++ b/src/Platform/Microsoft.Testing.Platform/Telemetry/TelemetryManager.cs @@ -103,7 +103,7 @@ private async Task ShowTelemetryBannerFirstNoticeAsync(ServiceProvider servicePr bool sentinelIsNotPresent = RoslynString.IsNullOrWhiteSpace(directory) - || !fileSystem.Exists(Path.Combine(directory, fileName)); + || !fileSystem.ExistFile(Path.Combine(directory, fileName)); if (!sentinelIsNotPresent) { diff --git a/test/Performance/MSTest.Performance.Runner/Steps/MoveFiles.cs b/test/Performance/MSTest.Performance.Runner/Steps/MoveFiles.cs index 6251d93fbc..aa1c4164f1 100644 --- a/test/Performance/MSTest.Performance.Runner/Steps/MoveFiles.cs +++ b/test/Performance/MSTest.Performance.Runner/Steps/MoveFiles.cs @@ -10,7 +10,7 @@ internal class MoveFiles : IStep private readonly DirectoryInfo _finalFolder; private readonly Matcher _matcher = new(); - public string Description => "Move files"; + public string Description => "MoveFile files"; public MoveFiles(string filter, string finalFolder) { diff --git a/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/TrxTests.cs b/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/TrxTests.cs index e718088fef..17ce5c64e7 100644 --- a/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/TrxTests.cs +++ b/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/TrxTests.cs @@ -122,7 +122,7 @@ public async Task TrxReportEngine_GenerateReportAsync_WithArgumentTrxReportFileN _ = _commandLineOptionsMock.Setup(_ => _.TryGetOptionArgumentList(TrxReportGeneratorCommandLine.TrxReportFileNameOptionName, out argumentTrxReportFileName)).Returns(true); PropertyBag propertyBag = new(new PassedTestNodeStateProperty()); TrxReportEngine trxReportEngine = GenerateTrxReportEngine(1, 0, propertyBag, memoryStream, isExplicitFileName: true); - _ = _fileSystem.Setup(x => x.Exists(It.IsAny())).Returns(true); + _ = _fileSystem.Setup(x => x.ExistFile(It.IsAny())).Returns(true); // Act (string fileName, string? warning) = await trxReportEngine.GenerateReportAsync(); @@ -576,7 +576,7 @@ private TrxReportEngine GenerateTrxReportEngine(int passedTestsCount, int failed DateTime testStartTime = DateTime.Now; CancellationToken cancellationToken = CancellationToken.None; - _ = _fileSystem.Setup(x => x.Exists(It.IsAny())).Returns(false); + _ = _fileSystem.Setup(x => x.ExistFile(It.IsAny())).Returns(false); _ = _fileSystem.Setup(x => x.NewFileStream(It.IsAny(), isExplicitFileName ? FileMode.Create : FileMode.CreateNew)) .Returns(memoryStream); diff --git a/test/UnitTests/Microsoft.Testing.Extensions.VSTestBridge.UnitTests/CommandLine/RunSettingsCommandLineOptionsProviderTests.cs b/test/UnitTests/Microsoft.Testing.Extensions.VSTestBridge.UnitTests/CommandLine/RunSettingsCommandLineOptionsProviderTests.cs index 1609ade663..8788c56af4 100644 --- a/test/UnitTests/Microsoft.Testing.Extensions.VSTestBridge.UnitTests/CommandLine/RunSettingsCommandLineOptionsProviderTests.cs +++ b/test/UnitTests/Microsoft.Testing.Extensions.VSTestBridge.UnitTests/CommandLine/RunSettingsCommandLineOptionsProviderTests.cs @@ -20,7 +20,7 @@ public async Task RunSettingsOption_WhenFileDoesNotExist_IsNotValid() // Arrange const string filePath = "file"; var fileSystem = new Mock(MockBehavior.Strict); - fileSystem.Setup(fs => fs.Exists(It.IsAny())).Returns(false); + fileSystem.Setup(fs => fs.ExistFile(It.IsAny())).Returns(false); var provider = new RunSettingsCommandLineOptionsProvider(new TestExtension(), fileSystem.Object); CommandLineOption option = provider.GetCommandLineOptions().Single(); @@ -39,7 +39,7 @@ public async Task RunSettingsOption_WhenFileCannotBeOpen_IsNotValid() // Arrange const string filePath = "file"; var fileSystem = new Mock(MockBehavior.Strict); - fileSystem.Setup(fs => fs.Exists(filePath)).Returns(true); + fileSystem.Setup(fs => fs.ExistFile(filePath)).Returns(true); fileSystem.Setup(fs => fs.NewFileStream(filePath, FileMode.Open, FileAccess.Read)).Throws(new IOException()); var provider = new RunSettingsCommandLineOptionsProvider(new TestExtension(), fileSystem.Object); @@ -59,7 +59,7 @@ public async Task RunSettingsOption_WhenFileExistsAndCanBeOpen_IsValid() // Arrange const string filePath = "file"; var fileSystem = new Mock(MockBehavior.Strict); - fileSystem.Setup(fs => fs.Exists(filePath)).Returns(true); + fileSystem.Setup(fs => fs.ExistFile(filePath)).Returns(true); fileSystem.Setup(fs => fs.NewFileStream(filePath, FileMode.Open, FileAccess.Read)).Returns(new Mock().Object); var provider = new RunSettingsCommandLineOptionsProvider(new TestExtension(), fileSystem.Object); diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Configuration/ConfigurationManagerTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Configuration/ConfigurationManagerTests.cs index 2465f64839..063e9b5116 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Configuration/ConfigurationManagerTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Configuration/ConfigurationManagerTests.cs @@ -23,7 +23,7 @@ public sealed class ConfigurationManagerTests public async ValueTask GetConfigurationValueFromJson(string jsonFileConfig, string key, string? result) { Mock fileSystem = new(); - fileSystem.Setup(x => x.Exists(It.IsAny())).Returns(true); + fileSystem.Setup(x => x.ExistFile(It.IsAny())).Returns(true); fileSystem.Setup(x => x.NewFileStream(It.IsAny(), FileMode.Open, FileAccess.Read)) .Returns(new MemoryFileStream(Encoding.UTF8.GetBytes(jsonFileConfig))); CurrentTestApplicationModuleInfo testApplicationModuleInfo = new(new SystemEnvironment(), new SystemProcessHandler()); @@ -54,7 +54,7 @@ public async ValueTask GetConfigurationValueFromJson(string jsonFileConfig, stri public async ValueTask InvalidJson_Fail() { Mock fileSystem = new(); - fileSystem.Setup(x => x.Exists(It.IsAny())).Returns(true); + fileSystem.Setup(x => x.ExistFile(It.IsAny())).Returns(true); fileSystem.Setup(x => x.NewFileStream(It.IsAny(), FileMode.Open, FileAccess.Read)).Returns(() => new MemoryFileStream(Encoding.UTF8.GetBytes(string.Empty))); CurrentTestApplicationModuleInfo testApplicationModuleInfo = new(new SystemEnvironment(), new SystemProcessHandler()); ConfigurationManager configurationManager = new(fileSystem.Object, testApplicationModuleInfo); @@ -76,7 +76,7 @@ public async ValueTask GetConfigurationValueFromJsonWithFileLoggerProvider(strin byte[] bytes = Encoding.UTF8.GetBytes(jsonFileConfig); Mock fileSystem = new(); - fileSystem.Setup(x => x.Exists(It.IsAny())).Returns(true); + fileSystem.Setup(x => x.ExistFile(It.IsAny())).Returns(true); fileSystem.Setup(x => x.NewFileStream(It.IsAny(), FileMode.Open, FileAccess.Read)) .Returns(() => new MemoryFileStream(bytes)); diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Logging/FileLoggerTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Logging/FileLoggerTests.cs index 2541881cac..92aaa59645 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Logging/FileLoggerTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Logging/FileLoggerTests.cs @@ -128,7 +128,7 @@ public void FileLogger_NullFileSyncFlush_FileStreamCreationThrows() public void FileLogger_ValidFileName_FileStreamCreatedSuccessfully(bool syncFlush, bool fileExists) { string expectedPath = Path.Combine(LogFolder, FileName); - _mockFileSystem.Setup(x => x.Exists(expectedPath)).Returns(fileExists); + _mockFileSystem.Setup(x => x.ExistFile(expectedPath)).Returns(fileExists); _mockFileStreamFactory .Setup(x => x.Create(It.IsAny(), fileExists ? FileMode.Append : FileMode.CreateNew, FileAccess.Write, FileShare.Read)) .Returns(_mockStream.Object); @@ -156,7 +156,7 @@ public void FileLogger_ValidFileName_FileStreamCreatedSuccessfully(bool syncFlus [DynamicData(nameof(LogTestHelpers.GetLogLevelCombinations), typeof(LogTestHelpers))] public async Task Log_WhenSyncFlush_StreamWriterIsCalledOnlyWhenLogLevelAllowsIt(LogLevel defaultLogLevel, LogLevel currentLogLevel) { - _mockFileSystem.Setup(x => x.Exists(It.IsAny())).Returns(false); + _mockFileSystem.Setup(x => x.ExistFile(It.IsAny())).Returns(false); _mockFileStreamFactory .Setup(x => x.Create(It.IsAny(), FileMode.CreateNew, FileAccess.Write, FileShare.Read)) .Returns(_mockStream.Object); @@ -196,7 +196,7 @@ public async Task Log_WhenSyncFlush_StreamWriterIsCalledOnlyWhenLogLevelAllowsIt [DynamicData(nameof(LogTestHelpers.GetLogLevelCombinations), typeof(LogTestHelpers))] public void Log_WhenAsyncFlush_StreamWriterIsCalledOnlyWhenLogLevelAllowsIt(LogLevel defaultLogLevel, LogLevel currentLogLevel) { - _mockFileSystem.Setup(x => x.Exists(It.IsAny())).Returns(false); + _mockFileSystem.Setup(x => x.ExistFile(It.IsAny())).Returns(false); _mockFileStreamFactory .Setup(x => x.Create(It.IsAny(), FileMode.CreateNew, FileAccess.Write, FileShare.Read)) .Returns(_mockStream.Object); diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Telemetry/TelemetryManagerTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Telemetry/TelemetryManagerTests.cs index 763032a277..fd54131f0a 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Telemetry/TelemetryManagerTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Telemetry/TelemetryManagerTests.cs @@ -169,7 +169,7 @@ public async Task TelemetryManager_SentinelIsWrittenPerUserAndAvoidsShowingNotic // Combination of where LOCALAPPDATA or HOME is, the name of the exe and our file extension. string path = Path.Combine("sentinelDir", "Microsoft", "TestingPlatform", "myExe.testingPlatformFirstTimeUseSentinel"); - fileSystemMock.Verify(f => f.Exists(path), Times.Once); + fileSystemMock.Verify(f => f.ExistFile(path), Times.Once); // Message was written to screen. outputDevice.Verify(c => c.DisplayAsync(It.IsAny(), It.IsAny()), Times.Once); @@ -181,9 +181,9 @@ public async Task TelemetryManager_SentinelIsWrittenPerUserAndAvoidsShowingNotic outputDevice.Invocations.Clear(); fileSystemMock.Invocations.Clear(); - fileSystemMock.Setup(f => f.Exists(path)).Returns(true); + fileSystemMock.Setup(f => f.ExistFile(path)).Returns(true); await telemetryManager.BuildAsync(serviceProvider, loggerFactoryMock.Object, options); - fileSystemMock.Verify(f => f.Exists(path), Times.Once); + fileSystemMock.Verify(f => f.ExistFile(path), Times.Once); // Message is not written to screen. outputDevice.Verify(c => c.DisplayAsync(It.IsAny(), It.IsAny()), Times.Never); @@ -237,7 +237,7 @@ public async Task TelemetryManager_SentinelIsWrittenOnlyWhenUserWouldSeeTheMessa string path = Path.Combine("sentinelDir", "Microsoft", "TestingPlatform", "myExe.testingPlatformFirstTimeUseSentinel"); // We should not check for the sentinel, because we disabled the logo. - fileSystemMock.Verify(f => f.Exists(path), Times.Never); + fileSystemMock.Verify(f => f.ExistFile(path), Times.Never); // Message was not written to screen. outputDevice.Verify(c => c.DisplayAsync(It.IsAny(), It.IsAny()), Times.Never); @@ -252,9 +252,9 @@ public async Task TelemetryManager_SentinelIsWrittenOnlyWhenUserWouldSeeTheMessa // Enable showing the telemetry message. environmentMock.Setup(s => s.GetEnvironmentVariable(EnvironmentVariableConstants.TESTINGPLATFORM_NOBANNER)).Returns("0"); - fileSystemMock.Setup(f => f.Exists(path)).Returns(false); + fileSystemMock.Setup(f => f.ExistFile(path)).Returns(false); await telemetryManager.BuildAsync(serviceProvider, loggerFactoryMock.Object, options); - fileSystemMock.Verify(f => f.Exists(path), Times.Once); + fileSystemMock.Verify(f => f.ExistFile(path), Times.Once); // Message is written to screen. outputDevice.Verify(c => c.DisplayAsync(It.IsAny(), It.IsAny()), Times.Once); From 3f0923ccd2a5e516d5caac48bc1727e230d2d6ee Mon Sep 17 00:00:00 2001 From: Copilot <198982749+Copilot@users.noreply.github.com> Date: Tue, 15 Jul 2025 11:17:39 +0200 Subject: [PATCH 211/541] Obsolete CssIteration, CssProjectStructure, and Description attributes for v3.10 (#5981) Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: Youssef1313 <31348972+Youssef1313@users.noreply.github.com> --- .../Attributes/TestMethod/CssIterationAttribute.cs | 5 +++++ .../Attributes/TestMethod/CssProjectStructureAttribute.cs | 5 +++++ 2 files changed, 10 insertions(+) diff --git a/src/TestFramework/TestFramework/Attributes/TestMethod/CssIterationAttribute.cs b/src/TestFramework/TestFramework/Attributes/TestMethod/CssIterationAttribute.cs index a1c070d4a1..54f0a0d610 100644 --- a/src/TestFramework/TestFramework/Attributes/TestMethod/CssIterationAttribute.cs +++ b/src/TestFramework/TestFramework/Attributes/TestMethod/CssIterationAttribute.cs @@ -7,6 +7,11 @@ namespace Microsoft.VisualStudio.TestTools.UnitTesting; /// CSS Iteration URI. /// [AttributeUsage(AttributeTargets.Method)] +#if NET6_0_OR_GREATER +[Obsolete(FrameworkConstants.PublicTypeObsoleteMessage, DiagnosticId = "MSTESTOBS")] +#else +[Obsolete(FrameworkConstants.PublicTypeObsoleteMessage)] +#endif public sealed class CssIterationAttribute : Attribute { /// diff --git a/src/TestFramework/TestFramework/Attributes/TestMethod/CssProjectStructureAttribute.cs b/src/TestFramework/TestFramework/Attributes/TestMethod/CssProjectStructureAttribute.cs index eb3a354b45..e88074fde4 100644 --- a/src/TestFramework/TestFramework/Attributes/TestMethod/CssProjectStructureAttribute.cs +++ b/src/TestFramework/TestFramework/Attributes/TestMethod/CssProjectStructureAttribute.cs @@ -7,6 +7,11 @@ namespace Microsoft.VisualStudio.TestTools.UnitTesting; /// CSS Project Structure URI. /// [AttributeUsage(AttributeTargets.Method)] +#if NET6_0_OR_GREATER +[Obsolete(FrameworkConstants.PublicTypeObsoleteMessage, DiagnosticId = "MSTESTOBS")] +#else +[Obsolete(FrameworkConstants.PublicTypeObsoleteMessage)] +#endif public sealed class CssProjectStructureAttribute : Attribute { /// From f0f7edc0cc72d7dc1b3364e2961f9b3df095669b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Tue, 15 Jul 2025 12:52:44 +0200 Subject: [PATCH 212/541] Do not create TestResults dir for help and info options (#6020) --- .../Hosts/TestHostBuilder.cs | 21 ++++-- .../HelpInfoTests.cs | 66 +++++++++++++++++++ 2 files changed, 80 insertions(+), 7 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostBuilder.cs b/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostBuilder.cs index a0301d1535..1abd744536 100644 --- a/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostBuilder.cs +++ b/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostBuilder.cs @@ -270,11 +270,18 @@ public async Task BuildAsync( testApplicationCancellationTokenSource.CancelAfter(timeout); } - // At this point we start to build extensions so we need to have all the information complete for the usage, - // here we ensure to override the result directory if user passed the argument --results-directory in command line. - // After this check users can get the result directory using IConfiguration["platformOptions:resultDirectory"] or the - // extension method helper serviceProvider.GetConfiguration() - await configuration.CheckTestResultsDirectoryOverrideAndCreateItAsync(loggingState.FileLoggerProvider).ConfigureAwait(false); + bool isHelpCommand = commandLineHandler.IsHelpInvoked(); + bool isInfoCommand = commandLineHandler.IsInfoInvoked(); + + // Do not create the result directory if the user invoked --help or --info command. + if (!isHelpCommand && !isInfoCommand) + { + // At this point we start to build extensions so we need to have all the information complete for the usage, + // here we ensure to override the result directory if user passed the argument --results-directory in command line. + // After this check users can get the result directory using IConfiguration["platformOptions:resultDirectory"] or the + // extension method helper serviceProvider.GetConfiguration() + await configuration.CheckTestResultsDirectoryOverrideAndCreateItAsync(loggingState.FileLoggerProvider).ConfigureAwait(false); + } // Display banner now because we need capture the output in case of MSBuild integration and we want to forward // to file disc also the banner, so at this point we need to have all services and configuration(result directory) built. @@ -336,7 +343,7 @@ await LogTestHostCreatedAsync( } // If --help is invoked we return - if (commandLineHandler.IsHelpInvoked()) + if (isHelpCommand) { if (pushOnlyProtocol.IsServerMode) { @@ -351,7 +358,7 @@ await LogTestHostCreatedAsync( } // If --info is invoked we return - if (commandLineHandler.IsInfoInvoked()) + if (isInfoCommand) { await commandLineHandler.PrintInfoAsync(proxyOutputDevice, toolsInformation).ConfigureAwait(false); return new InformativeCommandLineTestHost(0, serviceProvider); diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/HelpInfoTests.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/HelpInfoTests.cs index 49ec524d6f..1956c917fc 100644 --- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/HelpInfoTests.cs +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/HelpInfoTests.cs @@ -639,6 +639,72 @@ Default type is 'Full' testHostResult.AssertOutputMatchesLines(wildcardPattern); } + [DynamicData(nameof(TargetFrameworks.AllForDynamicData), typeof(TargetFrameworks))] + [TestMethod] + public async Task Help_DoesNotCreateTestResultsFolder(string tfm) + { + var testHost = TestInfrastructure.TestHost.LocateFrom(AssetFixture.NoExtensionTargetAssetPath, TestAssetFixture.NoExtensionAssetName, tfm); + string testHostDirectory = testHost.DirectoryName; + string testResultsPath = Path.Combine(testHostDirectory, "TestResults"); + + // Ensure TestResults folder doesn't exist before running the test + if (Directory.Exists(testResultsPath)) + { + Directory.Delete(testResultsPath, recursive: true); + } + + TestHostResult testHostResult = await testHost.ExecuteAsync("--help"); + + testHostResult.AssertExitCodeIs(ExitCodes.Success); + + // Verify that TestResults folder was not created + Assert.IsFalse(Directory.Exists(testResultsPath), "TestResults folder should not be created for help command"); + } + + [DynamicData(nameof(TargetFrameworks.AllForDynamicData), typeof(TargetFrameworks))] + [TestMethod] + public async Task HelpShortName_DoesNotCreateTestResultsFolder(string tfm) + { + var testHost = TestInfrastructure.TestHost.LocateFrom(AssetFixture.NoExtensionTargetAssetPath, TestAssetFixture.NoExtensionAssetName, tfm); + string testHostDirectory = testHost.DirectoryName; + string testResultsPath = Path.Combine(testHostDirectory, "TestResults"); + + // Ensure TestResults folder doesn't exist before running the test + if (Directory.Exists(testResultsPath)) + { + Directory.Delete(testResultsPath, recursive: true); + } + + TestHostResult testHostResult = await testHost.ExecuteAsync("--?"); + + testHostResult.AssertExitCodeIs(ExitCodes.Success); + + // Verify that TestResults folder was not created + Assert.IsFalse(Directory.Exists(testResultsPath), "TestResults folder should not be created for help short name command"); + } + + [DynamicData(nameof(TargetFrameworks.AllForDynamicData), typeof(TargetFrameworks))] + [TestMethod] + public async Task Info_DoesNotCreateTestResultsFolder(string tfm) + { + var testHost = TestInfrastructure.TestHost.LocateFrom(AssetFixture.NoExtensionTargetAssetPath, TestAssetFixture.NoExtensionAssetName, tfm); + string testHostDirectory = testHost.DirectoryName; + string testResultsPath = Path.Combine(testHostDirectory, "TestResults"); + + // Ensure TestResults folder doesn't exist before running the test + if (Directory.Exists(testResultsPath)) + { + Directory.Delete(testResultsPath, recursive: true); + } + + TestHostResult testHostResult = await testHost.ExecuteAsync("--info"); + + testHostResult.AssertExitCodeIs(ExitCodes.Success); + + // Verify that TestResults folder was not created + Assert.IsFalse(Directory.Exists(testResultsPath), "TestResults folder should not be created for info command"); + } + public sealed class TestAssetFixture() : TestAssetFixtureBase(AcceptanceFixture.NuGetGlobalPackagesFolder) { public const string AllExtensionsAssetName = "AllExtensionsInfoTest"; From 1d18d423fd74daf2e2e1a6ddbc0053587c0c4fa8 Mon Sep 17 00:00:00 2001 From: dotnet bot Date: Tue, 15 Jul 2025 13:10:36 +0200 Subject: [PATCH 213/541] Localized file check-in by OneLocBuild Task: Build definition ID 1218: Build ID 2750351 --- .../Resources/xlf/PlatformResources.cs.xlf | 4 ++-- .../Resources/xlf/PlatformResources.de.xlf | 4 ++-- .../Resources/xlf/PlatformResources.fr.xlf | 4 ++-- .../Resources/xlf/PlatformResources.it.xlf | 4 ++-- .../Resources/xlf/PlatformResources.ja.xlf | 4 ++-- .../Resources/xlf/PlatformResources.pl.xlf | 4 ++-- .../Resources/xlf/PlatformResources.ru.xlf | 4 ++-- .../Resources/xlf/PlatformResources.tr.xlf | 4 ++-- .../Resources/xlf/PlatformResources.zh-Hans.xlf | 4 ++-- 9 files changed, 18 insertions(+), 18 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.cs.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.cs.xlf index 7574cd18b9..e018539d41 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.cs.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.cs.xlf @@ -433,7 +433,7 @@ Passing both '--treenode-filter' and '--filter-uid' is unsupported. - Passing both '--treenode-filter' and '--filter-uid' is unsupported. + Předávání možností --treenode-filter a --filter-uid není podporováno. @@ -540,7 +540,7 @@ Dostupné hodnoty jsou Trace, Debug, Information, Warning, Error a Critical. Provides a list of test node UIDs to filter by. - Provides a list of test node UIDs to filter by. + Poskytuje seznam identifikátorů UID testovacích uzlů, podle kterých lze filtrovat. diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.de.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.de.xlf index 4517511eff..c644fbab7b 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.de.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.de.xlf @@ -433,7 +433,7 @@ Passing both '--treenode-filter' and '--filter-uid' is unsupported. - Passing both '--treenode-filter' and '--filter-uid' is unsupported. + Das gleichzeitige Übergeben von „--treenode-filter“ und „--filter-uid“ wird nicht unterstützt. @@ -540,7 +540,7 @@ Die verfügbaren Werte sind "Trace", "Debug", "Information", "Warning", "Error" Provides a list of test node UIDs to filter by. - Provides a list of test node UIDs to filter by. + Stellt eine Liste der UIDs von Testknoten bereit, nach denen gefiltert werden kann. diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.fr.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.fr.xlf index 5a705374cd..cb4438020f 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.fr.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.fr.xlf @@ -433,7 +433,7 @@ Passing both '--treenode-filter' and '--filter-uid' is unsupported. - Passing both '--treenode-filter' and '--filter-uid' is unsupported. + Vous ne pouvez pas passer à la fois « --treenode-filter » et « --filter-uid ». Cette action n’est pas prise en charge. @@ -540,7 +540,7 @@ Les valeurs disponibles sont « Trace », « Debug », « Information », Provides a list of test node UIDs to filter by. - Provides a list of test node UIDs to filter by. + Fournit la liste des IUD de nœud de test à filtrer. diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.it.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.it.xlf index b08a309ae3..11f76ac113 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.it.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.it.xlf @@ -433,7 +433,7 @@ Passing both '--treenode-filter' and '--filter-uid' is unsupported. - Passing both '--treenode-filter' and '--filter-uid' is unsupported. + Il passaggio di '--treenode-filter' e '--filter-uid' non è supportato. @@ -540,7 +540,7 @@ I valori disponibili sono 'Trace', 'Debug', 'Information', 'Warning', 'Error' e Provides a list of test node UIDs to filter by. - Provides a list of test node UIDs to filter by. + Fornisce un elenco di UID dei nodi di prova per il filtraggio. diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ja.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ja.xlf index 5a06691f95..6c865ecf29 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ja.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ja.xlf @@ -433,7 +433,7 @@ Passing both '--treenode-filter' and '--filter-uid' is unsupported. - Passing both '--treenode-filter' and '--filter-uid' is unsupported. + '--treenode-filter' と '--filter-uid' の両方を渡すことはサポートされていません。 @@ -541,7 +541,7 @@ The available values are 'Trace', 'Debug', 'Information', 'Warning', 'Error', an Provides a list of test node UIDs to filter by. - Provides a list of test node UIDs to filter by. + フィルター対象のテスト ノード UID のリストを提供します。 diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pl.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pl.xlf index eaafb3599b..2d3ef86afc 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pl.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pl.xlf @@ -433,7 +433,7 @@ Passing both '--treenode-filter' and '--filter-uid' is unsupported. - Passing both '--treenode-filter' and '--filter-uid' is unsupported. + Przekazywanie obu parametrów „--treenode-filter” i „--filter-uid” jest nieobsługiwane. @@ -540,7 +540,7 @@ Dostępne wartości to „Trace”, „Debug”, „Information”, „Warning Provides a list of test node UIDs to filter by. - Provides a list of test node UIDs to filter by. + Zawiera listę identyfikatorów UID węzła testowego do filtrowania. diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ru.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ru.xlf index 5567e817a8..f5fc475df9 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ru.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ru.xlf @@ -433,7 +433,7 @@ Passing both '--treenode-filter' and '--filter-uid' is unsupported. - Passing both '--treenode-filter' and '--filter-uid' is unsupported. + Передача одновременно "--treenode-filter" и "--filter-uid" не поддерживается. @@ -540,7 +540,7 @@ The available values are 'Trace', 'Debug', 'Information', 'Warning', 'Error', an Provides a list of test node UIDs to filter by. - Provides a list of test node UIDs to filter by. + Предоставляет список UID тестовых узлов для фильтрации. diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.tr.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.tr.xlf index 39c2e84d16..ec4fe257a8 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.tr.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.tr.xlf @@ -433,7 +433,7 @@ Passing both '--treenode-filter' and '--filter-uid' is unsupported. - Passing both '--treenode-filter' and '--filter-uid' is unsupported. + Hem ‘--treenode-filter’ hem de ‘--filter-uid’ parametrelerinin birlikte kullanılması desteklenmemektedir. @@ -540,7 +540,7 @@ Kullanılabilir değerler: 'Trace', 'Debug', 'Information', 'Warning', 'Error' v Provides a list of test node UIDs to filter by. - Provides a list of test node UIDs to filter by. + Filtrelemek için test düğümü UID'lerinin bir listesini sağlar. diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hans.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hans.xlf index b3a323045d..80021f473a 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hans.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hans.xlf @@ -433,7 +433,7 @@ Passing both '--treenode-filter' and '--filter-uid' is unsupported. - Passing both '--treenode-filter' and '--filter-uid' is unsupported. + 不支持同时传递“--treenode-filter”和“--filter-uid”。 @@ -540,7 +540,7 @@ The available values are 'Trace', 'Debug', 'Information', 'Warning', 'Error', an Provides a list of test node UIDs to filter by. - Provides a list of test node UIDs to filter by. + 提供用作筛选依据的测试节点 UID 列表。 From 46299087736e23f4d9dbebb0b99001cd6ed24a27 Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Tue, 15 Jul 2025 21:13:50 +1000 Subject: [PATCH 214/541] remove Uid from DiscoveredTests (#6019) --- .../OutputDevice/Terminal/TerminalTestReporter.cs | 9 ++++----- .../OutputDevice/Terminal/TestProgressState.cs | 2 +- .../OutputDevice/TerminalOutputDevice.cs | 3 +-- 3 files changed, 6 insertions(+), 8 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporter.cs b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporter.cs index a24a154e01..b00a8fe4b7 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporter.cs +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporter.cs @@ -865,8 +865,7 @@ internal void TestDiscovered( string assembly, string? targetFramework, string? architecture, - string displayName, - string uid) + string displayName) { TestProgressState asm = _assemblies[$"{assembly}|{targetFramework}|{architecture}"]; @@ -878,7 +877,7 @@ internal void TestDiscovered( asm.TotalTests++; } - asm.DiscoveredTests.Add(new(displayName, uid)); + asm.DiscoveredTestDisplayNames.Add(displayName); _terminalWithProgress.UpdateWorker(asm.SlotIndex); } @@ -896,13 +895,13 @@ public void AppendTestDiscoverySummary(ITerminal terminal) { if (_options.ShowAssembly) { - terminal.Append(string.Format(CultureInfo.CurrentCulture, PlatformResources.DiscoveredTestsInAssembly, assembly.DiscoveredTests.Count)); + terminal.Append(string.Format(CultureInfo.CurrentCulture, PlatformResources.DiscoveredTestsInAssembly, assembly.DiscoveredTestDisplayNames.Count)); terminal.Append(" - "); AppendAssemblyLinkTargetFrameworkAndArchitecture(terminal, assembly.Assembly, assembly.TargetFramework, assembly.Architecture); terminal.AppendLine(); } - foreach ((string displayName, string? uid) in assembly.DiscoveredTests) + foreach (string displayName in assembly.DiscoveredTestDisplayNames) { terminal.Append(SingleIndentation); terminal.AppendLine(displayName); diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TestProgressState.cs b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TestProgressState.cs index 66c4dfe712..5cccaafa99 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TestProgressState.cs +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TestProgressState.cs @@ -45,7 +45,7 @@ public TestProgressState(long id, string assembly, string? targetFramework, stri public long Version { get; internal set; } - public List<(string DisplayName, string UID)> DiscoveredTests { get; internal set; } = []; + public List DiscoveredTestDisplayNames { get; internal set; } = []; internal void AddError(string text) => Messages.Add(new ErrorMessage(text)); diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/TerminalOutputDevice.cs b/src/Platform/Microsoft.Testing.Platform/OutputDevice/TerminalOutputDevice.cs index 3c02b2b997..3509eb9e50 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/TerminalOutputDevice.cs +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/TerminalOutputDevice.cs @@ -533,8 +533,7 @@ public Task ConsumeAsync(IDataProducer dataProducer, IData value, CancellationTo _assemblyName, _targetFramework, _shortArchitecture, - testNodeStateChanged.TestNode.DisplayName, - testNodeStateChanged.TestNode.Uid); + testNodeStateChanged.TestNode.DisplayName); break; } From dd9d091ca4ed9f4b89b9f3434550833cd5f63c94 Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Tue, 15 Jul 2025 22:07:22 +1000 Subject: [PATCH 215/541] remove predicate from RetryHelper (#6027) --- .../Helpers/TaskExtensionsTests.cs | 4 ++-- .../Microsoft.Testing.TestInfrastructure/RetryHelper.cs | 8 ++++---- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Helpers/TaskExtensionsTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Helpers/TaskExtensionsTests.cs index 1a020ae938..6712aef3f0 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Helpers/TaskExtensionsTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Helpers/TaskExtensionsTests.cs @@ -84,7 +84,7 @@ await Assert.ThrowsAsync(async () waitException.WaitOne(); await Task.Delay(TimeSpan.FromSeconds(4)); - }, 3, TimeSpan.FromSeconds(3), _ => true); + }, 3, TimeSpan.FromSeconds(3)); [TestMethod] public async Task CancellationAsyncWithReturnValue_ObserveException_Succeeds() @@ -111,7 +111,7 @@ await Assert.ThrowsAsync(async () waitException.WaitOne(); await Task.Delay(TimeSpan.FromSeconds(4)); - }, 3, TimeSpan.FromSeconds(3), _ => true); + }, 3, TimeSpan.FromSeconds(3)); private static async Task DoSomething() { diff --git a/test/Utilities/Microsoft.Testing.TestInfrastructure/RetryHelper.cs b/test/Utilities/Microsoft.Testing.TestInfrastructure/RetryHelper.cs index a2adaf6262..821e5f5b9a 100644 --- a/test/Utilities/Microsoft.Testing.TestInfrastructure/RetryHelper.cs +++ b/test/Utilities/Microsoft.Testing.TestInfrastructure/RetryHelper.cs @@ -7,13 +7,13 @@ namespace Microsoft.Testing.TestInfrastructure; public class RetryHelper { - public static async Task RetryAsync(Func action, uint times, TimeSpan every, Func? predicate = null) - => await Policy.Handle(exception => predicate is null || predicate(exception)) + public static async Task RetryAsync(Func action, uint times, TimeSpan every) + => await Policy.Handle() .WaitAndRetryAsync((int)times, _ => every) .ExecuteAsync(action); - public static async Task RetryAsync(Func> action, uint times, TimeSpan every, Func? predicate = null) - => await Policy.Handle(exception => predicate is null || predicate(exception)) + public static async Task RetryAsync(Func> action, uint times, TimeSpan every) + => await Policy.Handle() .WaitAndRetryAsync((int)times, _ => every) .ExecuteAsync(action); } From 4cd865fc87733bd8a7de8d8e09c46d61b651f94c Mon Sep 17 00:00:00 2001 From: Copilot <198982749+Copilot@users.noreply.github.com> Date: Tue, 15 Jul 2025 14:22:49 +0200 Subject: [PATCH 216/541] Add missing tests for Assert.DoesNotContain string method overloads (#6021) Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: Evangelink <11340282+Evangelink@users.noreply.github.com> --- .../Assertions/AssertTests.Contains.cs | 136 ++++++++++++++++++ 1 file changed, 136 insertions(+) diff --git a/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.Contains.cs b/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.Contains.cs index a652e9aa40..ea9da826ea 100644 --- a/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.Contains.cs +++ b/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.Contains.cs @@ -591,6 +591,142 @@ public void DoesNotContain_StringVersion_SubstringPresent_ThrowsException() action.Should().Throw().WithMessage("*brown*"); } + /// + /// Tests the string DoesNotContain overload with message and parameters when substring is not present. + /// This test ensures the method overload works correctly and prevents regression of stackoverflow bug. + /// + public void DoesNotContain_StringWithMessageAndParameters_SubstringNotPresent_DoesNotThrow() + { + // Arrange + string value = "The quick brown fox"; + string substring = "lazy"; + + // Act + Action action = () => Assert.DoesNotContain(substring, value, "Custom message: {0}", "test parameter"); + + // Assert + action.Should().NotThrow(); + } + + /// + /// Tests the string DoesNotContain overload with message and parameters when substring is present. + /// This test ensures the method overload works correctly and prevents regression of stackoverflow bug. + /// Expects an exception. + /// + public void DoesNotContain_StringWithMessageAndParameters_SubstringPresent_ThrowsException() + { + // Arrange + string value = "The quick brown fox"; + string substring = "brown"; + + // Act + Action action = () => Assert.DoesNotContain(substring, value, "Found unexpected substring: {0}", substring); + + // Assert + action.Should().Throw().WithMessage("*Found unexpected substring: brown*"); + } + + /// + /// Tests the string DoesNotContain overload with StringComparison and message when substring is not present. + /// This test ensures the method overload works correctly and prevents regression of stackoverflow bug. + /// + public void DoesNotContain_StringWithComparisonAndMessage_SubstringNotPresent_DoesNotThrow() + { + // Arrange + string value = "The quick brown fox"; + string substring = "LAZY"; + + // Act + Action action = () => Assert.DoesNotContain(substring, value, StringComparison.OrdinalIgnoreCase, "Should not contain lazy"); + + // Assert + action.Should().NotThrow(); + } + + /// + /// Tests the string DoesNotContain overload with StringComparison and message when substring is present. + /// This test ensures the method overload works correctly and prevents regression of stackoverflow bug. + /// Expects an exception. + /// + public void DoesNotContain_StringWithComparisonAndMessage_SubstringPresent_ThrowsException() + { + // Arrange + string value = "The quick brown fox"; + string substring = "BROWN"; + + // Act + Action action = () => Assert.DoesNotContain(substring, value, StringComparison.OrdinalIgnoreCase, "Found unexpected substring"); + + // Assert + action.Should().Throw().WithMessage("*Found unexpected substring*"); + } + + /// + /// Tests the simplest string DoesNotContain overload when substring is not present. + /// + public void DoesNotContain_StringSimpleOverload_SubstringNotPresent_DoesNotThrow() + { + // Arrange + string value = "The quick brown fox"; + string substring = "lazy"; + + // Act + Action action = () => Assert.DoesNotContain(substring, value); + + // Assert + action.Should().NotThrow(); + } + + /// + /// Tests the simplest string DoesNotContain overload when substring is present. + /// Expects an exception. + /// + public void DoesNotContain_StringSimpleOverload_SubstringPresent_ThrowsException() + { + // Arrange + string value = "The quick brown fox"; + string substring = "brown"; + + // Act + Action action = () => Assert.DoesNotContain(substring, value); + + // Assert + action.Should().Throw().WithMessage("*brown*"); + } + + /// + /// Tests the string DoesNotContain overload with message only when substring is not present. + /// + public void DoesNotContain_StringWithMessageOnly_SubstringNotPresent_DoesNotThrow() + { + // Arrange + string value = "The quick brown fox"; + string substring = "lazy"; + + // Act + Action action = () => Assert.DoesNotContain(substring, value, "Should not contain lazy"); + + // Assert + action.Should().NotThrow(); + } + + /// + /// Tests the string DoesNotContain overload with message only when substring is present. + /// Expects an exception. + /// + public void DoesNotContain_StringWithMessageOnly_SubstringPresent_ThrowsException() + { + // Arrange + string value = "The quick brown fox"; + string substring = "brown"; + + // Act + Action action = () => Assert.DoesNotContain(substring, value, "Found unexpected substring"); + + // Assert + action.Should().Throw().WithMessage("*Found unexpected substring*"); + } + private static bool IsEven(int x) => x % 2 == 0; #endregion From fdb65e26b14b3f7f44956591fb37d022c575db51 Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Tue, 15 Jul 2025 22:48:39 +1000 Subject: [PATCH 217/541] Dont generate documentation for tests and samples (#5441) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Amaury Levé --- samples/FxExtensibility/FxExtensibility.csproj | 2 ++ samples/Playground/Playground.csproj | 3 ++- samples/public/Directory.Build.props | 2 ++ test/Directory.Build.props | 2 ++ 4 files changed, 8 insertions(+), 1 deletion(-) diff --git a/samples/FxExtensibility/FxExtensibility.csproj b/samples/FxExtensibility/FxExtensibility.csproj index 152e1d9d23..e8a0b1e442 100644 --- a/samples/FxExtensibility/FxExtensibility.csproj +++ b/samples/FxExtensibility/FxExtensibility.csproj @@ -11,6 +11,8 @@ $(DefineConstants);TRACE prompt 4 + false + $(NoWarn);SA0001;EnableGenerateDocumentationFile diff --git a/samples/Playground/Playground.csproj b/samples/Playground/Playground.csproj index b8570b8348..2b8a942126 100644 --- a/samples/Playground/Playground.csproj +++ b/samples/Playground/Playground.csproj @@ -5,9 +5,10 @@ net9.0 enable false - $(NoWarn);NETSDK1023 + $(NoWarn);NETSDK1023;SA0001;EnableGenerateDocumentationFile true + false diff --git a/samples/public/Directory.Build.props b/samples/public/Directory.Build.props index 94c524b6b1..fe854da07b 100644 --- a/samples/public/Directory.Build.props +++ b/samples/public/Directory.Build.props @@ -8,6 +8,8 @@ 1.50.0 1.7.0 17.13.0 + false + $(NoWarn);SA0001;EnableGenerateDocumentationFile diff --git a/test/Directory.Build.props b/test/Directory.Build.props index 7b462d3b5c..09674c87fb 100644 --- a/test/Directory.Build.props +++ b/test/Directory.Build.props @@ -16,6 +16,8 @@ $(DefineConstants);ENABLE_CODECOVERAGE false + false + $(NoWarn);SA0001;EnableGenerateDocumentationFile From 14c31d14e08b25191f434a328ea5c27612206b33 Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Wed, 16 Jul 2025 00:38:16 +1000 Subject: [PATCH 218/541] update Polyfill and simplify SHA256 usage (#6029) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Amaury Levé Co-authored-by: Amaury Levé --- Directory.Packages.props | 2 +- .../TrxReportEngine.cs | 3 +-- .../Helpers/Sha256Hasher.cs | 19 +++---------------- 3 files changed, 5 insertions(+), 19 deletions(-) diff --git a/Directory.Packages.props b/Directory.Packages.props index 36a006caaf..1be90580da 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -54,7 +54,7 @@ - + diff --git a/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxReportEngine.cs b/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxReportEngine.cs index 191dfdb278..c9e81e9b13 100644 --- a/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxReportEngine.cs +++ b/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxReportEngine.cs @@ -736,8 +736,7 @@ private static Guid GuidFromString(string data) ArrayPool.Shared.Return(dataBytes); } #else - var sha256 = SHA256.Create(); - byte[] hash = sha256.ComputeHash(Encoding.Unicode.GetBytes(data)); + byte[] hash = SHA256.HashData(Encoding.Unicode.GetBytes(data)); byte[] bytes = new byte[16]; Array.Copy(hash, bytes, 16); return new Guid(bytes); diff --git a/src/Platform/Microsoft.Testing.Platform/Helpers/Sha256Hasher.cs b/src/Platform/Microsoft.Testing.Platform/Helpers/Sha256Hasher.cs index 99f5c70729..51df458a4c 100644 --- a/src/Platform/Microsoft.Testing.Platform/Helpers/Sha256Hasher.cs +++ b/src/Platform/Microsoft.Testing.Platform/Helpers/Sha256Hasher.cs @@ -9,23 +9,10 @@ namespace Microsoft.Testing.Platform.Helpers; [ExcludeFromCodeCoverage] internal static class Sha256Hasher { - private static string Hash(string text) + public static string HashWithNormalizedCasing(string text) { - byte[] bytes = Encoding.UTF8.GetBytes(text); -#if NETCOREAPP + byte[] bytes = Encoding.UTF8.GetBytes(text.ToUpperInvariant()); byte[] hash = SHA256.HashData(bytes); -#else - using var hasher = SHA256.Create(); - byte[] hash = hasher.ComputeHash(bytes); -#endif - -#if NETCOREAPP - return Convert.ToHexString(hash).ToLowerInvariant(); -#else - return BitConverter.ToString(hash).Replace("-", string.Empty).ToLowerInvariant(); -#endif + return Convert.ToHexStringLower(hash); } - - public static string HashWithNormalizedCasing(string text) - => Hash(text.ToUpperInvariant()); } From c5110ced5c1fba781b84b902427e9a4e9fc21add Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Tue, 15 Jul 2025 17:49:31 +0200 Subject: [PATCH 219/541] Fix RootFinder to handle git worktrees (#6034) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Jakub Jareš --- samples/Playground/Playground.csproj | 4 ++ .../TestingPlatformClientFactory.cs | 23 +-------- .../AzureDevOpsReporter.cs | 1 + ...esting.Extensions.AzureDevOpsReport.csproj | 4 ++ .../RootFinder.cs | 34 -------------- ...icrosoft.Testing.TestInfrastructure.csproj | 1 + .../RootFinder.cs | 47 +++++++++++++++---- 7 files changed, 49 insertions(+), 65 deletions(-) delete mode 100644 src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/RootFinder.cs diff --git a/samples/Playground/Playground.csproj b/samples/Playground/Playground.csproj index 2b8a942126..ba8afed52d 100644 --- a/samples/Playground/Playground.csproj +++ b/samples/Playground/Playground.csproj @@ -15,6 +15,10 @@ + + + + diff --git a/samples/Playground/ServerMode/TestingPlatformClientFactory.cs b/samples/Playground/ServerMode/TestingPlatformClientFactory.cs index 44491c2798..5fe8dc28d6 100644 --- a/samples/Playground/ServerMode/TestingPlatformClientFactory.cs +++ b/samples/Playground/ServerMode/TestingPlatformClientFactory.cs @@ -5,6 +5,7 @@ using System.Net.Sockets; using Microsoft.Testing.Platform.ServerMode.IntegrationTests.Messages.V100; +using Microsoft.Testing.TestInfrastructure; namespace MSTest.Acceptance.IntegrationTests.Messages.V100; @@ -382,25 +383,3 @@ public static class WellKnownEnvironmentVariables "TESTINGPLATFORM_CONSOLEOUTPUTDEVICE_SKIP_BANNER" ]; } - -public static class RootFinder -{ - public static string Find() - { - string path = AppContext.BaseDirectory; - string dir = path; - while (Directory.GetDirectoryRoot(dir) != dir) - { - if (Directory.Exists(Path.Combine(dir, ".git"))) - { - return dir; - } - else - { - dir = Directory.GetParent(dir)!.ToString(); - } - } - - throw new InvalidOperationException($"Could not find solution root, .git not found in {path} or any parent directory."); - } -} diff --git a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/AzureDevOpsReporter.cs b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/AzureDevOpsReporter.cs index 08d2667545..5d9c0f65b3 100644 --- a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/AzureDevOpsReporter.cs +++ b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/AzureDevOpsReporter.cs @@ -11,6 +11,7 @@ using Microsoft.Testing.Platform.Helpers; using Microsoft.Testing.Platform.Logging; using Microsoft.Testing.Platform.OutputDevice; +using Microsoft.Testing.TestInfrastructure; namespace Microsoft.Testing.Extensions.AzureDevOpsReport; diff --git a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Microsoft.Testing.Extensions.AzureDevOpsReport.csproj b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Microsoft.Testing.Extensions.AzureDevOpsReport.csproj index 03f70cd149..cf9962e410 100644 --- a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Microsoft.Testing.Extensions.AzureDevOpsReport.csproj +++ b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Microsoft.Testing.Extensions.AzureDevOpsReport.csproj @@ -39,6 +39,10 @@ This package extends Microsoft Testing Platform to provide a Azure DevOps report + + + + diff --git a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/RootFinder.cs b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/RootFinder.cs deleted file mode 100644 index aa4cf86d09..0000000000 --- a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/RootFinder.cs +++ /dev/null @@ -1,34 +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. - -namespace Microsoft.Testing.Extensions.AzureDevOpsReport; - -internal static class RootFinder -{ - private static string? s_root; - - public static string Find() - { - if (s_root != null) - { - return s_root; - } - - string path = AppContext.BaseDirectory; - string dir = path; - while (Directory.GetDirectoryRoot(dir) != dir) - { - if (Directory.Exists(Path.Combine(dir, ".git"))) - { - s_root = dir + Path.DirectorySeparatorChar; - return dir + Path.DirectorySeparatorChar; - } - else - { - dir = Directory.GetParent(dir)!.ToString(); - } - } - - throw new InvalidOperationException($"Could not find solution root, .git not found in {path} or any parent directory."); - } -} diff --git a/test/Utilities/Microsoft.Testing.TestInfrastructure/Microsoft.Testing.TestInfrastructure.csproj b/test/Utilities/Microsoft.Testing.TestInfrastructure/Microsoft.Testing.TestInfrastructure.csproj index 4fa39e0f86..5533e96445 100644 --- a/test/Utilities/Microsoft.Testing.TestInfrastructure/Microsoft.Testing.TestInfrastructure.csproj +++ b/test/Utilities/Microsoft.Testing.TestInfrastructure/Microsoft.Testing.TestInfrastructure.csproj @@ -4,6 +4,7 @@ $(MicrosoftTestingTargetFrameworks);netstandard2.0 enable $(DefineConstants);SKIP_INTERMEDIATE_TARGET_FRAMEWORKS + $(DefineConstants);ROOT_FINDER_PUBLIC diff --git a/test/Utilities/Microsoft.Testing.TestInfrastructure/RootFinder.cs b/test/Utilities/Microsoft.Testing.TestInfrastructure/RootFinder.cs index 32f01c4489..404f930f6a 100644 --- a/test/Utilities/Microsoft.Testing.TestInfrastructure/RootFinder.cs +++ b/test/Utilities/Microsoft.Testing.TestInfrastructure/RootFinder.cs @@ -3,22 +3,51 @@ namespace Microsoft.Testing.TestInfrastructure; -public static class RootFinder +/// +/// Provides functionality to locate the root directory of a Git repository. +/// +/// The class is used to find the root directory of a Git repository by +/// searching for a ".git" directory or file starting from the application's base directory and moving up the directory +/// hierarchy. This is useful for applications that need to determine the root of a project or repository. +#if ROOT_FINDER_PUBLIC +public +#else +internal +#endif + static class RootFinder { + private static string? s_root; + + /// + /// Finds the root directory of a Git repository starting from the application's base directory. + /// + /// This method searches for a ".git" directory or file in the application's base directory and + /// its parent directories. If a Git repository is found, the path to its root directory is returned. If no Git + /// repository is found, an is thrown. + /// The path to the root directory of the Git repository, ending with a directory separator character. + /// Thrown if a Git repository is not found in the application's base directory or any of its parent directories. public static string Find() { + if (s_root != null) + { + return s_root; + } + string path = AppContext.BaseDirectory; - string dir = path; - while (Directory.GetDirectoryRoot(dir) != dir) + string currentDirectory = path; + string rootDriveDirectory = Directory.GetDirectoryRoot(currentDirectory); + while (rootDriveDirectory != currentDirectory) { - if (Directory.Exists(Path.Combine(dir, ".git"))) - { - return dir; - } - else + string gitPath = Path.Combine(currentDirectory, ".git"); + + // When working with git worktrees, the .git is a file not a folder + if (Directory.Exists(gitPath) || File.Exists(gitPath)) { - dir = Directory.GetParent(dir)!.ToString(); + s_root = currentDirectory + Path.DirectorySeparatorChar; + return s_root; } + + currentDirectory = Directory.GetParent(currentDirectory)!.ToString(); } throw new InvalidOperationException($"Could not find solution root, .git not found in {path} or any parent directory."); From 15fe99f052b4627c349bb32ae0b427f6ea557fdd Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Wed, 16 Jul 2025 02:12:04 +1000 Subject: [PATCH 220/541] simplify TrxCompareTool using an inner type instead of tuples (#6024) --- .../TrxCompareTool.cs | 28 ++++++++++--------- 1 file changed, 15 insertions(+), 13 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxCompareTool.cs b/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxCompareTool.cs index af1bddf91f..43e967f035 100644 --- a/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxCompareTool.cs +++ b/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxCompareTool.cs @@ -12,6 +12,8 @@ namespace Microsoft.Testing.Extensions.TrxReport.Abstractions; internal sealed class TrxCompareTool : ITool, IOutputDeviceDataProducer { + private record struct Trx(string TestName, string Outcome, string Storage); + public const string ToolName = "ms-trxcompare"; private readonly ICommandLineOptions _commandLineOptions; private readonly IExtension _extension; @@ -55,9 +57,9 @@ public async Task RunAsync() XNamespace trxNamespace = "http://microsoft.com/schemas/VisualStudio/TeamTest/2010"; - List<(string TestName, string Outcome, string Storage)> baseLineResults = []; + List baseLineResults = []; List baseLineIssues = []; - List<(string TestName, string Outcome, string Storage)> comparedResults = []; + List comparedResults = []; List comparedIssues = []; await _task.WhenAll( CollectEntriesAndErrorsAsync(baselineFilePaths[0], trxNamespace, baseLineResults, baseLineIssues), @@ -81,22 +83,22 @@ await _task.WhenAll( } private static bool AreMatchingTrxFiles( - List<(string TestName, string Outcome, string Storage)> baseLineResults, - List<(string TestName, string Outcome, string Storage)> comparedResults, + List baseLineResults, + List comparedResults, StringBuilder outputBuilder) { bool checkFailed = false; outputBuilder.AppendLine("--- Comparing TRX files ---"); - IEnumerable<((string TestName, string Outcome, string Storage), string Source)> trxEntries = + IEnumerable<(Trx, string Source)> trxEntries = baseLineResults.Select(tuple => (tuple, "baseline")) .Concat(comparedResults.Select(tuple => (tuple, "other"))) .OrderBy(x => x.tuple.TestName); - foreach (((string TestName, string Outcome, string Storage) sourceTrx, string entrySource) in trxEntries) + foreach ((Trx sourceTrx, string entrySource) in trxEntries) { string otherSource = entrySource == "baseline" ? "other" : "baseline"; - IEnumerable<(string MatchingTestName, string MatchingOutcome, string MatchingStorage)> matchingEntries = + IEnumerable matchingEntries = entrySource == "baseline" ? comparedResults.Where(x => x.TestName == sourceTrx.TestName) : baseLineResults.Where(x => x.TestName == sourceTrx.TestName); @@ -118,13 +120,13 @@ private static bool AreMatchingTrxFiles( continue; } - (string otherTestName, string otherOutcome, string otherStorage) = matchingEntries.First(); - if (sourceTrx.Outcome != otherOutcome) + Trx otherTrx = matchingEntries.First(); + if (sourceTrx.Outcome != otherTrx.Outcome) { checkFailed = true; outputBuilder.AppendLine( CultureInfo.InvariantCulture, - $" - Test '{sourceTrx.TestName}' has a different outcome. Got '{otherOutcome}', expected '{sourceTrx.Outcome}'"); + $" - Test '{sourceTrx.TestName}' has a different outcome. Got '{otherTrx.Outcome}', expected '{sourceTrx.Outcome}'"); } } @@ -142,7 +144,7 @@ private static bool AreMatchingTrxFiles( } private static void AppendResultsAndIssues(string category, string filePath, - List<(string TestName, string Outcome, string Storage)> results, List issues, StringBuilder outputBuilder) + List results, List issues, StringBuilder outputBuilder) { outputBuilder.AppendLine(CultureInfo.InvariantCulture, $"--- {category} ---"); outputBuilder.AppendLine(CultureInfo.InvariantCulture, $"File '{filePath}'"); @@ -175,7 +177,7 @@ private static void AppendResultsAndIssues(string category, string filePath, outputBuilder.AppendLine(); } - private static async Task CollectEntriesAndErrorsAsync(string trxFile, XNamespace ns, List<(string TestName, string Outcome, string Storage)> results, List issues) + private static async Task CollectEntriesAndErrorsAsync(string trxFile, XNamespace ns, List results, List issues) { using FileStream stream = File.OpenRead(trxFile); XElement trxTestRun = await XElement.LoadAsync(stream, LoadOptions.None, CancellationToken.None).ConfigureAwait(false); @@ -239,7 +241,7 @@ private static async Task CollectEntriesAndErrorsAsync(string trxFile, XNamespac continue; } - results.Add((testDefinitionClassName + "." + testResultTestName, testResultOutcome, testDefinitionStorage)); + results.Add(new(testDefinitionClassName + "." + testResultTestName, testResultOutcome, testDefinitionStorage)); } } } From abd410c74bc42b82d18d3671182666d4444e3d4c Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Wed, 16 Jul 2025 06:08:30 +1000 Subject: [PATCH 221/541] reduce some linq alloc in AppendTestDiscoverySummary (#6025) --- .../OutputDevice/Terminal/TerminalTestReporter.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporter.cs b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporter.cs index b00a8fe4b7..477a8833fa 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporter.cs +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporter.cs @@ -886,7 +886,7 @@ public void AppendTestDiscoverySummary(ITerminal terminal) { terminal.AppendLine(); - var assemblies = _assemblies.Select(asm => asm.Value).OrderBy(a => a.Assembly).Where(a => a is not null).ToList(); + var assemblies = _assemblies.Values.OrderBy(a => a.Assembly).ToList(); int totalTests = _assemblies.Values.Sum(a => a.TotalTests); bool runFailed = _wasCancelled; From c304b8b6e88afacfd64f3118a406f3910114b3a7 Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Wed, 16 Jul 2025 15:41:29 +1000 Subject: [PATCH 222/541] remove some empty type declarations (#6041) --- src/Adapter/MSTest.Engine/Helpers/ISuccessReason.cs | 4 +--- src/Adapter/MSTest.Engine/Helpers/IWarningReason.cs | 4 +--- src/Adapter/MSTest.Engine/TestNodes/IActionableTestNode.cs | 4 +--- test/UnitTests/MSTest.Engine.UnitTests/TestBase.cs | 4 +--- test/UnitTests/MSTest.SourceGeneration.UnitTests/TestBase.cs | 4 +--- .../TestUtilities/CSharpCodeFixVerifier.cs | 4 +--- 6 files changed, 6 insertions(+), 18 deletions(-) diff --git a/src/Adapter/MSTest.Engine/Helpers/ISuccessReason.cs b/src/Adapter/MSTest.Engine/Helpers/ISuccessReason.cs index e9f739f4e5..5952b324bf 100644 --- a/src/Adapter/MSTest.Engine/Helpers/ISuccessReason.cs +++ b/src/Adapter/MSTest.Engine/Helpers/ISuccessReason.cs @@ -3,6 +3,4 @@ namespace Microsoft.Testing.Framework; -internal interface ISuccessReason : IReason -{ -} +internal interface ISuccessReason : IReason; diff --git a/src/Adapter/MSTest.Engine/Helpers/IWarningReason.cs b/src/Adapter/MSTest.Engine/Helpers/IWarningReason.cs index 7b38a5ea9c..e5a50b9aba 100644 --- a/src/Adapter/MSTest.Engine/Helpers/IWarningReason.cs +++ b/src/Adapter/MSTest.Engine/Helpers/IWarningReason.cs @@ -3,6 +3,4 @@ namespace Microsoft.Testing.Framework; -internal interface IWarningReason : IReason -{ -} +internal interface IWarningReason : IReason; diff --git a/src/Adapter/MSTest.Engine/TestNodes/IActionableTestNode.cs b/src/Adapter/MSTest.Engine/TestNodes/IActionableTestNode.cs index 158cd96a6e..2631b535d2 100644 --- a/src/Adapter/MSTest.Engine/TestNodes/IActionableTestNode.cs +++ b/src/Adapter/MSTest.Engine/TestNodes/IActionableTestNode.cs @@ -3,6 +3,4 @@ namespace Microsoft.Testing.Framework; -internal interface IActionableTestNode -{ -} +internal interface IActionableTestNode; diff --git a/test/UnitTests/MSTest.Engine.UnitTests/TestBase.cs b/test/UnitTests/MSTest.Engine.UnitTests/TestBase.cs index 9c09f265b5..0e748f47ce 100644 --- a/test/UnitTests/MSTest.Engine.UnitTests/TestBase.cs +++ b/test/UnitTests/MSTest.Engine.UnitTests/TestBase.cs @@ -6,6 +6,4 @@ namespace Microsoft.Testing.Framework.UnitTests; /// /// Empty test base, because TestInfrastructure project depends on Testing.Framework, and we cannot use that. /// -public abstract class TestBase -{ -} +public abstract class TestBase; diff --git a/test/UnitTests/MSTest.SourceGeneration.UnitTests/TestBase.cs b/test/UnitTests/MSTest.SourceGeneration.UnitTests/TestBase.cs index fcc6fa6db5..7a6d1c82ee 100644 --- a/test/UnitTests/MSTest.SourceGeneration.UnitTests/TestBase.cs +++ b/test/UnitTests/MSTest.SourceGeneration.UnitTests/TestBase.cs @@ -6,6 +6,4 @@ namespace Microsoft.Testing.Framework.SourceGeneration.UnitTests; /// /// Empty test base, because TestInfrastructure project depends on Testing.Framework, and we cannot use that. /// -public abstract class TestBase -{ -} +public abstract class TestBase; diff --git a/test/UnitTests/MSTest.SourceGeneration.UnitTests/TestUtilities/CSharpCodeFixVerifier.cs b/test/UnitTests/MSTest.SourceGeneration.UnitTests/TestUtilities/CSharpCodeFixVerifier.cs index 4d606aedc6..7b2cfb8660 100644 --- a/test/UnitTests/MSTest.SourceGeneration.UnitTests/TestUtilities/CSharpCodeFixVerifier.cs +++ b/test/UnitTests/MSTest.SourceGeneration.UnitTests/TestUtilities/CSharpCodeFixVerifier.cs @@ -23,7 +23,5 @@ public static async Task VerifyAnalyzerAsync(string source, params DiagnosticRes public static DiagnosticResult Diagnostic(DiagnosticDescriptor descriptor) => CSharpCodeFixVerifier.Diagnostic(descriptor); - public sealed class Test : CSharpCodeFixTest - { - } + public sealed class Test : CSharpCodeFixTest; } From 651ddca1378f9e0bf0a3b38f6626c954e532035d Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Wed, 16 Jul 2025 16:15:27 +1000 Subject: [PATCH 223/541] fix Syncronous typo (#6048) --- .../Logging/FileLoggerInformation.cs | 4 ++-- .../Logging/IFIleLoggerInformation.cs | 2 +- .../OutputDevice/TerminalOutputDevice.cs | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Platform/Logging/FileLoggerInformation.cs b/src/Platform/Microsoft.Testing.Platform/Logging/FileLoggerInformation.cs index 2237492e9b..3651bc24b5 100644 --- a/src/Platform/Microsoft.Testing.Platform/Logging/FileLoggerInformation.cs +++ b/src/Platform/Microsoft.Testing.Platform/Logging/FileLoggerInformation.cs @@ -3,9 +3,9 @@ namespace Microsoft.Testing.Platform.Logging; -internal sealed record FileLoggerInformation(bool SyncronousWrite, FileInfo LogFile, LogLevel LogLevel) : IFileLoggerInformation +internal sealed record FileLoggerInformation(bool SynchronousWrite, FileInfo LogFile, LogLevel LogLevel) : IFileLoggerInformation { - public bool SyncronousWrite { get; init; } = SyncronousWrite; + public bool SynchronousWrite { get; init; } = SynchronousWrite; public FileInfo LogFile { get; init; } = LogFile; diff --git a/src/Platform/Microsoft.Testing.Platform/Logging/IFIleLoggerInformation.cs b/src/Platform/Microsoft.Testing.Platform/Logging/IFIleLoggerInformation.cs index 1a77067d53..6f8867e8f4 100644 --- a/src/Platform/Microsoft.Testing.Platform/Logging/IFIleLoggerInformation.cs +++ b/src/Platform/Microsoft.Testing.Platform/Logging/IFIleLoggerInformation.cs @@ -5,7 +5,7 @@ namespace Microsoft.Testing.Platform.Logging; internal interface IFileLoggerInformation { - bool SyncronousWrite { get; } + bool SynchronousWrite { get; } FileInfo LogFile { get; } diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/TerminalOutputDevice.cs b/src/Platform/Microsoft.Testing.Platform/OutputDevice/TerminalOutputDevice.cs index 3509eb9e50..c034d07cb5 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/TerminalOutputDevice.cs +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/TerminalOutputDevice.cs @@ -251,7 +251,7 @@ public async Task DisplayBannerAsync(string? bannerMessage) if (_fileLoggerInformation is not null) { - if (_fileLoggerInformation.SyncronousWrite) + if (_fileLoggerInformation.SynchronousWrite) { _terminalTestReporter.WriteWarningMessage(_assemblyName, _targetFramework, _shortArchitecture, string.Format(CultureInfo.CurrentCulture, PlatformResources.DiagnosticFileLevelWithFlush, _fileLoggerInformation.LogLevel, _fileLoggerInformation.LogFile.FullName), padding: null); } From 625c342e65ed457b08533e48b0409418617ee599 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Wed, 16 Jul 2025 08:28:12 +0200 Subject: [PATCH 224/541] Support passing arguments to DynamicData methods (#5892) --- .../DynamicDataShouldBeValidAnalyzer.cs | 10 +- .../DataSource/DynamicDataAttribute.cs | 41 +++- .../DataSource/DynamicDataOperations.cs | 59 +++--- .../PublicAPI/PublicAPI.Unshipped.txt | 2 + .../Resources/FrameworkMessages.Designer.cs | 2 +- .../Resources/FrameworkMessages.resx | 4 +- .../Resources/xlf/FrameworkMessages.cs.xlf | 4 +- .../Resources/xlf/FrameworkMessages.de.xlf | 4 +- .../Resources/xlf/FrameworkMessages.es.xlf | 4 +- .../Resources/xlf/FrameworkMessages.fr.xlf | 4 +- .../Resources/xlf/FrameworkMessages.it.xlf | 4 +- .../Resources/xlf/FrameworkMessages.ja.xlf | 4 +- .../Resources/xlf/FrameworkMessages.ko.xlf | 4 +- .../Resources/xlf/FrameworkMessages.pl.xlf | 4 +- .../Resources/xlf/FrameworkMessages.pt-BR.xlf | 4 +- .../Resources/xlf/FrameworkMessages.ru.xlf | 4 +- .../Resources/xlf/FrameworkMessages.tr.xlf | 4 +- .../xlf/FrameworkMessages.zh-Hans.xlf | 4 +- .../xlf/FrameworkMessages.zh-Hant.xlf | 4 +- .../DynamicDataMethodTests.cs | 184 ++++++++++++++++++ .../DynamicDataShouldBeValidAnalyzerTests.cs | 52 +++++ 21 files changed, 349 insertions(+), 57 deletions(-) create mode 100644 test/IntegrationTests/MSTest.Acceptance.IntegrationTests/DynamicDataMethodTests.cs diff --git a/src/Analyzers/MSTest.Analyzers/DynamicDataShouldBeValidAnalyzer.cs b/src/Analyzers/MSTest.Analyzers/DynamicDataShouldBeValidAnalyzer.cs index 3ac8f69fca..2a91cf33eb 100644 --- a/src/Analyzers/MSTest.Analyzers/DynamicDataShouldBeValidAnalyzer.cs +++ b/src/Analyzers/MSTest.Analyzers/DynamicDataShouldBeValidAnalyzer.cs @@ -184,6 +184,7 @@ private static void AnalyzeDataSource(SymbolAnalysisContext context, AttributeDa { string? memberName = null; int dataSourceType = DynamicDataSourceTypeAutoDetect; + int argumentsCount = 0; INamedTypeSymbol declaringType = methodSymbol.ContainingType; foreach (TypedConstant argument in attributeData.ConstructorArguments) { @@ -202,10 +203,15 @@ private static void AnalyzeDataSource(SymbolAnalysisContext context, AttributeDa { dataSourceType = dataType; } - else if (argument.Value is INamedTypeSymbol type) + else if (argument.Kind != TypedConstantKind.Array && + argument.Value is INamedTypeSymbol type) { declaringType = type; } + else if (argument.Kind == TypedConstantKind.Array) + { + argumentsCount = argument.Values.Length; + } } // If the member name is not available, bail out. @@ -264,7 +270,7 @@ private static void AnalyzeDataSource(SymbolAnalysisContext context, AttributeDa if (member.Kind == SymbolKind.Method && member is IMethodSymbol method - && (method.IsGenericMethod || method.Parameters.Length != 0)) + && (method.IsGenericMethod || method.Parameters.Length != argumentsCount)) { context.ReportDiagnostic(attributeSyntax.CreateDiagnostic(DataMemberSignatureRule, declaringType.Name, memberName)); return; diff --git a/src/TestFramework/TestFramework/Attributes/DataSource/DynamicDataAttribute.cs b/src/TestFramework/TestFramework/Attributes/DataSource/DynamicDataAttribute.cs index 900906b127..6768a2195b 100644 --- a/src/TestFramework/TestFramework/Attributes/DataSource/DynamicDataAttribute.cs +++ b/src/TestFramework/TestFramework/Attributes/DataSource/DynamicDataAttribute.cs @@ -36,7 +36,7 @@ public sealed class DynamicDataAttribute : Attribute, ITestDataSource, ITestData { private readonly string _dynamicDataSourceName; private readonly DynamicDataSourceType _dynamicDataSourceType; - + private readonly object?[] _dynamicDataSourceArguments = []; private readonly Type? _dynamicDataDeclaringType; /// @@ -67,6 +67,22 @@ public DynamicDataAttribute(string dynamicDataSourceName) _dynamicDataSourceType = DynamicDataSourceType.AutoDetect; } + /// + /// Initializes a new instance of the class. + /// + /// + /// The name of method or property having test data. + /// + /// + /// Arguments to be passed to method referred to by . + /// + public DynamicDataAttribute(string dynamicDataSourceName, params object?[] dynamicDataSourceArguments) + { + _dynamicDataSourceName = dynamicDataSourceName; + _dynamicDataSourceType = DynamicDataSourceType.AutoDetect; + _dynamicDataSourceArguments = dynamicDataSourceArguments; + } + /// /// Initializes a new instance of the class when the test data is present in a class different /// from test method's class. @@ -99,6 +115,27 @@ public DynamicDataAttribute(string dynamicDataSourceName, Type dynamicDataDeclar public DynamicDataAttribute(string dynamicDataSourceName, Type dynamicDataDeclaringType) : this(dynamicDataSourceName) => _dynamicDataDeclaringType = dynamicDataDeclaringType; + /// + /// Initializes a new instance of the class when the test data is present in a class different + /// from test method's class. + /// + /// + /// The name of method or property having test data. + /// + /// + /// The declaring type of property or method having data. Useful in cases when declaring type is present in a class different from + /// test method's class. If null, declaring type defaults to test method's class type. + /// + /// + /// Arguments to be passed to method referred to by . + /// + public DynamicDataAttribute(string dynamicDataSourceName, Type dynamicDataDeclaringType, params object?[] dynamicDataSourceArguments) + : this(dynamicDataSourceName) + { + _dynamicDataDeclaringType = dynamicDataDeclaringType; + _dynamicDataSourceArguments = dynamicDataSourceArguments; + } + internal static TestIdGenerationStrategy TestIdGenerationStrategy { get; set; } /// @@ -121,7 +158,7 @@ public DynamicDataAttribute(string dynamicDataSourceName, Type dynamicDataDeclar /// public IEnumerable GetData(MethodInfo methodInfo) - => DynamicDataOperations.GetData(_dynamicDataDeclaringType, _dynamicDataSourceType, _dynamicDataSourceName, methodInfo); + => DynamicDataOperations.GetData(_dynamicDataDeclaringType, _dynamicDataSourceType, _dynamicDataSourceName, _dynamicDataSourceArguments, methodInfo); /// public string? GetDisplayName(MethodInfo methodInfo, object?[]? data) diff --git a/src/TestFramework/TestFramework/Attributes/DataSource/DynamicDataOperations.cs b/src/TestFramework/TestFramework/Attributes/DataSource/DynamicDataOperations.cs index d2d4b3dd2f..8a654af412 100644 --- a/src/TestFramework/TestFramework/Attributes/DataSource/DynamicDataOperations.cs +++ b/src/TestFramework/TestFramework/Attributes/DataSource/DynamicDataOperations.cs @@ -7,45 +7,45 @@ internal static class DynamicDataOperations { private const BindingFlags DeclaredOnlyLookup = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly; - public static IEnumerable GetData(Type? _dynamicDataDeclaringType, DynamicDataSourceType _dynamicDataSourceType, string _dynamicDataSourceName, MethodInfo methodInfo) + public static IEnumerable GetData(Type? dynamicDataDeclaringType, DynamicDataSourceType dynamicDataSourceType, string dynamicDataSourceName, object?[] dynamicDataSourceArguments, MethodInfo methodInfo) { // Check if the declaring type of test data is passed in. If not, default to test method's class type. - _dynamicDataDeclaringType ??= methodInfo.DeclaringType; - DebugEx.Assert(_dynamicDataDeclaringType is not null, "Declaring type of test data cannot be null."); + dynamicDataDeclaringType ??= methodInfo.DeclaringType; + DebugEx.Assert(dynamicDataDeclaringType is not null, "Declaring type of test data cannot be null."); object? obj = null; - switch (_dynamicDataSourceType) + switch (dynamicDataSourceType) { case DynamicDataSourceType.AutoDetect: #pragma warning disable IDE0045 // Convert to conditional expression - it becomes less readable. - if (GetPropertyConsideringInheritance(_dynamicDataDeclaringType, _dynamicDataSourceName) is { } dynamicDataPropertyInfo) + if (GetPropertyConsideringInheritance(dynamicDataDeclaringType, dynamicDataSourceName) is { } dynamicDataPropertyInfo) { obj = GetDataFromProperty(dynamicDataPropertyInfo); } - else if (GetMethodConsideringInheritance(_dynamicDataDeclaringType, _dynamicDataSourceName) is { } dynamicDataMethodInfo) + else if (GetMethodConsideringInheritance(dynamicDataDeclaringType, dynamicDataSourceName) is { } dynamicDataMethodInfo) { - obj = GetDataFromMethod(dynamicDataMethodInfo); + obj = GetDataFromMethod(dynamicDataMethodInfo, dynamicDataSourceArguments); } else { - throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, FrameworkMessages.DynamicDataSourceShouldExistAndBeValid, _dynamicDataSourceName, _dynamicDataDeclaringType.FullName)); + throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, FrameworkMessages.DynamicDataSourceShouldExistAndBeValid, dynamicDataSourceName, dynamicDataDeclaringType.FullName)); } #pragma warning restore IDE0045 // Convert to conditional expression break; case DynamicDataSourceType.Property: - PropertyInfo property = GetPropertyConsideringInheritance(_dynamicDataDeclaringType, _dynamicDataSourceName) - ?? throw new ArgumentNullException($"{DynamicDataSourceType.Property} {_dynamicDataSourceName}"); + PropertyInfo property = GetPropertyConsideringInheritance(dynamicDataDeclaringType, dynamicDataSourceName) + ?? throw new ArgumentNullException($"{DynamicDataSourceType.Property} {dynamicDataSourceName}"); obj = GetDataFromProperty(property); break; case DynamicDataSourceType.Method: - MethodInfo method = GetMethodConsideringInheritance(_dynamicDataDeclaringType, _dynamicDataSourceName) - ?? throw new ArgumentNullException($"{DynamicDataSourceType.Method} {_dynamicDataSourceName}"); + MethodInfo method = GetMethodConsideringInheritance(dynamicDataDeclaringType, dynamicDataSourceName) + ?? throw new ArgumentNullException($"{DynamicDataSourceType.Method} {dynamicDataSourceName}"); - obj = GetDataFromMethod(method); + obj = GetDataFromMethod(method, dynamicDataSourceArguments); break; } @@ -55,8 +55,8 @@ public static IEnumerable GetData(Type? _dynamicDataDeclaringType, Dyn string.Format( CultureInfo.InvariantCulture, FrameworkMessages.DynamicDataValueNull, - _dynamicDataSourceName, - _dynamicDataDeclaringType.FullName)); + dynamicDataSourceName, + dynamicDataDeclaringType.FullName)); } if (!TryGetData(obj, out IEnumerable? data)) @@ -65,29 +65,40 @@ public static IEnumerable GetData(Type? _dynamicDataDeclaringType, Dyn string.Format( CultureInfo.InvariantCulture, FrameworkMessages.DynamicDataIEnumerableNull, - _dynamicDataSourceName, - _dynamicDataDeclaringType.FullName)); + dynamicDataSourceName, + dynamicDataDeclaringType.FullName)); } // Data is valid, return it. return data; } - private static object? GetDataFromMethod(MethodInfo method) + private static object? GetDataFromMethod(MethodInfo method, object?[] arguments) { - if (!method.IsStatic - || method.ContainsGenericParameters - || method.GetParameters().Length > 0) + if (!method.IsStatic || method.ContainsGenericParameters) { throw new NotSupportedException( string.Format( CultureInfo.InvariantCulture, - FrameworkMessages.DynamicDataInvalidPropertyLayout, + FrameworkMessages.DynamicDataInvalidMethodLayout, + method.DeclaringType?.FullName is { } typeFullName ? $"{typeFullName}.{method.Name}" : method.Name)); + } + + ParameterInfo[] methodParameters = method.GetParameters(); + ParameterInfo? lastParameter = methodParameters.Length > 0 ? methodParameters[methodParameters.Length - 1] : null; + if (lastParameter is not null && + (lastParameter.GetCustomAttribute() is not null || + lastParameter.GetCustomAttribute() is not null)) + { + throw new NotSupportedException( + string.Format( + CultureInfo.InvariantCulture, + FrameworkMessages.DynamicDataInvalidMethodLayout, method.DeclaringType?.FullName is { } typeFullName ? $"{typeFullName}.{method.Name}" : method.Name)); } - // Note: the method is static and takes no parameters. - return method.Invoke(null, null); + // Note: the method is static. + return method.Invoke(null, arguments.Length == 0 ? null : arguments); } private static object? GetDataFromProperty(PropertyInfo property) diff --git a/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Unshipped.txt b/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Unshipped.txt index 65701549f5..c28957dede 100644 --- a/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Unshipped.txt +++ b/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Unshipped.txt @@ -6,6 +6,8 @@ Microsoft.VisualStudio.TestTools.UnitTesting.ConditionBaseAttribute.Mode.get -> override Microsoft.VisualStudio.TestTools.UnitTesting.CIConditionAttribute.GroupName.get -> string! override Microsoft.VisualStudio.TestTools.UnitTesting.CIConditionAttribute.IgnoreMessage.get -> string? override Microsoft.VisualStudio.TestTools.UnitTesting.CIConditionAttribute.ShouldRun.get -> bool +Microsoft.VisualStudio.TestTools.UnitTesting.DynamicDataAttribute.DynamicDataAttribute(string! dynamicDataSourceName, params object?[]! dynamicDataSourceArguments) -> void +Microsoft.VisualStudio.TestTools.UnitTesting.DynamicDataAttribute.DynamicDataAttribute(string! dynamicDataSourceName, System.Type! dynamicDataDeclaringType, params object?[]! dynamicDataSourceArguments) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.ContainsSingle(System.Func! predicate, System.Collections.Generic.IEnumerable! collection, string! message = "") -> T static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.DoesNotEndWith(string? substring, string? value, string! message = "") -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.DoesNotEndWith(string? substring, string? value, System.StringComparison comparisonType, string! message = "") -> void diff --git a/src/TestFramework/TestFramework/Resources/FrameworkMessages.Designer.cs b/src/TestFramework/TestFramework/Resources/FrameworkMessages.Designer.cs index 2a8ad9824e..6f6bd8b572 100644 --- a/src/TestFramework/TestFramework/Resources/FrameworkMessages.Designer.cs +++ b/src/TestFramework/TestFramework/Resources/FrameworkMessages.Designer.cs @@ -403,7 +403,7 @@ internal static string DynamicDataIEnumerableNull { } /// - /// Looks up a localized string similar to Dynamic data method '{0}' should be static, parameterless and non-generic.. + /// Looks up a localized string similar to Dynamic data method '{0}' should be static, non-generic, and cannot have 'params' parameter.. /// internal static string DynamicDataInvalidMethodLayout { get { diff --git a/src/TestFramework/TestFramework/Resources/FrameworkMessages.resx b/src/TestFramework/TestFramework/Resources/FrameworkMessages.resx index 2306f21622..2fbf6e32e0 100644 --- a/src/TestFramework/TestFramework/Resources/FrameworkMessages.resx +++ b/src/TestFramework/TestFramework/Resources/FrameworkMessages.resx @@ -269,7 +269,7 @@ Actual: {2} Property or method {0} on {1} returns empty IEnumerable<object[]>. - Dynamic data method '{0}' should be static, parameterless and non-generic. + Dynamic data method '{0}' should be static, non-generic, and cannot have 'params' parameter. Dynamic data property '{0}' should be static and have a getter. @@ -349,4 +349,4 @@ Actual: {2} CollectionAssert.ReferenceEquals should not be used for Assertions. Please use CollectionAssert methods or Assert.AreSame & overloads instead. - + \ No newline at end of file diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.cs.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.cs.xlf index 101611f327..cd09820994 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.cs.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.cs.xlf @@ -128,8 +128,8 @@ - Dynamic data method '{0}' should be static, parameterless and non-generic. - Metoda dynamických dat {0} by měla být statická, bez parametrů a negenerická. + Dynamic data method '{0}' should be static, non-generic, and cannot have 'params' parameter. + Metoda dynamických dat {0} by měla být statická, bez parametrů a negenerická. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.de.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.de.xlf index 5dbd5cc065..45cf5b7ab6 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.de.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.de.xlf @@ -128,8 +128,8 @@ - Dynamic data method '{0}' should be static, parameterless and non-generic. - Die dynamische Datenmethode "{0}" muss statisch, parameterlos sein und nichtgenerisch sein. + Dynamic data method '{0}' should be static, non-generic, and cannot have 'params' parameter. + Die dynamische Datenmethode "{0}" muss statisch, parameterlos sein und nichtgenerisch sein. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.es.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.es.xlf index 478263aa43..051409c88b 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.es.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.es.xlf @@ -128,8 +128,8 @@ - Dynamic data method '{0}' should be static, parameterless and non-generic. - El método de datos dinámicos '{0}' debe ser estático, sin parámetros y no genérico. + Dynamic data method '{0}' should be static, non-generic, and cannot have 'params' parameter. + El método de datos dinámicos '{0}' debe ser estático, sin parámetros y no genérico. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.fr.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.fr.xlf index aa3992bd0d..c724cb752f 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.fr.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.fr.xlf @@ -128,8 +128,8 @@ - Dynamic data method '{0}' should be static, parameterless and non-generic. - La méthode de données dynamiques « {0} » doit être statique, sans paramètre et non générique. + Dynamic data method '{0}' should be static, non-generic, and cannot have 'params' parameter. + La méthode de données dynamiques « {0} » doit être statique, sans paramètre et non générique. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.it.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.it.xlf index 8f08e8cdf7..22d4ebcb42 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.it.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.it.xlf @@ -128,8 +128,8 @@ - Dynamic data method '{0}' should be static, parameterless and non-generic. - Il metodo '{0}' di Dynamic Data deve essere statico, senza parametri e non generico. + Dynamic data method '{0}' should be static, non-generic, and cannot have 'params' parameter. + Il metodo '{0}' di Dynamic Data deve essere statico, senza parametri e non generico. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ja.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ja.xlf index 4caa825f52..4c01f755cb 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ja.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ja.xlf @@ -128,8 +128,8 @@ - Dynamic data method '{0}' should be static, parameterless and non-generic. - 動的データ メソッド '{0}' は、静的、パラメーターなし、および非ジェネリックである必要があります。 + Dynamic data method '{0}' should be static, non-generic, and cannot have 'params' parameter. + 動的データ メソッド '{0}' は、静的、パラメーターなし、および非ジェネリックである必要があります。 diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ko.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ko.xlf index c149d66b93..a821258570 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ko.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ko.xlf @@ -128,8 +128,8 @@ - Dynamic data method '{0}' should be static, parameterless and non-generic. - 동적 데이터 메서드 '{0}'은(는) 정적이고 매개 변수가 없으며 제네릭이 아니어야 합니다. + Dynamic data method '{0}' should be static, non-generic, and cannot have 'params' parameter. + 동적 데이터 메서드 '{0}'은(는) 정적이고 매개 변수가 없으며 제네릭이 아니어야 합니다. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pl.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pl.xlf index 8bd972fb05..006492b973 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pl.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pl.xlf @@ -128,8 +128,8 @@ - Dynamic data method '{0}' should be static, parameterless and non-generic. - Metoda danych dynamicznych „{0}” powinna być statyczna, bez parametrów i nie generyczna. + Dynamic data method '{0}' should be static, non-generic, and cannot have 'params' parameter. + Metoda danych dynamicznych „{0}” powinna być statyczna, bez parametrów i nie generyczna. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf index 517ff7ea57..89cab33007 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf @@ -128,8 +128,8 @@ - Dynamic data method '{0}' should be static, parameterless and non-generic. - O método de dados dinâmicos "{0}" deve ser estático, sem parâmetros e não genérico. + Dynamic data method '{0}' should be static, non-generic, and cannot have 'params' parameter. + O método de dados dinâmicos "{0}" deve ser estático, sem parâmetros e não genérico. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ru.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ru.xlf index 30777fbe1c..facc544bf2 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ru.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ru.xlf @@ -128,8 +128,8 @@ - Dynamic data method '{0}' should be static, parameterless and non-generic. - Метод динамических данных "{0}" должен быть статическим, не иметь параметров и быть неуниверсальным. + Dynamic data method '{0}' should be static, non-generic, and cannot have 'params' parameter. + Метод динамических данных "{0}" должен быть статическим, не иметь параметров и быть неуниверсальным. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.tr.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.tr.xlf index 30a31a43e5..2787b15cbd 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.tr.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.tr.xlf @@ -128,8 +128,8 @@ - Dynamic data method '{0}' should be static, parameterless and non-generic. - '{0}' dinamik veri yöntemi statik ve parametresiz olmalı ve genel olmamalıdır. + Dynamic data method '{0}' should be static, non-generic, and cannot have 'params' parameter. + '{0}' dinamik veri yöntemi statik ve parametresiz olmalı ve genel olmamalıdır. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf index 84a637d30b..82058cc4ea 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf @@ -128,8 +128,8 @@ - Dynamic data method '{0}' should be static, parameterless and non-generic. - 动态数据方法“{0}”应为静态、无参数和非泛型。 + Dynamic data method '{0}' should be static, non-generic, and cannot have 'params' parameter. + 动态数据方法“{0}”应为静态、无参数和非泛型。 diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf index 9a1cb2f02a..86030a3f11 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf @@ -128,8 +128,8 @@ - Dynamic data method '{0}' should be static, parameterless and non-generic. - 動態資料方法 '{0}' 應為靜態、無參數及非泛型。 + Dynamic data method '{0}' should be static, non-generic, and cannot have 'params' parameter. + 動態資料方法 '{0}' 應為靜態、無參數及非泛型。 diff --git a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/DynamicDataMethodTests.cs b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/DynamicDataMethodTests.cs new file mode 100644 index 0000000000..0e2701b754 --- /dev/null +++ b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/DynamicDataMethodTests.cs @@ -0,0 +1,184 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using Microsoft.Testing.Platform.Acceptance.IntegrationTests; +using Microsoft.Testing.Platform.Acceptance.IntegrationTests.Helpers; +using Microsoft.Testing.Platform.Helpers; + +namespace MSTest.Acceptance.IntegrationTests; + +[TestClass] +public sealed class DynamicDataMethodTests : AcceptanceTestBase +{ + [TestMethod] + [DynamicData(nameof(TargetFrameworks.AllForDynamicData), typeof(TargetFrameworks))] + public async Task DynamicDataTestWithParameterizedDataProviderMethod(string tfm) + { + var testHost = TestHost.LocateFrom(AssetFixture.ProjectPath, TestAssetFixture.ProjectName, tfm); + TestHostResult testHostResult = await testHost.ExecuteAsync("--settings my.runsettings"); + + testHostResult.AssertExitCodeIs(ExitCodes.AtLeastOneTestFailed); + testHostResult.AssertOutputContainsSummary(failed: 3, passed: 9, skipped: 0); + + // failed TestMethodSingleParameterIntCountMismatchSmaller (0ms) + // Parameter count mismatch. + // at System.Reflection.MethodBaseInvoker.ThrowTargetParameterCountException() + // at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) + // at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters) + // + // failed TestMethodSingleParameterIntCountMismatchLarger (0ms) + // Parameter count mismatch. + // at System.Reflection.MethodBaseInvoker.ThrowTargetParameterCountException() + // at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) + // at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters) + // + // failed TestMethodParamsNotSupported (0ms) + // Dynamic data method 'TestClass1.GetDataParams' should be static, non-generic, and cannot have 'params' parameter. + testHostResult.AssertOutputMatchesRegex(@"failed TestMethodSingleParameterIntCountMismatchSmaller \(\d+ms\)[\r\n]+\s+Parameter count mismatch."); + testHostResult.AssertOutputMatchesRegex(@"failed TestMethodSingleParameterIntCountMismatchLarger \(\d+ms\)[\r\n]+\s+Parameter count mismatch."); + testHostResult.AssertOutputMatchesRegex(@"failed TestMethodParamsNotSupported \(\d+ms\)[\r\n]+\s+Dynamic data method 'TestClass1.GetDataParams' should be static, non-generic, and cannot have 'params' parameter."); + + testHostResult.AssertOutputContains("TestMethodSingleParameterInt called with: 4"); + testHostResult.AssertOutputContains("TestMethodSingleParameterInt called with: 5"); + testHostResult.AssertOutputContains("TestMethodSingleParameterInt called with: 6"); + + testHostResult.AssertOutputContains("TestMethodTwoParametersIntAndString called with: 4, Hello1"); + testHostResult.AssertOutputContains("TestMethodTwoParametersIntAndString called with: 5, Hello2"); + testHostResult.AssertOutputContains("TestMethodTwoParametersIntAndString called with: 6, Hello3"); + + testHostResult.AssertOutputContains("TestMethodSingleParameterIntArray called with: 5"); + testHostResult.AssertOutputContains("TestMethodSingleParameterIntArray called with: 7"); + testHostResult.AssertOutputContains("TestMethodSingleParameterIntArray called with: 9"); + } + + public sealed class TestAssetFixture() : TestAssetFixtureBase(AcceptanceFixture.NuGetGlobalPackagesFolder) + { + public const string ProjectName = "DynamicDataMethodTests"; + + public string ProjectPath => GetAssetPath(ProjectName); + + public override IEnumerable<(string ID, string Name, string Code)> GetAssetsToGenerate() + { + yield return (ProjectName, ProjectName, + SourceCode + .PatchTargetFrameworks(TargetFrameworks.All) + .PatchCodeWithReplace("$MSTestVersion$", MSTestVersion)); + } + + private const string SourceCode = """ +#file DynamicDataMethodTests.csproj + + + + Exe + true + $TargetFrameworks$ + preview + + + + + + + + + + PreserveNewest + + + + +#file TestClass1.cs +using System; +using System.Collections.Generic; +using System.Text; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +[TestClass] +public class TestClass1 +{ + [TestMethod] + [DynamicData(nameof(GetDataSingleParameterInt), 4)] + public void TestMethodSingleParameterInt(int a) + { + // We call GetDataSingleParameterInt with 4, so it should yield 4, 5, and 6. + Console.WriteLine($"TestMethodSingleParameterInt called with: {a}"); + } + + [TestMethod] + [DynamicData(nameof(GetDataTwoParametersIntAndString), 4, "Hello")] + public void TestMethodTwoParametersIntAndString(int a, string s) + { + // We call GetDataTwoParametersIntAndString with 4 and "Hello", so it should yield: + // - (4, "Hello1") + // - (5, "Hello2") + // - (6, "Hello3") + Console.WriteLine($"TestMethodTwoParametersIntAndString called with: {a}, {s}"); + } + + [TestMethod] + [DynamicData(nameof(GetDataSingleParameterIntArray), [new int[] { 4, 5, 6 }])] + public void TestMethodSingleParameterIntArray(int x) + { + // We call GetDataSingleParameterIntArray with an array (4, 5, and 6), so it should yield 5, 7, and 9. + Console.WriteLine($"TestMethodSingleParameterIntArray called with: {x}"); + } + + [TestMethod] + [DynamicData(nameof(GetDataSingleParameterInt))] + public void TestMethodSingleParameterIntCountMismatchSmaller(int x) + { + // This test should fail due parameter count mismatch. + } + + [TestMethod] + [DynamicData(nameof(GetDataSingleParameterInt), 1, 2)] + public void TestMethodSingleParameterIntCountMismatchLarger(int x) + { + // This test should fail due parameter count mismatch. + } + + [TestMethod] + [DynamicData(nameof(GetDataParams), 1, 2)] + public void TestMethodParamsNotSupported(int x) + { + // This test should fail because we don't support params. + } + + public static IEnumerable GetDataSingleParameterInt(int i) + { + yield return i++; + yield return i++; + yield return i++; + } + + public static IEnumerable GetDataSingleParameterIntArray(int[] input) + { + yield return [1 + input[0]]; + yield return [2 + input[1]]; + yield return [3 + input[2]]; + } + + public static IEnumerable GetDataTwoParametersIntAndString(int i, string s) + { + yield return new object[] { i++, s + "1" }; + yield return new object[] { i++, s + "2" }; + yield return new object[] { i++, s + "3" }; + } + + public static IEnumerable GetDataParams(params int[] i) + { + yield return 0; + yield return 1; + } +} + +#file my.runsettings + + + false + + +"""; + } +} diff --git a/test/UnitTests/MSTest.Analyzers.UnitTests/DynamicDataShouldBeValidAnalyzerTests.cs b/test/UnitTests/MSTest.Analyzers.UnitTests/DynamicDataShouldBeValidAnalyzerTests.cs index 4d8a1b3a03..ee825e62da 100644 --- a/test/UnitTests/MSTest.Analyzers.UnitTests/DynamicDataShouldBeValidAnalyzerTests.cs +++ b/test/UnitTests/MSTest.Analyzers.UnitTests/DynamicDataShouldBeValidAnalyzerTests.cs @@ -1641,4 +1641,56 @@ public void TestMethod2(char c) """, VerifyCS.Diagnostic(DynamicDataShouldBeValidAnalyzer.MemberTypeRule).WithLocation(0).WithArguments("MyTestClass", "GetData")); + + [TestMethod] + public async Task WhenDataWithArgument_NoDiagnostic() + => await VerifyCS.VerifyAnalyzerAsync( + """ + using System; + using System.Collections.Generic; + using Microsoft.VisualStudio.TestTools.UnitTesting; + [TestClass] + public class MyTestClass + { + [TestMethod] + [DynamicData(nameof(GetData), 4)] + public void TestMethod(int a) + => Assert.IsInRange(4, 6, a); + + public static IEnumerable GetData(int i) + { + yield return i++; + yield return i++; + yield return i++; + } + } + + """); + + [TestMethod] + public async Task WhenDataWithArgument_ParameterCountMismatch_Diagnostic() + => await VerifyCS.VerifyAnalyzerAsync( + """ + using System; + using System.Collections.Generic; + using Microsoft.VisualStudio.TestTools.UnitTesting; + [TestClass] + public class MyTestClass + { + [TestMethod] + [{|#0:DynamicData(nameof(GetData), 4, 5)|}] + public void TestMethod(int a) + { + } + + public static IEnumerable GetData(int i) + { + yield return i++; + yield return i++; + yield return i++; + } + } + + """, + VerifyCS.Diagnostic(DynamicDataShouldBeValidAnalyzer.DataMemberSignatureRule).WithLocation(0).WithArguments("MyTestClass", "GetData")); } From 325929223262993cedb8dbf1622a29e0124fb0bf Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Wed, 16 Jul 2025 17:13:15 +1000 Subject: [PATCH 225/541] simplify IsNaN checks (#6043) --- .../TestFramework/Assertions/Assert.IComparable.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/TestFramework/TestFramework/Assertions/Assert.IComparable.cs b/src/TestFramework/TestFramework/Assertions/Assert.IComparable.cs index 3a59a112d9..3e27a0f99d 100644 --- a/src/TestFramework/TestFramework/Assertions/Assert.IComparable.cs +++ b/src/TestFramework/TestFramework/Assertions/Assert.IComparable.cs @@ -183,14 +183,14 @@ public static void IsPositive(T value, string message = "") var zero = default(T); // Handle special case for floating point NaN values - if (value is float floatValue && float.IsNaN(floatValue)) + if (value is float.NaN) { string userMessage = BuildUserMessage(message); ThrowAssertIsPositiveFailed(value, userMessage); return; } - if (value is double doubleValue && double.IsNaN(doubleValue)) + if (value is double.NaN) { string userMessage = BuildUserMessage(message); ThrowAssertIsPositiveFailed(value, userMessage); @@ -233,14 +233,14 @@ public static void IsNegative(T value, string message = "") var zero = default(T); // Handle special case for floating point NaN values - if (value is float floatValue && float.IsNaN(floatValue)) + if (value is float.NaN) { string userMessage = BuildUserMessage(message); ThrowAssertIsNegativeFailed(value, userMessage); return; } - if (value is double doubleValue && double.IsNaN(doubleValue)) + if (value is double.NaN) { string userMessage = BuildUserMessage(message); ThrowAssertIsNegativeFailed(value, userMessage); From 6dd364574cebb0440fb6e1b84943d841e7e3cbba Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Wed, 16 Jul 2025 09:15:07 +0200 Subject: [PATCH 226/541] Cleanup TerminalTestReporter (#6037) --- .../Terminal/TerminalTestReporter.cs | 290 +++++------------- .../Terminal/TerminalTestReporterOptions.cs | 10 - .../OutputDevice/TerminalOutputDevice.cs | 54 +--- .../Terminal/TerminalTestReporterTests.cs | 114 ++++--- 4 files changed, 145 insertions(+), 323 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporter.cs b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporter.cs index 477a8833fa..024f1f5c0d 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporter.cs +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporter.cs @@ -35,15 +35,21 @@ internal event EventHandler OnProgressStopUpdate remove => _terminalWithProgress.OnProgressStopUpdate -= value; } - private readonly ConcurrentDictionary _assemblies = new(); + private readonly string _assembly; + private readonly string? _targetFramework; + private readonly string? _architecture; private readonly List _artifacts = []; private readonly TerminalTestReporterOptions _options; private readonly TestProgressStateAwareTerminal _terminalWithProgress; + private readonly Lock _lock = new(); private readonly uint? _originalConsoleMode; + + private TestProgressState? _testProgressState; + private bool _isDiscovery; private DateTimeOffset? _testExecutionStartTime; @@ -60,8 +66,11 @@ internal event EventHandler OnProgressStopUpdate /// /// Initializes a new instance of the class with custom terminal and manual refresh for testing. /// - public TerminalTestReporter(IConsole console, TerminalTestReporterOptions options) + public TerminalTestReporter(string assembly, string? targetFramework, string? architecture, IConsole console, TerminalTestReporterOptions options) { + _assembly = assembly; + _targetFramework = targetFramework; + _architecture = architecture; _options = options; Func showProgress = _options.ShowProgress; @@ -103,34 +112,30 @@ public void TestExecutionStarted(DateTimeOffset testStartTime, int workerCount, _terminalWithProgress.StartShowingProgress(workerCount); } - public void AssemblyRunStarted(string assembly, string? targetFramework, string? architecture) + public void AssemblyRunStarted() + => GetOrAddAssemblyRun(); + + private TestProgressState GetOrAddAssemblyRun() { - if (_options.ShowAssembly && _options.ShowAssemblyStartAndComplete) + if (_testProgressState is not null) { - _terminalWithProgress.WriteToTerminal(terminal => - { - terminal.Append(_isDiscovery ? PlatformResources.DiscoveringTestsFrom : PlatformResources.RunningTestsFrom); - terminal.Append(' '); - AppendAssemblyLinkTargetFrameworkAndArchitecture(terminal, assembly, targetFramework, architecture); - terminal.AppendLine(); - }); + return _testProgressState; } - GetOrAddAssemblyRun(assembly, targetFramework, architecture); - } - - private TestProgressState GetOrAddAssemblyRun(string assembly, string? targetFramework, string? architecture) - { - string key = $"{assembly}|{targetFramework}|{architecture}"; - return _assemblies.GetOrAdd(key, _ => + lock (_lock) { + if (_testProgressState is not null) + { + return _testProgressState; + } + IStopwatch sw = CreateStopwatch(); - var assemblyRun = new TestProgressState(Interlocked.Increment(ref _counter), assembly, targetFramework, architecture, sw); + var assemblyRun = new TestProgressState(Interlocked.Increment(ref _counter), _assembly, _targetFramework, _architecture, sw); int slotIndex = _terminalWithProgress.AddWorker(assemblyRun); assemblyRun.SlotIndex = slotIndex; - + _testProgressState = assemblyRun; return assemblyRun; - }); + } } public void TestExecutionCompleted(DateTimeOffset endTime) @@ -141,7 +146,6 @@ public void TestExecutionCompleted(DateTimeOffset endTime) _terminalWithProgress.WriteToTerminal(_isDiscovery ? AppendTestDiscoverySummary : AppendTestRunSummary); NativeMethods.RestoreConsoleMode(_originalConsoleMode); - _assemblies.Clear(); _buildErrorsCount = 0; _testExecutionStartTime = null; _testExecutionEndTime = null; @@ -179,9 +183,9 @@ private void AppendTestRunSummary(ITerminal terminal) terminal.AppendLine(); - int totalTests = _assemblies.Values.Sum(a => a.TotalTests); - int totalFailedTests = _assemblies.Values.Sum(a => a.FailedTests); - int totalSkippedTests = _assemblies.Values.Sum(a => a.SkippedTests); + int totalTests = _testProgressState?.TotalTests ?? 0; + int totalFailedTests = _testProgressState?.FailedTests ?? 0; + int totalSkippedTests = _testProgressState?.SkippedTests ?? 0; bool notEnoughTests = totalTests < _options.MinimumExpectedTests; bool allTestsWereSkipped = totalTests == 0 || totalTests == totalSkippedTests; @@ -213,33 +217,17 @@ private void AppendTestRunSummary(ITerminal terminal) terminal.Append($"{PlatformResources.Passed}!"); } - if (!_options.ShowAssembly && _assemblies.Count == 1) - { - TestProgressState testProgressState = _assemblies.Values.Single(); - terminal.SetColor(TerminalColor.DarkGray); - terminal.Append(" - "); - terminal.ResetColor(); - AppendAssemblyLinkTargetFrameworkAndArchitecture(terminal, testProgressState.Assembly, testProgressState.TargetFramework, testProgressState.Architecture); - } + terminal.SetColor(TerminalColor.DarkGray); + terminal.Append(" - "); + terminal.ResetColor(); + AppendAssemblyLinkTargetFrameworkAndArchitecture(terminal); terminal.AppendLine(); - if (_options.ShowAssembly && _assemblies.Count > 1) - { - foreach (TestProgressState assemblyRun in _assemblies.Values) - { - terminal.Append(SingleIndentation); - AppendAssemblySummary(assemblyRun, terminal); - terminal.AppendLine(); - } - - terminal.AppendLine(); - } - - int total = _assemblies.Values.Sum(t => t.TotalTests); - int failed = _assemblies.Values.Sum(t => t.FailedTests); - int passed = _assemblies.Values.Sum(t => t.PassedTests); - int skipped = _assemblies.Values.Sum(t => t.SkippedTests); + int total = _testProgressState?.TotalTests ?? 0; + int failed = _testProgressState?.FailedTests ?? 0; + int passed = _testProgressState?.PassedTests ?? 0; + int skipped = _testProgressState?.SkippedTests ?? 0; TimeSpan runDuration = _testExecutionStartTime != null && _testExecutionEndTime != null ? (_testExecutionEndTime - _testExecutionStartTime).Value : TimeSpan.Zero; bool colorizeFailed = failed > 0; @@ -295,43 +283,7 @@ private void AppendTestRunSummary(ITerminal terminal) terminal.AppendLine(); } - /// - /// Print a build result summary to the output. - /// - private static void AppendAssemblyResult(ITerminal terminal, bool succeeded, int countErrors, int countWarnings) - { - if (!succeeded) - { - terminal.SetColor(TerminalColor.DarkRed); - // If the build failed, we print one of three red strings. - string text = (countErrors > 0, countWarnings > 0) switch - { - (true, true) => string.Format(CultureInfo.CurrentCulture, PlatformResources.FailedWithErrorsAndWarnings, countErrors, countWarnings), - (true, _) => string.Format(CultureInfo.CurrentCulture, PlatformResources.FailedWithErrors, countErrors), - (false, true) => string.Format(CultureInfo.CurrentCulture, PlatformResources.FailedWithWarnings, countWarnings), - _ => PlatformResources.FailedLowercase, - }; - terminal.Append(text); - terminal.ResetColor(); - } - else if (countWarnings > 0) - { - terminal.SetColor(TerminalColor.DarkYellow); - terminal.Append($"succeeded with {countWarnings} warning(s)"); - terminal.ResetColor(); - } - else - { - terminal.SetColor(TerminalColor.DarkGreen); - terminal.Append(PlatformResources.PassedLowercase); - terminal.ResetColor(); - } - } - internal void TestCompleted( - string assembly, - string? targetFramework, - string? architecture, string testNodeUid, string displayName, TestOutcome outcome, @@ -346,9 +298,6 @@ internal void TestCompleted( { FlatException[] flatExceptions = ExceptionFlattener.Flatten(errorMessage, exception); TestCompleted( - assembly, - targetFramework, - architecture, testNodeUid, displayName, outcome, @@ -362,9 +311,6 @@ internal void TestCompleted( } private void TestCompleted( - string assembly, - string? targetFramework, - string? architecture, string testNodeUid, string displayName, TestOutcome outcome, @@ -376,7 +322,12 @@ private void TestCompleted( string? standardOutput, string? errorOutput) { - TestProgressState asm = _assemblies[$"{assembly}|{targetFramework}|{architecture}"]; + if (_testProgressState is null) + { + throw ApplicationStateGuard.Unreachable(); + } + + TestProgressState asm = _testProgressState; if (_options.ShowActiveTests) { @@ -407,9 +358,6 @@ private void TestCompleted( { _terminalWithProgress.WriteToTerminal(terminal => RenderTestCompleted( terminal, - assembly, - targetFramework, - architecture, displayName, outcome, duration, @@ -430,9 +378,6 @@ private bool GetShowPassedTests() private void RenderTestCompleted( ITerminal terminal, - string assembly, - string? targetFramework, - string? architecture, string displayName, TestOutcome outcome, TimeSpan duration, @@ -472,14 +417,6 @@ private void RenderTestCompleted( terminal.SetColor(TerminalColor.DarkGray); terminal.Append(' '); AppendLongDuration(terminal, duration); - if (_options.ShowAssembly) - { - terminal.AppendLine(); - terminal.Append(SingleIndentation); - terminal.Append(PlatformResources.FromFile); - terminal.Append(' '); - AppendAssemblyLinkTargetFrameworkAndArchitecture(terminal, assembly, targetFramework, architecture); - } terminal.AppendLine(); @@ -595,21 +532,21 @@ private static void FormatStandardAndErrorOutput(ITerminal terminal, string? sta terminal.ResetColor(); } - private static void AppendAssemblyLinkTargetFrameworkAndArchitecture(ITerminal terminal, string assembly, string? targetFramework, string? architecture) + private void AppendAssemblyLinkTargetFrameworkAndArchitecture(ITerminal terminal) { - terminal.AppendLink(assembly, lineNumber: null); - if (targetFramework != null || architecture != null) + terminal.AppendLink(_assembly, lineNumber: null); + if (_targetFramework != null || _architecture != null) { terminal.Append(" ("); - if (targetFramework != null) + if (_targetFramework != null) { - terminal.Append(targetFramework); + terminal.Append(_targetFramework); terminal.Append('|'); } - if (architecture != null) + if (_architecture != null) { - terminal.Append(architecture); + terminal.Append(_architecture); } terminal.Append(')'); @@ -686,46 +623,12 @@ private static void AppendIndentedLine(ITerminal terminal, string? message, stri } } - internal void AssemblyRunCompleted(string assembly, string? targetFramework, string? architecture, - // These parameters are useful only for "remote" runs in dotnet test, where we are reporting on multiple processes. - // In single process run, like with testing platform .exe we report these via messages, and run exit. - int? exitCode, string? outputData, string? errorData) + internal void AssemblyRunCompleted() { - TestProgressState assemblyRun = GetOrAddAssemblyRun(assembly, targetFramework, architecture); + TestProgressState assemblyRun = GetOrAddAssemblyRun(); assemblyRun.Stopwatch.Stop(); _terminalWithProgress.RemoveWorker(assemblyRun.SlotIndex); - - if (!_isDiscovery && _options.ShowAssembly && _options.ShowAssemblyStartAndComplete) - { - _terminalWithProgress.WriteToTerminal(terminal => AppendAssemblySummary(assemblyRun, terminal)); - } - - if (exitCode is null or 0) - { - // Report nothing, we don't want to report on success, because then we will also report on test-discovery etc. - return; - } - - _terminalWithProgress.WriteToTerminal(terminal => - { - AppendExecutableSummary(terminal, exitCode, outputData, errorData); - terminal.AppendLine(); - }); - } - - private static void AppendExecutableSummary(ITerminal terminal, int? exitCode, string? outputData, string? errorData) - { - terminal.AppendLine(); - terminal.Append(PlatformResources.ExitCode); - terminal.Append(": "); - terminal.AppendLine(exitCode?.ToString(CultureInfo.CurrentCulture) ?? ""); - terminal.Append(PlatformResources.StandardOutput); - terminal.AppendLine(":"); - terminal.AppendLine(RoslynString.IsNullOrWhiteSpace(outputData) ? string.Empty : outputData); - terminal.Append(PlatformResources.StandardError); - terminal.AppendLine(":"); - terminal.AppendLine(RoslynString.IsNullOrWhiteSpace(errorData) ? string.Empty : errorData); } private static string? NormalizeSpecialCharacters(string? text) @@ -733,18 +636,6 @@ private static void AppendExecutableSummary(ITerminal terminal, int? exitCode, s // escape char .Replace('\x001b', '\x241b'); - private static void AppendAssemblySummary(TestProgressState assemblyRun, ITerminal terminal) - { - int failedTests = assemblyRun.FailedTests; - int warnings = 0; - - AppendAssemblyLinkTargetFrameworkAndArchitecture(terminal, assemblyRun.Assembly, assemblyRun.TargetFramework, assemblyRun.Architecture); - terminal.Append(' '); - AppendAssemblyResult(terminal, assemblyRun.FailedTests == 0, failedTests, warnings); - terminal.Append(' '); - AppendLongDuration(terminal, assemblyRun.Stopwatch.Elapsed); - } - /// /// Appends a long duration in human readable format such as 1h 23m 500ms. /// @@ -765,8 +656,8 @@ private static void AppendLongDuration(ITerminal terminal, TimeSpan duration, bo public void Dispose() => _terminalWithProgress.Dispose(); - public void ArtifactAdded(bool outOfProcess, string? assembly, string? targetFramework, string? architecture, string? testName, string path) - => _artifacts.Add(new TestRunArtifact(outOfProcess, assembly, targetFramework, architecture, testName, path)); + public void ArtifactAdded(bool outOfProcess, string? testName, string path) + => _artifacts.Add(new TestRunArtifact(outOfProcess, _assembly, _targetFramework, _architecture, testName, path)); /// /// Let the user know that cancellation was triggered. @@ -782,9 +673,9 @@ public void StartCancelling() }); } - internal void WriteErrorMessage(string assembly, string? targetFramework, string? architecture, string text, int? padding) + internal void WriteErrorMessage(string text, int? padding) { - TestProgressState asm = GetOrAddAssemblyRun(assembly, targetFramework, architecture); + TestProgressState asm = GetOrAddAssemblyRun(); asm.AddError(text); _terminalWithProgress.WriteToTerminal(terminal => @@ -803,9 +694,9 @@ internal void WriteErrorMessage(string assembly, string? targetFramework, string }); } - internal void WriteWarningMessage(string assembly, string? targetFramework, string? architecture, string text, int? padding) + internal void WriteWarningMessage(string text, int? padding) { - TestProgressState asm = GetOrAddAssemblyRun(assembly, targetFramework, architecture); + TestProgressState asm = GetOrAddAssemblyRun(); asm.AddWarning(text); _terminalWithProgress.WriteToTerminal(terminal => { @@ -823,8 +714,8 @@ internal void WriteWarningMessage(string assembly, string? targetFramework, stri }); } - internal void WriteErrorMessage(string assembly, string? targetFramework, string? architecture, Exception exception) - => WriteErrorMessage(assembly, targetFramework, architecture, exception.ToString(), padding: null); + internal void WriteErrorMessage(Exception exception) + => WriteErrorMessage(exception.ToString(), padding: null); public void WriteMessage(string text, SystemConsoleColor? color = null, int? padding = null) { @@ -861,14 +752,14 @@ public void WriteMessage(string text, SystemConsoleColor? color = null, int? pad } } - internal void TestDiscovered( - string assembly, - string? targetFramework, - string? architecture, - string displayName) + internal void TestDiscovered(string displayName) { - TestProgressState asm = _assemblies[$"{assembly}|{targetFramework}|{architecture}"]; + if (_testProgressState is null) + { + throw ApplicationStateGuard.Unreachable(); + } + TestProgressState asm = _testProgressState; if (_isDiscovery) { // TODO: add mode for discovered tests to the progress bar, to get rid of the hack here that allows updating the @@ -884,50 +775,30 @@ internal void TestDiscovered( public void AppendTestDiscoverySummary(ITerminal terminal) { + TestProgressState? assembly = _testProgressState; terminal.AppendLine(); - var assemblies = _assemblies.Values.OrderBy(a => a.Assembly).ToList(); - - int totalTests = _assemblies.Values.Sum(a => a.TotalTests); + int totalTests = assembly?.TotalTests ?? 0; bool runFailed = _wasCancelled; - foreach (TestProgressState assembly in assemblies) + if (assembly is not null) { - if (_options.ShowAssembly) - { - terminal.Append(string.Format(CultureInfo.CurrentCulture, PlatformResources.DiscoveredTestsInAssembly, assembly.DiscoveredTestDisplayNames.Count)); - terminal.Append(" - "); - AppendAssemblyLinkTargetFrameworkAndArchitecture(terminal, assembly.Assembly, assembly.TargetFramework, assembly.Architecture); - terminal.AppendLine(); - } - foreach (string displayName in assembly.DiscoveredTestDisplayNames) { terminal.Append(SingleIndentation); terminal.AppendLine(displayName); } - - terminal.AppendLine(); } + terminal.AppendLine(); + terminal.SetColor(runFailed ? TerminalColor.DarkRed : TerminalColor.DarkGreen); - if (assemblies.Count <= 1) - { - terminal.Append(string.Format(CultureInfo.CurrentCulture, PlatformResources.TestDiscoverySummarySingular, totalTests)); + terminal.Append(string.Format(CultureInfo.CurrentCulture, PlatformResources.TestDiscoverySummarySingular, totalTests)); - if (!_options.ShowAssembly && _assemblies.Count == 1) - { - TestProgressState testProgressState = _assemblies.Values.Single(); - terminal.SetColor(TerminalColor.DarkGray); - terminal.Append(" - "); - terminal.ResetColor(); - AppendAssemblyLinkTargetFrameworkAndArchitecture(terminal, testProgressState.Assembly, testProgressState.TargetFramework, testProgressState.Architecture); - } - } - else - { - terminal.Append(string.Format(CultureInfo.CurrentCulture, PlatformResources.TestDiscoverySummary, totalTests, assemblies.Count)); - } + terminal.SetColor(TerminalColor.DarkGray); + terminal.Append(" - "); + terminal.ResetColor(); + AppendAssemblyLinkTargetFrameworkAndArchitecture(terminal); terminal.ResetColor(); terminal.AppendLine(); @@ -968,14 +839,15 @@ private static TerminalColor ToTerminalColor(ConsoleColor consoleColor) }; public void TestInProgress( - string assembly, - string? targetFramework, - string? architecture, string testNodeUid, string displayName) { - TestProgressState asm = _assemblies[$"{assembly}|{targetFramework}|{architecture}"]; + if (_testProgressState is null) + { + throw ApplicationStateGuard.Unreachable(); + } + TestProgressState asm = _testProgressState; if (_options.ShowActiveTests) { asm.TestNodeResultsState ??= new(Interlocked.Increment(ref _counter)); diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporterOptions.cs b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporterOptions.cs index bb610c1026..30aee81d59 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporterOptions.cs +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporterOptions.cs @@ -15,16 +15,6 @@ internal sealed class TerminalTestReporterOptions /// public Func ShowPassedTests { get; init; } = () => true; - /// - /// Gets a value indicating whether we should show information about which assembly is the source of the data on screen. Turn this off when running directly from an exe to reduce noise, because the path will always be the same. - /// - public bool ShowAssembly { get; init; } - - /// - /// Gets a value indicating whether we should show information about which assembly started or completed. Turn this off when running directly from an exe to reduce noise, because the path will always be the same. - /// - public bool ShowAssemblyStartAndComplete { get; init; } - /// /// Gets minimum amount of tests to run. /// diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/TerminalOutputDevice.cs b/src/Platform/Microsoft.Testing.Platform/OutputDevice/TerminalOutputDevice.cs index c034d07cb5..eb751d88ee 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/TerminalOutputDevice.cs +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/TerminalOutputDevice.cs @@ -151,11 +151,9 @@ await _policiesService.RegisterOnAbortCallbackAsync( : !_testHostControllerInfo.IsCurrentProcessTestHostController; // This is single exe run, don't show all the details of assemblies and their summaries. - _terminalTestReporter = new TerminalTestReporter(_console, new() + _terminalTestReporter = new TerminalTestReporter(_assemblyName, _targetFramework, _shortArchitecture, _console, new() { BaseDirectory = null, - ShowAssembly = false, - ShowAssemblyStartAndComplete = false, ShowPassedTests = showPassed, MinimumExpectedTests = PlatformCommandLineProvider.GetMinimumExpectedTests(_commandLineOptions), UseAnsi = !noAnsi, @@ -253,11 +251,11 @@ public async Task DisplayBannerAsync(string? bannerMessage) { if (_fileLoggerInformation.SynchronousWrite) { - _terminalTestReporter.WriteWarningMessage(_assemblyName, _targetFramework, _shortArchitecture, string.Format(CultureInfo.CurrentCulture, PlatformResources.DiagnosticFileLevelWithFlush, _fileLoggerInformation.LogLevel, _fileLoggerInformation.LogFile.FullName), padding: null); + _terminalTestReporter.WriteWarningMessage(string.Format(CultureInfo.CurrentCulture, PlatformResources.DiagnosticFileLevelWithFlush, _fileLoggerInformation.LogLevel, _fileLoggerInformation.LogFile.FullName), padding: null); } else { - _terminalTestReporter.WriteWarningMessage(_assemblyName, _targetFramework, _shortArchitecture, string.Format(CultureInfo.CurrentCulture, PlatformResources.DiagnosticFileLevelWithAsyncFlush, _fileLoggerInformation.LogLevel, _fileLoggerInformation.LogFile.FullName), padding: null); + _terminalTestReporter.WriteWarningMessage(string.Format(CultureInfo.CurrentCulture, PlatformResources.DiagnosticFileLevelWithAsyncFlush, _fileLoggerInformation.LogLevel, _fileLoggerInformation.LogFile.FullName), padding: null); } } } @@ -278,7 +276,7 @@ public async Task DisplayBeforeSessionStartAsync() // Start test execution here, rather than in ShowBanner, because then we know // if we are a testHost controller or not, and if we should show progress bar. _terminalTestReporter.TestExecutionStarted(_clock.UtcNow, workerCount: 1, isDiscovery: _isListTests); - _terminalTestReporter.AssemblyRunStarted(_assemblyName, _targetFramework, _shortArchitecture); + _terminalTestReporter.AssemblyRunStarted(); if (_logger is not null && _logger.IsEnabled(LogLevel.Trace)) { await _logger.LogTraceAsync("DisplayBeforeSessionStartAsync").ConfigureAwait(false); @@ -313,7 +311,7 @@ private async Task DisplayAfterSessionEndRunInternalAsync() { if (!_firstCallTo_OnSessionStartingAsync) { - _terminalTestReporter.AssemblyRunCompleted(_assemblyName, _targetFramework, _shortArchitecture, exitCode: null, outputData: null, errorData: null); + _terminalTestReporter.AssemblyRunCompleted(); _terminalTestReporter.TestExecutionCompleted(_clock.UtcNow); } } @@ -364,17 +362,17 @@ public async Task DisplayAsync(IOutputDeviceDataProducer producer, IOutputDevice case WarningMessageOutputDeviceData warningData: await LogDebugAsync(warningData.Message).ConfigureAwait(false); - _terminalTestReporter.WriteWarningMessage(_assemblyName, _targetFramework, _shortArchitecture, warningData.Message, null); + _terminalTestReporter.WriteWarningMessage(warningData.Message, null); break; case ErrorMessageOutputDeviceData errorData: await LogDebugAsync(errorData.Message).ConfigureAwait(false); - _terminalTestReporter.WriteErrorMessage(_assemblyName, _targetFramework, _shortArchitecture, errorData.Message, null); + _terminalTestReporter.WriteErrorMessage(errorData.Message, null); break; case ExceptionOutputDeviceData exceptionOutputDeviceData: await LogDebugAsync(exceptionOutputDeviceData.Exception.ToString()).ConfigureAwait(false); - _terminalTestReporter.WriteErrorMessage(_assemblyName, _targetFramework, _shortArchitecture, exceptionOutputDeviceData.Exception); + _terminalTestReporter.WriteErrorMessage(exceptionOutputDeviceData.Exception); break; } } @@ -402,9 +400,6 @@ public Task ConsumeAsync(IDataProducer dataProducer, IData value, CancellationTo bool isOutOfProcessArtifact = _firstCallTo_OnSessionStartingAsync; _terminalTestReporter.ArtifactAdded( isOutOfProcessArtifact, - _assemblyName, - _targetFramework, - _shortArchitecture, testNodeStateChanged.TestNode.DisplayName, artifact.FileInfo.FullName); } @@ -413,18 +408,12 @@ public Task ConsumeAsync(IDataProducer dataProducer, IData value, CancellationTo { case InProgressTestNodeStateProperty: _terminalTestReporter.TestInProgress( - _assemblyName, - _targetFramework, - _shortArchitecture, testNodeStateChanged.TestNode.Uid.Value, testNodeStateChanged.TestNode.DisplayName); break; case ErrorTestNodeStateProperty errorState: _terminalTestReporter.TestCompleted( - _assemblyName, - _targetFramework, - _shortArchitecture, testNodeStateChanged.TestNode.Uid.Value, testNodeStateChanged.TestNode.DisplayName, TestOutcome.Error, @@ -440,9 +429,6 @@ public Task ConsumeAsync(IDataProducer dataProducer, IData value, CancellationTo case FailedTestNodeStateProperty failedState: _terminalTestReporter.TestCompleted( - _assemblyName, - _targetFramework, - _shortArchitecture, testNodeStateChanged.TestNode.Uid.Value, testNodeStateChanged.TestNode.DisplayName, TestOutcome.Fail, @@ -458,9 +444,6 @@ public Task ConsumeAsync(IDataProducer dataProducer, IData value, CancellationTo case TimeoutTestNodeStateProperty timeoutState: _terminalTestReporter.TestCompleted( - _assemblyName, - _targetFramework, - _shortArchitecture, testNodeStateChanged.TestNode.Uid.Value, testNodeStateChanged.TestNode.DisplayName, TestOutcome.Timeout, @@ -476,9 +459,6 @@ public Task ConsumeAsync(IDataProducer dataProducer, IData value, CancellationTo case CancelledTestNodeStateProperty cancelledState: _terminalTestReporter.TestCompleted( - _assemblyName, - _targetFramework, - _shortArchitecture, testNodeStateChanged.TestNode.Uid.Value, testNodeStateChanged.TestNode.DisplayName, TestOutcome.Canceled, @@ -494,9 +474,6 @@ public Task ConsumeAsync(IDataProducer dataProducer, IData value, CancellationTo case PassedTestNodeStateProperty: _terminalTestReporter.TestCompleted( - _assemblyName, - _targetFramework, - _shortArchitecture, testNodeStateChanged.TestNode.Uid.Value, testNodeStateChanged.TestNode.DisplayName, outcome: TestOutcome.Passed, @@ -512,9 +489,6 @@ public Task ConsumeAsync(IDataProducer dataProducer, IData value, CancellationTo case SkippedTestNodeStateProperty skippedState: _terminalTestReporter.TestCompleted( - _assemblyName, - _targetFramework, - _shortArchitecture, testNodeStateChanged.TestNode.Uid.Value, testNodeStateChanged.TestNode.DisplayName, TestOutcome.Skipped, @@ -529,11 +503,7 @@ public Task ConsumeAsync(IDataProducer dataProducer, IData value, CancellationTo break; case DiscoveredTestNodeStateProperty: - _terminalTestReporter.TestDiscovered( - _assemblyName, - _targetFramework, - _shortArchitecture, - testNodeStateChanged.TestNode.DisplayName); + _terminalTestReporter.TestDiscovered(testNodeStateChanged.TestNode.DisplayName); break; } @@ -544,9 +514,6 @@ public Task ConsumeAsync(IDataProducer dataProducer, IData value, CancellationTo bool isOutOfProcessArtifact = _firstCallTo_OnSessionStartingAsync; _terminalTestReporter.ArtifactAdded( isOutOfProcessArtifact, - _assemblyName, - _targetFramework, - _shortArchitecture, testName: null, artifact.FileInfo.FullName); } @@ -557,9 +524,6 @@ public Task ConsumeAsync(IDataProducer dataProducer, IData value, CancellationTo bool isOutOfProcessArtifact = _firstCallTo_OnSessionStartingAsync; _terminalTestReporter.ArtifactAdded( isOutOfProcessArtifact, - _assemblyName, - _targetFramework, - _shortArchitecture, testName: null, artifact.FileInfo.FullName); } diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/OutputDevice/Terminal/TerminalTestReporterTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/OutputDevice/Terminal/TerminalTestReporterTests.cs index 1cce4e85cc..f490b1474a 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/OutputDevice/Terminal/TerminalTestReporterTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/OutputDevice/Terminal/TerminalTestReporterTests.cs @@ -68,16 +68,18 @@ public void StackTraceRegexCapturesLines(string stackTraceLine, string expected) [TestMethod] public void NonAnsiTerminal_OutputFormattingIsCorrect() { + string targetFramework = "net8.0"; + string architecture = "x64"; + string assembly = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? @"C:\work\assembly.dll" : "/mnt/work/assembly.dll"; + var stringBuilderConsole = new StringBuilderConsole(); - var terminalReporter = new TerminalTestReporter(stringBuilderConsole, new TerminalTestReporterOptions + var terminalReporter = new TerminalTestReporter(assembly, targetFramework, architecture, stringBuilderConsole, new TerminalTestReporterOptions { ShowPassedTests = () => true, // Like --no-ansi in commandline, should disable ANSI altogether. UseAnsi = false, - ShowAssembly = false, - ShowAssemblyStartAndComplete = false, ShowProgress = () => false, }); @@ -85,32 +87,29 @@ public void NonAnsiTerminal_OutputFormattingIsCorrect() DateTimeOffset endTime = DateTimeOffset.MaxValue; terminalReporter.TestExecutionStarted(startTime, 1, isDiscovery: false); - string targetFramework = "net8.0"; - string architecture = "x64"; - string assembly = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? @"C:\work\assembly.dll" : "/mnt/work/assembly.dll"; string folder = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? @"C:\work\" : "/mnt/work/"; string folderNoSlash = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? @"C:\work" : "/mnt/work"; string folderLink = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? @"C:/work/" : "mnt/work/"; string folderLinkNoSlash = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? @"C:/work" : "mnt/work"; - terminalReporter.AssemblyRunStarted(assembly, targetFramework, architecture); + terminalReporter.AssemblyRunStarted(); string standardOutput = "Hello!"; string errorOutput = "Oh no!"; - terminalReporter.TestCompleted(assembly, targetFramework, architecture, testNodeUid: "PassedTest1", "PassedTest1", TestOutcome.Passed, TimeSpan.FromSeconds(10), + terminalReporter.TestCompleted(testNodeUid: "PassedTest1", "PassedTest1", TestOutcome.Passed, TimeSpan.FromSeconds(10), informativeMessage: null, errorMessage: null, exception: null, expected: null, actual: null, standardOutput, errorOutput); - terminalReporter.TestCompleted(assembly, targetFramework, architecture, testNodeUid: "SkippedTest1", "SkippedTest1", TestOutcome.Skipped, TimeSpan.FromSeconds(10), + terminalReporter.TestCompleted(testNodeUid: "SkippedTest1", "SkippedTest1", TestOutcome.Skipped, TimeSpan.FromSeconds(10), informativeMessage: null, errorMessage: null, exception: null, expected: null, actual: null, standardOutput, errorOutput); // timed out + canceled + failed should all report as failed in summary - terminalReporter.TestCompleted(assembly, targetFramework, architecture, testNodeUid: "TimedoutTest1", "TimedoutTest1", TestOutcome.Timeout, TimeSpan.FromSeconds(10), + terminalReporter.TestCompleted(testNodeUid: "TimedoutTest1", "TimedoutTest1", TestOutcome.Timeout, TimeSpan.FromSeconds(10), informativeMessage: null, errorMessage: null, exception: null, expected: null, actual: null, standardOutput, errorOutput); - terminalReporter.TestCompleted(assembly, targetFramework, architecture, testNodeUid: "CanceledTest1", "CanceledTest1", TestOutcome.Canceled, TimeSpan.FromSeconds(10), + terminalReporter.TestCompleted(testNodeUid: "CanceledTest1", "CanceledTest1", TestOutcome.Canceled, TimeSpan.FromSeconds(10), informativeMessage: null, errorMessage: null, exception: null, expected: null, actual: null, standardOutput, errorOutput); - terminalReporter.TestCompleted(assembly, targetFramework, architecture, testNodeUid: "FailedTest1", "FailedTest1", TestOutcome.Fail, TimeSpan.FromSeconds(10), + terminalReporter.TestCompleted(testNodeUid: "FailedTest1", "FailedTest1", TestOutcome.Fail, TimeSpan.FromSeconds(10), informativeMessage: null, errorMessage: "Tests failed", exception: new StackTraceException(@$" at FailingTest() in {folder}codefile.cs:line 10"), expected: "ABC", actual: "DEF", standardOutput, errorOutput); - terminalReporter.ArtifactAdded(outOfProcess: true, assembly, targetFramework, architecture, testName: null, @$"{folder}artifact1.txt"); - terminalReporter.ArtifactAdded(outOfProcess: false, assembly, targetFramework, architecture, testName: null, @$"{folder}artifact2.txt"); - terminalReporter.AssemblyRunCompleted(assembly, targetFramework, architecture, exitCode: null, outputData: null, errorData: null); + terminalReporter.ArtifactAdded(outOfProcess: true, testName: null, @$"{folder}artifact1.txt"); + terminalReporter.ArtifactAdded(outOfProcess: false, testName: null, @$"{folder}artifact2.txt"); + terminalReporter.AssemblyRunCompleted(); terminalReporter.TestExecutionCompleted(endTime); string output = stringBuilderConsole.Output; @@ -168,8 +167,12 @@ Oh no! [TestMethod] public void SimpleAnsiTerminal_OutputFormattingIsCorrect() { + string targetFramework = "net8.0"; + string architecture = "x64"; + string assembly = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? @"C:\work\assembly.dll" : "/mnt/work/assembly.dll"; + var stringBuilderConsole = new StringBuilderConsole(); - var terminalReporter = new TerminalTestReporter(stringBuilderConsole, new TerminalTestReporterOptions + var terminalReporter = new TerminalTestReporter(assembly, targetFramework, architecture, stringBuilderConsole, new TerminalTestReporterOptions { ShowPassedTests = () => true, // Like if we autodetect that we are in CI (e.g. by looking at TF_BUILD, and we don't disable ANSI. @@ -177,8 +180,6 @@ public void SimpleAnsiTerminal_OutputFormattingIsCorrect() UseCIAnsi = true, ForceAnsi = true, - ShowAssembly = false, - ShowAssemblyStartAndComplete = false, ShowProgress = () => false, }); @@ -186,32 +187,29 @@ public void SimpleAnsiTerminal_OutputFormattingIsCorrect() DateTimeOffset endTime = DateTimeOffset.MaxValue; terminalReporter.TestExecutionStarted(startTime, 1, isDiscovery: false); - string targetFramework = "net8.0"; - string architecture = "x64"; - string assembly = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? @"C:\work\assembly.dll" : "/mnt/work/assembly.dll"; string folder = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? @"C:\work\" : "/mnt/work/"; string folderNoSlash = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? @"C:\work" : "/mnt/work"; string folderLink = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? @"C:/work/" : "mnt/work/"; string folderLinkNoSlash = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? @"C:/work" : "mnt/work"; - terminalReporter.AssemblyRunStarted(assembly, targetFramework, architecture); + terminalReporter.AssemblyRunStarted(); string standardOutput = "Hello!"; string errorOutput = "Oh no!"; - terminalReporter.TestCompleted(assembly, targetFramework, architecture, testNodeUid: "PassedTest1", "PassedTest1", TestOutcome.Passed, TimeSpan.FromSeconds(10), + terminalReporter.TestCompleted(testNodeUid: "PassedTest1", "PassedTest1", TestOutcome.Passed, TimeSpan.FromSeconds(10), informativeMessage: null, errorMessage: null, exception: null, expected: null, actual: null, standardOutput, errorOutput); - terminalReporter.TestCompleted(assembly, targetFramework, architecture, testNodeUid: "SkippedTest1", "SkippedTest1", TestOutcome.Skipped, TimeSpan.FromSeconds(10), + terminalReporter.TestCompleted(testNodeUid: "SkippedTest1", "SkippedTest1", TestOutcome.Skipped, TimeSpan.FromSeconds(10), informativeMessage: null, errorMessage: null, exception: null, expected: null, actual: null, standardOutput, errorOutput); // timed out + canceled + failed should all report as failed in summary - terminalReporter.TestCompleted(assembly, targetFramework, architecture, testNodeUid: "TimedoutTest1", "TimedoutTest1", TestOutcome.Timeout, TimeSpan.FromSeconds(10), + terminalReporter.TestCompleted(testNodeUid: "TimedoutTest1", "TimedoutTest1", TestOutcome.Timeout, TimeSpan.FromSeconds(10), informativeMessage: null, errorMessage: null, exception: null, expected: null, actual: null, standardOutput, errorOutput); - terminalReporter.TestCompleted(assembly, targetFramework, architecture, testNodeUid: "CanceledTest1", "CanceledTest1", TestOutcome.Canceled, TimeSpan.FromSeconds(10), + terminalReporter.TestCompleted(testNodeUid: "CanceledTest1", "CanceledTest1", TestOutcome.Canceled, TimeSpan.FromSeconds(10), informativeMessage: null, errorMessage: null, exception: null, expected: null, actual: null, standardOutput, errorOutput); - terminalReporter.TestCompleted(assembly, targetFramework, architecture, testNodeUid: "FailedTest1", "FailedTest1", TestOutcome.Fail, TimeSpan.FromSeconds(10), + terminalReporter.TestCompleted(testNodeUid: "FailedTest1", "FailedTest1", TestOutcome.Fail, TimeSpan.FromSeconds(10), informativeMessage: null, errorMessage: "Tests failed", exception: new StackTraceException(@$" at FailingTest() in {folder}codefile.cs:line 10"), expected: "ABC", actual: "DEF", standardOutput, errorOutput); - terminalReporter.ArtifactAdded(outOfProcess: true, assembly, targetFramework, architecture, testName: null, @$"{folder}artifact1.txt"); - terminalReporter.ArtifactAdded(outOfProcess: false, assembly, targetFramework, architecture, testName: null, @$"{folder}artifact2.txt"); - terminalReporter.AssemblyRunCompleted(assembly, targetFramework, architecture, exitCode: null, outputData: null, errorData: null); + terminalReporter.ArtifactAdded(outOfProcess: true, testName: null, @$"{folder}artifact1.txt"); + terminalReporter.ArtifactAdded(outOfProcess: false, testName: null, @$"{folder}artifact2.txt"); + terminalReporter.AssemblyRunCompleted(); terminalReporter.TestExecutionCompleted(endTime); string output = stringBuilderConsole.Output; @@ -269,8 +267,12 @@ public void SimpleAnsiTerminal_OutputFormattingIsCorrect() [TestMethod] public void AnsiTerminal_OutputFormattingIsCorrect() { + string targetFramework = "net8.0"; + string architecture = "x64"; + string assembly = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? @"C:\work\assembly.dll" : "/mnt/work/assembly.dll"; + var stringBuilderConsole = new StringBuilderConsole(); - var terminalReporter = new TerminalTestReporter(stringBuilderConsole, new TerminalTestReporterOptions + var terminalReporter = new TerminalTestReporter(assembly, targetFramework, architecture, stringBuilderConsole, new TerminalTestReporterOptions { ShowPassedTests = () => true, // Like if we autodetect that we are in ANSI capable terminal. @@ -278,8 +280,6 @@ public void AnsiTerminal_OutputFormattingIsCorrect() UseCIAnsi = false, ForceAnsi = true, - ShowAssembly = false, - ShowAssemblyStartAndComplete = false, ShowProgress = () => false, }); @@ -287,32 +287,29 @@ public void AnsiTerminal_OutputFormattingIsCorrect() DateTimeOffset endTime = DateTimeOffset.MaxValue; terminalReporter.TestExecutionStarted(startTime, 1, isDiscovery: false); - string targetFramework = "net8.0"; - string architecture = "x64"; - string assembly = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? @"C:\work\assembly.dll" : "/mnt/work/assembly.dll"; string folder = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? @"C:\work\" : "/mnt/work/"; string folderNoSlash = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? @"C:\work" : "/mnt/work"; string folderLink = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? @"C:/work/" : "mnt/work/"; string folderLinkNoSlash = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? @"C:/work" : "mnt/work"; - terminalReporter.AssemblyRunStarted(assembly, targetFramework, architecture); + terminalReporter.AssemblyRunStarted(); string standardOutput = "Hello!"; string errorOutput = "Oh no!"; - terminalReporter.TestCompleted(assembly, targetFramework, architecture, testNodeUid: "PassedTest1", "PassedTest1", TestOutcome.Passed, TimeSpan.FromSeconds(10), + terminalReporter.TestCompleted(testNodeUid: "PassedTest1", "PassedTest1", TestOutcome.Passed, TimeSpan.FromSeconds(10), informativeMessage: null, errorMessage: null, exception: null, expected: null, actual: null, standardOutput, errorOutput); - terminalReporter.TestCompleted(assembly, targetFramework, architecture, testNodeUid: "SkippedTest1", "SkippedTest1", TestOutcome.Skipped, TimeSpan.FromSeconds(10), + terminalReporter.TestCompleted(testNodeUid: "SkippedTest1", "SkippedTest1", TestOutcome.Skipped, TimeSpan.FromSeconds(10), informativeMessage: null, errorMessage: null, exception: null, expected: null, actual: null, standardOutput, errorOutput); // timed out + canceled + failed should all report as failed in summary - terminalReporter.TestCompleted(assembly, targetFramework, architecture, testNodeUid: "TimedoutTest1", "TimedoutTest1", TestOutcome.Timeout, TimeSpan.FromSeconds(10), + terminalReporter.TestCompleted(testNodeUid: "TimedoutTest1", "TimedoutTest1", TestOutcome.Timeout, TimeSpan.FromSeconds(10), informativeMessage: null, errorMessage: null, exception: null, expected: null, actual: null, standardOutput, errorOutput); - terminalReporter.TestCompleted(assembly, targetFramework, architecture, testNodeUid: "CanceledTest1", "CanceledTest1", TestOutcome.Canceled, TimeSpan.FromSeconds(10), + terminalReporter.TestCompleted(testNodeUid: "CanceledTest1", "CanceledTest1", TestOutcome.Canceled, TimeSpan.FromSeconds(10), informativeMessage: null, errorMessage: null, exception: null, expected: null, actual: null, standardOutput, errorOutput); - terminalReporter.TestCompleted(assembly, targetFramework, architecture, testNodeUid: "FailedTest1", "FailedTest1", TestOutcome.Fail, TimeSpan.FromSeconds(10), + terminalReporter.TestCompleted(testNodeUid: "FailedTest1", "FailedTest1", TestOutcome.Fail, TimeSpan.FromSeconds(10), informativeMessage: null, errorMessage: "Tests failed", exception: new StackTraceException(@$" at FailingTest() in {folder}codefile.cs:line 10"), expected: "ABC", actual: "DEF", standardOutput, errorOutput); - terminalReporter.ArtifactAdded(outOfProcess: true, assembly, targetFramework, architecture, testName: null, @$"{folder}artifact1.txt"); - terminalReporter.ArtifactAdded(outOfProcess: false, assembly, targetFramework, architecture, testName: null, @$"{folder}artifact2.txt"); - terminalReporter.AssemblyRunCompleted(assembly, targetFramework, architecture, exitCode: null, outputData: null, errorData: null); + terminalReporter.ArtifactAdded(outOfProcess: true, testName: null, @$"{folder}artifact1.txt"); + terminalReporter.ArtifactAdded(outOfProcess: false, testName: null, @$"{folder}artifact2.txt"); + terminalReporter.AssemblyRunCompleted(); terminalReporter.TestExecutionCompleted(endTime); string output = stringBuilderConsole.Output; @@ -370,9 +367,13 @@ Oh no! [TestMethod] public void AnsiTerminal_OutputProgressFrameIsCorrect() { + string targetFramework = "net8.0"; + string architecture = "x64"; + string assembly = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? @"C:\work\assembly.dll" : "/mnt/work/assembly.dll"; + var stringBuilderConsole = new StringBuilderConsole(); var stopwatchFactory = new StopwatchFactory(); - var terminalReporter = new TerminalTestReporter(stringBuilderConsole, new TerminalTestReporterOptions + var terminalReporter = new TerminalTestReporter(assembly, targetFramework, architecture, stringBuilderConsole, new TerminalTestReporterOptions { ShowPassedTests = () => true, // Like if we autodetect that we are in ANSI capable terminal. @@ -381,8 +382,6 @@ public void AnsiTerminal_OutputProgressFrameIsCorrect() ForceAnsi = true, ShowActiveTests = true, - ShowAssembly = false, - ShowAssemblyStartAndComplete = false, ShowProgress = () => true, }) { @@ -400,34 +399,31 @@ public void AnsiTerminal_OutputProgressFrameIsCorrect() DateTimeOffset endTime = DateTimeOffset.MaxValue; terminalReporter.TestExecutionStarted(startTime, 1, isDiscovery: false); - string targetFramework = "net8.0"; - string architecture = "x64"; - string assembly = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? @"C:\work\assembly.dll" : "/mnt/work/assembly.dll"; string folder = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? @"C:\work\" : "/mnt/work/"; string folderNoSlash = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? @"C:\work" : "/mnt/work"; string folderLink = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? @"C:/work/" : "mnt/work/"; string folderLinkNoSlash = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? @"C:/work" : "mnt/work"; - terminalReporter.AssemblyRunStarted(assembly, targetFramework, architecture); + terminalReporter.AssemblyRunStarted(); string standardOutput = "Hello!"; string errorOutput = "Oh no!"; // Note: Add 1ms to make the order of the progress frame deterministic. // Otherwise all tests that run for 1m31s could show in any order. - terminalReporter.TestInProgress(assembly, targetFramework, architecture, testNodeUid: "PassedTest1", displayName: "PassedTest1"); + terminalReporter.TestInProgress(testNodeUid: "PassedTest1", displayName: "PassedTest1"); stopwatchFactory.AddTime(TimeSpan.FromMilliseconds(1)); - terminalReporter.TestInProgress(assembly, targetFramework, architecture, testNodeUid: "SkippedTest1", displayName: "SkippedTest1"); + terminalReporter.TestInProgress(testNodeUid: "SkippedTest1", displayName: "SkippedTest1"); stopwatchFactory.AddTime(TimeSpan.FromMilliseconds(1)); - terminalReporter.TestInProgress(assembly, targetFramework, architecture, testNodeUid: "InProgressTest1", displayName: "InProgressTest1"); + terminalReporter.TestInProgress(testNodeUid: "InProgressTest1", displayName: "InProgressTest1"); stopwatchFactory.AddTime(TimeSpan.FromMinutes(1)); - terminalReporter.TestInProgress(assembly, targetFramework, architecture, testNodeUid: "InProgressTest2", displayName: "InProgressTest2"); + terminalReporter.TestInProgress(testNodeUid: "InProgressTest2", displayName: "InProgressTest2"); stopwatchFactory.AddTime(TimeSpan.FromSeconds(30)); - terminalReporter.TestInProgress(assembly, targetFramework, architecture, testNodeUid: "InProgressTest3", displayName: "InProgressTest3"); + terminalReporter.TestInProgress(testNodeUid: "InProgressTest3", displayName: "InProgressTest3"); stopwatchFactory.AddTime(TimeSpan.FromSeconds(1)); - terminalReporter.TestCompleted(assembly, targetFramework, architecture, testNodeUid: "PassedTest1", "PassedTest1", TestOutcome.Passed, TimeSpan.FromSeconds(10), + terminalReporter.TestCompleted(testNodeUid: "PassedTest1", "PassedTest1", TestOutcome.Passed, TimeSpan.FromSeconds(10), informativeMessage: null, errorMessage: null, exception: null, expected: null, actual: null, standardOutput, errorOutput); - terminalReporter.TestCompleted(assembly, targetFramework, architecture, testNodeUid: "SkippedTest1", "SkippedTest1", TestOutcome.Skipped, TimeSpan.FromSeconds(10), + terminalReporter.TestCompleted(testNodeUid: "SkippedTest1", "SkippedTest1", TestOutcome.Skipped, TimeSpan.FromSeconds(10), informativeMessage: null, errorMessage: null, exception: null, expected: null, actual: null, standardOutput, errorOutput); string output = stringBuilderConsole.Output; From 591ca0a7be822c570ffb13515baaf1267a3846b7 Mon Sep 17 00:00:00 2001 From: Copilot <198982749+Copilot@users.noreply.github.com> Date: Wed, 16 Jul 2025 09:19:06 +0200 Subject: [PATCH 227/541] Fix TypeContainingTestMethodShouldBeATestClassAnalyzer to handle structs with TestMethod (#5818) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: Evangelink <11340282+Evangelink@users.noreply.github.com> Co-authored-by: Amaury Levé --- .../AddTestClassFixer.cs | 100 +++++++++- .../CodeFixResources.Designer.cs | 9 + .../CodeFixResources.resx | 3 + .../xlf/CodeFixResources.cs.xlf | 5 + .../xlf/CodeFixResources.de.xlf | 5 + .../xlf/CodeFixResources.es.xlf | 5 + .../xlf/CodeFixResources.fr.xlf | 5 + .../xlf/CodeFixResources.it.xlf | 5 + .../xlf/CodeFixResources.ja.xlf | 5 + .../xlf/CodeFixResources.ko.xlf | 5 + .../xlf/CodeFixResources.pl.xlf | 5 + .../xlf/CodeFixResources.pt-BR.xlf | 5 + .../xlf/CodeFixResources.ru.xlf | 5 + .../xlf/CodeFixResources.tr.xlf | 5 + .../xlf/CodeFixResources.zh-Hans.xlf | 5 + .../xlf/CodeFixResources.zh-Hant.xlf | 5 + .../MSTest.Analyzers/Resources.Designer.cs | 4 +- src/Analyzers/MSTest.Analyzers/Resources.resx | 4 +- ...ingTestMethodShouldBeATestClassAnalyzer.cs | 2 +- .../MSTest.Analyzers/xlf/Resources.cs.xlf | 8 +- .../MSTest.Analyzers/xlf/Resources.de.xlf | 8 +- .../MSTest.Analyzers/xlf/Resources.es.xlf | 8 +- .../MSTest.Analyzers/xlf/Resources.fr.xlf | 78 ++++---- .../MSTest.Analyzers/xlf/Resources.it.xlf | 52 +++--- .../MSTest.Analyzers/xlf/Resources.ja.xlf | 108 +++++------ .../MSTest.Analyzers/xlf/Resources.ko.xlf | 108 +++++------ .../MSTest.Analyzers/xlf/Resources.pl.xlf | 38 ++-- .../MSTest.Analyzers/xlf/Resources.pt-BR.xlf | 44 ++--- .../MSTest.Analyzers/xlf/Resources.ru.xlf | 8 +- .../MSTest.Analyzers/xlf/Resources.tr.xlf | 22 +-- .../xlf/Resources.zh-Hans.xlf | 162 ++++++++--------- .../xlf/Resources.zh-Hant.xlf | 104 +++++------ ...ingTestMethodShouldBeATestClassAnalyzer.cs | 172 ++++++++++++++++++ 33 files changed, 721 insertions(+), 386 deletions(-) diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/AddTestClassFixer.cs b/src/Analyzers/MSTest.Analyzers.CodeFixes/AddTestClassFixer.cs index 2b6488f8de..bca1789d1b 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/AddTestClassFixer.cs +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/AddTestClassFixer.cs @@ -52,13 +52,36 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) // Find the type declaration identified by the diagnostic. TypeDeclarationSyntax declaration = syntaxToken.Parent.AncestorsAndSelf().OfType().First(); - // Register a code action that will invoke the fix. - context.RegisterCodeFix( - CodeAction.Create( - title: CodeFixResources.AddTestClassFix, - createChangedDocument: c => AddTestClassAttributeAsync(context.Document, declaration, c), - equivalenceKey: $"{nameof(AddTestClassFixer)}_{diagnostic.Id}"), - diagnostic); + // For structs and record structs, we need to change them to classes/record classes since [TestClass] cannot be applied to structs + if (declaration is StructDeclarationSyntax) + { + context.RegisterCodeFix( + CodeAction.Create( + title: CodeFixResources.ChangeStructToClassAndAddTestClassFix, + createChangedDocument: c => ChangeStructToClassAndAddTestClassAttributeAsync(context.Document, declaration, c), + equivalenceKey: $"{nameof(AddTestClassFixer)}_ChangeStructToClass_{diagnostic.Id}"), + diagnostic); + } + else if (declaration is RecordDeclarationSyntax recordDeclaration + && recordDeclaration.ClassOrStructKeyword.IsKind(SyntaxKind.StructKeyword)) + { + context.RegisterCodeFix( + CodeAction.Create( + title: CodeFixResources.ChangeStructToClassAndAddTestClassFix, + createChangedDocument: c => ChangeRecordStructToRecordClassAndAddTestClassAttributeAsync(context.Document, recordDeclaration, c), + equivalenceKey: $"{nameof(AddTestClassFixer)}_ChangeRecordStructToClass_{diagnostic.Id}"), + diagnostic); + } + else + { + // For classes and record classes, just add the [TestClass] attribute + context.RegisterCodeFix( + CodeAction.Create( + title: CodeFixResources.AddTestClassFix, + createChangedDocument: c => AddTestClassAttributeAsync(context.Document, declaration, c), + equivalenceKey: $"{nameof(AddTestClassFixer)}_{diagnostic.Id}"), + diagnostic); + } } private static async Task AddTestClassAttributeAsync(Document document, TypeDeclarationSyntax typeDeclaration, CancellationToken cancellationToken) @@ -75,4 +98,67 @@ private static async Task AddTestClassAttributeAsync(Document document SyntaxNode newRoot = editor.GetChangedRoot(); return document.WithSyntaxRoot(newRoot); } + + private static async Task ChangeStructToClassAndAddTestClassAttributeAsync(Document document, TypeDeclarationSyntax structDeclaration, CancellationToken cancellationToken) + { + cancellationToken.ThrowIfCancellationRequested(); + DocumentEditor editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false); + + // Create the [TestClass] attribute + AttributeSyntax testClassAttribute = SyntaxFactory.Attribute(SyntaxFactory.ParseName("TestClass")); + AttributeListSyntax attributeList = SyntaxFactory.AttributeList(SyntaxFactory.SingletonSeparatedList(testClassAttribute)); + + // Convert struct to class + ClassDeclarationSyntax classDeclaration = SyntaxFactory.ClassDeclaration(structDeclaration.Identifier) + .WithModifiers(structDeclaration.Modifiers) + .WithTypeParameterList(structDeclaration.TypeParameterList) + .WithConstraintClauses(structDeclaration.ConstraintClauses) + .WithBaseList(structDeclaration.BaseList) + .WithMembers(structDeclaration.Members) + .WithAttributeLists(structDeclaration.AttributeLists.Add(attributeList)) + .WithLeadingTrivia(structDeclaration.GetLeadingTrivia()) + .WithTrailingTrivia(structDeclaration.GetTrailingTrivia()); + + editor.ReplaceNode(structDeclaration, classDeclaration); + + SyntaxNode newRoot = editor.GetChangedRoot(); + return document.WithSyntaxRoot(newRoot); + } + + private static async Task ChangeRecordStructToRecordClassAndAddTestClassAttributeAsync(Document document, RecordDeclarationSyntax recordStructDeclaration, CancellationToken cancellationToken) + { + cancellationToken.ThrowIfCancellationRequested(); + DocumentEditor editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false); + + // Create the [TestClass] attribute + AttributeSyntax testClassAttribute = SyntaxFactory.Attribute(SyntaxFactory.ParseName("TestClass")); + AttributeListSyntax attributeList = SyntaxFactory.AttributeList(SyntaxFactory.SingletonSeparatedList(testClassAttribute)); + + // Filter out readonly modifier since it's not valid for record classes + SyntaxTokenList filteredModifiers = SyntaxFactory.TokenList( + recordStructDeclaration.Modifiers.Where(modifier => !modifier.IsKind(SyntaxKind.ReadOnlyKeyword))); + + // Convert record struct to record class by creating a new RecordDeclarationSyntax + // We need to create a new record declaration instead of just changing the keyword + RecordDeclarationSyntax recordClassDeclaration = SyntaxFactory.RecordDeclaration( + recordStructDeclaration.Keyword, + recordStructDeclaration.Identifier) + .WithModifiers(filteredModifiers) + .WithTypeParameterList(recordStructDeclaration.TypeParameterList) + .WithParameterList(recordStructDeclaration.ParameterList) + .WithBaseList(recordStructDeclaration.BaseList) + .WithConstraintClauses(recordStructDeclaration.ConstraintClauses) + .WithOpenBraceToken(recordStructDeclaration.OpenBraceToken) + .WithMembers(recordStructDeclaration.Members) + .WithCloseBraceToken(recordStructDeclaration.CloseBraceToken) + .WithSemicolonToken(recordStructDeclaration.SemicolonToken) + .WithAttributeLists(recordStructDeclaration.AttributeLists.Add(attributeList)) + .WithLeadingTrivia(recordStructDeclaration.GetLeadingTrivia()) + .WithTrailingTrivia(recordStructDeclaration.GetTrailingTrivia()); + + editor.ReplaceNode(recordStructDeclaration, recordClassDeclaration); + + SyntaxNode newRoot = editor.GetChangedRoot(); + return document.WithSyntaxRoot(newRoot); + } } diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/CodeFixResources.Designer.cs b/src/Analyzers/MSTest.Analyzers.CodeFixes/CodeFixResources.Designer.cs index 127d898b5d..2ff93de26f 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/CodeFixResources.Designer.cs +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/CodeFixResources.Designer.cs @@ -69,6 +69,15 @@ internal static string AddTestClassFix { } } + /// + /// Looks up a localized string similar to Change to 'class' and add '[TestClass]'. + /// + internal static string ChangeStructToClassAndAddTestClassFix { + get { + return ResourceManager.GetString("ChangeStructToClassAndAddTestClassFix", resourceCulture); + } + } + /// /// Looks up a localized string similar to Add '[TestMethod]'. /// diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/CodeFixResources.resx b/src/Analyzers/MSTest.Analyzers.CodeFixes/CodeFixResources.resx index 6f73aa7fd7..f415177ca0 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/CodeFixResources.resx +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/CodeFixResources.resx @@ -129,6 +129,9 @@ Add '[TestClass]' + + Change to 'class' and add '[TestClass]' + Fix test method signature diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.cs.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.cs.xlf index f0cdadaa0e..e0efdc4f9a 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.cs.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.cs.xlf @@ -27,6 +27,11 @@ Změnit přístupnost metody na private + + Change to 'class' and add '[TestClass]' + Change to 'class' and add '[TestClass]' + + Fix actual/expected arguments order Opravit pořadí skutečných/očekávaných argumentů diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.de.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.de.xlf index e1966e09a0..9e88a374a7 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.de.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.de.xlf @@ -27,6 +27,11 @@ Methodenzugriff auf „privat“ ändern + + Change to 'class' and add '[TestClass]' + Change to 'class' and add '[TestClass]' + + Fix actual/expected arguments order Reihenfolge der tatsächlichen/erwarteten Argumente korrigieren diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.es.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.es.xlf index 0f1e41ab01..1514c0607b 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.es.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.es.xlf @@ -27,6 +27,11 @@ Cambiar la accesibilidad del método a "private" + + Change to 'class' and add '[TestClass]' + Change to 'class' and add '[TestClass]' + + Fix actual/expected arguments order Corregir el orden de los argumentos reales o esperados diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.fr.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.fr.xlf index 28032182a6..113115ea70 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.fr.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.fr.xlf @@ -27,6 +27,11 @@ Remplacer l’accessibilité de la méthode par « privé » + + Change to 'class' and add '[TestClass]' + Change to 'class' and add '[TestClass]' + + Fix actual/expected arguments order Corriger l’ordre des arguments réels/attendus diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.it.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.it.xlf index ce079335fe..af72ceead8 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.it.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.it.xlf @@ -27,6 +27,11 @@ Modifica l'accessibilità del metodo in 'privato' + + Change to 'class' and add '[TestClass]' + Change to 'class' and add '[TestClass]' + + Fix actual/expected arguments order Correggi l'ordine degli argomenti effettivi/previsti diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ja.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ja.xlf index f5a9896efa..bec40b5c3d 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ja.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ja.xlf @@ -27,6 +27,11 @@ メソッドのアクセシビリティを 'private' に変更する + + Change to 'class' and add '[TestClass]' + Change to 'class' and add '[TestClass]' + + Fix actual/expected arguments order 実際の引数と予想される引数の順序を修正する diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ko.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ko.xlf index 378b6b3129..c00e2327e4 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ko.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ko.xlf @@ -27,6 +27,11 @@ 메서드 접근성 '비공개'로 변경하기 + + Change to 'class' and add '[TestClass]' + Change to 'class' and add '[TestClass]' + + Fix actual/expected arguments order 실제/예상 인수 순서 수정 diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pl.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pl.xlf index 16a86f9cb5..19091ac8b0 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pl.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pl.xlf @@ -27,6 +27,11 @@ Zmień dostępność metody na „private” (prywatna) + + Change to 'class' and add '[TestClass]' + Change to 'class' and add '[TestClass]' + + Fix actual/expected arguments order Napraw rzeczywistą/oczekiwaną kolejność argumentów diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pt-BR.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pt-BR.xlf index 2d7501bc44..970e7c9fcd 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pt-BR.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pt-BR.xlf @@ -27,6 +27,11 @@ Alterar a acessibilidade do método para 'privado' + + Change to 'class' and add '[TestClass]' + Change to 'class' and add '[TestClass]' + + Fix actual/expected arguments order Corrigir ordem de argumentos real/esperada diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ru.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ru.xlf index 1a166df4bb..c447d1881b 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ru.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ru.xlf @@ -27,6 +27,11 @@ Изменить доступность метода на "private" + + Change to 'class' and add '[TestClass]' + Change to 'class' and add '[TestClass]' + + Fix actual/expected arguments order Исправить порядок фактических и ожидаемых аргументов diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.tr.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.tr.xlf index 2ed16a4416..8787deb22c 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.tr.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.tr.xlf @@ -27,6 +27,11 @@ Yöntem erişilebilirliğini ‘özel’ olarak değiştir + + Change to 'class' and add '[TestClass]' + Change to 'class' and add '[TestClass]' + + Fix actual/expected arguments order Fiili/beklenen bağımsız değişken sırasını düzelt diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hans.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hans.xlf index e37b91c542..ae3f469fff 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hans.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hans.xlf @@ -27,6 +27,11 @@ 将方法可访问性更改为“private” + + Change to 'class' and add '[TestClass]' + Change to 'class' and add '[TestClass]' + + Fix actual/expected arguments order 修复实际/预期参数顺序 diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hant.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hant.xlf index 8782e30dca..e8b747f631 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hant.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hant.xlf @@ -27,6 +27,11 @@ 將方法協助工具變更為 'private' + + Change to 'class' and add '[TestClass]' + Change to 'class' and add '[TestClass]' + + Fix actual/expected arguments order 修正實際/預期的引數順序 diff --git a/src/Analyzers/MSTest.Analyzers/Resources.Designer.cs b/src/Analyzers/MSTest.Analyzers/Resources.Designer.cs index 380694b48f..76be305263 100644 --- a/src/Analyzers/MSTest.Analyzers/Resources.Designer.cs +++ b/src/Analyzers/MSTest.Analyzers/Resources.Designer.cs @@ -1043,7 +1043,7 @@ internal static string TestMethodShouldNotBeIgnoredAnalyzerTitle { } /// - /// Looks up a localized string similar to Type contaning '[TestMethod]' should be marked with '[TestClass]', otherwise the test method will be silently ignored.. + /// Looks up a localized string similar to Type containing '[TestMethod]' should be marked with '[TestClass]', otherwise the test method will be silently ignored.. /// internal static string TypeContainingTestMethodShouldBeATestClassDescription { get { @@ -1052,7 +1052,7 @@ internal static string TypeContainingTestMethodShouldBeATestClassDescription { } /// - /// Looks up a localized string similar to Class '{0}' contains test methods and should be marked with '[TestClass]'. + /// Looks up a localized string similar to Type '{0}' contains test methods and should be marked with '[TestClass]'. /// internal static string TypeContainingTestMethodShouldBeATestClassMessageFormat { get { diff --git a/src/Analyzers/MSTest.Analyzers/Resources.resx b/src/Analyzers/MSTest.Analyzers/Resources.resx index fc98d87ff4..c311df6480 100644 --- a/src/Analyzers/MSTest.Analyzers/Resources.resx +++ b/src/Analyzers/MSTest.Analyzers/Resources.resx @@ -448,10 +448,10 @@ The type declaring these methods should also respect the following rules: Type containing '[TestMethod]' should be marked with '[TestClass]' - Type contaning '[TestMethod]' should be marked with '[TestClass]', otherwise the test method will be silently ignored. + Type containing '[TestMethod]' should be marked with '[TestClass]', otherwise the test method will be silently ignored. - Class '{0}' contains test methods and should be marked with '[TestClass]' + Type '{0}' contains test methods and should be marked with '[TestClass]' 'System.ComponentModel.DescriptionAttribute' has no effect on test methods diff --git a/src/Analyzers/MSTest.Analyzers/TypeContainingTestMethodShouldBeATestClassAnalyzer.cs b/src/Analyzers/MSTest.Analyzers/TypeContainingTestMethodShouldBeATestClassAnalyzer.cs index f5c4d19827..998f4f1ba5 100644 --- a/src/Analyzers/MSTest.Analyzers/TypeContainingTestMethodShouldBeATestClassAnalyzer.cs +++ b/src/Analyzers/MSTest.Analyzers/TypeContainingTestMethodShouldBeATestClassAnalyzer.cs @@ -56,7 +56,7 @@ public override void Initialize(AnalysisContext context) private static void AnalyzeSymbol(SymbolAnalysisContext context, INamedTypeSymbol testClassAttributeSymbol, INamedTypeSymbol testMethodAttributeSymbol) { var namedTypeSymbol = (INamedTypeSymbol)context.Symbol; - if (namedTypeSymbol.TypeKind != TypeKind.Class + if ((namedTypeSymbol.TypeKind != TypeKind.Class && namedTypeSymbol.TypeKind != TypeKind.Struct) || namedTypeSymbol.IsAbstract) { return; diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf index 28403c1afc..aa95370756 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf @@ -750,13 +750,13 @@ Typ deklarující tyto metody by měl také respektovat následující pravidla: - Type contaning '[TestMethod]' should be marked with '[TestClass]', otherwise the test method will be silently ignored. - Typ obsahující [TestMethod] by měl mít označení [TestClass], jinak bude testovací metoda bez jakéhokoli upozornění ignorována. + Type containing '[TestMethod]' should be marked with '[TestClass]', otherwise the test method will be silently ignored. + Typ obsahující [TestMethod] by měl mít označení [TestClass], jinak bude testovací metoda bez jakéhokoli upozornění ignorována. - Class '{0}' contains test methods and should be marked with '[TestClass]' - Třída {0} obsahuje testovací metody a měla by mít označení [TestClass]. + Type '{0}' contains test methods and should be marked with '[TestClass]' + Typ {0} obsahuje testovací metody a měl by mít označení [TestClass]. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf index b0f6603c26..9725c61ef3 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf @@ -751,13 +751,13 @@ Der Typ, der diese Methoden deklariert, sollte auch die folgenden Regeln beachte - Type contaning '[TestMethod]' should be marked with '[TestClass]', otherwise the test method will be silently ignored. - Der Typ, der "[TestMethod]" enthält, sollte mit "[TestClass]" gekennzeichnet werden, andernfalls wird die Testmethode im Hintergrund ignoriert. + Type containing '[TestMethod]' should be marked with '[TestClass]', otherwise the test method will be silently ignored. + Der Typ, der "[TestMethod]" enthält, sollte mit "[TestClass]" gekennzeichnet werden, andernfalls wird die Testmethode im Hintergrund ignoriert. - Class '{0}' contains test methods and should be marked with '[TestClass]' - Die Klasse "{0}" enthält Testmethoden und muss mit "[TestClass]" gekennzeichnet werden. + Type '{0}' contains test methods and should be marked with '[TestClass]' + Der Typ "{0}" enthält Testmethoden und muss mit "[TestClass]" gekennzeichnet werden. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf index 66862bdfae..7f84dff4f1 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf @@ -750,13 +750,13 @@ El tipo que declara estos métodos también debe respetar las reglas siguientes: - Type contaning '[TestMethod]' should be marked with '[TestClass]', otherwise the test method will be silently ignored. - El tipo que contiene '[TestMethod]' debe marcarse con '[TestClass]'; de lo contrario, el método de prueba se omitirá de forma silenciosa. + Type containing '[TestMethod]' should be marked with '[TestClass]', otherwise the test method will be silently ignored. + El tipo que contiene '[TestMethod]' debe marcarse con '[TestClass]'; de lo contrario, el método de prueba se omitirá de forma silenciosa. - Class '{0}' contains test methods and should be marked with '[TestClass]' - La clase '{0}' contiene métodos de prueba y debe marcarse con '[TestClass]' + Type '{0}' contains test methods and should be marked with '[TestClass]' + El tipo '{0}' contiene métodos de prueba y debe marcarse con '[TestClass]' diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf index ceb5ac37c8..2d80aefa8e 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf @@ -19,7 +19,7 @@ The type declaring these methods should also respect the following rules: -The class shouldn't be 'static' -The class should be marked with '[TestClass]' (or a derived attribute) -the class should not be generic. - Les méthodes marquées par « [AssemblyCleanup] » doivent respecter le schéma suivant pour être valides : + Les méthodes marqués par « [AssemblyCleanup] » doivent respecter le schéma suivant pour être valides : -il ne peut pas être déclarée dans une classe générique – il doit être « public » – il doit être « static » @@ -31,9 +31,9 @@ The type declaring these methods should also respect the following rules: Le type déclarant ces méthodes doit également respecter les règles suivantes : Le type doit être une classe --La classe doit être « public » ou « internal » (si le projet de test utilise l’attribut ’[DiscoverInternals]’) --La classe ne doit pas être» ’static » --La classe doit être marquée par « [TestClass] » (ou un attribut dérivé) +-Le type doit être « public » ou « internal » (si le projet de test utilise l’attribut ’[DiscoverInternals]’) +-Le type ne doit pas être» ’static » +-Le type doit être marqué par « [TestClass] » (ou un attribut dérivé) -la classe ne doit pas être générique. @@ -64,7 +64,7 @@ The type declaring these methods should also respect the following rules: -The class shouldn't be 'static' -The class should be marked with '[TestClass]' (or a derived attribute) -the class should not be generic. - Les méthodes marquées par « [AssemblyInitialize] » doivent respecter le schéma suivant pour être valides : + Les méthodes marqués par « [AssemblyInitialize] » doivent respecter le schéma suivant pour être valides : -il ne peut pas être déclarée dans une classe générique – il doit être « public » – il doit être « static » @@ -76,9 +76,9 @@ The type declaring these methods should also respect the following rules: Le type déclarant ces méthodes doit également respecter les règles suivantes : Le type doit être une classe --La classe doit être « public » ou « internal » (si le projet de test utilise l’attribut ’[DiscoverInternals]’) --La classe ne doit pas être» ’static » --La classe doit être marquée par « [TestClass] » (ou un attribut dérivé). +-Le type doit être « public » ou « internal » (si le projet de test utilise l’attribut ’[DiscoverInternals]’) +-Le type ne doit pas être» ’static » +-Le type doit être marqué par « [TestClass] » (ou un attribut dérivé). -la classe ne doit pas être générique. @@ -181,7 +181,7 @@ The type declaring these methods should also respect the following rules: -The class shouldn't be 'static' -If the class is 'sealed', it should be marked with '[TestClass]' (or a derived attribute) -the class should not be generic. - Les méthodes marquées par « [ClassCleanup] » doivent respecter le schéma suivant pour être valides : + Les méthodes marqués par « [ClassCleanup] » doivent respecter le schéma suivant pour être valides : -il ne peut pas être déclarée dans une classe générique si le mode ’InheritanceBehavior’ n’est pas activé – il doit être « public » – il doit être « static » @@ -195,9 +195,9 @@ The type declaring these methods should also respect the following rules: Le type déclarant ces méthodes doit également respecter les règles suivantes : Le type doit être une classe --La classe doit être « public » ou « internal » (si le projet de test utilise l’attribut ’[DiscoverInternals]’) --La classe ne doit pas être « static » --Si la classe est « sealed », elle doit être marquée avec « [TestClass] » (ou un attribut dérivé) +-Le type doit être « public » ou « internal » (si le projet de test utilise l’attribut ’[DiscoverInternals]’) +-Le type ne doit pas être « static » +-Si la classe est « sealed », elle doit être marqué avec « [TestClass] » (ou un attribut dérivé) -la classe ne doit pas être générique. @@ -230,7 +230,7 @@ The type declaring these methods should also respect the following rules: -The class shouldn't be 'static' -If the class is 'sealed', it should be marked with '[TestClass]' (or a derived attribute) -the class should not be generic. - Les méthodes marquées par « [ClassInitialize] » doivent respecter le schéma suivant pour être valides : + Les méthodes marqués par « [ClassInitialize] » doivent respecter le schéma suivant pour être valides : -il ne peut pas être déclarée dans une classe générique si le mode ’InheritanceBehavior’ n’est pas activé. – il doit être « public » – il doit être « static » @@ -244,9 +244,9 @@ The type declaring these methods should also respect the following rules: Le type déclarant ces méthodes doit également respecter les règles suivantes : Le type doit être une classe --La classe doit être « public » ou « internal » (si le projet de test utilise l’attribut ’[DiscoverInternals]’) --La classe ne doit pas être « static » --Si la classe est « sealed », elle doit être marquée avec « [TestClass] » (ou un attribut dérivé). +-Le type doit être « public » ou « internal » (si le projet de test utilise l’attribut ’[DiscoverInternals]’) +-Le type ne doit pas être « static » +-Si la classe est « sealed », elle doit être marqué avec « [TestClass] » (ou un attribut dérivé). -la classe ne doit pas être générique. @@ -524,7 +524,7 @@ Le type doit être une classe It's considered a good practice to have only test classes marked public in a test project. - C’est considéré comme une bonne pratique d’avoir uniquement des classes de test marquées comme publiques dans un projet de test. + C’est considéré comme une bonne pratique d’avoir uniquement des classes de test marqués comme publiques dans un projet de test. @@ -549,7 +549,7 @@ Le type doit être une classe Test class '{0}' should be valid - La classe de test « {0} » doit être valide + Le type de test « {0} » doit être valide @@ -582,7 +582,7 @@ Le type doit être une classe - it should be 'public' (or 'internal' if '[assembly: DiscoverInternals]' attribute is set) - it should not be 'static' (except if it contains only 'AssemblyInitialize' and/or 'AssemblyCleanup' methods) - it should not be generic. - Les classes de test, à savoir les classes marquées par l’attribut « [TestClass] », doivent respecter la disposition suivante pour être considérées comme valides par MSTest : + Les classes de test, à savoir les classes marqués par l’attribut « [TestClass] », doivent respecter la disposition suivante pour être considérées comme valides par MSTest : – Elle doit être « publique » (ou « interne » si l’attribut « [assembly : DiscoverInternals] » est défini) – Elle ne doit pas être « statique » (sauf si elle ne contient que des méthodes « AssemblyInitialize » et/ou « AssemblyCleanup ») – Elle ne doit pas être générique. @@ -595,17 +595,17 @@ Le type doit être une classe Test class should have at least one test method or be 'static' with method(s) marked by '[AssemblyInitialize]' and/or '[AssemblyCleanup]'. - La classe de test doit avoir au moins une méthode de test ou être « statique » avec une ou plusieurs méthodes marquées par « [AssemblyInitialize] » et/ou « [AssemblyCleanup] ». + Le type de test doit avoir au moins une méthode de test ou être « statique » avec une ou plusieurs méthodes marqués par « [AssemblyInitialize] » et/ou « [AssemblyCleanup] ». Test class '{0}' should have at least one test method or be 'static' with method(s) marked by '[AssemblyInitialize]' and/or '[AssemblyCleanup]' - La classe de test '{0}' doit avoir au moins une méthode de test ou être « statique » avec une ou plusieurs méthodes marquées par « [AssemblyInitialize] » et/ou « [AssemblyCleanup] » + Le type de test '{0}' doit avoir au moins une méthode de test ou être « statique » avec une ou plusieurs méthodes marqués par « [AssemblyInitialize] » et/ou « [AssemblyCleanup] » Test class should have test method - La classe de test doit avoir une méthode de test + Le type de test doit avoir une méthode de test @@ -624,7 +624,7 @@ The type declaring these methods should also respect the following rules: -The class should be 'public' or 'internal' (if the test project is using the '[DiscoverInternals]' attribute) -The class shouldn't be 'static' -If the class is 'sealed', it should be marked with '[TestClass]' (or a derived attribute). - Les méthodes marquées par « [TestCleanup] » doivent respecter le schéma suivant pour être valides : + Les méthodes marqués par « [TestCleanup] » doivent respecter le schéma suivant pour être valides : – il doit être « public » – il ne doit pas être « abstract » – il ne doit pas être « async void » @@ -636,9 +636,9 @@ The type declaring these methods should also respect the following rules: Le type déclarant ces méthodes doit également respecter les règles suivantes : Le type doit être une classe --La classe doit être « public » ou « internal » (si le projet de test utilise l’attribut ’[DiscoverInternals]’) --La classe ne doit pas être» ’static » --Si la classe est « sealed », elle doit être marquée avec « [TestClass] » (ou un attribut dérivé). +-Le type doit être « public » ou « internal » (si le projet de test utilise l’attribut ’[DiscoverInternals]’) +-Le type ne doit pas être» ’static » +-Si la classe est « sealed », elle doit être marqué avec « [TestClass] » (ou un attribut dérivé). @@ -683,7 +683,7 @@ The type declaring these methods should also respect the following rules: -The class should be 'public' or 'internal' (if the test project is using the '[DiscoverInternals]' attribute) -The class shouldn't be 'static' -If the class is 'sealed', it should be marked with '[TestClass]' (or a derived attribute). - Les méthodes marquées par [TestInitialize] doivent respecter le schéma suivant pour être valides : + Les méthodes marqués par [TestInitialize] doivent respecter le schéma suivant pour être valides : – il doit être « public » – il ne doit pas être « abstract » – il ne doit pas être « async void » @@ -695,9 +695,9 @@ The type declaring these methods should also respect the following rules: Le type déclarant ces méthodes doit également respecter les règles suivantes : Le type doit être une classe --La classe doit être « public » ou « internal » (si le projet de test utilise l’attribut ’[DiscoverInternals]’) --La classe ne doit pas être» ’static » --Si la classe est « sealed », elle doit être marquée avec « [TestClass] » (ou un attribut dérivé). +-Le type doit être « public » ou « internal » (si le projet de test utilise l’attribut ’[DiscoverInternals]’) +-Le type ne doit pas être» ’static » +-Si la classe est « sealed », elle doit être marqué avec « [TestClass] » (ou un attribut dérivé). @@ -719,7 +719,7 @@ Le type doit être une classe - return type should be 'void', 'Task' or 'ValueTask' - it should not be 'async void' - it should not be a special method (finalizer, operator...). - Les méthodes de test, c’est-à-dire les méthodes marquées de l’attribut « [TestMethod] », doivent respecter la disposition suivante pour être considérées comme valides par MSTest : + Les méthodes de test, c’est-à-dire les méthodes marqués de l’attribut « [TestMethod] », doivent respecter la disposition suivante pour être considérées comme valides par MSTest : – elle doit être « publique » (ou « interne » si l’attribut « [assembly : DiscoverInternals] » est défini) – elle ne doit pas être « statique » – elle peut être générique tant que les paramètres de type peuvent être déduits et que les types d’arguments sont compatibles @@ -736,7 +736,7 @@ Le type doit être une classe Test methods should not be ignored (marked with '[Ignore]'). - Les méthodes de test ne doivent pas être ignorées (marquées avec « [Ignorer] »). + Les méthodes de test ne doivent pas être ignorées (marqués avec « [Ignorer] »). @@ -750,13 +750,13 @@ Le type doit être une classe - Type contaning '[TestMethod]' should be marked with '[TestClass]', otherwise the test method will be silently ignored. - Le type contenant « [TestMethod] » doit être marqué avec « [TestClass] », sans quoi la méthode de test sera ignorée silencieusement. + Type containing '[TestMethod]' should be marked with '[TestClass]', otherwise the test method will be silently ignored. + Le type contenant « [TestMethod] » doit être marqué avec « [TestClass] », sans quoi la méthode de test sera ignorée silencieusement. - Class '{0}' contains test methods and should be marked with '[TestClass]' - La classe « {0} » contient des méthodes de test et doit être marquée avec « [TestClass] » + Type '{0}' contains test methods and should be marked with '[TestClass]' + Le type « {0} » contient des méthodes de test et doit être marqué avec « [TestClass] » @@ -776,17 +776,17 @@ Le type doit être une classe [{0}] can only be set on methods marked with [TestMethod] - [{0}] ne peut être défini que sur les méthodes marquées avec [TestMethod] + [{0}] ne peut être défini que sur les méthodes marqués avec [TestMethod] [{0}] can only be set on methods marked with [TestMethod] - [{0}] ne peut être défini que sur les méthodes marquées avec [TestMethod] + [{0}] ne peut être défini que sur les méthodes marqués avec [TestMethod] The attribute '{0}' which derives from 'ConditionBaseAttribute' should be used only on classes marked with `TestClassAttribute` - L’attribut '{0}' qui dérive de 'ConditionBaseAttribute' doit être utilisé uniquement sur les classes marquées avec 'TestClassAttribute' + L’attribut '{0}' qui dérive de 'ConditionBaseAttribute' doit être utilisé uniquement sur les classes marqués avec 'TestClassAttribute' diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf index 71e58eaf00..2760189435 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf @@ -31,10 +31,10 @@ The type declaring these methods should also respect the following rules: Anche il tipo che dichiara questi metodi deve rispettare le regole seguenti: -Il tipo deve essere una classe --La classe deve essere 'public' o 'internal' (se il progetto di test usa l'attributo '[DiscoverInternals]') --La classe non deve essere 'static' --La classe deve essere contrassegnata con '[TestClass]' (o un attributo derivato) --La classe non deve essere generica. +-Il tipo deve essere 'public' o 'internal' (se il progetto di test usa l'attributo '[DiscoverInternals]') +-Il tipo non deve essere 'static' +-Il tipo deve essere contrassegnata con '[TestClass]' (o un attributo derivato) +-Il tipo non deve essere generica. @@ -76,10 +76,10 @@ The type declaring these methods should also respect the following rules: Anche il tipo che dichiara questi metodi deve rispettare le regole seguenti: -Il tipo deve essere una classe --La classe deve essere 'public' o 'internal' (se il progetto di test usa l'attributo '[DiscoverInternals]') --La classe non deve essere 'static' --La classe deve essere contrassegnata con '[TestClass]' (o un attributo derivato). --La classe non deve essere generica. +-Il tipo deve essere 'public' o 'internal' (se il progetto di test usa l'attributo '[DiscoverInternals]') +-Il tipo non deve essere 'static' +-Il tipo deve essere contrassegnata con '[TestClass]' (o un attributo derivato). +-Il tipo non deve essere generica. @@ -195,10 +195,10 @@ The type declaring these methods should also respect the following rules: Anche il tipo che dichiara questi metodi deve rispettare le regole seguenti: -Il tipo deve essere una classe --La classe deve essere 'public' o 'internal' (se il progetto di test usa l'attributo '[DiscoverInternals]') --La classe non deve essere 'static' +-Il tipo deve essere 'public' o 'internal' (se il progetto di test usa l'attributo '[DiscoverInternals]') +-Il tipo non deve essere 'static' -Se la classe è 'sealed', deve essere contrassegnata con '[TestClass]' (o un attributo derivato) --La classe non deve essere generica. +-Il tipo non deve essere generica. @@ -244,10 +244,10 @@ The type declaring these methods should also respect the following rules: Anche il tipo che dichiara questi metodi deve rispettare le regole seguenti: -Il tipo deve essere una classe --La classe deve essere 'public' o 'internal' (se il progetto di test usa l'attributo '[DiscoverInternals]') --La classe non deve essere 'static' +-Il tipo deve essere 'public' o 'internal' (se il progetto di test usa l'attributo '[DiscoverInternals]') +-Il tipo non deve essere 'static' -Se la classe è 'sealed', deve essere contrassegnata con '[TestClass]' (o un attributo derivato) --La classe non deve essere generica. +-Il tipo non deve essere generica. @@ -549,7 +549,7 @@ Anche il tipo che dichiara questi metodi deve rispettare le regole seguenti: Test class '{0}' should be valid - La classe di test '{0}' deve essere valida + Il tipo di test '{0}' deve essere valida @@ -595,17 +595,17 @@ Anche il tipo che dichiara questi metodi deve rispettare le regole seguenti: Test class should have at least one test method or be 'static' with method(s) marked by '[AssemblyInitialize]' and/or '[AssemblyCleanup]'. - La classe di test deve avere almeno un metodo di test o essere 'static' con metodi contrassegnati da '[AssemblyInitialize]' e/o '[AssemblyCleanup]'. + Il tipo di test deve avere almeno un metodo di test o essere 'static' con metodi contrassegnati da '[AssemblyInitialize]' e/o '[AssemblyCleanup]'. Test class '{0}' should have at least one test method or be 'static' with method(s) marked by '[AssemblyInitialize]' and/or '[AssemblyCleanup]' - La classe di test '{0}' deve avere almeno un metodo di test o essere 'static' con metodi contrassegnati da '[AssemblyInitializate]' e/o '[AssemblyCleanup]' + Il tipo di test '{0}' deve avere almeno un metodo di test o essere 'static' con metodi contrassegnati da '[AssemblyInitializate]' e/o '[AssemblyCleanup]' Test class should have test method - La classe di test deve avere un metodo di test + Il tipo di test deve avere un metodo di test @@ -636,8 +636,8 @@ The type declaring these methods should also respect the following rules: Anche il tipo che dichiara questi metodi deve rispettare le regole seguenti: -Il tipo deve essere una classe --La classe deve essere 'public' o 'internal' (se il progetto di test usa l'attributo '[DiscoverInternals]') --La classe non deve essere 'static' +-Il tipo deve essere 'public' o 'internal' (se il progetto di test usa l'attributo '[DiscoverInternals]') +-Il tipo non deve essere 'static' -Se la classe è 'sealed', deve essere contrassegnata con '[TestClass]' (o un attributo derivato). @@ -695,8 +695,8 @@ The type declaring these methods should also respect the following rules: Anche il tipo che dichiara questi metodi deve rispettare le regole seguenti: -Il tipo deve essere una classe --La classe deve essere 'public' o 'internal' (se il progetto di test usa l'attributo '[DiscoverInternals]') --La classe non deve essere 'static' +-Il tipo deve essere 'public' o 'internal' (se il progetto di test usa l'attributo '[DiscoverInternals]') +-Il tipo non deve essere 'static' -Se la classe è 'sealed', deve essere contrassegnata con '[TestClass]' (o un attributo derivato). @@ -750,13 +750,13 @@ Anche il tipo che dichiara questi metodi deve rispettare le regole seguenti: - Type contaning '[TestMethod]' should be marked with '[TestClass]', otherwise the test method will be silently ignored. - Il tipo contenente '[TestMethod]' deve essere contrassegnato con '[TestClass]', altrimenti il metodo di test verrà ignorato automaticamente. + Type containing '[TestMethod]' should be marked with '[TestClass]', otherwise the test method will be silently ignored. + Il tipo contenente '[TestMethod]' deve essere contrassegnato con '[TestClass]', altrimenti il metodo di test verrà ignorato automaticamente. - Class '{0}' contains test methods and should be marked with '[TestClass]' - La classe '{0}' contiene metodi di test e deve essere contrassegnata come '[TestClass]' + Type '{0}' contains test methods and should be marked with '[TestClass]' + Il tipo '{0}' contiene metodi di test e deve essere contrassegnata come '[TestClass]' diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf index 7c6f99794c..e374a94b87 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf @@ -20,7 +20,7 @@ The type declaring these methods should also respect the following rules: -The class should be marked with '[TestClass]' (or a derived attribute) -the class should not be generic. '[AssemblyCleanup]' でマークされたメソッドを有効にするには、次のレイアウトに従う必要があります: -- ジェネリック クラスで宣言することはできません +- ジェネリック 型で宣言することはできません - 'public' である必要があります - 'static' である必要があります - 'async void' にすることはできません @@ -30,11 +30,11 @@ The type declaring these methods should also respect the following rules: - 戻り値の型が 'void'、'Task'、または 'ValueTask' である必要があります これらのメソッドを宣言する型も、次の規則に従う必要があります: -- 型はクラスである必要があります -- クラスは 'public' または 'internal' である必要があります (テスト プロジェクトが '[DiscoverInternals]' 属性を使用している場合) -- クラスを 'static' にすることはできません -- クラスは '[TestClass]' (または派生属性) でマークする必要があります -- クラスをジェネリックにすることはできません。 +- 型は型である必要があります +- 型は 'public' または 'internal' である必要があります (テスト プロジェクトが '[DiscoverInternals]' 属性を使用している場合) +- 型を 'static' にすることはできません +- 型は '[TestClass]' (または派生属性) でマークする必要があります +- 型をジェネリックにすることはできません。 @@ -65,7 +65,7 @@ The type declaring these methods should also respect the following rules: -The class should be marked with '[TestClass]' (or a derived attribute) -the class should not be generic. '[AssemblyInitialize]' でマークされたメソッドを有効にするには、次のレイアウトに従う必要があります: -- ジェネリック クラスで宣言することはできません +- ジェネリック 型で宣言することはできません - 'public' である必要があります - 'static' である必要があります - 'async void' にすることはできません @@ -75,11 +75,11 @@ The type declaring these methods should also respect the following rules: - 戻り値の型が 'void'、'Task'、または 'ValueTask' である必要があります これらのメソッドを宣言する型も、次の規則に従う必要があります: -- 型はクラスである必要があります -- クラスは 'public' または 'internal' である必要があります (テスト プロジェクトが '[DiscoverInternals]' 属性を使用している場合) -- クラスを 'static' にすることはできません -- クラスは '[TestClass]' (または派生属性) でマークする必要があります -- クラスをジェネリックにすることはできません。 +- 型は型である必要があります +- 型は 'public' または 'internal' である必要があります (テスト プロジェクトが '[DiscoverInternals]' 属性を使用している場合) +- 型を 'static' にすることはできません +- 型は '[TestClass]' (または派生属性) でマークする必要があります +- 型をジェネリックにすることはできません。 @@ -182,7 +182,7 @@ The type declaring these methods should also respect the following rules: -If the class is 'sealed', it should be marked with '[TestClass]' (or a derived attribute) -the class should not be generic. '[ClassCleanup]' でマークされたメソッドを有効にするには、次のレイアウトに従う必要があります: -- 'InheritanceBehavior' モードが設定されていないと、ジェネリック クラスで宣言できません +- 'InheritanceBehavior' モードが設定されていないと、ジェネリック 型で宣言できません - 'public' である必要があります - 'static' である必要があります - 'async void' にすることはできません @@ -190,15 +190,15 @@ The type declaring these methods should also respect the following rules: - ジェネリックにすることはできません - パラメーターを受け取らないか、'TestContext' 型の 1 つのパラメーターを受け取る必要があります - 戻り値の型が 'void'、'Task'、または 'ValueTask' である必要があります -- クラスが 'abstract' である場合は 'InheritanceBehavior.BeforeEachDerivedClass' 属性パラメーターを指定する必要があります -- クラスが 'sealed' である場合は 'InheritanceBehavior.BeforeEachDerivedClass' 属性パラメーターを指定しない必要があります +- 型が 'abstract' である場合は 'InheritanceBehavior.BeforeEachDerivedClass' 属性パラメーターを指定する必要があります +- 型が 'sealed' である場合は 'InheritanceBehavior.BeforeEachDerivedClass' 属性パラメーターを指定しない必要があります これらのメソッドを宣言する型も、次の規則に従う必要があります: -- 型はクラスである必要があります -- クラスは 'public' または 'internal' である必要があります (テスト プロジェクトが '[DiscoverInternals]' 属性を使用している場合) -- クラスを 'static' にすることはできません -- クラスが 'sealed' の場合は、'[TestClass]' (または派生属性) でマークする必要があります -- クラスをジェネリックにすることはできません。 +- 型は型である必要があります +- 型は 'public' または 'internal' である必要があります (テスト プロジェクトが '[DiscoverInternals]' 属性を使用している場合) +- 型を 'static' にすることはできません +- 型が 'sealed' の場合は、'[TestClass]' (または派生属性) でマークする必要があります +- 型をジェネリックにすることはできません。 @@ -231,7 +231,7 @@ The type declaring these methods should also respect the following rules: -If the class is 'sealed', it should be marked with '[TestClass]' (or a derived attribute) -the class should not be generic. '[ClassInitialize]' でマークされたメソッドを有効にするには、次のレイアウトに従う必要があります: -- 'InheritanceBehavior' モードが設定されていないと、ジェネリック クラスで宣言できません +- 'InheritanceBehavior' モードが設定されていないと、ジェネリック 型で宣言できません - 'public' である必要があります - 'static' である必要があります - 'async void' にすることはできません @@ -239,15 +239,15 @@ The type declaring these methods should also respect the following rules: - ジェネリックにすることはできません - 'TestContext' 型のパラメーターを 1 つ受け取る必要があります - 戻り値の型が 'void'、'Task'、または 'ValueTask' である必要があります -- クラスが 'abstract' である場合は 'InheritanceBehavior.BeforeEachDerivedClass' 属性パラメーターーを指定する必要があります -- クラスが 'sealed' である場合は 'InheritanceBehavior.BeforeEachDerivedClass' 属性パラメーターーを指定しない必要があります +- 型が 'abstract' である場合は 'InheritanceBehavior.BeforeEachDerivedClass' 属性パラメーターーを指定する必要があります +- 型が 'sealed' である場合は 'InheritanceBehavior.BeforeEachDerivedClass' 属性パラメーターーを指定しない必要があります これらのメソッドを宣言する型も、次の規則に従う必要があります: -- 型はクラスである必要があります -- クラスは 'public' または 'internal' である必要があります (テスト プロジェクトが '[DiscoverInternals]' 属性を使用している場合) -- クラスを 'static' にすることはできません -- クラスが 'sealed' の場合は、'[TestClass]' (または派生属性) でマークする必要があります -- クラスをジェネリックにすることはできません。 +- 型は型である必要があります +- 型は 'public' または 'internal' である必要があります (テスト プロジェクトが '[DiscoverInternals]' 属性を使用している場合) +- 型を 'static' にすることはできません +- 型が 'sealed' の場合は、'[TestClass]' (または派生属性) でマークする必要があります +- 型をジェネリックにすることはできません。 @@ -333,7 +333,7 @@ The type declaring these methods should also respect the following rules: Member '{0}' already exists in the base class - メンバー '{0}' は既に基本クラスに存在します + メンバー '{0}' は既に基本型に存在します @@ -524,7 +524,7 @@ The type declaring these methods should also respect the following rules: It's considered a good practice to have only test classes marked public in a test project. - テスト プロジェクトでは、テスト クラスのみをパブリックとしてマークすることをお勧めします。 + テスト プロジェクトでは、テスト 型のみをパブリックとしてマークすることをお勧めします。 @@ -534,7 +534,7 @@ The type declaring these methods should also respect the following rules: Public types should be test classes - パブリック型はテスト クラスである必要があります + パブリック型はテスト 型である必要があります @@ -549,7 +549,7 @@ The type declaring these methods should also respect the following rules: Test class '{0}' should be valid - テスト クラス '{0}' は有効である必要があります + テスト 型 '{0}' は有効である必要があります @@ -564,7 +564,7 @@ The type declaring these methods should also respect the following rules: Without using 'ClassCleanupBehavior.EndOfClass', the '[ClassCleanup]' will by default be run at the end of the assembly and not at the end of the class. - 'ClassCleanupBehavior.EndOfClass' を使用しない場合、'[ClassCleanup]' は既定でアセンブリの最後に実行され、クラスの最後には実行されません。 + 'ClassCleanupBehavior.EndOfClass' を使用しない場合、'[ClassCleanup]' は既定でアセンブリの最後に実行され、型の最後には実行されません。 @@ -582,7 +582,7 @@ The type declaring these methods should also respect the following rules: - it should be 'public' (or 'internal' if '[assembly: DiscoverInternals]' attribute is set) - it should not be 'static' (except if it contains only 'AssemblyInitialize' and/or 'AssemblyCleanup' methods) - it should not be generic. - テスト クラス ('[TestClass]' 属性でマークされたクラス) は、MSTest によって有効と見なされるように、次のレイアウトを考慮する必要があります: + テスト 型 ('[TestClass]' 属性でマークされた型) は、MSTest によって有効と見なされるように、次のレイアウトを考慮する必要があります: - 'public' である必要があります ('[assembly: DiscoverInternals]' 属性が設定されている場合は 'internal' である必要があります) - 'static' にすることはできません ('AssemblyInitialize' メソッドおよび/または 'AssemblyCleanup' メソッドのみが含まれる場合は除きます) - ジェネリックにすることはできません。 @@ -590,22 +590,22 @@ The type declaring these methods should also respect the following rules: Test classes should have valid layout - テスト クラスには有効なレイアウトが必要です + テスト 型には有効なレイアウトが必要です Test class should have at least one test method or be 'static' with method(s) marked by '[AssemblyInitialize]' and/or '[AssemblyCleanup]'. - テスト クラスには、少なくとも 1 つのテスト メソッドがあるか、'[AssemblyInitialize]' または '[AssemblyCleanup]' によってマークされたメソッドを含む 'static' である必要があります。 + テスト 型には、少なくとも 1 つのテスト メソッドがあるか、'[AssemblyInitialize]' または '[AssemblyCleanup]' によってマークされたメソッドを含む 'static' である必要があります。 Test class '{0}' should have at least one test method or be 'static' with method(s) marked by '[AssemblyInitialize]' and/or '[AssemblyCleanup]' - テスト クラス '{0}' には、少なくとも 1 つのテスト メソッドがあるか、'[AssemblyInitialize]' または '[AssemblyCleanup]' によってマークされたメソッドを含む 'static' である必要があります。 + テスト 型 '{0}' には、少なくとも 1 つのテスト メソッドがあるか、'[AssemblyInitialize]' または '[AssemblyCleanup]' によってマークされたメソッドを含む 'static' である必要があります。 Test class should have test method - テスト クラスにはテスト メソッドが必要です + テスト 型にはテスト メソッドが必要です @@ -635,10 +635,10 @@ The type declaring these methods should also respect the following rules: - 戻り値の型が 'void'、'Task'、または 'ValueTask' である必要があります これらのメソッドを宣言する型も、次の規則に従う必要があります: -- 型はクラスである必要があります -- クラスは 'public' または 'internal' である必要があります (テスト プロジェクトが '[DiscoverInternals]' 属性を使用している場合) -- クラスを 'static' にすることはできません --クラスが 'sealed' の場合は、'[TestClass]' (または派生属性) でマークする必要があります。 +- 型は型である必要があります +- 型は 'public' または 'internal' である必要があります (テスト プロジェクトが '[DiscoverInternals]' 属性を使用している場合) +- 型を 'static' にすることはできません +-型が 'sealed' の場合は、'[TestClass]' (または派生属性) でマークする必要があります。 @@ -694,10 +694,10 @@ The type declaring these methods should also respect the following rules: - 戻り値の型が 'void'、'Task'、または 'ValueTask' である必要があります これらのメソッドを宣言する型も、次の規則に従う必要があります: -- 型はクラスである必要があります -- クラスは 'public' または 'internal' である必要があります (テスト プロジェクトが '[DiscoverInternals]' 属性を使用している場合) -- クラスを 'static' にすることはできません --クラスが 'sealed' の場合は、'[TestClass]' (または派生属性) でマークする必要があります。 +- 型は型である必要があります +- 型は 'public' または 'internal' である必要があります (テスト プロジェクトが '[DiscoverInternals]' 属性を使用している場合) +- 型を 'static' にすることはできません +-型が 'sealed' の場合は、'[TestClass]' (または派生属性) でマークする必要があります。 @@ -750,13 +750,13 @@ The type declaring these methods should also respect the following rules: - Type contaning '[TestMethod]' should be marked with '[TestClass]', otherwise the test method will be silently ignored. - 連続する型 '[TestMethod]' は '[TestClass]' でマークする必要があります。それ以外の場合、テスト メソッドは暗黙的に無視されます。 + Type containing '[TestMethod]' should be marked with '[TestClass]', otherwise the test method will be silently ignored. + 連続する型 '[TestMethod]' は '[TestClass]' でマークする必要があります。それ以外の場合、テスト メソッドは暗黙的に無視されます。 - Class '{0}' contains test methods and should be marked with '[TestClass]' - クラス '{0}' にはテスト メソッドが含まれており、'[TestClass]' でマークする必要があります + Type '{0}' contains test methods and should be marked with '[TestClass]' + 型 '{0}' にはテスト メソッドが含まれており、'[TestClass]' でマークする必要があります @@ -786,12 +786,12 @@ The type declaring these methods should also respect the following rules: The attribute '{0}' which derives from 'ConditionBaseAttribute' should be used only on classes marked with `TestClassAttribute` - 'ConditionBaseAttribute' から派生する属性 '{0}' は、'TestClassAttribute' でマークされたクラスでのみ使用する必要があります + 'ConditionBaseAttribute' から派生する属性 '{0}' は、'TestClassAttribute' でマークされた型でのみ使用する必要があります Use 'ConditionBaseAttribute' on test classes - テスト クラスで 'ConditionBaseAttribute' を使用する + テスト 型で 'ConditionBaseAttribute' を使用する @@ -811,12 +811,12 @@ The type declaring these methods should also respect the following rules: '[DeploymentItem]' can be specified only on test class or test method - '[DeploymentItem]' は、テスト クラスまたはテスト メソッドでのみ指定できます + '[DeploymentItem]' は、テスト 型またはテスト メソッドでのみ指定できます '[DeploymentItem]' can be specified only on test class or test method - '[DeploymentItem]' は、テスト クラスまたはテスト メソッドでのみ指定できます + '[DeploymentItem]' は、テスト 型またはテスト メソッドでのみ指定できます diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf index b300258adb..bed02c35ee 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf @@ -20,7 +20,7 @@ The type declaring these methods should also respect the following rules: -The class should be marked with '[TestClass]' (or a derived attribute) -the class should not be generic. '[AssemblyCleanup]'으로 표시된 메서드가 유효하려면 다음 레이아웃을 따라야 합니다. -- 제네릭 클래스에서 선언할 수 없습니다. +- 제네릭 형식에서 선언할 수 없습니다. - 'public'이어야 합니다. - 'static'이어야 합니다. - 'async void'가 아니어야 합니다. @@ -30,11 +30,11 @@ The type declaring these methods should also respect the following rules: - 반환 형식은 'void', 'Task' 또는 'ValueTask'여야 합니다. 이러한 메서드를 선언하는 형식은 다음 규칙도 준수해야 합니다. -- 형식은 클래스여야 합니다. -- 클래스는 'public' 또는 'internal'이어야 합니다(테스트 프로젝트에서 '[DiscoverInternals]' 특성을 사용하는 경우). -- 클래스는 'static'이 되어서는 안 됩니다. -- 클래스는 '[TestClass]'(또는 파생 특성)로 표시되어야 합니다. -- 클래스는 제네릭이 아니어야 합니다. +- 형식은 형식여야 합니다. +- 형식는 'public' 또는 'internal'이어야 합니다(테스트 프로젝트에서 '[DiscoverInternals]' 특성을 사용하는 경우). +- 형식는 'static'이 되어서는 안 됩니다. +- 형식는 '[TestClass]'(또는 파생 특성)로 표시되어야 합니다. +- 형식는 제네릭이 아니어야 합니다. @@ -65,7 +65,7 @@ The type declaring these methods should also respect the following rules: -The class should be marked with '[TestClass]' (or a derived attribute) -the class should not be generic. '[AssemblyInitialize]'로 표시된 메서드가 유효하려면 다음 레이아웃을 따라야 합니다. --제네릭 클래스에서 선언할 수 없습니다. +-제네릭 형식에서 선언할 수 없습니다. - 'public'이어야 합니다. - 'static'이어야 합니다. - 'async void'가 아니어야 합니다. @@ -75,11 +75,11 @@ The type declaring these methods should also respect the following rules: - 반환 형식은 'void', 'Task' 또는 'ValueTask'여야 합니다. 이러한 메서드를 선언하는 형식은 다음 규칙도 준수해야 합니다. --형식은 클래스여야 합니다. --클래스는 'public' 또는 'internal'이어야 합니다(테스트 프로젝트에서 '[DiscoverInternals]' 특성을 사용하는 경우). --클래스는 'static'이 되어서는 안 됩니다. --클래스는 '[TestClass]'(또는 파생 특성)로 표시되어야 합니다. --클래스는 제네릭이 아니어야 합니다. +-형식은 형식여야 합니다. +-형식는 'public' 또는 'internal'이어야 합니다(테스트 프로젝트에서 '[DiscoverInternals]' 특성을 사용하는 경우). +-형식는 'static'이 되어서는 안 됩니다. +-형식는 '[TestClass]'(또는 파생 특성)로 표시되어야 합니다. +-형식는 제네릭이 아니어야 합니다. @@ -182,7 +182,7 @@ The type declaring these methods should also respect the following rules: -If the class is 'sealed', it should be marked with '[TestClass]' (or a derived attribute) -the class should not be generic. '[ClassCleanup]'으로 표시된 메서드가 유효하려면 다음 레이아웃을 따라야 합니다. -- 'InheritanceBehavior' 모드가 설정되지 않은 제네릭 클래스에서 선언할 수 없습니다. +- 'InheritanceBehavior' 모드가 설정되지 않은 제네릭 형식에서 선언할 수 없습니다. - 'public'이어야 합니다. - 'static'이어야 합니다. - 'async void'가 아니어야 합니다. @@ -190,15 +190,15 @@ The type declaring these methods should also respect the following rules: - 제네릭이 아니어야 합니다. - 매개 변수를 사용하거나 'TestContext' 형식의 단일 매개 변수를 사용해서는 안 됩니다. - 반환 형식은 'void', 'Task' 또는 'ValueTask'여야 합니다. -- 클래스가 'abstract'인 경우 'InheritanceBehavior.BeforeEachDerivedClass' 특성 매개 변수를 지정해야 합니다. -- 클래스가 'sealed'인 경우 'InheritanceBehavior.BeforeEachDerivedClass' 특성 매개 변수를 지정하면 안 됩니다. +- 형식가 'abstract'인 경우 'InheritanceBehavior.BeforeEachDerivedClass' 특성 매개 변수를 지정해야 합니다. +- 형식가 'sealed'인 경우 'InheritanceBehavior.BeforeEachDerivedClass' 특성 매개 변수를 지정하면 안 됩니다. 이러한 메서드를 선언하는 형식은 다음 규칙도 준수해야 합니다. -- 형식은 클래스여야 합니다. -- 클래스는 'public' 또는 'internal'이어야 합니다(테스트 프로젝트에서 '[DiscoverInternals]' 특성을 사용하는 경우). -- 클래스는 'static'이 되어서는 안 됩니다. -- 클래스가 'sealed'인 경우 '[TestClass]'(또는 파생 특성)로 표시되어야 합니다. -- 클래스는 제네릭이 아니어야 합니다. +- 형식은 형식여야 합니다. +- 형식는 'public' 또는 'internal'이어야 합니다(테스트 프로젝트에서 '[DiscoverInternals]' 특성을 사용하는 경우). +- 형식는 'static'이 되어서는 안 됩니다. +- 형식가 'sealed'인 경우 '[TestClass]'(또는 파생 특성)로 표시되어야 합니다. +- 형식는 제네릭이 아니어야 합니다. @@ -231,7 +231,7 @@ The type declaring these methods should also respect the following rules: -If the class is 'sealed', it should be marked with '[TestClass]' (or a derived attribute) -the class should not be generic. '[ClassInitialize]'로 표시된 메서드가 유효하려면 다음 레이아웃을 따라야 합니다. --'InheritanceBehavior' 모드가 설정되지 않은 제네릭 클래스에서 선언할 수 없습니다. +-'InheritanceBehavior' 모드가 설정되지 않은 제네릭 형식에서 선언할 수 없습니다. - 'public'이어야 합니다. - 'static'이어야 합니다. - 'async void'가 아니어야 합니다. @@ -239,15 +239,15 @@ The type declaring these methods should also respect the following rules: - 제네릭이 아니어야 합니다. - 'TestContext' 형식의 매개 변수를 하나 사용해야 합니다. - 반환 형식은 'void', 'Task' 또는 'ValueTask'여야 합니다. -- 클래스가 'abstract'인 경우 'InheritanceBehavior.BeforeEachDerivedClass' 특성 매개 변수를 지정해야 합니다. -- 클래스가 'sealed'인 경우 'InheritanceBehavior.BeforeEachDerivedClass' 특성 매개 변수를 지정하면 안 됩니다. +- 형식가 'abstract'인 경우 'InheritanceBehavior.BeforeEachDerivedClass' 특성 매개 변수를 지정해야 합니다. +- 형식가 'sealed'인 경우 'InheritanceBehavior.BeforeEachDerivedClass' 특성 매개 변수를 지정하면 안 됩니다. 이러한 메서드를 선언하는 형식은 다음 규칙도 준수해야 합니다. --형식은 클래스여야 합니다. --클래스는 'public' 또는 'internal'이어야 합니다(테스트 프로젝트에서 '[DiscoverInternals]' 특성을 사용하는 경우). --클래스는 'static'이 되어서는 안 됩니다. --클래스가 'sealed'인 경우 '[TestClass]'(또는 파생 특성)로 표시되어야 합니다. --클래스는 제네릭이 아니어야 합니다. +-형식은 형식여야 합니다. +-형식는 'public' 또는 'internal'이어야 합니다(테스트 프로젝트에서 '[DiscoverInternals]' 특성을 사용하는 경우). +-형식는 'static'이 되어서는 안 됩니다. +-형식가 'sealed'인 경우 '[TestClass]'(또는 파생 특성)로 표시되어야 합니다. +-형식는 제네릭이 아니어야 합니다. @@ -333,7 +333,7 @@ The type declaring these methods should also respect the following rules: Member '{0}' already exists in the base class - 멤버 '{0}'이(가) 기본 클래스에 이미 있습니다. + 멤버 '{0}'이(가) 기본 형식에 이미 있습니다. @@ -524,7 +524,7 @@ The type declaring these methods should also respect the following rules: It's considered a good practice to have only test classes marked public in a test project. - 테스트 프로젝트에서 공용으로 표시된 테스트 클래스만 사용하는 것이 좋습니다. + 테스트 프로젝트에서 공용으로 표시된 테스트 형식만 사용하는 것이 좋습니다. @@ -534,7 +534,7 @@ The type declaring these methods should also respect the following rules: Public types should be test classes - 공용 형식은 테스트 클래스여야 합니다. + 공용 형식은 테스트 형식여야 합니다. @@ -549,7 +549,7 @@ The type declaring these methods should also respect the following rules: Test class '{0}' should be valid - 테스트 클래스 '{0}'은(는) 유효해야 합니다. + 테스트 형식 '{0}'은(는) 유효해야 합니다. @@ -564,7 +564,7 @@ The type declaring these methods should also respect the following rules: Without using 'ClassCleanupBehavior.EndOfClass', the '[ClassCleanup]' will by default be run at the end of the assembly and not at the end of the class. - 'ClassCleanupBehavior.EndOfClass'를 사용하지 않으면 '[ClassCleanup]'은 기본적으로 클래스의 끝이 아니라 어셈블리의 끝에서 실행됩니다. + 'ClassCleanupBehavior.EndOfClass'를 사용하지 않으면 '[ClassCleanup]'은 기본적으로 형식의 끝이 아니라 어셈블리의 끝에서 실행됩니다. @@ -582,7 +582,7 @@ The type declaring these methods should also respect the following rules: - it should be 'public' (or 'internal' if '[assembly: DiscoverInternals]' attribute is set) - it should not be 'static' (except if it contains only 'AssemblyInitialize' and/or 'AssemblyCleanup' methods) - it should not be generic. - '[TestClass]' 특성으로 표시된 클래스인 테스트 클래스는 MSTest에서 유효하다고 간주하려면 다음 레이아웃을 준수해야 합니다. + '[TestClass]' 특성으로 표시된 형식인 테스트 형식는 MSTest에서 유효하다고 간주하려면 다음 레이아웃을 준수해야 합니다. - 'public'(또는 '[assembly: DiscoverInternals]' 특성이 설정된 경우 'internal')이어야 합니다. - 'static'이 아니어야 합니다('AssemblyInitialize' 및/또는 'AssemblyCleanup' 메서드만 포함된 경우 제외). - 제네릭이 아니어야 합니다. @@ -590,22 +590,22 @@ The type declaring these methods should also respect the following rules: Test classes should have valid layout - 테스트 클래스에는 유효한 레이아웃이 있어야 합니다. + 테스트 형식에는 유효한 레이아웃이 있어야 합니다. Test class should have at least one test method or be 'static' with method(s) marked by '[AssemblyInitialize]' and/or '[AssemblyCleanup]'. - 테스트 클래스에는 하나 이상의 테스트 메서드가 있거나 '[AssemblyInitialize]' 및/또는 '[AssemblyCleanup]'으로 표시된 메서드가 있는 'static'이어야 합니다. + 테스트 형식에는 하나 이상의 테스트 메서드가 있거나 '[AssemblyInitialize]' 및/또는 '[AssemblyCleanup]'으로 표시된 메서드가 있는 'static'이어야 합니다. Test class '{0}' should have at least one test method or be 'static' with method(s) marked by '[AssemblyInitialize]' and/or '[AssemblyCleanup]' - 테스트 클래스 '{0}'에는 하나 이상의 테스트 메서드가 있거나 '[AssemblyInitialize]' 및/또는 '[AssemblyCleanup]'으로 표시된 메서드가 있는 'static'이어야 합니다. + 테스트 형식 '{0}'에는 하나 이상의 테스트 메서드가 있거나 '[AssemblyInitialize]' 및/또는 '[AssemblyCleanup]'으로 표시된 메서드가 있는 'static'이어야 합니다. Test class should have test method - 테스트 클래스에는 테스트 메서드가 있어야 합니다. + 테스트 형식에는 테스트 메서드가 있어야 합니다. @@ -635,10 +635,10 @@ The type declaring these methods should also respect the following rules: - 반환 형식은 'void', 'Task' 또는 'ValueTask'여야 합니다. 이러한 메서드를 선언하는 형식은 다음 규칙도 준수해야 합니다. --형식은 클래스여야 합니다. --클래스는 'public' 또는 'internal'이어야 합니다(테스트 프로젝트에서 '[DiscoverInternals]' 특성을 사용하는 경우). --클래스는 'static'이 되어서는 안 됩니다. --클래스가 'sealed'인 경우 '[TestClass]'(또는 파생 특성)로 표시되어야 합니다. +-형식은 형식여야 합니다. +-형식는 'public' 또는 'internal'이어야 합니다(테스트 프로젝트에서 '[DiscoverInternals]' 특성을 사용하는 경우). +-형식는 'static'이 되어서는 안 됩니다. +-형식가 'sealed'인 경우 '[TestClass]'(또는 파생 특성)로 표시되어야 합니다. @@ -694,10 +694,10 @@ The type declaring these methods should also respect the following rules: - 반환 형식은 'void', 'Task' 또는 'ValueTask'여야 합니다. 이러한 메서드를 선언하는 형식은 다음 규칙도 준수해야 합니다. --형식은 클래스여야 합니다. --클래스는 'public' 또는 'internal'이어야 합니다(테스트 프로젝트에서 '[DiscoverInternals]' 특성을 사용하는 경우). --클래스는 'static'이 되어서는 안 됩니다. --클래스가 'sealed'인 경우 '[TestClass]'(또는 파생 특성)로 표시되어야 합니다. +-형식은 형식여야 합니다. +-형식는 'public' 또는 'internal'이어야 합니다(테스트 프로젝트에서 '[DiscoverInternals]' 특성을 사용하는 경우). +-형식는 'static'이 되어서는 안 됩니다. +-형식가 'sealed'인 경우 '[TestClass]'(또는 파생 특성)로 표시되어야 합니다. @@ -750,13 +750,13 @@ The type declaring these methods should also respect the following rules: - Type contaning '[TestMethod]' should be marked with '[TestClass]', otherwise the test method will be silently ignored. - '[TestMethod]'를 포함하는 유형은 '[TestClass]'로 표시되어야 합니다. 그렇지 않으면 테스트 메서드가 자동으로 무시됩니다. + Type containing '[TestMethod]' should be marked with '[TestClass]', otherwise the test method will be silently ignored. + '[TestMethod]'를 포함하는 유형은 '[TestClass]'로 표시되어야 합니다. 그렇지 않으면 테스트 메서드가 자동으로 무시됩니다. - Class '{0}' contains test methods and should be marked with '[TestClass]' - '{0}' 클래스에는 테스트 메서드가 포함되어 있으며 '[TestClass]'로 표시되어야 합니다. + Type '{0}' contains test methods and should be marked with '[TestClass]' + '{0}' 형식에는 테스트 메서드가 포함되어 있으며 '[TestClass]'로 표시되어야 합니다. @@ -786,12 +786,12 @@ The type declaring these methods should also respect the following rules: The attribute '{0}' which derives from 'ConditionBaseAttribute' should be used only on classes marked with `TestClassAttribute` - 'ConditionBaseAttribute'에서 파생되는 '{0}' 특성은 'TestClassAttribute'로 표시된 클래스에서만 사용해야 합니다. + 'ConditionBaseAttribute'에서 파생되는 '{0}' 특성은 'TestClassAttribute'로 표시된 형식에서만 사용해야 합니다. Use 'ConditionBaseAttribute' on test classes - 테스트 클래스에 'ConditionBaseAttribute' 사용 + 테스트 형식에 'ConditionBaseAttribute' 사용 @@ -811,12 +811,12 @@ The type declaring these methods should also respect the following rules: '[DeploymentItem]' can be specified only on test class or test method - '[DeploymentItem]'은(는) 테스트 클래스 또는 테스트 메서드에만 지정할 수 있습니다. + '[DeploymentItem]'은(는) 테스트 형식 또는 테스트 메서드에만 지정할 수 있습니다. '[DeploymentItem]' can be specified only on test class or test method - '[DeploymentItem]'은(는) 테스트 클래스 또는 테스트 메서드에만 지정할 수 있습니다. + '[DeploymentItem]'은(는) 테스트 형식 또는 테스트 메서드에만 지정할 수 있습니다. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf index 113da1e59f..3e34f669a6 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf @@ -76,10 +76,10 @@ The type declaring these methods should also respect the following rules: Typ deklarujący te metody powinien również przestrzegać następujących reguł: — Typ powinien być klasą -— Klasa powinna mieć wartość „public” lub „internal” (jeśli projekt testowy używa atrybutu „[DiscoverInternals]”) -— Klasa nie powinna mieć wartości „static” -— Klasa powinna być oznaczona znakiem „[TestClass]” (lub atrybutem pochodnym) -— Klasa nie powinna być ogólna. +— Typ powinna mieć wartość „public” lub „internal” (jeśli projekt testowy używa atrybutu „[DiscoverInternals]”) +— Typ nie powinna mieć wartości „static” +— Typ powinna być oznaczona znakiem „[TestClass]” (lub atrybutem pochodnym) +— Typ nie powinna być ogólna. @@ -244,10 +244,10 @@ The type declaring these methods should also respect the following rules: Typ deklarujący te metody powinien również przestrzegać następujących reguł: — Typ powinien być klasą -— Klasa powinna mieć wartość „public” lub „internal” (jeśli projekt testowy używa atrybutu „[DiscoverInternals]”) -— Klasa nie powinna mieć wartości „static” +— Typ powinna mieć wartość „public” lub „internal” (jeśli projekt testowy używa atrybutu „[DiscoverInternals]”) +— Typ nie powinna mieć wartości „static” — Jeśli klasa ma wartość „sealed”, powinna być oznaczona znakiem „[TestClass]” (lub atrybutem pochodnym) -— Klasa nie powinna być ogólna. +— Typ nie powinna być ogólna. @@ -549,7 +549,7 @@ Typ deklarujący te metody powinien również przestrzegać następujących regu Test class '{0}' should be valid - Klasa testowa „{0}” powinna być prawidłowa + Typ testowa „{0}” powinna być prawidłowa @@ -595,17 +595,17 @@ Typ deklarujący te metody powinien również przestrzegać następujących regu Test class should have at least one test method or be 'static' with method(s) marked by '[AssemblyInitialize]' and/or '[AssemblyCleanup]'. - Klasa testowa powinna mieć co najmniej jedną metodę testową lub być „statyczna” z metodami oznaczonymi jako „[AssemblyInitialize]” i/lub „[AssemblyCleanup]”. + Typ testowa powinna mieć co najmniej jedną metodę testową lub być „statyczna” z metodami oznaczonymi jako „[AssemblyInitialize]” i/lub „[AssemblyCleanup]”. Test class '{0}' should have at least one test method or be 'static' with method(s) marked by '[AssemblyInitialize]' and/or '[AssemblyCleanup]' - Klasa „{0}” testowa powinna mieć co najmniej jedną metodę testową lub być „statyczna” z metodami oznaczonymi jako „[AssemblyInitialize]” i/lub „[AssemblyCleanup]”. + Typ „{0}” testowa powinna mieć co najmniej jedną metodę testową lub być „statyczna” z metodami oznaczonymi jako „[AssemblyInitialize]” i/lub „[AssemblyCleanup]”. Test class should have test method - Klasa testowa powinna mieć metodę testową + Typ testowa powinna mieć metodę testową @@ -636,8 +636,8 @@ The type declaring these methods should also respect the following rules: Typ deklarujący te metody powinien również przestrzegać następujących reguł: — Typ powinien być klasą -— Klasa powinna mieć wartość „public” lub „internal” (jeśli projekt testowy używa atrybutu „[DiscoverInternals]”) -— Klasa nie powinna mieć wartości „static” +— Typ powinna mieć wartość „public” lub „internal” (jeśli projekt testowy używa atrybutu „[DiscoverInternals]”) +— Typ nie powinna mieć wartości „static” — Jeśli klasa jest zapieczętowana, powinna być oznaczona znakiem „[TestClass]” (lub atrybutem pochodnym). @@ -695,8 +695,8 @@ The type declaring these methods should also respect the following rules: Typ deklarujący te metody powinien również przestrzegać następujących reguł: — Typ powinien być klasą -— Klasa powinna mieć wartość „public” lub „internal” (jeśli projekt testowy używa atrybutu „[DiscoverInternals]”) -— Klasa nie powinna mieć wartości „static” +— Typ powinna mieć wartość „public” lub „internal” (jeśli projekt testowy używa atrybutu „[DiscoverInternals]”) +— Typ nie powinna mieć wartości „static” — Jeśli klasa jest zapieczętowana, powinna być oznaczona znakiem „[TestClass]” (lub atrybutem pochodnym). @@ -750,13 +750,13 @@ Typ deklarujący te metody powinien również przestrzegać następujących regu - Type contaning '[TestMethod]' should be marked with '[TestClass]', otherwise the test method will be silently ignored. - Typ zwierający metodę „[TestMethod]” powinien być oznaczony klasa „[TestClass]”. W przeciwnym razie metoda testowa zostanie zignorowana w trybie dyskretnym. + Type containing '[TestMethod]' should be marked with '[TestClass]', otherwise the test method will be silently ignored. + Typ zwierający metodę „[TestMethod]” powinien być oznaczony klasa „[TestClass]”. W przeciwnym razie metoda testowa zostanie zignorowana w trybie dyskretnym. - Class '{0}' contains test methods and should be marked with '[TestClass]' - Klasa „{0}” zawiera metody testowe i powinna być oznaczona klasą „[TestClass]” + Type '{0}' contains test methods and should be marked with '[TestClass]' + Typ „{0}” zawiera metody testowe i powinna być oznaczona klasą „[TestClass]” diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf index 359f90963a..252619d932 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf @@ -31,9 +31,9 @@ The type declaring these methods should also respect the following rules: O tipo declarando esses métodos também deve respeitar as seguintes regras: -O tipo deve ser uma classe --A classe deve ser 'public' ou 'internal' (se o projeto de teste estiver usando o '[DiscoverInternals]' atributo) --A classe não deve ser 'static' --A classe deve ser marcada com '[TestClass]' (ou um atributo derivado) +-O tipo deve ser 'public' ou 'internal' (se o projeto de teste estiver usando o '[DiscoverInternals]' atributo) +-O tipo não deve ser 'static' +-O tipo deve ser marcada com '[TestClass]' (ou um atributo derivado) -a classe não deve ser genérica. @@ -76,9 +76,9 @@ The type declaring these methods should also respect the following rules: O tipo que declara esses métodos também deve respeitar as seguintes regras: -O tipo deve ser uma classe --A classe deve ser “público” ou '”interno” (se o projeto de teste estiver usando o atributo “[DiscoverInternals]”) --A classe não deve ser “estático” --A classe deve ser marcada com “[TestClass]” (ou um atributo derivado) +-O tipo deve ser “público” ou '”interno” (se o projeto de teste estiver usando o atributo “[DiscoverInternals]”) +-O tipo não deve ser “estático” +-O tipo deve ser marcada com “[TestClass]” (ou um atributo derivado) -a classe não deve ser genérica. @@ -195,8 +195,8 @@ O parâmetro de atributo -'InheritanceBehavior.BeforeEachDerivedClass' não deve O tipo declarando esses métodos também deve respeitar as seguintes regras: -O tipo deve ser uma classe --A classe deve ser 'public' ou 'internal' (se o projeto de teste estiver usando o '[DiscoverInternals]' atributo) --A classe não deve ser 'static' +-O tipo deve ser 'public' ou 'internal' (se o projeto de teste estiver usando o '[DiscoverInternals]' atributo) +-O tipo não deve ser 'static' -Se a classe for 'sealed', ela deverá ser marcada com '[TestClass]' (ou um atributo derivado) -a classe não deve ser genérica. @@ -244,8 +244,8 @@ The type declaring these methods should also respect the following rules: O tipo que declara esses métodos também deve respeitar as seguintes regras: -O tipo deve ser uma classe --A classe deve ser “público” ou '”interno” (se o projeto de teste estiver usando o atributo “[DiscoverInternals]”) --A classe não deve ser “estático” +-O tipo deve ser “público” ou '”interno” (se o projeto de teste estiver usando o atributo “[DiscoverInternals]”) +-O tipo não deve ser “estático” -Se a classe for “selado”, ela deverá ser marcada com “[TestClass]” (ou um atributo derivado) -a classe não deve ser genérica. @@ -549,7 +549,7 @@ O tipo que declara esses métodos também deve respeitar as seguintes regras: Test class '{0}' should be valid - A classe de teste ''{0}'' deve ser válida + O tipo de teste ''{0}'' deve ser válida @@ -595,17 +595,17 @@ O tipo que declara esses métodos também deve respeitar as seguintes regras: Test class should have at least one test method or be 'static' with method(s) marked by '[AssemblyInitialize]' and/or '[AssemblyCleanup]'. - A classe de teste deve ter pelo menos um método de teste ou ser 'estática' com métodos marcados por '[AssemblyInitialize]' e/ou '[AssemblyCleanup]'. + O tipo de teste deve ter pelo menos um método de teste ou ser 'estática' com métodos marcados por '[AssemblyInitialize]' e/ou '[AssemblyCleanup]'. Test class '{0}' should have at least one test method or be 'static' with method(s) marked by '[AssemblyInitialize]' and/or '[AssemblyCleanup]' - A classe de teste '{0}' deve ter pelo menos um método de teste ou ser 'estática' com métodos marcados por '[AssemblyInitialize]' e/ou '[AssemblyCleanup]'. + O tipo de teste '{0}' deve ter pelo menos um método de teste ou ser 'estática' com métodos marcados por '[AssemblyInitialize]' e/ou '[AssemblyCleanup]'. Test class should have test method - A classe de teste deve ter um método de teste + O tipo de teste deve ter um método de teste @@ -636,8 +636,8 @@ The type declaring these methods should also respect the following rules: O tipo que declara esses métodos também deve respeitar as seguintes regras: -O tipo deve ser uma classe --A classe deve ser “público” ou '”interno” (se o projeto de teste estiver usando o atributo “[DiscoverInternals]”) --A classe não deve ser “estático” +-O tipo deve ser “público” ou '”interno” (se o projeto de teste estiver usando o atributo “[DiscoverInternals]”) +-O tipo não deve ser “estático” -Se a classe for “selado”, ela deverá ser marcada com “[TestClass]” (ou um atributo derivado). @@ -695,8 +695,8 @@ The type declaring these methods should also respect the following rules: O tipo que declara esses métodos também deve respeitar as seguintes regras: -O tipo deve ser uma classe --A classe deve ser “público” ou '”interno” (se o projeto de teste estiver usando o atributo “[DiscoverInternals]”) --A classe não deve ser “estático” +-O tipo deve ser “público” ou '”interno” (se o projeto de teste estiver usando o atributo “[DiscoverInternals]”) +-O tipo não deve ser “estático” -Se a classe for “selado”, ela deverá ser marcada com “[TestClass]” (ou um atributo derivado). @@ -750,13 +750,13 @@ O tipo que declara esses métodos também deve respeitar as seguintes regras: - Type contaning '[TestMethod]' should be marked with '[TestClass]', otherwise the test method will be silently ignored. - O tipo contendo '[TestMethod]' deve ser marcado com '[TestClass]', caso contrário, o método de teste será ignorado silenciosamente. + Type containing '[TestMethod]' should be marked with '[TestClass]', otherwise the test method will be silently ignored. + O tipo contendo '[TestMethod]' deve ser marcado com '[TestClass]', caso contrário, o método de teste será ignorado silenciosamente. - Class '{0}' contains test methods and should be marked with '[TestClass]' - A classe '{0}' contém métodos de teste e deve ser marcada com '[TestClass]' + Type '{0}' contains test methods and should be marked with '[TestClass]' + O tipo '{0}' contém métodos de teste e deve ser marcada com '[TestClass]' diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf index 8fdcabbd8a..6f2af8fac8 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf @@ -762,13 +762,13 @@ The type declaring these methods should also respect the following rules: - Type contaning '[TestMethod]' should be marked with '[TestClass]', otherwise the test method will be silently ignored. - У типа, содержащего "[TestMethod]", должна быть пометка "[TestClass]", иначе метод тестирования будет проигнорирован без уведомления пользователя. + Type containing '[TestMethod]' should be marked with '[TestClass]', otherwise the test method will be silently ignored. + У типа, содержащего "[TestMethod]", должна быть пометка "[TestClass]", иначе метод тестирования будет проигнорирован без уведомления пользователя. - Class '{0}' contains test methods and should be marked with '[TestClass]' - Класс "{0}" тестовые методы. У этого класса должна быть пометка "[TestClass]". + Type '{0}' contains test methods and should be marked with '[TestClass]' + Тип "{0}" тестовые методы. У этого класса должна быть пометка "[TestClass]". diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf index 605cfec512..bfbfd657bb 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf @@ -549,7 +549,7 @@ Bu yöntemleri bildiren tipin ayrıca aşağıdaki kurallara uyması gerekir: Test class '{0}' should be valid - '{0}' test sınıfı geçerli olmalıdır + '{0}' test türü geçerli olmalıdır @@ -564,7 +564,7 @@ Bu yöntemleri bildiren tipin ayrıca aşağıdaki kurallara uyması gerekir: Without using 'ClassCleanupBehavior.EndOfClass', the '[ClassCleanup]' will by default be run at the end of the assembly and not at the end of the class. - 'ClassCleanupBehavior.EndOfClass' kullanılmadığında, '[ClassCleanup]' varsayılan olarak sınıfın sonunda değil derlemenin sonunda çalıştırılır. + 'ClassCleanupBehavior.EndOfClass' kullanılmadığında, '[ClassCleanup]' varsayılan olarak türün sonunda değil derlemenin sonunda çalıştırılır. @@ -596,17 +596,17 @@ Bu yöntemleri bildiren tipin ayrıca aşağıdaki kurallara uyması gerekir: Test class should have at least one test method or be 'static' with method(s) marked by '[AssemblyInitialize]' and/or '[AssemblyCleanup]'. - Test sınıfı en az bir test yöntemine sahip olmalıdır veya '[AssemblyInitialize]' ve/veya '[AssemblyCleanup]' ile işaretlenen yöntemlere sahip 'static' olmalıdır. + Test türü en az bir test yöntemine sahip olmalıdır veya '[AssemblyInitialize]' ve/veya '[AssemblyCleanup]' ile işaretlenen yöntemlere sahip 'static' olmalıdır. Test class '{0}' should have at least one test method or be 'static' with method(s) marked by '[AssemblyInitialize]' and/or '[AssemblyCleanup]' - '{0}' test sınıfı en az bir test yöntemine sahip olmalıdır veya '[AssemblyInitialize]' ve/veya '[AssemblyCleanup]' ile işaretlenen yöntemlere sahip 'static' olmalıdır + '{0}' test türü en az bir test yöntemine sahip olmalıdır veya '[AssemblyInitialize]' ve/veya '[AssemblyCleanup]' ile işaretlenen yöntemlere sahip 'static' olmalıdır Test class should have test method - Test sınıfı test yöntemine sahip olmalıdır + Test türü test yöntemine sahip olmalıdır @@ -752,13 +752,13 @@ Bu yöntemleri bildiren tipin ayrıca aşağıdaki kurallara uyması gerekir: - Type contaning '[TestMethod]' should be marked with '[TestClass]', otherwise the test method will be silently ignored. - '[TestMethod]' içeren tür '[TestClass]' ile işaretlenmeli, aksi takdirde test yöntemi sessizce yoksayılır. + Type containing '[TestMethod]' should be marked with '[TestClass]', otherwise the test method will be silently ignored. + '[TestMethod]' içeren tür '[TestClass]' ile işaretlenmeli, aksi takdirde test yöntemi sessizce yoksayılır. - Class '{0}' contains test methods and should be marked with '[TestClass]' - '{0}' sınıfı test yöntemleri içeriyor ve '[TestClass]' ile işaretlenmeli + Type '{0}' contains test methods and should be marked with '[TestClass]' + '{0}' türü test yöntemleri içeriyor ve '[TestClass]' ile işaretlenmeli @@ -813,12 +813,12 @@ Bu yöntemleri bildiren tipin ayrıca aşağıdaki kurallara uyması gerekir: '[DeploymentItem]' can be specified only on test class or test method - '[DeploymentItem]' yalnızca test sınıfında veya test yönteminde belirtilebilir + '[DeploymentItem]' yalnızca test türünda veya test yönteminde belirtilebilir '[DeploymentItem]' can be specified only on test class or test method - '[DeploymentItem]' yalnızca test sınıfında veya test yönteminde belirtilebilir + '[DeploymentItem]' yalnızca test türünda veya test yönteminde belirtilebilir diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf index 35666c9f6e..9b594f3f4e 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf @@ -20,21 +20,21 @@ The type declaring these methods should also respect the following rules: -The class should be marked with '[TestClass]' (or a derived attribute) -the class should not be generic. 标记有“[AssemblyCleanup]”的方法应遵循以下布局才会有效: --不能在泛型类上声明它 +-不能在泛型类型上声明它 - 它应为“public” - 它应为“static” - 它不应为“async void” - 它不应是特殊方法(终结器、运算符...)。 - 它不应是泛型的 --它不应采用任何参数,或采用类型为“TestContext”的单个参数 -- 返回类型应为“void”、“Task”或“ValueTask” +-它不应采用任何参数,或采用类型型为“TestContext”的单个参数 +- 返回类型型应为“void”、“Task”或“ValueTask” -声明这些方法的类型还应遵循以下规则: --类型应为类 --类应为“public”或“internal”(如果测试项目正在使用“[DiscoverInternals]”属性) --类不应为“static” --应使用“[TestClass]”(或派生属性)标记类 --类不应是泛型的。 +声明这些方法的类型型还应遵循以下规则: +-类型型应为类型 +-类型应为“public”或“internal”(如果测试项目正在使用“[DiscoverInternals]”属性) +-类型不应为“static” +-应使用“[TestClass]”(或派生属性)标记类型 +-类型不应是泛型的。 @@ -65,21 +65,21 @@ The type declaring these methods should also respect the following rules: -The class should be marked with '[TestClass]' (or a derived attribute) -the class should not be generic. 标记有“[AssemblyInitialize]”的方法应遵循以下布局才会有效: --不能在泛型类上声明它 +-不能在泛型类型上声明它 - 它应为“public” - 它应为“static” - 它不应为“async void” - 它不应是特殊方法(终结器、运算符...)。 - 它不应是泛型的 -- 它应采用“TestContext”类型的一个参数 -- 返回类型应为“void”、“Task”或“ValueTask” +- 它应采用“TestContext”类型型的一个参数 +- 返回类型型应为“void”、“Task”或“ValueTask” -声明这些方法的类型还应遵循以下规则: --类型应为类 --类应为“public”或“internal”(如果测试项目正在使用“[DiscoverInternals]”属性) --类不应为“static” --应使用“[TestClass]”(或派生属性)标记类 --类不应是泛型的。 +声明这些方法的类型型还应遵循以下规则: +-类型型应为类型 +-类型应为“public”或“internal”(如果测试项目正在使用“[DiscoverInternals]”属性) +-类型不应为“static” +-应使用“[TestClass]”(或派生属性)标记类型 +-类型不应是泛型的。 @@ -119,17 +119,17 @@ The type declaring these methods should also respect the following rules: Use 'Assert.AreEqual'/'Assert.AreNotEqual' instead of 'Assert.AreSame'/'Assert.AreNotSame' when comparing value types. Passing a value type to 'Assert.AreSame'/'Assert.AreNotSame' will be boxed (creating a new object). Because 'Assert.AreSame'/'Assert.AreNotSame' does the comparison by reference, 'Assert.AreSame' will fail when boxing happens, and 'Assert.AreNotSame' will always pass. - 比较值类型时,请使用 “Assert.AreEqual”/“Assert.AreNotEqual” 而不是 “Assert.AreSame”/“Assert.AreNotSame”。将值类型传递给 “Assert.AreSame”/“Assert.AreNotSame”将装箱 (创建新的对象)。由于 'Assert.AreSame'/'Assert.AreNotSame' 按引用进行比较,所以当装箱发生时,“Assert.AreSame” 将失败,并且 “Assert.AreNotSame” 将始终通过。 + 比较值类型型时,请使用 “Assert.AreEqual”/“Assert.AreNotEqual” 而不是 “Assert.AreSame”/“Assert.AreNotSame”。将值类型型传递给 “Assert.AreSame”/“Assert.AreNotSame”将装箱 (创建新的对象)。由于 'Assert.AreSame'/'Assert.AreNotSame' 按引用进行比较,所以当装箱发生时,“Assert.AreSame” 将失败,并且 “Assert.AreNotSame” 将始终通过。 Use '{0}' instead of '{1}' when comparing value types - 比较值类型时使用 '{0}' 而不是 '{1}' + 比较值类型型时使用 '{0}' 而不是 '{1}' Don't use 'Assert.AreSame' or 'Assert.AreNotSame' with value types - 不要将 “Assert.AreSame” 或 “Assert.AreNotSame” 与值类型一起使用 + 不要将 “Assert.AreSame” 或 “Assert.AreNotSame” 与值类型型一起使用 @@ -182,23 +182,23 @@ The type declaring these methods should also respect the following rules: -If the class is 'sealed', it should be marked with '[TestClass]' (or a derived attribute) -the class should not be generic. 标记有“[ClassCleanup]”的方法应遵循以下布局才会有效: --如果未设置“InheritanceBehavior”模式,则不能在泛型类上声明它 +-如果未设置“InheritanceBehavior”模式,则不能在泛型类型上声明它 - 它应为“public” - 它应为“static” - 它不应为“async void” - 它不应是特殊方法(终结器、运算符...)。 - 它不应是泛型的 --它不应采用任何参数,或采用类型为“TestContext”的单个参数 -- 返回类型应为“void”、“Task”或“ValueTask” -- "InheritanceBehavior.BeforeEachDerivedClass" 属性参数应在类为 "abstract" 时指定 -- "InheritanceBehavior.BeforeEachDerivedClass" 属性参数不应在类为 "sealed" 时指定 +-它不应采用任何参数,或采用类型型为“TestContext”的单个参数 +- 返回类型型应为“void”、“Task”或“ValueTask” +- "InheritanceBehavior.BeforeEachDerivedClass" 属性参数应在类型为 "abstract" 时指定 +- "InheritanceBehavior.BeforeEachDerivedClass" 属性参数不应在类型为 "sealed" 时指定 -声明这些方法的类型还应遵循以下规则: --类型应为类 --类应为“public”或“internal”(如果测试项目正在使用“[DiscoverInternals]”属性) --类不应为“static” --如果类为“sealed”,应使用“[TestClass]”(或派生属性)标记该类 --类不应是泛型的。 +声明这些方法的类型型还应遵循以下规则: +-类型型应为类型 +-类型应为“public”或“internal”(如果测试项目正在使用“[DiscoverInternals]”属性) +-类型不应为“static” +-如果类型为“sealed”,应使用“[TestClass]”(或派生属性)标记该类型 +-类型不应是泛型的。 @@ -231,23 +231,23 @@ The type declaring these methods should also respect the following rules: -If the class is 'sealed', it should be marked with '[TestClass]' (or a derived attribute) -the class should not be generic. 标记有“[ClassInitialize]”的方法应遵循以下布局才会有效: --如果未设置“InheritanceBehavior”模式,则不能在泛型类上声明它 +-如果未设置“InheritanceBehavior”模式,则不能在泛型类型上声明它 - 它应为“public” - 它应为“static” - 它不应为“async void” - 它不应是特殊方法(终结器、运算符...)。 - 它不应是泛型的 -- 它应采用“TestContext”类型的一个参数 -- 返回类型应为“void”、“Task”或“ValueTask” -- "InheritanceBehavior.BeforeEachDerivedClass" 属性参数应在类为 "abstract" 时指定 -- "InheritanceBehavior.BeforeEachDerivedClass" 属性参数不应在类为 "sealed" 时指定 +- 它应采用“TestContext”类型型的一个参数 +- 返回类型型应为“void”、“Task”或“ValueTask” +- "InheritanceBehavior.BeforeEachDerivedClass" 属性参数应在类型为 "abstract" 时指定 +- "InheritanceBehavior.BeforeEachDerivedClass" 属性参数不应在类型为 "sealed" 时指定 -声明这些方法的类型还应遵循以下规则: --类型应为类 --类应为“public”或“internal”(如果测试项目正在使用“[DiscoverInternals]”属性) --类不应为“static” --如果类为“sealed”,则应使用“[TestClass]”(或派生属性)标记该类 --类不应是泛型的。 +声明这些方法的类型型还应遵循以下规则: +-类型型应为类型 +-类型应为“public”或“internal”(如果测试项目正在使用“[DiscoverInternals]”属性) +-类型不应为“static” +-如果类型为“sealed”,则应使用“[TestClass]”(或派生属性)标记该类型 +-类型不应是泛型的。 @@ -268,7 +268,7 @@ The type declaring these methods should also respect the following rules: DataRow 条目应具有以下布局才能有效: - 应仅在测试方法上进行设置; - 参数计数应与方法参数计数匹配; -- 参数类型应与方法参数类型匹配。 +- 参数类型型应与方法参数类型型匹配。 @@ -288,12 +288,12 @@ The type declaring these methods should also respect the following rules: Found two conflicting types for generic parameter '{0}'. The conflicting types are '{1}' and '{2}'. - 发现泛型参数 '{0}' 的两个冲突类型。冲突类型 '{1}' 和 '{2}'。 + 发现泛型参数 '{0}' 的两个冲突类型型。冲突类型型 '{1}' 和 '{2}'。 The type of the generic parameter '{0}' could not be inferred. - 无法推断 '{0}' 泛型参数的类型。 + 无法推断 '{0}' 泛型参数的类型型。 @@ -333,7 +333,7 @@ The type declaring these methods should also respect the following rules: Member '{0}' already exists in the base class - 基类中已存在成员“{0}” + 基类型中已存在成员“{0}” @@ -373,7 +373,7 @@ The type declaring these methods should also respect the following rules: - member should be a method if DynamicDataSourceType.Method is specified or a property otherwise. "DynamicData" 条目应具有以下布局才能有效: - 应仅对测试方法设置; -- 应对指定的类型定义成员; +- 应对指定的类型型定义成员; - 如果指定了 DynamicDataSourceType.Method,则成员应为方法,否则应为属性。 @@ -524,17 +524,17 @@ The type declaring these methods should also respect the following rules: It's considered a good practice to have only test classes marked public in a test project. - 在测试项目中仅将测试类标记为“公开”是一种不错的做法。 + 在测试项目中仅将测试类型标记为“公开”是一种不错的做法。 Public type '{0}' should be marked with '[TestClass]' or changed to 'internal' - 公共类型“{0}”应标记为“[TestClass]”或更改为“internal” + 公共类型型“{0}”应标记为“[TestClass]”或更改为“internal” Public types should be test classes - 公共类型应为测试类 + 公共类型型应为测试类型 @@ -549,7 +549,7 @@ The type declaring these methods should also respect the following rules: Test class '{0}' should be valid - 测试类“{0}”应该有效 + 测试类型“{0}”应该有效 @@ -564,7 +564,7 @@ The type declaring these methods should also respect the following rules: Without using 'ClassCleanupBehavior.EndOfClass', the '[ClassCleanup]' will by default be run at the end of the assembly and not at the end of the class. - 如果不使用 "ClassCleanupBehavior.EndOfClass","[ClassCleanup]" 将默认在程序集末尾运行,而不是在类的末尾运行。 + 如果不使用 "ClassCleanupBehavior.EndOfClass","[ClassCleanup]" 将默认在程序集末尾运行,而不是在类型的末尾运行。 @@ -582,7 +582,7 @@ The type declaring these methods should also respect the following rules: - it should be 'public' (or 'internal' if '[assembly: DiscoverInternals]' attribute is set) - it should not be 'static' (except if it contains only 'AssemblyInitialize' and/or 'AssemblyCleanup' methods) - it should not be generic. - 测试类(标记有“[TestClass]”属性的类)应遵循以下布局,才能被 MSTest 视为有效: + 测试类型(标记有“[TestClass]”属性的类型)应遵循以下布局,才能被 MSTest 视为有效: - 它应为 "public" (如果设置了“[assembly: DiscoverInternals]”属性,则应为 "internal") - 它不应为 "static" (除非它只包含 "AssemblyInitialize" 和/或 "AssemblyCleanup" 方法) - 它不应是泛型的。 @@ -590,22 +590,22 @@ The type declaring these methods should also respect the following rules: Test classes should have valid layout - 测试类应具有有效的布局 + 测试类型应具有有效的布局 Test class should have at least one test method or be 'static' with method(s) marked by '[AssemblyInitialize]' and/or '[AssemblyCleanup]'. - 测试类应至少有一个测试方法,或者应为 "static" 且方法由 "[AssemblyInitialize]" 和/或 "[AssemblyCleanup]" 标记。 + 测试类型应至少有一个测试方法,或者应为 "static" 且方法由 "[AssemblyInitialize]" 和/或 "[AssemblyCleanup]" 标记。 Test class '{0}' should have at least one test method or be 'static' with method(s) marked by '[AssemblyInitialize]' and/or '[AssemblyCleanup]' - 测试类 "{0}" 应至少有一个测试方法,或者应为 "static" 且方法由 "[AssemblyInitialize]" 和/或 "[AssemblyCleanup]" 标记 + 测试类型 "{0}" 应至少有一个测试方法,或者应为 "static" 且方法由 "[AssemblyInitialize]" 和/或 "[AssemblyCleanup]" 标记 Test class should have test method - 测试类应具有测试方法 + 测试类型应具有测试方法 @@ -632,13 +632,13 @@ The type declaring these methods should also respect the following rules: - 它不应是特殊方法(终结器、运算符...)。 - 它不应是泛型的 - 它不应采用任何参数 -- 返回类型应为“void”、“Task”或“ValueTask” +- 返回类型型应为“void”、“Task”或“ValueTask” -声明这些方法的类型还应遵循以下规则: --类型应为类 --类应为“public”或“internal”(如果测试项目正在使用“[DiscoverInternals]”属性) --类不应为“static” --如果类为“sealed”,则应使用“[TestClass]”(或派生属性)标记该类。 +声明这些方法的类型型还应遵循以下规则: +-类型型应为类型 +-类型应为“public”或“internal”(如果测试项目正在使用“[DiscoverInternals]”属性) +-类型不应为“static” +-如果类型为“sealed”,则应使用“[TestClass]”(或派生属性)标记该类型。 @@ -691,13 +691,13 @@ The type declaring these methods should also respect the following rules: - 它不应是特殊方法(终结器、运算符...)。 - 它不应是泛型的 - 它不应采用任何参数 -- 返回类型应为“void”、“Task”或“ValueTask” +- 返回类型型应为“void”、“Task”或“ValueTask” -声明这些方法的类型还应遵循以下规则: --类型应为类 --类应为“public”或“internal”(如果测试项目正在使用“[DiscoverInternals]”属性) --类不应为“static” --如果类为“sealed”,则应使用“[TestClass]”(或派生属性)标记该类。 +声明这些方法的类型型还应遵循以下规则: +-类型型应为类型 +-类型应为“public”或“internal”(如果测试项目正在使用“[DiscoverInternals]”属性) +-类型不应为“static” +-如果类型为“sealed”,则应使用“[TestClass]”(或派生属性)标记该类型。 @@ -722,9 +722,9 @@ The type declaring these methods should also respect the following rules: 测试方法(标记有 "[TestMethod]" 属性的方法)应遵循以下布局,以便 MSTest 将其视为有效: - 它应该是 "public" (如果设置了 "[assembly: DiscoverInternals]" 属性,则应该是 "internal") - 它不应为 "static" -- 只要可以推断类型参数并且参数类型兼容,它就应该是泛型 +- 只要可以推断类型型参数并且参数类型型兼容,它就应该是泛型 - 它不应为 "abstract" -- 返回类型应为 "void”、"Task" 或 "ValueTask" +- 返回类型型应为 "void”、"Task" 或 "ValueTask" - 它不应为 "async void" - 它不应是特殊方法(终结器、运算符...)。 @@ -750,18 +750,18 @@ The type declaring these methods should also respect the following rules: - Type contaning '[TestMethod]' should be marked with '[TestClass]', otherwise the test method will be silently ignored. - 应使用“[TestClass]”标记包含“[TestMethod]”的类型,否则将以静默方式忽略该测试方法。 + Type containing '[TestMethod]' should be marked with '[TestClass]', otherwise the test method will be silently ignored. + 应使用“[TestClass]”标记包含“[TestMethod]”的类型型,否则将以静默方式忽略该测试方法。 - Class '{0}' contains test methods and should be marked with '[TestClass]' - 类“{0}”包含测试方法,应使用“[TestClass]”进行标记 + Type '{0}' contains test methods and should be marked with '[TestClass]' + 类型“{0}”包含测试方法,应使用“[TestClass]”进行标记 Type containing '[TestMethod]' should be marked with '[TestClass]' - 应使用“[TestClass]”标记包含“[TestMethod]”的类型 + 应使用“[TestClass]”标记包含“[TestMethod]”的类型型 @@ -786,12 +786,12 @@ The type declaring these methods should also respect the following rules: The attribute '{0}' which derives from 'ConditionBaseAttribute' should be used only on classes marked with `TestClassAttribute` - 派生自 “ConditionBaseAttribute” 的属性 '{0}' 只能在标记为 “TestClassAttribute” 的类上使用 + 派生自 “ConditionBaseAttribute” 的属性 '{0}' 只能在标记为 “TestClassAttribute” 的类型上使用 Use 'ConditionBaseAttribute' on test classes - 对测试类使用 “ConditionBaseAttribute” + 对测试类型使用 “ConditionBaseAttribute” @@ -811,12 +811,12 @@ The type declaring these methods should also respect the following rules: '[DeploymentItem]' can be specified only on test class or test method - 只能对测试类或测试方法指定 "[DeploymentItem]" + 只能对测试类型或测试方法指定 "[DeploymentItem]" '[DeploymentItem]' can be specified only on test class or test method - 只能对测试类或测试方法指定 "[DeploymentItem]" + 只能对测试类型或测试方法指定 "[DeploymentItem]" diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf index eee571adc5..6919579be7 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf @@ -20,7 +20,7 @@ The type declaring these methods should also respect the following rules: -The class should be marked with '[TestClass]' (or a derived attribute) -the class should not be generic. 標示為 '[AssemblyCleanup]' 的方法應該遵循下列配置才能有效: --其不能在泛型類別上宣告 +-其不能在泛型類型上宣告 -其應為 'public' -其應為 'static' -其不應為 'async void' @@ -30,11 +30,11 @@ The type declaring these methods should also respect the following rules: -傳回類型應為 'void'、'Task' 或 'ValueTask' 宣告這些方法的類型還應遵循以下規則: --類型應為類別 --類別應為 'public' 或 'internal' (如果測試專案使用 '[DiscoverInternals]' 屬性) --類別不應為 'static' --類別應標示為 '[TestClass]' (或衍生屬性) --類別不應為泛型。 +-類型應為類型 +-類型應為 'public' 或 'internal' (如果測試專案使用 '[DiscoverInternals]' 屬性) +-類型不應為 'static' +-類型應標示為 '[TestClass]' (或衍生屬性) +-類型不應為泛型。 @@ -65,7 +65,7 @@ The type declaring these methods should also respect the following rules: -The class should be marked with '[TestClass]' (or a derived attribute) -the class should not be generic. 標示為 '[AssemblyInitialize]' 的方法應該遵循下列配置才能有效: --其不能在泛型類別上宣告 +-其不能在泛型類型上宣告 - 其應為 'public' - 其應為 'static' - 其不應為 'async void' @@ -75,11 +75,11 @@ The type declaring these methods should also respect the following rules: - 傳回類型應為 'void'、'Task' 或 'ValueTask' 宣告這些方法的類型還應遵循以下規則: --類型應為類別 --類別應為 'public' 或 'internal' (如果測試專案使用 '[DiscoverInternals]' 屬性) --類別不應為 'static' --類別應標示為 '[TestClass]' (或衍生屬性)。 --類別不應為泛型。 +-類型應為類型 +-類型應為 'public' 或 'internal' (如果測試專案使用 '[DiscoverInternals]' 屬性) +-類型不應為 'static' +-類型應標示為 '[TestClass]' (或衍生屬性)。 +-類型不應為泛型。 @@ -182,7 +182,7 @@ The type declaring these methods should also respect the following rules: -If the class is 'sealed', it should be marked with '[TestClass]' (or a derived attribute) -the class should not be generic. 標示 '[ClassCleanup]' 的方法應該遵循下列配置,才會有效: --未設定 'InheritanceBehavior' 模式的情況下不能在泛型類別上宣告它 +-未設定 'InheritanceBehavior' 模式的情況下不能在泛型類型上宣告它 -其應為 'public' -其應為 'static' -其不應為 'async void' @@ -190,15 +190,15 @@ The type declaring these methods should also respect the following rules: -其不應為泛型 -其不應接受任何參數,或接受類型為 'TestContext' 的單一參數 -傳回類型應為 'void'、'Task' 或 'ValueTask' --如果類別為 'abstract',應指定 'InheritanceBehavior.BeforeEachDerivedClass' 屬性參數 --如果類別為 'sealed',則不應指定 'InheritanceBehavior.BeforeEachDerivedClass' 屬性參數 +-如果類型為 'abstract',應指定 'InheritanceBehavior.BeforeEachDerivedClass' 屬性參數 +-如果類型為 'sealed',則不應指定 'InheritanceBehavior.BeforeEachDerivedClass' 屬性參數 宣告這些方法的類型還應遵循以下規則: --類型應為類別 --類別應為 'public' 或 'internal' (如果測試專案使用 '[DiscoverInternals]' 屬性) --類別不應為 'static' --如果類別是 'sealed',則應標示為 '[TestClass]' (或衍生屬性) --類別不應為泛型。 +-類型應為類型 +-類型應為 'public' 或 'internal' (如果測試專案使用 '[DiscoverInternals]' 屬性) +-類型不應為 'static' +-如果類型是 'sealed',則應標示為 '[TestClass]' (或衍生屬性) +-類型不應為泛型。 @@ -231,7 +231,7 @@ The type declaring these methods should also respect the following rules: -If the class is 'sealed', it should be marked with '[TestClass]' (or a derived attribute) -the class should not be generic. 標示 '[ClassInitialize]' 的方法應該遵循下列配置,才會有效: --未設定 'InheritanceBehavior' 模式的情況下不能在泛型類別上宣告它 +-未設定 'InheritanceBehavior' 模式的情況下不能在泛型類型上宣告它 - 其應為 'public' - 其應為 'static' - 其不應為 'async void' @@ -239,15 +239,15 @@ The type declaring these methods should also respect the following rules: - 其不應為泛型 - 其應該接受類型為 'TestContext' 的一個參數 - 傳回類型應為 'void'、'Task' 或 'ValueTask' -- 如果類別為 'abstract',應指定 'InheritanceBehavior.BeforeEachDerivedClass' 屬性參數。 -- 如果類別為 'sealed',則不應指定 'InheritanceBehavior.BeforeEachDerivedClass' 屬性參數。 +- 如果類型為 'abstract',應指定 'InheritanceBehavior.BeforeEachDerivedClass' 屬性參數。 +- 如果類型為 'sealed',則不應指定 'InheritanceBehavior.BeforeEachDerivedClass' 屬性參數。 宣告這些方法的類型還應遵循以下規則: --類型應為類別 --類別應為 'public' 或 'internal' (如果測試專案使用 '[DiscoverInternals]' 屬性) --類別不應為 'static' --如果類別是 'sealed',則應標示為 '[TestClass]' (或衍生屬性)。 --類別不應為泛型。 +-類型應為類型 +-類型應為 'public' 或 'internal' (如果測試專案使用 '[DiscoverInternals]' 屬性) +-類型不應為 'static' +-如果類型是 'sealed',則應標示為 '[TestClass]' (或衍生屬性)。 +-類型不應為泛型。 @@ -333,7 +333,7 @@ The type declaring these methods should also respect the following rules: Member '{0}' already exists in the base class - 成員 '{0}' 已經存在於基底類別中 + 成員 '{0}' 已經存在於基底類型中 @@ -524,7 +524,7 @@ The type declaring these methods should also respect the following rules: It's considered a good practice to have only test classes marked public in a test project. - 在測試專案中僅將測試類別標記為公開被認為是一種很好的做法。 + 在測試專案中僅將測試類型標記為公開被認為是一種很好的做法。 @@ -534,7 +534,7 @@ The type declaring these methods should also respect the following rules: Public types should be test classes - 公用類型應為測試類別 + 公用類型應為測試類型 @@ -549,7 +549,7 @@ The type declaring these methods should also respect the following rules: Test class '{0}' should be valid - 測試類別 '{0}' 應為有效 + 測試類型 '{0}' 應為有效 @@ -564,7 +564,7 @@ The type declaring these methods should also respect the following rules: Without using 'ClassCleanupBehavior.EndOfClass', the '[ClassCleanup]' will by default be run at the end of the assembly and not at the end of the class. - 如不使用 'ClassCleanupBehavior.EndOfClass',則預設會在組件結尾執行 '[ClassCleanup]',而非在類別的結尾執行。 + 如不使用 'ClassCleanupBehavior.EndOfClass',則預設會在組件結尾執行 '[ClassCleanup]',而非在類型的結尾執行。 @@ -582,7 +582,7 @@ The type declaring these methods should also respect the following rules: - it should be 'public' (or 'internal' if '[assembly: DiscoverInternals]' attribute is set) - it should not be 'static' (except if it contains only 'AssemblyInitialize' and/or 'AssemblyCleanup' methods) - it should not be generic. - 測試類別 (標示為 '[TestClass]' 屬性的類別) 應該遵循下列配置,讓 MSTest 視為有效: + 測試類型 (標示為 '[TestClass]' 屬性的類型) 應該遵循下列配置,讓 MSTest 視為有效: - 它應該是 'public' (如果設定 '[assembly: DiscoverInternals]' 屬性,則為 'internal') - 它不應該是 'static' (除非其僅包含 'AssemblyInitialize' 和/或 'AssemblyCleanup' 方法) - 它不能是泛型。 @@ -590,22 +590,22 @@ The type declaring these methods should also respect the following rules: Test classes should have valid layout - 測試類別應具備有效的配置 + 測試類型應具備有效的配置 Test class should have at least one test method or be 'static' with method(s) marked by '[AssemblyInitialize]' and/or '[AssemblyCleanup]'. - 測試類別至少應有一個測試方法或是 'static',而其方法是以 '[AssemblyInitialization]' 和/或 '[AssemblyCleanup]'標示。 + 測試類型至少應有一個測試方法或是 'static',而其方法是以 '[AssemblyInitialization]' 和/或 '[AssemblyCleanup]'標示。 Test class '{0}' should have at least one test method or be 'static' with method(s) marked by '[AssemblyInitialize]' and/or '[AssemblyCleanup]' - 測試類別 '{0}' 至少應有一個測試方法或是 'static',而其方法是以 '[AssemblyInitialization]' 和/或 '[AssemblyCleanup]'標示。 + 測試類型 '{0}' 至少應有一個測試方法或是 'static',而其方法是以 '[AssemblyInitialization]' 和/或 '[AssemblyCleanup]'標示。 Test class should have test method - 測試類別應該要有測試方法 + 測試類型應該要有測試方法 @@ -635,10 +635,10 @@ The type declaring these methods should also respect the following rules: - 傳回類型應為 'void'、'Task' 或 'ValueTask' 宣告這些方法的類型還應遵循以下規則: --類型應為類別 --類別應為 'public' 或 'internal' (如果測試專案使用 '[DiscoverInternals]' 屬性) --類別不應為 'static' --如果類別是 'sealed',則應標示為 '[TestClass]' (或衍生屬性)。 +-類型應為類型 +-類型應為 'public' 或 'internal' (如果測試專案使用 '[DiscoverInternals]' 屬性) +-類型不應為 'static' +-如果類型是 'sealed',則應標示為 '[TestClass]' (或衍生屬性)。 @@ -694,10 +694,10 @@ The type declaring these methods should also respect the following rules: - 傳回類型應為 'void'、'Task' 或 'ValueTask' 宣告這些方法的類型還應遵循以下規則: --類型應為類別 --類別應為 'public' 或 'internal' (如果測試專案使用 '[DiscoverInternals]' 屬性) --類別不應為 'static' --如果類別是 'sealed',則應標示為 '[TestClass]' (或衍生屬性)。 +-類型應為類型 +-類型應為 'public' 或 'internal' (如果測試專案使用 '[DiscoverInternals]' 屬性) +-類型不應為 'static' +-如果類型是 'sealed',則應標示為 '[TestClass]' (或衍生屬性)。 @@ -750,13 +750,13 @@ The type declaring these methods should also respect the following rules: - Type contaning '[TestMethod]' should be marked with '[TestClass]', otherwise the test method will be silently ignored. - 包含 '[TestMethod]' 的類型應標記為 '[TestClass]',否則將以無訊息的方式忽略測試方法。 + Type containing '[TestMethod]' should be marked with '[TestClass]', otherwise the test method will be silently ignored. + 包含 '[TestMethod]' 的類型應標記為 '[TestClass]',否則將以無訊息的方式忽略測試方法。 - Class '{0}' contains test methods and should be marked with '[TestClass]' - 類別 '{0}' 包含測試方法,應以 '[TestClass]' 標記 + Type '{0}' contains test methods and should be marked with '[TestClass]' + 類型 '{0}' 包含測試方法,應以 '[TestClass]' 標記 @@ -786,12 +786,12 @@ The type declaring these methods should also respect the following rules: The attribute '{0}' which derives from 'ConditionBaseAttribute' should be used only on classes marked with `TestClassAttribute` - 衍生自 'ConditionBaseAttribute' 的屬性 '{0}' 只能用於標示為 'TestClassAttribute' 的類別 + 衍生自 'ConditionBaseAttribute' 的屬性 '{0}' 只能用於標示為 'TestClassAttribute' 的類型 Use 'ConditionBaseAttribute' on test classes - 在測試類別上使用 'ConditionBaseAttribute' + 在測試類型上使用 'ConditionBaseAttribute' diff --git a/test/UnitTests/MSTest.Analyzers.UnitTests/TypeContainingTestMethodShouldBeATestClassAnalyzer.cs b/test/UnitTests/MSTest.Analyzers.UnitTests/TypeContainingTestMethodShouldBeATestClassAnalyzer.cs index ebbd1131ab..bec343fbaf 100644 --- a/test/UnitTests/MSTest.Analyzers.UnitTests/TypeContainingTestMethodShouldBeATestClassAnalyzer.cs +++ b/test/UnitTests/MSTest.Analyzers.UnitTests/TypeContainingTestMethodShouldBeATestClassAnalyzer.cs @@ -290,4 +290,176 @@ public void TestMethod1() await VerifyCS.VerifyCodeFixAsync(code, fixedCode); } + + [TestMethod] + public async Task WhenStructWithTestMethod_Diagnostic() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + public struct [|TestStruct|] + { + [TestMethod] + public void TestMethod1() + { + } + } + """; + + string fixedCode = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class TestStruct + { + [TestMethod] + public void TestMethod1() + { + } + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, fixedCode); + } + + [TestMethod] + public async Task WhenStructWithoutTestMethod_NoDiagnostic() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + public struct TestStruct + { + public void RegularMethod() + { + } + } + """; + + await VerifyCS.VerifyAnalyzerAsync(code); + } + + [TestMethod] + public async Task WhenRecordStructWithTestMethod_Diagnostic() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + public record struct [|TestRecordStruct|] + { + [TestMethod] + public void TestMethod1() + { + } + } + """; + + string fixedCode = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public record TestRecordStruct + { + [TestMethod] + public void TestMethod1() + { + } + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, fixedCode); + } + + [TestMethod] + public async Task WhenRecordClassWithTestMethod_Diagnostic() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + public record class [|TestRecordClass|] + { + [TestMethod] + public void TestMethod1() + { + } + } + """; + + string fixedCode = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public record class TestRecordClass + { + [TestMethod] + public void TestMethod1() + { + } + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, fixedCode); + } + + [TestMethod] + public async Task WhenRecordWithTestMethod_Diagnostic() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + public record [|TestRecord|] + { + [TestMethod] + public void TestMethod1() + { + } + } + """; + + string fixedCode = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public record TestRecord + { + [TestMethod] + public void TestMethod1() + { + } + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, fixedCode); + } + + [TestMethod] + public async Task WhenReadonlyRecordStructWithTestMethod_Diagnostic() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + public readonly record struct [|TestRecordStruct|] + { + [TestMethod] + public void TestMethod1() + { + } + } + """; + + string fixedCode = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public record TestRecordStruct + { + [TestMethod] + public void TestMethod1() + { + } + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, fixedCode); + } } From a2e005df7511405e19c2ae5df355e8badce85084 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Wed, 16 Jul 2025 09:23:25 +0200 Subject: [PATCH 228/541] Add clarifying comment to NamedPipeServer.WaitConnectionAsync (#6036) --- .../Microsoft.Testing.Platform/IPC/NamedPipeServer.cs | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/Platform/Microsoft.Testing.Platform/IPC/NamedPipeServer.cs b/src/Platform/Microsoft.Testing.Platform/IPC/NamedPipeServer.cs index 3caf9be910..6d03564086 100644 --- a/src/Platform/Microsoft.Testing.Platform/IPC/NamedPipeServer.cs +++ b/src/Platform/Microsoft.Testing.Platform/IPC/NamedPipeServer.cs @@ -77,6 +77,13 @@ public NamedPipeServer( public async Task WaitConnectionAsync(CancellationToken cancellationToken) { + // NOTE: _cancellationToken field is usually the "test session" cancellation token. + // And cancellationToken parameter may have hang mitigating timeout. + // The parameter should only be used for the call of WaitForConnectionAsync and Task.Run call. + // NOTE: The cancellation token passed to Task.Run will only have effect before the task is started by runtime. + // Once it starts, it won't be considered. + // Then, for the internal loop, we should use _cancellationToken, because we don't know for how long the loop will run. + // So what we pass to InternalLoopAsync shouldn't have any timeout (it's usually linked to Ctrl+C). await _logger.LogDebugAsync($"Waiting for connection for the pipe name {PipeName.Name}").ConfigureAwait(false); #pragma warning disable CA1416 // Validate platform compatibility await _namedPipeServerStream.WaitForConnectionAsync(cancellationToken).ConfigureAwait(false); From a2f93ab73cf2c93e44740ab27cbfd7708b044570 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Wed, 16 Jul 2025 09:26:09 +0200 Subject: [PATCH 229/541] Merge TcpMessageHandler and StreamMessageHandler (#6054) --- .../JsonRpc/StreamMessageHandler.cs | 147 ------------------ .../ServerMode/JsonRpc/TcpMessageHandler.cs | 119 +++++++++++++- 2 files changed, 113 insertions(+), 153 deletions(-) delete mode 100644 src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/StreamMessageHandler.cs diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/StreamMessageHandler.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/StreamMessageHandler.cs deleted file mode 100644 index 9efdf0535b..0000000000 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/StreamMessageHandler.cs +++ /dev/null @@ -1,147 +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. - -#if NETCOREAPP -using System.Buffers; -#else -using Microsoft.Testing.Platform.Helpers; -#endif - -namespace Microsoft.Testing.Platform.ServerMode; - -internal class StreamMessageHandler : IMessageHandler, IDisposable -{ - private readonly StreamReader _reader; - private readonly StreamWriter _writer; - private readonly IMessageFormatter _formatter; - private bool _isDisposed; - - public StreamMessageHandler( - Stream clientToServerStream, - Stream serverToClientStream, - IMessageFormatter formatter) - { - _reader = new StreamReader(clientToServerStream); - _writer = new StreamWriter(serverToClientStream) - { - // We need to force the NewLine because in Windows and nix different char sequence are used - // https://learn.microsoft.com/dotnet/api/system.io.textwriter.newline?view=net-7.0 - NewLine = "\r\n", - }; - _formatter = formatter; - } - - public virtual async Task ReadAsync(CancellationToken cancellationToken) - { - // Reads an RPC message. - // The message is currently encoded by writing a list of headers - // and then passing a byte stream with the message. - // The headers include the size of the byte stream. - // Content-Length: [content-length]\r\n - // Content-Type: [mime-type]\r\n - // \r\n - // [content]\r\n - while (true) - { - int commandSize = await ReadHeadersAsync(cancellationToken).ConfigureAwait(false); - - // Most probably connection lost - if (commandSize is -1) - { - return null; - } - -#if NETCOREAPP - char[] commandCharsBuffer = ArrayPool.Shared.Rent(commandSize); - try - { - Memory memoryBuffer = new(commandCharsBuffer, 0, commandSize); - await _reader.ReadBlockAsync(memoryBuffer, cancellationToken).ConfigureAwait(false); - return _formatter.Deserialize(memoryBuffer); - } - finally - { - ArrayPool.Shared.Return(commandCharsBuffer); - } -#else - char[] commandChars = new char[commandSize]; - await _reader.ReadBlockAsync(commandChars, 0, commandSize).WithCancellationAsync(cancellationToken).ConfigureAwait(false); - return _formatter.Deserialize(new string(commandChars, 0, commandSize)); -#endif - } - } - - private async Task ReadHeadersAsync(CancellationToken cancellationToken) - { - int contentSize = -1; - - while (true) - { -#if NET7_0_OR_GREATER - string? line = await _reader.ReadLineAsync(cancellationToken).ConfigureAwait(false); -#elif NET6_0_OR_GREATER - string? line = await _reader.ReadLineAsync().WaitAsync(cancellationToken).ConfigureAwait(false); -#else - string? line = await _reader.ReadLineAsync().WithCancellationAsync(cancellationToken).ConfigureAwait(false); -#endif - if (line is null || (line.Length == 0 && contentSize != -1)) - { - break; - } - - const string ContentLengthHeaderName = "Content-Length:"; - // Content type is not mandatory, and we don't use it. - if (line.StartsWith(ContentLengthHeaderName, StringComparison.OrdinalIgnoreCase)) - { -#if NETCOREAPP - _ = int.TryParse(line.AsSpan()[ContentLengthHeaderName.Length..].Trim(), out contentSize); -#else - _ = int.TryParse(line[ContentLengthHeaderName.Length..].Trim(), out contentSize); -#endif - } - } - - return contentSize; - } - - public async Task WriteRequestAsync(RpcMessage message, CancellationToken cancellationToken) - { - string messageStr = await _formatter.SerializeAsync(message).ConfigureAwait(false); - await _writer.WriteLineAsync($"Content-Length: {Encoding.UTF8.GetByteCount(messageStr)}").ConfigureAwait(false); - await _writer.WriteLineAsync("Content-Type: application/testingplatform").ConfigureAwait(false); - await _writer.WriteLineAsync().ConfigureAwait(false); - await _writer.WriteAsync(messageStr).ConfigureAwait(false); - await _writer.FlushAsync(cancellationToken).ConfigureAwait(false); - } - - protected virtual void Dispose(bool disposing) - { - if (!_isDisposed) - { - if (disposing) - { - _reader.Dispose(); - try - { - _writer.Dispose(); - } - catch (InvalidOperationException) - { - // We can exit the server without wait that the streaming activity is completed. - // In that case we can get an InvalidOperationException - // (https://learn.microsoft.com/dotnet/api/system.io.streamwriter.writelineasync?view=net-7.0#system-io-streamwriter-writelineasync(system-string)): - // The stream writer is currently in use by a previous write operation. - } - } - - _isDisposed = true; - } - } - - public void Dispose() - { - // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method - Dispose(disposing: true); - GC.SuppressFinalize(this); - } -} diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/TcpMessageHandler.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/TcpMessageHandler.cs index e72aff6780..65aa8498dc 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/TcpMessageHandler.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/TcpMessageHandler.cs @@ -1,23 +1,74 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +#if NETCOREAPP +using System.Buffers; +#endif using System.Net.Sockets; +#if !NETCOREAPP +using Microsoft.Testing.Platform.Helpers; +#endif + namespace Microsoft.Testing.Platform.ServerMode; internal sealed class TcpMessageHandler( TcpClient client, Stream clientToServerStream, Stream serverToClientStream, - IMessageFormatter formatter) : StreamMessageHandler(clientToServerStream, serverToClientStream, formatter) + IMessageFormatter formatter) : IMessageHandler, IDisposable { private readonly TcpClient _client = client; + private readonly StreamReader _reader = new(clientToServerStream); + private readonly StreamWriter _writer = new(serverToClientStream) + { + // We need to force the NewLine because in Windows and nix different char sequence are used + // https://learn.microsoft.com/dotnet/api/system.io.textwriter.newline?view=net-7.0 + NewLine = "\r\n", + }; - public override async Task ReadAsync(CancellationToken cancellationToken) + private readonly IMessageFormatter _formatter = formatter; + + public async Task ReadAsync(CancellationToken cancellationToken) { try { - return await base.ReadAsync(cancellationToken).ConfigureAwait(false); + // Reads an RPC message. + // The message is currently encoded by writing a list of headers + // and then passing a byte stream with the message. + // The headers include the size of the byte stream. + // Content-Length: [content-length]\r\n + // Content-Type: [mime-type]\r\n + // \r\n + // [content]\r\n + while (true) + { + int commandSize = await ReadHeadersAsync(cancellationToken).ConfigureAwait(false); + + // Most probably connection lost + if (commandSize is -1) + { + return null; + } + +#if NETCOREAPP + char[] commandCharsBuffer = ArrayPool.Shared.Rent(commandSize); + try + { + Memory memoryBuffer = new(commandCharsBuffer, 0, commandSize); + await _reader.ReadBlockAsync(memoryBuffer, cancellationToken).ConfigureAwait(false); + return _formatter.Deserialize(memoryBuffer); + } + finally + { + ArrayPool.Shared.Return(commandCharsBuffer); + } +#else + char[] commandChars = new char[commandSize]; + await _reader.ReadBlockAsync(commandChars, 0, commandSize).WithCancellationAsync(cancellationToken).ConfigureAwait(false); + return _formatter.Deserialize(new string(commandChars, 0, commandSize)); +#endif + } } // Client close the connection in an unexpected way @@ -34,11 +85,67 @@ internal sealed class TcpMessageHandler( } } - protected override void Dispose(bool disposing) + private async Task ReadHeadersAsync(CancellationToken cancellationToken) + { + int contentSize = -1; + + while (true) + { +#if NET7_0_OR_GREATER + string? line = await _reader.ReadLineAsync(cancellationToken).ConfigureAwait(false); +#elif NET6_0_OR_GREATER + string? line = await _reader.ReadLineAsync().WaitAsync(cancellationToken).ConfigureAwait(false); +#else + string? line = await _reader.ReadLineAsync().WithCancellationAsync(cancellationToken).ConfigureAwait(false); +#endif + if (line is null || (line.Length == 0 && contentSize != -1)) + { + break; + } + + const string ContentLengthHeaderName = "Content-Length:"; + // Content type is not mandatory, and we don't use it. + if (line.StartsWith(ContentLengthHeaderName, StringComparison.OrdinalIgnoreCase)) + { +#if NETCOREAPP + _ = int.TryParse(line.AsSpan()[ContentLengthHeaderName.Length..].Trim(), out contentSize); +#else + _ = int.TryParse(line[ContentLengthHeaderName.Length..].Trim(), out contentSize); +#endif + } + } + + return contentSize; + } + + public async Task WriteRequestAsync(RpcMessage message, CancellationToken cancellationToken) + { + string messageStr = await _formatter.SerializeAsync(message).ConfigureAwait(false); + await _writer.WriteLineAsync($"Content-Length: {Encoding.UTF8.GetByteCount(messageStr)}").ConfigureAwait(false); + await _writer.WriteLineAsync("Content-Type: application/testingplatform").ConfigureAwait(false); + await _writer.WriteLineAsync().ConfigureAwait(false); + await _writer.WriteAsync(messageStr).ConfigureAwait(false); + await _writer.FlushAsync(cancellationToken).ConfigureAwait(false); + } + + public void Dispose() { - base.Dispose(disposing); + _reader.Dispose(); + + try + { + _writer.Dispose(); + } + catch (InvalidOperationException) + { + // We can exit the server without wait that the streaming activity is completed. + // In that case we can get an InvalidOperationException + // (https://learn.microsoft.com/dotnet/api/system.io.streamwriter.writelineasync?view=net-7.0#system-io-streamwriter-writelineasync(system-string)): + // The stream writer is currently in use by a previous write operation. + } + #pragma warning disable CA1416 // Validate platform compatibility - _client.Close(); + _client.Dispose(); #pragma warning restore CA1416 } } From 8918da6c1ffb20569ed225ddc643410445c2f472 Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Wed, 16 Jul 2025 18:34:30 +1000 Subject: [PATCH 230/541] use some exception filters (#6049) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Amaury Levé --- .../v1.0.0/TestingPlatformClient.cs | 9 +-- .../Helpers/FixtureMethodRunner.cs | 62 +++++++------------ .../TestMethodFilter.cs | 11 ++-- .../ServerMode/JsonRpc/TcpMessageHandler.cs | 17 +++-- .../v1.0.0/TestingPlatformClient.cs | 9 +-- 5 files changed, 41 insertions(+), 67 deletions(-) diff --git a/samples/Playground/ServerMode/v1.0.0/TestingPlatformClient.cs b/samples/Playground/ServerMode/v1.0.0/TestingPlatformClient.cs index 5d1a5b917c..d789e2bd04 100644 --- a/samples/Playground/ServerMode/v1.0.0/TestingPlatformClient.cs +++ b/samples/Playground/ServerMode/v1.0.0/TestingPlatformClient.cs @@ -64,14 +64,9 @@ private async Task CheckedInvokeAsync(Func func) { await func(); } - catch (Exception ex) + catch (Exception ex) when (_disconnectionReason.Length > 0) { - if (_disconnectionReason.Length > 0) - { - throw new InvalidOperationException($"{ex.Message}\n{_disconnectionReason}", ex); - } - - throw; + throw new InvalidOperationException($"{ex.Message}\n{_disconnectionReason}", ex); } } diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Helpers/FixtureMethodRunner.cs b/src/Adapter/MSTestAdapter.PlatformServices/Helpers/FixtureMethodRunner.cs index 69551cc173..5feb0ce26b 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Helpers/FixtureMethodRunner.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Helpers/FixtureMethodRunner.cs @@ -35,26 +35,22 @@ internal static class FixtureMethodRunner return null; } catch (Exception ex) + when (ex.GetRealException().IsOperationCanceledExceptionFromToken(cancellationTokenSource.Token)) { - if (ex.GetRealException().IsOperationCanceledExceptionFromToken(cancellationTokenSource.Token)) - { - return new( - UnitTestOutcome.Timeout, - testTimeoutInfo?.TokenSource.Token.IsCancellationRequested == true - ? string.Format( - CultureInfo.InvariantCulture, - methodTimedOutMessageFormat, - methodInfo.DeclaringType!.FullName, - methodInfo.Name, - testTimeoutInfo.Value.Timeout) - : string.Format( - CultureInfo.InvariantCulture, - methodCanceledMessageFormat, - methodInfo.DeclaringType!.FullName, - methodInfo.Name)); - } - - throw; + return new( + UnitTestOutcome.Timeout, + testTimeoutInfo?.TokenSource.Token.IsCancellationRequested == true + ? string.Format( + CultureInfo.InvariantCulture, + methodTimedOutMessageFormat, + methodInfo.DeclaringType!.FullName, + methodInfo.Name, + testTimeoutInfo.Value.Timeout) + : string.Format( + CultureInfo.InvariantCulture, + methodCanceledMessageFormat, + methodInfo.DeclaringType!.FullName, + methodInfo.Name)); } } @@ -172,15 +168,10 @@ internal static class FixtureMethodRunner UnitTestOutcome.Timeout, string.Format(CultureInfo.InvariantCulture, methodCanceledMessageFormat, methodInfo.DeclaringType!.FullName, methodInfo.Name)); } - catch (Exception) + catch (Exception) when (realException is not null) { // We throw the real exception to have the original stack trace to elaborate up the chain. - if (realException is not null) - { - throw realException; - } - - throw; + throw realException; } } @@ -236,20 +227,15 @@ internal static class FixtureMethodRunner UnitTestOutcome.Timeout, string.Format(CultureInfo.InvariantCulture, methodCanceledMessageFormat, methodInfo.DeclaringType!.FullName, methodInfo.Name)); } - catch (Exception) + catch (Exception) when (realException is not null) { // We throw the real exception to have the original stack trace to elaborate up the chain. - // Also note that tcs.Task.Exception can be an AggregateException, so we favor the "real exception". - if (realException is not null) - { - throw realException; - } - else if (tcs.Task.Exception is not null) - { - throw tcs.Task.Exception; - } - - throw; + throw realException; + } + catch (Exception) when (tcs.Task.Exception is not null) + { + // The tcs.Task.Exception can be an AggregateException, so we favor the "real exception". + throw tcs.Task.Exception; } } } diff --git a/src/Adapter/MSTestAdapter.PlatformServices/TestMethodFilter.cs b/src/Adapter/MSTestAdapter.PlatformServices/TestMethodFilter.cs index 5db7934e25..33f554a96c 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/TestMethodFilter.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/TestMethodFilter.cs @@ -125,15 +125,14 @@ internal TestProperty PropertyProvider(string propertyName) MethodInfo? methodGetTestCaseFilter = context.GetType().GetRuntimeMethod("GetTestCaseFilter", [typeof(IEnumerable), typeof(Func)]); return (ITestCaseFilterExpression?)methodGetTestCaseFilter?.Invoke(context, [_supportedProperties.Keys, (Func)PropertyProvider]); } - catch (Exception ex) + catch (TargetInvocationException ex) { // In case of UWP .Net Native Tool Chain compilation. Invoking methods via Reflection doesn't work, hence discovery always fails. // Hence throwing exception only if it is of type TargetInvocationException(i.e. Method got invoked but something went wrong in GetTestCaseFilter Method) - if (ex is TargetInvocationException) - { - throw ex.InnerException!; - } - + throw ex.InnerException!; + } + catch (Exception ex) + { logger.SendMessage(TestMessageLevel.Warning, ex.Message); } diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/TcpMessageHandler.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/TcpMessageHandler.cs index 65aa8498dc..30b690cbd2 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/TcpMessageHandler.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/TcpMessageHandler.cs @@ -72,16 +72,15 @@ internal sealed class TcpMessageHandler( } // Client close the connection in an unexpected way - catch (Exception ex) + catch (Exception ex) when + (ex is + SocketException { SocketErrorCode: SocketError.ConnectionReset } or + IOException + { + InnerException: SocketException { SocketErrorCode: SocketError.ConnectionReset } + }) { - switch (ex) - { - case SocketException { SocketErrorCode: SocketError.ConnectionReset }: - case IOException { InnerException: SocketException { SocketErrorCode: SocketError.ConnectionReset } }: - return null; - default: - throw; - } + return null; } } diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/ServerMode/v1.0.0/TestingPlatformClient.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/ServerMode/v1.0.0/TestingPlatformClient.cs index e1abd7b78a..43c86c3cb3 100644 --- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/ServerMode/v1.0.0/TestingPlatformClient.cs +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/ServerMode/v1.0.0/TestingPlatformClient.cs @@ -64,14 +64,9 @@ private async Task CheckedInvoke(Func func) { await func(); } - catch (Exception ex) + catch (Exception ex) when (_disconnectionReason.Length > 0) { - if (_disconnectionReason.Length > 0) - { - throw new InvalidOperationException($"{ex.Message}\n{_disconnectionReason}", ex); - } - - throw; + throw new InvalidOperationException($"{ex.Message}\n{_disconnectionReason}", ex); } } From fa78df32255351dd7db9b5e5acb6dd94a3af60c5 Mon Sep 17 00:00:00 2001 From: Copilot <198982749+Copilot@users.noreply.github.com> Date: Wed, 16 Jul 2025 10:34:56 +0200 Subject: [PATCH 231/541] Add TestCategories property to ITestDataRow for per-test-case categorization (#5795) Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: Evangelink <11340282+Evangelink@users.noreply.github.com> Co-authored-by: Youssef1313 <31348972+Youssef1313@users.noreply.github.com> Co-authored-by: Youssef Victor --- MSTest.slnf | 1 + TestFx.slnx | 1 + .../Discovery/AssemblyEnumerator.cs | 10 +- .../Helpers/TestDataSourceHelpers.cs | 11 ++ .../TestFramework/ITestDataRow.cs | 2 + .../PublicAPI/PublicAPI.Unshipped.txt | 2 + .../TestFramework/TestDataRow.cs | 6 + .../TestCategoriesFromTestDataRowTests.cs | 88 +++++++++++++ ...estCategoriesFromTestDataRowProject.csproj | 12 ++ .../TestCategoriesFromTestDataRowTests.cs | 71 +++++++++++ .../Helpers/TestDataSourceHelpersTests.cs | 118 ++++++++++++++++++ .../TestDataRowTests.cs | 79 ++++++++++++ 12 files changed, 400 insertions(+), 1 deletion(-) create mode 100644 test/IntegrationTests/MSTest.IntegrationTests/TestCategoriesFromTestDataRowTests.cs create mode 100644 test/IntegrationTests/TestAssets/TestCategoriesFromTestDataRowProject/TestCategoriesFromTestDataRowProject.csproj create mode 100644 test/IntegrationTests/TestAssets/TestCategoriesFromTestDataRowProject/TestCategoriesFromTestDataRowTests.cs create mode 100644 test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Helpers/TestDataSourceHelpersTests.cs create mode 100644 test/UnitTests/TestFramework.UnitTests/TestDataRowTests.cs diff --git a/MSTest.slnf b/MSTest.slnf index af9d38802e..5b52bd185f 100644 --- a/MSTest.slnf +++ b/MSTest.slnf @@ -40,6 +40,7 @@ "test\\IntegrationTests\\TestAssets\\SampleFrameworkExtensions\\SampleFrameworkExtensions.csproj", "test\\IntegrationTests\\TestAssets\\SampleProjectForAssemblyResolution\\SampleProjectForAssemblyResolution.csproj", "test\\IntegrationTests\\TestAssets\\SuiteLifeCycleTestProject\\SuiteLifeCycleTestProject.csproj", + "test\\IntegrationTests\\TestAssets\\TestCategoriesFromTestDataRowProject\\TestCategoriesFromTestDataRowProject.csproj", "test\\IntegrationTests\\TestAssets\\TestIdProject.DefaultStrategy\\TestIdProject.DefaultStrategy.csproj", "test\\IntegrationTests\\TestAssets\\TestIdProject.DisplayNameStrategy\\TestIdProject.DisplayNameStrategy.csproj", "test\\IntegrationTests\\TestAssets\\TestIdProject.FullyQualifiedTestStrategy\\TestIdProject.FullyQualifiedStrategy.csproj", diff --git a/TestFx.slnx b/TestFx.slnx index d51b6d22e2..d1a4ea3a97 100644 --- a/TestFx.slnx +++ b/TestFx.slnx @@ -106,6 +106,7 @@ + diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Discovery/AssemblyEnumerator.cs b/src/Adapter/MSTestAdapter.PlatformServices/Discovery/AssemblyEnumerator.cs index c4f93526f5..7ea3298836 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Discovery/AssemblyEnumerator.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Discovery/AssemblyEnumerator.cs @@ -439,7 +439,7 @@ private static bool TryUnfoldITestDataSource(ITestDataSource dataSource, TestDat { object?[] d = dataOrTestDataRow; ParameterInfo[] parameters = methodInfo.GetParameters(); - if (TestDataSourceHelpers.TryHandleITestDataRow(d, parameters, out d, out string? ignoreMessageFromTestDataRow, out string? displayNameFromTestDataRow)) + if (TestDataSourceHelpers.TryHandleITestDataRow(d, parameters, out d, out string? ignoreMessageFromTestDataRow, out string? displayNameFromTestDataRow, out IList? testCategoriesFromTestDataRow)) { testDataSourceIgnoreMessage = ignoreMessageFromTestDataRow ?? testDataSourceIgnoreMessage; } @@ -467,6 +467,14 @@ private static bool TryUnfoldITestDataSource(ITestDataSource dataSource, TestDat UnitTestElement discoveredTest = test.Clone(); discoveredTest.DisplayName = displayNameFromTestDataRow ?? dataSource.GetDisplayName(methodInfo, d) ?? discoveredTest.DisplayName; + // Merge test categories from the test data row with the existing categories + if (testCategoriesFromTestDataRow is { Count: > 0 }) + { + discoveredTest.TestCategory = discoveredTest.TestCategory is { Length: > 0 } + ? [.. testCategoriesFromTestDataRow, .. discoveredTest.TestCategory] + : [.. testCategoriesFromTestDataRow]; + } + // If strategy is DisplayName and we have a duplicate test name don't expand the test, bail out. #pragma warning disable CS0618 // Type or member is obsolete if (test.TestMethod.TestIdGenerationStrategy == TestIdGenerationStrategy.DisplayName diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Helpers/TestDataSourceHelpers.cs b/src/Adapter/MSTestAdapter.PlatformServices/Helpers/TestDataSourceHelpers.cs index db7144303b..4f3e0b614a 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Helpers/TestDataSourceHelpers.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Helpers/TestDataSourceHelpers.cs @@ -19,12 +19,22 @@ public static bool TryHandleITestDataRow( out object?[] data, out string? ignoreMessageFromTestDataRow, out string? displayNameFromTestDataRow) + => TryHandleITestDataRow(d, testMethodParameters, out data, out ignoreMessageFromTestDataRow, out displayNameFromTestDataRow, out _); + + public static bool TryHandleITestDataRow( + object?[] d, + ParameterInfo[] testMethodParameters, + out object?[] data, + out string? ignoreMessageFromTestDataRow, + out string? displayNameFromTestDataRow, + out IList? testCategoriesFromTestDataRow) { if (d.Length == 1 && d[0] is ITestDataRow testDataRow) { object? dataFromTestDataRow = testDataRow.Value; ignoreMessageFromTestDataRow = testDataRow.IgnoreMessage; displayNameFromTestDataRow = testDataRow.DisplayName; + testCategoriesFromTestDataRow = testDataRow.TestCategories; data = TryHandleTupleDataSource(dataFromTestDataRow, testMethodParameters, out object?[] tupleExpandedToArray) ? tupleExpandedToArray @@ -36,6 +46,7 @@ public static bool TryHandleITestDataRow( data = d; ignoreMessageFromTestDataRow = null; displayNameFromTestDataRow = null; + testCategoriesFromTestDataRow = null; return false; } diff --git a/src/TestFramework/TestFramework/ITestDataRow.cs b/src/TestFramework/TestFramework/ITestDataRow.cs index 2150fa1c96..ed8ea6c612 100644 --- a/src/TestFramework/TestFramework/ITestDataRow.cs +++ b/src/TestFramework/TestFramework/ITestDataRow.cs @@ -10,4 +10,6 @@ internal interface ITestDataRow string? IgnoreMessage { get; } string? DisplayName { get; } + + IList? TestCategories { get; } } diff --git a/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Unshipped.txt b/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Unshipped.txt index c28957dede..766c80085b 100644 --- a/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Unshipped.txt +++ b/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Unshipped.txt @@ -8,6 +8,8 @@ override Microsoft.VisualStudio.TestTools.UnitTesting.CIConditionAttribute.Ignor override Microsoft.VisualStudio.TestTools.UnitTesting.CIConditionAttribute.ShouldRun.get -> bool Microsoft.VisualStudio.TestTools.UnitTesting.DynamicDataAttribute.DynamicDataAttribute(string! dynamicDataSourceName, params object?[]! dynamicDataSourceArguments) -> void Microsoft.VisualStudio.TestTools.UnitTesting.DynamicDataAttribute.DynamicDataAttribute(string! dynamicDataSourceName, System.Type! dynamicDataDeclaringType, params object?[]! dynamicDataSourceArguments) -> void +Microsoft.VisualStudio.TestTools.UnitTesting.TestDataRow.TestCategories.get -> System.Collections.Generic.IList? +Microsoft.VisualStudio.TestTools.UnitTesting.TestDataRow.TestCategories.set -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.ContainsSingle(System.Func! predicate, System.Collections.Generic.IEnumerable! collection, string! message = "") -> T static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.DoesNotEndWith(string? substring, string? value, string! message = "") -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.DoesNotEndWith(string? substring, string? value, System.StringComparison comparisonType, string! message = "") -> void diff --git a/src/TestFramework/TestFramework/TestDataRow.cs b/src/TestFramework/TestFramework/TestDataRow.cs index c8865a3806..ff3a433e2a 100644 --- a/src/TestFramework/TestFramework/TestDataRow.cs +++ b/src/TestFramework/TestFramework/TestDataRow.cs @@ -40,6 +40,12 @@ public TestDataRow(T value) [DataMember] public string? DisplayName { get; set; } + /// + /// Gets or sets the test categories for the test case. + /// + [DataMember] + public IList? TestCategories { get; set; } + /// object? ITestDataRow.Value => Value; } diff --git a/test/IntegrationTests/MSTest.IntegrationTests/TestCategoriesFromTestDataRowTests.cs b/test/IntegrationTests/MSTest.IntegrationTests/TestCategoriesFromTestDataRowTests.cs new file mode 100644 index 0000000000..878cf09f4f --- /dev/null +++ b/test/IntegrationTests/MSTest.IntegrationTests/TestCategoriesFromTestDataRowTests.cs @@ -0,0 +1,88 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using Microsoft.MSTestV2.CLIAutomation; + +namespace MSTest.IntegrationTests; + +public class TestCategoriesFromTestDataRowTests : CLITestBase +{ + private const string TestAssetName = "TestCategoriesFromTestDataRowProject"; + + [TestMethod] + public void TestCategoriesFromTestDataRow_ShouldDiscoverTestsWithIntegrationCategory() + { + // Arrange + string assemblyPath = GetAssetFullPath(TestAssetName); + + // Act - Filter by "Integration" category which should come from TestDataRow + System.Collections.Immutable.ImmutableArray testCases = DiscoverTests(assemblyPath, "TestCategory~Integration"); + + // Assert - Should discover the test that has Integration category from TestDataRow + Assert.AreEqual(1, testCases.Length, "Should discover exactly 1 test with Integration category"); + + Microsoft.VisualStudio.TestPlatform.ObjectModel.TestCase integrationTest = testCases[0]; + Assert.IsTrue(integrationTest.DisplayName.Contains("Integration and Slow"), "Should be the test with Integration and Slow categories"); + } + + [TestMethod] + public void TestCategoriesFromTestDataRow_ShouldDiscoverTestsWithUnitCategory() + { + // Arrange + string assemblyPath = GetAssetFullPath(TestAssetName); + + // Act - Filter by "Unit" category which should come from TestDataRow + System.Collections.Immutable.ImmutableArray testCases = DiscoverTests(assemblyPath, "TestCategory~Unit"); + + // Assert - Should discover the test that has Unit category from TestDataRow + Assert.AreEqual(1, testCases.Length, "Should discover exactly 1 test with Unit category"); + + Microsoft.VisualStudio.TestPlatform.ObjectModel.TestCase unitTest = testCases[0]; + Assert.IsTrue(unitTest.DisplayName.Contains("Unit and Fast"), "Should be the test with Unit and Fast categories"); + } + + [TestMethod] + public void TestCategoriesFromTestDataRow_ShouldCombineMethodAndDataCategories() + { + // Arrange + string assemblyPath = GetAssetFullPath(TestAssetName); + + // Act - Filter by "MethodLevel" category (method attribute) + System.Collections.Immutable.ImmutableArray methodLevelTests = DiscoverTests(assemblyPath, "TestCategory~MethodLevel"); + + // Act - Filter by "DataLevel" category (from TestDataRow) + System.Collections.Immutable.ImmutableArray dataLevelTests = DiscoverTests(assemblyPath, "TestCategory~DataLevel"); + + // Assert - The same test should be found by both filters since categories are merged + Assert.AreEqual(1, methodLevelTests.Length, "Should discover exactly 1 test with MethodLevel category"); + Assert.AreEqual(1, dataLevelTests.Length, "Should discover exactly 1 test with DataLevel category"); + + Microsoft.VisualStudio.TestPlatform.ObjectModel.TestCase methodTest = methodLevelTests[0]; + Microsoft.VisualStudio.TestPlatform.ObjectModel.TestCase dataTest = dataLevelTests[0]; + + Assert.AreEqual(methodTest.FullyQualifiedName, dataTest.FullyQualifiedName, "Both filters should find the same test"); + Assert.IsTrue(methodTest.DisplayName.Contains("method and data categories"), "Should be the test with combined categories"); + } + + [TestMethod] + public async Task TestCategoriesFromTestDataRow_ShouldExecuteCorrectly() + { + // Arrange + string assemblyPath = GetAssetFullPath(TestAssetName); + + // Act + System.Collections.Immutable.ImmutableArray testCases = DiscoverTests(assemblyPath, "FullyQualifiedName~TestCategoriesFromTestDataRowTests"); + System.Collections.Immutable.ImmutableArray testResults = await RunTestsAsync(testCases); + + // Assert - All tests should pass + VerifyE2E.TestsPassed( + testResults, + "Test with Integration and Slow categories", + "Test with Unit and Fast categories", + "Test with no additional categories", + "TestMethodWithRegularData (\"value4\",4)", + "Test with method and data categories"); + + VerifyE2E.FailedTestCount(testResults, 0); + } +} diff --git a/test/IntegrationTests/TestAssets/TestCategoriesFromTestDataRowProject/TestCategoriesFromTestDataRowProject.csproj b/test/IntegrationTests/TestAssets/TestCategoriesFromTestDataRowProject/TestCategoriesFromTestDataRowProject.csproj new file mode 100644 index 0000000000..05f68e1367 --- /dev/null +++ b/test/IntegrationTests/TestAssets/TestCategoriesFromTestDataRowProject/TestCategoriesFromTestDataRowProject.csproj @@ -0,0 +1,12 @@ + + + net462 + enable + enable + false + + + + + + diff --git a/test/IntegrationTests/TestAssets/TestCategoriesFromTestDataRowProject/TestCategoriesFromTestDataRowTests.cs b/test/IntegrationTests/TestAssets/TestCategoriesFromTestDataRowProject/TestCategoriesFromTestDataRowTests.cs new file mode 100644 index 0000000000..3bad685d52 --- /dev/null +++ b/test/IntegrationTests/TestAssets/TestCategoriesFromTestDataRowProject/TestCategoriesFromTestDataRowTests.cs @@ -0,0 +1,71 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace TestCategoriesFromTestDataRowProject; + +[TestClass] +public class TestCategoriesFromTestDataRowTests +{ + [TestMethod] + [DynamicData(nameof(GetTestDataWithCategories))] + public void TestMethodWithDynamicDataCategories(string value, int number) + { + Assert.IsTrue(!string.IsNullOrEmpty(value)); + Assert.IsTrue(number > 0); + } + + public static IEnumerable> GetTestDataWithCategories() + { + // Test data row with categories + yield return new TestDataRow<(string, int)>(("value1", 1)) + { + TestCategories = ["Integration", "Slow"], + DisplayName = "Test with Integration and Slow categories", + }; + + // Test data row with different categories + yield return new TestDataRow<(string, int)>(("value2", 2)) + { + TestCategories = ["Unit", "Fast"], + DisplayName = "Test with Unit and Fast categories", + }; + + // Test data row with no categories (should inherit from method level) + yield return new TestDataRow<(string, int)>(("value3", 3)) + { + DisplayName = "Test with no additional categories", + }; + } + + public static IEnumerable GetRegularTestData() + { + // Regular data row (not TestDataRow) - should work as before + yield return new object[] { "value4", 4 }; + } + + [TestMethod] + [DynamicData(nameof(GetRegularTestData))] + public void TestMethodWithRegularData(string value, int number) + { + Assert.IsTrue(!string.IsNullOrEmpty(value)); + Assert.IsTrue(number > 0); + } + + [TestCategory("MethodLevel")] + [TestMethod] + [DynamicData(nameof(GetTestDataWithCategoriesForMethodWithCategory))] + public void TestMethodWithMethodLevelCategoriesAndDataCategories(string value) + => Assert.IsTrue(!string.IsNullOrEmpty(value)); + + public static IEnumerable> GetTestDataWithCategoriesForMethodWithCategory() + { + // This should have both "MethodLevel" and "DataLevel" categories + yield return new TestDataRow("test") + { + TestCategories = ["DataLevel"], + DisplayName = "Test with method and data categories", + }; + } +} diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Helpers/TestDataSourceHelpersTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Helpers/TestDataSourceHelpersTests.cs new file mode 100644 index 0000000000..c470744a70 --- /dev/null +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Helpers/TestDataSourceHelpersTests.cs @@ -0,0 +1,118 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Helpers; + +using TestFramework.ForTestingMSTest; + +namespace Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.UnitTests.Helpers; + +public class TestDataSourceHelpersTests : TestContainer +{ + public void TryHandleITestDataRow_WithTestDataRow_ShouldExtractTestCategories() + { + // Arrange + var testData = new TestDataRow("test_value") + { + TestCategories = ["Category1", "Category2"], + IgnoreMessage = "ignore_message", + DisplayName = "display_name", + }; + object?[] dataArray = [testData]; + ParameterInfo[] parameters = []; // No method parameters for this test + + // Act + bool result = TestDataSourceHelpers.TryHandleITestDataRow( + dataArray, + parameters, + out object?[] extractedData, + out string? ignoreMessage, + out string? displayName, + out IList? testCategories); + + // Assert + Verify(result); + Verify(extractedData != null); + Verify(extractedData.Length == 1); + Verify((string?)extractedData[0] == "test_value"); + Verify(ignoreMessage == "ignore_message"); + Verify(displayName == "display_name"); + Verify(testCategories != null); + Verify(testCategories.Count == 2); + Verify(testCategories.Contains("Category1")); + Verify(testCategories.Contains("Category2")); + } + + public void TryHandleITestDataRow_WithTestDataRowNullCategories_ShouldReturnNullCategories() + { + // Arrange + var testData = new TestDataRow("test_value"); + object?[] dataArray = [testData]; + ParameterInfo[] parameters = []; + + // Act + bool result = TestDataSourceHelpers.TryHandleITestDataRow( + dataArray, + parameters, + out _, + out _, + out _, + out IList? testCategories); + + // Assert + Verify(result); + Verify(testCategories == null); + } + + public void TryHandleITestDataRow_WithNonTestDataRow_ShouldReturnFalseAndNullCategories() + { + // Arrange + object?[] dataArray = ["regular_string"]; + ParameterInfo[] parameters = []; + + // Act + bool result = TestDataSourceHelpers.TryHandleITestDataRow( + dataArray, + parameters, + out object?[] extractedData, + out string? ignoreMessage, + out string? displayName, + out IList? testCategories); + + // Assert + Verify(!result); + Verify(extractedData == dataArray); + Verify(ignoreMessage == null); + Verify(displayName == null); + Verify(testCategories == null); + } + + public void TryHandleITestDataRow_BackwardCompatibilityOverload_ShouldWork() + { + // Arrange + var testData = new TestDataRow("test_value") + { + TestCategories = ["Category1", "Category2"], + IgnoreMessage = "ignore_message", + DisplayName = "display_name", + }; + object?[] dataArray = [testData]; + ParameterInfo[] parameters = []; + + // Act + bool result = TestDataSourceHelpers.TryHandleITestDataRow( + dataArray, + parameters, + out object?[] extractedData, + out string? ignoreMessage, + out string? displayName); + + // Assert - should work without TestCategories parameter + Verify(result); + Verify(extractedData != null); + Verify(extractedData.Length == 1); + Verify((string?)extractedData[0] == "test_value"); + Verify(ignoreMessage == "ignore_message"); + Verify(displayName == "display_name"); + } +} diff --git a/test/UnitTests/TestFramework.UnitTests/TestDataRowTests.cs b/test/UnitTests/TestFramework.UnitTests/TestDataRowTests.cs new file mode 100644 index 0000000000..44f6138dec --- /dev/null +++ b/test/UnitTests/TestFramework.UnitTests/TestDataRowTests.cs @@ -0,0 +1,79 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using TestFramework.ForTestingMSTest; + +namespace Microsoft.VisualStudio.TestPlatform.TestFramework.UnitTests; + +public class TestDataRowTests : TestContainer +{ + public void TestDataRowShouldInitializeWithValue() + { + string value = "test_value"; + var testDataRow = new TestDataRow(value); + + Verify(testDataRow.Value == value); + Verify(testDataRow.IgnoreMessage == null); + Verify(testDataRow.DisplayName == null); + Verify(testDataRow.TestCategories == null); + } + + public void TestDataRowShouldAllowSettingTestCategories() + { + string value = "test_value"; + var testDataRow = new TestDataRow(value); + var testCategories = new List { "Category1", "Category2" }; + + testDataRow.TestCategories = testCategories; + + Verify(testDataRow.TestCategories == testCategories); + Verify(testDataRow.TestCategories.Count == 2); + Verify(testDataRow.TestCategories.Contains("Category1")); + Verify(testDataRow.TestCategories.Contains("Category2")); + } + + public void TestDataRowShouldImplementITestDataRowForTestCategories() + { + string value = "test_value"; + var testDataRow = new TestDataRow(value); + var testCategories = new List { "Integration", "Unit" }; + testDataRow.TestCategories = testCategories; + + ITestDataRow dataRow = testDataRow; + + Verify(dataRow.TestCategories != null); + Verify(dataRow.TestCategories.Count == 2); + Verify(dataRow.TestCategories.Contains("Integration")); + Verify(dataRow.TestCategories.Contains("Unit")); + } + + public void TestDataRowShouldAllowNullTestCategories() + { + string value = "test_value"; + var testDataRow = new TestDataRow(value) + { + TestCategories = null, + }; + + Verify(testDataRow.TestCategories == null); + + ITestDataRow dataRow = testDataRow; + Verify(dataRow.TestCategories == null); + } + + public void TestDataRowShouldAllowEmptyTestCategories() + { + string value = "test_value"; + var testDataRow = new TestDataRow(value); + var emptyCategories = new List(); + + testDataRow.TestCategories = emptyCategories; + + Verify(testDataRow.TestCategories == emptyCategories); + Verify(testDataRow.TestCategories.Count == 0); + + ITestDataRow dataRow = testDataRow; + Verify(dataRow.TestCategories != null); + Verify(dataRow.TestCategories.Count == 0); + } +} From 9c83ce3cbd0065702f5b19d7c1aeb12decde6eef Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Wed, 16 Jul 2025 18:36:29 +1000 Subject: [PATCH 232/541] remove some un-used polyfills (#6042) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Amaury Levé --- .../Helpers/SystemPolyfills.cs | 166 +----------------- 1 file changed, 2 insertions(+), 164 deletions(-) diff --git a/src/Analyzers/MSTest.SourceGeneration/Helpers/SystemPolyfills.cs b/src/Analyzers/MSTest.SourceGeneration/Helpers/SystemPolyfills.cs index f3e2817245..6a80a1ca13 100644 --- a/src/Analyzers/MSTest.SourceGeneration/Helpers/SystemPolyfills.cs +++ b/src/Analyzers/MSTest.SourceGeneration/Helpers/SystemPolyfills.cs @@ -3,62 +3,21 @@ #if !NETCOREAPP #pragma warning disable SA1403 // File may only contain a single namespace -#pragma warning disable SA1623 // Property summary documentation should match accessors #pragma warning disable SA1642 // Constructor summary documentation should begin with standard text -#pragma warning disable SA1502 // Element should not be on a single line +#pragma warning disable SA1623 // Property summary documentation should match accessors using System.ComponentModel; namespace System.Runtime.CompilerServices { [EditorBrowsable(EditorBrowsableState.Never)] - internal static class IsExternalInit { } + internal static class IsExternalInit; } // This was copied from https://github.com/dotnet/coreclr/blob/60f1e6265bd1039f023a82e0643b524d6aaf7845/src/System.Private.CoreLib/shared/System/Diagnostics/CodeAnalysis/NullableAttributes.cs // and updated to have the scope of the attributes be internal. namespace System.Diagnostics.CodeAnalysis { - /// Specifies that null is allowed as an input even if the corresponding type disallows it. - [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property, Inherited = false)] - internal sealed class AllowNullAttribute : Attribute { } - - /// Specifies that null is disallowed as an input even if the corresponding type allows it. - [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property, Inherited = false)] - internal sealed class DisallowNullAttribute : Attribute { } - - /// Specifies that an output may be null even if the corresponding type disallows it. - [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue, Inherited = false)] - internal sealed class MaybeNullAttribute : Attribute { } - - /// Specifies that when a method returns , the parameter may be null even if the corresponding type disallows it. - [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] - internal sealed class MaybeNullWhenAttribute : Attribute - { - /// Initializes the attribute with the specified return value condition. - /// - /// The return value condition. If the method returns this value, the associated parameter may be null. - /// - public MaybeNullWhenAttribute(bool returnValue) => ReturnValue = returnValue; - - /// Gets the return value condition. - public bool ReturnValue { get; } - } - - /// Specifies that the output will be non-null if the named parameter is non-null. - [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue, AllowMultiple = true, Inherited = false)] - internal sealed class NotNullIfNotNullAttribute : Attribute - { - /// Initializes the attribute with the associated parameter name. - /// - /// The associated parameter name. The output will be non-null if the argument to the parameter specified is non-null. - /// - public NotNullIfNotNullAttribute(string parameterName) => ParameterName = parameterName; - - /// Gets the associated parameter name. - public string ParameterName { get; } - } - /// Specifies that when a method returns , the parameter will not be null even if the corresponding type allows it. [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed class NotNullWhenAttribute : Attribute @@ -72,127 +31,6 @@ internal sealed class NotNullWhenAttribute : Attribute /// Gets the return value condition. public bool ReturnValue { get; } } - - /// Specifies that the method or property will ensure that the listed field and property members have not-null values. - [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] - internal sealed class MemberNotNullAttribute : Attribute - { - /// Initializes the attribute with a field or property member. - /// - /// The field or property member that is promised to be not-null. - /// - public MemberNotNullAttribute(string member) => Members = [member]; - - /// Initializes the attribute with the list of field and property members. - /// - /// The list of field and property members that are promised to be not-null. - /// - public MemberNotNullAttribute(params string[] members) => Members = members; - - /// Gets field or property member names. - public string[] Members { get; } - } - - /// Specifies that the method or property will ensure that the listed field and property members have not-null values when returning with the specified return value condition. - [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] - internal sealed class MemberNotNullWhenAttribute : Attribute - { - /// Initializes the attribute with the specified return value condition and a field or property member. - /// - /// The return value condition. If the method returns this value, the associated parameter will not be null. - /// - /// - /// The field or property member that is promised to be not-null. - /// - public MemberNotNullWhenAttribute(bool returnValue, string member) - { - ReturnValue = returnValue; - Members = [member]; - } - - /// Initializes the attribute with the specified return value condition and list of field and property members. - /// - /// The return value condition. If the method returns this value, the associated parameter will not be null. - /// - /// - /// The list of field and property members that are promised to be not-null. - /// - public MemberNotNullWhenAttribute(bool returnValue, params string[] members) - { - ReturnValue = returnValue; - Members = members; - } - - /// Gets the return value condition. - public bool ReturnValue { get; } - - /// Gets field or property member names. - public string[] Members { get; } - } } #endif - -#if !NET7_0_OR_GREATER -namespace System.Diagnostics.CodeAnalysis -{ - /// - /// Specifies that this constructor sets all required members for the current type, - /// and callers do not need to set any required members themselves. - /// - [AttributeUsage(AttributeTargets.Constructor, AllowMultiple = false, Inherited = false)] - internal sealed class SetsRequiredMembersAttribute : Attribute - { - } -} - -namespace System.Runtime.CompilerServices -{ - /// - /// Indicates that compiler support for a particular feature is required for the location where this attribute is applied. - /// - [AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = false)] - internal sealed class CompilerFeatureRequiredAttribute : Attribute - { - /// - /// Creates a new instance of the type. - /// - /// The name of the feature to indicate. - public CompilerFeatureRequiredAttribute(string featureName) => FeatureName = featureName; - - /// - /// The name of the compiler feature. - /// - public string FeatureName { get; } - - /// - /// If true, the compiler can choose to allow access to the location where this attribute is applied if it does not understand . - /// - public bool IsOptional { get; set; } - - /// - /// The used for the ref structs C# feature. - /// - public const string RefStructs = nameof(RefStructs); - - /// - /// The used for the required members C# feature. - /// - public const string RequiredMembers = nameof(RequiredMembers); - } - - /// - /// Specifies that a type has required members or that a member is required. - /// - [AttributeUsage( - AttributeTargets.Class | - AttributeTargets.Struct | - AttributeTargets.Field | - AttributeTargets.Property, - AllowMultiple = false, - Inherited = false)] - internal sealed class RequiredMemberAttribute : Attribute - { - } -} -#endif From 8f41c7bd43d83e552557e478b29a95b2ce422f85 Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Wed, 16 Jul 2025 08:38:35 +0000 Subject: [PATCH 233/541] [main] Update dependencies from devdiv/DevDiv/vs-code-coverage, dotnet/arcade (#5937) [main] Update dependencies from devdiv/DevDiv/vs-code-coverage, dotnet/arcade --- eng/Version.Details.xml | 16 ++++++++-------- eng/Versions.props | 4 ++-- global.json | 2 +- 3 files changed, 11 insertions(+), 11 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index 2500a84cd2..a0bbb0706e 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -1,21 +1,21 @@ - + https://github.com/dotnet/arcade - aea743edf7c9345cfdbdf9593756973baadc6b37 + 4e526204e83e615efe8eb5743be7fbccfa4e492a - + https://github.com/dotnet/arcade - aea743edf7c9345cfdbdf9593756973baadc6b37 + 4e526204e83e615efe8eb5743be7fbccfa4e492a - + https://github.com/dotnet/arcade - aea743edf7c9345cfdbdf9593756973baadc6b37 + 4e526204e83e615efe8eb5743be7fbccfa4e492a - + https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage - 910a5566a1c5a9d179c58b3497e763aa888a1b1c + 06325faa0d16bac193af8d51026f03208034880d diff --git a/eng/Versions.props b/eng/Versions.props index a0596001d8..f3deca5315 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -7,7 +7,7 @@ preview - 10.0.0-beta.25353.1 - 17.15.0-preview.25352.2 + 10.0.0-beta.25358.3 + 18.0.0-preview.25365.3 diff --git a/global.json b/global.json index fa4d243f01..f874223fd2 100644 --- a/global.json +++ b/global.json @@ -33,7 +33,7 @@ "rollForward": "latestFeature" }, "msbuild-sdks": { - "Microsoft.DotNet.Arcade.Sdk": "10.0.0-beta.25353.1", + "Microsoft.DotNet.Arcade.Sdk": "10.0.0-beta.25358.3", "MSBuild.Sdk.Extras": "3.0.44" } } From c1f484b493fb63da52447eb444c739fe97ade1cb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Wed, 16 Jul 2025 12:00:13 +0200 Subject: [PATCH 234/541] Update copilot instructions (#6062) --- .github/copilot-instructions.md | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index 168d8307cb..0ca019af93 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -2,10 +2,11 @@ This is a .NET based repository that contains the MSTest testing framework and M ## Code Standards -You MUST follow all code-formatting and naming conventions defined in [`.editorconfig`](./.editorconfig). +You MUST follow all code-formatting and naming conventions defined in [`.editorconfig`](../.editorconfig). In addition to the rules enforced by `.editorconfig`, you SHOULD: +- Favor style and conventions that are consistent with the existing codebase. - Prefer file-scoped namespace declarations and single-line using directives. - Ensure that the final return statement of a method is on its own line. - Use pattern matching and switch expressions wherever possible. @@ -14,7 +15,10 @@ In addition to the rules enforced by `.editorconfig`, you SHOULD: - Trust the C# null annotations and don't add null checks when the type system says a value cannot be null. - Prefer `?.` if applicable (e.g. `scope?.Dispose()`). - Use `ObjectDisposedException.ThrowIf` where applicable. -- Respect StyleCop.Analyzers rules. +- Respect StyleCop.Analyzers rules, in particular: + - SA1028: Code must not contain trailing whitespace + - SA1316: Tuple element names should use correct casing + - SA1518: File is required to end with a single newline character You MUST minimize adding public API surface area but any newly added public API MUST be declared in the related `PublicAPI.Unshipped.txt` file. @@ -23,9 +27,10 @@ You MUST minimize adding public API surface area but any newly added public API Anytime you add a new localization resource, you MUST: - Add a corresponding entry in the localization resource file. - Add an entry in all `*.xlf` files related to the modified `.resx` file. +- Do not modify existing entries in '*.xlf' files unless you are also modifying the corresponding `.resx` file. ## Testing Guidelines - Tests for MTP and MSTest analyzers MUST use MSTest. -- Unit tests for MSTest MUST use the internal test framework defined in [`TestFramework.ForTestingMSTest`](./test/Utilities/TestFramework.ForTestingMSTest). +- Unit tests for MSTest MUST use the internal test framework defined in [`TestFramework.ForTestingMSTest`](../test/Utilities/TestFramework.ForTestingMSTest). - All assertions must be written using FluentAssertions style of assertion. From cb805a106c77552551e16f10202db6adefe33b89 Mon Sep 17 00:00:00 2001 From: dotnet bot Date: Wed, 16 Jul 2025 12:11:19 +0200 Subject: [PATCH 235/541] Localized file check-in by OneLocBuild Task: Build definition ID 1218: Build ID 2751225 --- .../MSTest.Analyzers/xlf/Resources.cs.xlf | 4 +- .../MSTest.Analyzers/xlf/Resources.de.xlf | 4 +- .../MSTest.Analyzers/xlf/Resources.es.xlf | 4 +- .../MSTest.Analyzers/xlf/Resources.fr.xlf | 74 ++++---- .../MSTest.Analyzers/xlf/Resources.it.xlf | 48 +++--- .../MSTest.Analyzers/xlf/Resources.ja.xlf | 104 ++++++------ .../MSTest.Analyzers/xlf/Resources.ko.xlf | 104 ++++++------ .../MSTest.Analyzers/xlf/Resources.pl.xlf | 34 ++-- .../MSTest.Analyzers/xlf/Resources.pt-BR.xlf | 40 ++--- .../MSTest.Analyzers/xlf/Resources.ru.xlf | 4 +- .../MSTest.Analyzers/xlf/Resources.tr.xlf | 18 +- .../xlf/Resources.zh-Hans.xlf | 158 +++++++++--------- .../xlf/Resources.zh-Hant.xlf | 100 +++++------ 13 files changed, 348 insertions(+), 348 deletions(-) diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf index aa95370756..5e787821df 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf @@ -751,12 +751,12 @@ Typ deklarující tyto metody by měl také respektovat následující pravidla: Type containing '[TestMethod]' should be marked with '[TestClass]', otherwise the test method will be silently ignored. - Typ obsahující [TestMethod] by měl mít označení [TestClass], jinak bude testovací metoda bez jakéhokoli upozornění ignorována. + Type containing '[TestMethod]' should be marked with '[TestClass]', otherwise the test method will be silently ignored. Type '{0}' contains test methods and should be marked with '[TestClass]' - Typ {0} obsahuje testovací metody a měl by mít označení [TestClass]. + Type '{0}' contains test methods and should be marked with '[TestClass]' diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf index 9725c61ef3..ccbde6b1a4 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf @@ -752,12 +752,12 @@ Der Typ, der diese Methoden deklariert, sollte auch die folgenden Regeln beachte Type containing '[TestMethod]' should be marked with '[TestClass]', otherwise the test method will be silently ignored. - Der Typ, der "[TestMethod]" enthält, sollte mit "[TestClass]" gekennzeichnet werden, andernfalls wird die Testmethode im Hintergrund ignoriert. + Type containing '[TestMethod]' should be marked with '[TestClass]', otherwise the test method will be silently ignored. Type '{0}' contains test methods and should be marked with '[TestClass]' - Der Typ "{0}" enthält Testmethoden und muss mit "[TestClass]" gekennzeichnet werden. + Type '{0}' contains test methods and should be marked with '[TestClass]' diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf index 7f84dff4f1..81f1f62818 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf @@ -751,12 +751,12 @@ El tipo que declara estos métodos también debe respetar las reglas siguientes: Type containing '[TestMethod]' should be marked with '[TestClass]', otherwise the test method will be silently ignored. - El tipo que contiene '[TestMethod]' debe marcarse con '[TestClass]'; de lo contrario, el método de prueba se omitirá de forma silenciosa. + Type containing '[TestMethod]' should be marked with '[TestClass]', otherwise the test method will be silently ignored. Type '{0}' contains test methods and should be marked with '[TestClass]' - El tipo '{0}' contiene métodos de prueba y debe marcarse con '[TestClass]' + Type '{0}' contains test methods and should be marked with '[TestClass]' diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf index 2d80aefa8e..22234547e0 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf @@ -19,7 +19,7 @@ The type declaring these methods should also respect the following rules: -The class shouldn't be 'static' -The class should be marked with '[TestClass]' (or a derived attribute) -the class should not be generic. - Les méthodes marqués par « [AssemblyCleanup] » doivent respecter le schéma suivant pour être valides : + Les méthodes marquées par « [AssemblyCleanup] » doivent respecter le schéma suivant pour être valides : -il ne peut pas être déclarée dans une classe générique – il doit être « public » – il doit être « static » @@ -31,9 +31,9 @@ The type declaring these methods should also respect the following rules: Le type déclarant ces méthodes doit également respecter les règles suivantes : Le type doit être une classe --Le type doit être « public » ou « internal » (si le projet de test utilise l’attribut ’[DiscoverInternals]’) --Le type ne doit pas être» ’static » --Le type doit être marqué par « [TestClass] » (ou un attribut dérivé) +-La classe doit être « public » ou « internal » (si le projet de test utilise l’attribut ’[DiscoverInternals]’) +-La classe ne doit pas être» ’static » +-La classe doit être marquée par « [TestClass] » (ou un attribut dérivé) -la classe ne doit pas être générique. @@ -64,7 +64,7 @@ The type declaring these methods should also respect the following rules: -The class shouldn't be 'static' -The class should be marked with '[TestClass]' (or a derived attribute) -the class should not be generic. - Les méthodes marqués par « [AssemblyInitialize] » doivent respecter le schéma suivant pour être valides : + Les méthodes marquées par « [AssemblyInitialize] » doivent respecter le schéma suivant pour être valides : -il ne peut pas être déclarée dans une classe générique – il doit être « public » – il doit être « static » @@ -76,9 +76,9 @@ The type declaring these methods should also respect the following rules: Le type déclarant ces méthodes doit également respecter les règles suivantes : Le type doit être une classe --Le type doit être « public » ou « internal » (si le projet de test utilise l’attribut ’[DiscoverInternals]’) --Le type ne doit pas être» ’static » --Le type doit être marqué par « [TestClass] » (ou un attribut dérivé). +-La classe doit être « public » ou « internal » (si le projet de test utilise l’attribut ’[DiscoverInternals]’) +-La classe ne doit pas être» ’static » +-La classe doit être marquée par « [TestClass] » (ou un attribut dérivé). -la classe ne doit pas être générique. @@ -181,7 +181,7 @@ The type declaring these methods should also respect the following rules: -The class shouldn't be 'static' -If the class is 'sealed', it should be marked with '[TestClass]' (or a derived attribute) -the class should not be generic. - Les méthodes marqués par « [ClassCleanup] » doivent respecter le schéma suivant pour être valides : + Les méthodes marquées par « [ClassCleanup] » doivent respecter le schéma suivant pour être valides : -il ne peut pas être déclarée dans une classe générique si le mode ’InheritanceBehavior’ n’est pas activé – il doit être « public » – il doit être « static » @@ -195,9 +195,9 @@ The type declaring these methods should also respect the following rules: Le type déclarant ces méthodes doit également respecter les règles suivantes : Le type doit être une classe --Le type doit être « public » ou « internal » (si le projet de test utilise l’attribut ’[DiscoverInternals]’) --Le type ne doit pas être « static » --Si la classe est « sealed », elle doit être marqué avec « [TestClass] » (ou un attribut dérivé) +-La classe doit être « public » ou « internal » (si le projet de test utilise l’attribut ’[DiscoverInternals]’) +-La classe ne doit pas être « static » +-Si la classe est « sealed », elle doit être marquée avec « [TestClass] » (ou un attribut dérivé) -la classe ne doit pas être générique. @@ -230,7 +230,7 @@ The type declaring these methods should also respect the following rules: -The class shouldn't be 'static' -If the class is 'sealed', it should be marked with '[TestClass]' (or a derived attribute) -the class should not be generic. - Les méthodes marqués par « [ClassInitialize] » doivent respecter le schéma suivant pour être valides : + Les méthodes marquées par « [ClassInitialize] » doivent respecter le schéma suivant pour être valides : -il ne peut pas être déclarée dans une classe générique si le mode ’InheritanceBehavior’ n’est pas activé. – il doit être « public » – il doit être « static » @@ -244,9 +244,9 @@ The type declaring these methods should also respect the following rules: Le type déclarant ces méthodes doit également respecter les règles suivantes : Le type doit être une classe --Le type doit être « public » ou « internal » (si le projet de test utilise l’attribut ’[DiscoverInternals]’) --Le type ne doit pas être « static » --Si la classe est « sealed », elle doit être marqué avec « [TestClass] » (ou un attribut dérivé). +-La classe doit être « public » ou « internal » (si le projet de test utilise l’attribut ’[DiscoverInternals]’) +-La classe ne doit pas être « static » +-Si la classe est « sealed », elle doit être marquée avec « [TestClass] » (ou un attribut dérivé). -la classe ne doit pas être générique. @@ -524,7 +524,7 @@ Le type doit être une classe It's considered a good practice to have only test classes marked public in a test project. - C’est considéré comme une bonne pratique d’avoir uniquement des classes de test marqués comme publiques dans un projet de test. + C’est considéré comme une bonne pratique d’avoir uniquement des classes de test marquées comme publiques dans un projet de test. @@ -549,7 +549,7 @@ Le type doit être une classe Test class '{0}' should be valid - Le type de test « {0} » doit être valide + La classe de test « {0} » doit être valide @@ -582,7 +582,7 @@ Le type doit être une classe - it should be 'public' (or 'internal' if '[assembly: DiscoverInternals]' attribute is set) - it should not be 'static' (except if it contains only 'AssemblyInitialize' and/or 'AssemblyCleanup' methods) - it should not be generic. - Les classes de test, à savoir les classes marqués par l’attribut « [TestClass] », doivent respecter la disposition suivante pour être considérées comme valides par MSTest : + Les classes de test, à savoir les classes marquées par l’attribut « [TestClass] », doivent respecter la disposition suivante pour être considérées comme valides par MSTest : – Elle doit être « publique » (ou « interne » si l’attribut « [assembly : DiscoverInternals] » est défini) – Elle ne doit pas être « statique » (sauf si elle ne contient que des méthodes « AssemblyInitialize » et/ou « AssemblyCleanup ») – Elle ne doit pas être générique. @@ -595,17 +595,17 @@ Le type doit être une classe Test class should have at least one test method or be 'static' with method(s) marked by '[AssemblyInitialize]' and/or '[AssemblyCleanup]'. - Le type de test doit avoir au moins une méthode de test ou être « statique » avec une ou plusieurs méthodes marqués par « [AssemblyInitialize] » et/ou « [AssemblyCleanup] ». + La classe de test doit avoir au moins une méthode de test ou être « statique » avec une ou plusieurs méthodes marquées par « [AssemblyInitialize] » et/ou « [AssemblyCleanup] ». Test class '{0}' should have at least one test method or be 'static' with method(s) marked by '[AssemblyInitialize]' and/or '[AssemblyCleanup]' - Le type de test '{0}' doit avoir au moins une méthode de test ou être « statique » avec une ou plusieurs méthodes marqués par « [AssemblyInitialize] » et/ou « [AssemblyCleanup] » + La classe de test '{0}' doit avoir au moins une méthode de test ou être « statique » avec une ou plusieurs méthodes marquées par « [AssemblyInitialize] » et/ou « [AssemblyCleanup] » Test class should have test method - Le type de test doit avoir une méthode de test + La classe de test doit avoir une méthode de test @@ -624,7 +624,7 @@ The type declaring these methods should also respect the following rules: -The class should be 'public' or 'internal' (if the test project is using the '[DiscoverInternals]' attribute) -The class shouldn't be 'static' -If the class is 'sealed', it should be marked with '[TestClass]' (or a derived attribute). - Les méthodes marqués par « [TestCleanup] » doivent respecter le schéma suivant pour être valides : + Les méthodes marquées par « [TestCleanup] » doivent respecter le schéma suivant pour être valides : – il doit être « public » – il ne doit pas être « abstract » – il ne doit pas être « async void » @@ -636,9 +636,9 @@ The type declaring these methods should also respect the following rules: Le type déclarant ces méthodes doit également respecter les règles suivantes : Le type doit être une classe --Le type doit être « public » ou « internal » (si le projet de test utilise l’attribut ’[DiscoverInternals]’) --Le type ne doit pas être» ’static » --Si la classe est « sealed », elle doit être marqué avec « [TestClass] » (ou un attribut dérivé). +-La classe doit être « public » ou « internal » (si le projet de test utilise l’attribut ’[DiscoverInternals]’) +-La classe ne doit pas être» ’static » +-Si la classe est « sealed », elle doit être marquée avec « [TestClass] » (ou un attribut dérivé). @@ -683,7 +683,7 @@ The type declaring these methods should also respect the following rules: -The class should be 'public' or 'internal' (if the test project is using the '[DiscoverInternals]' attribute) -The class shouldn't be 'static' -If the class is 'sealed', it should be marked with '[TestClass]' (or a derived attribute). - Les méthodes marqués par [TestInitialize] doivent respecter le schéma suivant pour être valides : + Les méthodes marquées par [TestInitialize] doivent respecter le schéma suivant pour être valides : – il doit être « public » – il ne doit pas être « abstract » – il ne doit pas être « async void » @@ -695,9 +695,9 @@ The type declaring these methods should also respect the following rules: Le type déclarant ces méthodes doit également respecter les règles suivantes : Le type doit être une classe --Le type doit être « public » ou « internal » (si le projet de test utilise l’attribut ’[DiscoverInternals]’) --Le type ne doit pas être» ’static » --Si la classe est « sealed », elle doit être marqué avec « [TestClass] » (ou un attribut dérivé). +-La classe doit être « public » ou « internal » (si le projet de test utilise l’attribut ’[DiscoverInternals]’) +-La classe ne doit pas être» ’static » +-Si la classe est « sealed », elle doit être marquée avec « [TestClass] » (ou un attribut dérivé). @@ -719,7 +719,7 @@ Le type doit être une classe - return type should be 'void', 'Task' or 'ValueTask' - it should not be 'async void' - it should not be a special method (finalizer, operator...). - Les méthodes de test, c’est-à-dire les méthodes marqués de l’attribut « [TestMethod] », doivent respecter la disposition suivante pour être considérées comme valides par MSTest : + Les méthodes de test, c’est-à-dire les méthodes marquées de l’attribut « [TestMethod] », doivent respecter la disposition suivante pour être considérées comme valides par MSTest : – elle doit être « publique » (ou « interne » si l’attribut « [assembly : DiscoverInternals] » est défini) – elle ne doit pas être « statique » – elle peut être générique tant que les paramètres de type peuvent être déduits et que les types d’arguments sont compatibles @@ -736,7 +736,7 @@ Le type doit être une classe Test methods should not be ignored (marked with '[Ignore]'). - Les méthodes de test ne doivent pas être ignorées (marqués avec « [Ignorer] »). + Les méthodes de test ne doivent pas être ignorées (marquées avec « [Ignorer] »). @@ -751,12 +751,12 @@ Le type doit être une classe Type containing '[TestMethod]' should be marked with '[TestClass]', otherwise the test method will be silently ignored. - Le type contenant « [TestMethod] » doit être marqué avec « [TestClass] », sans quoi la méthode de test sera ignorée silencieusement. + Type containing '[TestMethod]' should be marked with '[TestClass]', otherwise the test method will be silently ignored. Type '{0}' contains test methods and should be marked with '[TestClass]' - Le type « {0} » contient des méthodes de test et doit être marqué avec « [TestClass] » + Type '{0}' contains test methods and should be marked with '[TestClass]' @@ -776,17 +776,17 @@ Le type doit être une classe [{0}] can only be set on methods marked with [TestMethod] - [{0}] ne peut être défini que sur les méthodes marqués avec [TestMethod] + [{0}] ne peut être défini que sur les méthodes marquées avec [TestMethod] [{0}] can only be set on methods marked with [TestMethod] - [{0}] ne peut être défini que sur les méthodes marqués avec [TestMethod] + [{0}] ne peut être défini que sur les méthodes marquées avec [TestMethod] The attribute '{0}' which derives from 'ConditionBaseAttribute' should be used only on classes marked with `TestClassAttribute` - L’attribut '{0}' qui dérive de 'ConditionBaseAttribute' doit être utilisé uniquement sur les classes marqués avec 'TestClassAttribute' + L’attribut '{0}' qui dérive de 'ConditionBaseAttribute' doit être utilisé uniquement sur les classes marquées avec 'TestClassAttribute' diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf index 2760189435..3016d41c56 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf @@ -31,10 +31,10 @@ The type declaring these methods should also respect the following rules: Anche il tipo che dichiara questi metodi deve rispettare le regole seguenti: -Il tipo deve essere una classe --Il tipo deve essere 'public' o 'internal' (se il progetto di test usa l'attributo '[DiscoverInternals]') --Il tipo non deve essere 'static' --Il tipo deve essere contrassegnata con '[TestClass]' (o un attributo derivato) --Il tipo non deve essere generica. +-La classe deve essere 'public' o 'internal' (se il progetto di test usa l'attributo '[DiscoverInternals]') +-La classe non deve essere 'static' +-La classe deve essere contrassegnata con '[TestClass]' (o un attributo derivato) +-La classe non deve essere generica. @@ -76,10 +76,10 @@ The type declaring these methods should also respect the following rules: Anche il tipo che dichiara questi metodi deve rispettare le regole seguenti: -Il tipo deve essere una classe --Il tipo deve essere 'public' o 'internal' (se il progetto di test usa l'attributo '[DiscoverInternals]') --Il tipo non deve essere 'static' --Il tipo deve essere contrassegnata con '[TestClass]' (o un attributo derivato). --Il tipo non deve essere generica. +-La classe deve essere 'public' o 'internal' (se il progetto di test usa l'attributo '[DiscoverInternals]') +-La classe non deve essere 'static' +-La classe deve essere contrassegnata con '[TestClass]' (o un attributo derivato). +-La classe non deve essere generica. @@ -195,10 +195,10 @@ The type declaring these methods should also respect the following rules: Anche il tipo che dichiara questi metodi deve rispettare le regole seguenti: -Il tipo deve essere una classe --Il tipo deve essere 'public' o 'internal' (se il progetto di test usa l'attributo '[DiscoverInternals]') --Il tipo non deve essere 'static' +-La classe deve essere 'public' o 'internal' (se il progetto di test usa l'attributo '[DiscoverInternals]') +-La classe non deve essere 'static' -Se la classe è 'sealed', deve essere contrassegnata con '[TestClass]' (o un attributo derivato) --Il tipo non deve essere generica. +-La classe non deve essere generica. @@ -244,10 +244,10 @@ The type declaring these methods should also respect the following rules: Anche il tipo che dichiara questi metodi deve rispettare le regole seguenti: -Il tipo deve essere una classe --Il tipo deve essere 'public' o 'internal' (se il progetto di test usa l'attributo '[DiscoverInternals]') --Il tipo non deve essere 'static' +-La classe deve essere 'public' o 'internal' (se il progetto di test usa l'attributo '[DiscoverInternals]') +-La classe non deve essere 'static' -Se la classe è 'sealed', deve essere contrassegnata con '[TestClass]' (o un attributo derivato) --Il tipo non deve essere generica. +-La classe non deve essere generica. @@ -549,7 +549,7 @@ Anche il tipo che dichiara questi metodi deve rispettare le regole seguenti: Test class '{0}' should be valid - Il tipo di test '{0}' deve essere valida + La classe di test '{0}' deve essere valida @@ -595,17 +595,17 @@ Anche il tipo che dichiara questi metodi deve rispettare le regole seguenti: Test class should have at least one test method or be 'static' with method(s) marked by '[AssemblyInitialize]' and/or '[AssemblyCleanup]'. - Il tipo di test deve avere almeno un metodo di test o essere 'static' con metodi contrassegnati da '[AssemblyInitialize]' e/o '[AssemblyCleanup]'. + La classe di test deve avere almeno un metodo di test o essere 'static' con metodi contrassegnati da '[AssemblyInitialize]' e/o '[AssemblyCleanup]'. Test class '{0}' should have at least one test method or be 'static' with method(s) marked by '[AssemblyInitialize]' and/or '[AssemblyCleanup]' - Il tipo di test '{0}' deve avere almeno un metodo di test o essere 'static' con metodi contrassegnati da '[AssemblyInitializate]' e/o '[AssemblyCleanup]' + La classe di test '{0}' deve avere almeno un metodo di test o essere 'static' con metodi contrassegnati da '[AssemblyInitializate]' e/o '[AssemblyCleanup]' Test class should have test method - Il tipo di test deve avere un metodo di test + La classe di test deve avere un metodo di test @@ -636,8 +636,8 @@ The type declaring these methods should also respect the following rules: Anche il tipo che dichiara questi metodi deve rispettare le regole seguenti: -Il tipo deve essere una classe --Il tipo deve essere 'public' o 'internal' (se il progetto di test usa l'attributo '[DiscoverInternals]') --Il tipo non deve essere 'static' +-La classe deve essere 'public' o 'internal' (se il progetto di test usa l'attributo '[DiscoverInternals]') +-La classe non deve essere 'static' -Se la classe è 'sealed', deve essere contrassegnata con '[TestClass]' (o un attributo derivato). @@ -695,8 +695,8 @@ The type declaring these methods should also respect the following rules: Anche il tipo che dichiara questi metodi deve rispettare le regole seguenti: -Il tipo deve essere una classe --Il tipo deve essere 'public' o 'internal' (se il progetto di test usa l'attributo '[DiscoverInternals]') --Il tipo non deve essere 'static' +-La classe deve essere 'public' o 'internal' (se il progetto di test usa l'attributo '[DiscoverInternals]') +-La classe non deve essere 'static' -Se la classe è 'sealed', deve essere contrassegnata con '[TestClass]' (o un attributo derivato). @@ -751,12 +751,12 @@ Anche il tipo che dichiara questi metodi deve rispettare le regole seguenti: Type containing '[TestMethod]' should be marked with '[TestClass]', otherwise the test method will be silently ignored. - Il tipo contenente '[TestMethod]' deve essere contrassegnato con '[TestClass]', altrimenti il metodo di test verrà ignorato automaticamente. + Type containing '[TestMethod]' should be marked with '[TestClass]', otherwise the test method will be silently ignored. Type '{0}' contains test methods and should be marked with '[TestClass]' - Il tipo '{0}' contiene metodi di test e deve essere contrassegnata come '[TestClass]' + Type '{0}' contains test methods and should be marked with '[TestClass]' diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf index e374a94b87..9b5f87e55e 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf @@ -20,7 +20,7 @@ The type declaring these methods should also respect the following rules: -The class should be marked with '[TestClass]' (or a derived attribute) -the class should not be generic. '[AssemblyCleanup]' でマークされたメソッドを有効にするには、次のレイアウトに従う必要があります: -- ジェネリック 型で宣言することはできません +- ジェネリック クラスで宣言することはできません - 'public' である必要があります - 'static' である必要があります - 'async void' にすることはできません @@ -30,11 +30,11 @@ The type declaring these methods should also respect the following rules: - 戻り値の型が 'void'、'Task'、または 'ValueTask' である必要があります これらのメソッドを宣言する型も、次の規則に従う必要があります: -- 型は型である必要があります -- 型は 'public' または 'internal' である必要があります (テスト プロジェクトが '[DiscoverInternals]' 属性を使用している場合) -- 型を 'static' にすることはできません -- 型は '[TestClass]' (または派生属性) でマークする必要があります -- 型をジェネリックにすることはできません。 +- 型はクラスである必要があります +- クラスは 'public' または 'internal' である必要があります (テスト プロジェクトが '[DiscoverInternals]' 属性を使用している場合) +- クラスを 'static' にすることはできません +- クラスは '[TestClass]' (または派生属性) でマークする必要があります +- クラスをジェネリックにすることはできません。 @@ -65,7 +65,7 @@ The type declaring these methods should also respect the following rules: -The class should be marked with '[TestClass]' (or a derived attribute) -the class should not be generic. '[AssemblyInitialize]' でマークされたメソッドを有効にするには、次のレイアウトに従う必要があります: -- ジェネリック 型で宣言することはできません +- ジェネリック クラスで宣言することはできません - 'public' である必要があります - 'static' である必要があります - 'async void' にすることはできません @@ -75,11 +75,11 @@ The type declaring these methods should also respect the following rules: - 戻り値の型が 'void'、'Task'、または 'ValueTask' である必要があります これらのメソッドを宣言する型も、次の規則に従う必要があります: -- 型は型である必要があります -- 型は 'public' または 'internal' である必要があります (テスト プロジェクトが '[DiscoverInternals]' 属性を使用している場合) -- 型を 'static' にすることはできません -- 型は '[TestClass]' (または派生属性) でマークする必要があります -- 型をジェネリックにすることはできません。 +- 型はクラスである必要があります +- クラスは 'public' または 'internal' である必要があります (テスト プロジェクトが '[DiscoverInternals]' 属性を使用している場合) +- クラスを 'static' にすることはできません +- クラスは '[TestClass]' (または派生属性) でマークする必要があります +- クラスをジェネリックにすることはできません。 @@ -182,7 +182,7 @@ The type declaring these methods should also respect the following rules: -If the class is 'sealed', it should be marked with '[TestClass]' (or a derived attribute) -the class should not be generic. '[ClassCleanup]' でマークされたメソッドを有効にするには、次のレイアウトに従う必要があります: -- 'InheritanceBehavior' モードが設定されていないと、ジェネリック 型で宣言できません +- 'InheritanceBehavior' モードが設定されていないと、ジェネリック クラスで宣言できません - 'public' である必要があります - 'static' である必要があります - 'async void' にすることはできません @@ -190,15 +190,15 @@ The type declaring these methods should also respect the following rules: - ジェネリックにすることはできません - パラメーターを受け取らないか、'TestContext' 型の 1 つのパラメーターを受け取る必要があります - 戻り値の型が 'void'、'Task'、または 'ValueTask' である必要があります -- 型が 'abstract' である場合は 'InheritanceBehavior.BeforeEachDerivedClass' 属性パラメーターを指定する必要があります -- 型が 'sealed' である場合は 'InheritanceBehavior.BeforeEachDerivedClass' 属性パラメーターを指定しない必要があります +- クラスが 'abstract' である場合は 'InheritanceBehavior.BeforeEachDerivedClass' 属性パラメーターを指定する必要があります +- クラスが 'sealed' である場合は 'InheritanceBehavior.BeforeEachDerivedClass' 属性パラメーターを指定しない必要があります これらのメソッドを宣言する型も、次の規則に従う必要があります: -- 型は型である必要があります -- 型は 'public' または 'internal' である必要があります (テスト プロジェクトが '[DiscoverInternals]' 属性を使用している場合) -- 型を 'static' にすることはできません -- 型が 'sealed' の場合は、'[TestClass]' (または派生属性) でマークする必要があります -- 型をジェネリックにすることはできません。 +- 型はクラスである必要があります +- クラスは 'public' または 'internal' である必要があります (テスト プロジェクトが '[DiscoverInternals]' 属性を使用している場合) +- クラスを 'static' にすることはできません +- クラスが 'sealed' の場合は、'[TestClass]' (または派生属性) でマークする必要があります +- クラスをジェネリックにすることはできません。 @@ -231,7 +231,7 @@ The type declaring these methods should also respect the following rules: -If the class is 'sealed', it should be marked with '[TestClass]' (or a derived attribute) -the class should not be generic. '[ClassInitialize]' でマークされたメソッドを有効にするには、次のレイアウトに従う必要があります: -- 'InheritanceBehavior' モードが設定されていないと、ジェネリック 型で宣言できません +- 'InheritanceBehavior' モードが設定されていないと、ジェネリック クラスで宣言できません - 'public' である必要があります - 'static' である必要があります - 'async void' にすることはできません @@ -239,15 +239,15 @@ The type declaring these methods should also respect the following rules: - ジェネリックにすることはできません - 'TestContext' 型のパラメーターを 1 つ受け取る必要があります - 戻り値の型が 'void'、'Task'、または 'ValueTask' である必要があります -- 型が 'abstract' である場合は 'InheritanceBehavior.BeforeEachDerivedClass' 属性パラメーターーを指定する必要があります -- 型が 'sealed' である場合は 'InheritanceBehavior.BeforeEachDerivedClass' 属性パラメーターーを指定しない必要があります +- クラスが 'abstract' である場合は 'InheritanceBehavior.BeforeEachDerivedClass' 属性パラメーターーを指定する必要があります +- クラスが 'sealed' である場合は 'InheritanceBehavior.BeforeEachDerivedClass' 属性パラメーターーを指定しない必要があります これらのメソッドを宣言する型も、次の規則に従う必要があります: -- 型は型である必要があります -- 型は 'public' または 'internal' である必要があります (テスト プロジェクトが '[DiscoverInternals]' 属性を使用している場合) -- 型を 'static' にすることはできません -- 型が 'sealed' の場合は、'[TestClass]' (または派生属性) でマークする必要があります -- 型をジェネリックにすることはできません。 +- 型はクラスである必要があります +- クラスは 'public' または 'internal' である必要があります (テスト プロジェクトが '[DiscoverInternals]' 属性を使用している場合) +- クラスを 'static' にすることはできません +- クラスが 'sealed' の場合は、'[TestClass]' (または派生属性) でマークする必要があります +- クラスをジェネリックにすることはできません。 @@ -333,7 +333,7 @@ The type declaring these methods should also respect the following rules: Member '{0}' already exists in the base class - メンバー '{0}' は既に基本型に存在します + メンバー '{0}' は既に基本クラスに存在します @@ -524,7 +524,7 @@ The type declaring these methods should also respect the following rules: It's considered a good practice to have only test classes marked public in a test project. - テスト プロジェクトでは、テスト 型のみをパブリックとしてマークすることをお勧めします。 + テスト プロジェクトでは、テスト クラスのみをパブリックとしてマークすることをお勧めします。 @@ -534,7 +534,7 @@ The type declaring these methods should also respect the following rules: Public types should be test classes - パブリック型はテスト 型である必要があります + パブリック型はテスト クラスである必要があります @@ -549,7 +549,7 @@ The type declaring these methods should also respect the following rules: Test class '{0}' should be valid - テスト 型 '{0}' は有効である必要があります + テスト クラス '{0}' は有効である必要があります @@ -564,7 +564,7 @@ The type declaring these methods should also respect the following rules: Without using 'ClassCleanupBehavior.EndOfClass', the '[ClassCleanup]' will by default be run at the end of the assembly and not at the end of the class. - 'ClassCleanupBehavior.EndOfClass' を使用しない場合、'[ClassCleanup]' は既定でアセンブリの最後に実行され、型の最後には実行されません。 + 'ClassCleanupBehavior.EndOfClass' を使用しない場合、'[ClassCleanup]' は既定でアセンブリの最後に実行され、クラスの最後には実行されません。 @@ -582,7 +582,7 @@ The type declaring these methods should also respect the following rules: - it should be 'public' (or 'internal' if '[assembly: DiscoverInternals]' attribute is set) - it should not be 'static' (except if it contains only 'AssemblyInitialize' and/or 'AssemblyCleanup' methods) - it should not be generic. - テスト 型 ('[TestClass]' 属性でマークされた型) は、MSTest によって有効と見なされるように、次のレイアウトを考慮する必要があります: + テスト クラス ('[TestClass]' 属性でマークされたクラス) は、MSTest によって有効と見なされるように、次のレイアウトを考慮する必要があります: - 'public' である必要があります ('[assembly: DiscoverInternals]' 属性が設定されている場合は 'internal' である必要があります) - 'static' にすることはできません ('AssemblyInitialize' メソッドおよび/または 'AssemblyCleanup' メソッドのみが含まれる場合は除きます) - ジェネリックにすることはできません。 @@ -590,22 +590,22 @@ The type declaring these methods should also respect the following rules: Test classes should have valid layout - テスト 型には有効なレイアウトが必要です + テスト クラスには有効なレイアウトが必要です Test class should have at least one test method or be 'static' with method(s) marked by '[AssemblyInitialize]' and/or '[AssemblyCleanup]'. - テスト 型には、少なくとも 1 つのテスト メソッドがあるか、'[AssemblyInitialize]' または '[AssemblyCleanup]' によってマークされたメソッドを含む 'static' である必要があります。 + テスト クラスには、少なくとも 1 つのテスト メソッドがあるか、'[AssemblyInitialize]' または '[AssemblyCleanup]' によってマークされたメソッドを含む 'static' である必要があります。 Test class '{0}' should have at least one test method or be 'static' with method(s) marked by '[AssemblyInitialize]' and/or '[AssemblyCleanup]' - テスト 型 '{0}' には、少なくとも 1 つのテスト メソッドがあるか、'[AssemblyInitialize]' または '[AssemblyCleanup]' によってマークされたメソッドを含む 'static' である必要があります。 + テスト クラス '{0}' には、少なくとも 1 つのテスト メソッドがあるか、'[AssemblyInitialize]' または '[AssemblyCleanup]' によってマークされたメソッドを含む 'static' である必要があります。 Test class should have test method - テスト 型にはテスト メソッドが必要です + テスト クラスにはテスト メソッドが必要です @@ -635,10 +635,10 @@ The type declaring these methods should also respect the following rules: - 戻り値の型が 'void'、'Task'、または 'ValueTask' である必要があります これらのメソッドを宣言する型も、次の規則に従う必要があります: -- 型は型である必要があります -- 型は 'public' または 'internal' である必要があります (テスト プロジェクトが '[DiscoverInternals]' 属性を使用している場合) -- 型を 'static' にすることはできません --型が 'sealed' の場合は、'[TestClass]' (または派生属性) でマークする必要があります。 +- 型はクラスである必要があります +- クラスは 'public' または 'internal' である必要があります (テスト プロジェクトが '[DiscoverInternals]' 属性を使用している場合) +- クラスを 'static' にすることはできません +-クラスが 'sealed' の場合は、'[TestClass]' (または派生属性) でマークする必要があります。 @@ -694,10 +694,10 @@ The type declaring these methods should also respect the following rules: - 戻り値の型が 'void'、'Task'、または 'ValueTask' である必要があります これらのメソッドを宣言する型も、次の規則に従う必要があります: -- 型は型である必要があります -- 型は 'public' または 'internal' である必要があります (テスト プロジェクトが '[DiscoverInternals]' 属性を使用している場合) -- 型を 'static' にすることはできません --型が 'sealed' の場合は、'[TestClass]' (または派生属性) でマークする必要があります。 +- 型はクラスである必要があります +- クラスは 'public' または 'internal' である必要があります (テスト プロジェクトが '[DiscoverInternals]' 属性を使用している場合) +- クラスを 'static' にすることはできません +-クラスが 'sealed' の場合は、'[TestClass]' (または派生属性) でマークする必要があります。 @@ -751,12 +751,12 @@ The type declaring these methods should also respect the following rules: Type containing '[TestMethod]' should be marked with '[TestClass]', otherwise the test method will be silently ignored. - 連続する型 '[TestMethod]' は '[TestClass]' でマークする必要があります。それ以外の場合、テスト メソッドは暗黙的に無視されます。 + Type containing '[TestMethod]' should be marked with '[TestClass]', otherwise the test method will be silently ignored. Type '{0}' contains test methods and should be marked with '[TestClass]' - 型 '{0}' にはテスト メソッドが含まれており、'[TestClass]' でマークする必要があります + Type '{0}' contains test methods and should be marked with '[TestClass]' @@ -786,12 +786,12 @@ The type declaring these methods should also respect the following rules: The attribute '{0}' which derives from 'ConditionBaseAttribute' should be used only on classes marked with `TestClassAttribute` - 'ConditionBaseAttribute' から派生する属性 '{0}' は、'TestClassAttribute' でマークされた型でのみ使用する必要があります + 'ConditionBaseAttribute' から派生する属性 '{0}' は、'TestClassAttribute' でマークされたクラスでのみ使用する必要があります Use 'ConditionBaseAttribute' on test classes - テスト 型で 'ConditionBaseAttribute' を使用する + テスト クラスで 'ConditionBaseAttribute' を使用する @@ -811,12 +811,12 @@ The type declaring these methods should also respect the following rules: '[DeploymentItem]' can be specified only on test class or test method - '[DeploymentItem]' は、テスト 型またはテスト メソッドでのみ指定できます + '[DeploymentItem]' は、テスト クラスまたはテスト メソッドでのみ指定できます '[DeploymentItem]' can be specified only on test class or test method - '[DeploymentItem]' は、テスト 型またはテスト メソッドでのみ指定できます + '[DeploymentItem]' は、テスト クラスまたはテスト メソッドでのみ指定できます diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf index bed02c35ee..f7a0d60b2d 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf @@ -20,7 +20,7 @@ The type declaring these methods should also respect the following rules: -The class should be marked with '[TestClass]' (or a derived attribute) -the class should not be generic. '[AssemblyCleanup]'으로 표시된 메서드가 유효하려면 다음 레이아웃을 따라야 합니다. -- 제네릭 형식에서 선언할 수 없습니다. +- 제네릭 클래스에서 선언할 수 없습니다. - 'public'이어야 합니다. - 'static'이어야 합니다. - 'async void'가 아니어야 합니다. @@ -30,11 +30,11 @@ The type declaring these methods should also respect the following rules: - 반환 형식은 'void', 'Task' 또는 'ValueTask'여야 합니다. 이러한 메서드를 선언하는 형식은 다음 규칙도 준수해야 합니다. -- 형식은 형식여야 합니다. -- 형식는 'public' 또는 'internal'이어야 합니다(테스트 프로젝트에서 '[DiscoverInternals]' 특성을 사용하는 경우). -- 형식는 'static'이 되어서는 안 됩니다. -- 형식는 '[TestClass]'(또는 파생 특성)로 표시되어야 합니다. -- 형식는 제네릭이 아니어야 합니다. +- 형식은 클래스여야 합니다. +- 클래스는 'public' 또는 'internal'이어야 합니다(테스트 프로젝트에서 '[DiscoverInternals]' 특성을 사용하는 경우). +- 클래스는 'static'이 되어서는 안 됩니다. +- 클래스는 '[TestClass]'(또는 파생 특성)로 표시되어야 합니다. +- 클래스는 제네릭이 아니어야 합니다. @@ -65,7 +65,7 @@ The type declaring these methods should also respect the following rules: -The class should be marked with '[TestClass]' (or a derived attribute) -the class should not be generic. '[AssemblyInitialize]'로 표시된 메서드가 유효하려면 다음 레이아웃을 따라야 합니다. --제네릭 형식에서 선언할 수 없습니다. +-제네릭 클래스에서 선언할 수 없습니다. - 'public'이어야 합니다. - 'static'이어야 합니다. - 'async void'가 아니어야 합니다. @@ -75,11 +75,11 @@ The type declaring these methods should also respect the following rules: - 반환 형식은 'void', 'Task' 또는 'ValueTask'여야 합니다. 이러한 메서드를 선언하는 형식은 다음 규칙도 준수해야 합니다. --형식은 형식여야 합니다. --형식는 'public' 또는 'internal'이어야 합니다(테스트 프로젝트에서 '[DiscoverInternals]' 특성을 사용하는 경우). --형식는 'static'이 되어서는 안 됩니다. --형식는 '[TestClass]'(또는 파생 특성)로 표시되어야 합니다. --형식는 제네릭이 아니어야 합니다. +-형식은 클래스여야 합니다. +-클래스는 'public' 또는 'internal'이어야 합니다(테스트 프로젝트에서 '[DiscoverInternals]' 특성을 사용하는 경우). +-클래스는 'static'이 되어서는 안 됩니다. +-클래스는 '[TestClass]'(또는 파생 특성)로 표시되어야 합니다. +-클래스는 제네릭이 아니어야 합니다. @@ -182,7 +182,7 @@ The type declaring these methods should also respect the following rules: -If the class is 'sealed', it should be marked with '[TestClass]' (or a derived attribute) -the class should not be generic. '[ClassCleanup]'으로 표시된 메서드가 유효하려면 다음 레이아웃을 따라야 합니다. -- 'InheritanceBehavior' 모드가 설정되지 않은 제네릭 형식에서 선언할 수 없습니다. +- 'InheritanceBehavior' 모드가 설정되지 않은 제네릭 클래스에서 선언할 수 없습니다. - 'public'이어야 합니다. - 'static'이어야 합니다. - 'async void'가 아니어야 합니다. @@ -190,15 +190,15 @@ The type declaring these methods should also respect the following rules: - 제네릭이 아니어야 합니다. - 매개 변수를 사용하거나 'TestContext' 형식의 단일 매개 변수를 사용해서는 안 됩니다. - 반환 형식은 'void', 'Task' 또는 'ValueTask'여야 합니다. -- 형식가 'abstract'인 경우 'InheritanceBehavior.BeforeEachDerivedClass' 특성 매개 변수를 지정해야 합니다. -- 형식가 'sealed'인 경우 'InheritanceBehavior.BeforeEachDerivedClass' 특성 매개 변수를 지정하면 안 됩니다. +- 클래스가 'abstract'인 경우 'InheritanceBehavior.BeforeEachDerivedClass' 특성 매개 변수를 지정해야 합니다. +- 클래스가 'sealed'인 경우 'InheritanceBehavior.BeforeEachDerivedClass' 특성 매개 변수를 지정하면 안 됩니다. 이러한 메서드를 선언하는 형식은 다음 규칙도 준수해야 합니다. -- 형식은 형식여야 합니다. -- 형식는 'public' 또는 'internal'이어야 합니다(테스트 프로젝트에서 '[DiscoverInternals]' 특성을 사용하는 경우). -- 형식는 'static'이 되어서는 안 됩니다. -- 형식가 'sealed'인 경우 '[TestClass]'(또는 파생 특성)로 표시되어야 합니다. -- 형식는 제네릭이 아니어야 합니다. +- 형식은 클래스여야 합니다. +- 클래스는 'public' 또는 'internal'이어야 합니다(테스트 프로젝트에서 '[DiscoverInternals]' 특성을 사용하는 경우). +- 클래스는 'static'이 되어서는 안 됩니다. +- 클래스가 'sealed'인 경우 '[TestClass]'(또는 파생 특성)로 표시되어야 합니다. +- 클래스는 제네릭이 아니어야 합니다. @@ -231,7 +231,7 @@ The type declaring these methods should also respect the following rules: -If the class is 'sealed', it should be marked with '[TestClass]' (or a derived attribute) -the class should not be generic. '[ClassInitialize]'로 표시된 메서드가 유효하려면 다음 레이아웃을 따라야 합니다. --'InheritanceBehavior' 모드가 설정되지 않은 제네릭 형식에서 선언할 수 없습니다. +-'InheritanceBehavior' 모드가 설정되지 않은 제네릭 클래스에서 선언할 수 없습니다. - 'public'이어야 합니다. - 'static'이어야 합니다. - 'async void'가 아니어야 합니다. @@ -239,15 +239,15 @@ The type declaring these methods should also respect the following rules: - 제네릭이 아니어야 합니다. - 'TestContext' 형식의 매개 변수를 하나 사용해야 합니다. - 반환 형식은 'void', 'Task' 또는 'ValueTask'여야 합니다. -- 형식가 'abstract'인 경우 'InheritanceBehavior.BeforeEachDerivedClass' 특성 매개 변수를 지정해야 합니다. -- 형식가 'sealed'인 경우 'InheritanceBehavior.BeforeEachDerivedClass' 특성 매개 변수를 지정하면 안 됩니다. +- 클래스가 'abstract'인 경우 'InheritanceBehavior.BeforeEachDerivedClass' 특성 매개 변수를 지정해야 합니다. +- 클래스가 'sealed'인 경우 'InheritanceBehavior.BeforeEachDerivedClass' 특성 매개 변수를 지정하면 안 됩니다. 이러한 메서드를 선언하는 형식은 다음 규칙도 준수해야 합니다. --형식은 형식여야 합니다. --형식는 'public' 또는 'internal'이어야 합니다(테스트 프로젝트에서 '[DiscoverInternals]' 특성을 사용하는 경우). --형식는 'static'이 되어서는 안 됩니다. --형식가 'sealed'인 경우 '[TestClass]'(또는 파생 특성)로 표시되어야 합니다. --형식는 제네릭이 아니어야 합니다. +-형식은 클래스여야 합니다. +-클래스는 'public' 또는 'internal'이어야 합니다(테스트 프로젝트에서 '[DiscoverInternals]' 특성을 사용하는 경우). +-클래스는 'static'이 되어서는 안 됩니다. +-클래스가 'sealed'인 경우 '[TestClass]'(또는 파생 특성)로 표시되어야 합니다. +-클래스는 제네릭이 아니어야 합니다. @@ -333,7 +333,7 @@ The type declaring these methods should also respect the following rules: Member '{0}' already exists in the base class - 멤버 '{0}'이(가) 기본 형식에 이미 있습니다. + 멤버 '{0}'이(가) 기본 클래스에 이미 있습니다. @@ -524,7 +524,7 @@ The type declaring these methods should also respect the following rules: It's considered a good practice to have only test classes marked public in a test project. - 테스트 프로젝트에서 공용으로 표시된 테스트 형식만 사용하는 것이 좋습니다. + 테스트 프로젝트에서 공용으로 표시된 테스트 클래스만 사용하는 것이 좋습니다. @@ -534,7 +534,7 @@ The type declaring these methods should also respect the following rules: Public types should be test classes - 공용 형식은 테스트 형식여야 합니다. + 공용 형식은 테스트 클래스여야 합니다. @@ -549,7 +549,7 @@ The type declaring these methods should also respect the following rules: Test class '{0}' should be valid - 테스트 형식 '{0}'은(는) 유효해야 합니다. + 테스트 클래스 '{0}'은(는) 유효해야 합니다. @@ -564,7 +564,7 @@ The type declaring these methods should also respect the following rules: Without using 'ClassCleanupBehavior.EndOfClass', the '[ClassCleanup]' will by default be run at the end of the assembly and not at the end of the class. - 'ClassCleanupBehavior.EndOfClass'를 사용하지 않으면 '[ClassCleanup]'은 기본적으로 형식의 끝이 아니라 어셈블리의 끝에서 실행됩니다. + 'ClassCleanupBehavior.EndOfClass'를 사용하지 않으면 '[ClassCleanup]'은 기본적으로 클래스의 끝이 아니라 어셈블리의 끝에서 실행됩니다. @@ -582,7 +582,7 @@ The type declaring these methods should also respect the following rules: - it should be 'public' (or 'internal' if '[assembly: DiscoverInternals]' attribute is set) - it should not be 'static' (except if it contains only 'AssemblyInitialize' and/or 'AssemblyCleanup' methods) - it should not be generic. - '[TestClass]' 특성으로 표시된 형식인 테스트 형식는 MSTest에서 유효하다고 간주하려면 다음 레이아웃을 준수해야 합니다. + '[TestClass]' 특성으로 표시된 클래스인 테스트 클래스는 MSTest에서 유효하다고 간주하려면 다음 레이아웃을 준수해야 합니다. - 'public'(또는 '[assembly: DiscoverInternals]' 특성이 설정된 경우 'internal')이어야 합니다. - 'static'이 아니어야 합니다('AssemblyInitialize' 및/또는 'AssemblyCleanup' 메서드만 포함된 경우 제외). - 제네릭이 아니어야 합니다. @@ -590,22 +590,22 @@ The type declaring these methods should also respect the following rules: Test classes should have valid layout - 테스트 형식에는 유효한 레이아웃이 있어야 합니다. + 테스트 클래스에는 유효한 레이아웃이 있어야 합니다. Test class should have at least one test method or be 'static' with method(s) marked by '[AssemblyInitialize]' and/or '[AssemblyCleanup]'. - 테스트 형식에는 하나 이상의 테스트 메서드가 있거나 '[AssemblyInitialize]' 및/또는 '[AssemblyCleanup]'으로 표시된 메서드가 있는 'static'이어야 합니다. + 테스트 클래스에는 하나 이상의 테스트 메서드가 있거나 '[AssemblyInitialize]' 및/또는 '[AssemblyCleanup]'으로 표시된 메서드가 있는 'static'이어야 합니다. Test class '{0}' should have at least one test method or be 'static' with method(s) marked by '[AssemblyInitialize]' and/or '[AssemblyCleanup]' - 테스트 형식 '{0}'에는 하나 이상의 테스트 메서드가 있거나 '[AssemblyInitialize]' 및/또는 '[AssemblyCleanup]'으로 표시된 메서드가 있는 'static'이어야 합니다. + 테스트 클래스 '{0}'에는 하나 이상의 테스트 메서드가 있거나 '[AssemblyInitialize]' 및/또는 '[AssemblyCleanup]'으로 표시된 메서드가 있는 'static'이어야 합니다. Test class should have test method - 테스트 형식에는 테스트 메서드가 있어야 합니다. + 테스트 클래스에는 테스트 메서드가 있어야 합니다. @@ -635,10 +635,10 @@ The type declaring these methods should also respect the following rules: - 반환 형식은 'void', 'Task' 또는 'ValueTask'여야 합니다. 이러한 메서드를 선언하는 형식은 다음 규칙도 준수해야 합니다. --형식은 형식여야 합니다. --형식는 'public' 또는 'internal'이어야 합니다(테스트 프로젝트에서 '[DiscoverInternals]' 특성을 사용하는 경우). --형식는 'static'이 되어서는 안 됩니다. --형식가 'sealed'인 경우 '[TestClass]'(또는 파생 특성)로 표시되어야 합니다. +-형식은 클래스여야 합니다. +-클래스는 'public' 또는 'internal'이어야 합니다(테스트 프로젝트에서 '[DiscoverInternals]' 특성을 사용하는 경우). +-클래스는 'static'이 되어서는 안 됩니다. +-클래스가 'sealed'인 경우 '[TestClass]'(또는 파생 특성)로 표시되어야 합니다. @@ -694,10 +694,10 @@ The type declaring these methods should also respect the following rules: - 반환 형식은 'void', 'Task' 또는 'ValueTask'여야 합니다. 이러한 메서드를 선언하는 형식은 다음 규칙도 준수해야 합니다. --형식은 형식여야 합니다. --형식는 'public' 또는 'internal'이어야 합니다(테스트 프로젝트에서 '[DiscoverInternals]' 특성을 사용하는 경우). --형식는 'static'이 되어서는 안 됩니다. --형식가 'sealed'인 경우 '[TestClass]'(또는 파생 특성)로 표시되어야 합니다. +-형식은 클래스여야 합니다. +-클래스는 'public' 또는 'internal'이어야 합니다(테스트 프로젝트에서 '[DiscoverInternals]' 특성을 사용하는 경우). +-클래스는 'static'이 되어서는 안 됩니다. +-클래스가 'sealed'인 경우 '[TestClass]'(또는 파생 특성)로 표시되어야 합니다. @@ -751,12 +751,12 @@ The type declaring these methods should also respect the following rules: Type containing '[TestMethod]' should be marked with '[TestClass]', otherwise the test method will be silently ignored. - '[TestMethod]'를 포함하는 유형은 '[TestClass]'로 표시되어야 합니다. 그렇지 않으면 테스트 메서드가 자동으로 무시됩니다. + Type containing '[TestMethod]' should be marked with '[TestClass]', otherwise the test method will be silently ignored. Type '{0}' contains test methods and should be marked with '[TestClass]' - '{0}' 형식에는 테스트 메서드가 포함되어 있으며 '[TestClass]'로 표시되어야 합니다. + Type '{0}' contains test methods and should be marked with '[TestClass]' @@ -786,12 +786,12 @@ The type declaring these methods should also respect the following rules: The attribute '{0}' which derives from 'ConditionBaseAttribute' should be used only on classes marked with `TestClassAttribute` - 'ConditionBaseAttribute'에서 파생되는 '{0}' 특성은 'TestClassAttribute'로 표시된 형식에서만 사용해야 합니다. + 'ConditionBaseAttribute'에서 파생되는 '{0}' 특성은 'TestClassAttribute'로 표시된 클래스에서만 사용해야 합니다. Use 'ConditionBaseAttribute' on test classes - 테스트 형식에 'ConditionBaseAttribute' 사용 + 테스트 클래스에 'ConditionBaseAttribute' 사용 @@ -811,12 +811,12 @@ The type declaring these methods should also respect the following rules: '[DeploymentItem]' can be specified only on test class or test method - '[DeploymentItem]'은(는) 테스트 형식 또는 테스트 메서드에만 지정할 수 있습니다. + '[DeploymentItem]'은(는) 테스트 클래스 또는 테스트 메서드에만 지정할 수 있습니다. '[DeploymentItem]' can be specified only on test class or test method - '[DeploymentItem]'은(는) 테스트 형식 또는 테스트 메서드에만 지정할 수 있습니다. + '[DeploymentItem]'은(는) 테스트 클래스 또는 테스트 메서드에만 지정할 수 있습니다. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf index 3e34f669a6..bfc0402cf5 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf @@ -76,10 +76,10 @@ The type declaring these methods should also respect the following rules: Typ deklarujący te metody powinien również przestrzegać następujących reguł: — Typ powinien być klasą -— Typ powinna mieć wartość „public” lub „internal” (jeśli projekt testowy używa atrybutu „[DiscoverInternals]”) -— Typ nie powinna mieć wartości „static” -— Typ powinna być oznaczona znakiem „[TestClass]” (lub atrybutem pochodnym) -— Typ nie powinna być ogólna. +— Klasa powinna mieć wartość „public” lub „internal” (jeśli projekt testowy używa atrybutu „[DiscoverInternals]”) +— Klasa nie powinna mieć wartości „static” +— Klasa powinna być oznaczona znakiem „[TestClass]” (lub atrybutem pochodnym) +— Klasa nie powinna być ogólna. @@ -244,10 +244,10 @@ The type declaring these methods should also respect the following rules: Typ deklarujący te metody powinien również przestrzegać następujących reguł: — Typ powinien być klasą -— Typ powinna mieć wartość „public” lub „internal” (jeśli projekt testowy używa atrybutu „[DiscoverInternals]”) -— Typ nie powinna mieć wartości „static” +— Klasa powinna mieć wartość „public” lub „internal” (jeśli projekt testowy używa atrybutu „[DiscoverInternals]”) +— Klasa nie powinna mieć wartości „static” — Jeśli klasa ma wartość „sealed”, powinna być oznaczona znakiem „[TestClass]” (lub atrybutem pochodnym) -— Typ nie powinna być ogólna. +— Klasa nie powinna być ogólna. @@ -549,7 +549,7 @@ Typ deklarujący te metody powinien również przestrzegać następujących regu Test class '{0}' should be valid - Typ testowa „{0}” powinna być prawidłowa + Klasa testowa „{0}” powinna być prawidłowa @@ -595,17 +595,17 @@ Typ deklarujący te metody powinien również przestrzegać następujących regu Test class should have at least one test method or be 'static' with method(s) marked by '[AssemblyInitialize]' and/or '[AssemblyCleanup]'. - Typ testowa powinna mieć co najmniej jedną metodę testową lub być „statyczna” z metodami oznaczonymi jako „[AssemblyInitialize]” i/lub „[AssemblyCleanup]”. + Klasa testowa powinna mieć co najmniej jedną metodę testową lub być „statyczna” z metodami oznaczonymi jako „[AssemblyInitialize]” i/lub „[AssemblyCleanup]”. Test class '{0}' should have at least one test method or be 'static' with method(s) marked by '[AssemblyInitialize]' and/or '[AssemblyCleanup]' - Typ „{0}” testowa powinna mieć co najmniej jedną metodę testową lub być „statyczna” z metodami oznaczonymi jako „[AssemblyInitialize]” i/lub „[AssemblyCleanup]”. + Klasa „{0}” testowa powinna mieć co najmniej jedną metodę testową lub być „statyczna” z metodami oznaczonymi jako „[AssemblyInitialize]” i/lub „[AssemblyCleanup]”. Test class should have test method - Typ testowa powinna mieć metodę testową + Klasa testowa powinna mieć metodę testową @@ -636,8 +636,8 @@ The type declaring these methods should also respect the following rules: Typ deklarujący te metody powinien również przestrzegać następujących reguł: — Typ powinien być klasą -— Typ powinna mieć wartość „public” lub „internal” (jeśli projekt testowy używa atrybutu „[DiscoverInternals]”) -— Typ nie powinna mieć wartości „static” +— Klasa powinna mieć wartość „public” lub „internal” (jeśli projekt testowy używa atrybutu „[DiscoverInternals]”) +— Klasa nie powinna mieć wartości „static” — Jeśli klasa jest zapieczętowana, powinna być oznaczona znakiem „[TestClass]” (lub atrybutem pochodnym). @@ -695,8 +695,8 @@ The type declaring these methods should also respect the following rules: Typ deklarujący te metody powinien również przestrzegać następujących reguł: — Typ powinien być klasą -— Typ powinna mieć wartość „public” lub „internal” (jeśli projekt testowy używa atrybutu „[DiscoverInternals]”) -— Typ nie powinna mieć wartości „static” +— Klasa powinna mieć wartość „public” lub „internal” (jeśli projekt testowy używa atrybutu „[DiscoverInternals]”) +— Klasa nie powinna mieć wartości „static” — Jeśli klasa jest zapieczętowana, powinna być oznaczona znakiem „[TestClass]” (lub atrybutem pochodnym). @@ -751,12 +751,12 @@ Typ deklarujący te metody powinien również przestrzegać następujących regu Type containing '[TestMethod]' should be marked with '[TestClass]', otherwise the test method will be silently ignored. - Typ zwierający metodę „[TestMethod]” powinien być oznaczony klasa „[TestClass]”. W przeciwnym razie metoda testowa zostanie zignorowana w trybie dyskretnym. + Type containing '[TestMethod]' should be marked with '[TestClass]', otherwise the test method will be silently ignored. Type '{0}' contains test methods and should be marked with '[TestClass]' - Typ „{0}” zawiera metody testowe i powinna być oznaczona klasą „[TestClass]” + Type '{0}' contains test methods and should be marked with '[TestClass]' diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf index 252619d932..af02422de8 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf @@ -31,9 +31,9 @@ The type declaring these methods should also respect the following rules: O tipo declarando esses métodos também deve respeitar as seguintes regras: -O tipo deve ser uma classe --O tipo deve ser 'public' ou 'internal' (se o projeto de teste estiver usando o '[DiscoverInternals]' atributo) --O tipo não deve ser 'static' --O tipo deve ser marcada com '[TestClass]' (ou um atributo derivado) +-A classe deve ser 'public' ou 'internal' (se o projeto de teste estiver usando o '[DiscoverInternals]' atributo) +-A classe não deve ser 'static' +-A classe deve ser marcada com '[TestClass]' (ou um atributo derivado) -a classe não deve ser genérica. @@ -76,9 +76,9 @@ The type declaring these methods should also respect the following rules: O tipo que declara esses métodos também deve respeitar as seguintes regras: -O tipo deve ser uma classe --O tipo deve ser “público” ou '”interno” (se o projeto de teste estiver usando o atributo “[DiscoverInternals]”) --O tipo não deve ser “estático” --O tipo deve ser marcada com “[TestClass]” (ou um atributo derivado) +-A classe deve ser “público” ou '”interno” (se o projeto de teste estiver usando o atributo “[DiscoverInternals]”) +-A classe não deve ser “estático” +-A classe deve ser marcada com “[TestClass]” (ou um atributo derivado) -a classe não deve ser genérica. @@ -195,8 +195,8 @@ O parâmetro de atributo -'InheritanceBehavior.BeforeEachDerivedClass' não deve O tipo declarando esses métodos também deve respeitar as seguintes regras: -O tipo deve ser uma classe --O tipo deve ser 'public' ou 'internal' (se o projeto de teste estiver usando o '[DiscoverInternals]' atributo) --O tipo não deve ser 'static' +-A classe deve ser 'public' ou 'internal' (se o projeto de teste estiver usando o '[DiscoverInternals]' atributo) +-A classe não deve ser 'static' -Se a classe for 'sealed', ela deverá ser marcada com '[TestClass]' (ou um atributo derivado) -a classe não deve ser genérica. @@ -244,8 +244,8 @@ The type declaring these methods should also respect the following rules: O tipo que declara esses métodos também deve respeitar as seguintes regras: -O tipo deve ser uma classe --O tipo deve ser “público” ou '”interno” (se o projeto de teste estiver usando o atributo “[DiscoverInternals]”) --O tipo não deve ser “estático” +-A classe deve ser “público” ou '”interno” (se o projeto de teste estiver usando o atributo “[DiscoverInternals]”) +-A classe não deve ser “estático” -Se a classe for “selado”, ela deverá ser marcada com “[TestClass]” (ou um atributo derivado) -a classe não deve ser genérica. @@ -549,7 +549,7 @@ O tipo que declara esses métodos também deve respeitar as seguintes regras: Test class '{0}' should be valid - O tipo de teste ''{0}'' deve ser válida + A classe de teste ''{0}'' deve ser válida @@ -595,17 +595,17 @@ O tipo que declara esses métodos também deve respeitar as seguintes regras: Test class should have at least one test method or be 'static' with method(s) marked by '[AssemblyInitialize]' and/or '[AssemblyCleanup]'. - O tipo de teste deve ter pelo menos um método de teste ou ser 'estática' com métodos marcados por '[AssemblyInitialize]' e/ou '[AssemblyCleanup]'. + A classe de teste deve ter pelo menos um método de teste ou ser 'estática' com métodos marcados por '[AssemblyInitialize]' e/ou '[AssemblyCleanup]'. Test class '{0}' should have at least one test method or be 'static' with method(s) marked by '[AssemblyInitialize]' and/or '[AssemblyCleanup]' - O tipo de teste '{0}' deve ter pelo menos um método de teste ou ser 'estática' com métodos marcados por '[AssemblyInitialize]' e/ou '[AssemblyCleanup]'. + A classe de teste '{0}' deve ter pelo menos um método de teste ou ser 'estática' com métodos marcados por '[AssemblyInitialize]' e/ou '[AssemblyCleanup]'. Test class should have test method - O tipo de teste deve ter um método de teste + A classe de teste deve ter um método de teste @@ -636,8 +636,8 @@ The type declaring these methods should also respect the following rules: O tipo que declara esses métodos também deve respeitar as seguintes regras: -O tipo deve ser uma classe --O tipo deve ser “público” ou '”interno” (se o projeto de teste estiver usando o atributo “[DiscoverInternals]”) --O tipo não deve ser “estático” +-A classe deve ser “público” ou '”interno” (se o projeto de teste estiver usando o atributo “[DiscoverInternals]”) +-A classe não deve ser “estático” -Se a classe for “selado”, ela deverá ser marcada com “[TestClass]” (ou um atributo derivado). @@ -695,8 +695,8 @@ The type declaring these methods should also respect the following rules: O tipo que declara esses métodos também deve respeitar as seguintes regras: -O tipo deve ser uma classe --O tipo deve ser “público” ou '”interno” (se o projeto de teste estiver usando o atributo “[DiscoverInternals]”) --O tipo não deve ser “estático” +-A classe deve ser “público” ou '”interno” (se o projeto de teste estiver usando o atributo “[DiscoverInternals]”) +-A classe não deve ser “estático” -Se a classe for “selado”, ela deverá ser marcada com “[TestClass]” (ou um atributo derivado). @@ -751,12 +751,12 @@ O tipo que declara esses métodos também deve respeitar as seguintes regras: Type containing '[TestMethod]' should be marked with '[TestClass]', otherwise the test method will be silently ignored. - O tipo contendo '[TestMethod]' deve ser marcado com '[TestClass]', caso contrário, o método de teste será ignorado silenciosamente. + Type containing '[TestMethod]' should be marked with '[TestClass]', otherwise the test method will be silently ignored. Type '{0}' contains test methods and should be marked with '[TestClass]' - O tipo '{0}' contém métodos de teste e deve ser marcada com '[TestClass]' + Type '{0}' contains test methods and should be marked with '[TestClass]' diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf index 6f2af8fac8..fb9e235060 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf @@ -763,12 +763,12 @@ The type declaring these methods should also respect the following rules: Type containing '[TestMethod]' should be marked with '[TestClass]', otherwise the test method will be silently ignored. - У типа, содержащего "[TestMethod]", должна быть пометка "[TestClass]", иначе метод тестирования будет проигнорирован без уведомления пользователя. + Type containing '[TestMethod]' should be marked with '[TestClass]', otherwise the test method will be silently ignored. Type '{0}' contains test methods and should be marked with '[TestClass]' - Тип "{0}" тестовые методы. У этого класса должна быть пометка "[TestClass]". + Type '{0}' contains test methods and should be marked with '[TestClass]' diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf index bfbfd657bb..2810454bfe 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf @@ -549,7 +549,7 @@ Bu yöntemleri bildiren tipin ayrıca aşağıdaki kurallara uyması gerekir: Test class '{0}' should be valid - '{0}' test türü geçerli olmalıdır + '{0}' test sınıfı geçerli olmalıdır @@ -564,7 +564,7 @@ Bu yöntemleri bildiren tipin ayrıca aşağıdaki kurallara uyması gerekir: Without using 'ClassCleanupBehavior.EndOfClass', the '[ClassCleanup]' will by default be run at the end of the assembly and not at the end of the class. - 'ClassCleanupBehavior.EndOfClass' kullanılmadığında, '[ClassCleanup]' varsayılan olarak türün sonunda değil derlemenin sonunda çalıştırılır. + 'ClassCleanupBehavior.EndOfClass' kullanılmadığında, '[ClassCleanup]' varsayılan olarak sınıfın sonunda değil derlemenin sonunda çalıştırılır. @@ -596,17 +596,17 @@ Bu yöntemleri bildiren tipin ayrıca aşağıdaki kurallara uyması gerekir: Test class should have at least one test method or be 'static' with method(s) marked by '[AssemblyInitialize]' and/or '[AssemblyCleanup]'. - Test türü en az bir test yöntemine sahip olmalıdır veya '[AssemblyInitialize]' ve/veya '[AssemblyCleanup]' ile işaretlenen yöntemlere sahip 'static' olmalıdır. + Test sınıfı en az bir test yöntemine sahip olmalıdır veya '[AssemblyInitialize]' ve/veya '[AssemblyCleanup]' ile işaretlenen yöntemlere sahip 'static' olmalıdır. Test class '{0}' should have at least one test method or be 'static' with method(s) marked by '[AssemblyInitialize]' and/or '[AssemblyCleanup]' - '{0}' test türü en az bir test yöntemine sahip olmalıdır veya '[AssemblyInitialize]' ve/veya '[AssemblyCleanup]' ile işaretlenen yöntemlere sahip 'static' olmalıdır + '{0}' test sınıfı en az bir test yöntemine sahip olmalıdır veya '[AssemblyInitialize]' ve/veya '[AssemblyCleanup]' ile işaretlenen yöntemlere sahip 'static' olmalıdır Test class should have test method - Test türü test yöntemine sahip olmalıdır + Test sınıfı test yöntemine sahip olmalıdır @@ -753,12 +753,12 @@ Bu yöntemleri bildiren tipin ayrıca aşağıdaki kurallara uyması gerekir: Type containing '[TestMethod]' should be marked with '[TestClass]', otherwise the test method will be silently ignored. - '[TestMethod]' içeren tür '[TestClass]' ile işaretlenmeli, aksi takdirde test yöntemi sessizce yoksayılır. + Type containing '[TestMethod]' should be marked with '[TestClass]', otherwise the test method will be silently ignored. Type '{0}' contains test methods and should be marked with '[TestClass]' - '{0}' türü test yöntemleri içeriyor ve '[TestClass]' ile işaretlenmeli + Type '{0}' contains test methods and should be marked with '[TestClass]' @@ -813,12 +813,12 @@ Bu yöntemleri bildiren tipin ayrıca aşağıdaki kurallara uyması gerekir: '[DeploymentItem]' can be specified only on test class or test method - '[DeploymentItem]' yalnızca test türünda veya test yönteminde belirtilebilir + '[DeploymentItem]' yalnızca test sınıfında veya test yönteminde belirtilebilir '[DeploymentItem]' can be specified only on test class or test method - '[DeploymentItem]' yalnızca test türünda veya test yönteminde belirtilebilir + '[DeploymentItem]' yalnızca test sınıfında veya test yönteminde belirtilebilir diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf index 9b594f3f4e..547953c4db 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf @@ -20,21 +20,21 @@ The type declaring these methods should also respect the following rules: -The class should be marked with '[TestClass]' (or a derived attribute) -the class should not be generic. 标记有“[AssemblyCleanup]”的方法应遵循以下布局才会有效: --不能在泛型类型上声明它 +-不能在泛型类上声明它 - 它应为“public” - 它应为“static” - 它不应为“async void” - 它不应是特殊方法(终结器、运算符...)。 - 它不应是泛型的 --它不应采用任何参数,或采用类型型为“TestContext”的单个参数 -- 返回类型型应为“void”、“Task”或“ValueTask” +-它不应采用任何参数,或采用类型为“TestContext”的单个参数 +- 返回类型应为“void”、“Task”或“ValueTask” -声明这些方法的类型型还应遵循以下规则: --类型型应为类型 --类型应为“public”或“internal”(如果测试项目正在使用“[DiscoverInternals]”属性) --类型不应为“static” --应使用“[TestClass]”(或派生属性)标记类型 --类型不应是泛型的。 +声明这些方法的类型还应遵循以下规则: +-类型应为类 +-类应为“public”或“internal”(如果测试项目正在使用“[DiscoverInternals]”属性) +-类不应为“static” +-应使用“[TestClass]”(或派生属性)标记类 +-类不应是泛型的。 @@ -65,21 +65,21 @@ The type declaring these methods should also respect the following rules: -The class should be marked with '[TestClass]' (or a derived attribute) -the class should not be generic. 标记有“[AssemblyInitialize]”的方法应遵循以下布局才会有效: --不能在泛型类型上声明它 +-不能在泛型类上声明它 - 它应为“public” - 它应为“static” - 它不应为“async void” - 它不应是特殊方法(终结器、运算符...)。 - 它不应是泛型的 -- 它应采用“TestContext”类型型的一个参数 -- 返回类型型应为“void”、“Task”或“ValueTask” +- 它应采用“TestContext”类型的一个参数 +- 返回类型应为“void”、“Task”或“ValueTask” -声明这些方法的类型型还应遵循以下规则: --类型型应为类型 --类型应为“public”或“internal”(如果测试项目正在使用“[DiscoverInternals]”属性) --类型不应为“static” --应使用“[TestClass]”(或派生属性)标记类型 --类型不应是泛型的。 +声明这些方法的类型还应遵循以下规则: +-类型应为类 +-类应为“public”或“internal”(如果测试项目正在使用“[DiscoverInternals]”属性) +-类不应为“static” +-应使用“[TestClass]”(或派生属性)标记类 +-类不应是泛型的。 @@ -119,17 +119,17 @@ The type declaring these methods should also respect the following rules: Use 'Assert.AreEqual'/'Assert.AreNotEqual' instead of 'Assert.AreSame'/'Assert.AreNotSame' when comparing value types. Passing a value type to 'Assert.AreSame'/'Assert.AreNotSame' will be boxed (creating a new object). Because 'Assert.AreSame'/'Assert.AreNotSame' does the comparison by reference, 'Assert.AreSame' will fail when boxing happens, and 'Assert.AreNotSame' will always pass. - 比较值类型型时,请使用 “Assert.AreEqual”/“Assert.AreNotEqual” 而不是 “Assert.AreSame”/“Assert.AreNotSame”。将值类型型传递给 “Assert.AreSame”/“Assert.AreNotSame”将装箱 (创建新的对象)。由于 'Assert.AreSame'/'Assert.AreNotSame' 按引用进行比较,所以当装箱发生时,“Assert.AreSame” 将失败,并且 “Assert.AreNotSame” 将始终通过。 + 比较值类型时,请使用 “Assert.AreEqual”/“Assert.AreNotEqual” 而不是 “Assert.AreSame”/“Assert.AreNotSame”。将值类型传递给 “Assert.AreSame”/“Assert.AreNotSame”将装箱 (创建新的对象)。由于 'Assert.AreSame'/'Assert.AreNotSame' 按引用进行比较,所以当装箱发生时,“Assert.AreSame” 将失败,并且 “Assert.AreNotSame” 将始终通过。 Use '{0}' instead of '{1}' when comparing value types - 比较值类型型时使用 '{0}' 而不是 '{1}' + 比较值类型时使用 '{0}' 而不是 '{1}' Don't use 'Assert.AreSame' or 'Assert.AreNotSame' with value types - 不要将 “Assert.AreSame” 或 “Assert.AreNotSame” 与值类型型一起使用 + 不要将 “Assert.AreSame” 或 “Assert.AreNotSame” 与值类型一起使用 @@ -182,23 +182,23 @@ The type declaring these methods should also respect the following rules: -If the class is 'sealed', it should be marked with '[TestClass]' (or a derived attribute) -the class should not be generic. 标记有“[ClassCleanup]”的方法应遵循以下布局才会有效: --如果未设置“InheritanceBehavior”模式,则不能在泛型类型上声明它 +-如果未设置“InheritanceBehavior”模式,则不能在泛型类上声明它 - 它应为“public” - 它应为“static” - 它不应为“async void” - 它不应是特殊方法(终结器、运算符...)。 - 它不应是泛型的 --它不应采用任何参数,或采用类型型为“TestContext”的单个参数 -- 返回类型型应为“void”、“Task”或“ValueTask” -- "InheritanceBehavior.BeforeEachDerivedClass" 属性参数应在类型为 "abstract" 时指定 -- "InheritanceBehavior.BeforeEachDerivedClass" 属性参数不应在类型为 "sealed" 时指定 +-它不应采用任何参数,或采用类型为“TestContext”的单个参数 +- 返回类型应为“void”、“Task”或“ValueTask” +- "InheritanceBehavior.BeforeEachDerivedClass" 属性参数应在类为 "abstract" 时指定 +- "InheritanceBehavior.BeforeEachDerivedClass" 属性参数不应在类为 "sealed" 时指定 -声明这些方法的类型型还应遵循以下规则: --类型型应为类型 --类型应为“public”或“internal”(如果测试项目正在使用“[DiscoverInternals]”属性) --类型不应为“static” --如果类型为“sealed”,应使用“[TestClass]”(或派生属性)标记该类型 --类型不应是泛型的。 +声明这些方法的类型还应遵循以下规则: +-类型应为类 +-类应为“public”或“internal”(如果测试项目正在使用“[DiscoverInternals]”属性) +-类不应为“static” +-如果类为“sealed”,应使用“[TestClass]”(或派生属性)标记该类 +-类不应是泛型的。 @@ -231,23 +231,23 @@ The type declaring these methods should also respect the following rules: -If the class is 'sealed', it should be marked with '[TestClass]' (or a derived attribute) -the class should not be generic. 标记有“[ClassInitialize]”的方法应遵循以下布局才会有效: --如果未设置“InheritanceBehavior”模式,则不能在泛型类型上声明它 +-如果未设置“InheritanceBehavior”模式,则不能在泛型类上声明它 - 它应为“public” - 它应为“static” - 它不应为“async void” - 它不应是特殊方法(终结器、运算符...)。 - 它不应是泛型的 -- 它应采用“TestContext”类型型的一个参数 -- 返回类型型应为“void”、“Task”或“ValueTask” -- "InheritanceBehavior.BeforeEachDerivedClass" 属性参数应在类型为 "abstract" 时指定 -- "InheritanceBehavior.BeforeEachDerivedClass" 属性参数不应在类型为 "sealed" 时指定 +- 它应采用“TestContext”类型的一个参数 +- 返回类型应为“void”、“Task”或“ValueTask” +- "InheritanceBehavior.BeforeEachDerivedClass" 属性参数应在类为 "abstract" 时指定 +- "InheritanceBehavior.BeforeEachDerivedClass" 属性参数不应在类为 "sealed" 时指定 -声明这些方法的类型型还应遵循以下规则: --类型型应为类型 --类型应为“public”或“internal”(如果测试项目正在使用“[DiscoverInternals]”属性) --类型不应为“static” --如果类型为“sealed”,则应使用“[TestClass]”(或派生属性)标记该类型 --类型不应是泛型的。 +声明这些方法的类型还应遵循以下规则: +-类型应为类 +-类应为“public”或“internal”(如果测试项目正在使用“[DiscoverInternals]”属性) +-类不应为“static” +-如果类为“sealed”,则应使用“[TestClass]”(或派生属性)标记该类 +-类不应是泛型的。 @@ -268,7 +268,7 @@ The type declaring these methods should also respect the following rules: DataRow 条目应具有以下布局才能有效: - 应仅在测试方法上进行设置; - 参数计数应与方法参数计数匹配; -- 参数类型型应与方法参数类型型匹配。 +- 参数类型应与方法参数类型匹配。 @@ -288,12 +288,12 @@ The type declaring these methods should also respect the following rules: Found two conflicting types for generic parameter '{0}'. The conflicting types are '{1}' and '{2}'. - 发现泛型参数 '{0}' 的两个冲突类型型。冲突类型型 '{1}' 和 '{2}'。 + 发现泛型参数 '{0}' 的两个冲突类型。冲突类型 '{1}' 和 '{2}'。 The type of the generic parameter '{0}' could not be inferred. - 无法推断 '{0}' 泛型参数的类型型。 + 无法推断 '{0}' 泛型参数的类型。 @@ -333,7 +333,7 @@ The type declaring these methods should also respect the following rules: Member '{0}' already exists in the base class - 基类型中已存在成员“{0}” + 基类中已存在成员“{0}” @@ -373,7 +373,7 @@ The type declaring these methods should also respect the following rules: - member should be a method if DynamicDataSourceType.Method is specified or a property otherwise. "DynamicData" 条目应具有以下布局才能有效: - 应仅对测试方法设置; -- 应对指定的类型型定义成员; +- 应对指定的类型定义成员; - 如果指定了 DynamicDataSourceType.Method,则成员应为方法,否则应为属性。 @@ -524,17 +524,17 @@ The type declaring these methods should also respect the following rules: It's considered a good practice to have only test classes marked public in a test project. - 在测试项目中仅将测试类型标记为“公开”是一种不错的做法。 + 在测试项目中仅将测试类标记为“公开”是一种不错的做法。 Public type '{0}' should be marked with '[TestClass]' or changed to 'internal' - 公共类型型“{0}”应标记为“[TestClass]”或更改为“internal” + 公共类型“{0}”应标记为“[TestClass]”或更改为“internal” Public types should be test classes - 公共类型型应为测试类型 + 公共类型应为测试类 @@ -549,7 +549,7 @@ The type declaring these methods should also respect the following rules: Test class '{0}' should be valid - 测试类型“{0}”应该有效 + 测试类“{0}”应该有效 @@ -564,7 +564,7 @@ The type declaring these methods should also respect the following rules: Without using 'ClassCleanupBehavior.EndOfClass', the '[ClassCleanup]' will by default be run at the end of the assembly and not at the end of the class. - 如果不使用 "ClassCleanupBehavior.EndOfClass","[ClassCleanup]" 将默认在程序集末尾运行,而不是在类型的末尾运行。 + 如果不使用 "ClassCleanupBehavior.EndOfClass","[ClassCleanup]" 将默认在程序集末尾运行,而不是在类的末尾运行。 @@ -582,7 +582,7 @@ The type declaring these methods should also respect the following rules: - it should be 'public' (or 'internal' if '[assembly: DiscoverInternals]' attribute is set) - it should not be 'static' (except if it contains only 'AssemblyInitialize' and/or 'AssemblyCleanup' methods) - it should not be generic. - 测试类型(标记有“[TestClass]”属性的类型)应遵循以下布局,才能被 MSTest 视为有效: + 测试类(标记有“[TestClass]”属性的类)应遵循以下布局,才能被 MSTest 视为有效: - 它应为 "public" (如果设置了“[assembly: DiscoverInternals]”属性,则应为 "internal") - 它不应为 "static" (除非它只包含 "AssemblyInitialize" 和/或 "AssemblyCleanup" 方法) - 它不应是泛型的。 @@ -590,22 +590,22 @@ The type declaring these methods should also respect the following rules: Test classes should have valid layout - 测试类型应具有有效的布局 + 测试类应具有有效的布局 Test class should have at least one test method or be 'static' with method(s) marked by '[AssemblyInitialize]' and/or '[AssemblyCleanup]'. - 测试类型应至少有一个测试方法,或者应为 "static" 且方法由 "[AssemblyInitialize]" 和/或 "[AssemblyCleanup]" 标记。 + 测试类应至少有一个测试方法,或者应为 "static" 且方法由 "[AssemblyInitialize]" 和/或 "[AssemblyCleanup]" 标记。 Test class '{0}' should have at least one test method or be 'static' with method(s) marked by '[AssemblyInitialize]' and/or '[AssemblyCleanup]' - 测试类型 "{0}" 应至少有一个测试方法,或者应为 "static" 且方法由 "[AssemblyInitialize]" 和/或 "[AssemblyCleanup]" 标记 + 测试类 "{0}" 应至少有一个测试方法,或者应为 "static" 且方法由 "[AssemblyInitialize]" 和/或 "[AssemblyCleanup]" 标记 Test class should have test method - 测试类型应具有测试方法 + 测试类应具有测试方法 @@ -632,13 +632,13 @@ The type declaring these methods should also respect the following rules: - 它不应是特殊方法(终结器、运算符...)。 - 它不应是泛型的 - 它不应采用任何参数 -- 返回类型型应为“void”、“Task”或“ValueTask” +- 返回类型应为“void”、“Task”或“ValueTask” -声明这些方法的类型型还应遵循以下规则: --类型型应为类型 --类型应为“public”或“internal”(如果测试项目正在使用“[DiscoverInternals]”属性) --类型不应为“static” --如果类型为“sealed”,则应使用“[TestClass]”(或派生属性)标记该类型。 +声明这些方法的类型还应遵循以下规则: +-类型应为类 +-类应为“public”或“internal”(如果测试项目正在使用“[DiscoverInternals]”属性) +-类不应为“static” +-如果类为“sealed”,则应使用“[TestClass]”(或派生属性)标记该类。 @@ -691,13 +691,13 @@ The type declaring these methods should also respect the following rules: - 它不应是特殊方法(终结器、运算符...)。 - 它不应是泛型的 - 它不应采用任何参数 -- 返回类型型应为“void”、“Task”或“ValueTask” +- 返回类型应为“void”、“Task”或“ValueTask” -声明这些方法的类型型还应遵循以下规则: --类型型应为类型 --类型应为“public”或“internal”(如果测试项目正在使用“[DiscoverInternals]”属性) --类型不应为“static” --如果类型为“sealed”,则应使用“[TestClass]”(或派生属性)标记该类型。 +声明这些方法的类型还应遵循以下规则: +-类型应为类 +-类应为“public”或“internal”(如果测试项目正在使用“[DiscoverInternals]”属性) +-类不应为“static” +-如果类为“sealed”,则应使用“[TestClass]”(或派生属性)标记该类。 @@ -722,9 +722,9 @@ The type declaring these methods should also respect the following rules: 测试方法(标记有 "[TestMethod]" 属性的方法)应遵循以下布局,以便 MSTest 将其视为有效: - 它应该是 "public" (如果设置了 "[assembly: DiscoverInternals]" 属性,则应该是 "internal") - 它不应为 "static" -- 只要可以推断类型型参数并且参数类型型兼容,它就应该是泛型 +- 只要可以推断类型参数并且参数类型兼容,它就应该是泛型 - 它不应为 "abstract" -- 返回类型型应为 "void”、"Task" 或 "ValueTask" +- 返回类型应为 "void”、"Task" 或 "ValueTask" - 它不应为 "async void" - 它不应是特殊方法(终结器、运算符...)。 @@ -751,17 +751,17 @@ The type declaring these methods should also respect the following rules: Type containing '[TestMethod]' should be marked with '[TestClass]', otherwise the test method will be silently ignored. - 应使用“[TestClass]”标记包含“[TestMethod]”的类型型,否则将以静默方式忽略该测试方法。 + Type containing '[TestMethod]' should be marked with '[TestClass]', otherwise the test method will be silently ignored. Type '{0}' contains test methods and should be marked with '[TestClass]' - 类型“{0}”包含测试方法,应使用“[TestClass]”进行标记 + Type '{0}' contains test methods and should be marked with '[TestClass]' Type containing '[TestMethod]' should be marked with '[TestClass]' - 应使用“[TestClass]”标记包含“[TestMethod]”的类型型 + 应使用“[TestClass]”标记包含“[TestMethod]”的类型 @@ -786,12 +786,12 @@ The type declaring these methods should also respect the following rules: The attribute '{0}' which derives from 'ConditionBaseAttribute' should be used only on classes marked with `TestClassAttribute` - 派生自 “ConditionBaseAttribute” 的属性 '{0}' 只能在标记为 “TestClassAttribute” 的类型上使用 + 派生自 “ConditionBaseAttribute” 的属性 '{0}' 只能在标记为 “TestClassAttribute” 的类上使用 Use 'ConditionBaseAttribute' on test classes - 对测试类型使用 “ConditionBaseAttribute” + 对测试类使用 “ConditionBaseAttribute” @@ -811,12 +811,12 @@ The type declaring these methods should also respect the following rules: '[DeploymentItem]' can be specified only on test class or test method - 只能对测试类型或测试方法指定 "[DeploymentItem]" + 只能对测试类或测试方法指定 "[DeploymentItem]" '[DeploymentItem]' can be specified only on test class or test method - 只能对测试类型或测试方法指定 "[DeploymentItem]" + 只能对测试类或测试方法指定 "[DeploymentItem]" diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf index 6919579be7..cf7ea015e7 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf @@ -20,7 +20,7 @@ The type declaring these methods should also respect the following rules: -The class should be marked with '[TestClass]' (or a derived attribute) -the class should not be generic. 標示為 '[AssemblyCleanup]' 的方法應該遵循下列配置才能有效: --其不能在泛型類型上宣告 +-其不能在泛型類別上宣告 -其應為 'public' -其應為 'static' -其不應為 'async void' @@ -30,11 +30,11 @@ The type declaring these methods should also respect the following rules: -傳回類型應為 'void'、'Task' 或 'ValueTask' 宣告這些方法的類型還應遵循以下規則: --類型應為類型 --類型應為 'public' 或 'internal' (如果測試專案使用 '[DiscoverInternals]' 屬性) --類型不應為 'static' --類型應標示為 '[TestClass]' (或衍生屬性) --類型不應為泛型。 +-類型應為類別 +-類別應為 'public' 或 'internal' (如果測試專案使用 '[DiscoverInternals]' 屬性) +-類別不應為 'static' +-類別應標示為 '[TestClass]' (或衍生屬性) +-類別不應為泛型。 @@ -65,7 +65,7 @@ The type declaring these methods should also respect the following rules: -The class should be marked with '[TestClass]' (or a derived attribute) -the class should not be generic. 標示為 '[AssemblyInitialize]' 的方法應該遵循下列配置才能有效: --其不能在泛型類型上宣告 +-其不能在泛型類別上宣告 - 其應為 'public' - 其應為 'static' - 其不應為 'async void' @@ -75,11 +75,11 @@ The type declaring these methods should also respect the following rules: - 傳回類型應為 'void'、'Task' 或 'ValueTask' 宣告這些方法的類型還應遵循以下規則: --類型應為類型 --類型應為 'public' 或 'internal' (如果測試專案使用 '[DiscoverInternals]' 屬性) --類型不應為 'static' --類型應標示為 '[TestClass]' (或衍生屬性)。 --類型不應為泛型。 +-類型應為類別 +-類別應為 'public' 或 'internal' (如果測試專案使用 '[DiscoverInternals]' 屬性) +-類別不應為 'static' +-類別應標示為 '[TestClass]' (或衍生屬性)。 +-類別不應為泛型。 @@ -182,7 +182,7 @@ The type declaring these methods should also respect the following rules: -If the class is 'sealed', it should be marked with '[TestClass]' (or a derived attribute) -the class should not be generic. 標示 '[ClassCleanup]' 的方法應該遵循下列配置,才會有效: --未設定 'InheritanceBehavior' 模式的情況下不能在泛型類型上宣告它 +-未設定 'InheritanceBehavior' 模式的情況下不能在泛型類別上宣告它 -其應為 'public' -其應為 'static' -其不應為 'async void' @@ -190,15 +190,15 @@ The type declaring these methods should also respect the following rules: -其不應為泛型 -其不應接受任何參數,或接受類型為 'TestContext' 的單一參數 -傳回類型應為 'void'、'Task' 或 'ValueTask' --如果類型為 'abstract',應指定 'InheritanceBehavior.BeforeEachDerivedClass' 屬性參數 --如果類型為 'sealed',則不應指定 'InheritanceBehavior.BeforeEachDerivedClass' 屬性參數 +-如果類別為 'abstract',應指定 'InheritanceBehavior.BeforeEachDerivedClass' 屬性參數 +-如果類別為 'sealed',則不應指定 'InheritanceBehavior.BeforeEachDerivedClass' 屬性參數 宣告這些方法的類型還應遵循以下規則: --類型應為類型 --類型應為 'public' 或 'internal' (如果測試專案使用 '[DiscoverInternals]' 屬性) --類型不應為 'static' --如果類型是 'sealed',則應標示為 '[TestClass]' (或衍生屬性) --類型不應為泛型。 +-類型應為類別 +-類別應為 'public' 或 'internal' (如果測試專案使用 '[DiscoverInternals]' 屬性) +-類別不應為 'static' +-如果類別是 'sealed',則應標示為 '[TestClass]' (或衍生屬性) +-類別不應為泛型。 @@ -231,7 +231,7 @@ The type declaring these methods should also respect the following rules: -If the class is 'sealed', it should be marked with '[TestClass]' (or a derived attribute) -the class should not be generic. 標示 '[ClassInitialize]' 的方法應該遵循下列配置,才會有效: --未設定 'InheritanceBehavior' 模式的情況下不能在泛型類型上宣告它 +-未設定 'InheritanceBehavior' 模式的情況下不能在泛型類別上宣告它 - 其應為 'public' - 其應為 'static' - 其不應為 'async void' @@ -239,15 +239,15 @@ The type declaring these methods should also respect the following rules: - 其不應為泛型 - 其應該接受類型為 'TestContext' 的一個參數 - 傳回類型應為 'void'、'Task' 或 'ValueTask' -- 如果類型為 'abstract',應指定 'InheritanceBehavior.BeforeEachDerivedClass' 屬性參數。 -- 如果類型為 'sealed',則不應指定 'InheritanceBehavior.BeforeEachDerivedClass' 屬性參數。 +- 如果類別為 'abstract',應指定 'InheritanceBehavior.BeforeEachDerivedClass' 屬性參數。 +- 如果類別為 'sealed',則不應指定 'InheritanceBehavior.BeforeEachDerivedClass' 屬性參數。 宣告這些方法的類型還應遵循以下規則: --類型應為類型 --類型應為 'public' 或 'internal' (如果測試專案使用 '[DiscoverInternals]' 屬性) --類型不應為 'static' --如果類型是 'sealed',則應標示為 '[TestClass]' (或衍生屬性)。 --類型不應為泛型。 +-類型應為類別 +-類別應為 'public' 或 'internal' (如果測試專案使用 '[DiscoverInternals]' 屬性) +-類別不應為 'static' +-如果類別是 'sealed',則應標示為 '[TestClass]' (或衍生屬性)。 +-類別不應為泛型。 @@ -333,7 +333,7 @@ The type declaring these methods should also respect the following rules: Member '{0}' already exists in the base class - 成員 '{0}' 已經存在於基底類型中 + 成員 '{0}' 已經存在於基底類別中 @@ -524,7 +524,7 @@ The type declaring these methods should also respect the following rules: It's considered a good practice to have only test classes marked public in a test project. - 在測試專案中僅將測試類型標記為公開被認為是一種很好的做法。 + 在測試專案中僅將測試類別標記為公開被認為是一種很好的做法。 @@ -534,7 +534,7 @@ The type declaring these methods should also respect the following rules: Public types should be test classes - 公用類型應為測試類型 + 公用類型應為測試類別 @@ -549,7 +549,7 @@ The type declaring these methods should also respect the following rules: Test class '{0}' should be valid - 測試類型 '{0}' 應為有效 + 測試類別 '{0}' 應為有效 @@ -564,7 +564,7 @@ The type declaring these methods should also respect the following rules: Without using 'ClassCleanupBehavior.EndOfClass', the '[ClassCleanup]' will by default be run at the end of the assembly and not at the end of the class. - 如不使用 'ClassCleanupBehavior.EndOfClass',則預設會在組件結尾執行 '[ClassCleanup]',而非在類型的結尾執行。 + 如不使用 'ClassCleanupBehavior.EndOfClass',則預設會在組件結尾執行 '[ClassCleanup]',而非在類別的結尾執行。 @@ -582,7 +582,7 @@ The type declaring these methods should also respect the following rules: - it should be 'public' (or 'internal' if '[assembly: DiscoverInternals]' attribute is set) - it should not be 'static' (except if it contains only 'AssemblyInitialize' and/or 'AssemblyCleanup' methods) - it should not be generic. - 測試類型 (標示為 '[TestClass]' 屬性的類型) 應該遵循下列配置,讓 MSTest 視為有效: + 測試類別 (標示為 '[TestClass]' 屬性的類別) 應該遵循下列配置,讓 MSTest 視為有效: - 它應該是 'public' (如果設定 '[assembly: DiscoverInternals]' 屬性,則為 'internal') - 它不應該是 'static' (除非其僅包含 'AssemblyInitialize' 和/或 'AssemblyCleanup' 方法) - 它不能是泛型。 @@ -590,22 +590,22 @@ The type declaring these methods should also respect the following rules: Test classes should have valid layout - 測試類型應具備有效的配置 + 測試類別應具備有效的配置 Test class should have at least one test method or be 'static' with method(s) marked by '[AssemblyInitialize]' and/or '[AssemblyCleanup]'. - 測試類型至少應有一個測試方法或是 'static',而其方法是以 '[AssemblyInitialization]' 和/或 '[AssemblyCleanup]'標示。 + 測試類別至少應有一個測試方法或是 'static',而其方法是以 '[AssemblyInitialization]' 和/或 '[AssemblyCleanup]'標示。 Test class '{0}' should have at least one test method or be 'static' with method(s) marked by '[AssemblyInitialize]' and/or '[AssemblyCleanup]' - 測試類型 '{0}' 至少應有一個測試方法或是 'static',而其方法是以 '[AssemblyInitialization]' 和/或 '[AssemblyCleanup]'標示。 + 測試類別 '{0}' 至少應有一個測試方法或是 'static',而其方法是以 '[AssemblyInitialization]' 和/或 '[AssemblyCleanup]'標示。 Test class should have test method - 測試類型應該要有測試方法 + 測試類別應該要有測試方法 @@ -635,10 +635,10 @@ The type declaring these methods should also respect the following rules: - 傳回類型應為 'void'、'Task' 或 'ValueTask' 宣告這些方法的類型還應遵循以下規則: --類型應為類型 --類型應為 'public' 或 'internal' (如果測試專案使用 '[DiscoverInternals]' 屬性) --類型不應為 'static' --如果類型是 'sealed',則應標示為 '[TestClass]' (或衍生屬性)。 +-類型應為類別 +-類別應為 'public' 或 'internal' (如果測試專案使用 '[DiscoverInternals]' 屬性) +-類別不應為 'static' +-如果類別是 'sealed',則應標示為 '[TestClass]' (或衍生屬性)。 @@ -694,10 +694,10 @@ The type declaring these methods should also respect the following rules: - 傳回類型應為 'void'、'Task' 或 'ValueTask' 宣告這些方法的類型還應遵循以下規則: --類型應為類型 --類型應為 'public' 或 'internal' (如果測試專案使用 '[DiscoverInternals]' 屬性) --類型不應為 'static' --如果類型是 'sealed',則應標示為 '[TestClass]' (或衍生屬性)。 +-類型應為類別 +-類別應為 'public' 或 'internal' (如果測試專案使用 '[DiscoverInternals]' 屬性) +-類別不應為 'static' +-如果類別是 'sealed',則應標示為 '[TestClass]' (或衍生屬性)。 @@ -751,12 +751,12 @@ The type declaring these methods should also respect the following rules: Type containing '[TestMethod]' should be marked with '[TestClass]', otherwise the test method will be silently ignored. - 包含 '[TestMethod]' 的類型應標記為 '[TestClass]',否則將以無訊息的方式忽略測試方法。 + Type containing '[TestMethod]' should be marked with '[TestClass]', otherwise the test method will be silently ignored. Type '{0}' contains test methods and should be marked with '[TestClass]' - 類型 '{0}' 包含測試方法,應以 '[TestClass]' 標記 + Type '{0}' contains test methods and should be marked with '[TestClass]' @@ -786,12 +786,12 @@ The type declaring these methods should also respect the following rules: The attribute '{0}' which derives from 'ConditionBaseAttribute' should be used only on classes marked with `TestClassAttribute` - 衍生自 'ConditionBaseAttribute' 的屬性 '{0}' 只能用於標示為 'TestClassAttribute' 的類型 + 衍生自 'ConditionBaseAttribute' 的屬性 '{0}' 只能用於標示為 'TestClassAttribute' 的類別 Use 'ConditionBaseAttribute' on test classes - 在測試類型上使用 'ConditionBaseAttribute' + 在測試類別上使用 'ConditionBaseAttribute' From 62d63f1db75f3af6a6b03668dae7fa9fda519531 Mon Sep 17 00:00:00 2001 From: dotnet bot Date: Wed, 16 Jul 2025 12:15:38 +0200 Subject: [PATCH 236/541] Localized file check-in by OneLocBuild Task: Build definition ID 1218: Build ID 2751225 --- .../Resources/xlf/PlatformResources.es.xlf | 4 ++-- .../Resources/xlf/PlatformResources.ko.xlf | 4 ++-- .../Resources/xlf/PlatformResources.pt-BR.xlf | 4 ++-- .../Resources/xlf/PlatformResources.zh-Hant.xlf | 4 ++-- .../TestFramework/Resources/xlf/FrameworkMessages.cs.xlf | 2 +- .../TestFramework/Resources/xlf/FrameworkMessages.de.xlf | 2 +- .../TestFramework/Resources/xlf/FrameworkMessages.es.xlf | 2 +- .../TestFramework/Resources/xlf/FrameworkMessages.fr.xlf | 2 +- .../TestFramework/Resources/xlf/FrameworkMessages.it.xlf | 2 +- .../TestFramework/Resources/xlf/FrameworkMessages.ja.xlf | 2 +- .../TestFramework/Resources/xlf/FrameworkMessages.ko.xlf | 2 +- .../TestFramework/Resources/xlf/FrameworkMessages.pl.xlf | 2 +- .../TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf | 2 +- .../TestFramework/Resources/xlf/FrameworkMessages.ru.xlf | 2 +- .../TestFramework/Resources/xlf/FrameworkMessages.tr.xlf | 2 +- .../TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf | 2 +- .../TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf | 2 +- 17 files changed, 21 insertions(+), 21 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.es.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.es.xlf index d0d63bebd0..ca186817c4 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.es.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.es.xlf @@ -433,7 +433,7 @@ Passing both '--treenode-filter' and '--filter-uid' is unsupported. - Passing both '--treenode-filter' and '--filter-uid' is unsupported. + No se admite el paso de "--treenode-filter" y "--filter-uid". @@ -540,7 +540,7 @@ Los valores disponibles son 'Seguimiento', 'Depurar', 'Información', 'Advertenc Provides a list of test node UIDs to filter by. - Provides a list of test node UIDs to filter by. + Proporciona una lista de UID de nodo de prueba por los que filtrar. diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ko.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ko.xlf index 6ed7dc2c13..7f03d3493f 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ko.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ko.xlf @@ -433,7 +433,7 @@ Passing both '--treenode-filter' and '--filter-uid' is unsupported. - Passing both '--treenode-filter' and '--filter-uid' is unsupported. + '--treenode-filter'와 '--filter-uid'를 동시에 전달하는 것은 지원되지 않습니다. @@ -540,7 +540,7 @@ The available values are 'Trace', 'Debug', 'Information', 'Warning', 'Error', an Provides a list of test node UIDs to filter by. - Provides a list of test node UIDs to filter by. + 필터링에 사용할 테스트 노드 UID 목록을 제공합니다. diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pt-BR.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pt-BR.xlf index 8683d75595..1d7d23e6c5 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pt-BR.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pt-BR.xlf @@ -433,7 +433,7 @@ Passing both '--treenode-filter' and '--filter-uid' is unsupported. - Passing both '--treenode-filter' and '--filter-uid' is unsupported. + Não há suporte para a passagem de "--treenode-filter" e "--filter-uid". @@ -540,7 +540,7 @@ Os valores disponíveis são 'Rastreamento', 'Depuração', 'Informação', 'Avi Provides a list of test node UIDs to filter by. - Provides a list of test node UIDs to filter by. + Fornece uma lista de UIDs de nó de teste para filtrar. diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hant.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hant.xlf index 17f154bcbd..c28018b0c9 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hant.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hant.xlf @@ -433,7 +433,7 @@ Passing both '--treenode-filter' and '--filter-uid' is unsupported. - Passing both '--treenode-filter' and '--filter-uid' is unsupported. + 不支援同時傳遞 '--treenode-filter' 和 '--filter-uid'。 @@ -540,7 +540,7 @@ The available values are 'Trace', 'Debug', 'Information', 'Warning', 'Error', an Provides a list of test node UIDs to filter by. - Provides a list of test node UIDs to filter by. + 提供要篩選的測試節點 UID 清單。 diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.cs.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.cs.xlf index cd09820994..cdfd10e6e2 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.cs.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.cs.xlf @@ -129,7 +129,7 @@ Dynamic data method '{0}' should be static, non-generic, and cannot have 'params' parameter. - Metoda dynamických dat {0} by měla být statická, bez parametrů a negenerická. + Dynamic data method '{0}' should be static, non-generic, and cannot have 'params' parameter. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.de.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.de.xlf index 45cf5b7ab6..ab448cf99e 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.de.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.de.xlf @@ -129,7 +129,7 @@ Dynamic data method '{0}' should be static, non-generic, and cannot have 'params' parameter. - Die dynamische Datenmethode "{0}" muss statisch, parameterlos sein und nichtgenerisch sein. + Dynamic data method '{0}' should be static, non-generic, and cannot have 'params' parameter. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.es.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.es.xlf index 051409c88b..fa11435b72 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.es.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.es.xlf @@ -129,7 +129,7 @@ Dynamic data method '{0}' should be static, non-generic, and cannot have 'params' parameter. - El método de datos dinámicos '{0}' debe ser estático, sin parámetros y no genérico. + Dynamic data method '{0}' should be static, non-generic, and cannot have 'params' parameter. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.fr.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.fr.xlf index c724cb752f..5b232cdc7d 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.fr.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.fr.xlf @@ -129,7 +129,7 @@ Dynamic data method '{0}' should be static, non-generic, and cannot have 'params' parameter. - La méthode de données dynamiques « {0} » doit être statique, sans paramètre et non générique. + Dynamic data method '{0}' should be static, non-generic, and cannot have 'params' parameter. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.it.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.it.xlf index 22d4ebcb42..3d232247fa 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.it.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.it.xlf @@ -129,7 +129,7 @@ Dynamic data method '{0}' should be static, non-generic, and cannot have 'params' parameter. - Il metodo '{0}' di Dynamic Data deve essere statico, senza parametri e non generico. + Dynamic data method '{0}' should be static, non-generic, and cannot have 'params' parameter. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ja.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ja.xlf index 4c01f755cb..3379b1f817 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ja.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ja.xlf @@ -129,7 +129,7 @@ Dynamic data method '{0}' should be static, non-generic, and cannot have 'params' parameter. - 動的データ メソッド '{0}' は、静的、パラメーターなし、および非ジェネリックである必要があります。 + Dynamic data method '{0}' should be static, non-generic, and cannot have 'params' parameter. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ko.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ko.xlf index a821258570..af2bd1e43a 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ko.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ko.xlf @@ -129,7 +129,7 @@ Dynamic data method '{0}' should be static, non-generic, and cannot have 'params' parameter. - 동적 데이터 메서드 '{0}'은(는) 정적이고 매개 변수가 없으며 제네릭이 아니어야 합니다. + Dynamic data method '{0}' should be static, non-generic, and cannot have 'params' parameter. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pl.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pl.xlf index 006492b973..32011dab63 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pl.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pl.xlf @@ -129,7 +129,7 @@ Dynamic data method '{0}' should be static, non-generic, and cannot have 'params' parameter. - Metoda danych dynamicznych „{0}” powinna być statyczna, bez parametrów i nie generyczna. + Dynamic data method '{0}' should be static, non-generic, and cannot have 'params' parameter. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf index 89cab33007..e70e40945c 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf @@ -129,7 +129,7 @@ Dynamic data method '{0}' should be static, non-generic, and cannot have 'params' parameter. - O método de dados dinâmicos "{0}" deve ser estático, sem parâmetros e não genérico. + Dynamic data method '{0}' should be static, non-generic, and cannot have 'params' parameter. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ru.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ru.xlf index facc544bf2..a9cd38b2b7 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ru.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ru.xlf @@ -129,7 +129,7 @@ Dynamic data method '{0}' should be static, non-generic, and cannot have 'params' parameter. - Метод динамических данных "{0}" должен быть статическим, не иметь параметров и быть неуниверсальным. + Dynamic data method '{0}' should be static, non-generic, and cannot have 'params' parameter. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.tr.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.tr.xlf index 2787b15cbd..e59ba38112 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.tr.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.tr.xlf @@ -129,7 +129,7 @@ Dynamic data method '{0}' should be static, non-generic, and cannot have 'params' parameter. - '{0}' dinamik veri yöntemi statik ve parametresiz olmalı ve genel olmamalıdır. + Dynamic data method '{0}' should be static, non-generic, and cannot have 'params' parameter. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf index 82058cc4ea..cd60303177 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf @@ -129,7 +129,7 @@ Dynamic data method '{0}' should be static, non-generic, and cannot have 'params' parameter. - 动态数据方法“{0}”应为静态、无参数和非泛型。 + Dynamic data method '{0}' should be static, non-generic, and cannot have 'params' parameter. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf index 86030a3f11..97c00cffff 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf @@ -129,7 +129,7 @@ Dynamic data method '{0}' should be static, non-generic, and cannot have 'params' parameter. - 動態資料方法 '{0}' 應為靜態、無參數及非泛型。 + Dynamic data method '{0}' should be static, non-generic, and cannot have 'params' parameter. From 799f0b2cdcbef1577306748d9565b6117180cd49 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Wed, 16 Jul 2025 12:36:51 +0200 Subject: [PATCH 237/541] Track MSTest updates with Darc (#6061) --- Directory.Packages.props | 2 -- eng/Version.Details.xml | 4 ++++ eng/Versions.props | 2 ++ 3 files changed, 6 insertions(+), 2 deletions(-) diff --git a/Directory.Packages.props b/Directory.Packages.props index 1be90580da..7c8ac71080 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -29,8 +29,6 @@ 1.1.3-beta1.24423.1 - 3.10.0-preview.25311.1 - 1.8.0-preview.25311.1 diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index a0bbb0706e..c5d3a211fd 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -17,5 +17,9 @@ https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage 06325faa0d16bac193af8d51026f03208034880d + + https://github.com/microsoft/testfx + 0bc914379dd1521f8b0c75f860821e6b4ac5f547 + diff --git a/eng/Versions.props b/eng/Versions.props index f3deca5315..d8e2d77ffe 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -9,5 +9,7 @@ 10.0.0-beta.25358.3 18.0.0-preview.25365.3 + 3.10.0-preview.25311.1 + 1.8.0-preview.25311.1 From d4e613fa2988ed05264b27c08607d0430edc122e Mon Sep 17 00:00:00 2001 From: Copilot <198982749+Copilot@users.noreply.github.com> Date: Wed, 16 Jul 2025 11:45:38 +0000 Subject: [PATCH 238/541] Add diagnostic suppressor for IDE0060 warnings on TestContext parameters in MSTest fixture methods (#6055) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: Evangelink <11340282+Evangelink@users.noreply.github.com> Co-authored-by: Amaury Levé --- .../MSTest.Analyzers/Helpers/DiagnosticIds.cs | 1 + .../MSTest.Analyzers/PublicAPI.Unshipped.txt | 4 + .../MSTest.Analyzers/Resources.Designer.cs | 119 ++++++------ src/Analyzers/MSTest.Analyzers/Resources.resx | 3 + .../UnusedParameterSuppressor.cs | 66 +++++++ .../MSTest.Analyzers/xlf/Resources.cs.xlf | 5 + .../MSTest.Analyzers/xlf/Resources.de.xlf | 5 + .../MSTest.Analyzers/xlf/Resources.es.xlf | 5 + .../MSTest.Analyzers/xlf/Resources.fr.xlf | 5 + .../MSTest.Analyzers/xlf/Resources.it.xlf | 5 + .../MSTest.Analyzers/xlf/Resources.ja.xlf | 5 + .../MSTest.Analyzers/xlf/Resources.ko.xlf | 5 + .../MSTest.Analyzers/xlf/Resources.pl.xlf | 5 + .../MSTest.Analyzers/xlf/Resources.pt-BR.xlf | 5 + .../MSTest.Analyzers/xlf/Resources.ru.xlf | 5 + .../MSTest.Analyzers/xlf/Resources.tr.xlf | 5 + .../xlf/Resources.zh-Hans.xlf | 5 + .../xlf/Resources.zh-Hant.xlf | 5 + .../UnusedParameterSuppressorTests.cs | 182 ++++++++++++++++++ 19 files changed, 385 insertions(+), 55 deletions(-) create mode 100644 src/Analyzers/MSTest.Analyzers/UnusedParameterSuppressor.cs create mode 100644 test/UnitTests/MSTest.Analyzers.UnitTests/UnusedParameterSuppressorTests.cs diff --git a/src/Analyzers/MSTest.Analyzers/Helpers/DiagnosticIds.cs b/src/Analyzers/MSTest.Analyzers/Helpers/DiagnosticIds.cs index dd310737ac..4d53ecde3a 100644 --- a/src/Analyzers/MSTest.Analyzers/Helpers/DiagnosticIds.cs +++ b/src/Analyzers/MSTest.Analyzers/Helpers/DiagnosticIds.cs @@ -51,4 +51,5 @@ internal static class DiagnosticIds public const string PreferTestMethodOverDataTestMethodRuleId = "MSTEST0044"; public const string UseCooperativeCancellationForTimeoutRuleId = "MSTEST0045"; public const string StringAssertToAssertRuleId = "MSTEST0046"; + public const string UnusedParameterSuppressorRuleId = "MSTEST0047"; } diff --git a/src/Analyzers/MSTest.Analyzers/PublicAPI.Unshipped.txt b/src/Analyzers/MSTest.Analyzers/PublicAPI.Unshipped.txt index dcb3006d98..661b930e2b 100644 --- a/src/Analyzers/MSTest.Analyzers/PublicAPI.Unshipped.txt +++ b/src/Analyzers/MSTest.Analyzers/PublicAPI.Unshipped.txt @@ -7,3 +7,7 @@ MSTest.Analyzers.UseCooperativeCancellationForTimeoutAnalyzer MSTest.Analyzers.UseCooperativeCancellationForTimeoutAnalyzer.UseCooperativeCancellationForTimeoutAnalyzer() -> void override MSTest.Analyzers.UseCooperativeCancellationForTimeoutAnalyzer.Initialize(Microsoft.CodeAnalysis.Diagnostics.AnalysisContext! context) -> void override MSTest.Analyzers.UseCooperativeCancellationForTimeoutAnalyzer.SupportedDiagnostics.get -> System.Collections.Immutable.ImmutableArray +MSTest.Analyzers.UnusedParameterSuppressor +MSTest.Analyzers.UnusedParameterSuppressor.UnusedParameterSuppressor() -> void +override MSTest.Analyzers.UnusedParameterSuppressor.ReportSuppressions(Microsoft.CodeAnalysis.Diagnostics.SuppressionAnalysisContext context) -> void +override MSTest.Analyzers.UnusedParameterSuppressor.SupportedSuppressions.get -> System.Collections.Immutable.ImmutableArray diff --git a/src/Analyzers/MSTest.Analyzers/Resources.Designer.cs b/src/Analyzers/MSTest.Analyzers/Resources.Designer.cs index 76be305263..6c5ee95586 100644 --- a/src/Analyzers/MSTest.Analyzers/Resources.Designer.cs +++ b/src/Analyzers/MSTest.Analyzers/Resources.Designer.cs @@ -19,7 +19,7 @@ namespace MSTest.Analyzers { // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "18.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { @@ -363,15 +363,6 @@ internal static string DataRowShouldBeValidMessageFormat_ArgumentTypeMismatch { } } - /// - /// Looks up a localized string similar to Parameter '{0}' expects type '{1}', but the provided value has type '{2}'. - /// - internal static string DataRowShouldBeValidMessageFormat_ParameterMismatch { - get { - return ResourceManager.GetString("DataRowShouldBeValidMessageFormat_ParameterMismatch", resourceCulture); - } - } - /// /// Looks up a localized string similar to Found two conflicting types for generic parameter '{0}'. The conflicting types are '{1}' and '{2}'.. /// @@ -399,6 +390,15 @@ internal static string DataRowShouldBeValidMessageFormat_OnTestMethod { } } + /// + /// Looks up a localized string similar to Parameter '{0}' expects type '{1}', but the provided value has type '{2}'. + /// + internal static string DataRowShouldBeValidMessageFormat_ParameterMismatch { + get { + return ResourceManager.GetString("DataRowShouldBeValidMessageFormat_ParameterMismatch", resourceCulture); + } + } + /// /// Looks up a localized string similar to DataRow should be valid. /// @@ -816,6 +816,24 @@ internal static string ReviewAlwaysTrueAssertConditionAnalyzerTitle { } } + /// + /// Looks up a localized string similar to Use 'Assert.{0}' instead of 'StringAssert.{1}'. + /// + internal static string StringAssertToAssertMessageFormat { + get { + return ResourceManager.GetString("StringAssertToAssertMessageFormat", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Use 'Assert' instead of 'StringAssert'. + /// + internal static string StringAssertToAssertTitle { + get { + return ResourceManager.GetString("StringAssertToAssertTitle", resourceCulture); + } + } + /// /// Looks up a localized string similar to Test classes, classes marked with the '[TestClass]' attribute, should respect the following layout to be considered valid by MSTest: ///- it should be 'public' (or 'internal' if '[assembly: DiscoverInternals]' attribute is set) @@ -1069,6 +1087,15 @@ internal static string TypeContainingTestMethodShouldBeATestClassTitle { } } + /// + /// Looks up a localized string similar to TestContext parameter is required by MSTest for AssemblyInitialize and ClassInitialize methods. + /// + internal static string UnusedParameterSuppressorJustification { + get { + return ResourceManager.GetString("UnusedParameterSuppressorJustification", resourceCulture); + } + } + /// /// Looks up a localized string similar to Asynchronous test fixture methods do not require the 'Async' suffix. /// @@ -1150,6 +1177,33 @@ internal static string UseConditionBaseWithTestClassTitle { } } + /// + /// Looks up a localized string similar to Using '[Timeout]' without explicitly setting 'CooperativeCancellation = true' is discouraged. In a future version, cooperative cancellation will become the default behavior. Set 'CooperativeCancellation = true' to opt into the recommended behavior and avoid breaking changes.. + /// + internal static string UseCooperativeCancellationForTimeoutDescription { + get { + return ResourceManager.GetString("UseCooperativeCancellationForTimeoutDescription", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Use 'CooperativeCancellation = true' with '[Timeout]' to enable cooperative cancellation behavior. + /// + internal static string UseCooperativeCancellationForTimeoutMessageFormat { + get { + return ResourceManager.GetString("UseCooperativeCancellationForTimeoutMessageFormat", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Use 'CooperativeCancellation = true' with '[Timeout]'. + /// + internal static string UseCooperativeCancellationForTimeoutTitle { + get { + return ResourceManager.GetString("UseCooperativeCancellationForTimeoutTitle", resourceCulture); + } + } + /// /// Looks up a localized string similar to '[DeploymentItem]' can be specified only on test class or test method. /// @@ -1248,50 +1302,5 @@ internal static string UseRetryWithTestMethodTitle { return ResourceManager.GetString("UseRetryWithTestMethodTitle", resourceCulture); } } - - /// - /// Looks up a localized string similar to Using '[Timeout]' without explicitly setting 'CooperativeCancellation = true' is discouraged. In a future version, cooperative cancellation will become the default behavior. Set 'CooperativeCancellation = true' to opt into the recommended behavior and avoid breaking changes.. - /// - internal static string UseCooperativeCancellationForTimeoutDescription { - get { - return ResourceManager.GetString("UseCooperativeCancellationForTimeoutDescription", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Use 'CooperativeCancellation = true' with '[Timeout]' to enable cooperative cancellation behavior. - /// - internal static string UseCooperativeCancellationForTimeoutMessageFormat { - get { - return ResourceManager.GetString("UseCooperativeCancellationForTimeoutMessageFormat", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Use 'CooperativeCancellation = true' with '[Timeout]'. - /// - internal static string UseCooperativeCancellationForTimeoutTitle { - get { - return ResourceManager.GetString("UseCooperativeCancellationForTimeoutTitle", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Use 'Assert.{0}' instead of 'StringAssert.{1}'. - /// - internal static string StringAssertToAssertMessageFormat { - get { - return ResourceManager.GetString("StringAssertToAssertMessageFormat", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Use 'Assert' instead of 'StringAssert'. - /// - internal static string StringAssertToAssertTitle { - get { - return ResourceManager.GetString("StringAssertToAssertTitle", resourceCulture); - } - } } } diff --git a/src/Analyzers/MSTest.Analyzers/Resources.resx b/src/Analyzers/MSTest.Analyzers/Resources.resx index c311df6480..c07751049e 100644 --- a/src/Analyzers/MSTest.Analyzers/Resources.resx +++ b/src/Analyzers/MSTest.Analyzers/Resources.resx @@ -429,6 +429,9 @@ The type declaring these methods should also respect the following rules: Asynchronous test methods do not require the 'Async' suffix + + TestContext parameter is required by MSTest for AssemblyInitialize and ClassInitialize methods + [{0}] can only be set on methods marked with [TestMethod] diff --git a/src/Analyzers/MSTest.Analyzers/UnusedParameterSuppressor.cs b/src/Analyzers/MSTest.Analyzers/UnusedParameterSuppressor.cs new file mode 100644 index 0000000000..7919a526b8 --- /dev/null +++ b/src/Analyzers/MSTest.Analyzers/UnusedParameterSuppressor.cs @@ -0,0 +1,66 @@ +// 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.Immutable; + +using Analyzer.Utilities.Extensions; + +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Diagnostics; + +using MSTest.Analyzers.Helpers; + +namespace MSTest.Analyzers; + +/// +/// MSTEST0047: . +/// +[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] +public sealed class UnusedParameterSuppressor : DiagnosticSuppressor +{ + // IDE0060: Remove unused parameter 'name' if it is not part of a shipped public API + // https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0060 + private const string SuppressedDiagnosticId = "IDE0060"; + + internal static readonly SuppressionDescriptor Rule = + new(DiagnosticIds.UnusedParameterSuppressorRuleId, SuppressedDiagnosticId, Resources.UnusedParameterSuppressorJustification); + + /// + public override ImmutableArray SupportedSuppressions { get; } = ImmutableArray.Create(Rule); + + /// + public override void ReportSuppressions(SuppressionAnalysisContext context) + { + if (!context.Compilation.TryGetOrCreateTypeByMetadataName(WellKnownTypeNames.MicrosoftVisualStudioTestToolsUnitTestingAssemblyInitializeAttribute, out INamedTypeSymbol? assemblyInitializeAttributeSymbol) + || !context.Compilation.TryGetOrCreateTypeByMetadataName(WellKnownTypeNames.MicrosoftVisualStudioTestToolsUnitTestingClassInitializeAttribute, out INamedTypeSymbol? classInitializeAttributeSymbol) + || !context.Compilation.TryGetOrCreateTypeByMetadataName(WellKnownTypeNames.MicrosoftVisualStudioTestToolsUnitTestingTestContext, out INamedTypeSymbol? testContextSymbol)) + { + return; + } + + foreach (Diagnostic diagnostic in context.ReportedDiagnostics) + { + // The diagnostic is reported on the parameter + if (diagnostic.Location.SourceTree is not { } tree) + { + continue; + } + + SyntaxNode root = tree.GetRoot(context.CancellationToken); + SyntaxNode node = root.FindNode(diagnostic.Location.SourceSpan, getInnermostNodeForTie: true); + + SemanticModel semanticModel = context.GetSemanticModel(tree); + ISymbol? declaredSymbol = semanticModel.GetDeclaredSymbol(node, context.CancellationToken); + + if (declaredSymbol is IParameterSymbol parameter + && SymbolEqualityComparer.Default.Equals(testContextSymbol, parameter.Type) + && parameter.ContainingSymbol is IMethodSymbol method + && method.GetAttributes().Any(attr => + SymbolEqualityComparer.Default.Equals(attr.AttributeClass, assemblyInitializeAttributeSymbol) || + SymbolEqualityComparer.Default.Equals(attr.AttributeClass, classInitializeAttributeSymbol))) + { + context.ReportSuppression(Suppression.Create(Rule, diagnostic)); + } + } + } +} diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf index 5e787821df..b8317b2b0d 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf @@ -774,6 +774,11 @@ Typ deklarující tyto metody by měl také respektovat následující pravidla: Asynchronní testovací metody nevyžadují příponu Async. + + TestContext parameter is required by MSTest for AssemblyInitialize and ClassInitialize methods + TestContext parameter is required by MSTest for AssemblyInitialize and ClassInitialize methods + + [{0}] can only be set on methods marked with [TestMethod] [{0}] lze nastavit pouze u metod označených pomocí metody [TestMethod]. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf index ccbde6b1a4..86e519c247 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf @@ -775,6 +775,11 @@ Der Typ, der diese Methoden deklariert, sollte auch die folgenden Regeln beachte Für asynchrone Testmethoden ist das Suffix "Async" nicht erforderlich. + + TestContext parameter is required by MSTest for AssemblyInitialize and ClassInitialize methods + TestContext parameter is required by MSTest for AssemblyInitialize and ClassInitialize methods + + [{0}] can only be set on methods marked with [TestMethod] [{0}] kann nur für Methoden festgelegt werden, die mit [TestMethod] markiert sind. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf index 81f1f62818..7b76f19463 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf @@ -774,6 +774,11 @@ El tipo que declara estos métodos también debe respetar las reglas siguientes: Los métodos de prueba asincrónicos no requieren el sufijo "Async". + + TestContext parameter is required by MSTest for AssemblyInitialize and ClassInitialize methods + TestContext parameter is required by MSTest for AssemblyInitialize and ClassInitialize methods + + [{0}] can only be set on methods marked with [TestMethod] [{0}] solo se puede establecer en métodos marcados con [TestMethod] diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf index 22234547e0..ade02ce357 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf @@ -774,6 +774,11 @@ Le type doit être une classe Les méthodes de test asynchrones ne nécessitent pas le suffixe 'Async' + + TestContext parameter is required by MSTest for AssemblyInitialize and ClassInitialize methods + TestContext parameter is required by MSTest for AssemblyInitialize and ClassInitialize methods + + [{0}] can only be set on methods marked with [TestMethod] [{0}] ne peut être défini que sur les méthodes marquées avec [TestMethod] diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf index 3016d41c56..d63f2cbf01 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf @@ -774,6 +774,11 @@ Anche il tipo che dichiara questi metodi deve rispettare le regole seguenti: I metodi di test asincroni non richiedono il suffisso 'Async' + + TestContext parameter is required by MSTest for AssemblyInitialize and ClassInitialize methods + TestContext parameter is required by MSTest for AssemblyInitialize and ClassInitialize methods + + [{0}] can only be set on methods marked with [TestMethod] [{0}] può essere impostato solo su metodi contrassegnati con [TestMethod] diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf index 9b5f87e55e..188f74eec2 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf @@ -774,6 +774,11 @@ The type declaring these methods should also respect the following rules: 非同期テスト メソッドには 'Async' サフィックスは不要です + + TestContext parameter is required by MSTest for AssemblyInitialize and ClassInitialize methods + TestContext parameter is required by MSTest for AssemblyInitialize and ClassInitialize methods + + [{0}] can only be set on methods marked with [TestMethod] [{0}] は、[TestMethod] でマークされたメソッドにのみ設定できます diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf index f7a0d60b2d..a3d8d391f3 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf @@ -774,6 +774,11 @@ The type declaring these methods should also respect the following rules: 비동기 테스트 메서드에는 'Async' 접미사가 필요하지 않습니다. + + TestContext parameter is required by MSTest for AssemblyInitialize and ClassInitialize methods + TestContext parameter is required by MSTest for AssemblyInitialize and ClassInitialize methods + + [{0}] can only be set on methods marked with [TestMethod] [{0}]은(는) [TestMethod] 표시된 메서드에만 설정할 수 있습니다. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf index bfc0402cf5..955670c6d2 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf @@ -774,6 +774,11 @@ Typ deklarujący te metody powinien również przestrzegać następujących regu Asynchroniczne metody testowe nie wymagają sufiksu „Async” + + TestContext parameter is required by MSTest for AssemblyInitialize and ClassInitialize methods + TestContext parameter is required by MSTest for AssemblyInitialize and ClassInitialize methods + + [{0}] can only be set on methods marked with [TestMethod] [{0}] można ustawić tylko dla metod oznaczonych znakiem [TestMethod] diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf index af02422de8..0158a478ac 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf @@ -774,6 +774,11 @@ O tipo que declara esses métodos também deve respeitar as seguintes regras: Os métodos de teste assíncronos não exigem o sufixo 'Async' + + TestContext parameter is required by MSTest for AssemblyInitialize and ClassInitialize methods + TestContext parameter is required by MSTest for AssemblyInitialize and ClassInitialize methods + + [{0}] can only be set on methods marked with [TestMethod] [{0}] só pode ser definido em métodos marcados com [TestMethod] diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf index fb9e235060..6808e24aaf 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf @@ -786,6 +786,11 @@ The type declaring these methods should also respect the following rules: Асинхронные методы теста не требуют суффикса Async + + TestContext parameter is required by MSTest for AssemblyInitialize and ClassInitialize methods + TestContext parameter is required by MSTest for AssemblyInitialize and ClassInitialize methods + + [{0}] can only be set on methods marked with [TestMethod] [{0}] можно задать только для методов с пометкой [TestMethod] diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf index 2810454bfe..8d130388e4 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf @@ -776,6 +776,11 @@ Bu yöntemleri bildiren tipin ayrıca aşağıdaki kurallara uyması gerekir: Asenkron test metotları için 'Async' soneki gerekmez + + TestContext parameter is required by MSTest for AssemblyInitialize and ClassInitialize methods + TestContext parameter is required by MSTest for AssemblyInitialize and ClassInitialize methods + + [{0}] can only be set on methods marked with [TestMethod] [{0}] yalnızca [TestMethod] ile işaretli yöntemlerde ayarlanabilir diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf index 547953c4db..e82f1102d0 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf @@ -774,6 +774,11 @@ The type declaring these methods should also respect the following rules: 异步测试方法不需要 "Async" 后缀 + + TestContext parameter is required by MSTest for AssemblyInitialize and ClassInitialize methods + TestContext parameter is required by MSTest for AssemblyInitialize and ClassInitialize methods + + [{0}] can only be set on methods marked with [TestMethod] 只能对标记了 [TestMethod] 的方法设置 [{0}] diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf index cf7ea015e7..c8e722519c 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf @@ -774,6 +774,11 @@ The type declaring these methods should also respect the following rules: 非同步測試方法不需要 'Async' 尾碼 + + TestContext parameter is required by MSTest for AssemblyInitialize and ClassInitialize methods + TestContext parameter is required by MSTest for AssemblyInitialize and ClassInitialize methods + + [{0}] can only be set on methods marked with [TestMethod] [{0}] 只能在標示為 [TestMethod] 的方法上設定 diff --git a/test/UnitTests/MSTest.Analyzers.UnitTests/UnusedParameterSuppressorTests.cs b/test/UnitTests/MSTest.Analyzers.UnitTests/UnusedParameterSuppressorTests.cs new file mode 100644 index 0000000000..df1c94ea0d --- /dev/null +++ b/test/UnitTests/MSTest.Analyzers.UnitTests/UnusedParameterSuppressorTests.cs @@ -0,0 +1,182 @@ +// 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.Immutable; + +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Diagnostics; + +using VerifyCS = MSTest.Analyzers.Test.CSharpCodeFixVerifier< + MSTest.Analyzers.UnitTests.UnusedParameterSuppressorTests.WarnForUnusedParameters, + Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>; + +namespace MSTest.Analyzers.UnitTests; + +[TestClass] +public sealed class UnusedParameterSuppressorTests +{ + [TestMethod] + public async Task AssemblyInitializeWithUnusedTestContext_DiagnosticIsSuppressed() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class SomeClass + { + [AssemblyInitialize] + public static void Initialize(TestContext [|context|]) + { + // TestContext parameter is unused but required by MSTest + } + } + """; + + // Verify issue is reported without suppressor + await new VerifyCS.Test + { + TestState = { Sources = { code } }, + }.RunAsync(); + + // Verify issue is suppressed with suppressor + await new TestWithSuppressor + { + TestState = { Sources = { code } }, + }.RunAsync(); + } + + [TestMethod] + public async Task ClassInitializeWithUnusedTestContext_DiagnosticIsSuppressed() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class SomeClass + { + [ClassInitialize] + public static void Initialize(TestContext [|context|]) + { + // TestContext parameter is unused but required by MSTest + } + } + """; + + // Verify issue is reported without suppressor + await new VerifyCS.Test + { + TestState = { Sources = { code } }, + }.RunAsync(); + + // Verify issue is suppressed with suppressor + await new TestWithSuppressor + { + TestState = { Sources = { code } }, + }.RunAsync(); + } + + [TestMethod] + public async Task TestMethodWithUnusedParameter_DiagnosticIsNotSuppressed() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class SomeClass + { + [TestMethod] + public void TestMethod(int [|unusedParam|]) + { + // This should not be suppressed + } + } + """; + + // Verify issue is reported without suppressor + await new VerifyCS.Test + { + TestState = { Sources = { code } }, + }.RunAsync(); + + // Verify issue is still reported with suppressor (not suppressed) + await new TestWithSuppressor + { + TestState = { Sources = { code } }, + }.RunAsync(); + } + + [TestMethod] + public async Task RegularMethodWithUnusedTestContext_DiagnosticIsNotSuppressed() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class SomeClass + { + public void RegularMethod(TestContext [|context|]) + { + // This should not be suppressed as it's not AssemblyInitialize or ClassInitialize + } + } + """; + + // Verify issue is reported without suppressor + await new VerifyCS.Test + { + TestState = { Sources = { code } }, + }.RunAsync(); + + // Verify issue is still reported with suppressor (not suppressed) + await new TestWithSuppressor + { + TestState = { Sources = { code } }, + }.RunAsync(); + } + + [DiagnosticAnalyzer(LanguageNames.CSharp)] + [SuppressMessage("MicrosoftCodeAnalysisCorrectness", "RS1038:Compiler extensions should be implemented in assemblies with compiler-provided references", Justification = "For suppression test only.")] + [SuppressMessage("MicrosoftCodeAnalysisCorrectness", "RS1036:Specify analyzer banned API enforcement setting", Justification = "For suppression test only.")] + [SuppressMessage("MicrosoftCodeAnalysisCorrectness", "RS1041:Compiler extensions should be implemented in assemblies targeting netstandard2.0", Justification = "For suppression test only.")] + public class WarnForUnusedParameters : DiagnosticAnalyzer + { + [SuppressMessage("MicrosoftCodeAnalysisDesign", "RS1017:DiagnosticId for analyzers must be a non-null constant.", Justification = "For suppression test only.")] + public static readonly DiagnosticDescriptor Rule = new(UnusedParameterSuppressor.Rule.SuppressedDiagnosticId, "Remove unused parameter", "Remove unused parameter '{0}' if it is not part of a shipped public API", "Style", DiagnosticSeverity.Warning, isEnabledByDefault: true); + + public override ImmutableArray SupportedDiagnostics => [Rule]; + + public override void Initialize(AnalysisContext context) + { + context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); + context.EnableConcurrentExecution(); + + context.RegisterSymbolAction(AnalyzeSymbol, SymbolKind.Parameter); + } + + private static void AnalyzeSymbol(SymbolAnalysisContext context) + { + if (context.Symbol is IParameterSymbol parameter) + { + // Simple mock: report all parameters as unused for testing purposes + var diagnostic = Diagnostic.Create( + Rule, + parameter.Locations.FirstOrDefault(), + parameter.Name); + context.ReportDiagnostic(diagnostic); + } + } + } + + internal sealed class TestWithSuppressor : VerifyCS.Test + { + protected override IEnumerable GetDiagnosticAnalyzers() + { + foreach (DiagnosticAnalyzer analyzer in base.GetDiagnosticAnalyzers()) + { + yield return analyzer; + } + + yield return new UnusedParameterSuppressor(); + } + } +} From 8426edcf3e9e1331a29371acd0f2604544491b68 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Wed, 16 Jul 2025 14:05:07 +0200 Subject: [PATCH 239/541] Update Version.Details.xml (#6066) --- eng/Version.Details.xml | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index c5d3a211fd..f1b08fb4f8 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -17,7 +17,11 @@ https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage 06325faa0d16bac193af8d51026f03208034880d - + + https://github.com/microsoft/testfx + 0bc914379dd1521f8b0c75f860821e6b4ac5f547 + + https://github.com/microsoft/testfx 0bc914379dd1521f8b0c75f860821e6b4ac5f547 From 689830b314494a93b276672b70e35629d38ce639 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Wed, 16 Jul 2025 14:11:28 +0200 Subject: [PATCH 240/541] Use newer version of MSTest (#6059) --- eng/Versions.props | 4 ++-- test/Directory.Build.targets | 3 ++- .../AnalyzersTests.cs | 2 +- .../CrashDumpTests.cs | 6 +++--- .../HangDumpTests.cs | 8 ++++---- .../Helpers/AcceptanceAssert.cs | 6 +++--- .../MSBuildTests.Test.cs | 2 +- .../ServerLoggingTests.cs | 2 +- .../TrxTests.cs | 16 +++++++-------- .../DynamicDataNameProviderTests.cs | 2 +- .../TestUtilities/TestingFrameworkVerifier.cs | 8 +++----- .../ObjectModel/ObjectModelConvertersTests.cs | 6 +++--- .../CommandLine/CommandLineHandlerTests.cs | 6 +++--- .../ConfigurationExtensionsTests.cs | 2 +- .../IPC/IPCTests.cs | 4 ++-- .../Logging/FileLoggerTests.cs | 2 +- .../Messages/AsynchronousMessageBusTests.cs | 2 +- .../Messages/PropertyBagTests.cs | 18 ++++++++--------- .../Messages/TestNodeUidTests.cs | 12 +++++------ .../Terminal/TerminalTestReporterTests.cs | 4 ++-- .../Requests/TreeNodeFilterTests.cs | 18 ++++++++--------- .../Services/ServiceProviderTests.cs | 8 ++++---- .../TestApplicationBuilderTests.cs | 20 +++++++++---------- 23 files changed, 79 insertions(+), 82 deletions(-) diff --git a/eng/Versions.props b/eng/Versions.props index d8e2d77ffe..4f757fd06a 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -9,7 +9,7 @@ 10.0.0-beta.25358.3 18.0.0-preview.25365.3 - 3.10.0-preview.25311.1 - 1.8.0-preview.25311.1 + 3.10.0-preview.25365.10 + 1.8.0-preview.25365.10 diff --git a/test/Directory.Build.targets b/test/Directory.Build.targets index 2980dfd99e..cfdb45cae2 100644 --- a/test/Directory.Build.targets +++ b/test/Directory.Build.targets @@ -11,6 +11,8 @@ x64 $(MSBuildProjectName)_$(TargetFramework)_$(Configuration)_$(Architecture) + Recommended + $(TestRunnerAdditionalArguments) --diagnostic --diagnostic-output-directory $(RepoRoot)artifacts/log/$(Configuration) --diagnostic-output-fileprefix $(ModuleName) --diagnostic-verbosity trace $(TestRunnerAdditionalArguments) --crashdump @@ -47,7 +49,6 @@ - diff --git a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/AnalyzersTests.cs b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/AnalyzersTests.cs index b7db7f3140..bf6d87b7c3 100644 --- a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/AnalyzersTests.cs +++ b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/AnalyzersTests.cs @@ -233,7 +233,7 @@ private static async Task AssertAnalysisModeAsync(string mode, string[] contains foreach (string containsElement in contains) { - StringAssert.Contains(output, containsElement, $"Expected to find '{containsElement}' for analysisMode {mode}"); + Assert.Contains(containsElement, output, $"Expected to find '{containsElement}' for analysisMode {mode}"); } foreach (string doesNotContainElement in doesNotContain) diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/CrashDumpTests.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/CrashDumpTests.cs index fdb315d1cc..edf2e571da 100644 --- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/CrashDumpTests.cs +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/CrashDumpTests.cs @@ -21,7 +21,7 @@ public async Task CrashDump_DefaultSetting_CreateDump(string tfm) TestHostResult testHostResult = await testHost.ExecuteAsync($"--crashdump --results-directory {resultDirectory}"); testHostResult.AssertExitCodeIs(ExitCodes.TestHostProcessExitedNonGracefully); string? dumpFile = Directory.GetFiles(resultDirectory, "CrashDump_*.dmp", SearchOption.AllDirectories).SingleOrDefault(); - Assert.IsTrue(dumpFile is not null, $"Dump file not found '{tfm}'\n{testHostResult}'"); + Assert.IsNotNull(dumpFile, $"Dump file not found '{tfm}'\n{testHostResult}'"); } [TestMethod] @@ -37,7 +37,7 @@ public async Task CrashDump_CustomDumpName_CreateDump() var testHost = TestInfrastructure.TestHost.LocateFrom(AssetFixture.TargetAssetPath, "CrashDump", TargetFrameworks.NetCurrent); TestHostResult testHostResult = await testHost.ExecuteAsync($"--crashdump --crashdump-filename customdumpname.dmp --results-directory {resultDirectory}"); testHostResult.AssertExitCodeIs(ExitCodes.TestHostProcessExitedNonGracefully); - Assert.IsTrue(Directory.GetFiles(resultDirectory, "customdumpname.dmp", SearchOption.AllDirectories).SingleOrDefault() is not null, "Dump file not found"); + Assert.IsNotNull(Directory.GetFiles(resultDirectory, "customdumpname.dmp", SearchOption.AllDirectories).SingleOrDefault(), "Dump file not found"); } [DataRow("Mini")] @@ -58,7 +58,7 @@ public async Task CrashDump_Formats_CreateDump(string format) TestHostResult testHostResult = await testHost.ExecuteAsync($"--crashdump --crashdump-type {format} --results-directory {resultDirectory}"); testHostResult.AssertExitCodeIs(ExitCodes.TestHostProcessExitedNonGracefully); string? dumpFile = Directory.GetFiles(resultDirectory, "CrashDump_*.dmp", SearchOption.AllDirectories).SingleOrDefault(); - Assert.IsTrue(dumpFile is not null, $"Dump file not found '{format}'\n{testHostResult}'"); + Assert.IsNotNull(dumpFile, $"Dump file not found '{format}'\n{testHostResult}'"); File.Delete(dumpFile); } diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/HangDumpTests.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/HangDumpTests.cs index 44150dadf0..cfd501c18c 100644 --- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/HangDumpTests.cs +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/HangDumpTests.cs @@ -27,7 +27,7 @@ public async Task HangDump_DefaultSetting_CreateDump(string tfm) }); testHostResult.AssertExitCodeIs(ExitCodes.TestHostProcessExitedNonGracefully); string? dumpFile = Directory.GetFiles(resultDirectory, "HangDump*.dmp", SearchOption.AllDirectories).SingleOrDefault(); - Assert.IsTrue(dumpFile is not null, $"Dump file not found '{tfm}'\n{testHostResult}'"); + Assert.IsNotNull(dumpFile, $"Dump file not found '{tfm}'\n{testHostResult}'"); } [TestMethod] @@ -50,7 +50,7 @@ public async Task HangDump_CustomFileName_CreateDump() }); testHostResult.AssertExitCodeIs(ExitCodes.TestHostProcessExitedNonGracefully); string? dumpFile = Directory.GetFiles(resultDirectory, "myhungdumpfile_*.dmp", SearchOption.AllDirectories).SingleOrDefault(); - Assert.IsTrue(dumpFile is not null, $"Dump file not found '{TargetFrameworks.NetCurrent}'\n{testHostResult}'"); + Assert.IsNotNull(dumpFile, $"Dump file not found '{TargetFrameworks.NetCurrent}'\n{testHostResult}'"); } [TestMethod] @@ -75,7 +75,7 @@ public async Task HangDump_PathWithSpaces_CreateDump() }); testHostResult.AssertExitCodeIs(ExitCodes.TestHostProcessExitedNonGracefully); string? dumpFile = Directory.GetFiles(resultDirectory, "myhungdumpfile_*.dmp", SearchOption.AllDirectories).SingleOrDefault(); - Assert.IsTrue(dumpFile is not null, $"Dump file not found '{TargetFrameworks.NetCurrent}'\n{testHostResult}'"); + Assert.IsNotNull(dumpFile, $"Dump file not found '{TargetFrameworks.NetCurrent}'\n{testHostResult}'"); } [DataRow("Mini")] @@ -102,7 +102,7 @@ public async Task HangDump_Formats_CreateDump(string format) }); testHostResult.AssertExitCodeIs(ExitCodes.TestHostProcessExitedNonGracefully); string? dumpFile = Directory.GetFiles(resultDirectory, "HangDump*.dmp", SearchOption.AllDirectories).SingleOrDefault(); - Assert.IsTrue(dumpFile is not null, $"Dump file not found '{format}'\n{testHostResult}'"); + Assert.IsNotNull(dumpFile, $"Dump file not found '{format}'\n{testHostResult}'"); } [TestMethod] diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/Helpers/AcceptanceAssert.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/Helpers/AcceptanceAssert.cs index 4831e0ae1e..0669e768d1 100644 --- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/Helpers/AcceptanceAssert.cs +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/Helpers/AcceptanceAssert.cs @@ -85,10 +85,10 @@ public static void AssertOutputDoesNotMatchRegex(this TestHostResult testHostRes => Assert.IsFalse(Regex.IsMatch(testHostResult.StandardOutput, pattern), GenerateFailedAssertionMessage(testHostResult, callerMemberName: callerMemberName, callerFilePath: callerFilePath, callerLineNumber: callerLineNumber)); public static void AssertOutputContains(this TestHostResult testHostResult, string value, [CallerMemberName] string? callerMemberName = null, [CallerFilePath] string? callerFilePath = null, [CallerLineNumber] int callerLineNumber = 0) - => StringAssert.Contains(testHostResult.StandardOutput, value, GenerateFailedAssertionMessage(testHostResult, callerMemberName: callerMemberName, callerFilePath: callerFilePath, callerLineNumber: callerLineNumber), StringComparison.Ordinal); + => Assert.Contains(value, testHostResult.StandardOutput, GenerateFailedAssertionMessage(testHostResult, callerMemberName: callerMemberName, callerFilePath: callerFilePath, callerLineNumber: callerLineNumber), StringComparison.Ordinal); public static void AssertOutputContains(this DotnetMuxerResult dotnetMuxerResult, string value, [CallerMemberName] string? callerMemberName = null, [CallerFilePath] string? callerFilePath = null, [CallerLineNumber] int callerLineNumber = 0) - => StringAssert.Contains(dotnetMuxerResult.StandardOutput, value, GenerateFailedAssertionMessage(dotnetMuxerResult, callerMemberName: callerMemberName, callerFilePath: callerFilePath, callerLineNumber: callerLineNumber), StringComparison.Ordinal); + => Assert.Contains(value, dotnetMuxerResult.StandardOutput, GenerateFailedAssertionMessage(dotnetMuxerResult, callerMemberName: callerMemberName, callerFilePath: callerFilePath, callerLineNumber: callerLineNumber), StringComparison.Ordinal); public static void AssertOutputDoesNotContain(this DotnetMuxerResult dotnetMuxerResult, string value, [CallerMemberName] string? callerMemberName = null, [CallerFilePath] string? callerFilePath = null, [CallerLineNumber] int callerLineNumber = 0) => Assert.IsFalse(dotnetMuxerResult.StandardOutput.Contains(value, StringComparison.Ordinal), GenerateFailedAssertionMessage(dotnetMuxerResult, callerMemberName: callerMemberName, callerFilePath: callerFilePath, callerLineNumber: callerLineNumber)); @@ -100,7 +100,7 @@ public static void AssertOutputDoesNotContain(this TestHostResult testHostResult => Assert.IsFalse(testHostResult.StandardOutput.Contains(value, StringComparison.Ordinal), GenerateFailedAssertionMessage(testHostResult, callerMemberName: callerMemberName, callerFilePath: callerFilePath, callerLineNumber: callerLineNumber)); public static void AssertStandardErrorContains(this TestHostResult testHostResult, string value, [CallerMemberName] string? callerMemberName = null, [CallerFilePath] string? callerFilePath = null, [CallerLineNumber] int callerLineNumber = 0) - => StringAssert.Contains(testHostResult.StandardError, value, GenerateFailedAssertionMessage(testHostResult, callerMemberName: callerMemberName, callerFilePath: callerFilePath, callerLineNumber: callerLineNumber), StringComparison.Ordinal); + => Assert.Contains(value, testHostResult.StandardError, GenerateFailedAssertionMessage(testHostResult, callerMemberName: callerMemberName, callerFilePath: callerFilePath, callerLineNumber: callerLineNumber), StringComparison.Ordinal); public static void AssertOutputContainsSummary(this TestHostResult testHostResult, int failed, int passed, int skipped, bool? aborted = false, int? minimumNumberOfTests = null, [CallerMemberName] string? callerMemberName = null, [CallerFilePath] string? callerFilePath = null, [CallerLineNumber] int callerLineNumber = 0) { diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/MSBuildTests.Test.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/MSBuildTests.Test.cs index cd8eb9e5dd..8b857d9aba 100644 --- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/MSBuildTests.Test.cs +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/MSBuildTests.Test.cs @@ -119,7 +119,7 @@ public async Task RunUsingTestTargetWithNetfxMSBuild() { ["DOTNET_ROOT"] = Path.Combine(RootFinder.Find(), ".dotnet"), }); - StringAssert.Contains(commandLine.StandardOutput, "Tests succeeded"); + Assert.Contains("Tests succeeded", commandLine.StandardOutput); } [TestMethod] diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/ServerLoggingTests.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/ServerLoggingTests.cs index 16c19ea78a..8b161bc701 100644 --- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/ServerLoggingTests.cs +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/ServerLoggingTests.cs @@ -29,7 +29,7 @@ public async Task RunningInServerJsonRpcModeShouldHaveOutputDeviceLogsPushedToTe ResponseListener runListener = await jsonClient.RunTests(Guid.NewGuid(), runCollector.CollectNodeUpdates); await Task.WhenAll(discoveryListener.WaitCompletion(), runListener.WaitCompletion()); - Assert.IsFalse(logs.Count == 0, "Logs are empty"); + Assert.AreNotEqual(0, logs.Count, "Logs are empty"); string logsString = string.Join(Environment.NewLine, logs.Select(l => l.ToString())); string logPath = LogFilePathRegex().Match(logsString).Groups[1].Value; string port = PortRegex().Match(logsString).Groups[1].Value; diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/TrxTests.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/TrxTests.cs index 85bda001e8..90b89e9b90 100644 --- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/TrxTests.cs +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/TrxTests.cs @@ -57,7 +57,7 @@ public async Task Trx_WhenTestHostCrash_ErrorIsDisplayedInsideTheTrx(string tfm) string trxFile = Directory.GetFiles(testHost.DirectoryName, $"{fileName}.trx", SearchOption.AllDirectories).Single(); string trxContent = File.ReadAllText(trxFile); Assert.IsTrue(Regex.IsMatch(trxContent, @"Test host process pid: .* crashed\."), trxContent); - StringAssert.Contains(trxContent, """""", trxContent); + Assert.Contains("""""", trxContent, trxContent); } [DynamicData(nameof(TargetFrameworks.NetForDynamicData), typeof(TargetFrameworks))] @@ -73,14 +73,12 @@ public async Task Trx_WhenSkipTest_ItAppearsAsExpectedInsideTheTrx(string tfm) string trxFile = Directory.GetFiles(testHost.DirectoryName, $"{fileName}.trx", SearchOption.AllDirectories).Single(); string trxContent = File.ReadAllText(trxFile); - - // check if the tests have been added to Results, TestDefinitions, TestEntries and ResultSummary. - StringAssert.Contains(trxContent, @"""", trxContent); - StringAssert.Contains(trxContent, """""", trxContent); + Assert.Contains(@"""", trxContent, trxContent); + Assert.Contains("""""", trxContent, trxContent); } [DynamicData(nameof(TargetFrameworks.NetForDynamicData), typeof(TargetFrameworks))] diff --git a/test/UnitTests/MSTest.Engine.UnitTests/DynamicDataNameProviderTests.cs b/test/UnitTests/MSTest.Engine.UnitTests/DynamicDataNameProviderTests.cs index d7d29cca7a..f6c7004659 100644 --- a/test/UnitTests/MSTest.Engine.UnitTests/DynamicDataNameProviderTests.cs +++ b/test/UnitTests/MSTest.Engine.UnitTests/DynamicDataNameProviderTests.cs @@ -28,7 +28,7 @@ public void ParameterMismatchShowsDataInMessage() // you will get empty string while with the call you will get "null,a". // // check that this is still true: - ArgumentException exception = Assert.ThrowsException(() => DynamicDataNameProvider.GetUidFragment(["parameter1"], [null, "a"], 0)); + ArgumentException exception = Assert.ThrowsExactly(() => DynamicDataNameProvider.GetUidFragment(["parameter1"], [null, "a"], 0)); Assert.AreEqual("Parameter count mismatch. The provided data (null, a) have 2 items, but there are 1 parameters.", exception.Message); } } diff --git a/test/UnitTests/MSTest.SourceGeneration.UnitTests/TestUtilities/TestingFrameworkVerifier.cs b/test/UnitTests/MSTest.SourceGeneration.UnitTests/TestUtilities/TestingFrameworkVerifier.cs index 39c3e026ba..d21e00b691 100644 --- a/test/UnitTests/MSTest.SourceGeneration.UnitTests/TestUtilities/TestingFrameworkVerifier.cs +++ b/test/UnitTests/MSTest.SourceGeneration.UnitTests/TestUtilities/TestingFrameworkVerifier.cs @@ -20,7 +20,7 @@ internal TestingFrameworkVerifier(ImmutableStack context) public ImmutableStack Context { get; } - public void Empty(string collectionName, IEnumerable collection) => Assert.IsFalse(collection?.Any() == true, CreateMessage($"expected '{collectionName}' to be empty, contains '{collection?.Count()}' elements")); + public void Empty(string collectionName, IEnumerable collection) => Assert.AreNotEqual(true, collection?.Any(), CreateMessage($"expected '{collectionName}' to be empty, contains '{collection?.Count()}' elements")); public void Equal(T expected, T actual, string? message = null) { @@ -63,7 +63,7 @@ public void False([DoesNotReturnIf(true)] bool assert, string? message = null) public void LanguageIsSupported(string language) => Assert.IsFalse(language is not LanguageNames.CSharp and not LanguageNames.VisualBasic, CreateMessage($"Unsupported Language: '{language}'")); - public void NotEmpty(string collectionName, IEnumerable collection) => Assert.IsTrue(collection?.Any() == true, CreateMessage($"expected '{collectionName}' to be non-empty, contains")); + public void NotEmpty(string collectionName, IEnumerable collection) => Assert.IsNotEmpty(collection, CreateMessage($"expected '{collectionName}' to be non-empty, contains")); public IVerifier PushContext(string context) { @@ -108,9 +108,7 @@ private sealed class SequenceEqualEnumerableEqualityComparer : IEqualityCompa private readonly IEqualityComparer _itemEqualityComparer; public SequenceEqualEnumerableEqualityComparer(IEqualityComparer? itemEqualityComparer) - { - _itemEqualityComparer = itemEqualityComparer ?? EqualityComparer.Default; - } + => _itemEqualityComparer = itemEqualityComparer ?? EqualityComparer.Default; public bool Equals(IEnumerable? x, IEnumerable? y) => ReferenceEquals(x, y) diff --git a/test/UnitTests/Microsoft.Testing.Extensions.VSTestBridge.UnitTests/ObjectModel/ObjectModelConvertersTests.cs b/test/UnitTests/Microsoft.Testing.Extensions.VSTestBridge.UnitTests/ObjectModel/ObjectModelConvertersTests.cs index a2e8c73d20..0ee968124d 100644 --- a/test/UnitTests/Microsoft.Testing.Extensions.VSTestBridge.UnitTests/ObjectModel/ObjectModelConvertersTests.cs +++ b/test/UnitTests/Microsoft.Testing.Extensions.VSTestBridge.UnitTests/ObjectModel/ObjectModelConvertersTests.cs @@ -140,7 +140,7 @@ public void ToTestNode_WhenTestResultHasNoFullyQualifiedTypeAndTrxEnabled_Throws { TestResult testResult = new(new TestCase("test", new("executor://uri", UriKind.Absolute), "source.cs")); - string errorMessage = Assert.ThrowsException(() => testResult.ToTestNode(isTrxEnabled: true, useFullyQualifiedNameAsUid: false, null, new ConsoleCommandLineOptions(), ClientInfo)).Message; + string errorMessage = Assert.ThrowsExactly(() => testResult.ToTestNode(isTrxEnabled: true, useFullyQualifiedNameAsUid: false, null, new ConsoleCommandLineOptions(), ClientInfo)).Message; Assert.IsTrue(errorMessage.Contains("Unable to parse fully qualified type name from test case: ")); } @@ -267,7 +267,7 @@ public void ToTestNode_WhenTestResultHasMultipleStandardOutputMessages_TestNodeP var testNode = testResult.ToTestNode(isTrxEnabled: false, useFullyQualifiedNameAsUid: false, new NamedFeatureCapabilityWithVSTestProvider(), new ServerModeCommandLineOptions(), ClientInfo); StandardOutputProperty[] standardOutputProperties = [.. testNode.Properties.OfType()]; - Assert.IsTrue(standardOutputProperties.Length == 1); + Assert.AreEqual(1, standardOutputProperties.Length); Assert.AreEqual($"message1{Environment.NewLine}message2", standardOutputProperties[0].StandardOutput); } @@ -287,7 +287,7 @@ public void ToTestNode_WhenTestResultHasMultipleStandardErrorMessages_TestNodePr var testNode = testResult.ToTestNode(isTrxEnabled: false, useFullyQualifiedNameAsUid: false, new NamedFeatureCapabilityWithVSTestProvider(), new ServerModeCommandLineOptions(), ClientInfo); StandardErrorProperty[] standardErrorProperties = [.. testNode.Properties.OfType()]; - Assert.IsTrue(standardErrorProperties.Length == 1); + Assert.AreEqual(1, standardErrorProperties.Length); Assert.AreEqual($"message1{Environment.NewLine}message2", standardErrorProperties[0].StandardError); } diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/CommandLineHandlerTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/CommandLineHandlerTests.cs index ef9aaa6cca..ffbabc174b 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/CommandLineHandlerTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/CommandLineHandlerTests.cs @@ -38,8 +38,8 @@ public async Task ParseAndValidateAsync_InvalidCommandLineArguments_ReturnsFalse // Assert Assert.IsFalse(result.IsValid); - StringAssert.Contains(result.ErrorMessage, "Invalid command line arguments:"); - StringAssert.Contains(result.ErrorMessage, "Unexpected argument 'a'"); + Assert.Contains("Invalid command line arguments:", result.ErrorMessage); + Assert.Contains("Unexpected argument 'a'", result.ErrorMessage); } [TestMethod] @@ -75,7 +75,7 @@ public async Task ParseAndValidateAsync_DuplicateOption_ReturnsFalse() // Assert Assert.IsFalse(result.IsValid); - StringAssert.Contains(result.ErrorMessage, "Option '--userOption' is declared by multiple extensions: 'Microsoft Testing Platform command line provider', 'Microsoft Testing Platform command line provider'"); + Assert.Contains("Option '--userOption' is declared by multiple extensions: 'Microsoft Testing Platform command line provider', 'Microsoft Testing Platform command line provider'", result.ErrorMessage); } [TestMethod] diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Configuration/ConfigurationExtensionsTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Configuration/ConfigurationExtensionsTests.cs index 49d2df67cb..104bff4626 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Configuration/ConfigurationExtensionsTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Configuration/ConfigurationExtensionsTests.cs @@ -42,6 +42,6 @@ public void ConfigurationExtensions_TestedMethod_ThrowsArgumentNullException(str .Setup(configuration => configuration[key]) .Returns(value: null); - Assert.ThrowsException(() => GetActualValueFromConfiguration(configuration.Object, key)); + Assert.ThrowsExactly(() => GetActualValueFromConfiguration(configuration.Object, key)); } } diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/IPCTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/IPCTests.cs index e36d719839..a70e296401 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/IPCTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/IPCTests.cs @@ -185,7 +185,7 @@ public async Task ConnectionNamedPipeServer_MultipleConnection_Succeeds() _testContext.CancellationTokenSource.Token)); } - IOException exception = Assert.ThrowsException(() => + IOException exception = Assert.ThrowsExactly(() => new NamedPipeServer( pipeNameDescription, async _ => await Task.FromResult(VoidResponse.CachedInstance), @@ -194,7 +194,7 @@ public async Task ConnectionNamedPipeServer_MultipleConnection_Succeeds() new SystemTask(), maxNumberOfServerInstances: 3, _testContext.CancellationTokenSource.Token)); - StringAssert.Contains(exception.Message, "All pipe instances are busy."); + Assert.Contains("All pipe instances are busy.", exception.Message); List waitConnectionTask = []; int connectionCompleted = 0; diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Logging/FileLoggerTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Logging/FileLoggerTests.cs index 92aaa59645..1919fe223a 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Logging/FileLoggerTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Logging/FileLoggerTests.cs @@ -110,7 +110,7 @@ public void FileLogger_NullFileSyncFlush_FileStreamCreationThrows() .Throws() .Returns(_mockStream.Object); - Assert.ThrowsException(() => _ = new FileLogger( + Assert.ThrowsExactly(() => _ = new FileLogger( new(LogFolder, LogPrefix, fileName: null, syncFlush: true), LogLevel.Trace, _mockClock.Object, diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Messages/AsynchronousMessageBusTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Messages/AsynchronousMessageBusTests.cs index af1b5c2ab0..dd45c96de9 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Messages/AsynchronousMessageBusTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Messages/AsynchronousMessageBusTests.cs @@ -56,7 +56,7 @@ public async Task DrainDataAsync_Loop_ShouldFail() } catch (InvalidOperationException ex) { - StringAssert.Contains(ex.Message, "Publisher/Consumer loop detected during the drain after"); + Assert.Contains("Publisher/Consumer loop detected during the drain after", ex.Message); } // Prevent loop to continue diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Messages/PropertyBagTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Messages/PropertyBagTests.cs index 43805d2171..cd65c20d4e 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Messages/PropertyBagTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Messages/PropertyBagTests.cs @@ -23,8 +23,8 @@ public void Ctors_CorrectlyInit() [TestMethod] public void Ctors_With_WrongInit_ShouldFail() { - Assert.ThrowsException(() => _ = new PropertyBag([new DummyProperty(), PassedTestNodeStateProperty.CachedInstance, PassedTestNodeStateProperty.CachedInstance])); - Assert.ThrowsException(() => _ = new PropertyBag(new IProperty[] { new DummyProperty(), PassedTestNodeStateProperty.CachedInstance, PassedTestNodeStateProperty.CachedInstance }.AsEnumerable())); + Assert.ThrowsExactly(() => _ = new PropertyBag([new DummyProperty(), PassedTestNodeStateProperty.CachedInstance, PassedTestNodeStateProperty.CachedInstance])); + Assert.ThrowsExactly(() => _ = new PropertyBag(new IProperty[] { new DummyProperty(), PassedTestNodeStateProperty.CachedInstance, PassedTestNodeStateProperty.CachedInstance }.AsEnumerable())); } [TestMethod] @@ -55,7 +55,7 @@ public void Add_Of_TestNodeStateProperty_More_Than_One_Time_Fail() { PropertyBag property = new(); property.Add(PassedTestNodeStateProperty.CachedInstance); - Assert.ThrowsException(() => property.Add(PassedTestNodeStateProperty.CachedInstance)); + Assert.ThrowsExactly(() => property.Add(PassedTestNodeStateProperty.CachedInstance)); } [TestMethod] @@ -64,7 +64,7 @@ public void Add_Same_Instance_More_Times_Fail() PropertyBag property = new(); DummyProperty dummyProperty = new(); property.Add(dummyProperty); - Assert.ThrowsException(() => property.Add(dummyProperty)); + Assert.ThrowsExactly(() => property.Add(dummyProperty)); } [TestMethod] @@ -92,7 +92,7 @@ public void SingleOrDefault_Should_Return_CorrectObject() Assert.IsNull(property.SingleOrDefault()); property.Add(new DummyProperty()); - Assert.ThrowsException(property.SingleOrDefault); + Assert.ThrowsExactly(property.SingleOrDefault); } [TestMethod] @@ -105,10 +105,10 @@ public void Single_Should_Return_CorrectObject() Assert.AreEqual(PassedTestNodeStateProperty.CachedInstance, property.Single()); Assert.AreEqual(prop, property.Single()); - Assert.ThrowsException(property.Single); + Assert.ThrowsExactly(property.Single); property.Add(new DummyProperty()); - Assert.ThrowsException(property.Single); + Assert.ThrowsExactly(property.Single); } [TestMethod] @@ -159,13 +159,13 @@ public void EmptyProperties_Should_NotFail() Assert.AreEqual(0, property.Count); Assert.IsFalse(property.Any()); Assert.IsNull(property.SingleOrDefault()); - Assert.ThrowsException(property.Single); + Assert.ThrowsExactly(property.Single); Assert.AreEqual(0, property.OfType().Length); Assert.AreEqual(0, property.AsEnumerable().Count()); foreach (IProperty item in property) { - Assert.IsTrue(false, "no item expected"); + Assert.Fail("no item expected"); } } diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Messages/TestNodeUidTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Messages/TestNodeUidTests.cs index 6a57d3b664..794de47f8c 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Messages/TestNodeUidTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Messages/TestNodeUidTests.cs @@ -27,13 +27,13 @@ public void TestNodeUid_NullValue_ShouldFail() // Assert.Throw(() => { TestNodeUid testNode = null!; }); // Implicit conversion from a null, empty or whitespace string should throw. - Assert.ThrowsException(() => { TestNodeUid testNode = (string)null!; }); - Assert.ThrowsException(() => { TestNodeUid testNode = string.Empty; }); - Assert.ThrowsException(() => { TestNodeUid testNode = " "; }); + Assert.ThrowsExactly(() => { TestNodeUid testNode = (string)null!; }); + Assert.ThrowsExactly(() => { TestNodeUid testNode = string.Empty; }); + Assert.ThrowsExactly(() => { TestNodeUid testNode = " "; }); // Providing null, empty, or whitespace id should throw. - Assert.ThrowsException(() => { TestNodeUid testNode = new(null!); }); - Assert.ThrowsException(() => { TestNodeUid testNode = new(string.Empty); }); - Assert.ThrowsException(() => { TestNodeUid testNode = new(" "); }); + Assert.ThrowsExactly(() => { TestNodeUid testNode = new(null!); }); + Assert.ThrowsExactly(() => { TestNodeUid testNode = new(string.Empty); }); + Assert.ThrowsExactly(() => { TestNodeUid testNode = new(" "); }); } } diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/OutputDevice/Terminal/TerminalTestReporterTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/OutputDevice/Terminal/TerminalTestReporterTests.cs index f490b1474a..70a905d8b9 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/OutputDevice/Terminal/TerminalTestReporterTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/OutputDevice/Terminal/TerminalTestReporterTests.cs @@ -27,11 +27,11 @@ public void AppendStackFrameFormatsStackTraceLineCorrectly() TerminalTestReporter.AppendStackFrame(terminal, firstStackTraceLine); #if NETCOREAPP - StringAssert.Contains(terminal.Output, " at Microsoft.Testing.Platform.UnitTests.TerminalTestReporterTests.AppendStackFrameFormatsStackTraceLineCorrectly() in "); + Assert.Contains(" at Microsoft.Testing.Platform.UnitTests.TerminalTestReporterTests.AppendStackFrameFormatsStackTraceLineCorrectly() in ", terminal.Output); #else // This is caused by us using portable symbols, and .NET Framework 4.6.2, once we update to .NET Framework 4.7.2 the path to file will be included in the stacktrace and this won't be necessary. // See first point here: https://learn.microsoft.com/en-us/dotnet/core/diagnostics/symbols#support-for-portable-pdbs - StringAssert.Contains(terminal.Output, " at Microsoft.Testing.Platform.UnitTests.TerminalTestReporterTests.AppendStackFrameFormatsStackTraceLineCorrectly()"); + Assert.Contains(" at Microsoft.Testing.Platform.UnitTests.TerminalTestReporterTests.AppendStackFrameFormatsStackTraceLineCorrectly()", terminal.Output); #endif // Line number without the respective file Assert.IsFalse(terminal.Output.Contains(" :0")); diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Requests/TreeNodeFilterTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Requests/TreeNodeFilterTests.cs index 59862917ab..15b2b1794f 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Requests/TreeNodeFilterTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Requests/TreeNodeFilterTests.cs @@ -26,10 +26,10 @@ public void MatchAllFilter_MatchesSubpaths() } [TestMethod] - public void MatchAllFilter_Invalid() => Assert.ThrowsException(() => _ = new TreeNodeFilter("/A(&B)")); + public void MatchAllFilter_Invalid() => Assert.ThrowsExactly(() => _ = new TreeNodeFilter("/A(&B)")); [TestMethod] - public void MatchAllFilter_DoNotAllowInMiddleOfFilter() => Assert.ThrowsException(() => _ = new TreeNodeFilter("/**/Path")); + public void MatchAllFilter_DoNotAllowInMiddleOfFilter() => Assert.ThrowsExactly(() => _ = new TreeNodeFilter("/**/Path")); [TestMethod] public void MatchWildcard_MatchesSubstrings() @@ -59,7 +59,7 @@ public void EscapeSequences_SupportsParentheses() } [TestMethod] - public void EscapeSequences_ThrowsIfLastCharIsAnEscapeChar() => Assert.ThrowsException(() => _ = new TreeNodeFilter("/*.\\(UnitTests\\)\\")); + public void EscapeSequences_ThrowsIfLastCharIsAnEscapeChar() => Assert.ThrowsExactly(() => _ = new TreeNodeFilter("/*.\\(UnitTests\\)\\")); [TestMethod] public void OrExpression_WorksForLiteralStrings() @@ -94,7 +94,7 @@ public void Parentheses_EnsuresOrdering() [TestMethod] public void Parenthesis_DisallowSeparatorInside() - => Assert.ThrowsException(() => new TreeNodeFilter("/(A/B)")); + => Assert.ThrowsExactly(() => new TreeNodeFilter("/(A/B)")); [TestMethod] public void Parameters_PropertyCheck() @@ -143,19 +143,19 @@ public void Parameters_NegatedPropertyCheckCombinedWithOr() [TestMethod] public void Parameters_DisallowAtStart() - => Assert.ThrowsException(() => _ = new TreeNodeFilter("/[Tag=Fast]")); + => Assert.ThrowsExactly(() => _ = new TreeNodeFilter("/[Tag=Fast]")); [TestMethod] public void Parameters_DisallowEmpty() - => Assert.ThrowsException(() => _ = new TreeNodeFilter("/Path[]")); + => Assert.ThrowsExactly(() => _ = new TreeNodeFilter("/Path[]")); [TestMethod] public void Parameters_DisallowMultiple() - => Assert.ThrowsException(() => _ = new TreeNodeFilter("/Path[Prop=2][Prop=B]")); + => Assert.ThrowsExactly(() => _ = new TreeNodeFilter("/Path[Prop=2][Prop=B]")); [TestMethod] public void Parameters_DisallowNested() - => Assert.ThrowsException(() => _ = new TreeNodeFilter("/Path[X=[Y=1]]")); + => Assert.ThrowsExactly(() => _ = new TreeNodeFilter("/Path[X=[Y=1]]")); [DataRow("/A/B", "/A/B", true)] [DataRow("/A/B", "/A%2FB", false)] @@ -229,5 +229,5 @@ public void MatchAllFilterSubpathWithPropertyExpression_WithTestMetadataProperty } [TestMethod] - public void MatchAllFilterWithPropertyExpression_DoNotAllowInMiddleOfFilter() => Assert.ThrowsException(() => _ = new TreeNodeFilter("/**/Path[A=B]")); + public void MatchAllFilterWithPropertyExpression_DoNotAllowInMiddleOfFilter() => Assert.ThrowsExactly(() => _ = new TreeNodeFilter("/**/Path[A=B]")); } diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Services/ServiceProviderTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Services/ServiceProviderTests.cs index 6ebf2a49b4..aff2e76fe8 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Services/ServiceProviderTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Services/ServiceProviderTests.cs @@ -95,11 +95,11 @@ public void Clone_WithFilter_Succeeded() [TestMethod] public void AddService_TestFramework_ShouldFail() - => Assert.ThrowsException(() => _serviceProvider.AddService(new TestFramework())); + => Assert.ThrowsExactly(() => _serviceProvider.AddService(new TestFramework())); [TestMethod] public void TryAddService_TestFramework_ShouldFail() - => Assert.ThrowsException(() => _serviceProvider.TryAddService(new TestFramework())); + => Assert.ThrowsExactly(() => _serviceProvider.TryAddService(new TestFramework())); [TestMethod] public void AddService_TestFramework_ShouldNotFail() @@ -120,7 +120,7 @@ public void AddService_SameInstance_ShouldFail() { TestHostProcessLifetimeHandler instance = new(); _serviceProvider.AddService(instance); - _ = Assert.ThrowsException(() => _serviceProvider.AddService(instance)); + _ = Assert.ThrowsExactly(() => _serviceProvider.AddService(instance)); } [TestMethod] @@ -136,7 +136,7 @@ public void AddServices_SameInstance_ShouldFail() { TestHostProcessLifetimeHandler instance = new(); _serviceProvider.AddServices([instance]); - _ = Assert.ThrowsException(() => _serviceProvider.AddServices([instance])); + _ = Assert.ThrowsExactly(() => _serviceProvider.AddServices([instance])); } [TestMethod] diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/TestApplicationBuilderTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/TestApplicationBuilderTests.cs index b59d31106a..316212ee06 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/TestApplicationBuilderTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/TestApplicationBuilderTests.cs @@ -32,7 +32,7 @@ public async Task TestApplicationLifecycleCallbacks_DuplicatedId_ShouldFail() TestHostManager testHostManager = new(); testHostManager.AddTestHostApplicationLifetime(_ => new ApplicationLifecycleCallbacks("duplicatedId")); testHostManager.AddTestHostApplicationLifetime(_ => new ApplicationLifecycleCallbacks("duplicatedId")); - InvalidOperationException invalidOperationException = await Assert.ThrowsExceptionAsync(() => testHostManager.BuildTestApplicationLifecycleCallbackAsync(_serviceProvider)); + InvalidOperationException invalidOperationException = await Assert.ThrowsExactlyAsync(() => testHostManager.BuildTestApplicationLifecycleCallbackAsync(_serviceProvider)); Assert.IsTrue(invalidOperationException.Message.Contains("duplicatedId") && invalidOperationException.Message.Contains(typeof(ApplicationLifecycleCallbacks).ToString())); } @@ -42,7 +42,7 @@ public async Task DataConsumer_DuplicatedId_ShouldFail() TestHostManager testHostManager = new(); testHostManager.AddDataConsumer(_ => new Consumer("duplicatedId")); testHostManager.AddDataConsumer(_ => new Consumer("duplicatedId")); - InvalidOperationException invalidOperationException = await Assert.ThrowsExceptionAsync(() => testHostManager.BuildDataConsumersAsync(_serviceProvider, [])); + InvalidOperationException invalidOperationException = await Assert.ThrowsExactlyAsync(() => testHostManager.BuildDataConsumersAsync(_serviceProvider, [])); Assert.IsTrue(invalidOperationException.Message.Contains("duplicatedId") && invalidOperationException.Message.Contains(typeof(Consumer).ToString())); } @@ -53,7 +53,7 @@ public async Task DataConsumer_DuplicatedIdWithCompositeFactory_ShouldFail() CompositeExtensionFactory compositeExtensionFactory = new(() => new Consumer("duplicatedId")); testHostManager.AddDataConsumer(_ => new Consumer("duplicatedId")); testHostManager.AddDataConsumer(compositeExtensionFactory); - InvalidOperationException invalidOperationException = await Assert.ThrowsExceptionAsync(() => testHostManager.BuildDataConsumersAsync(_serviceProvider, [])); + InvalidOperationException invalidOperationException = await Assert.ThrowsExactlyAsync(() => testHostManager.BuildDataConsumersAsync(_serviceProvider, [])); Assert.IsTrue(invalidOperationException.Message.Contains("duplicatedId") && invalidOperationException.Message.Contains(typeof(Consumer).ToString())); } @@ -63,7 +63,7 @@ public async Task TestSessionLifetimeHandle_DuplicatedId_ShouldFail() TestHostManager testHostManager = new(); testHostManager.AddTestSessionLifetimeHandle(_ => new TestSessionLifetimeHandler("duplicatedId")); testHostManager.AddTestSessionLifetimeHandle(_ => new TestSessionLifetimeHandler("duplicatedId")); - InvalidOperationException invalidOperationException = await Assert.ThrowsExceptionAsync(() => testHostManager.BuildTestSessionLifetimeHandleAsync(_serviceProvider, [])); + InvalidOperationException invalidOperationException = await Assert.ThrowsExactlyAsync(() => testHostManager.BuildTestSessionLifetimeHandleAsync(_serviceProvider, [])); Assert.IsTrue(invalidOperationException.Message.Contains("duplicatedId") && invalidOperationException.Message.Contains(typeof(TestSessionLifetimeHandler).ToString())); } @@ -74,7 +74,7 @@ public async Task TestSessionLifetimeHandle_DuplicatedIdWithCompositeFactory_Sho CompositeExtensionFactory compositeExtensionFactory = new(() => new TestSessionLifetimeHandler("duplicatedId")); testHostManager.AddTestSessionLifetimeHandle(_ => new TestSessionLifetimeHandler("duplicatedId")); testHostManager.AddTestSessionLifetimeHandle(compositeExtensionFactory); - InvalidOperationException invalidOperationException = await Assert.ThrowsExceptionAsync(() => testHostManager.BuildTestSessionLifetimeHandleAsync(_serviceProvider, [])); + InvalidOperationException invalidOperationException = await Assert.ThrowsExactlyAsync(() => testHostManager.BuildTestSessionLifetimeHandleAsync(_serviceProvider, [])); Assert.IsTrue(invalidOperationException.Message.Contains("duplicatedId") && invalidOperationException.Message.Contains(typeof(TestSessionLifetimeHandler).ToString())); } @@ -105,7 +105,7 @@ public async Task TestHostControllerEnvironmentVariableProvider_DuplicatedId_Sho TestHostControllersManager testHostControllerManager = new(); testHostControllerManager.AddEnvironmentVariableProvider(_ => new TestHostEnvironmentVariableProvider("duplicatedId")); testHostControllerManager.AddEnvironmentVariableProvider(_ => new TestHostEnvironmentVariableProvider("duplicatedId")); - InvalidOperationException invalidOperationException = await Assert.ThrowsExceptionAsync(() => testHostControllerManager.BuildAsync(_serviceProvider)); + InvalidOperationException invalidOperationException = await Assert.ThrowsExactlyAsync(() => testHostControllerManager.BuildAsync(_serviceProvider)); Assert.IsTrue(invalidOperationException.Message.Contains("duplicatedId") && invalidOperationException.Message.Contains(typeof(TestHostEnvironmentVariableProvider).ToString())); } @@ -116,7 +116,7 @@ public async Task TestHostControllerEnvironmentVariableProvider_DuplicatedIdWith CompositeExtensionFactory compositeExtensionFactory = new(() => new TestHostEnvironmentVariableProvider("duplicatedId")); testHostControllerManager.AddEnvironmentVariableProvider(_ => new TestHostEnvironmentVariableProvider("duplicatedId")); testHostControllerManager.AddEnvironmentVariableProvider(compositeExtensionFactory); - InvalidOperationException invalidOperationException = await Assert.ThrowsExceptionAsync(() => testHostControllerManager.BuildAsync(_serviceProvider)); + InvalidOperationException invalidOperationException = await Assert.ThrowsExactlyAsync(() => testHostControllerManager.BuildAsync(_serviceProvider)); Assert.IsTrue(invalidOperationException.Message.Contains("duplicatedId") && invalidOperationException.Message.Contains(typeof(TestHostEnvironmentVariableProvider).ToString())); } @@ -126,7 +126,7 @@ public async Task TestHostControllerProcessLifetimeHandler_DuplicatedId_ShouldFa TestHostControllersManager testHostControllerManager = new(); testHostControllerManager.AddProcessLifetimeHandler(_ => new TestHostProcessLifetimeHandler("duplicatedId")); testHostControllerManager.AddProcessLifetimeHandler(_ => new TestHostProcessLifetimeHandler("duplicatedId")); - InvalidOperationException invalidOperationException = await Assert.ThrowsExceptionAsync(() => testHostControllerManager.BuildAsync(_serviceProvider)); + InvalidOperationException invalidOperationException = await Assert.ThrowsExactlyAsync(() => testHostControllerManager.BuildAsync(_serviceProvider)); Assert.IsTrue(invalidOperationException.Message.Contains("duplicatedId") && invalidOperationException.Message.Contains(typeof(TestHostProcessLifetimeHandler).ToString())); } @@ -137,7 +137,7 @@ public async Task TestHostControllerProcessLifetimeHandler_DuplicatedIdWithCompo CompositeExtensionFactory compositeExtensionFactory = new(() => new TestHostProcessLifetimeHandler("duplicatedId")); testHostControllerManager.AddProcessLifetimeHandler(_ => new TestHostProcessLifetimeHandler("duplicatedId")); testHostControllerManager.AddProcessLifetimeHandler(compositeExtensionFactory); - InvalidOperationException invalidOperationException = await Assert.ThrowsExceptionAsync(() => testHostControllerManager.BuildAsync(_serviceProvider)); + InvalidOperationException invalidOperationException = await Assert.ThrowsExactlyAsync(() => testHostControllerManager.BuildAsync(_serviceProvider)); Assert.IsTrue(invalidOperationException.Message.Contains("duplicatedId") && invalidOperationException.Message.Contains(typeof(TestHostProcessLifetimeHandler).ToString())); } @@ -171,7 +171,7 @@ public void ComposeFactory_InvalidComposition_ShouldFail(bool withParameter) withParameter ? new CompositeExtensionFactory(sp => new InvalidComposition(sp)) : new CompositeExtensionFactory(() => new InvalidComposition()); - InvalidOperationException invalidOperationException = Assert.ThrowsException(() => ((ICompositeExtensionFactory)compositeExtensionFactory).GetInstance()); + InvalidOperationException invalidOperationException = Assert.ThrowsExactly(() => ((ICompositeExtensionFactory)compositeExtensionFactory).GetInstance()); Assert.AreEqual(CompositeExtensionFactory.ValidateCompositionErrorMessage, invalidOperationException.Message); } From c95cdd652f42eeed95402c13baeb1656c2c5021a Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Wed, 16 Jul 2025 13:09:03 +0000 Subject: [PATCH 241/541] [main] Update dependencies from microsoft/testfx (#6069) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: dotnet-maestro[bot] Co-authored-by: Amaury Levé --- eng/Version.Details.xml | 8 ++++---- eng/Versions.props | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index f1b08fb4f8..3d366a9217 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -17,13 +17,13 @@ https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage 06325faa0d16bac193af8d51026f03208034880d - + https://github.com/microsoft/testfx - 0bc914379dd1521f8b0c75f860821e6b4ac5f547 + 6dd364574cebb0440fb6e1b84943d841e7e3cbba - + https://github.com/microsoft/testfx - 0bc914379dd1521f8b0c75f860821e6b4ac5f547 + 6dd364574cebb0440fb6e1b84943d841e7e3cbba diff --git a/eng/Versions.props b/eng/Versions.props index 4f757fd06a..0fb7898ba3 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -9,7 +9,7 @@ 10.0.0-beta.25358.3 18.0.0-preview.25365.3 - 3.10.0-preview.25365.10 - 1.8.0-preview.25365.10 + 3.10.0-preview.25366.1 + 1.8.0-preview.25366.1 From ddcb4dba6304a7b3288583f08486f31cc8d0d4b3 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Wed, 16 Jul 2025 16:10:12 +0200 Subject: [PATCH 242/541] Publish TestStep.binlog in CI (#6067) --- azure-pipelines.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/azure-pipelines.yml b/azure-pipelines.yml index 956517d250..e592a7c4b7 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -115,7 +115,7 @@ stages: # Because the build step is using -ci flag, restore is done in a local .packages directory. # We need to pass NUGET_PACKAGES so that when dotnet test is doing evaluation phase on the projects, it can resolve .props/.targets from packages and import them. # Otherwise, props/targets are not imported. It's important that they are imported so that IsTestingPlatformApplication ends up being set. - - script: dotnet test -c $(_BuildConfig) --no-build -bl:$(BUILD.SOURCESDIRECTORY)\artifacts\log\$(_BuildConfig)\TestStep.binlog --no-progress + - script: dotnet test -c $(_BuildConfig) --no-build -bl:$(BUILD.SOURCESDIRECTORY)\artifacts\TestResults\$(_BuildConfig)\TestStep.binlog --no-progress name: Test displayName: Test env: @@ -195,7 +195,7 @@ stages: # Because the build step is using -ci flag, restore is done in a local .packages directory. # We need to pass NUGET_PACKAGES so that when dotnet test is doing evaluation phase on the projects, it can resolve .props/.targets from packages and import them. # Otherwise, props/targets are not imported. It's important that they are imported so that IsTestingPlatformApplication ends up being set. - - script: dotnet test --solution NonWindowsTests.slnf -c $(_BuildConfig) --no-build -bl:$(BUILD.SOURCESDIRECTORY)\artifacts\log\$(_BuildConfig)\TestStep.binlog --no-progress + - script: dotnet test --solution NonWindowsTests.slnf -c $(_BuildConfig) --no-build -bl:$(BUILD.SOURCESDIRECTORY)\artifacts\TestResults\$(_BuildConfig)\TestStep.binlog --no-progress name: Test displayName: Test env: @@ -261,7 +261,7 @@ stages: # Because the build step is using -ci flag, restore is done in a local .packages directory. # We need to pass NUGET_PACKAGES so that when dotnet test is doing evaluation phase on the projects, it can resolve .props/.targets from packages and import them. # Otherwise, props/targets are not imported. It's important that they are imported so that IsTestingPlatformApplication ends up being set. - - script: dotnet test --solution NonWindowsTests.slnf -c $(_BuildConfig) --no-build -bl:$(BUILD.SOURCESDIRECTORY)\artifacts\log\$(_BuildConfig)\TestStep.binlog --no-progress + - script: dotnet test --solution NonWindowsTests.slnf -c $(_BuildConfig) --no-build -bl:$(BUILD.SOURCESDIRECTORY)\artifacts\TestResults\$(_BuildConfig)\TestStep.binlog --no-progress name: Test displayName: Test env: From dc1658bd41cccc2edd7403706655f5d92f7f8105 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Wed, 16 Jul 2025 22:44:19 +0200 Subject: [PATCH 243/541] Further cleanup to terminal test reporter (#6072) --- .../OutputDevice/Terminal/AnsiTerminal.cs | 4 ++-- .../OutputDevice/Terminal/TerminalTestReporter.cs | 4 ++-- .../OutputDevice/Terminal/TerminalTestReporterOptions.cs | 5 ----- .../OutputDevice/Terminal/TestRunArtifact.cs | 2 +- .../OutputDevice/TerminalOutputDevice.cs | 1 - 5 files changed, 5 insertions(+), 11 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/AnsiTerminal.cs b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/AnsiTerminal.cs index abc28c3ea2..20ffd4af20 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/AnsiTerminal.cs +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/AnsiTerminal.cs @@ -43,10 +43,10 @@ internal sealed class AnsiTerminal : ITerminal private bool _isBatching; private AnsiTerminalTestProgressFrame _currentFrame = new(0, 0); - public AnsiTerminal(IConsole console, string? baseDirectory) + public AnsiTerminal(IConsole console) { _console = console; - _baseDirectory = baseDirectory ?? Directory.GetCurrentDirectory(); + _baseDirectory = Directory.GetCurrentDirectory(); // Output ansi code to get spinner on top of a terminal, to indicate in-progress task. // https://github.com/dotnet/msbuild/issues/8958: iTerm2 treats ;9 code to post a notification instead, so disable progress reporting on Mac. diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporter.cs b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporter.cs index 024f1f5c0d..d1d0c0cdf9 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporter.cs +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporter.cs @@ -97,7 +97,7 @@ public TerminalTestReporter(string assembly, string? targetFramework, string? ar (bool consoleAcceptsAnsiCodes, bool _, uint? originalConsoleMode) = NativeMethods.QueryIsScreenAndTryEnableAnsiColorCodes(); _originalConsoleMode = originalConsoleMode; terminalWithProgress = consoleAcceptsAnsiCodes || _options.ForceAnsi is true - ? new TestProgressStateAwareTerminal(new AnsiTerminal(console, _options.BaseDirectory), showProgress, writeProgressImmediatelyAfterOutput: true, updateEvery: ansiUpdateCadenceInMs) + ? new TestProgressStateAwareTerminal(new AnsiTerminal(console), showProgress, writeProgressImmediatelyAfterOutput: true, updateEvery: ansiUpdateCadenceInMs) : new TestProgressStateAwareTerminal(new NonAnsiTerminal(console), showProgress, writeProgressImmediatelyAfterOutput: false, updateEvery: nonAnsiUpdateCadenceInMs); } } @@ -657,7 +657,7 @@ private static void AppendLongDuration(ITerminal terminal, TimeSpan duration, bo public void Dispose() => _terminalWithProgress.Dispose(); public void ArtifactAdded(bool outOfProcess, string? testName, string path) - => _artifacts.Add(new TestRunArtifact(outOfProcess, _assembly, _targetFramework, _architecture, testName, path)); + => _artifacts.Add(new TestRunArtifact(outOfProcess, testName, path)); /// /// Let the user know that cancellation was triggered. diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporterOptions.cs b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporterOptions.cs index 30aee81d59..b738158389 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporterOptions.cs +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporterOptions.cs @@ -5,11 +5,6 @@ namespace Microsoft.Testing.Platform.OutputDevice.Terminal; internal sealed class TerminalTestReporterOptions { - /// - /// Gets path to which all other paths in output should be relative. - /// - public string? BaseDirectory { get; init; } - /// /// Gets a value indicating whether we should show passed tests. /// diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TestRunArtifact.cs b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TestRunArtifact.cs index 5ab5c2172d..936a213f70 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TestRunArtifact.cs +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TestRunArtifact.cs @@ -6,4 +6,4 @@ namespace Microsoft.Testing.Platform.OutputDevice.Terminal; /// /// An artifact / attachment that was reported during run. /// -internal sealed record TestRunArtifact(bool OutOfProcess, string? Assembly, string? TargetFramework, string? Architecture, string? TestName, string Path); +internal sealed record TestRunArtifact(bool OutOfProcess, string? TestName, string Path); diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/TerminalOutputDevice.cs b/src/Platform/Microsoft.Testing.Platform/OutputDevice/TerminalOutputDevice.cs index eb751d88ee..f57b254ec6 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/TerminalOutputDevice.cs +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/TerminalOutputDevice.cs @@ -153,7 +153,6 @@ await _policiesService.RegisterOnAbortCallbackAsync( // This is single exe run, don't show all the details of assemblies and their summaries. _terminalTestReporter = new TerminalTestReporter(_assemblyName, _targetFramework, _shortArchitecture, _console, new() { - BaseDirectory = null, ShowPassedTests = showPassed, MinimumExpectedTests = PlatformCommandLineProvider.GetMinimumExpectedTests(_commandLineOptions), UseAnsi = !noAnsi, From 6b74365db8affe01cad0ca4ecd50e0ee944e25c6 Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Thu, 17 Jul 2025 17:04:11 +1000 Subject: [PATCH 244/541] fix Coxtext typo (#6051) --- .../Execution/TestClassInfoTests.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestClassInfoTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestClassInfoTests.cs index a20fcdeddf..9242df3d9f 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestClassInfoTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestClassInfoTests.cs @@ -16,9 +16,9 @@ namespace Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Execution; public class TestClassInfoTests : TestContainer { - private sealed class TestTestCoxtextImpl : ITestContext + private sealed class TestTestContextImpl : ITestContext { - public TestTestCoxtextImpl(TestContext testContext) + public TestTestContextImpl(TestContext testContext) => Context = testContext; public TestContext Context { get; } @@ -450,7 +450,7 @@ private TestResult GetResultOrRunClassInitialize() => GetResultOrRunClassInitialize(_testContext); private TestResult GetResultOrRunClassInitialize(TestContext? testContext) - => _testClassInfo.GetResultOrRunClassInitialize(new TestTestCoxtextImpl(testContext!), string.Empty, string.Empty, string.Empty, string.Empty); + => _testClassInfo.GetResultOrRunClassInitialize(new TestTestContextImpl(testContext!), string.Empty, string.Empty, string.Empty, string.Empty); #endregion #region Run Class Cleanup tests From cdcb707573792426f2c74e84903b905866a3ca01 Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Thu, 17 Jul 2025 09:59:17 +0200 Subject: [PATCH 245/541] [main] Update dependencies from microsoft/testfx (#6074) Co-authored-by: dotnet-maestro[bot] --- eng/Version.Details.xml | 8 ++++---- eng/Versions.props | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index 3d366a9217..19cabe236a 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -17,13 +17,13 @@ https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage 06325faa0d16bac193af8d51026f03208034880d - + https://github.com/microsoft/testfx - 6dd364574cebb0440fb6e1b84943d841e7e3cbba + 689830b314494a93b276672b70e35629d38ce639 - + https://github.com/microsoft/testfx - 6dd364574cebb0440fb6e1b84943d841e7e3cbba + 689830b314494a93b276672b70e35629d38ce639 diff --git a/eng/Versions.props b/eng/Versions.props index 0fb7898ba3..4adc4ce99e 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -9,7 +9,7 @@ 10.0.0-beta.25358.3 18.0.0-preview.25365.3 - 3.10.0-preview.25366.1 - 1.8.0-preview.25366.1 + 3.10.0-preview.25366.15 + 1.8.0-preview.25366.15 From 14332cbe19c2eddbddead4f57cf245a2769fedb2 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Thu, 17 Jul 2025 10:08:44 +0200 Subject: [PATCH 246/541] [MTP] Few renames around "test host" terminology (#5771) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Amaury Levé --- .../Builder/TestApplication.cs | 20 ++++++++----------- .../Builder/TestApplicationBuilder.cs | 8 ++++---- .../InformativeCommandLineTestHost.cs | 2 +- .../Hosts/CommonTestHost.cs | 8 ++++++-- .../Hosts/ConsoleTestHost.cs | 2 +- .../Microsoft.Testing.Platform/Hosts/IHost.cs | 14 +++++++++++++ .../Hosts/ITestHost.cs | 9 --------- .../Hosts/ITestHostBuilder.cs | 2 +- .../Hosts/ServerTestHost.cs | 2 +- .../Hosts/TestHostBuilder.cs | 14 ++++++------- .../Hosts/TestHostControlledHost.cs | 10 +++++----- .../Hosts/TestHostControllersTestHost.cs | 2 +- .../Hosts/TestHostOchestratorHost.cs | 2 +- .../Hosts/ToolsTestHost.cs | 6 +++--- 14 files changed, 53 insertions(+), 48 deletions(-) create mode 100644 src/Platform/Microsoft.Testing.Platform/Hosts/IHost.cs delete mode 100644 src/Platform/Microsoft.Testing.Platform/Hosts/ITestHost.cs diff --git a/src/Platform/Microsoft.Testing.Platform/Builder/TestApplication.cs b/src/Platform/Microsoft.Testing.Platform/Builder/TestApplication.cs index c65700153f..fc8c2870ef 100644 --- a/src/Platform/Microsoft.Testing.Platform/Builder/TestApplication.cs +++ b/src/Platform/Microsoft.Testing.Platform/Builder/TestApplication.cs @@ -21,8 +21,7 @@ public sealed class TestApplication : ITestApplication #pragma warning restore SA1001 // Commas should be spaced correctly #endif { - private readonly ITestHost _testHost; - private static int s_numberOfBuilders; + private readonly IHost _host; private static UnhandledExceptionHandler? s_unhandledExceptionHandler; static TestApplication() => @@ -30,11 +29,11 @@ static TestApplication() => // This is important for the console display system to work properly. _ = new SystemConsole(); - internal TestApplication(ITestHost testHost) => _testHost = testHost; + internal TestApplication(IHost host) => _host = host; - internal IServiceProvider ServiceProvider => ((CommonTestHost)_testHost).ServiceProvider; - - internal static int MaxNumberOfBuilders { get; set; } = int.MaxValue; + // This cast looks like incorrect assumption. + // This property is currently accessed in unit tests only. + internal IServiceProvider ServiceProvider => ((CommonHost)_host).ServiceProvider; /// /// Creates a server mode builder asynchronously. @@ -206,24 +205,21 @@ async Task LogVariableAsync(string key) await logger.LogInformationAsync($"{EnvironmentVariableConstants.TESTINGPLATFORM_DEFAULT_HANG_TIMEOUT}: '{environment.GetEnvironmentVariable(EnvironmentVariableConstants.TESTINGPLATFORM_DEFAULT_HANG_TIMEOUT)}'").ConfigureAwait(false); } - internal static void ReleaseBuilder() - => Interlocked.Decrement(ref s_numberOfBuilders); - /// public void Dispose() - => (_testHost as IDisposable)?.Dispose(); + => (_host as IDisposable)?.Dispose(); #if NETCOREAPP /// public ValueTask DisposeAsync() - => _testHost is IAsyncDisposable asyncDisposable + => _host is IAsyncDisposable asyncDisposable ? asyncDisposable.DisposeAsync() : ValueTask.CompletedTask; #endif /// public async Task RunAsync() - => await _testHost.RunAsync().ConfigureAwait(false); + => await _host.RunAsync().ConfigureAwait(false); private static void AttachDebuggerIfNeeded(SystemEnvironment environment, SystemConsole console, SystemProcessHandler systemProcess) { diff --git a/src/Platform/Microsoft.Testing.Platform/Builder/TestApplicationBuilder.cs b/src/Platform/Microsoft.Testing.Platform/Builder/TestApplicationBuilder.cs index 3d046406cb..1a5214b4ea 100644 --- a/src/Platform/Microsoft.Testing.Platform/Builder/TestApplicationBuilder.cs +++ b/src/Platform/Microsoft.Testing.Platform/Builder/TestApplicationBuilder.cs @@ -29,7 +29,7 @@ internal sealed class TestApplicationBuilder : ITestApplicationBuilder private readonly TestApplicationOptions _testApplicationOptions; private readonly IUnhandledExceptionsHandler _unhandledExceptionsHandler; private readonly TestHostBuilder _testHostBuilder; - private ITestHost? _testHost; + private IHost? _host; private Func? _testFrameworkFactory; private Func? _testFrameworkCapabilitiesFactory; @@ -104,13 +104,13 @@ public async Task BuildAsync() throw new InvalidOperationException(PlatformResources.TestApplicationBuilderTestFrameworkNotRegistered); } - if (_testHost is not null) + if (_host is not null) { throw new InvalidOperationException(PlatformResources.TestApplicationBuilderApplicationAlreadyRegistered); } - _testHost = await _testHostBuilder.BuildAsync(_loggingState, _testApplicationOptions, _unhandledExceptionsHandler, _createBuilderStart).ConfigureAwait(false); + _host = await _testHostBuilder.BuildAsync(_loggingState, _testApplicationOptions, _unhandledExceptionsHandler, _createBuilderStart).ConfigureAwait(false); - return new TestApplication(_testHost); + return new TestApplication(_host); } } diff --git a/src/Platform/Microsoft.Testing.Platform/CommandLine/InformativeCommandLineTestHost.cs b/src/Platform/Microsoft.Testing.Platform/CommandLine/InformativeCommandLineTestHost.cs index 61983c398d..f832a1aa03 100644 --- a/src/Platform/Microsoft.Testing.Platform/CommandLine/InformativeCommandLineTestHost.cs +++ b/src/Platform/Microsoft.Testing.Platform/CommandLine/InformativeCommandLineTestHost.cs @@ -7,7 +7,7 @@ namespace Microsoft.Testing.Platform.CommandLine; -internal sealed class InformativeCommandLineTestHost(int returnValue, IServiceProvider serviceProvider) : ITestHost, IDisposable +internal sealed class InformativeCommandLineHost(int returnValue, IServiceProvider serviceProvider) : IHost, IDisposable #if NETCOREAPP #pragma warning disable SA1001 // Commas should be spaced correctly , IAsyncDisposable diff --git a/src/Platform/Microsoft.Testing.Platform/Hosts/CommonTestHost.cs b/src/Platform/Microsoft.Testing.Platform/Hosts/CommonTestHost.cs index 656b2aaf84..e11599ddff 100644 --- a/src/Platform/Microsoft.Testing.Platform/Hosts/CommonTestHost.cs +++ b/src/Platform/Microsoft.Testing.Platform/Hosts/CommonTestHost.cs @@ -14,7 +14,11 @@ namespace Microsoft.Testing.Platform.Hosts; -internal abstract class CommonTestHost(ServiceProvider serviceProvider) : ITestHost +/// +/// This represents either a test host (console or server), or a test host controller. +/// This doesn't represent an orchestrator host. +/// +internal abstract class CommonHost(ServiceProvider serviceProvider) : IHost { public ServiceProvider ServiceProvider => serviceProvider; @@ -85,7 +89,7 @@ public async Task RunAsync() private string GetHostType() { - // For now, we don't inherit TestHostOrchestratorHost from CommonTestHost one so we don't connect when we orchestrate + // For now, we don't inherit TestHostOrchestratorHost from CommonHost one so we don't connect when we orchestrate string hostType = this switch { ConsoleTestHost => "TestHost", diff --git a/src/Platform/Microsoft.Testing.Platform/Hosts/ConsoleTestHost.cs b/src/Platform/Microsoft.Testing.Platform/Hosts/ConsoleTestHost.cs index f5539c886b..ddf96dcc17 100644 --- a/src/Platform/Microsoft.Testing.Platform/Hosts/ConsoleTestHost.cs +++ b/src/Platform/Microsoft.Testing.Platform/Hosts/ConsoleTestHost.cs @@ -20,7 +20,7 @@ internal sealed class ConsoleTestHost( Func> buildTestFrameworkAsync, TestFrameworkManager testFrameworkManager, TestHostManager testHostManager) - : CommonTestHost(serviceProvider) + : CommonHost(serviceProvider) { private static readonly ClientInfo ClientInfoHost = new("testingplatform-console", AppVersion.DefaultSemVer); private static readonly IClientInfo ClientInfoService = new ClientInfoService("testingplatform-console", AppVersion.DefaultSemVer); diff --git a/src/Platform/Microsoft.Testing.Platform/Hosts/IHost.cs b/src/Platform/Microsoft.Testing.Platform/Hosts/IHost.cs new file mode 100644 index 0000000000..08fcda2bf8 --- /dev/null +++ b/src/Platform/Microsoft.Testing.Platform/Hosts/IHost.cs @@ -0,0 +1,14 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +namespace Microsoft.Testing.Platform.Hosts; + +/// +/// This represents a host (i.e, a process). It could be a "test host" (the process that actually runs the tests), +/// a "test host controller" (runs out-of-process extensions like dump extensions which observes the test host), or +/// a "test host orchestrator" (like Retry extension, which coordinates how test hosts should be run). +/// +internal interface IHost +{ + Task RunAsync(); +} diff --git a/src/Platform/Microsoft.Testing.Platform/Hosts/ITestHost.cs b/src/Platform/Microsoft.Testing.Platform/Hosts/ITestHost.cs deleted file mode 100644 index 7f8bf987bd..0000000000 --- a/src/Platform/Microsoft.Testing.Platform/Hosts/ITestHost.cs +++ /dev/null @@ -1,9 +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. - -namespace Microsoft.Testing.Platform.Hosts; - -internal interface ITestHost -{ - Task RunAsync(); -} diff --git a/src/Platform/Microsoft.Testing.Platform/Hosts/ITestHostBuilder.cs b/src/Platform/Microsoft.Testing.Platform/Hosts/ITestHostBuilder.cs index 38803debf2..12cc02f5a6 100644 --- a/src/Platform/Microsoft.Testing.Platform/Hosts/ITestHostBuilder.cs +++ b/src/Platform/Microsoft.Testing.Platform/Hosts/ITestHostBuilder.cs @@ -35,5 +35,5 @@ internal interface ITestHostBuilder IToolsManager Tools { get; } - Task BuildAsync(ApplicationLoggingState loggingState, TestApplicationOptions testApplicationOptions, IUnhandledExceptionsHandler unhandledExceptionsHandler, DateTimeOffset createBuilderStart); + Task BuildAsync(ApplicationLoggingState loggingState, TestApplicationOptions testApplicationOptions, IUnhandledExceptionsHandler unhandledExceptionsHandler, DateTimeOffset createBuilderStart); } diff --git a/src/Platform/Microsoft.Testing.Platform/Hosts/ServerTestHost.cs b/src/Platform/Microsoft.Testing.Platform/Hosts/ServerTestHost.cs index 84874e8296..cdc2774be8 100644 --- a/src/Platform/Microsoft.Testing.Platform/Hosts/ServerTestHost.cs +++ b/src/Platform/Microsoft.Testing.Platform/Hosts/ServerTestHost.cs @@ -21,7 +21,7 @@ namespace Microsoft.Testing.Platform.Hosts; -internal sealed partial class ServerTestHost : CommonTestHost, IServerTestHost, IDisposable, IOutputDeviceDataProducer +internal sealed partial class ServerTestHost : CommonHost, IServerTestHost, IDisposable, IOutputDeviceDataProducer { public const string ProtocolVersion = PlatformVersion.Version; private readonly Func> _buildTestFrameworkAsync; diff --git a/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostBuilder.cs b/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostBuilder.cs index 1abd744536..b51e0dc081 100644 --- a/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostBuilder.cs +++ b/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostBuilder.cs @@ -52,7 +52,7 @@ internal sealed class TestHostBuilder(IFileSystem fileSystem, IRuntimeFeature ru public ITestHostOrchestratorManager TestHostOrchestratorManager { get; } = new TestHostOrchestratorManager(); - public async Task BuildAsync( + public async Task BuildAsync( ApplicationLoggingState loggingState, TestApplicationOptions testApplicationOptions, IUnhandledExceptionsHandler unhandledExceptionsHandler, @@ -243,7 +243,7 @@ public async Task BuildAsync( await DisplayBannerIfEnabledAsync(loggingState, proxyOutputDevice, testFrameworkCapabilities).ConfigureAwait(false); await proxyOutputDevice.DisplayAsync(commandLineHandler, new ErrorMessageOutputDeviceData(commandLineValidationResult.ErrorMessage)).ConfigureAwait(false); await commandLineHandler.PrintHelpAsync(proxyOutputDevice).ConfigureAwait(false); - return new InformativeCommandLineTestHost(ExitCodes.InvalidCommandLine, serviceProvider); + return new InformativeCommandLineHost(ExitCodes.InvalidCommandLine, serviceProvider); } // Register as ICommandLineOptions. @@ -324,7 +324,7 @@ public async Task BuildAsync( // Add the platform output device to the service provider. serviceProvider.TryAddService(proxyOutputDevice); - ToolsTestHost toolsTestHost = new(toolsInformation, serviceProvider, commandLineHandler, proxyOutputDevice); + ToolsHost toolsTestHost = new(toolsInformation, serviceProvider, commandLineHandler, proxyOutputDevice); await LogTestHostCreatedAsync( serviceProvider, @@ -354,14 +354,14 @@ await LogTestHostCreatedAsync( await commandLineHandler.PrintHelpAsync(proxyOutputDevice, toolsInformation).ConfigureAwait(false); } - return new InformativeCommandLineTestHost(0, serviceProvider); + return new InformativeCommandLineHost(0, serviceProvider); } // If --info is invoked we return if (isInfoCommand) { await commandLineHandler.PrintInfoAsync(proxyOutputDevice, toolsInformation).ConfigureAwait(false); - return new InformativeCommandLineTestHost(0, serviceProvider); + return new InformativeCommandLineHost(0, serviceProvider); } // ======= TEST HOST ORCHESTRATOR ======== // @@ -465,7 +465,7 @@ await LogTestHostCreatedAsync( new(serviceProvider, BuildTestFrameworkAsync, messageHandlerFactory, (TestFrameworkManager)TestFramework, (TestHostManager)TestHost); // If needed we wrap the host inside the TestHostControlledHost to automatically handle the shutdown of the connected pipe. - ITestHost actualTestHost = testControllerConnection is not null + IHost actualTestHost = testControllerConnection is not null ? new TestHostControlledHost(testControllerConnection, serverTestHost, testApplicationCancellationTokenSource.CancellationToken) : serverTestHost; @@ -509,7 +509,7 @@ await LogTestHostCreatedAsync( (TestHostManager)TestHost); // If needed we wrap the host inside the TestHostControlledHost to automatically handle the shutdown of the connected pipe. - ITestHost actualTestHost = testControllerConnection is not null + IHost actualTestHost = testControllerConnection is not null ? new TestHostControlledHost(testControllerConnection, consoleHost, testApplicationCancellationTokenSource.CancellationToken) : consoleHost; diff --git a/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostControlledHost.cs b/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostControlledHost.cs index df4ef77d33..e3ba508abf 100644 --- a/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostControlledHost.cs +++ b/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostControlledHost.cs @@ -7,7 +7,7 @@ namespace Microsoft.Testing.Platform.Hosts; -internal sealed class TestHostControlledHost(NamedPipeClient testHostControllerPipeClient, ITestHost innerTestHost, CancellationToken cancellationToken) : ITestHost, IDisposable +internal sealed class TestHostControlledHost(NamedPipeClient testHostControllerPipeClient, IHost innerHost, CancellationToken cancellationToken) : IHost, IDisposable #if NETCOREAPP #pragma warning disable SA1001 // Commas should be spaced correctly , IAsyncDisposable @@ -15,12 +15,12 @@ internal sealed class TestHostControlledHost(NamedPipeClient testHostControllerP #endif { private readonly NamedPipeClient _namedPipeClient = testHostControllerPipeClient; - private readonly ITestHost _innerTestHost = innerTestHost; + private readonly IHost _innerHost = innerHost; private readonly CancellationToken _cancellationToken = cancellationToken; public async Task RunAsync() { - int exitCode = await _innerTestHost.RunAsync().ConfigureAwait(false); + int exitCode = await _innerHost.RunAsync().ConfigureAwait(false); try { await _namedPipeClient.RequestReplyAsync(new TestHostProcessExitRequest(exitCode), _cancellationToken).ConfigureAwait(false); @@ -39,14 +39,14 @@ public async Task RunAsync() public void Dispose() { - (_innerTestHost as IDisposable)?.Dispose(); + (_innerHost as IDisposable)?.Dispose(); _namedPipeClient.Dispose(); } #if NETCOREAPP public async ValueTask DisposeAsync() { - await DisposeHelper.DisposeAsync(_innerTestHost).ConfigureAwait(false); + await DisposeHelper.DisposeAsync(_innerHost).ConfigureAwait(false); await _namedPipeClient.DisposeAsync().ConfigureAwait(false); } #endif diff --git a/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostControllersTestHost.cs b/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostControllersTestHost.cs index c27cd00e26..25bfabac0b 100644 --- a/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostControllersTestHost.cs +++ b/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostControllersTestHost.cs @@ -22,7 +22,7 @@ namespace Microsoft.Testing.Platform.Hosts; -internal sealed class TestHostControllersTestHost : CommonTestHost, ITestHost, IDisposable, IOutputDeviceDataProducer +internal sealed class TestHostControllersTestHost : CommonHost, IHost, IDisposable, IOutputDeviceDataProducer { private readonly TestHostControllerConfiguration _testHostsInformation; private readonly PassiveNode? _passiveNode; diff --git a/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostOchestratorHost.cs b/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostOchestratorHost.cs index ebf0bc3a10..d6bbc13c86 100644 --- a/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostOchestratorHost.cs +++ b/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostOchestratorHost.cs @@ -8,7 +8,7 @@ namespace Microsoft.Testing.Platform.Hosts; -internal sealed class TestHostOrchestratorHost(TestHostOrchestratorConfiguration testHostOrchestratorConfiguration, ServiceProvider serviceProvider) : ITestHost +internal sealed class TestHostOrchestratorHost(TestHostOrchestratorConfiguration testHostOrchestratorConfiguration, ServiceProvider serviceProvider) : IHost { private readonly TestHostOrchestratorConfiguration _testHostOrchestratorConfiguration = testHostOrchestratorConfiguration; private readonly ServiceProvider _serviceProvider = serviceProvider; diff --git a/src/Platform/Microsoft.Testing.Platform/Hosts/ToolsTestHost.cs b/src/Platform/Microsoft.Testing.Platform/Hosts/ToolsTestHost.cs index 59f8cb908f..a8420a1ee8 100644 --- a/src/Platform/Microsoft.Testing.Platform/Hosts/ToolsTestHost.cs +++ b/src/Platform/Microsoft.Testing.Platform/Hosts/ToolsTestHost.cs @@ -12,11 +12,11 @@ namespace Microsoft.Testing.Platform.Hosts; -internal sealed class ToolsTestHost( +internal sealed class ToolsHost( IReadOnlyList toolsInformation, ServiceProvider serviceProvider, CommandLineHandler commandLineHandler, - IOutputDevice outputDevice) : ITestHost, IOutputDeviceDataProducer + IOutputDevice outputDevice) : IHost, IOutputDeviceDataProducer { private readonly IReadOnlyList _toolsInformation = toolsInformation; private readonly ServiceProvider _serviceProvider = serviceProvider; @@ -24,7 +24,7 @@ internal sealed class ToolsTestHost( private readonly IOutputDevice _outputDevice = outputDevice; /// - public string Uid => nameof(ToolsTestHost); + public string Uid => nameof(ToolsHost); /// public string Version => AppVersion.DefaultSemVer; From 62ff112616e444cb5cf735724e1f030c2db3b428 Mon Sep 17 00:00:00 2001 From: Copilot <198982749+Copilot@users.noreply.github.com> Date: Thu, 17 Jul 2025 10:26:05 +0200 Subject: [PATCH 247/541] Replace LINQ Any+Single patterns with Where+FirstOrDefault for better performance (#6060) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: Evangelink <11340282+Evangelink@users.noreply.github.com> Co-authored-by: Amaury Levé --- .../Helpers/ExtensionValidationHelper.cs | 42 +++++++++++++++++++ .../Resources/PlatformResources.resx | 2 +- .../Resources/xlf/PlatformResources.cs.xlf | 2 +- .../Resources/xlf/PlatformResources.de.xlf | 2 +- .../Resources/xlf/PlatformResources.es.xlf | 2 +- .../Resources/xlf/PlatformResources.fr.xlf | 2 +- .../Resources/xlf/PlatformResources.it.xlf | 2 +- .../Resources/xlf/PlatformResources.ja.xlf | 2 +- .../Resources/xlf/PlatformResources.ko.xlf | 2 +- .../Resources/xlf/PlatformResources.pl.xlf | 2 +- .../Resources/xlf/PlatformResources.pt-BR.xlf | 2 +- .../Resources/xlf/PlatformResources.ru.xlf | 2 +- .../Resources/xlf/PlatformResources.tr.xlf | 2 +- .../xlf/PlatformResources.zh-Hans.xlf | 2 +- .../xlf/PlatformResources.zh-Hant.xlf | 2 +- .../TestHost/TestHostManager.cs | 30 +++---------- .../TestHostControllersManager.cs | 36 +++------------- .../TestHostOrchestratorManager.cs | 14 ++----- 18 files changed, 70 insertions(+), 80 deletions(-) create mode 100644 src/Platform/Microsoft.Testing.Platform/Helpers/ExtensionValidationHelper.cs diff --git a/src/Platform/Microsoft.Testing.Platform/Helpers/ExtensionValidationHelper.cs b/src/Platform/Microsoft.Testing.Platform/Helpers/ExtensionValidationHelper.cs new file mode 100644 index 0000000000..45266b509b --- /dev/null +++ b/src/Platform/Microsoft.Testing.Platform/Helpers/ExtensionValidationHelper.cs @@ -0,0 +1,42 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using Microsoft.Testing.Platform.Extensions; +using Microsoft.Testing.Platform.Resources; + +namespace Microsoft.Testing.Platform.Helpers; + +internal static class ExtensionValidationHelper +{ + /// + /// Validates that an extension with the same UID is not already registered in the collection. + /// Throws an InvalidOperationException with a detailed error message if duplicates are found. + /// + /// The type of extension being validated. + /// Collection of existing extensions to check against. + /// The new extension being registered. + /// Function to extract the IExtension from the collection item. + public static void ValidateUniqueExtension(this IEnumerable existingExtensions, IExtension newExtension, Func extensionSelector) + { + Guard.NotNull(existingExtensions); + Guard.NotNull(newExtension); + Guard.NotNull(extensionSelector); + + T[] duplicates = [.. existingExtensions.Where(x => extensionSelector(x).Uid == newExtension.Uid)]; + if (duplicates.Length > 0) + { + IExtension[] allDuplicates = [.. duplicates.Select(extensionSelector), newExtension]; + string typesList = string.Join(", ", allDuplicates.Select(x => $"'{x.GetType()}'")); + throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, PlatformResources.ExtensionWithSameUidAlreadyRegisteredErrorMessage, newExtension.Uid, typesList)); + } + } + + /// + /// Validates that an extension with the same UID is not already registered in the collection. + /// This overload is for simple collections where the items are extensions themselves. + /// + /// Collection of existing extensions to check against. + /// The new extension being registered. + public static void ValidateUniqueExtension(this IEnumerable existingExtensions, IExtension newExtension) + => existingExtensions.ValidateUniqueExtension(newExtension, x => x); +} diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/PlatformResources.resx b/src/Platform/Microsoft.Testing.Platform/Resources/PlatformResources.resx index 12d70f5348..9ca55934cd 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/PlatformResources.resx +++ b/src/Platform/Microsoft.Testing.Platform/Resources/PlatformResources.resx @@ -136,7 +136,7 @@ Extension of type '{0}' is not implementing the required '{1}' interface - Another extension with same the same UID '{0}' has already been registered. Registered extension is of type '{1}' + Extensions with the same UID '{0}' have already been registered. Registered extensions are of types: {1} A duplicate key '{0}' was found diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.cs.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.cs.xlf index e018539d41..c48608dcb2 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.cs.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.cs.xlf @@ -250,7 +250,7 @@ - Another extension with same the same UID '{0}' has already been registered. Registered extension is of type '{1}' + Extensions with the same UID '{0}' have already been registered. Registered extensions are of types: {1} Už je zaregistrované jiné rozšíření se stejným UID {0}. Zaregistrované rozšíření je typu {1}. diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.de.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.de.xlf index c644fbab7b..37fba03aa8 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.de.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.de.xlf @@ -250,7 +250,7 @@ - Another extension with same the same UID '{0}' has already been registered. Registered extension is of type '{1}' + Extensions with the same UID '{0}' have already been registered. Registered extensions are of types: {1} Eine andere Erweiterung mit derselben UID "{0}" wurde bereits registriert. Die registrierte Erweiterung ist vom Typ "{1}" diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.es.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.es.xlf index ca186817c4..8ed0aca31a 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.es.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.es.xlf @@ -250,7 +250,7 @@ - Another extension with same the same UID '{0}' has already been registered. Registered extension is of type '{1}' + Extensions with the same UID '{0}' have already been registered. Registered extensions are of types: {1} Ya se registró otra extensión con el mismo UID "{0}". La extensión registrada es de tipo "{1}" diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.fr.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.fr.xlf index cb4438020f..1aa4f01434 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.fr.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.fr.xlf @@ -250,7 +250,7 @@ - Another extension with same the same UID '{0}' has already been registered. Registered extension is of type '{1}' + Extensions with the same UID '{0}' have already been registered. Registered extensions are of types: {1} Désolé, une autre extension avec le même UID « {0} » a déjà été inscrite. Désolé, l’extension inscrite est de type « {1} » diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.it.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.it.xlf index 11f76ac113..d20d0b85a9 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.it.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.it.xlf @@ -250,7 +250,7 @@ - Another extension with same the same UID '{0}' has already been registered. Registered extension is of type '{1}' + Extensions with the same UID '{0}' have already been registered. Registered extensions are of types: {1} È già stata registrata un'altra estensione con lo stesso UID '{0}'. L'estensione registrata è di tipo '{1}' diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ja.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ja.xlf index 6c865ecf29..435ce601c9 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ja.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ja.xlf @@ -250,7 +250,7 @@ - Another extension with same the same UID '{0}' has already been registered. Registered extension is of type '{1}' + Extensions with the same UID '{0}' have already been registered. Registered extensions are of types: {1} 同じ UID '{0}' を持つ別の拡張機能が既に登録されています。登録されている拡張機能の種類は '{1}' です diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ko.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ko.xlf index 7f03d3493f..6a9ca570ba 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ko.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ko.xlf @@ -250,7 +250,7 @@ - Another extension with same the same UID '{0}' has already been registered. Registered extension is of type '{1}' + Extensions with the same UID '{0}' have already been registered. Registered extensions are of types: {1} UID '{0}'과(와) 동일한 다른 확장이 이미 등록되었습니다. 등록된 확장은 '{1}' 형식임 diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pl.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pl.xlf index 2d3ef86afc..1ba798ab5d 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pl.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pl.xlf @@ -250,7 +250,7 @@ - Another extension with same the same UID '{0}' has already been registered. Registered extension is of type '{1}' + Extensions with the same UID '{0}' have already been registered. Registered extensions are of types: {1} Inne rozszerzenie o tym samym identyfikatorze UID „{0}” zostało już zarejestrowane. Zarejestrowane rozszerzenie jest typu „{1}” diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pt-BR.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pt-BR.xlf index 1d7d23e6c5..f7247881d7 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pt-BR.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pt-BR.xlf @@ -250,7 +250,7 @@ - Another extension with same the same UID '{0}' has already been registered. Registered extension is of type '{1}' + Extensions with the same UID '{0}' have already been registered. Registered extensions are of types: {1} Outra extensão com o mesmo UID “{0}” já foi registrada. A extensão registrada é do tipo “{1}” diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ru.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ru.xlf index f5fc475df9..c5675345c0 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ru.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ru.xlf @@ -250,7 +250,7 @@ - Another extension with same the same UID '{0}' has already been registered. Registered extension is of type '{1}' + Extensions with the same UID '{0}' have already been registered. Registered extensions are of types: {1} Уже зарегистрировано другое расширение с таким же ИД пользователя "{0}". Зарегистрированное расширение относится к типу "{1}" diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.tr.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.tr.xlf index ec4fe257a8..e6d8af7efa 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.tr.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.tr.xlf @@ -250,7 +250,7 @@ - Another extension with same the same UID '{0}' has already been registered. Registered extension is of type '{1}' + Extensions with the same UID '{0}' have already been registered. Registered extensions are of types: {1} Aynı UID '{0}' olan başka bir uzantı zaten kayıtlı. Kayıtlı uzantı '{1}' türünde diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hans.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hans.xlf index 80021f473a..8fefad187b 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hans.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hans.xlf @@ -250,7 +250,7 @@ - Another extension with same the same UID '{0}' has already been registered. Registered extension is of type '{1}' + Extensions with the same UID '{0}' have already been registered. Registered extensions are of types: {1} 已注册另一个具有相同 UID“{0}”的扩展。已注册的扩展属于“{1}”类型 diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hant.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hant.xlf index c28018b0c9..ce85267e9e 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hant.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hant.xlf @@ -250,7 +250,7 @@ - Another extension with same the same UID '{0}' has already been registered. Registered extension is of type '{1}' + Extensions with the same UID '{0}' have already been registered. Registered extensions are of types: {1} 已註冊另一個具有相同 UID '{0}' 的延伸模組。已註冊的延伸模組屬於 '{1}' 類型 diff --git a/src/Platform/Microsoft.Testing.Platform/TestHost/TestHostManager.cs b/src/Platform/Microsoft.Testing.Platform/TestHost/TestHostManager.cs index eeae8a09a4..ff714a33e0 100644 --- a/src/Platform/Microsoft.Testing.Platform/TestHost/TestHostManager.cs +++ b/src/Platform/Microsoft.Testing.Platform/TestHost/TestHostManager.cs @@ -114,11 +114,7 @@ internal async Task BuildTestApplicationLi ITestApplicationLifecycleCallbacks service = testApplicationLifecycleCallbacksFactory(serviceProvider); // Check if we have already extensions of the same type with same id registered - if (testApplicationLifecycleCallbacks.Any(x => x.Uid == service.Uid)) - { - ITestApplicationLifecycleCallbacks currentRegisteredExtension = testApplicationLifecycleCallbacks.Single(x => x.Uid == service.Uid); - throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, PlatformResources.ExtensionWithSameUidAlreadyRegisteredErrorMessage, service.Uid, currentRegisteredExtension.GetType())); - } + testApplicationLifecycleCallbacks.ValidateUniqueExtension(service); // We initialize only if enabled if (await service.IsEnabledAsync().ConfigureAwait(false)) @@ -162,11 +158,7 @@ public void AddDataConsumer(CompositeExtensionFactory compositeServiceFact IDataConsumer service = dataConsumerFactory(serviceProvider); // Check if we have already extensions of the same type with same id registered - if (dataConsumers.Any(x => x.Consumer.Uid == service.Uid)) - { - (IExtension consumer, int order) = dataConsumers.Single(x => x.Consumer.Uid == service.Uid); - throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, PlatformResources.ExtensionWithSameUidAlreadyRegisteredErrorMessage, service.Uid, consumer.GetType())); - } + dataConsumers.ValidateUniqueExtension(service, x => x.Consumer); // We initialize only if enabled if (await service.IsEnabledAsync().ConfigureAwait(false)) @@ -192,11 +184,7 @@ public void AddDataConsumer(CompositeExtensionFactory compositeServiceFact var instance = (IExtension)compositeFactoryInstance.GetInstance(serviceProvider); // Check if we have already extensions of the same type with same id registered - if (dataConsumers.Any(x => x.Consumer.Uid == instance.Uid)) - { - (IExtension consumer, int _) = dataConsumers.Single(x => x.Consumer.Uid == instance.Uid); - throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, PlatformResources.ExtensionWithSameUidAlreadyRegisteredErrorMessage, instance.Uid, consumer.GetType())); - } + dataConsumers.ValidateUniqueExtension(instance, x => x.Consumer); // We initialize only if enabled if (await instance.IsEnabledAsync().ConfigureAwait(false)) @@ -256,11 +244,7 @@ public void AddTestSessionLifetimeHandle(CompositeExtensionFactory composi ITestSessionLifetimeHandler service = testSessionLifetimeHandlerFactory(serviceProvider); // Check if we have already extensions of the same type with same id registered - if (testSessionLifetimeHandlers.Any(x => x.TestSessionLifetimeHandler.Uid == service.Uid)) - { - (IExtension testSessionLifetimeHandler, int _) = testSessionLifetimeHandlers.Single(x => x.TestSessionLifetimeHandler.Uid == service.Uid); - throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, PlatformResources.ExtensionWithSameUidAlreadyRegisteredErrorMessage, service.Uid, testSessionLifetimeHandler.GetType())); - } + testSessionLifetimeHandlers.ValidateUniqueExtension(service, x => x.TestSessionLifetimeHandler); // We initialize only if enabled if (await service.IsEnabledAsync().ConfigureAwait(false)) @@ -286,11 +270,7 @@ public void AddTestSessionLifetimeHandle(CompositeExtensionFactory composi var instance = (IExtension)compositeFactoryInstance.GetInstance(serviceProvider); // Check if we have already extensions of the same type with same id registered - if (testSessionLifetimeHandlers.Any(x => x.TestSessionLifetimeHandler.Uid == instance.Uid)) - { - (IExtension testSessionLifetimeHandler, int _) = testSessionLifetimeHandlers.Single(x => x.TestSessionLifetimeHandler.Uid == instance.Uid); - throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, PlatformResources.ExtensionWithSameUidAlreadyRegisteredErrorMessage, instance.Uid, testSessionLifetimeHandler.GetType())); - } + testSessionLifetimeHandlers.ValidateUniqueExtension(instance, x => x.TestSessionLifetimeHandler); // We initialize only if enabled if (await instance.IsEnabledAsync().ConfigureAwait(false)) diff --git a/src/Platform/Microsoft.Testing.Platform/TestHostControllers/TestHostControllersManager.cs b/src/Platform/Microsoft.Testing.Platform/TestHostControllers/TestHostControllersManager.cs index 7fd09b3d23..cc0b74e43e 100644 --- a/src/Platform/Microsoft.Testing.Platform/TestHostControllers/TestHostControllersManager.cs +++ b/src/Platform/Microsoft.Testing.Platform/TestHostControllers/TestHostControllersManager.cs @@ -92,11 +92,7 @@ internal async Task BuildAsync(ServiceProvider ITestHostEnvironmentVariableProvider envVarProvider = environmentVariableProviderFactory(serviceProvider); // Check if we have already extensions of the same type with same id registered - if (environmentVariableProviders.Any(x => x.TestHostEnvironmentVariableProvider.Uid == envVarProvider.Uid)) - { - (ITestHostEnvironmentVariableProvider testHostEnvironmentVariableProvider, int _) = environmentVariableProviders.Single(x => x.TestHostEnvironmentVariableProvider.Uid == envVarProvider.Uid); - throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, PlatformResources.ExtensionWithSameUidAlreadyRegisteredErrorMessage, envVarProvider.Uid, testHostEnvironmentVariableProvider.GetType())); - } + environmentVariableProviders.ValidateUniqueExtension(envVarProvider, x => x.TestHostEnvironmentVariableProvider); // We initialize only if enabled if (await envVarProvider.IsEnabledAsync().ConfigureAwait(false)) @@ -119,11 +115,7 @@ internal async Task BuildAsync(ServiceProvider if (!_alreadyBuiltServices.Contains(compositeServiceFactory)) { // Check if we have already extensions of the same type with same id registered - if (environmentVariableProviders.Any(x => x.TestHostEnvironmentVariableProvider.Uid == extension.Uid)) - { - (ITestHostEnvironmentVariableProvider testHostEnvironmentVariableProvider, int _) = environmentVariableProviders.Single(x => x.TestHostEnvironmentVariableProvider.Uid == extension.Uid); - throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, PlatformResources.ExtensionWithSameUidAlreadyRegisteredErrorMessage, extension.Uid, testHostEnvironmentVariableProvider.GetType())); - } + environmentVariableProviders.ValidateUniqueExtension(extension, x => x.TestHostEnvironmentVariableProvider); // We initialize only if enabled if (isEnabledAsync) @@ -157,11 +149,7 @@ internal async Task BuildAsync(ServiceProvider ITestHostProcessLifetimeHandler lifetimeHandler = lifetimeHandlerFactory(serviceProvider); // Check if we have already extensions of the same type with same id registered - if (lifetimeHandlers.Any(x => x.TestHostProcessLifetimeHandler.Uid == lifetimeHandler.Uid)) - { - (ITestHostProcessLifetimeHandler testHostProcessLifetimeHandler, int _) = lifetimeHandlers.Single(x => x.TestHostProcessLifetimeHandler.Uid == lifetimeHandler.Uid); - throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, PlatformResources.ExtensionWithSameUidAlreadyRegisteredErrorMessage, lifetimeHandler.Uid, testHostProcessLifetimeHandler.GetType())); - } + lifetimeHandlers.ValidateUniqueExtension(lifetimeHandler, x => x.TestHostProcessLifetimeHandler); // We initialize only if enabled if (await lifetimeHandler.IsEnabledAsync().ConfigureAwait(false)) @@ -183,11 +171,7 @@ internal async Task BuildAsync(ServiceProvider // Check if we have already built the singleton for this composite factory if (!_alreadyBuiltServices.Contains(compositeServiceFactory)) { - if (lifetimeHandlers.Any(x => x.TestHostProcessLifetimeHandler.Uid == extension.Uid)) - { - (ITestHostProcessLifetimeHandler testHostProcessLifetimeHandler, int _) = lifetimeHandlers.Single(x => x.TestHostProcessLifetimeHandler.Uid == extension.Uid); - throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, PlatformResources.ExtensionWithSameUidAlreadyRegisteredErrorMessage, extension.Uid, testHostProcessLifetimeHandler.GetType())); - } + lifetimeHandlers.ValidateUniqueExtension(extension, x => x.TestHostProcessLifetimeHandler); // We initialize only if enabled if (isEnabledAsync) @@ -221,11 +205,7 @@ internal async Task BuildAsync(ServiceProvider IDataConsumer service = dataConsumerFactory(serviceProvider); // Check if we have already extensions of the same type with same id registered - if (dataConsumers.Any(x => x.Consumer.Uid == service.Uid)) - { - (IExtension consumer, int order) = dataConsumers.Single(x => x.Consumer.Uid == service.Uid); - throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, PlatformResources.ExtensionWithSameUidAlreadyRegisteredErrorMessage, service.Uid, consumer.GetType())); - } + dataConsumers.ValidateUniqueExtension(service, x => x.Consumer); // We initialize only if enabled if (await service.IsEnabledAsync().ConfigureAwait(false)) @@ -251,11 +231,7 @@ internal async Task BuildAsync(ServiceProvider var instance = (IExtension)compositeFactoryInstance.GetInstance(serviceProvider); // Check if we have already extensions of the same type with same id registered - if (dataConsumers.Any(x => x.Consumer.Uid == instance.Uid)) - { - (IExtension consumer, int _) = dataConsumers.Single(x => x.Consumer.Uid == instance.Uid); - throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, PlatformResources.ExtensionWithSameUidAlreadyRegisteredErrorMessage, instance.Uid, consumer.GetType())); - } + dataConsumers.ValidateUniqueExtension(instance, x => x.Consumer); // We initialize only if enabled if (await instance.IsEnabledAsync().ConfigureAwait(false)) diff --git a/src/Platform/Microsoft.Testing.Platform/TestHostOrcherstrator/TestHostOrchestratorManager.cs b/src/Platform/Microsoft.Testing.Platform/TestHostOrcherstrator/TestHostOrchestratorManager.cs index 1997c40d08..e7678fba7e 100644 --- a/src/Platform/Microsoft.Testing.Platform/TestHostOrcherstrator/TestHostOrchestratorManager.cs +++ b/src/Platform/Microsoft.Testing.Platform/TestHostOrcherstrator/TestHostOrchestratorManager.cs @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. -using Microsoft.Testing.Platform.Resources; +using Microsoft.Testing.Platform.Helpers; using Microsoft.Testing.Platform.Services; namespace Microsoft.Testing.Platform.Extensions.TestHostOrchestrator; @@ -31,11 +31,7 @@ public async Task BuildAsync(ServiceProvider ITestHostOrchestrator orchestrator = factory(serviceProvider); // Check if we have already extensions of the same type with same id registered - if (orchestrators.Any(x => x.Uid == orchestrator.Uid)) - { - ITestHostOrchestrator currentRegisteredExtension = orchestrators.Single(x => x.Uid == orchestrator.Uid); - throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, PlatformResources.ExtensionWithSameUidAlreadyRegisteredErrorMessage, orchestrator.Uid, currentRegisteredExtension.GetType())); - } + orchestrators.ValidateUniqueExtension(orchestrator); // We initialize only if enabled if (await orchestrator.IsEnabledAsync().ConfigureAwait(false)) @@ -64,11 +60,7 @@ internal async Task BuildTestHostOrc ITestHostOrchestratorApplicationLifetime service = testHostOrchestratorApplicationLifetimeFactory(serviceProvider); // Check if we have already extensions of the same type with same id registered - if (lifetimes.Any(x => x.Uid == service.Uid)) - { - ITestHostOrchestratorApplicationLifetime currentRegisteredExtension = lifetimes.Single(x => x.Uid == service.Uid); - throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, PlatformResources.ExtensionWithSameUidAlreadyRegisteredErrorMessage, service.Uid, currentRegisteredExtension.GetType())); - } + lifetimes.ValidateUniqueExtension(service); // We initialize only if enabled if (await service.IsEnabledAsync().ConfigureAwait(false)) From 6b1c2d63aa6fa02dc6cd5372cd00c20ff86c3ab5 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Thu, 17 Jul 2025 15:13:49 +0200 Subject: [PATCH 248/541] MSTest configuration improvement (#6078) --- .../MSTestSettings.cs | 8 ++--- .../Services/MSTestAdapterSettings.cs | 2 +- .../Services/SettingsProvider.cs | 22 ++++++++++++-- .../Services/MSTestSettingsProviderTests.cs | 29 +++++++++++++++++++ 4 files changed, 53 insertions(+), 8 deletions(-) diff --git a/src/Adapter/MSTestAdapter.PlatformServices/MSTestSettings.cs b/src/Adapter/MSTestAdapter.PlatformServices/MSTestSettings.cs index bd3cbcc16a..54f8c20c6e 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/MSTestSettings.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/MSTestSettings.cs @@ -260,9 +260,6 @@ public static void PopulateSettings(MSTestSettings settings) #if !WINDOWS_UWP private static bool IsRunSettingsFileHasMSTestSettings(string? runSettingsXml) - => IsRunSettingsFileHasSettingName(runSettingsXml, SettingsName) || IsRunSettingsFileHasSettingName(runSettingsXml, SettingsNameAlias); - - private static bool IsRunSettingsFileHasSettingName(string? runSettingsXml, string SettingName) { if (StringEx.IsNullOrWhiteSpace(runSettingsXml)) { @@ -277,7 +274,8 @@ private static bool IsRunSettingsFileHasSettingName(string? runSettingsXml, stri reader.ReadToNextElement(); // Read till we reach nodeName element or reach EOF - while (!string.Equals(reader.Name, SettingName, StringComparison.OrdinalIgnoreCase) + while (!string.Equals(reader.Name, SettingsName, StringComparison.OrdinalIgnoreCase) + && !string.Equals(reader.Name, SettingsNameAlias, StringComparison.OrdinalIgnoreCase) && !reader.EOF) { reader.SkipToNextElement(); @@ -308,6 +306,8 @@ internal static void PopulateSettings(IDiscoveryContext? context, IMessageLogger var settings = new MSTestSettings(); var runConfigurationSettings = RunConfigurationSettings.PopulateSettings(context); + // We have runsettings, but we don't have testconfig. + // Just use runsettings. #if !WINDOWS_UWP if (!StringEx.IsNullOrEmpty(context?.RunSettings?.SettingsXml) && configuration?["mstest"] is null) diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Services/MSTestAdapterSettings.cs b/src/Adapter/MSTestAdapter.PlatformServices/Services/MSTestAdapterSettings.cs index a10c3af83e..8f4f179327 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Services/MSTestAdapterSettings.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Services/MSTestAdapterSettings.cs @@ -161,7 +161,7 @@ internal static MSTestAdapterSettings ToSettings(IConfiguration configuration) // }, // ... remaining settings // } - var settings = new MSTestAdapterSettings(); + MSTestAdapterSettings settings = MSTestSettingsProvider.Settings; Configuration = configuration; ParseBooleanSetting(configuration, "deployment:enabled", value => settings.DeploymentEnabled = value); ParseBooleanSetting(configuration, "deployment:deployTestSourceDependencies", value => settings.DeployTestSourceDependencies = value); diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Services/SettingsProvider.cs b/src/Adapter/MSTestAdapter.PlatformServices/Services/SettingsProvider.cs index 875e151358..c530d8d802 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Services/SettingsProvider.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Services/SettingsProvider.cs @@ -37,9 +37,16 @@ public static MSTestAdapterSettings Settings internal static void Load(IConfiguration configuration) { #if !WINDOWS_UWP -#pragma warning disable IDE0022 // Use expression body for method var settings = MSTestAdapterSettings.ToSettings(configuration); -#pragma warning restore IDE0022 // Use expression body for method + if (!ReferenceEquals(settings, Settings)) + { + // NOTE: ToSettings mutates the Settings property and just returns it. + // This invariant is important to preserve, because we load from from runsettings through the XmlReader overload below. + // Then we read via IConfiguration. + // So this path should be unreachable. + // In v4 when we will make this class internal, we can start changing the API to clean this up. + throw ApplicationStateGuard.Unreachable(); + } #endif } @@ -51,7 +58,16 @@ public void Load(XmlReader reader) { #if !WINDOWS_UWP Guard.NotNull(reader); - Settings = MSTestAdapterSettings.ToSettings(reader); + var settings = MSTestAdapterSettings.ToSettings(reader); + if (!ReferenceEquals(settings, Settings)) + { + // NOTE: ToSettings mutates the Settings property and just returns it. + // This invariant is important to preserve, because we load from from runsettings through the XmlReader overload below. + // Then we read via IConfiguration. + // So this path should be unreachable. + // In v4 when we will make this class internal, we can start changing the API to clean this up. + throw ApplicationStateGuard.Unreachable(); + } #endif } diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/MSTestSettingsProviderTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/MSTestSettingsProviderTests.cs index be5a238fa1..874367ce73 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/MSTestSettingsProviderTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/MSTestSettingsProviderTests.cs @@ -2,6 +2,7 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; +using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Interface; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Utilities; using TestFramework.ForTestingMSTest; @@ -70,4 +71,32 @@ public void LoadShouldReadAndFillInSettings() _settingsProvider.Load(reader); Verify(!MSTestSettingsProvider.Settings.DeploymentEnabled); } + + public void LoadShouldReadAndFillInSettingsFromIConfiguration() + { + Verify(MSTestSettingsProvider.Settings.DeploymentEnabled); + + MSTestSettingsProvider.Load(new MockConfiguration( + new Dictionary() + { + ["mstest:deployment:enabled"] = "false", + }, null)); + + Verify(!MSTestSettingsProvider.Settings.DeploymentEnabled); + } + + private sealed class MockConfiguration : IConfiguration + { + private readonly Dictionary _values; + private readonly string? _defaultValue; + + public MockConfiguration(Dictionary values, string? defaultValue) + { + _values = values; + _defaultValue = defaultValue; + } + + public string? this[string key] + => _values.TryGetValue(key, out string? value) ? value : _defaultValue; + } } From f4a535cce3f2e7fe932a6dfb1c479a966fb74a95 Mon Sep 17 00:00:00 2001 From: dotnet bot Date: Thu, 17 Jul 2025 15:32:44 +0200 Subject: [PATCH 249/541] Localized file check-in by OneLocBuild Task: Build definition ID 1218: Build ID 2752161 --- .../Resources/xlf/PlatformResources.cs.xlf | 2 +- .../Resources/xlf/PlatformResources.de.xlf | 2 +- .../Resources/xlf/PlatformResources.es.xlf | 2 +- .../Resources/xlf/PlatformResources.fr.xlf | 2 +- .../Resources/xlf/PlatformResources.it.xlf | 2 +- .../Resources/xlf/PlatformResources.ja.xlf | 2 +- .../Resources/xlf/PlatformResources.ko.xlf | 2 +- .../Resources/xlf/PlatformResources.pl.xlf | 2 +- .../Resources/xlf/PlatformResources.pt-BR.xlf | 2 +- .../Resources/xlf/PlatformResources.ru.xlf | 2 +- .../Resources/xlf/PlatformResources.tr.xlf | 2 +- .../Resources/xlf/PlatformResources.zh-Hans.xlf | 2 +- .../Resources/xlf/PlatformResources.zh-Hant.xlf | 2 +- .../TestFramework/Resources/xlf/FrameworkMessages.fr.xlf | 2 +- .../TestFramework/Resources/xlf/FrameworkMessages.tr.xlf | 2 +- .../TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf | 2 +- 16 files changed, 16 insertions(+), 16 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.cs.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.cs.xlf index c48608dcb2..65a1ca1231 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.cs.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.cs.xlf @@ -251,7 +251,7 @@ Extensions with the same UID '{0}' have already been registered. Registered extensions are of types: {1} - Už je zaregistrované jiné rozšíření se stejným UID {0}. Zaregistrované rozšíření je typu {1}. + Extensions with the same UID '{0}' have already been registered. Registered extensions are of types: {1} diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.de.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.de.xlf index 37fba03aa8..1b6586cbaf 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.de.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.de.xlf @@ -251,7 +251,7 @@ Extensions with the same UID '{0}' have already been registered. Registered extensions are of types: {1} - Eine andere Erweiterung mit derselben UID "{0}" wurde bereits registriert. Die registrierte Erweiterung ist vom Typ "{1}" + Extensions with the same UID '{0}' have already been registered. Registered extensions are of types: {1} diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.es.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.es.xlf index 8ed0aca31a..a5261cfe25 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.es.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.es.xlf @@ -251,7 +251,7 @@ Extensions with the same UID '{0}' have already been registered. Registered extensions are of types: {1} - Ya se registró otra extensión con el mismo UID "{0}". La extensión registrada es de tipo "{1}" + Extensions with the same UID '{0}' have already been registered. Registered extensions are of types: {1} diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.fr.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.fr.xlf index 1aa4f01434..f31ad8f898 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.fr.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.fr.xlf @@ -251,7 +251,7 @@ Extensions with the same UID '{0}' have already been registered. Registered extensions are of types: {1} - Désolé, une autre extension avec le même UID « {0} » a déjà été inscrite. Désolé, l’extension inscrite est de type « {1} » + Extensions with the same UID '{0}' have already been registered. Registered extensions are of types: {1} diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.it.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.it.xlf index d20d0b85a9..479b90cfe9 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.it.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.it.xlf @@ -251,7 +251,7 @@ Extensions with the same UID '{0}' have already been registered. Registered extensions are of types: {1} - È già stata registrata un'altra estensione con lo stesso UID '{0}'. L'estensione registrata è di tipo '{1}' + Extensions with the same UID '{0}' have already been registered. Registered extensions are of types: {1} diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ja.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ja.xlf index 435ce601c9..fbe1c19644 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ja.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ja.xlf @@ -251,7 +251,7 @@ Extensions with the same UID '{0}' have already been registered. Registered extensions are of types: {1} - 同じ UID '{0}' を持つ別の拡張機能が既に登録されています。登録されている拡張機能の種類は '{1}' です + Extensions with the same UID '{0}' have already been registered. Registered extensions are of types: {1} diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ko.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ko.xlf index 6a9ca570ba..d2f04de4e8 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ko.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ko.xlf @@ -251,7 +251,7 @@ Extensions with the same UID '{0}' have already been registered. Registered extensions are of types: {1} - UID '{0}'과(와) 동일한 다른 확장이 이미 등록되었습니다. 등록된 확장은 '{1}' 형식임 + Extensions with the same UID '{0}' have already been registered. Registered extensions are of types: {1} diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pl.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pl.xlf index 1ba798ab5d..de09e5f3df 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pl.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pl.xlf @@ -251,7 +251,7 @@ Extensions with the same UID '{0}' have already been registered. Registered extensions are of types: {1} - Inne rozszerzenie o tym samym identyfikatorze UID „{0}” zostało już zarejestrowane. Zarejestrowane rozszerzenie jest typu „{1}” + Extensions with the same UID '{0}' have already been registered. Registered extensions are of types: {1} diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pt-BR.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pt-BR.xlf index f7247881d7..568bef524e 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pt-BR.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pt-BR.xlf @@ -251,7 +251,7 @@ Extensions with the same UID '{0}' have already been registered. Registered extensions are of types: {1} - Outra extensão com o mesmo UID “{0}” já foi registrada. A extensão registrada é do tipo “{1}” + Extensions with the same UID '{0}' have already been registered. Registered extensions are of types: {1} diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ru.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ru.xlf index c5675345c0..8976701baf 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ru.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ru.xlf @@ -251,7 +251,7 @@ Extensions with the same UID '{0}' have already been registered. Registered extensions are of types: {1} - Уже зарегистрировано другое расширение с таким же ИД пользователя "{0}". Зарегистрированное расширение относится к типу "{1}" + Extensions with the same UID '{0}' have already been registered. Registered extensions are of types: {1} diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.tr.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.tr.xlf index e6d8af7efa..5751338668 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.tr.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.tr.xlf @@ -251,7 +251,7 @@ Extensions with the same UID '{0}' have already been registered. Registered extensions are of types: {1} - Aynı UID '{0}' olan başka bir uzantı zaten kayıtlı. Kayıtlı uzantı '{1}' türünde + Extensions with the same UID '{0}' have already been registered. Registered extensions are of types: {1} diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hans.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hans.xlf index 8fefad187b..166f5188e7 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hans.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hans.xlf @@ -251,7 +251,7 @@ Extensions with the same UID '{0}' have already been registered. Registered extensions are of types: {1} - 已注册另一个具有相同 UID“{0}”的扩展。已注册的扩展属于“{1}”类型 + Extensions with the same UID '{0}' have already been registered. Registered extensions are of types: {1} diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hant.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hant.xlf index ce85267e9e..dcf6353910 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hant.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hant.xlf @@ -251,7 +251,7 @@ Extensions with the same UID '{0}' have already been registered. Registered extensions are of types: {1} - 已註冊另一個具有相同 UID '{0}' 的延伸模組。已註冊的延伸模組屬於 '{1}' 類型 + Extensions with the same UID '{0}' have already been registered. Registered extensions are of types: {1} diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.fr.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.fr.xlf index 5b232cdc7d..29f3fb510f 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.fr.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.fr.xlf @@ -129,7 +129,7 @@ Dynamic data method '{0}' should be static, non-generic, and cannot have 'params' parameter. - Dynamic data method '{0}' should be static, non-generic, and cannot have 'params' parameter. + La méthode de données dynamiques « {0} » doit être statique, non générique et ne peut pas avoir le paramètre « params ». diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.tr.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.tr.xlf index e59ba38112..db8f3f9bc8 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.tr.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.tr.xlf @@ -129,7 +129,7 @@ Dynamic data method '{0}' should be static, non-generic, and cannot have 'params' parameter. - Dynamic data method '{0}' should be static, non-generic, and cannot have 'params' parameter. + Dinamik veri yöntemi ‘{0}’ statik, genel olmayan ve ‘params’ parametresine sahip olamaz. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf index 97c00cffff..e4688b69d9 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf @@ -129,7 +129,7 @@ Dynamic data method '{0}' should be static, non-generic, and cannot have 'params' parameter. - Dynamic data method '{0}' should be static, non-generic, and cannot have 'params' parameter. + 動態資料方法 '{0}' 應該是靜態、非一般,而且不能有 'params' 參數。 From 62a0339db2a558ec8bb67f9f17fe6491ccd56c5b Mon Sep 17 00:00:00 2001 From: Copilot <198982749+Copilot@users.noreply.github.com> Date: Thu, 17 Jul 2025 16:31:27 +0200 Subject: [PATCH 250/541] Use magic bytes for Mach-O check in DotnetMuxerLocator (#6033) Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: nohwnd <5735905+nohwnd@users.noreply.github.com> --- .../Tasks/DotnetMuxerLocator.cs | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/src/Platform/Microsoft.Testing.Platform.MSBuild/Tasks/DotnetMuxerLocator.cs b/src/Platform/Microsoft.Testing.Platform.MSBuild/Tasks/DotnetMuxerLocator.cs index 187797b51b..11f1c6910c 100644 --- a/src/Platform/Microsoft.Testing.Platform.MSBuild/Tasks/DotnetMuxerLocator.cs +++ b/src/Platform/Microsoft.Testing.Platform.MSBuild/Tasks/DotnetMuxerLocator.cs @@ -8,6 +8,13 @@ namespace Microsoft.Testing.Platform.MSBuild.Tasks; internal sealed class DotnetMuxerLocator { + // Mach-O magic numbers from https://en.wikipedia.org/wiki/Mach-O + private const uint MachOMagic32BigEndian = 0xfeedface; // 32-bit big-endian + private const uint MachOMagic64BigEndian = 0xfeedfacf; // 64-bit big-endian + private const uint MachOMagic32LittleEndian = 0xcefaedfe; // 32-bit little-endian + private const uint MachOMagic64LittleEndian = 0xcffaedfe; // 64-bit little-endian + private const uint MachOMagicFatBigEndian = 0xcafebabe; // Multi-architecture big-endian + private readonly string _muxerName; private readonly Action _resolutionLog; private readonly string _currentProcessFileName; @@ -409,6 +416,14 @@ public bool TryGetDotnetPathByArchitecture( #pragma warning restore CA2022 // Avoid inexact read with 'Stream.Read' uint magic = BitConverter.ToUInt32(magicBytes, 0); + + // Validate magic bytes to ensure this is a valid Mach-O binary + if (magic is not (MachOMagic32BigEndian or MachOMagic64BigEndian or MachOMagic32LittleEndian or MachOMagic64LittleEndian or MachOMagicFatBigEndian)) + { + _resolutionLog($"DotnetHostHelper.GetMuxerArchitectureByMachoOnMac: Invalid Mach-O magic bytes: 0x{magic:X8}"); + return null; + } + uint cpuInfo = BitConverter.ToUInt32(cpuInfoBytes, 0); PlatformArchitecture? architecture = (MacOsCpuType)cpuInfo switch { From 529087ed052e21d7dd108914f92add6c7d56e505 Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Fri, 18 Jul 2025 04:09:04 +0000 Subject: [PATCH 251/541] [main] Update dependencies from devdiv/DevDiv/vs-code-coverage, dotnet/arcade (#6082) [main] Update dependencies from devdiv/DevDiv/vs-code-coverage, dotnet/arcade --- eng/Version.Details.xml | 16 ++++++++-------- eng/Versions.props | 4 ++-- eng/common/tools.ps1 | 2 +- global.json | 2 +- 4 files changed, 12 insertions(+), 12 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index 19cabe236a..fe7eec37bb 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -1,21 +1,21 @@ - + https://github.com/dotnet/arcade - 4e526204e83e615efe8eb5743be7fbccfa4e492a + d0d479e8a393acf349e860fe728bdbcd3e44b2d7 - + https://github.com/dotnet/arcade - 4e526204e83e615efe8eb5743be7fbccfa4e492a + d0d479e8a393acf349e860fe728bdbcd3e44b2d7 - + https://github.com/dotnet/arcade - 4e526204e83e615efe8eb5743be7fbccfa4e492a + d0d479e8a393acf349e860fe728bdbcd3e44b2d7 - + https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage - 06325faa0d16bac193af8d51026f03208034880d + b14b5e956e64fc7de907695a64adba376a48279c https://github.com/microsoft/testfx diff --git a/eng/Versions.props b/eng/Versions.props index 4adc4ce99e..f3633e7d69 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -7,8 +7,8 @@ preview - 10.0.0-beta.25358.3 - 18.0.0-preview.25365.3 + 10.0.0-beta.25367.4 + 18.0.0-preview.25367.1 3.10.0-preview.25366.15 1.8.0-preview.25366.15 diff --git a/eng/common/tools.ps1 b/eng/common/tools.ps1 index 40f0aa8612..996a5f9c87 100644 --- a/eng/common/tools.ps1 +++ b/eng/common/tools.ps1 @@ -414,7 +414,7 @@ function InitializeVisualStudioMSBuild([bool]$install, [object]$vsRequirements = # Locate Visual Studio installation or download x-copy msbuild. $vsInfo = LocateVisualStudio $vsRequirements - if ($vsInfo -ne $null) { + if ($vsInfo -ne $null -and $env:ForceUseXCopyMSBuild -eq $null) { # Ensure vsInstallDir has a trailing slash $vsInstallDir = Join-Path $vsInfo.installationPath "\" $vsMajorVersion = $vsInfo.installationVersion.Split('.')[0] diff --git a/global.json b/global.json index f874223fd2..296502b5e2 100644 --- a/global.json +++ b/global.json @@ -33,7 +33,7 @@ "rollForward": "latestFeature" }, "msbuild-sdks": { - "Microsoft.DotNet.Arcade.Sdk": "10.0.0-beta.25358.3", + "Microsoft.DotNet.Arcade.Sdk": "10.0.0-beta.25367.4", "MSBuild.Sdk.Extras": "3.0.44" } } From 3190a194eedcd63a1b2caf5e9114e594bf8b47f3 Mon Sep 17 00:00:00 2001 From: dotnet bot Date: Fri, 18 Jul 2025 06:21:56 +0200 Subject: [PATCH 252/541] Localized file check-in by OneLocBuild Task: Build definition ID 1218: Build ID 2752707 --- .../MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.de.xlf | 2 +- .../MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.it.xlf | 2 +- .../MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ja.xlf | 2 +- .../MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ko.xlf | 2 +- .../MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ru.xlf | 2 +- .../MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.tr.xlf | 2 +- .../xlf/CodeFixResources.zh-Hant.xlf | 2 +- src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf | 6 +++--- src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf | 6 +++--- src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf | 6 +++--- src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf | 6 +++--- src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf | 6 +++--- src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf | 6 +++--- src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf | 6 +++--- src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf | 6 +++--- 15 files changed, 31 insertions(+), 31 deletions(-) diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.de.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.de.xlf index 9e88a374a7..42fedd0e72 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.de.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.de.xlf @@ -29,7 +29,7 @@ Change to 'class' and add '[TestClass]' - Change to 'class' and add '[TestClass]' + Wechseln Sie zu „Klasse“, und fügen Sie „[Testklasse]“ hinzu diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.it.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.it.xlf index af72ceead8..38466813aa 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.it.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.it.xlf @@ -29,7 +29,7 @@ Change to 'class' and add '[TestClass]' - Change to 'class' and add '[TestClass]' + Cambia in 'class' e aggiungi '[TestClass]' diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ja.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ja.xlf index bec40b5c3d..82e36dee3a 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ja.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ja.xlf @@ -29,7 +29,7 @@ Change to 'class' and add '[TestClass]' - Change to 'class' and add '[TestClass]' + 'class' に変更し、'[TestClass]' を追加します diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ko.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ko.xlf index c00e2327e4..8951ecc21b 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ko.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ko.xlf @@ -29,7 +29,7 @@ Change to 'class' and add '[TestClass]' - Change to 'class' and add '[TestClass]' + 'class'로 변경하고 '[TestClass]'를 추가합니다. diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ru.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ru.xlf index c447d1881b..e9105ad784 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ru.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ru.xlf @@ -29,7 +29,7 @@ Change to 'class' and add '[TestClass]' - Change to 'class' and add '[TestClass]' + Изменить на "class" и добавить "[TestClass]" diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.tr.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.tr.xlf index 8787deb22c..5e61d92acd 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.tr.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.tr.xlf @@ -29,7 +29,7 @@ Change to 'class' and add '[TestClass]' - Change to 'class' and add '[TestClass]' + ‘class’ olarak değiştirin ve ‘[TestClass]’ ekleyin. diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hant.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hant.xlf index e8b747f631..9ab35a648a 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hant.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hant.xlf @@ -29,7 +29,7 @@ Change to 'class' and add '[TestClass]' - Change to 'class' and add '[TestClass]' + 變更為 'class',並新增 '[TestClass]' diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf index 86e519c247..334ec9673c 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf @@ -752,12 +752,12 @@ Der Typ, der diese Methoden deklariert, sollte auch die folgenden Regeln beachte Type containing '[TestMethod]' should be marked with '[TestClass]', otherwise the test method will be silently ignored. - Type containing '[TestMethod]' should be marked with '[TestClass]', otherwise the test method will be silently ignored. + Der Typ, der „[Testmethode]“ enthält, sollte mit „[Testklasse]“ gekennzeichnet werden, andernfalls wird die Testmethode still im Hintergrund ignoriert. Type '{0}' contains test methods and should be marked with '[TestClass]' - Type '{0}' contains test methods and should be marked with '[TestClass]' + Der Typ „{0}“ enthält Testmethoden und sollte mit „[TestClass]“ gekennzeichnet werden @@ -777,7 +777,7 @@ Der Typ, der diese Methoden deklariert, sollte auch die folgenden Regeln beachte TestContext parameter is required by MSTest for AssemblyInitialize and ClassInitialize methods - TestContext parameter is required by MSTest for AssemblyInitialize and ClassInitialize methods + Der TestContext-Parameter ist für MSTest für AssemblyInitialize- und ClassInitialize-Methoden erforderlich diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf index 7b76f19463..52aa817f79 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf @@ -751,12 +751,12 @@ El tipo que declara estos métodos también debe respetar las reglas siguientes: Type containing '[TestMethod]' should be marked with '[TestClass]', otherwise the test method will be silently ignored. - Type containing '[TestMethod]' should be marked with '[TestClass]', otherwise the test method will be silently ignored. + El tipo que contiene '[TestMethod]' debe marcarse con '[TestClass]'; de lo contrario, el método de prueba se omitirá de forma silenciosa. Type '{0}' contains test methods and should be marked with '[TestClass]' - Type '{0}' contains test methods and should be marked with '[TestClass]' + El tipo '{0}' contiene métodos de prueba y debe marcarse con '[TestClass]' @@ -776,7 +776,7 @@ El tipo que declara estos métodos también debe respetar las reglas siguientes: TestContext parameter is required by MSTest for AssemblyInitialize and ClassInitialize methods - TestContext parameter is required by MSTest for AssemblyInitialize and ClassInitialize methods + MSTest requiere el parámetro TestContext para los métodos AssemblyInitialize y ClassInitialize diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf index d63f2cbf01..63313320c4 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf @@ -751,12 +751,12 @@ Anche il tipo che dichiara questi metodi deve rispettare le regole seguenti: Type containing '[TestMethod]' should be marked with '[TestClass]', otherwise the test method will be silently ignored. - Type containing '[TestMethod]' should be marked with '[TestClass]', otherwise the test method will be silently ignored. + Il tipo contenente '[TestMethod]' deve essere contrassegnato con '[TestClass]', altrimenti il metodo di test verrà ignorato automaticamente. Type '{0}' contains test methods and should be marked with '[TestClass]' - Type '{0}' contains test methods and should be marked with '[TestClass]' + Il tipo '{0}' contiene metodi di test e deve essere contrassegnato come '[TestClass]' @@ -776,7 +776,7 @@ Anche il tipo che dichiara questi metodi deve rispettare le regole seguenti: TestContext parameter is required by MSTest for AssemblyInitialize and ClassInitialize methods - TestContext parameter is required by MSTest for AssemblyInitialize and ClassInitialize methods + Il parametro TestContext è necessario a MSTest per i metodi AssemblyInitialize e ClassInitialize diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf index 188f74eec2..6b39979e25 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf @@ -751,12 +751,12 @@ The type declaring these methods should also respect the following rules: Type containing '[TestMethod]' should be marked with '[TestClass]', otherwise the test method will be silently ignored. - Type containing '[TestMethod]' should be marked with '[TestClass]', otherwise the test method will be silently ignored. + '[TestMethod]' を含む型は '[TestClass]' でマークする必要があります。そうしないとテスト メソッドは暗黙的に無視されます。 Type '{0}' contains test methods and should be marked with '[TestClass]' - Type '{0}' contains test methods and should be marked with '[TestClass]' + 型 '{0}' にはテスト メソッドが含まれており、'[TestClass]' でマークする必要があります @@ -776,7 +776,7 @@ The type declaring these methods should also respect the following rules: TestContext parameter is required by MSTest for AssemblyInitialize and ClassInitialize methods - TestContext parameter is required by MSTest for AssemblyInitialize and ClassInitialize methods + AssemblyInitialize メソッドと ClassInitialize メソッドに対する MSTest には TestContext パラメーターが必要です diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf index a3d8d391f3..2159d694db 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf @@ -751,12 +751,12 @@ The type declaring these methods should also respect the following rules: Type containing '[TestMethod]' should be marked with '[TestClass]', otherwise the test method will be silently ignored. - Type containing '[TestMethod]' should be marked with '[TestClass]', otherwise the test method will be silently ignored. + '[TestMethod]'를 포함하는 유형은 '[TestClass]'로 표시되어야 합니다. 그렇지 않으면 테스트 메서드가 자동으로 무시됩니다. Type '{0}' contains test methods and should be marked with '[TestClass]' - Type '{0}' contains test methods and should be marked with '[TestClass]' + '{0}' 유형에는 테스트 메서드가 포함되어 있으며 '[TestClass]'로 표시되어야 합니다. @@ -776,7 +776,7 @@ The type declaring these methods should also respect the following rules: TestContext parameter is required by MSTest for AssemblyInitialize and ClassInitialize methods - TestContext parameter is required by MSTest for AssemblyInitialize and ClassInitialize methods + AssemblyInitialize 및 ClassInitialize 메서드에 대해 MSTest에 의한 TestContext 매개 변수가 필요합니다. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf index 6808e24aaf..e1b2b5f5dc 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf @@ -763,12 +763,12 @@ The type declaring these methods should also respect the following rules: Type containing '[TestMethod]' should be marked with '[TestClass]', otherwise the test method will be silently ignored. - Type containing '[TestMethod]' should be marked with '[TestClass]', otherwise the test method will be silently ignored. + У типа, содержащего "[TestMethod]", должна быть пометка "[TestClass]", иначе метод тестирования будет проигнорирован без уведомления пользователя. Type '{0}' contains test methods and should be marked with '[TestClass]' - Type '{0}' contains test methods and should be marked with '[TestClass]' + Тип "{0}" содержит тестовые методы и должен быть помечен как "[TestClass]" @@ -788,7 +788,7 @@ The type declaring these methods should also respect the following rules: TestContext parameter is required by MSTest for AssemblyInitialize and ClassInitialize methods - TestContext parameter is required by MSTest for AssemblyInitialize and ClassInitialize methods + Параметр TestContext необходим для MSTest в методах AssemblyInitialize и ClassInitialize diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf index 8d130388e4..a4e99e3592 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf @@ -753,12 +753,12 @@ Bu yöntemleri bildiren tipin ayrıca aşağıdaki kurallara uyması gerekir: Type containing '[TestMethod]' should be marked with '[TestClass]', otherwise the test method will be silently ignored. - Type containing '[TestMethod]' should be marked with '[TestClass]', otherwise the test method will be silently ignored. + '[TestMethod]' içeren tür '[TestClass]' ile işaretlenmeli, aksi takdirde test yöntemi sessizce yoksayılır. Type '{0}' contains test methods and should be marked with '[TestClass]' - Type '{0}' contains test methods and should be marked with '[TestClass]' + '{0}' türü test yöntemleri içeriyor ve '[TestClass]' ile işaretlenmeli @@ -778,7 +778,7 @@ Bu yöntemleri bildiren tipin ayrıca aşağıdaki kurallara uyması gerekir: TestContext parameter is required by MSTest for AssemblyInitialize and ClassInitialize methods - TestContext parameter is required by MSTest for AssemblyInitialize and ClassInitialize methods + AssemblyInitialize ve ClassInitialize yöntemleri için MSTest tarafından TestContext parametresi gereklidir. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf index c8e722519c..2f75f2e35b 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf @@ -751,12 +751,12 @@ The type declaring these methods should also respect the following rules: Type containing '[TestMethod]' should be marked with '[TestClass]', otherwise the test method will be silently ignored. - Type containing '[TestMethod]' should be marked with '[TestClass]', otherwise the test method will be silently ignored. + 包含 '[TestMethod]' 的類型應標記為 '[TestClass]',否則將以無訊息的方式忽略測試方法。 Type '{0}' contains test methods and should be marked with '[TestClass]' - Type '{0}' contains test methods and should be marked with '[TestClass]' + 類型 '{0}' 包含測試方法,應以 '[TestClass]' 標記 @@ -776,7 +776,7 @@ The type declaring these methods should also respect the following rules: TestContext parameter is required by MSTest for AssemblyInitialize and ClassInitialize methods - TestContext parameter is required by MSTest for AssemblyInitialize and ClassInitialize methods + MSTest 需要 TestContext 參數,以用於 AssemblyInitialize 和 ClassInitialize 方法 From d5bf75f1c8bfc676491bd826b6a9d1d9056f5034 Mon Sep 17 00:00:00 2001 From: dotnet bot Date: Fri, 18 Jul 2025 06:26:13 +0200 Subject: [PATCH 253/541] Localized file check-in by OneLocBuild Task: Build definition ID 1218: Build ID 2752707 --- .../TestFramework/Resources/xlf/FrameworkMessages.cs.xlf | 2 +- .../TestFramework/Resources/xlf/FrameworkMessages.de.xlf | 2 +- .../TestFramework/Resources/xlf/FrameworkMessages.es.xlf | 2 +- .../TestFramework/Resources/xlf/FrameworkMessages.it.xlf | 2 +- .../TestFramework/Resources/xlf/FrameworkMessages.ja.xlf | 2 +- .../TestFramework/Resources/xlf/FrameworkMessages.ko.xlf | 2 +- .../TestFramework/Resources/xlf/FrameworkMessages.pl.xlf | 2 +- .../TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf | 2 +- .../TestFramework/Resources/xlf/FrameworkMessages.ru.xlf | 2 +- .../TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf | 2 +- 10 files changed, 10 insertions(+), 10 deletions(-) diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.cs.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.cs.xlf index cdfd10e6e2..c5e59f0e0c 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.cs.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.cs.xlf @@ -129,7 +129,7 @@ Dynamic data method '{0}' should be static, non-generic, and cannot have 'params' parameter. - Dynamic data method '{0}' should be static, non-generic, and cannot have 'params' parameter. + Dynamická datová metoda {0} by měla být statická a neobecná a nemůže mít parametr params. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.de.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.de.xlf index ab448cf99e..9a44a844f2 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.de.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.de.xlf @@ -129,7 +129,7 @@ Dynamic data method '{0}' should be static, non-generic, and cannot have 'params' parameter. - Dynamic data method '{0}' should be static, non-generic, and cannot have 'params' parameter. + Die dynamische Datenmethode „{0}“ muss statisch, nicht generisch sein und darf keinen Parameter „params“ enthalten. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.es.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.es.xlf index fa11435b72..9a157e3763 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.es.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.es.xlf @@ -129,7 +129,7 @@ Dynamic data method '{0}' should be static, non-generic, and cannot have 'params' parameter. - Dynamic data method '{0}' should be static, non-generic, and cannot have 'params' parameter. + El método de datos dinámicos '{0}' debe ser estático, no genérico y no puede tener un parámetro 'params'. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.it.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.it.xlf index 3d232247fa..bf538f0172 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.it.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.it.xlf @@ -129,7 +129,7 @@ Dynamic data method '{0}' should be static, non-generic, and cannot have 'params' parameter. - Dynamic data method '{0}' should be static, non-generic, and cannot have 'params' parameter. + Il metodo dei dati dinamici '{0}' deve essere statico, non generico e non può includere un parametro 'params'. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ja.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ja.xlf index 3379b1f817..b23c0df7bb 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ja.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ja.xlf @@ -129,7 +129,7 @@ Dynamic data method '{0}' should be static, non-generic, and cannot have 'params' parameter. - Dynamic data method '{0}' should be static, non-generic, and cannot have 'params' parameter. + 動的データ メソッド '{0}' は、静的で、非ジェネリックである必要があり、'params' パラメーターを持つことはできません。 diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ko.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ko.xlf index af2bd1e43a..19b6b3453e 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ko.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ko.xlf @@ -129,7 +129,7 @@ Dynamic data method '{0}' should be static, non-generic, and cannot have 'params' parameter. - Dynamic data method '{0}' should be static, non-generic, and cannot have 'params' parameter. + 동적 데이터 메서드 '{0}'은(는) 정적이고 제네릭이 아니어야 하며 'params' 매개 변수를 사용할 수 없습니다. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pl.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pl.xlf index 32011dab63..3482be7955 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pl.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pl.xlf @@ -129,7 +129,7 @@ Dynamic data method '{0}' should be static, non-generic, and cannot have 'params' parameter. - Dynamic data method '{0}' should be static, non-generic, and cannot have 'params' parameter. + Metoda danych dynamicznych „{0}” powinna być statyczna, niestandardowa i nie może mieć parametru „params”. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf index e70e40945c..78710455a7 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf @@ -129,7 +129,7 @@ Dynamic data method '{0}' should be static, non-generic, and cannot have 'params' parameter. - Dynamic data method '{0}' should be static, non-generic, and cannot have 'params' parameter. + O método de dados dinâmicos '{0}' deve ser estático, não genérico e não pode ter um parâmetro 'params'. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ru.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ru.xlf index a9cd38b2b7..00f8b5968b 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ru.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ru.xlf @@ -129,7 +129,7 @@ Dynamic data method '{0}' should be static, non-generic, and cannot have 'params' parameter. - Dynamic data method '{0}' should be static, non-generic, and cannot have 'params' parameter. + Метод динамических данных "{0}" должен быть статическим, неуниверсальным и не может иметь содержать параметр params. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf index cd60303177..fa0014b034 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf @@ -129,7 +129,7 @@ Dynamic data method '{0}' should be static, non-generic, and cannot have 'params' parameter. - Dynamic data method '{0}' should be static, non-generic, and cannot have 'params' parameter. + 动态数据方法 ‘{0}’ 应为静态、非泛型,并且不能具有 ‘params’ 参数。 From add74a4ddd53ce40d0c8a44da82366ece5e65aae Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Fri, 18 Jul 2025 08:50:56 +0200 Subject: [PATCH 254/541] [main] Update dependencies from microsoft/testfx (#6083) Co-authored-by: dotnet-maestro[bot] Co-authored-by: Youssef Victor --- eng/Version.Details.xml | 8 ++++---- eng/Versions.props | 7 +++++-- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index fe7eec37bb..09de5382fb 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -17,13 +17,13 @@ https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage b14b5e956e64fc7de907695a64adba376a48279c - + https://github.com/microsoft/testfx - 689830b314494a93b276672b70e35629d38ce639 + 62a0339db2a558ec8bb67f9f17fe6491ccd56c5b - + https://github.com/microsoft/testfx - 689830b314494a93b276672b70e35629d38ce639 + 62a0339db2a558ec8bb67f9f17fe6491ccd56c5b diff --git a/eng/Versions.props b/eng/Versions.props index f3633e7d69..59434cfb71 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -9,7 +9,10 @@ 10.0.0-beta.25367.4 18.0.0-preview.25367.1 - 3.10.0-preview.25366.15 - 1.8.0-preview.25366.15 + + + + 3.10.0-preview.25367.8 + 1.8.0-preview.25367.8 From 287615bbd144bf1b8fb41625dcb9bf02ffd04bbd Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Sat, 19 Jul 2025 03:13:18 +0000 Subject: [PATCH 255/541] [main] Update dependencies from dotnet/arcade (#6090) [main] Update dependencies from dotnet/arcade --- eng/Version.Details.xml | 12 ++++++------ eng/Versions.props | 4 +--- global.json | 2 +- 3 files changed, 8 insertions(+), 10 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index 09de5382fb..5805393fcb 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -1,17 +1,17 @@ - + https://github.com/dotnet/arcade - d0d479e8a393acf349e860fe728bdbcd3e44b2d7 + d777c20040bdc2e52b372fa98dcb84141ed692d3 - + https://github.com/dotnet/arcade - d0d479e8a393acf349e860fe728bdbcd3e44b2d7 + d777c20040bdc2e52b372fa98dcb84141ed692d3 - + https://github.com/dotnet/arcade - d0d479e8a393acf349e860fe728bdbcd3e44b2d7 + d777c20040bdc2e52b372fa98dcb84141ed692d3 https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage diff --git a/eng/Versions.props b/eng/Versions.props index 59434cfb71..5ae42d82a3 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -7,11 +7,9 @@ preview - 10.0.0-beta.25367.4 + 10.0.0-beta.25367.5 18.0.0-preview.25367.1 - - 3.10.0-preview.25367.8 1.8.0-preview.25367.8 diff --git a/global.json b/global.json index 296502b5e2..0e6ed74a6c 100644 --- a/global.json +++ b/global.json @@ -33,7 +33,7 @@ "rollForward": "latestFeature" }, "msbuild-sdks": { - "Microsoft.DotNet.Arcade.Sdk": "10.0.0-beta.25367.4", + "Microsoft.DotNet.Arcade.Sdk": "10.0.0-beta.25367.5", "MSBuild.Sdk.Extras": "3.0.44" } } From 40b4b2f8a5e66a7d486cc3d43818e61d62e1005f Mon Sep 17 00:00:00 2001 From: dotnet bot Date: Sat, 19 Jul 2025 05:26:30 +0200 Subject: [PATCH 256/541] Localized file check-in by OneLocBuild Task: Build definition ID 1218: Build ID 2753491 --- .../MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.cs.xlf | 2 +- .../MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.es.xlf | 2 +- .../MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.fr.xlf | 2 +- .../MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pl.xlf | 2 +- .../xlf/CodeFixResources.pt-BR.xlf | 2 +- .../xlf/CodeFixResources.zh-Hans.xlf | 2 +- src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf | 6 +++--- src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf | 6 +++--- src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf | 6 +++--- src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf | 6 +++--- src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf | 6 +++--- 11 files changed, 21 insertions(+), 21 deletions(-) diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.cs.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.cs.xlf index e0efdc4f9a..2ae6c3610c 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.cs.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.cs.xlf @@ -29,7 +29,7 @@ Change to 'class' and add '[TestClass]' - Change to 'class' and add '[TestClass]' + Změňte na class a přidejte [TestClass] diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.es.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.es.xlf index 1514c0607b..d07684cc08 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.es.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.es.xlf @@ -29,7 +29,7 @@ Change to 'class' and add '[TestClass]' - Change to 'class' and add '[TestClass]' + Cambiar a "class" y agregar "[TestClass]" diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.fr.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.fr.xlf index 113115ea70..e907d183fa 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.fr.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.fr.xlf @@ -29,7 +29,7 @@ Change to 'class' and add '[TestClass]' - Change to 'class' and add '[TestClass]' + Remplacez par « classe » et ajoutez « [TestClass] » diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pl.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pl.xlf index 19091ac8b0..602784038f 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pl.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pl.xlf @@ -29,7 +29,7 @@ Change to 'class' and add '[TestClass]' - Change to 'class' and add '[TestClass]' + Zmień na wartość „class” i dodaj element „[TestClass]” diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pt-BR.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pt-BR.xlf index 970e7c9fcd..c47d5b1c8d 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pt-BR.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pt-BR.xlf @@ -29,7 +29,7 @@ Change to 'class' and add '[TestClass]' - Change to 'class' and add '[TestClass]' + Alterar para 'classe' e adicionar '[TestClass]' diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hans.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hans.xlf index ae3f469fff..177c517350 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hans.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hans.xlf @@ -29,7 +29,7 @@ Change to 'class' and add '[TestClass]' - Change to 'class' and add '[TestClass]' + 更改为 "class" 并添加 "[TestClass]" diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf index b8317b2b0d..841088788f 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf @@ -751,12 +751,12 @@ Typ deklarující tyto metody by měl také respektovat následující pravidla: Type containing '[TestMethod]' should be marked with '[TestClass]', otherwise the test method will be silently ignored. - Type containing '[TestMethod]' should be marked with '[TestClass]', otherwise the test method will be silently ignored. + Typ obsahující [TestMethod] by měl mít označení [TestClass], jinak se bude testovací metoda bez upozornění ignorovat. Type '{0}' contains test methods and should be marked with '[TestClass]' - Type '{0}' contains test methods and should be marked with '[TestClass]' + Třída {0} obsahuje testovací metody a měla by mít označení [TestClass]. @@ -776,7 +776,7 @@ Typ deklarující tyto metody by měl také respektovat následující pravidla: TestContext parameter is required by MSTest for AssemblyInitialize and ClassInitialize methods - TestContext parameter is required by MSTest for AssemblyInitialize and ClassInitialize methods + Parametr TestContext vyžaduje MSTest pro metody AssemblyInitialize a ClassInitialize. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf index ade02ce357..cbab5ed0ff 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf @@ -751,12 +751,12 @@ Le type doit être une classe Type containing '[TestMethod]' should be marked with '[TestClass]', otherwise the test method will be silently ignored. - Type containing '[TestMethod]' should be marked with '[TestClass]', otherwise the test method will be silently ignored. + Le type contenant « [TestMethod] » doit être marqué avec « [TestClass] », sans quoi la méthode de test sera ignorée silencieusement. Type '{0}' contains test methods and should be marked with '[TestClass]' - Type '{0}' contains test methods and should be marked with '[TestClass]' + Le type « {0} » contient des méthodes de test et doit être marquée avec « [TestClass] » @@ -776,7 +776,7 @@ Le type doit être une classe TestContext parameter is required by MSTest for AssemblyInitialize and ClassInitialize methods - TestContext parameter is required by MSTest for AssemblyInitialize and ClassInitialize methods + Le paramètre TestContext est requis par MSTest pour les méthodes AssemblyInitialize et ClassInitialize diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf index 955670c6d2..a087a3a12c 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf @@ -751,12 +751,12 @@ Typ deklarujący te metody powinien również przestrzegać następujących regu Type containing '[TestMethod]' should be marked with '[TestClass]', otherwise the test method will be silently ignored. - Type containing '[TestMethod]' should be marked with '[TestClass]', otherwise the test method will be silently ignored. + Typ zawierający element „[TestMethod]” powinien być oznaczony znakiem „[TestClass]”. W przeciwnym razie metoda testowa zostanie zignorowana w trybie dyskretnym. Type '{0}' contains test methods and should be marked with '[TestClass]' - Type '{0}' contains test methods and should be marked with '[TestClass]' + Typ „{0}” zawiera metody testowe i powinien być oznaczony znakiem „[TestClass]” @@ -776,7 +776,7 @@ Typ deklarujący te metody powinien również przestrzegać następujących regu TestContext parameter is required by MSTest for AssemblyInitialize and ClassInitialize methods - TestContext parameter is required by MSTest for AssemblyInitialize and ClassInitialize methods + Parametr TestContext jest wymagany przez narzędzie MSTest dla metod AssemblyInitialize i ClassInitialize diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf index 0158a478ac..72e8661844 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf @@ -751,12 +751,12 @@ O tipo que declara esses métodos também deve respeitar as seguintes regras: Type containing '[TestMethod]' should be marked with '[TestClass]', otherwise the test method will be silently ignored. - Type containing '[TestMethod]' should be marked with '[TestClass]', otherwise the test method will be silently ignored. + O tipo que contém '[TestMethod]' deve ser marcado com '[TestClass]', caso contrário, o método de teste será ignorado sem aviso. Type '{0}' contains test methods and should be marked with '[TestClass]' - Type '{0}' contains test methods and should be marked with '[TestClass]' + O tipo '{0}' contém métodos de teste e deve ser marcado com '[TestClass]' @@ -776,7 +776,7 @@ O tipo que declara esses métodos também deve respeitar as seguintes regras: TestContext parameter is required by MSTest for AssemblyInitialize and ClassInitialize methods - TestContext parameter is required by MSTest for AssemblyInitialize and ClassInitialize methods + O parâmetro TestContext é obrigatório para métodos AssemblyInitialize e ClassInitialize do MSTest diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf index e82f1102d0..d2e1588328 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf @@ -751,12 +751,12 @@ The type declaring these methods should also respect the following rules: Type containing '[TestMethod]' should be marked with '[TestClass]', otherwise the test method will be silently ignored. - Type containing '[TestMethod]' should be marked with '[TestClass]', otherwise the test method will be silently ignored. + 应使用 "[TestClass]" 标记包含 "[TestMethod]" 的类型,否则将以静默方式忽略该测试方法。 Type '{0}' contains test methods and should be marked with '[TestClass]' - Type '{0}' contains test methods and should be marked with '[TestClass]' + 类型 "{0}" 包含测试方法,应使用 "[TestClass]" 进行标记 @@ -776,7 +776,7 @@ The type declaring these methods should also respect the following rules: TestContext parameter is required by MSTest for AssemblyInitialize and ClassInitialize methods - TestContext parameter is required by MSTest for AssemblyInitialize and ClassInitialize methods + AssemblyInitialize 和 ClassInitialize 方法的 MSTest 需要 TestContext 参数 From dde3fd14733917bb685ae16945d9ffcd77970e99 Mon Sep 17 00:00:00 2001 From: dotnet bot Date: Sat, 19 Jul 2025 05:30:45 +0200 Subject: [PATCH 257/541] Localized file check-in by OneLocBuild Task: Build definition ID 1218: Build ID 2753491 --- .../Resources/xlf/PlatformResources.cs.xlf | 2 +- .../Resources/xlf/PlatformResources.de.xlf | 2 +- .../Resources/xlf/PlatformResources.es.xlf | 2 +- .../Resources/xlf/PlatformResources.it.xlf | 2 +- .../Resources/xlf/PlatformResources.pt-BR.xlf | 2 +- .../Resources/xlf/PlatformResources.ru.xlf | 2 +- .../Resources/xlf/PlatformResources.tr.xlf | 2 +- .../Resources/xlf/PlatformResources.zh-Hans.xlf | 2 +- .../Resources/xlf/PlatformResources.zh-Hant.xlf | 2 +- 9 files changed, 9 insertions(+), 9 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.cs.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.cs.xlf index 65a1ca1231..2dd7c37384 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.cs.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.cs.xlf @@ -251,7 +251,7 @@ Extensions with the same UID '{0}' have already been registered. Registered extensions are of types: {1} - Extensions with the same UID '{0}' have already been registered. Registered extensions are of types: {1} + Rozšíření se stejným UID {0} již byla zaregistrována. Registrovaná rozšíření jsou těchto typů: {1} diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.de.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.de.xlf index 1b6586cbaf..2901eea04a 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.de.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.de.xlf @@ -251,7 +251,7 @@ Extensions with the same UID '{0}' have already been registered. Registered extensions are of types: {1} - Extensions with the same UID '{0}' have already been registered. Registered extensions are of types: {1} + Erweiterungen mit derselben UID „{0}“ wurden bereits registriert. Registrierte Erweiterungen haben die Typen: {1} diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.es.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.es.xlf index a5261cfe25..613ea681c3 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.es.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.es.xlf @@ -251,7 +251,7 @@ Extensions with the same UID '{0}' have already been registered. Registered extensions are of types: {1} - Extensions with the same UID '{0}' have already been registered. Registered extensions are of types: {1} + Ya se han registrado extensiones con el mismo UID ''{0}". Las extensiones registradas son de los siguientes tipos: {1} diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.it.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.it.xlf index 479b90cfe9..e2b61cae0c 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.it.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.it.xlf @@ -251,7 +251,7 @@ Extensions with the same UID '{0}' have already been registered. Registered extensions are of types: {1} - Extensions with the same UID '{0}' have already been registered. Registered extensions are of types: {1} + Le estensioni con lo stesso UID '{0}' sono già state registrate. Le estensioni registrate sono di tipo: {1} diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pt-BR.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pt-BR.xlf index 568bef524e..a0884e336d 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pt-BR.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pt-BR.xlf @@ -251,7 +251,7 @@ Extensions with the same UID '{0}' have already been registered. Registered extensions are of types: {1} - Extensions with the same UID '{0}' have already been registered. Registered extensions are of types: {1} + Extensões com o mesmo UID '{0}' já foram registradas. As extensões registradas são dos tipos: {1} diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ru.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ru.xlf index 8976701baf..e57b6d1544 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ru.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ru.xlf @@ -251,7 +251,7 @@ Extensions with the same UID '{0}' have already been registered. Registered extensions are of types: {1} - Extensions with the same UID '{0}' have already been registered. Registered extensions are of types: {1} + Расширения с тем же UID "{0}" уже зарегистрированы. Зарегистрированные расширения относятся к следующим типам: {1} diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.tr.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.tr.xlf index 5751338668..4008f64005 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.tr.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.tr.xlf @@ -251,7 +251,7 @@ Extensions with the same UID '{0}' have already been registered. Registered extensions are of types: {1} - Extensions with the same UID '{0}' have already been registered. Registered extensions are of types: {1} + Aynı UID ‘{0}’ ile uzantılar zaten kayıtlıdır. Kayıtlı uzantılar şu türlerde olabilir: {1} diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hans.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hans.xlf index 166f5188e7..5fdcc9180a 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hans.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hans.xlf @@ -251,7 +251,7 @@ Extensions with the same UID '{0}' have already been registered. Registered extensions are of types: {1} - Extensions with the same UID '{0}' have already been registered. Registered extensions are of types: {1} + 已注册具有相同 UID“{0}”的扩展。已注册的扩展类型如下: {1} diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hant.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hant.xlf index dcf6353910..60fd30786c 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hant.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hant.xlf @@ -251,7 +251,7 @@ Extensions with the same UID '{0}' have already been registered. Registered extensions are of types: {1} - Extensions with the same UID '{0}' have already been registered. Registered extensions are of types: {1} + 具有相同 UID '{0}' 的延伸模組已經註冊。已註冊的延伸模組類型為: {1} From bdbf566ae0b38a8b804fe66c9ce32ccf9d153130 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Sat, 19 Jul 2025 15:44:34 +0200 Subject: [PATCH 258/541] Always publish TestResults folder (#6096) --- azure-pipelines-official.yml | 6 ------ azure-pipelines.yml | 9 --------- 2 files changed, 15 deletions(-) diff --git a/azure-pipelines-official.yml b/azure-pipelines-official.yml index c522b12d3f..6af86aa6e3 100644 --- a/azure-pipelines-official.yml +++ b/azure-pipelines-official.yml @@ -171,14 +171,11 @@ extends: Remove-Item -Path $(Build.SourcesDirectory)/artifacts/tmp -Recurse -Force displayName: Remove artifacts/tmp - # This step is only helpful for diagnosing some issues with vstest/test host that would not appear - # through the console or trx - task: 1ES.PublishBuildArtifacts@1 displayName: 'Publish Test Results folders' inputs: PathtoPublish: '$(Build.SourcesDirectory)/artifacts/TestResults/$(_BuildConfig)' ArtifactName: TestResults_Windows - condition: failed() - task: NuGetAuthenticate@1 displayName: 'NuGet Authenticate to test-tools feed' @@ -221,14 +218,11 @@ extends: name: Test displayName: Tests - # This step is only helpful for diagnosing some issues with vstest/test host that would not appear - # through the console or trx - task: 1ES.PublishBuildArtifacts@1 displayName: 'Publish Test Results folders' inputs: PathtoPublish: '$(Build.SourcesDirectory)/artifacts/TestResults/$(_BuildConfig)' ArtifactName: TestResults_Linux - condition: failed() - ${{ if eq(variables['Build.SourceBranchName'], 'main') }}: - template: /eng/common/templates-official/job/onelocbuild.yml@self diff --git a/azure-pipelines.yml b/azure-pipelines.yml index e592a7c4b7..8c10a6e4cc 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -123,14 +123,11 @@ stages: NUGET_PACKAGES: $(Build.SourcesDirectory)/.packages DOTNET_CLI_CONTEXT_VERBOSE: 1 - # This step is only helpful for diagnosing some issues with vstest/test host that would not appear - # through the console or trx - task: PublishBuildArtifacts@1 displayName: 'Publish Test Results folders' inputs: PathtoPublish: '$(Build.SourcesDirectory)/artifacts/TestResults/$(_BuildConfig)' ArtifactName: TestResults_Windows_$(_BuildConfig) - condition: failed() - task: CopyFiles@2 displayName: 'Copy binlogs' @@ -203,14 +200,11 @@ stages: NUGET_PACKAGES: $(Build.SourcesDirectory)/.packages DOTNET_CLI_CONTEXT_VERBOSE: 1 - # This step is only helpful for diagnosing some issues with vstest/test host that would not appear - # through the console or trx - task: PublishBuildArtifacts@1 displayName: 'Publish Test Results folders' inputs: PathtoPublish: '$(Build.SourcesDirectory)/artifacts/TestResults/$(_BuildConfig)' ArtifactName: TestResults_Linux_$(_BuildConfig) - condition: failed() - task: CopyFiles@2 displayName: 'Copy binlogs' @@ -269,14 +263,11 @@ stages: NUGET_PACKAGES: $(Build.SourcesDirectory)/.packages DOTNET_CLI_CONTEXT_VERBOSE: 1 - # This step is only helpful for diagnosing some issues with vstest/test host that would not appear - # through the console or trx - task: PublishBuildArtifacts@1 displayName: 'Publish Test Results folders' inputs: PathtoPublish: '$(Build.SourcesDirectory)/artifacts/TestResults/$(_BuildConfig)' ArtifactName: TestResults_MacOs_$(_BuildConfig) - condition: failed() - task: CopyFiles@2 displayName: 'Copy binlogs' From f3b99ea880143244215fc0304423932f3851ea9a Mon Sep 17 00:00:00 2001 From: dotnet bot Date: Sat, 19 Jul 2025 16:03:07 +0200 Subject: [PATCH 259/541] Localized file check-in by OneLocBuild Task: Build definition ID 1218: Build ID 2753709 --- .../Resources/xlf/PlatformResources.fr.xlf | 2 +- .../Resources/xlf/PlatformResources.ja.xlf | 2 +- .../Resources/xlf/PlatformResources.ko.xlf | 2 +- .../Resources/xlf/PlatformResources.pl.xlf | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.fr.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.fr.xlf index f31ad8f898..6ac9dfb271 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.fr.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.fr.xlf @@ -251,7 +251,7 @@ Extensions with the same UID '{0}' have already been registered. Registered extensions are of types: {1} - Extensions with the same UID '{0}' have already been registered. Registered extensions are of types: {1} + Les extensions ayant le même UID « {0} » ont déjà été enregistrées. Les extensions enregistrées sont de types : {1} diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ja.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ja.xlf index fbe1c19644..1998a73c03 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ja.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ja.xlf @@ -251,7 +251,7 @@ Extensions with the same UID '{0}' have already been registered. Registered extensions are of types: {1} - Extensions with the same UID '{0}' have already been registered. Registered extensions are of types: {1} + 同じ UID '{0}' の拡張機能は既に登録されています。登録済みの拡張機能の種類: {1} diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ko.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ko.xlf index d2f04de4e8..e2d0097ada 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ko.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ko.xlf @@ -251,7 +251,7 @@ Extensions with the same UID '{0}' have already been registered. Registered extensions are of types: {1} - Extensions with the same UID '{0}' have already been registered. Registered extensions are of types: {1} + UID가 '{0}’인 확장이 이미 등록되었습니다. 등록된 확장은 다음과 같은 형식입니다. {1} diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pl.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pl.xlf index de09e5f3df..9f96ada5b5 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pl.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pl.xlf @@ -251,7 +251,7 @@ Extensions with the same UID '{0}' have already been registered. Registered extensions are of types: {1} - Extensions with the same UID '{0}' have already been registered. Registered extensions are of types: {1} + Rozszerzenia o tym samym identyfikatorze UID „{0}” zostały już zarejestrowane. Zarejestrowane rozszerzenia są typu: {1} From 639e5cd9730d9642d93c2828b1e4686a164e040c Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Sat, 19 Jul 2025 16:49:37 +0200 Subject: [PATCH 260/541] Disable flaky test (#6095) --- .../Services/ThreadSafeStringWriterTests.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/ThreadSafeStringWriterTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/ThreadSafeStringWriterTests.cs index a1c3c7f4ee..05d287b9d1 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/ThreadSafeStringWriterTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/ThreadSafeStringWriterTests.cs @@ -84,7 +84,9 @@ public void ThreadSafeStringWriterWritesLinesFromDifferentTasksSeparately() while (exception != null && currentAttempt++ < 3); } - public void ThreadSafeStringWriterWritesLinesIntoDifferentWritesSeparately() +#pragma warning disable IDE0051 // Remove unused private members - Test is flaky. + private void ThreadSafeStringWriterWritesLinesIntoDifferentWritesSeparately() +#pragma warning restore IDE0051 // Remove unused private members { // Suppress the flow of parent context here because this test method will run in // a task already and we don't want the existing async context to interfere with this. From 94835d15a100d237e6fe371d194c5da703fc9a93 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Sat, 19 Jul 2025 18:08:30 +0200 Subject: [PATCH 261/541] Produce test binlogs for official pipeline (#6097) --- azure-pipelines-official.yml | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/azure-pipelines-official.yml b/azure-pipelines-official.yml index 6af86aa6e3..180ed8a1c0 100644 --- a/azure-pipelines-official.yml +++ b/azure-pipelines-official.yml @@ -142,11 +142,11 @@ extends: - ${{ if eq(parameters.SkipTests, False) }}: # -ci is allowing to import some environment variables and some required configurations - # -nobl avoids overwriting build binlog with binlog from tests - script: Test.cmd -configuration $(_BuildConfig) -ci -nobl + /bl:$(BUILD.SOURCESDIRECTORY)\artifacts\TestResults\$(_BuildConfig)\TestStep.binlog name: Test displayName: Test @@ -211,10 +211,9 @@ extends: - ${{ if eq(parameters.SkipTests, False) }}: # -ci is allowing to import some environment variables and some required configurations - # --nobl avoids overwriting build binlog with binlog from tests - script: | chmod +x ./test.sh - ./test.sh --configuration $(_BuildConfig) --ci --test --integrationTest --nobl + ./test.sh --configuration $(_BuildConfig) --ci --test --integrationTest --nobl /bl:$(BUILD.SOURCESDIRECTORY)\artifacts\TestResults\$(_BuildConfig)\TestStep.binlog name: Test displayName: Tests From c974bba68a7f02db2712d768b1c53ee5593e2ec9 Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Sun, 20 Jul 2025 20:41:25 +0200 Subject: [PATCH 262/541] [main] Update dependencies from microsoft/testfx (#6102) Co-authored-by: dotnet-maestro[bot] --- eng/Version.Details.xml | 8 ++++---- eng/Versions.props | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index 5805393fcb..5e5b47edd6 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -17,13 +17,13 @@ https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage b14b5e956e64fc7de907695a64adba376a48279c - + https://github.com/microsoft/testfx - 62a0339db2a558ec8bb67f9f17fe6491ccd56c5b + 639e5cd9730d9642d93c2828b1e4686a164e040c - + https://github.com/microsoft/testfx - 62a0339db2a558ec8bb67f9f17fe6491ccd56c5b + 639e5cd9730d9642d93c2828b1e4686a164e040c diff --git a/eng/Versions.props b/eng/Versions.props index 5ae42d82a3..975d4d378d 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -10,7 +10,7 @@ 10.0.0-beta.25367.5 18.0.0-preview.25367.1 - 3.10.0-preview.25367.8 - 1.8.0-preview.25367.8 + 3.10.0-preview.25369.5 + 1.8.0-preview.25369.5 From 860abb97944315891d960bcf58c5909bc46c47a2 Mon Sep 17 00:00:00 2001 From: Copilot <198982749+Copilot@users.noreply.github.com> Date: Mon, 21 Jul 2025 08:45:02 +0000 Subject: [PATCH 263/541] Change integration test timeouts from 60s to 10000 to improve CI stability (#6088) Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: Youssef1313 <31348972+Youssef1313@users.noreply.github.com> --- .../Microsoft.Testing.TestInfrastructure/CommandLine.cs | 2 +- .../Microsoft.Testing.TestInfrastructure/DotnetCli.cs | 2 +- .../Microsoft.Testing.TestInfrastructure/DotnetMuxer.cs | 4 ++-- .../Microsoft.Testing.TestInfrastructure/TestHost.cs | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/test/Utilities/Microsoft.Testing.TestInfrastructure/CommandLine.cs b/test/Utilities/Microsoft.Testing.TestInfrastructure/CommandLine.cs index 8594a61021..d2e33f7df4 100644 --- a/test/Utilities/Microsoft.Testing.TestInfrastructure/CommandLine.cs +++ b/test/Utilities/Microsoft.Testing.TestInfrastructure/CommandLine.cs @@ -72,7 +72,7 @@ public async Task RunAsyncAndReturnExitCodeAsync( IDictionary? environmentVariables = null, string? workingDirectory = null, bool cleanDefaultEnvironmentVariableIfCustomAreProvided = false, - int timeoutInSeconds = 60) + int timeoutInSeconds = 10000) { await s_maxOutstandingCommands_semaphore.WaitAsync(); try diff --git a/test/Utilities/Microsoft.Testing.TestInfrastructure/DotnetCli.cs b/test/Utilities/Microsoft.Testing.TestInfrastructure/DotnetCli.cs index 03ec18f867..61ec18e1b8 100644 --- a/test/Utilities/Microsoft.Testing.TestInfrastructure/DotnetCli.cs +++ b/test/Utilities/Microsoft.Testing.TestInfrastructure/DotnetCli.cs @@ -54,7 +54,7 @@ public static async Task RunAsync( Dictionary? environmentVariables = null, bool failIfReturnValueIsNotZero = true, bool disableTelemetry = true, - int timeoutInSeconds = 60, + int timeoutInSeconds = 10000, int retryCount = 5, bool disableCodeCoverage = true, bool warnAsError = true, diff --git a/test/Utilities/Microsoft.Testing.TestInfrastructure/DotnetMuxer.cs b/test/Utilities/Microsoft.Testing.TestInfrastructure/DotnetMuxer.cs index 6be55cb242..c799142b28 100644 --- a/test/Utilities/Microsoft.Testing.TestInfrastructure/DotnetMuxer.cs +++ b/test/Utilities/Microsoft.Testing.TestInfrastructure/DotnetMuxer.cs @@ -92,14 +92,14 @@ protected virtual void Dispose(bool disposing) _isDisposed = true; } - public async Task ExecuteAsync(string arguments, string? workingDirectory = null, int timeoutInSeconds = 60) + public async Task ExecuteAsync(string arguments, string? workingDirectory = null, int timeoutInSeconds = 10000) => await ExecuteAsync(arguments, workingDirectory, _environmentVariables, timeoutInSeconds); public async Task ExecuteAsync( string arguments, string? workingDirectory, IDictionary environmentVariables, - int timeoutInSeconds = 60) + int timeoutInSeconds = 10000) => await _commandLine.RunAsyncAndReturnExitCodeAsync( $"{_dotnet} {arguments}", environmentVariables, diff --git a/test/Utilities/Microsoft.Testing.TestInfrastructure/TestHost.cs b/test/Utilities/Microsoft.Testing.TestInfrastructure/TestHost.cs index e81575f584..4187c76c72 100644 --- a/test/Utilities/Microsoft.Testing.TestInfrastructure/TestHost.cs +++ b/test/Utilities/Microsoft.Testing.TestInfrastructure/TestHost.cs @@ -41,7 +41,7 @@ public async Task ExecuteAsync( string? command = null, Dictionary? environmentVariables = null, bool disableTelemetry = true, - int timeoutSeconds = 60) + int timeoutSeconds = 10000) { await s_maxOutstandingExecutions_semaphore.WaitAsync(); try From 736a1ae0c93f8524e64119d9fa7c670a7b36d740 Mon Sep 17 00:00:00 2001 From: Copilot <198982749+Copilot@users.noreply.github.com> Date: Mon, 21 Jul 2025 11:18:23 +0000 Subject: [PATCH 264/541] Add analyzer for incorrect TestContext property usage in fixture methods (#5990) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: Youssef1313 <31348972+Youssef1313@users.noreply.github.com> Co-authored-by: Youssef1313 Co-authored-by: Amaury Levé --- .../AnalyzerReleases.Unshipped.md | 1 + .../MSTest.Analyzers/Helpers/DiagnosticIds.cs | 1 + .../MSTest.Analyzers/PublicAPI.Unshipped.txt | 4 + .../MSTest.Analyzers/Resources.Designer.cs | 27 ++ src/Analyzers/MSTest.Analyzers/Resources.resx | 9 + .../TestContextPropertyUsageAnalyzer.cs | 128 +++++++++ .../MSTest.Analyzers/xlf/Resources.cs.xlf | 15 + .../MSTest.Analyzers/xlf/Resources.de.xlf | 15 + .../MSTest.Analyzers/xlf/Resources.es.xlf | 15 + .../MSTest.Analyzers/xlf/Resources.fr.xlf | 15 + .../MSTest.Analyzers/xlf/Resources.it.xlf | 15 + .../MSTest.Analyzers/xlf/Resources.ja.xlf | 15 + .../MSTest.Analyzers/xlf/Resources.ko.xlf | 15 + .../MSTest.Analyzers/xlf/Resources.pl.xlf | 15 + .../MSTest.Analyzers/xlf/Resources.pt-BR.xlf | 15 + .../MSTest.Analyzers/xlf/Resources.ru.xlf | 15 + .../MSTest.Analyzers/xlf/Resources.tr.xlf | 15 + .../xlf/Resources.zh-Hans.xlf | 15 + .../xlf/Resources.zh-Hant.xlf | 15 + ...semblyCleanupShouldBeValidAnalyzerTests.cs | 2 + ...blyInitializeShouldBeValidAnalyzerTests.cs | 2 + .../ClassCleanupShouldBeValidAnalyzerTests.cs | 2 + ...assInitializeShouldBeValidAnalyzerTests.cs | 2 + ...oNotStoreStaticTestContextAnalyzerTests.cs | 2 + .../DynamicDataShouldBeValidAnalyzerTests.cs | 2 + .../MSTest.Analyzers.UnitTests.csproj | 3 +- ...eferDisposeOverTestCleanupAnalyzerTests.cs | 4 + ...eferTestCleanupOverDisposeAnalyzerTests.cs | 2 + .../MSTest.Analyzers.UnitTests/Program.cs | 2 + .../TestCleanupShouldBeValidAnalyzerTests.cs | 2 + .../TestContextPropertyUsageAnalyzerTests.cs | 259 ++++++++++++++++++ ...estInitializeShouldBeValidAnalyzerTests.cs | 2 + .../TestMethodShouldBeValidAnalyzerTests.cs | 2 + .../UseParallelizeAttributeAnalyzerTests.cs | 2 + .../Verifiers/CSharpCodeFixVerifier`2+Test.cs | 6 + 35 files changed, 660 insertions(+), 1 deletion(-) create mode 100644 src/Analyzers/MSTest.Analyzers/TestContextPropertyUsageAnalyzer.cs create mode 100644 test/UnitTests/MSTest.Analyzers.UnitTests/TestContextPropertyUsageAnalyzerTests.cs diff --git a/src/Analyzers/MSTest.Analyzers/AnalyzerReleases.Unshipped.md b/src/Analyzers/MSTest.Analyzers/AnalyzerReleases.Unshipped.md index 0adb7548d8..ff09804347 100644 --- a/src/Analyzers/MSTest.Analyzers/AnalyzerReleases.Unshipped.md +++ b/src/Analyzers/MSTest.Analyzers/AnalyzerReleases.Unshipped.md @@ -8,6 +8,7 @@ Rule ID | Category | Severity | Notes MSTEST0044 | Design | Warning | PreferTestMethodOverDataTestMethodAnalyzer, [Documentation](https://learn.microsoft.com/dotnet/core/testing/mstest-analyzers/mstest0044) MSTEST0045 | Usage | Info | UseCooperativeCancellationForTimeoutAnalyzer, [Documentation](https://learn.microsoft.com/dotnet/core/testing/mstest-analyzers/mstest0045) MSTEST0046 | Usage | Info | StringAssertToAssertAnalyzer, [Documentation](https://learn.microsoft.com/dotnet/core/testing/mstest-analyzers/mstest0046) +MSTEST0048 | Usage | Warning | TestContextPropertyUsageAnalyzer, [Documentation](https://learn.microsoft.com/dotnet/core/testing/mstest-analyzers/mstest0047) ### Changed Rules diff --git a/src/Analyzers/MSTest.Analyzers/Helpers/DiagnosticIds.cs b/src/Analyzers/MSTest.Analyzers/Helpers/DiagnosticIds.cs index 4d53ecde3a..43d50724e4 100644 --- a/src/Analyzers/MSTest.Analyzers/Helpers/DiagnosticIds.cs +++ b/src/Analyzers/MSTest.Analyzers/Helpers/DiagnosticIds.cs @@ -52,4 +52,5 @@ internal static class DiagnosticIds public const string UseCooperativeCancellationForTimeoutRuleId = "MSTEST0045"; public const string StringAssertToAssertRuleId = "MSTEST0046"; public const string UnusedParameterSuppressorRuleId = "MSTEST0047"; + public const string TestContextPropertyUsageRuleId = "MSTEST0048"; } diff --git a/src/Analyzers/MSTest.Analyzers/PublicAPI.Unshipped.txt b/src/Analyzers/MSTest.Analyzers/PublicAPI.Unshipped.txt index 661b930e2b..462739b1d3 100644 --- a/src/Analyzers/MSTest.Analyzers/PublicAPI.Unshipped.txt +++ b/src/Analyzers/MSTest.Analyzers/PublicAPI.Unshipped.txt @@ -11,3 +11,7 @@ MSTest.Analyzers.UnusedParameterSuppressor MSTest.Analyzers.UnusedParameterSuppressor.UnusedParameterSuppressor() -> void override MSTest.Analyzers.UnusedParameterSuppressor.ReportSuppressions(Microsoft.CodeAnalysis.Diagnostics.SuppressionAnalysisContext context) -> void override MSTest.Analyzers.UnusedParameterSuppressor.SupportedSuppressions.get -> System.Collections.Immutable.ImmutableArray +MSTest.Analyzers.TestContextPropertyUsageAnalyzer +MSTest.Analyzers.TestContextPropertyUsageAnalyzer.TestContextPropertyUsageAnalyzer() -> void +override MSTest.Analyzers.TestContextPropertyUsageAnalyzer.Initialize(Microsoft.CodeAnalysis.Diagnostics.AnalysisContext! context) -> void +override MSTest.Analyzers.TestContextPropertyUsageAnalyzer.SupportedDiagnostics.get -> System.Collections.Immutable.ImmutableArray diff --git a/src/Analyzers/MSTest.Analyzers/Resources.Designer.cs b/src/Analyzers/MSTest.Analyzers/Resources.Designer.cs index 6c5ee95586..9945dfaa28 100644 --- a/src/Analyzers/MSTest.Analyzers/Resources.Designer.cs +++ b/src/Analyzers/MSTest.Analyzers/Resources.Designer.cs @@ -1302,5 +1302,32 @@ internal static string UseRetryWithTestMethodTitle { return ResourceManager.GetString("UseRetryWithTestMethodTitle", resourceCulture); } } + + /// + /// Looks up a localized string similar to TestContext property cannot be accessed in this context. + /// + internal static string TestContextPropertyUsageTitle { + get { + return ResourceManager.GetString("TestContextPropertyUsageTitle", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to TestContext property '{0}' cannot be accessed in '{1}' method. + /// + internal static string TestContextPropertyUsageMessageFormat { + get { + return ResourceManager.GetString("TestContextPropertyUsageMessageFormat", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Some TestContext properties are only available during test execution and cannot be accessed in assembly initialize, class initialize, class cleanup, or assembly cleanup methods. + /// + internal static string TestContextPropertyUsageDescription { + get { + return ResourceManager.GetString("TestContextPropertyUsageDescription", resourceCulture); + } + } } } diff --git a/src/Analyzers/MSTest.Analyzers/Resources.resx b/src/Analyzers/MSTest.Analyzers/Resources.resx index c07751049e..c21184b023 100644 --- a/src/Analyzers/MSTest.Analyzers/Resources.resx +++ b/src/Analyzers/MSTest.Analyzers/Resources.resx @@ -615,4 +615,13 @@ The type declaring these methods should also respect the following rules: Using '[Timeout]' without explicitly setting 'CooperativeCancellation = true' is discouraged. In a future version, cooperative cancellation will become the default behavior. Set 'CooperativeCancellation = true' to opt into the recommended behavior and avoid breaking changes. + + TestContext property cannot be accessed in this context + + + TestContext property '{0}' cannot be accessed in '{1}' method + + + Some TestContext properties are only available during test execution and cannot be accessed in assembly initialize, class initialize, class cleanup, or assembly cleanup methods. + diff --git a/src/Analyzers/MSTest.Analyzers/TestContextPropertyUsageAnalyzer.cs b/src/Analyzers/MSTest.Analyzers/TestContextPropertyUsageAnalyzer.cs new file mode 100644 index 0000000000..1cedf89c78 --- /dev/null +++ b/src/Analyzers/MSTest.Analyzers/TestContextPropertyUsageAnalyzer.cs @@ -0,0 +1,128 @@ +// 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.Immutable; + +using Analyzer.Utilities.Extensions; + +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Diagnostics; +using Microsoft.CodeAnalysis.Operations; + +using MSTest.Analyzers.Helpers; + +namespace MSTest.Analyzers; + +/// +/// MSTEST0047: . +/// +[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] +public sealed class TestContextPropertyUsageAnalyzer : DiagnosticAnalyzer +{ + private static readonly LocalizableResourceString Title = new(nameof(Resources.TestContextPropertyUsageTitle), Resources.ResourceManager, typeof(Resources)); + private static readonly LocalizableResourceString MessageFormat = new(nameof(Resources.TestContextPropertyUsageMessageFormat), Resources.ResourceManager, typeof(Resources)); + private static readonly LocalizableResourceString Description = new(nameof(Resources.TestContextPropertyUsageDescription), Resources.ResourceManager, typeof(Resources)); + + internal static readonly DiagnosticDescriptor Rule = DiagnosticDescriptorHelper.Create( + DiagnosticIds.TestContextPropertyUsageRuleId, + Title, + MessageFormat, + Description, + Category.Usage, + DiagnosticSeverity.Warning, + isEnabledByDefault: true); + + /// + public override ImmutableArray SupportedDiagnostics { get; } = ImmutableArray.Create(Rule); + + // Properties that cannot be accessed in assembly initialize, class initialize, class cleanup, or assembly cleanup + private static readonly ImmutableHashSet RestrictedInAllFixtureMethods = ImmutableHashSet.Create( + StringComparer.Ordinal, + "TestData", + "TestDisplayName", + "DataRow", + "DataConnection", + "TestName", + "ManagedMethod"); + + // Properties that cannot be accessed in assembly initialize or assembly cleanup + private static readonly ImmutableHashSet RestrictedInAssemblyMethods = ImmutableHashSet.Create( + StringComparer.Ordinal, + "FullyQualifiedTestClassName", + "ManagedType"); + + /// + public override void Initialize(AnalysisContext context) + { + context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); + context.EnableConcurrentExecution(); + + context.RegisterCompilationStartAction(context => + { + if (!context.Compilation.TryGetOrCreateTypeByMetadataName(WellKnownTypeNames.MicrosoftVisualStudioTestToolsUnitTestingTestContext, out INamedTypeSymbol? testContextSymbol) + || !context.Compilation.TryGetOrCreateTypeByMetadataName(WellKnownTypeNames.MicrosoftVisualStudioTestToolsUnitTestingAssemblyInitializeAttribute, out INamedTypeSymbol? assemblyInitializeAttributeSymbol) + || !context.Compilation.TryGetOrCreateTypeByMetadataName(WellKnownTypeNames.MicrosoftVisualStudioTestToolsUnitTestingAssemblyCleanupAttribute, out INamedTypeSymbol? assemblyCleanupAttributeSymbol) + || !context.Compilation.TryGetOrCreateTypeByMetadataName(WellKnownTypeNames.MicrosoftVisualStudioTestToolsUnitTestingClassInitializeAttribute, out INamedTypeSymbol? classInitializeAttributeSymbol) + || !context.Compilation.TryGetOrCreateTypeByMetadataName(WellKnownTypeNames.MicrosoftVisualStudioTestToolsUnitTestingClassCleanupAttribute, out INamedTypeSymbol? classCleanupAttributeSymbol)) + { + return; + } + + context.RegisterOperationAction(context => AnalyzePropertyReference(context, testContextSymbol, assemblyInitializeAttributeSymbol, assemblyCleanupAttributeSymbol, classInitializeAttributeSymbol, classCleanupAttributeSymbol), OperationKind.PropertyReference); + }); + } + + private static void AnalyzePropertyReference( + OperationAnalysisContext context, + INamedTypeSymbol testContextSymbol, + INamedTypeSymbol assemblyInitializeAttributeSymbol, + INamedTypeSymbol assemblyCleanupAttributeSymbol, + INamedTypeSymbol classInitializeAttributeSymbol, + INamedTypeSymbol classCleanupAttributeSymbol) + { + var propertyReference = (IPropertyReferenceOperation)context.Operation; + + // Check if the property is a TestContext property + if (!SymbolEqualityComparer.Default.Equals(propertyReference.Property.ContainingType, testContextSymbol)) + { + return; + } + + string propertyName = propertyReference.Property.Name; + + // Check if we're in a forbidden context + if (context.ContainingSymbol is not IMethodSymbol containingMethod) + { + return; + } + + // Check for assembly initialize/cleanup methods + bool isAssemblyInitialize = containingMethod.HasAttribute(assemblyInitializeAttributeSymbol); + bool isAssemblyCleanup = containingMethod.HasAttribute(assemblyCleanupAttributeSymbol); + bool isClassInitialize = containingMethod.HasAttribute(classInitializeAttributeSymbol); + bool isClassCleanup = containingMethod.HasAttribute(classCleanupAttributeSymbol); + + bool isInAssemblyMethod = isAssemblyInitialize || isAssemblyCleanup; + bool isInFixtureMethod = isInAssemblyMethod || isClassInitialize || isClassCleanup; + + // Check if the property is restricted in the current context + if (isInFixtureMethod && RestrictedInAllFixtureMethods.Contains(propertyName)) + { + context.ReportDiagnostic(propertyReference.CreateDiagnostic(Rule, propertyName, GetMethodType(isAssemblyInitialize, isAssemblyCleanup, isClassInitialize, isClassCleanup))); + } + else if (isInAssemblyMethod && RestrictedInAssemblyMethods.Contains(propertyName)) + { + context.ReportDiagnostic(propertyReference.CreateDiagnostic(Rule, propertyName, GetMethodType(isAssemblyInitialize, isAssemblyCleanup, isClassInitialize, isClassCleanup))); + } + } + + private static string GetMethodType(bool isAssemblyInitialize, bool isAssemblyCleanup, bool isClassInitialize, bool isClassCleanup) + => (isAssemblyInitialize, isAssemblyCleanup, isClassInitialize, isClassCleanup) switch + { + (true, _, _, _) => "AssemblyInitialize", + (_, true, _, _) => "AssemblyCleanup", + (_, _, true, _) => "ClassInitialize", + (_, _, _, true) => "ClassCleanup", + _ => "unknown", + }; +} diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf index 841088788f..02fbb5012a 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf @@ -869,6 +869,21 @@ Typ deklarující tyto metody by měl také respektovat následující pravidla: Použití atributu opakování u testovací metody + + TestContext property cannot be accessed in this context + TestContext property cannot be accessed in this context + + + + TestContext property '{0}' cannot be accessed in '{1}' method + TestContext property '{0}' cannot be accessed in '{1}' method + + + + Some TestContext properties are only available during test execution and cannot be accessed in assembly initialize, class initialize, class cleanup, or assembly cleanup methods. + Some TestContext properties are only available during test execution and cannot be accessed in assembly initialize, class initialize, class cleanup, or assembly cleanup methods. + + \ No newline at end of file diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf index 334ec9673c..add305ccd7 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf @@ -870,6 +870,21 @@ Der Typ, der diese Methoden deklariert, sollte auch die folgenden Regeln beachte Verwenden des Wiederholungsattributs für die Testmethode + + TestContext property cannot be accessed in this context + TestContext property cannot be accessed in this context + + + + TestContext property '{0}' cannot be accessed in '{1}' method + TestContext property '{0}' cannot be accessed in '{1}' method + + + + Some TestContext properties are only available during test execution and cannot be accessed in assembly initialize, class initialize, class cleanup, or assembly cleanup methods. + Some TestContext properties are only available during test execution and cannot be accessed in assembly initialize, class initialize, class cleanup, or assembly cleanup methods. + + \ No newline at end of file diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf index 52aa817f79..0f4618d872 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf @@ -869,6 +869,21 @@ El tipo que declara estos métodos también debe respetar las reglas siguientes: Usar el atributo de reintento en el método de prueba + + TestContext property cannot be accessed in this context + TestContext property cannot be accessed in this context + + + + TestContext property '{0}' cannot be accessed in '{1}' method + TestContext property '{0}' cannot be accessed in '{1}' method + + + + Some TestContext properties are only available during test execution and cannot be accessed in assembly initialize, class initialize, class cleanup, or assembly cleanup methods. + Some TestContext properties are only available during test execution and cannot be accessed in assembly initialize, class initialize, class cleanup, or assembly cleanup methods. + + \ No newline at end of file diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf index cbab5ed0ff..1e2c0d9f70 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf @@ -869,6 +869,21 @@ Le type doit être une classe Utilisez l’attribut de nouvelle tentative sur la méthode de test + + TestContext property cannot be accessed in this context + TestContext property cannot be accessed in this context + + + + TestContext property '{0}' cannot be accessed in '{1}' method + TestContext property '{0}' cannot be accessed in '{1}' method + + + + Some TestContext properties are only available during test execution and cannot be accessed in assembly initialize, class initialize, class cleanup, or assembly cleanup methods. + Some TestContext properties are only available during test execution and cannot be accessed in assembly initialize, class initialize, class cleanup, or assembly cleanup methods. + + \ No newline at end of file diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf index 63313320c4..2e69adbeab 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf @@ -869,6 +869,21 @@ Anche il tipo che dichiara questi metodi deve rispettare le regole seguenti: Utilizzare l'attributo di ripetizione nel metodo di test + + TestContext property cannot be accessed in this context + TestContext property cannot be accessed in this context + + + + TestContext property '{0}' cannot be accessed in '{1}' method + TestContext property '{0}' cannot be accessed in '{1}' method + + + + Some TestContext properties are only available during test execution and cannot be accessed in assembly initialize, class initialize, class cleanup, or assembly cleanup methods. + Some TestContext properties are only available during test execution and cannot be accessed in assembly initialize, class initialize, class cleanup, or assembly cleanup methods. + + \ No newline at end of file diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf index 6b39979e25..3094fd9e81 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf @@ -869,6 +869,21 @@ The type declaring these methods should also respect the following rules: テスト メソッドで retry 属性を使用する + + TestContext property cannot be accessed in this context + TestContext property cannot be accessed in this context + + + + TestContext property '{0}' cannot be accessed in '{1}' method + TestContext property '{0}' cannot be accessed in '{1}' method + + + + Some TestContext properties are only available during test execution and cannot be accessed in assembly initialize, class initialize, class cleanup, or assembly cleanup methods. + Some TestContext properties are only available during test execution and cannot be accessed in assembly initialize, class initialize, class cleanup, or assembly cleanup methods. + + \ No newline at end of file diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf index 2159d694db..119fd7fa19 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf @@ -869,6 +869,21 @@ The type declaring these methods should also respect the following rules: 테스트 메서드에 재시도 속성 사용 + + TestContext property cannot be accessed in this context + TestContext property cannot be accessed in this context + + + + TestContext property '{0}' cannot be accessed in '{1}' method + TestContext property '{0}' cannot be accessed in '{1}' method + + + + Some TestContext properties are only available during test execution and cannot be accessed in assembly initialize, class initialize, class cleanup, or assembly cleanup methods. + Some TestContext properties are only available during test execution and cannot be accessed in assembly initialize, class initialize, class cleanup, or assembly cleanup methods. + + \ No newline at end of file diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf index a087a3a12c..3dfa3d4c0a 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf @@ -869,6 +869,21 @@ Typ deklarujący te metody powinien również przestrzegać następujących regu Użyj atrybutu ponawiania dla metody testowej + + TestContext property cannot be accessed in this context + TestContext property cannot be accessed in this context + + + + TestContext property '{0}' cannot be accessed in '{1}' method + TestContext property '{0}' cannot be accessed in '{1}' method + + + + Some TestContext properties are only available during test execution and cannot be accessed in assembly initialize, class initialize, class cleanup, or assembly cleanup methods. + Some TestContext properties are only available during test execution and cannot be accessed in assembly initialize, class initialize, class cleanup, or assembly cleanup methods. + + \ No newline at end of file diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf index 72e8661844..5e85f598b5 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf @@ -869,6 +869,21 @@ O tipo que declara esses métodos também deve respeitar as seguintes regras: Usar o atributo de repetição no método de teste + + TestContext property cannot be accessed in this context + TestContext property cannot be accessed in this context + + + + TestContext property '{0}' cannot be accessed in '{1}' method + TestContext property '{0}' cannot be accessed in '{1}' method + + + + Some TestContext properties are only available during test execution and cannot be accessed in assembly initialize, class initialize, class cleanup, or assembly cleanup methods. + Some TestContext properties are only available during test execution and cannot be accessed in assembly initialize, class initialize, class cleanup, or assembly cleanup methods. + + \ No newline at end of file diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf index e1b2b5f5dc..60dc6019e3 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf @@ -881,6 +881,21 @@ The type declaring these methods should also respect the following rules: Использовать атрибут retry в тестовом методе + + TestContext property cannot be accessed in this context + TestContext property cannot be accessed in this context + + + + TestContext property '{0}' cannot be accessed in '{1}' method + TestContext property '{0}' cannot be accessed in '{1}' method + + + + Some TestContext properties are only available during test execution and cannot be accessed in assembly initialize, class initialize, class cleanup, or assembly cleanup methods. + Some TestContext properties are only available during test execution and cannot be accessed in assembly initialize, class initialize, class cleanup, or assembly cleanup methods. + + \ No newline at end of file diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf index a4e99e3592..d1fd2bbc3f 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf @@ -871,6 +871,21 @@ Bu yöntemleri bildiren tipin ayrıca aşağıdaki kurallara uyması gerekir: Test yönteminde yeniden deneme özniteliğini kullan + + TestContext property cannot be accessed in this context + TestContext property cannot be accessed in this context + + + + TestContext property '{0}' cannot be accessed in '{1}' method + TestContext property '{0}' cannot be accessed in '{1}' method + + + + Some TestContext properties are only available during test execution and cannot be accessed in assembly initialize, class initialize, class cleanup, or assembly cleanup methods. + Some TestContext properties are only available during test execution and cannot be accessed in assembly initialize, class initialize, class cleanup, or assembly cleanup methods. + + \ No newline at end of file diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf index d2e1588328..34953062c7 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf @@ -869,6 +869,21 @@ The type declaring these methods should also respect the following rules: 对测试方法使用重试属性 + + TestContext property cannot be accessed in this context + TestContext property cannot be accessed in this context + + + + TestContext property '{0}' cannot be accessed in '{1}' method + TestContext property '{0}' cannot be accessed in '{1}' method + + + + Some TestContext properties are only available during test execution and cannot be accessed in assembly initialize, class initialize, class cleanup, or assembly cleanup methods. + Some TestContext properties are only available during test execution and cannot be accessed in assembly initialize, class initialize, class cleanup, or assembly cleanup methods. + + \ No newline at end of file diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf index 2f75f2e35b..182a4b2d03 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf @@ -869,6 +869,21 @@ The type declaring these methods should also respect the following rules: 在測試方法上使用重試屬性 + + TestContext property cannot be accessed in this context + TestContext property cannot be accessed in this context + + + + TestContext property '{0}' cannot be accessed in '{1}' method + TestContext property '{0}' cannot be accessed in '{1}' method + + + + Some TestContext properties are only available during test execution and cannot be accessed in assembly initialize, class initialize, class cleanup, or assembly cleanup methods. + Some TestContext properties are only available during test execution and cannot be accessed in assembly initialize, class initialize, class cleanup, or assembly cleanup methods. + + \ No newline at end of file diff --git a/test/UnitTests/MSTest.Analyzers.UnitTests/AssemblyCleanupShouldBeValidAnalyzerTests.cs b/test/UnitTests/MSTest.Analyzers.UnitTests/AssemblyCleanupShouldBeValidAnalyzerTests.cs index 44aba361df..7ca5537617 100644 --- a/test/UnitTests/MSTest.Analyzers.UnitTests/AssemblyCleanupShouldBeValidAnalyzerTests.cs +++ b/test/UnitTests/MSTest.Analyzers.UnitTests/AssemblyCleanupShouldBeValidAnalyzerTests.cs @@ -261,6 +261,7 @@ public static void AssemblyCleanup(TestContext testContext) await VerifyCS.VerifyCodeFixAsync(code, code); } +#if NET [TestMethod] public async Task WhenAssemblyCleanupReturnTypeIsNotValid_Diagnostic() { @@ -400,6 +401,7 @@ public static ValueTask AssemblyCleanup2() await VerifyCS.VerifyAnalyzerAsync(code); } +#endif [TestMethod] public async Task WhenAssemblyCleanupIsAsyncVoid_Diagnostic() diff --git a/test/UnitTests/MSTest.Analyzers.UnitTests/AssemblyInitializeShouldBeValidAnalyzerTests.cs b/test/UnitTests/MSTest.Analyzers.UnitTests/AssemblyInitializeShouldBeValidAnalyzerTests.cs index e7ffa9a0fe..48acceee09 100644 --- a/test/UnitTests/MSTest.Analyzers.UnitTests/AssemblyInitializeShouldBeValidAnalyzerTests.cs +++ b/test/UnitTests/MSTest.Analyzers.UnitTests/AssemblyInitializeShouldBeValidAnalyzerTests.cs @@ -277,6 +277,7 @@ await VerifyCS.VerifyCodeFixAsync( fixedCode); } +#if NET [TestMethod] public async Task WhenAssemblyInitializeReturnTypeIsNotValid_Diagnostic() { @@ -412,6 +413,7 @@ public static ValueTask AssemblyInitialize2(TestContext testContext) await VerifyCS.VerifyAnalyzerAsync(code); } +#endif [TestMethod] public async Task WhenAssemblyInitializeIsAsyncVoid_Diagnostic() diff --git a/test/UnitTests/MSTest.Analyzers.UnitTests/ClassCleanupShouldBeValidAnalyzerTests.cs b/test/UnitTests/MSTest.Analyzers.UnitTests/ClassCleanupShouldBeValidAnalyzerTests.cs index bf5c6d78d3..a6693c6028 100644 --- a/test/UnitTests/MSTest.Analyzers.UnitTests/ClassCleanupShouldBeValidAnalyzerTests.cs +++ b/test/UnitTests/MSTest.Analyzers.UnitTests/ClassCleanupShouldBeValidAnalyzerTests.cs @@ -302,6 +302,7 @@ public static void ClassCleanup(TestContext testContext) await VerifyCS.VerifyCodeFixAsync(code, code); } +#if NET [TestMethod] public async Task WhenClassCleanupReturnTypeIsNotValid_Diagnostic() { @@ -409,6 +410,7 @@ public static ValueTask ClassCleanup2() await VerifyCS.VerifyAnalyzerAsync(code); } +#endif [TestMethod] public async Task WhenClassCleanupIsAsyncVoid_Diagnostic() diff --git a/test/UnitTests/MSTest.Analyzers.UnitTests/ClassInitializeShouldBeValidAnalyzerTests.cs b/test/UnitTests/MSTest.Analyzers.UnitTests/ClassInitializeShouldBeValidAnalyzerTests.cs index 55cc137e6f..9e279b7ac4 100644 --- a/test/UnitTests/MSTest.Analyzers.UnitTests/ClassInitializeShouldBeValidAnalyzerTests.cs +++ b/test/UnitTests/MSTest.Analyzers.UnitTests/ClassInitializeShouldBeValidAnalyzerTests.cs @@ -320,6 +320,7 @@ await VerifyCS.VerifyCodeFixAsync( fixedCode); } +#if NET [TestMethod] public async Task WhenClassInitializeReturnTypeIsNotValid_Diagnostic() { @@ -427,6 +428,7 @@ public static ValueTask ClassInitialize2(TestContext testContext) await VerifyCS.VerifyAnalyzerAsync(code); } +#endif [TestMethod] public async Task WhenClassInitializeIsAsyncVoid_Diagnostic() diff --git a/test/UnitTests/MSTest.Analyzers.UnitTests/DoNotStoreStaticTestContextAnalyzerTests.cs b/test/UnitTests/MSTest.Analyzers.UnitTests/DoNotStoreStaticTestContextAnalyzerTests.cs index f0c3590176..0ad128b738 100644 --- a/test/UnitTests/MSTest.Analyzers.UnitTests/DoNotStoreStaticTestContextAnalyzerTests.cs +++ b/test/UnitTests/MSTest.Analyzers.UnitTests/DoNotStoreStaticTestContextAnalyzerTests.cs @@ -10,6 +10,7 @@ namespace MSTest.Analyzers.Test; [TestClass] public sealed class DoNotStoreStaticTestContextAnalyzerTests { +#if NET [TestMethod] public async Task WhenAssemblyInitializeOrClassInitialize_Diagnostic() { @@ -87,6 +88,7 @@ public static ValueTask ClassInit(TestContext tc) await VerifyCS.VerifyAnalyzerAsync(code); } +#endif [TestMethod] public async Task WhenOtherTestContext_NoDiagnostic() diff --git a/test/UnitTests/MSTest.Analyzers.UnitTests/DynamicDataShouldBeValidAnalyzerTests.cs b/test/UnitTests/MSTest.Analyzers.UnitTests/DynamicDataShouldBeValidAnalyzerTests.cs index ee825e62da..75d851eb83 100644 --- a/test/UnitTests/MSTest.Analyzers.UnitTests/DynamicDataShouldBeValidAnalyzerTests.cs +++ b/test/UnitTests/MSTest.Analyzers.UnitTests/DynamicDataShouldBeValidAnalyzerTests.cs @@ -202,6 +202,7 @@ public class SomeClass await VerifyCS.VerifyAnalyzerAsync(code); } +#if NET [TestMethod] public async Task WhenDataIsIEnumerableValueTuple_NoDiagnostic() { @@ -273,6 +274,7 @@ public class SomeClass """; await VerifyCS.VerifyAnalyzerAsync(code); } +#endif [TestMethod] public async Task WhenDataIsJaggedArrays_NoDiagnostic() diff --git a/test/UnitTests/MSTest.Analyzers.UnitTests/MSTest.Analyzers.UnitTests.csproj b/test/UnitTests/MSTest.Analyzers.UnitTests/MSTest.Analyzers.UnitTests.csproj index cc5a99e741..555c1372a1 100644 --- a/test/UnitTests/MSTest.Analyzers.UnitTests/MSTest.Analyzers.UnitTests.csproj +++ b/test/UnitTests/MSTest.Analyzers.UnitTests/MSTest.Analyzers.UnitTests.csproj @@ -1,7 +1,8 @@  - net6.0 + net462;net6.0 + net6.0 true true diff --git a/test/UnitTests/MSTest.Analyzers.UnitTests/PreferDisposeOverTestCleanupAnalyzerTests.cs b/test/UnitTests/MSTest.Analyzers.UnitTests/PreferDisposeOverTestCleanupAnalyzerTests.cs index 65bb4d83c5..1c6934bd3e 100644 --- a/test/UnitTests/MSTest.Analyzers.UnitTests/PreferDisposeOverTestCleanupAnalyzerTests.cs +++ b/test/UnitTests/MSTest.Analyzers.UnitTests/PreferDisposeOverTestCleanupAnalyzerTests.cs @@ -29,6 +29,7 @@ public void Dispose() await VerifyCS.VerifyCodeFixAsync(code, code); } +#if NET [TestMethod] public async Task WhenTestClassHasDisposeAsync_NoDiagnostic() { @@ -49,6 +50,7 @@ public ValueTask DisposeAsync() await VerifyCS.VerifyCodeFixAsync(code, code); } +#endif [TestMethod] public async Task WhenTestClassHasTestCleanup_Diagnostic() @@ -230,6 +232,7 @@ public class MyTestClass await VerifyCS.VerifyCodeFixAsync(code, code); } +#if NET [TestMethod] public async Task WhenTestClassHasTestCleanupValueTask_Diagnostic() { @@ -251,4 +254,5 @@ public class MyTestClass await VerifyCS.VerifyCodeFixAsync(code, code); } +#endif } diff --git a/test/UnitTests/MSTest.Analyzers.UnitTests/PreferTestCleanupOverDisposeAnalyzerTests.cs b/test/UnitTests/MSTest.Analyzers.UnitTests/PreferTestCleanupOverDisposeAnalyzerTests.cs index fcee06522e..c6f26187d3 100644 --- a/test/UnitTests/MSTest.Analyzers.UnitTests/PreferTestCleanupOverDisposeAnalyzerTests.cs +++ b/test/UnitTests/MSTest.Analyzers.UnitTests/PreferTestCleanupOverDisposeAnalyzerTests.cs @@ -68,6 +68,7 @@ public interface IMyInterface { } await VerifyCS.VerifyCodeFixAsync(code, fixedCode); } +#if NET [TestMethod] public async Task WhenTestClassHasDisposeAsync_Diagnostic() { @@ -143,4 +144,5 @@ public ValueTask MyTestCleanup() await VerifyCS.VerifyCodeFixAsync(code, code); } +#endif } diff --git a/test/UnitTests/MSTest.Analyzers.UnitTests/Program.cs b/test/UnitTests/MSTest.Analyzers.UnitTests/Program.cs index 92aed8206f..aaaee854d8 100644 --- a/test/UnitTests/MSTest.Analyzers.UnitTests/Program.cs +++ b/test/UnitTests/MSTest.Analyzers.UnitTests/Program.cs @@ -3,6 +3,8 @@ using Microsoft.Testing.Extensions; +using ExecutionScope = Microsoft.VisualStudio.TestTools.UnitTesting.ExecutionScope; + [assembly: Parallelize(Scope = ExecutionScope.MethodLevel, Workers = 0)] [assembly: ClassCleanupExecution(ClassCleanupBehavior.EndOfClass)] diff --git a/test/UnitTests/MSTest.Analyzers.UnitTests/TestCleanupShouldBeValidAnalyzerTests.cs b/test/UnitTests/MSTest.Analyzers.UnitTests/TestCleanupShouldBeValidAnalyzerTests.cs index cdfea41d81..aede7da0fb 100644 --- a/test/UnitTests/MSTest.Analyzers.UnitTests/TestCleanupShouldBeValidAnalyzerTests.cs +++ b/test/UnitTests/MSTest.Analyzers.UnitTests/TestCleanupShouldBeValidAnalyzerTests.cs @@ -292,6 +292,7 @@ await VerifyCS.VerifyCodeFixAsync( fixedCode); } +#if NET [TestMethod] public async Task WhenTestCleanupReturnTypeIsNotValid_Diagnostic() { @@ -399,6 +400,7 @@ public ValueTask TestCleanup2() await VerifyCS.VerifyAnalyzerAsync(code); } +#endif [TestMethod] public async Task WhenTestCleanupIsAsyncVoid_Diagnostic() diff --git a/test/UnitTests/MSTest.Analyzers.UnitTests/TestContextPropertyUsageAnalyzerTests.cs b/test/UnitTests/MSTest.Analyzers.UnitTests/TestContextPropertyUsageAnalyzerTests.cs new file mode 100644 index 0000000000..96a769a53e --- /dev/null +++ b/test/UnitTests/MSTest.Analyzers.UnitTests/TestContextPropertyUsageAnalyzerTests.cs @@ -0,0 +1,259 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using VerifyCS = MSTest.Analyzers.Test.CSharpCodeFixVerifier< + MSTest.Analyzers.TestContextPropertyUsageAnalyzer, + Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>; + +namespace MSTest.Analyzers.Test; + +[TestClass] +public sealed class TestContextPropertyUsageAnalyzerTests +{ + [TestMethod] + public async Task WhenTestContextPropertyAccessedInAssemblyInitialize_Diagnostic() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [AssemblyInitialize] + public static void AssemblyInit(TestContext testContext) + { + _ = [|testContext.TestData|]; + _ = [|testContext.TestDisplayName|]; + _ = [|testContext.TestName|]; + _ = [|testContext.ManagedMethod|]; + _ = [|testContext.FullyQualifiedTestClassName|]; + _ = [|testContext.ManagedType|]; + } + } + """; + + await VerifyCS.VerifyAnalyzerAsync(code); + } + + [TestMethod] + public async Task WhenTestContextPropertyAccessedInAssemblyCleanup_Diagnostic() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [AssemblyCleanup] + public static void AssemblyCleanup() + { + TestContext testContext = GetTestContext(); + _ = [|testContext.TestData|]; + _ = [|testContext.TestDisplayName|]; + _ = [|testContext.TestName|]; + _ = [|testContext.ManagedMethod|]; + _ = [|testContext.FullyQualifiedTestClassName|]; + _ = [|testContext.ManagedType|]; + } + + private static TestContext GetTestContext() => null; + } + """; + + await VerifyCS.VerifyAnalyzerAsync(code); + } + + [TestMethod] + public async Task WhenTestContextPropertyAccessedInClassInitialize_Diagnostic() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [ClassInitialize] + public static void ClassInit(TestContext testContext) + { + _ = [|testContext.TestData|]; + _ = [|testContext.TestDisplayName|]; + _ = [|testContext.TestName|]; + _ = [|testContext.ManagedMethod|]; + // These should NOT trigger diagnostics in class initialize + _ = testContext.FullyQualifiedTestClassName; + _ = testContext.ManagedType; + } + } + """; + + await VerifyCS.VerifyAnalyzerAsync(code); + } + + [TestMethod] + public async Task WhenTestContextPropertyAccessedInClassCleanup_Diagnostic() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [ClassCleanup] + public static void ClassCleanup() + { + TestContext testContext = GetTestContext(); + _ = [|testContext.TestData|]; + _ = [|testContext.TestDisplayName|]; + _ = [|testContext.TestName|]; + _ = [|testContext.ManagedMethod|]; + // These should NOT trigger diagnostics in class cleanup + _ = testContext.FullyQualifiedTestClassName; + _ = testContext.ManagedType; + } + + private static TestContext GetTestContext() => null; + } + """; + + await VerifyCS.VerifyAnalyzerAsync(code); + } + + [TestMethod] + public async Task WhenTestContextPropertyAccessedInTestMethod_NoDiagnostic() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + public TestContext TestContext { get; set; } + + [TestMethod] + public void TestMethod() + { + // All of these should be allowed in test methods + _ = TestContext.TestData; + _ = TestContext.TestDisplayName; + _ = TestContext.TestName; + _ = TestContext.ManagedMethod; + _ = TestContext.FullyQualifiedTestClassName; + _ = TestContext.ManagedType; + } + } + """; + + await VerifyCS.VerifyAnalyzerAsync(code); + } + + [TestMethod] + public async Task WhenTestContextPropertyAccessedInTestInitialize_NoDiagnostic() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + public TestContext TestContext { get; set; } + + [TestInitialize] + public void TestInit() + { + // All of these should be allowed in test initialize + _ = TestContext.TestData; + _ = TestContext.TestDisplayName; + _ = TestContext.TestName; + _ = TestContext.ManagedMethod; + _ = TestContext.FullyQualifiedTestClassName; + _ = TestContext.ManagedType; + } + } + """; + + await VerifyCS.VerifyAnalyzerAsync(code); + } + + [TestMethod] + public async Task WhenTestContextPropertyAccessedInTestCleanup_NoDiagnostic() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + public TestContext TestContext { get; set; } + + [TestCleanup] + public void TestCleanup() + { + // All of these should be allowed in test cleanup + _ = TestContext.TestData; + _ = TestContext.TestDisplayName; + _ = TestContext.TestName; + _ = TestContext.ManagedMethod; + _ = TestContext.FullyQualifiedTestClassName; + _ = TestContext.ManagedType; + } + } + """; + + await VerifyCS.VerifyAnalyzerAsync(code); + } + +#if NETFRAMEWORK + [TestMethod] + public async Task WhenDataRowAndDataConnectionAccessedInNetFramework_Diagnostic() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [AssemblyInitialize] + public static void AssemblyInit(TestContext testContext) + { + _ = [|testContext.DataRow|]; + _ = [|testContext.DataConnection|]; + } + } + """; + + await VerifyCS.VerifyAnalyzerAsync(code); + } +#endif + + [TestMethod] + public async Task WhenAllowedPropertiesAccessedInFixtureMethods_NoDiagnostic() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [AssemblyInitialize] + public static void AssemblyInit(TestContext testContext) + { + // These properties should be allowed in fixture methods + _ = testContext.Properties; + testContext.WriteLine("test"); + testContext.Write("test"); + } + + [ClassInitialize] + public static void ClassInit(TestContext testContext) + { + // These properties should be allowed in class initialize + _ = testContext.FullyQualifiedTestClassName; + _ = testContext.ManagedType; + _ = testContext.Properties; + } + } + """; + + await VerifyCS.VerifyAnalyzerAsync(code); + } +} diff --git a/test/UnitTests/MSTest.Analyzers.UnitTests/TestInitializeShouldBeValidAnalyzerTests.cs b/test/UnitTests/MSTest.Analyzers.UnitTests/TestInitializeShouldBeValidAnalyzerTests.cs index d8eb9cbe5e..05367fc67d 100644 --- a/test/UnitTests/MSTest.Analyzers.UnitTests/TestInitializeShouldBeValidAnalyzerTests.cs +++ b/test/UnitTests/MSTest.Analyzers.UnitTests/TestInitializeShouldBeValidAnalyzerTests.cs @@ -290,6 +290,7 @@ await VerifyCS.VerifyCodeFixAsync( fixedCode); } +#if NET [TestMethod] public async Task WhenTestInitializeReturnTypeIsNotValid_Diagnostic() { @@ -397,6 +398,7 @@ public ValueTask TestInitialize2() await VerifyCS.VerifyAnalyzerAsync(code); } +#endif [TestMethod] public async Task WhenTestInitializeIsAsyncVoid_Diagnostic() diff --git a/test/UnitTests/MSTest.Analyzers.UnitTests/TestMethodShouldBeValidAnalyzerTests.cs b/test/UnitTests/MSTest.Analyzers.UnitTests/TestMethodShouldBeValidAnalyzerTests.cs index 05977b87d7..b311c1976f 100644 --- a/test/UnitTests/MSTest.Analyzers.UnitTests/TestMethodShouldBeValidAnalyzerTests.cs +++ b/test/UnitTests/MSTest.Analyzers.UnitTests/TestMethodShouldBeValidAnalyzerTests.cs @@ -247,6 +247,7 @@ public class MyTestClass await VerifyCS.VerifyAnalyzerAsync(code); } +#if NET [TestMethod] public async Task WhenTestMethodReturnTypeIsNotValid_Diagnostic() { @@ -346,6 +347,7 @@ public ValueTask MyTestMethod2() await VerifyCS.VerifyCodeFixAsync(code, code); } +#endif [TestMethod] public async Task WhenTestMethodIsAsyncVoid_Diagnostic() diff --git a/test/UnitTests/MSTest.Analyzers.UnitTests/UseParallelizeAttributeAnalyzerTests.cs b/test/UnitTests/MSTest.Analyzers.UnitTests/UseParallelizeAttributeAnalyzerTests.cs index 8872cb744b..bb48573015 100644 --- a/test/UnitTests/MSTest.Analyzers.UnitTests/UseParallelizeAttributeAnalyzerTests.cs +++ b/test/UnitTests/MSTest.Analyzers.UnitTests/UseParallelizeAttributeAnalyzerTests.cs @@ -24,7 +24,9 @@ private static async Task VerifyAsync(string code, bool includeTestAdapter, para if (includeTestAdapter) { // NOTE: Test constructor already adds TestFramework refs. +#pragma warning disable CS0618 // Type or member is obsolete test.TestState.AdditionalReferences.Add(MetadataReference.CreateFromFile(typeof(MSTestExecutor).Assembly.Location)); +#pragma warning restore CS0618 // Type or member is obsolete } test.ExpectedDiagnostics.AddRange(expected); diff --git a/test/UnitTests/MSTest.Analyzers.UnitTests/Verifiers/CSharpCodeFixVerifier`2+Test.cs b/test/UnitTests/MSTest.Analyzers.UnitTests/Verifiers/CSharpCodeFixVerifier`2+Test.cs index 3fc45b7658..05f286761c 100644 --- a/test/UnitTests/MSTest.Analyzers.UnitTests/Verifiers/CSharpCodeFixVerifier`2+Test.cs +++ b/test/UnitTests/MSTest.Analyzers.UnitTests/Verifiers/CSharpCodeFixVerifier`2+Test.cs @@ -19,7 +19,13 @@ public class Test : CSharpCodeFixTest { public Test() { +#if NET462 + ReferenceAssemblies = ReferenceAssemblies.NetFramework.Net462.Default; + TestState.AdditionalReferences.Add(MetadataReference.CreateFromFile(typeof(ValueTask<>).Assembly.Location)); + TestState.AdditionalReferences.Add(MetadataReference.CreateFromFile(typeof(IAsyncDisposable).Assembly.Location)); +#else ReferenceAssemblies = ReferenceAssemblies.Net.Net60; +#endif TestState.AdditionalReferences.Add(MetadataReference.CreateFromFile(typeof(ParallelizeAttribute).Assembly.Location)); TestState.AdditionalReferences.Add(MetadataReference.CreateFromFile(typeof(TestContext).Assembly.Location)); SolutionTransforms.Add((solution, projectId) => From 8e01c43c6b5914c78fe89315f2a41781707c9479 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Mon, 21 Jul 2025 13:56:54 +0200 Subject: [PATCH 265/541] Update TerminalTestReporter to consider ct.IsCancellationRequested to print "abort" (#6108) --- .../OutputDevice/OutputDeviceManager.cs | 3 ++- .../Terminal/TerminalTestReporter.cs | 27 ++++++++++++++----- .../OutputDevice/TerminalOutputDevice.cs | 8 ++++-- .../AbortionTests.cs | 10 +++---- .../Terminal/TerminalTestReporterTests.cs | 9 ++++--- 5 files changed, 36 insertions(+), 21 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/OutputDeviceManager.cs b/src/Platform/Microsoft.Testing.Platform/OutputDevice/OutputDeviceManager.cs index 4248cc474e..bd791add93 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/OutputDeviceManager.cs +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/OutputDeviceManager.cs @@ -62,5 +62,6 @@ public static IPlatformOutputDevice GetDefaultTerminalOutputDevice(ServiceProvid serviceProvider.GetFileLoggerInformation(), serviceProvider.GetLoggerFactory(), serviceProvider.GetClock(), - serviceProvider.GetRequiredService()); + serviceProvider.GetRequiredService(), + serviceProvider.GetTestApplicationCancellationTokenSource()); } diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporter.cs b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporter.cs index d1d0c0cdf9..576117e89e 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporter.cs +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporter.cs @@ -3,6 +3,7 @@ using Microsoft.Testing.Platform.Helpers; using Microsoft.Testing.Platform.Resources; +using Microsoft.Testing.Platform.Services; namespace Microsoft.Testing.Platform.OutputDevice.Terminal; @@ -38,6 +39,7 @@ internal event EventHandler OnProgressStopUpdate private readonly string _assembly; private readonly string? _targetFramework; private readonly string? _architecture; + private readonly ITestApplicationCancellationTokenSource _testApplicationCancellationTokenSource; private readonly List _artifacts = []; @@ -57,7 +59,11 @@ internal event EventHandler OnProgressStopUpdate private int _buildErrorsCount; - private bool _wasCancelled; + private bool WasCancelled + { + get => field || _testApplicationCancellationTokenSource.CancellationToken.IsCancellationRequested; + set => field = value; + } private bool? _shouldShowPassedTests; @@ -66,11 +72,18 @@ internal event EventHandler OnProgressStopUpdate /// /// Initializes a new instance of the class with custom terminal and manual refresh for testing. /// - public TerminalTestReporter(string assembly, string? targetFramework, string? architecture, IConsole console, TerminalTestReporterOptions options) + public TerminalTestReporter( + string assembly, + string? targetFramework, + string? architecture, + IConsole console, + ITestApplicationCancellationTokenSource testApplicationCancellationTokenSource, + TerminalTestReporterOptions options) { _assembly = assembly; _targetFramework = targetFramework; _architecture = architecture; + _testApplicationCancellationTokenSource = testApplicationCancellationTokenSource; _options = options; Func showProgress = _options.ShowProgress; @@ -190,13 +203,13 @@ private void AppendTestRunSummary(ITerminal terminal) bool notEnoughTests = totalTests < _options.MinimumExpectedTests; bool allTestsWereSkipped = totalTests == 0 || totalTests == totalSkippedTests; bool anyTestFailed = totalFailedTests > 0; - bool runFailed = anyTestFailed || notEnoughTests || allTestsWereSkipped || _wasCancelled; + bool runFailed = anyTestFailed || notEnoughTests || allTestsWereSkipped || WasCancelled; terminal.SetColor(runFailed ? TerminalColor.DarkRed : TerminalColor.DarkGreen); terminal.Append(PlatformResources.TestRunSummary); terminal.Append(' '); - if (_wasCancelled) + if (WasCancelled) { terminal.Append(PlatformResources.Aborted); } @@ -664,7 +677,7 @@ public void ArtifactAdded(bool outOfProcess, string? testName, string path) /// public void StartCancelling() { - _wasCancelled = true; + WasCancelled = true; _terminalWithProgress.WriteToTerminal(terminal => { terminal.AppendLine(); @@ -779,7 +792,7 @@ public void AppendTestDiscoverySummary(ITerminal terminal) terminal.AppendLine(); int totalTests = assembly?.TotalTests ?? 0; - bool runFailed = _wasCancelled; + bool runFailed = WasCancelled; if (assembly is not null) { @@ -803,7 +816,7 @@ public void AppendTestDiscoverySummary(ITerminal terminal) terminal.ResetColor(); terminal.AppendLine(); - if (_wasCancelled) + if (WasCancelled) { terminal.Append(PlatformResources.Aborted); terminal.AppendLine(); diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/TerminalOutputDevice.cs b/src/Platform/Microsoft.Testing.Platform/OutputDevice/TerminalOutputDevice.cs index f57b254ec6..2fd1bbb28f 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/TerminalOutputDevice.cs +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/TerminalOutputDevice.cs @@ -44,6 +44,7 @@ internal sealed partial class TerminalOutputDevice : IHotReloadPlatformOutputDev private readonly ILoggerFactory _loggerFactory; private readonly IClock _clock; private readonly IStopPoliciesService _policiesService; + private readonly ITestApplicationCancellationTokenSource _testApplicationCancellationTokenSource; private readonly string? _longArchitecture; private readonly string? _shortArchitecture; @@ -66,7 +67,7 @@ public TerminalOutputDevice( ITestApplicationModuleInfo testApplicationModuleInfo, ITestHostControllerInfo testHostControllerInfo, IAsyncMonitor asyncMonitor, IRuntimeFeature runtimeFeature, IEnvironment environment, IPlatformInformation platformInformation, ICommandLineOptions commandLineOptions, IFileLoggerInformation? fileLoggerInformation, ILoggerFactory loggerFactory, IClock clock, - IStopPoliciesService policiesService) + IStopPoliciesService policiesService, ITestApplicationCancellationTokenSource testApplicationCancellationTokenSource) { _console = console; _testHostControllerInfo = testHostControllerInfo; @@ -79,6 +80,7 @@ public TerminalOutputDevice( _loggerFactory = loggerFactory; _clock = clock; _policiesService = policiesService; + _testApplicationCancellationTokenSource = testApplicationCancellationTokenSource; if (_runtimeFeature.IsDynamicCodeSupported) { @@ -100,6 +102,8 @@ public TerminalOutputDevice( { _bannerDisplayed = true; } + + _testApplicationCancellationTokenSource = testApplicationCancellationTokenSource; } public async Task InitializeAsync() @@ -151,7 +155,7 @@ await _policiesService.RegisterOnAbortCallbackAsync( : !_testHostControllerInfo.IsCurrentProcessTestHostController; // This is single exe run, don't show all the details of assemblies and their summaries. - _terminalTestReporter = new TerminalTestReporter(_assemblyName, _targetFramework, _shortArchitecture, _console, new() + _terminalTestReporter = new TerminalTestReporter(_assemblyName, _targetFramework, _shortArchitecture, _console, _testApplicationCancellationTokenSource, new() { ShowPassedTests = showPassed, MinimumExpectedTests = PlatformCommandLineProvider.GetMinimumExpectedTests(_commandLineOptions), diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/AbortionTests.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/AbortionTests.cs index e35a768106..40e225f5b1 100644 --- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/AbortionTests.cs +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/AbortionTests.cs @@ -25,13 +25,9 @@ public async Task AbortWithCTRLPlusC_TestHost_Succeeded(string tfm) testHostResult.AssertExitCodeIs(ExitCodes.TestSessionAborted); - // We check only in netcore for netfx is now showing in CI every time, the same behavior in local something works sometime nope. - // Manual test works pretty always as expected, looks like the implementation is different, we care more on .NET Core. - if (TargetFrameworks.Net.Contains(tfm)) - { - testHostResult.AssertOutputMatchesRegex("Canceling the test session.*"); - } - + // We don't assert "Canceling the test session" message. + // Cancellation could happen very first that we didn't have the opportunity to write this message. + // However, the summary should always be correct and should always indicate that the session was aborted. testHostResult.AssertOutputContainsSummary(failed: 0, passed: 0, skipped: 0, aborted: true); } diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/OutputDevice/Terminal/TerminalTestReporterTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/OutputDevice/Terminal/TerminalTestReporterTests.cs index 70a905d8b9..f8d8a9b240 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/OutputDevice/Terminal/TerminalTestReporterTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/OutputDevice/Terminal/TerminalTestReporterTests.cs @@ -3,6 +3,7 @@ using Microsoft.Testing.Platform.Helpers; using Microsoft.Testing.Platform.OutputDevice.Terminal; +using Microsoft.Testing.Platform.Services; namespace Microsoft.Testing.Platform.UnitTests; @@ -73,7 +74,7 @@ public void NonAnsiTerminal_OutputFormattingIsCorrect() string assembly = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? @"C:\work\assembly.dll" : "/mnt/work/assembly.dll"; var stringBuilderConsole = new StringBuilderConsole(); - var terminalReporter = new TerminalTestReporter(assembly, targetFramework, architecture, stringBuilderConsole, new TerminalTestReporterOptions + var terminalReporter = new TerminalTestReporter(assembly, targetFramework, architecture, stringBuilderConsole, new CTRLPlusCCancellationTokenSource(), new TerminalTestReporterOptions { ShowPassedTests = () => true, @@ -172,7 +173,7 @@ public void SimpleAnsiTerminal_OutputFormattingIsCorrect() string assembly = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? @"C:\work\assembly.dll" : "/mnt/work/assembly.dll"; var stringBuilderConsole = new StringBuilderConsole(); - var terminalReporter = new TerminalTestReporter(assembly, targetFramework, architecture, stringBuilderConsole, new TerminalTestReporterOptions + var terminalReporter = new TerminalTestReporter(assembly, targetFramework, architecture, stringBuilderConsole, new CTRLPlusCCancellationTokenSource(), new TerminalTestReporterOptions { ShowPassedTests = () => true, // Like if we autodetect that we are in CI (e.g. by looking at TF_BUILD, and we don't disable ANSI. @@ -272,7 +273,7 @@ public void AnsiTerminal_OutputFormattingIsCorrect() string assembly = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? @"C:\work\assembly.dll" : "/mnt/work/assembly.dll"; var stringBuilderConsole = new StringBuilderConsole(); - var terminalReporter = new TerminalTestReporter(assembly, targetFramework, architecture, stringBuilderConsole, new TerminalTestReporterOptions + var terminalReporter = new TerminalTestReporter(assembly, targetFramework, architecture, stringBuilderConsole, new CTRLPlusCCancellationTokenSource(), new TerminalTestReporterOptions { ShowPassedTests = () => true, // Like if we autodetect that we are in ANSI capable terminal. @@ -373,7 +374,7 @@ public void AnsiTerminal_OutputProgressFrameIsCorrect() var stringBuilderConsole = new StringBuilderConsole(); var stopwatchFactory = new StopwatchFactory(); - var terminalReporter = new TerminalTestReporter(assembly, targetFramework, architecture, stringBuilderConsole, new TerminalTestReporterOptions + var terminalReporter = new TerminalTestReporter(assembly, targetFramework, architecture, stringBuilderConsole, new CTRLPlusCCancellationTokenSource(), new TerminalTestReporterOptions { ShowPassedTests = () => true, // Like if we autodetect that we are in ANSI capable terminal. From 4a8fcdaacd6ff086be895fc4aaf9e5c7d49e9f24 Mon Sep 17 00:00:00 2001 From: Copilot <198982749+Copilot@users.noreply.github.com> Date: Mon, 21 Jul 2025 14:12:37 +0200 Subject: [PATCH 266/541] Update UseProperAssertMethodsAnalyzer to handle more use cases (#6058) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: Evangelink <11340282+Evangelink@users.noreply.github.com> Co-authored-by: Amaury Levé --- .../UseProperAssertMethodsFixer.cs | 76 ++- .../UseProperAssertMethodsAnalyzer.cs | 366 ++++++++++++ .../UseProperAssertMethodsAnalyzerTests.cs | 558 ++++++++++++++++++ 3 files changed, 998 insertions(+), 2 deletions(-) diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/UseProperAssertMethodsFixer.cs b/src/Analyzers/MSTest.Analyzers.CodeFixes/UseProperAssertMethodsFixer.cs index 37be3ecc36..ddeb839fd7 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/UseProperAssertMethodsFixer.cs +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/UseProperAssertMethodsFixer.cs @@ -78,6 +78,9 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) case UseProperAssertMethodsAnalyzer.CodeFixModeRemoveArgument: createChangedDocument = ct => FixAssertMethodForRemoveArgumentModeAsync(context.Document, diagnostic.AdditionalLocations, root, simpleNameSyntax, properAssertMethodName, diagnostic.Properties.ContainsKey(UseProperAssertMethodsAnalyzer.NeedsNullableBooleanCastKey), ct); break; + case UseProperAssertMethodsAnalyzer.CodeFixModeCollectionCount: + createChangedDocument = ct => FixAssertMethodForCollectionCountModeAsync(context.Document, diagnostic.AdditionalLocations, root, simpleNameSyntax, properAssertMethodName, ct); + break; default: break; } @@ -132,7 +135,8 @@ private static async Task FixAssertMethodForAddArgumentModeAsync(Docum return document; } - if (root.FindNode(expectedLocation.SourceSpan) is not ExpressionSyntax expectedNode) + if (root.FindNode(expectedLocation.SourceSpan) is not { } expectedNode + || expectedNode is not ArgumentSyntax and not ExpressionSyntax) { return document; } @@ -146,7 +150,13 @@ private static async Task FixAssertMethodForAddArgumentModeAsync(Docum FixInvocationMethodName(editor, simpleNameSyntax, properAssertMethodName); ArgumentListSyntax newArgumentList = argumentList; - newArgumentList = newArgumentList.ReplaceNode(conditionNode, SyntaxFactory.Argument(expectedNode).WithAdditionalAnnotations(Formatter.Annotation)); + ExpressionSyntax expectedExpression = expectedNode switch + { + ArgumentSyntax argument => argument.Expression, + ExpressionSyntax expression => expression, + _ => throw new InvalidOperationException($"Unexpected node type for expected argument: {expectedNode.GetType()}"), + }; + newArgumentList = newArgumentList.ReplaceNode(conditionNode, SyntaxFactory.Argument(expectedExpression).WithAdditionalAnnotations(Formatter.Annotation)); int insertionIndex = argumentList.Arguments.IndexOf(conditionNode) + 1; newArgumentList = newArgumentList.WithArguments(newArgumentList.Arguments.Insert(insertionIndex, SyntaxFactory.Argument(actualNode).WithAdditionalAnnotations(Formatter.Annotation))); @@ -203,6 +213,68 @@ private static async Task FixAssertMethodForRemoveArgumentModeAsync( return editor.GetChangedDocument(); } + private static async Task FixAssertMethodForCollectionCountModeAsync( + Document document, + IReadOnlyList additionalLocations, + SyntaxNode root, + SimpleNameSyntax simpleNameSyntax, + string properAssertMethodName, + CancellationToken cancellationToken) + { + // Handle collection count transformations: + // Assert.AreEqual(0, list.Count) -> Assert.IsEmpty(list) + // Assert.AreEqual(3, list.Count) -> Assert.HasCount(3, list) + // Assert.AreEqual(list.Count, 0) -> Assert.IsEmpty(list) + // Assert.AreEqual(list.Count, 3) -> Assert.HasCount(3, list) + if (root.FindNode(additionalLocations[0].SourceSpan) is not ArgumentSyntax firstArgument || + root.FindNode(additionalLocations[1].SourceSpan) is not ArgumentSyntax || + firstArgument.Parent is not ArgumentListSyntax argumentList) + { + return document; + } + + if (root.FindNode(additionalLocations[2].SourceSpan) is not ExpressionSyntax collectionExpression) + { + return document; + } + + DocumentEditor editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false); + FixInvocationMethodName(editor, simpleNameSyntax, properAssertMethodName); + + ArgumentListSyntax newArgumentList; + + if (properAssertMethodName == "IsEmpty") + { + // For IsEmpty, we just need the collection argument + newArgumentList = argumentList.WithArguments( + SyntaxFactory.SeparatedList(new[] { SyntaxFactory.Argument(collectionExpression).WithAdditionalAnnotations(Formatter.Annotation) })); + } + else // HasCount + { + // For HasCount, we need count and collection arguments + // additionalLocations[3] should contain the count expression + if (additionalLocations.Count > 3 && + root.FindNode(additionalLocations[3].SourceSpan) is ArgumentSyntax countArgument) + { + newArgumentList = argumentList.WithArguments( + SyntaxFactory.SeparatedList(new[] + { + SyntaxFactory.Argument(countArgument.Expression).WithAdditionalAnnotations(Formatter.Annotation), + SyntaxFactory.Argument(collectionExpression).WithAdditionalAnnotations(Formatter.Annotation), + })); + } + else + { + // Fallback: something went wrong, don't apply the fix + return document; + } + } + + editor.ReplaceNode(argumentList, newArgumentList); + + return editor.GetChangedDocument(); + } + private static void FixInvocationMethodName(DocumentEditor editor, SimpleNameSyntax simpleNameSyntax, string properAssertMethodName) // NOTE: Switching Assert.IsTrue(x == y) to Assert.AreEqual(x, y) MAY produce an overload resolution error. // For example, Assert.AreEqual("string", true) will fail the inference for generic argument. diff --git a/src/Analyzers/MSTest.Analyzers/UseProperAssertMethodsAnalyzer.cs b/src/Analyzers/MSTest.Analyzers/UseProperAssertMethodsAnalyzer.cs index ef26733c67..5859cacb41 100644 --- a/src/Analyzers/MSTest.Analyzers/UseProperAssertMethodsAnalyzer.cs +++ b/src/Analyzers/MSTest.Analyzers/UseProperAssertMethodsAnalyzer.cs @@ -41,6 +41,26 @@ namespace MSTest.Analyzers; /// Assert.[AreEqual|AreNotEqual](null, x) /// /// +/// +/// +/// Assert.IsTrue(myString.[StartsWith|EndsWith|Contains]("...")) +/// +/// +/// +/// +/// Assert.IsTrue(myCollection.Contains(...)) +/// +/// +/// +/// +/// Assert.[IsTrue|IsFalse](x [>|>=|<|<=] y) +/// +/// +/// +/// +/// Assert.AreEqual([0|X], myCollection.[Count|Length]) +/// +/// /// /// [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] @@ -60,6 +80,36 @@ private enum EqualityCheckStatus NotEquals, } + private enum StringMethodCheckStatus + { + Unknown, + StartsWith, + EndsWith, + Contains, + } + + private enum ComparisonCheckStatus + { + Unknown, + GreaterThan, + GreaterThanOrEqual, + LessThan, + LessThanOrEqual, + } + + private enum CollectionCheckStatus + { + Unknown, + Contains, + } + + private enum CountCheckStatus + { + Unknown, + IsEmpty, + HasCount, + } + internal const string ProperAssertMethodNameKey = nameof(ProperAssertMethodNameKey); /// @@ -120,6 +170,18 @@ private enum EqualityCheckStatus /// internal const string CodeFixModeRemoveArgument = nameof(CodeFixModeRemoveArgument); + /// + /// This mode means the codefix operation is as follows for collection count checks: + /// + /// Find the right assert method name from the properties bag using . + /// Replace the identifier syntax for the invocation with the right assert method name. + /// Transform arguments based on the count check pattern. + /// + /// Example: For Assert.AreEqual(0, list.Count), it will become Assert.IsEmpty(list). + /// Example: For Assert.AreEqual(3, list.Count), it will become Assert.HasCount(3, list). + /// + internal const string CodeFixModeCollectionCount = nameof(CodeFixModeCollectionCount); + private static readonly LocalizableResourceString Title = new(nameof(Resources.UseProperAssertMethodsTitle), Resources.ResourceManager, typeof(Resources)); private static readonly LocalizableResourceString MessageFormat = new(nameof(Resources.UseProperAssertMethodsMessageFormat), Resources.ResourceManager, typeof(Resources)); @@ -325,6 +387,97 @@ private static bool CanUseTypeAsObject(Compilation compilation, ITypeSymbol? typ => type is null || compilation.ClassifyCommonConversion(type, compilation.GetSpecialType(SpecialType.System_Object)).Exists; + private static StringMethodCheckStatus RecognizeStringMethodCheck( + IOperation operation, + out SyntaxNode? stringExpression, + out SyntaxNode? substringExpression) + { + if (operation is IInvocationOperation invocation && + invocation.TargetMethod.ContainingType?.SpecialType == SpecialType.System_String && + invocation.Arguments.Length == 1) + { + string methodName = invocation.TargetMethod.Name; + if (methodName is "StartsWith" or "EndsWith" or "Contains") + { + stringExpression = invocation.Instance?.Syntax; + substringExpression = invocation.Arguments[0].Value.Syntax; + + return methodName switch + { + "StartsWith" => StringMethodCheckStatus.StartsWith, + "EndsWith" => StringMethodCheckStatus.EndsWith, + "Contains" => StringMethodCheckStatus.Contains, + _ => StringMethodCheckStatus.Unknown, + }; + } + } + + stringExpression = null; + substringExpression = null; + return StringMethodCheckStatus.Unknown; + } + + private static CollectionCheckStatus RecognizeCollectionMethodCheck( + IOperation operation, + out SyntaxNode? collectionExpression, + out SyntaxNode? itemExpression) + { + if (operation is IInvocationOperation invocation) + { + string methodName = invocation.TargetMethod.Name; + + // Check for Collection.Contains(item) + if (methodName == "Contains" && invocation.Arguments.Length == 1) + { + // Ensure it's a collection type (implements IEnumerable) + ITypeSymbol? receiverType = invocation.Instance?.Type; + if (receiverType is not null && + IsCollectionType(receiverType)) + { + collectionExpression = invocation.Instance?.Syntax; + itemExpression = invocation.Arguments[0].Value.Syntax; + return CollectionCheckStatus.Contains; + } + } + } + + collectionExpression = null; + itemExpression = null; + return CollectionCheckStatus.Unknown; + } + + private static bool IsCollectionType(ITypeSymbol type) + // Check if the type implements IEnumerable (but is not string) + => type.SpecialType != SpecialType.System_String && type.AllInterfaces.Any(i => + i.SpecialType == SpecialType.System_Collections_IEnumerable || + (i.OriginalDefinition?.SpecialType == SpecialType.System_Collections_Generic_IEnumerable_T)); + + private static ComparisonCheckStatus RecognizeComparisonCheck( + IOperation operation, + out SyntaxNode? leftExpression, + out SyntaxNode? rightExpression) + { + if (operation is IBinaryOperation binaryOperation && + binaryOperation.OperatorMethod is not { MethodKind: MethodKind.UserDefinedOperator }) + { + leftExpression = binaryOperation.LeftOperand.Syntax; + rightExpression = binaryOperation.RightOperand.Syntax; + + return binaryOperation.OperatorKind switch + { + BinaryOperatorKind.GreaterThan => ComparisonCheckStatus.GreaterThan, + BinaryOperatorKind.GreaterThanOrEqual => ComparisonCheckStatus.GreaterThanOrEqual, + BinaryOperatorKind.LessThan => ComparisonCheckStatus.LessThan, + BinaryOperatorKind.LessThanOrEqual => ComparisonCheckStatus.LessThanOrEqual, + _ => ComparisonCheckStatus.Unknown, + }; + } + + leftExpression = null; + rightExpression = null; + return ComparisonCheckStatus.Unknown; + } + private static void AnalyzeIsTrueOrIsFalseInvocation(OperationAnalysisContext context, IOperation conditionArgument, bool isTrueInvocation) { RoslynDebug.Assert(context.Operation is IInvocationOperation, "Expected IInvocationOperation."); @@ -361,6 +514,118 @@ private static void AnalyzeIsTrueOrIsFalseInvocation(OperationAnalysisContext co return; } + // Check for string method patterns: myString.StartsWith/EndsWith/Contains(...) + StringMethodCheckStatus stringMethodStatus = RecognizeStringMethodCheck(conditionArgument, out SyntaxNode? stringExpr, out SyntaxNode? substringExpr); + if (stringMethodStatus != StringMethodCheckStatus.Unknown) + { + // For string methods, we only suggest when the condition is positive (IsTrue) + // Assert.IsFalse(str.StartsWith(...)) could suggest Assert.DoesNotStartWith, but that's less common + if (isTrueInvocation) + { + string properAssertMethod = stringMethodStatus switch + { + StringMethodCheckStatus.StartsWith => "StartsWith", + StringMethodCheckStatus.EndsWith => "EndsWith", + StringMethodCheckStatus.Contains => "Contains", + _ => throw new InvalidOperationException("Unexpected StringMethodCheckStatus value."), + }; + + ImmutableDictionary.Builder properties = ImmutableDictionary.CreateBuilder(); + properties.Add(ProperAssertMethodNameKey, properAssertMethod); + properties.Add(CodeFixModeKey, CodeFixModeAddArgument); + context.ReportDiagnostic(context.Operation.CreateDiagnostic( + Rule, + additionalLocations: ImmutableArray.Create(conditionArgument.Syntax.GetLocation(), substringExpr!.GetLocation(), stringExpr!.GetLocation()), + properties: properties.ToImmutable(), + properAssertMethod, + "IsTrue")); + return; + } + } + + // Check for collection method patterns: myCollection.Contains(...) + CollectionCheckStatus collectionMethodStatus = RecognizeCollectionMethodCheck(conditionArgument, out SyntaxNode? collectionExpr, out SyntaxNode? itemExpr); + if (collectionMethodStatus != CollectionCheckStatus.Unknown) + { + if (isTrueInvocation && collectionMethodStatus == CollectionCheckStatus.Contains) + { + string properAssertMethod = "Contains"; + + ImmutableDictionary.Builder properties = ImmutableDictionary.CreateBuilder(); + properties.Add(ProperAssertMethodNameKey, properAssertMethod); + properties.Add(CodeFixModeKey, CodeFixModeAddArgument); + context.ReportDiagnostic(context.Operation.CreateDiagnostic( + Rule, + additionalLocations: ImmutableArray.Create(conditionArgument.Syntax.GetLocation(), itemExpr!.GetLocation(), collectionExpr!.GetLocation()), + properties: properties.ToImmutable(), + properAssertMethod, + "IsTrue")); + return; + } + } + + // Check for comparison patterns: a > b, a >= b, a < b, a <= b + ComparisonCheckStatus comparisonStatus = RecognizeComparisonCheck(conditionArgument, out SyntaxNode? leftExpr, out SyntaxNode? rightExpr); + if (comparisonStatus != ComparisonCheckStatus.Unknown) + { + string properAssertMethod = (isTrueInvocation, comparisonStatus) switch + { + (true, ComparisonCheckStatus.GreaterThan) => "IsGreaterThan", + (true, ComparisonCheckStatus.GreaterThanOrEqual) => "IsGreaterThanOrEqualTo", + (true, ComparisonCheckStatus.LessThan) => "IsLessThan", + (true, ComparisonCheckStatus.LessThanOrEqual) => "IsLessThanOrEqualTo", + (false, ComparisonCheckStatus.GreaterThan) => "IsLessThanOrEqualTo", + (false, ComparisonCheckStatus.GreaterThanOrEqual) => "IsLessThan", + (false, ComparisonCheckStatus.LessThan) => "IsGreaterThanOrEqualTo", + (false, ComparisonCheckStatus.LessThanOrEqual) => "IsGreaterThan", + _ => throw new InvalidOperationException("Unexpected ComparisonCheckStatus value."), + }; + + // For Assert.IsGreaterThan, IsLessThan etc., the method signature is (lowerBound, value) or (upperBound, value) + // So for a > b -> Assert.IsGreaterThan(b, a) where b is the lower bound and a is the value + // For a < b -> Assert.IsLessThan(b, a) where b is the upper bound and a is the value + SyntaxNode? firstArg, secondArg; + switch ((isTrueInvocation, comparisonStatus)) + { + // a > b -> IsGreaterThan(b, a) + case (true, ComparisonCheckStatus.GreaterThan): + // a >= b -> IsGreaterThanOrEqualTo(b, a) + case (true, ComparisonCheckStatus.GreaterThanOrEqual): + // !(a < b) -> IsGreaterThanOrEqualTo(b, a) + case (false, ComparisonCheckStatus.LessThan): + // !(a <= b) -> IsGreaterThan(b, a) + case (false, ComparisonCheckStatus.LessThanOrEqual): + firstArg = rightExpr; // b becomes first arg (lower bound) + secondArg = leftExpr; // a becomes second arg (value) + break; + // a < b -> IsLessThan(b, a) + case (true, ComparisonCheckStatus.LessThan): + // a <= b -> IsLessThanOrEqualTo(b, a) + case (true, ComparisonCheckStatus.LessThanOrEqual): + // !(a > b) -> IsLessThanOrEqualTo(b, a) + case (false, ComparisonCheckStatus.GreaterThan): + // !(a >= b) -> IsLessThan(b, a) + case (false, ComparisonCheckStatus.GreaterThanOrEqual): + firstArg = rightExpr; // b becomes first arg (upper bound) + secondArg = leftExpr; // a becomes second arg (value) + break; + + default: + throw new InvalidOperationException("Unexpected comparison case."); + } + + ImmutableDictionary.Builder properties = ImmutableDictionary.CreateBuilder(); + properties.Add(ProperAssertMethodNameKey, properAssertMethod); + properties.Add(CodeFixModeKey, CodeFixModeAddArgument); + context.ReportDiagnostic(context.Operation.CreateDiagnostic( + Rule, + additionalLocations: ImmutableArray.Create(conditionArgument.Syntax.GetLocation(), firstArg!.GetLocation(), secondArg!.GetLocation()), + properties: properties.ToImmutable(), + properAssertMethod, + isTrueInvocation ? "IsTrue" : "IsFalse")); + return; + } + EqualityCheckStatus equalityCheckStatus = RecognizeEqualityCheck(conditionArgument, out SyntaxNode? toBecomeExpected, out SyntaxNode? toBecomeActual, out ITypeSymbol? leftType, out ITypeSymbol? rightType); if (equalityCheckStatus != EqualityCheckStatus.Unknown && CanUseTypeAsObject(context.Compilation, leftType) && @@ -392,6 +657,64 @@ private static void AnalyzeIsTrueOrIsFalseInvocation(OperationAnalysisContext co private static void AnalyzeAreEqualOrAreNotEqualInvocation(OperationAnalysisContext context, IOperation expectedArgument, bool isAreEqualInvocation) { + // Check for collection count patterns: collection.Count/Length == 0 or collection.Count/Length == X + if (isAreEqualInvocation) + { + if (TryGetSecondArgumentValue((IInvocationOperation)context.Operation, out IOperation? actualArgumentValue)) + { + // Check if we're comparing a count/length property + CountCheckStatus countStatus = RecognizeCountCheck( + expectedArgument, + actualArgumentValue, + out SyntaxNode? collectionExpr, + out _, + out _); + + if (countStatus != CountCheckStatus.Unknown) + { + string properAssertMethod = countStatus == CountCheckStatus.IsEmpty ? "IsEmpty" : "HasCount"; + + ImmutableDictionary.Builder properties = ImmutableDictionary.CreateBuilder(); + properties.Add(ProperAssertMethodNameKey, properAssertMethod); + + if (countStatus == CountCheckStatus.IsEmpty) + { + // Assert.IsEmpty(collection) + properties.Add(CodeFixModeKey, CodeFixModeCollectionCount); + context.ReportDiagnostic(context.Operation.CreateDiagnostic( + Rule, + additionalLocations: ImmutableArray.Create( + expectedArgument.Syntax.GetLocation(), // argument to remove/modify + actualArgumentValue.Syntax.GetLocation(), // argument to remove/modify + collectionExpr!.GetLocation()), // collection expression + properties: properties.ToImmutable(), + properAssertMethod, + "AreEqual")); + } + else + { + // Assert.HasCount(expectedCount, collection) + properties.Add(CodeFixModeKey, CodeFixModeCollectionCount); + SyntaxNode expectedCountExpr = expectedArgument.ConstantValue.HasValue && expectedArgument.ConstantValue.Value is int ? + expectedArgument.Syntax : actualArgumentValue.Syntax; + + context.ReportDiagnostic(context.Operation.CreateDiagnostic( + Rule, + additionalLocations: ImmutableArray.Create( + expectedArgument.Syntax.GetLocation(), // first original argument + actualArgumentValue.Syntax.GetLocation(), // second original argument + collectionExpr!.GetLocation(), // collection expression + expectedCountExpr.GetLocation()), // count value expression + properties: properties.ToImmutable(), + properAssertMethod, + "AreEqual")); + } + + return; + } + } + } + // Don't flag a warning for Assert.AreNotEqual([true|false], x). // This is not the same as Assert.IsFalse(x). if (isAreEqualInvocation && expectedArgument is ILiteralOperation { ConstantValue: { HasValue: true, Value: bool expectedLiteralBoolean } }) @@ -446,6 +769,49 @@ actualArgumentValue.Type is { } actualType && } } + private static CountCheckStatus RecognizeCountCheck( + IOperation expectedArgument, + IOperation actualArgument, + out SyntaxNode? collectionExpression, + out SyntaxNode? countExpression, + out int countValue) + { + // Check if expectedArgument is a literal and actualArgument is a count/length property + if (expectedArgument.ConstantValue.HasValue && + expectedArgument.ConstantValue.Value is int expectedValue && + expectedValue >= 0 && + actualArgument is IPropertyReferenceOperation propertyRef && + propertyRef.Property.Name is "Count" or "Length" && + propertyRef.Instance?.Type is not null && + IsCollectionType(propertyRef.Instance.Type)) + { + collectionExpression = propertyRef.Instance.Syntax; + countExpression = propertyRef.Syntax; + countValue = expectedValue; + return expectedValue == 0 ? CountCheckStatus.IsEmpty : CountCheckStatus.HasCount; + } + + // Check if actualArgument is a literal and expectedArgument is a count/length property + if (actualArgument.ConstantValue.HasValue && + actualArgument.ConstantValue.Value is int actualValue && + actualValue >= 0 && + expectedArgument is IPropertyReferenceOperation propertyRef2 && + propertyRef2.Property.Name is "Count" or "Length" && + propertyRef2.Instance?.Type is not null && + IsCollectionType(propertyRef2.Instance.Type)) + { + collectionExpression = propertyRef2.Instance.Syntax; + countExpression = propertyRef2.Syntax; + countValue = actualValue; + return actualValue == 0 ? CountCheckStatus.IsEmpty : CountCheckStatus.HasCount; + } + + collectionExpression = null; + countExpression = null; + countValue = 0; + return CountCheckStatus.Unknown; + } + private static bool TryGetFirstArgumentValue(IInvocationOperation operation, [NotNullWhen(true)] out IOperation? argumentValue) => TryGetArgumentValueForParameterOrdinal(operation, 0, out argumentValue); diff --git a/test/UnitTests/MSTest.Analyzers.UnitTests/UseProperAssertMethodsAnalyzerTests.cs b/test/UnitTests/MSTest.Analyzers.UnitTests/UseProperAssertMethodsAnalyzerTests.cs index 0be2307acd..227bd1fd20 100644 --- a/test/UnitTests/MSTest.Analyzers.UnitTests/UseProperAssertMethodsAnalyzerTests.cs +++ b/test/UnitTests/MSTest.Analyzers.UnitTests/UseProperAssertMethodsAnalyzerTests.cs @@ -1309,4 +1309,562 @@ public void MyTestMethod() await VerifyCS.VerifyAnalyzerAsync(code); } + + #region New test cases for string methods + + [TestMethod] + public async Task WhenAssertIsTrueWithStringStartsWith() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + string myString = "Hello World"; + {|#0:Assert.IsTrue(myString.StartsWith("Hello"))|}; + } + } + """; + + string fixedCode = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + string myString = "Hello World"; + Assert.StartsWith("Hello", myString); + } + } + """; + + await VerifyCS.VerifyCodeFixAsync( + code, + // /0/Test0.cs(10,9): info MSTEST0037: Use 'Assert.StartsWith' instead of 'Assert.IsTrue' + VerifyCS.DiagnosticIgnoringAdditionalLocations().WithLocation(0).WithArguments("StartsWith", "IsTrue"), + fixedCode); + } + + [TestMethod] + public async Task WhenAssertIsTrueWithStringEndsWith() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + string myString = "Hello World"; + {|#0:Assert.IsTrue(myString.EndsWith("World"))|}; + } + } + """; + + string fixedCode = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + string myString = "Hello World"; + Assert.EndsWith("World", myString); + } + } + """; + + await VerifyCS.VerifyCodeFixAsync( + code, + // /0/Test0.cs(10,9): info MSTEST0037: Use 'Assert.EndsWith' instead of 'Assert.IsTrue' + VerifyCS.DiagnosticIgnoringAdditionalLocations().WithLocation(0).WithArguments("EndsWith", "IsTrue"), + fixedCode); + } + + [TestMethod] + public async Task WhenAssertIsTrueWithStringContains() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + string myString = "Hello World"; + {|#0:Assert.IsTrue(myString.Contains("lo Wo"))|}; + } + } + """; + + string fixedCode = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + string myString = "Hello World"; + Assert.Contains("lo Wo", myString); + } + } + """; + + await VerifyCS.VerifyCodeFixAsync( + code, + // /0/Test0.cs(10,9): info MSTEST0037: Use 'Assert.Contains' instead of 'Assert.IsTrue' + VerifyCS.DiagnosticIgnoringAdditionalLocations().WithLocation(0).WithArguments("Contains", "IsTrue"), + fixedCode); + } + + [TestMethod] + public async Task WhenAssertIsFalseWithStringStartsWith() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + string myString = "Hello World"; + Assert.IsFalse(myString.StartsWith("Hello")); + } + } + """; + + await VerifyCS.VerifyAnalyzerAsync(code); + } + + [TestMethod] + public async Task WhenAssertIsFalseWithStringEndsWith() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + string myString = "Hello World"; + Assert.IsFalse(myString.EndsWith("World")); + } + } + """; + + await VerifyCS.VerifyAnalyzerAsync(code); + } + + [TestMethod] + public async Task WhenAssertIsFalseWithStringContains() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + string myString = "Hello World"; + Assert.IsFalse(myString.Contains("test")); + } + } + """; + + await VerifyCS.VerifyAnalyzerAsync(code); + } + + #endregion + + #region New test cases for collection methods + + [TestMethod] + public async Task WhenAssertIsTrueWithCollectionContains() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + using System.Collections.Generic; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + var list = new List { 1, 2, 3 }; + {|#0:Assert.IsTrue(list.Contains(2))|}; + } + } + """; + + string fixedCode = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + using System.Collections.Generic; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + var list = new List { 1, 2, 3 }; + Assert.Contains(2, list); + } + } + """; + + await VerifyCS.VerifyCodeFixAsync( + code, + // /0/Test0.cs(11,9): info MSTEST0037: Use 'Assert.Contains' instead of 'Assert.IsTrue' + VerifyCS.DiagnosticIgnoringAdditionalLocations().WithLocation(0).WithArguments("Contains", "IsTrue"), + fixedCode); + } + + #endregion + + #region New test cases for comparisons + + [TestMethod] + public async Task WhenAssertIsTrueWithGreaterThanComparison() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + int a = 5; + int b = 3; + {|#0:Assert.IsTrue(a > b)|}; + } + } + """; + + string fixedCode = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + int a = 5; + int b = 3; + Assert.IsGreaterThan(b, a); + } + } + """; + + await VerifyCS.VerifyCodeFixAsync( + code, + // /0/Test0.cs(11,9): info MSTEST0037: Use 'Assert.IsGreaterThan' instead of 'Assert.IsTrue' + VerifyCS.DiagnosticIgnoringAdditionalLocations().WithLocation(0).WithArguments("IsGreaterThan", "IsTrue"), + fixedCode); + } + + [TestMethod] + public async Task WhenAssertIsFalseWithGreaterThanComparison() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + int a = 5; + int b = 3; + {|#0:Assert.IsFalse(a > b)|}; + } + } + """; + + string fixedCode = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + int a = 5; + int b = 3; + Assert.IsLessThanOrEqualTo(b, a); + } + } + """; + + await VerifyCS.VerifyCodeFixAsync( + code, + // /0/Test0.cs(11,9): info MSTEST0037: Use 'Assert.IsLessThanOrEqualTo' instead of 'Assert.IsFalse' + VerifyCS.DiagnosticIgnoringAdditionalLocations().WithLocation(0).WithArguments("IsLessThanOrEqualTo", "IsFalse"), + fixedCode); + } + + [TestMethod] + public async Task WhenAssertIsTrueWithEqualsComparison() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + int a = 5; + int b = 5; + {|#0:Assert.IsTrue(a == b)|}; + } + } + """; + + string fixedCode = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + int a = 5; + int b = 5; + Assert.AreEqual(b, a); + } + } + """; + + await VerifyCS.VerifyCodeFixAsync( + code, + // /0/Test0.cs(11,9): info MSTEST0037: Use 'Assert.AreEqual' instead of 'Assert.IsTrue' + VerifyCS.DiagnosticIgnoringAdditionalLocations().WithLocation(0).WithArguments("AreEqual", "IsTrue"), + fixedCode); + } + + [TestMethod] + public async Task WhenAssertIsFalseWithEqualsComparison() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + int a = 5; + int b = 3; + {|#0:Assert.IsFalse(a == b)|}; + } + } + """; + + string fixedCode = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + int a = 5; + int b = 3; + Assert.AreNotEqual(b, a); + } + } + """; + + await VerifyCS.VerifyCodeFixAsync( + code, + // /0/Test0.cs(11,9): info MSTEST0037: Use 'Assert.AreNotEqual' instead of 'Assert.IsFalse' + VerifyCS.DiagnosticIgnoringAdditionalLocations().WithLocation(0).WithArguments("AreNotEqual", "IsFalse"), + fixedCode); + } + + #endregion + + #region New test cases for collection count + + [TestMethod] + public async Task WhenAssertAreEqualWithCollectionCountZero() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + using System.Collections.Generic; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + var list = new List(); + {|#0:Assert.AreEqual(0, list.Count)|}; + } + } + """; + + string fixedCode = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + using System.Collections.Generic; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + var list = new List(); + Assert.IsEmpty(list); + } + } + """; + + await VerifyCS.VerifyCodeFixAsync( + code, + // /0/Test0.cs(11,9): info MSTEST0037: Use 'Assert.IsEmpty' instead of 'Assert.AreEqual' + VerifyCS.DiagnosticIgnoringAdditionalLocations().WithLocation(0).WithArguments("IsEmpty", "AreEqual"), + fixedCode); + } + + [TestMethod] + public async Task WhenAssertAreEqualWithCollectionCountNonZero() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + using System.Collections.Generic; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + var list = new List { 1, 2, 3 }; + {|#0:Assert.AreEqual(3, list.Count)|}; + } + } + """; + + string fixedCode = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + using System.Collections.Generic; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + var list = new List { 1, 2, 3 }; + Assert.HasCount(3, list); + } + } + """; + + await VerifyCS.VerifyCodeFixAsync( + code, + // /0/Test0.cs(11,9): info MSTEST0037: Use 'Assert.HasCount' instead of 'Assert.AreEqual' + VerifyCS.DiagnosticIgnoringAdditionalLocations().WithLocation(0).WithArguments("HasCount", "AreEqual"), + fixedCode); + } + + [TestMethod] + public async Task WhenAssertAreNotEqualWithCollectionCountZero() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + using System.Collections.Generic; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + var list = new List(); + Assert.AreNotEqual(0, list.Count); + } + } + """; + + await VerifyCS.VerifyAnalyzerAsync(code); + } + + [TestMethod] + public async Task WhenAssertAreNotEqualWithCollectionCountNonZero() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + using System.Collections.Generic; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + var list = new List { 1, 2, 3 }; + Assert.AreNotEqual(3, list.Count); + } + } + """; + + await VerifyCS.VerifyAnalyzerAsync(code); + } + + [TestMethod] + public async Task WhenAssertAreNotEqualWithArrayLength() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + var array = new int[] { 1, 2, 3, 4, 5 }; + Assert.AreNotEqual(5, array.Length); + } + } + """; + + await VerifyCS.VerifyAnalyzerAsync(code); + } + + #endregion } From 4c64e943663452a476b0a089dc11b35d8e020d6a Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Mon, 21 Jul 2025 18:08:11 +0200 Subject: [PATCH 267/541] Always publish test results folder (#6112) --- azure-pipelines-official.yml | 6 ++++-- azure-pipelines.yml | 9 ++++++--- 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/azure-pipelines-official.yml b/azure-pipelines-official.yml index 180ed8a1c0..7af415966c 100644 --- a/azure-pipelines-official.yml +++ b/azure-pipelines-official.yml @@ -175,7 +175,8 @@ extends: displayName: 'Publish Test Results folders' inputs: PathtoPublish: '$(Build.SourcesDirectory)/artifacts/TestResults/$(_BuildConfig)' - ArtifactName: TestResults_Windows + ArtifactName: TestResults_Windows_Attempt$(System.JobAttempt) + condition: always() - task: NuGetAuthenticate@1 displayName: 'NuGet Authenticate to test-tools feed' @@ -221,7 +222,8 @@ extends: displayName: 'Publish Test Results folders' inputs: PathtoPublish: '$(Build.SourcesDirectory)/artifacts/TestResults/$(_BuildConfig)' - ArtifactName: TestResults_Linux + ArtifactName: TestResults_Linux_Attempt$(System.JobAttempt) + condition: always() - ${{ if eq(variables['Build.SourceBranchName'], 'main') }}: - template: /eng/common/templates-official/job/onelocbuild.yml@self diff --git a/azure-pipelines.yml b/azure-pipelines.yml index 8c10a6e4cc..6a746387a5 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -127,7 +127,8 @@ stages: displayName: 'Publish Test Results folders' inputs: PathtoPublish: '$(Build.SourcesDirectory)/artifacts/TestResults/$(_BuildConfig)' - ArtifactName: TestResults_Windows_$(_BuildConfig) + ArtifactName: TestResults_Windows_$(_BuildConfig)_Attempt$(System.JobAttempt) + condition: always() - task: CopyFiles@2 displayName: 'Copy binlogs' @@ -204,7 +205,8 @@ stages: displayName: 'Publish Test Results folders' inputs: PathtoPublish: '$(Build.SourcesDirectory)/artifacts/TestResults/$(_BuildConfig)' - ArtifactName: TestResults_Linux_$(_BuildConfig) + ArtifactName: TestResults_Linux_$(_BuildConfig)_Attempt$(System.JobAttempt) + condition: always() - task: CopyFiles@2 displayName: 'Copy binlogs' @@ -267,7 +269,8 @@ stages: displayName: 'Publish Test Results folders' inputs: PathtoPublish: '$(Build.SourcesDirectory)/artifacts/TestResults/$(_BuildConfig)' - ArtifactName: TestResults_MacOs_$(_BuildConfig) + ArtifactName: TestResults_MacOs_$(_BuildConfig)_Attempt$(System.JobAttempt) + condition: always() - task: CopyFiles@2 displayName: 'Copy binlogs' From 689dd232eaca5acc036c832240294534fe811ffe Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Mon, 21 Jul 2025 21:04:52 +0200 Subject: [PATCH 268/541] Update SDK to latest from main (#6115) --- global.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/global.json b/global.json index 0e6ed74a6c..61875203a0 100644 --- a/global.json +++ b/global.json @@ -1,6 +1,6 @@ { "tools": { - "dotnet": "10.0.100-preview.7.25359.101", + "dotnet": "10.0.100-preview.7.25368.105", "runtimes": { "dotnet": [ "3.1.32", @@ -23,7 +23,7 @@ } }, "sdk": { - "version": "10.0.100-preview.7.25359.101", + "version": "10.0.100-preview.7.25368.105", "paths": [ ".dotnet", "$host$" From 918cd6f7576cbd06957e7f358fb435a0cf201398 Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Tue, 22 Jul 2025 06:11:18 +0200 Subject: [PATCH 269/541] [main] Update dependencies from devdiv/DevDiv/vs-code-coverage (#6119) Co-authored-by: dotnet-maestro[bot] --- eng/Version.Details.xml | 4 ++-- eng/Versions.props | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index 5e5b47edd6..28e4331a8a 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -13,9 +13,9 @@ https://github.com/dotnet/arcade d777c20040bdc2e52b372fa98dcb84141ed692d3 - + https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage - b14b5e956e64fc7de907695a64adba376a48279c + 6140a1b569c1205f4f596d4752c95a43c0f06d06 https://github.com/microsoft/testfx diff --git a/eng/Versions.props b/eng/Versions.props index 975d4d378d..2e8e813d02 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -8,7 +8,7 @@ 10.0.0-beta.25367.5 - 18.0.0-preview.25367.1 + 18.0.0-preview.25371.1 3.10.0-preview.25369.5 1.8.0-preview.25369.5 From a2b7143f086b26a8e8ce92711ab41b897b2af46b Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Tue, 22 Jul 2025 10:47:38 +0200 Subject: [PATCH 270/541] [main] Update dependencies from microsoft/testfx (#6120) Co-authored-by: dotnet-maestro[bot] --- eng/Version.Details.xml | 8 ++--- eng/Versions.props | 4 +-- .../MaxFailedTestsExtensionTests.cs | 4 +-- .../RunnerTests.cs | 2 +- .../ServerModeTests.cs | 2 +- .../TimeoutTests.cs | 2 +- .../CrashPlusHangDumpTests.cs | 8 ++--- .../ExecutionTests.cs | 2 +- .../MSBuild.KnownExtensionRegistration.cs | 12 ++++---- .../MSBuildTests.ConfigurationFile.cs | 2 +- .../MSBuildTests.GenerateEntryPoint.cs | 4 +-- .../RetryFailedTestsTests.cs | 4 +-- .../Adapter_ExecuteRequestAsyncTests.cs | 7 ++--- .../BFSTestNodeVisitorTests.cs | 12 ++++---- .../TrxTests.cs | 6 ++-- .../ObjectModel/ObjectModelConvertersTests.cs | 30 +++++++++---------- .../CommandLine/CommandLineHandlerTests.cs | 4 +-- .../Helpers/SystemAsyncMonitorTests.cs | 2 +- .../IPC/IPCTests.cs | 8 ++--- .../Messages/AsynchronousMessageBusTests.cs | 4 +-- .../Messages/PropertyBagTests.cs | 12 ++++---- .../ServerDataConsumerServiceTests.cs | 2 +- .../Services/ServiceProviderTests.cs | 2 +- .../TestApplicationBuilderTests.cs | 8 ++--- 24 files changed, 75 insertions(+), 76 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index 28e4331a8a..d937350ea9 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -17,13 +17,13 @@ https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage 6140a1b569c1205f4f596d4752c95a43c0f06d06 - + https://github.com/microsoft/testfx - 639e5cd9730d9642d93c2828b1e4686a164e040c + 4a8fcdaacd6ff086be895fc4aaf9e5c7d49e9f24 - + https://github.com/microsoft/testfx - 639e5cd9730d9642d93c2828b1e4686a164e040c + 4a8fcdaacd6ff086be895fc4aaf9e5c7d49e9f24 diff --git a/eng/Versions.props b/eng/Versions.props index 2e8e813d02..5ee36231a6 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -10,7 +10,7 @@ 10.0.0-beta.25367.5 18.0.0-preview.25371.1 - 3.10.0-preview.25369.5 - 1.8.0-preview.25369.5 + 3.10.0-preview.25371.5 + 1.8.0-preview.25371.5 diff --git a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/MaxFailedTestsExtensionTests.cs b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/MaxFailedTestsExtensionTests.cs index 6d11054c28..0df04d170a 100644 --- a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/MaxFailedTestsExtensionTests.cs +++ b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/MaxFailedTestsExtensionTests.cs @@ -26,8 +26,8 @@ public async Task SimpleMaxFailedTestsScenario(string tfm) // We can't know the number of tests that will be executed exactly due to the async // nature of publish/consume on the platform side. But we expect the cancellation to // happen "fast" enough that we don't execute all tests. - Assert.IsTrue(total < 12); - Assert.IsTrue(total >= 5); + Assert.IsLessThan(12, total); + Assert.IsGreaterThanOrEqualTo(5, total); testHostResult = await testHost.ExecuteAsync(); testHostResult.AssertExitCodeIs(ExitCodes.AtLeastOneTestFailed); diff --git a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/RunnerTests.cs b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/RunnerTests.cs index e8316ee811..f33fa0eb98 100644 --- a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/RunnerTests.cs +++ b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/RunnerTests.cs @@ -102,7 +102,7 @@ public async SystemTask EnableMSTestRunner_False_Will_Run_Empty_Program_EntryPoi { if (TargetFrameworks.NetFramework.Any(x => x == tfm)) { - Assert.IsTrue(ex.Message.Contains("Program does not contain a static 'Main' method suitable for an entry point"), ex.Message); + Assert.Contains("Program does not contain a static 'Main' method suitable for an entry point", ex.Message, ex.Message); // .NET Framework does not insert the entry point for empty program. } } diff --git a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/ServerModeTests.cs b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/ServerModeTests.cs index 1405d7ad71..a4975ed3da 100644 --- a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/ServerModeTests.cs +++ b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/ServerModeTests.cs @@ -35,7 +35,7 @@ public async Task DiscoverAndRun(string tfm) await Task.WhenAll(discoveryListener.WaitCompletion(), runListener.WaitCompletion()); Assert.AreEqual(1, discoveryCollector.TestNodeUpdates.Count(x => x.Node.NodeType == "action"), "Wrong number of discovery"); - Assert.AreEqual(2, runCollector.TestNodeUpdates.Count, "Wrong number of updates"); + Assert.HasCount(2, runCollector.TestNodeUpdates); Assert.AreNotEqual(0, logs.Count, "Logs are empty"); Assert.IsFalse(telemetry.IsEmpty, "telemetry is empty"); await jsonClient.Exit(); diff --git a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/TimeoutTests.cs b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/TimeoutTests.cs index 9c486257be..05cab7771b 100644 --- a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/TimeoutTests.cs +++ b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/TimeoutTests.cs @@ -406,7 +406,7 @@ private static async Task RunAndAssertWithRunSettingsAsync(string tfm, int timeo if (assertAttributePrecedence) { - Assert.IsTrue(stopwatch.Elapsed.TotalSeconds < 25); + Assert.IsLessThan(25, stopwatch.Elapsed.TotalSeconds); } testHostResult.AssertOutputContains($"{InfoByKind[entryKind].Prefix} method '{InfoByKind[entryKind].MethodFullName}' timed out after {timeoutValue}ms"); diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/CrashPlusHangDumpTests.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/CrashPlusHangDumpTests.cs index 11f81640bf..5422a5d334 100644 --- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/CrashPlusHangDumpTests.cs +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/CrashPlusHangDumpTests.cs @@ -30,8 +30,8 @@ public async Task CrashPlusHangDump_InCaseOfCrash_CreateCrashDump() testHostResult.AssertOutputMatchesRegex(@"Test host process with PID \'.+\' crashed, a dump file was generated"); testHostResult.AssertOutputDoesNotContain(@"Hang dump timeout '00:00:08' expired"); - Assert.IsTrue(Directory.GetFiles(resultDirectory, "CrashPlusHangDump*_crash.dmp", SearchOption.AllDirectories).Length > 0, $"Dump file not found '{TargetFrameworks.NetCurrent}'\n{testHostResult}'"); - Assert.IsFalse(Directory.GetFiles(resultDirectory, "CrashPlusHangDump*_hang.dmp", SearchOption.AllDirectories).Length > 0, $"Dump file not found '{TargetFrameworks.NetCurrent}'\n{testHostResult}'"); + Assert.IsGreaterThan(0, Directory.GetFiles(resultDirectory, "CrashPlusHangDump*_crash.dmp", SearchOption.AllDirectories).Length, $"Dump file not found '{TargetFrameworks.NetCurrent}'\n{testHostResult}'"); + Assert.IsLessThanOrEqualTo(0, Directory.GetFiles(resultDirectory, "CrashPlusHangDump*_hang.dmp", SearchOption.AllDirectories).Length, $"Dump file not found '{TargetFrameworks.NetCurrent}'\n{testHostResult}'"); } [TestMethod] @@ -58,8 +58,8 @@ public async Task CrashPlusHangDump_InCaseOfHang_CreateHangDump() testHostResult.AssertOutputDoesNotMatchRegex(@"Test host process with PID '.+' crashed, a dump file was generated"); testHostResult.AssertOutputContains(@"Hang dump timeout of '00:00:08' expired"); - Assert.IsFalse(Directory.GetFiles(resultDirectory, "CrashPlusHangDump.dll*_crash.dmp", SearchOption.AllDirectories).Length > 0, $"Dump file not found '{TargetFrameworks.NetCurrent}'\n{testHostResult}'"); - Assert.IsTrue(Directory.GetFiles(resultDirectory, "CrashPlusHangDump*_hang.dmp", SearchOption.AllDirectories).Length > 0, $"Dump file not found '{TargetFrameworks.NetCurrent}'\n{testHostResult}'"); + Assert.IsLessThanOrEqualTo(0, Directory.GetFiles(resultDirectory, "CrashPlusHangDump.dll*_crash.dmp", SearchOption.AllDirectories).Length, $"Dump file not found '{TargetFrameworks.NetCurrent}'\n{testHostResult}'"); + Assert.IsGreaterThan(0, Directory.GetFiles(resultDirectory, "CrashPlusHangDump*_hang.dmp", SearchOption.AllDirectories).Length, $"Dump file not found '{TargetFrameworks.NetCurrent}'\n{testHostResult}'"); } public sealed class TestAssetFixture() : TestAssetFixtureBase(AcceptanceFixture.NuGetGlobalPackagesFolder) diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/ExecutionTests.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/ExecutionTests.cs index 0f60919345..ece6d5b0fe 100644 --- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/ExecutionTests.cs +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/ExecutionTests.cs @@ -170,7 +170,7 @@ public async Task Exec_Honor_Request_Complete(string tfm) TestHostResult testHostResult = await testHost.ExecuteAsync(); stopwatch.Stop(); Assert.AreEqual(ExitCodes.Success, testHostResult.ExitCode); - Assert.IsTrue(stopwatch.Elapsed.TotalSeconds > 3); + Assert.IsGreaterThan(3, stopwatch.Elapsed.TotalSeconds); } public sealed class TestAssetFixture() : TestAssetFixtureBase(AcceptanceFixture.NuGetGlobalPackagesFolder) diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/MSBuild.KnownExtensionRegistration.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/MSBuild.KnownExtensionRegistration.cs index 72c7d84f37..717e6bbe24 100644 --- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/MSBuild.KnownExtensionRegistration.cs +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/MSBuild.KnownExtensionRegistration.cs @@ -35,12 +35,12 @@ public async Task Microsoft_Testing_Platform_Extensions_ShouldBe_Correctly_Regis SL.Task testingPlatformSelfRegisteredExtensions = generateSelfRegisteredExtensions.FindChildrenRecursive().Single(t => t.Name == "TestingPlatformSelfRegisteredExtensions"); SL.Message generatedSource = testingPlatformSelfRegisteredExtensions.FindChildrenRecursive().Single(m => m.Text.Contains("SelfRegisteredExtensions source:")); - Assert.IsTrue(generatedSource.Text.Contains("Microsoft.Testing.Extensions.CrashDump.TestingPlatformBuilderHook.AddExtensions"), generatedSource.Text); - Assert.IsTrue(generatedSource.Text.Contains("Microsoft.Testing.Extensions.HangDump.TestingPlatformBuilderHook.AddExtensions"), generatedSource.Text); - Assert.IsTrue(generatedSource.Text.Contains("Microsoft.Testing.Extensions.HotReload.TestingPlatformBuilderHook.AddExtensions"), generatedSource.Text); - Assert.IsTrue(generatedSource.Text.Contains("Microsoft.Testing.Extensions.Retry.TestingPlatformBuilderHook.AddExtensions"), generatedSource.Text); - Assert.IsTrue(generatedSource.Text.Contains("Microsoft.Testing.Extensions.Telemetry.TestingPlatformBuilderHook.AddExtensions"), generatedSource.Text); - Assert.IsTrue(generatedSource.Text.Contains("Microsoft.Testing.Extensions.TrxReport.TestingPlatformBuilderHook.AddExtensions"), generatedSource.Text); + Assert.Contains("Microsoft.Testing.Extensions.CrashDump.TestingPlatformBuilderHook.AddExtensions", generatedSource.Text, generatedSource.Text); + Assert.Contains("Microsoft.Testing.Extensions.HangDump.TestingPlatformBuilderHook.AddExtensions", generatedSource.Text, generatedSource.Text); + Assert.Contains("Microsoft.Testing.Extensions.HotReload.TestingPlatformBuilderHook.AddExtensions", generatedSource.Text, generatedSource.Text); + Assert.Contains("Microsoft.Testing.Extensions.Retry.TestingPlatformBuilderHook.AddExtensions", generatedSource.Text, generatedSource.Text); + Assert.Contains("Microsoft.Testing.Extensions.Telemetry.TestingPlatformBuilderHook.AddExtensions", generatedSource.Text, generatedSource.Text); + Assert.Contains("Microsoft.Testing.Extensions.TrxReport.TestingPlatformBuilderHook.AddExtensions", generatedSource.Text, generatedSource.Text); } private const string SourceCode = """ diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/MSBuildTests.ConfigurationFile.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/MSBuildTests.ConfigurationFile.cs index e99e1c7c28..42cbee1fee 100644 --- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/MSBuildTests.ConfigurationFile.cs +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/MSBuildTests.ConfigurationFile.cs @@ -23,7 +23,7 @@ public async Task ConfigFileGeneration_CorrectlyCreateAndCacheAndCleaned(string string generatedConfigurationFile = Path.Combine(testHost.DirectoryName, "MSBuildTests.testconfig.json"); Assert.IsTrue(File.Exists(generatedConfigurationFile)); Assert.AreEqual(ConfigurationContent.Trim(), File.ReadAllText(generatedConfigurationFile).Trim()); - Assert.IsTrue(compilationResult.StandardOutput.Contains("Microsoft Testing Platform configuration file written")); + Assert.Contains("Microsoft Testing Platform configuration file written", compilationResult.StandardOutput); compilationResult = await DotnetCli.RunAsync($"{(verb == Verb.publish ? $"publish -f {tfm}" : "build")} -v:normal -nodeReuse:false {testAsset.TargetAssetPath} -c {compilationMode}", AcceptanceFixture.NuGetGlobalPackagesFolder.Path); Assert.IsTrue(File.Exists(generatedConfigurationFile)); diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/MSBuildTests.GenerateEntryPoint.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/MSBuildTests.GenerateEntryPoint.cs index 50dbb77d3d..ff2364b1fb 100644 --- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/MSBuildTests.GenerateEntryPoint.cs +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/MSBuildTests.GenerateEntryPoint.cs @@ -130,7 +130,7 @@ private async Task GenerateAndVerifyLanguageSpecificEntryPointAsync(string asset var testHost = TestInfrastructure.TestHost.LocateFrom(testAsset.TargetAssetPath, AssetName, tfm, rid: RID, verb: verb, buildConfiguration: compilationMode); TestHostResult testHostResult = await testHost.ExecuteAsync(); testHostResult.AssertExitCodeIs(ExitCodes.Success); - Assert.IsTrue(testHostResult.StandardOutput.Contains("Passed!")); + Assert.Contains("Passed!", testHostResult.StandardOutput); SL.Target coreCompile = binLog.FindChildrenRecursive().Single(t => t.Name == "CoreCompile" && t.Children.Count > 0); SL.Task csc = coreCompile.FindChildrenRecursive(t => t.Name == cscProcessName).Single(); @@ -147,7 +147,7 @@ private async Task GenerateAndVerifyLanguageSpecificEntryPointAsync(string asset testHost = TestInfrastructure.TestHost.LocateFrom(testAsset.TargetAssetPath, AssetName, tfm, rid: RID, verb: verb, buildConfiguration: compilationMode); testHostResult = await testHost.ExecuteAsync(); Assert.AreEqual(ExitCodes.Success, testHostResult.ExitCode); - Assert.IsTrue(testHostResult.StandardOutput.Contains("Passed!")); + Assert.Contains("Passed!", testHostResult.StandardOutput); } private const string CSharpSourceCode = """ diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/RetryFailedTestsTests.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/RetryFailedTestsTests.cs index 5e8fa515e7..b58782582a 100644 --- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/RetryFailedTestsTests.cs +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/RetryFailedTestsTests.cs @@ -45,7 +45,7 @@ public async Task RetryFailedTests_OnlyRetryTimes_Succeeds(string tfm, bool fail testHostResult.AssertOutputContains("Passed! -"); string[] trxFiles = Directory.GetFiles(resultDirectory, "*.trx", SearchOption.AllDirectories); - Assert.AreEqual(2, trxFiles.Length); + Assert.HasCount(2, trxFiles); string trxContents1 = File.ReadAllText(trxFiles[0]); string trxContents2 = File.ReadAllText(trxFiles[1]); Assert.AreNotEqual(trxContents1, trxContents2); @@ -85,7 +85,7 @@ public async Task RetryFailedTests_MaxPercentage_Succeeds(string tfm, bool fail) string retriesPath = Path.Combine(resultDirectory, "Retries"); Assert.IsTrue(Directory.Exists(retriesPath)); string[] retriesDirectories = Directory.GetDirectories(retriesPath); - Assert.AreEqual(1, retriesDirectories.Length); + Assert.HasCount(1, retriesDirectories); string createdDirName = Path.GetFileName(retriesDirectories[0]); // Asserts that we are not using long names, to reduce long path issues. diff --git a/test/UnitTests/MSTest.Engine.UnitTests/Adapter_ExecuteRequestAsyncTests.cs b/test/UnitTests/MSTest.Engine.UnitTests/Adapter_ExecuteRequestAsyncTests.cs index 620cce4afd..73bc6395ab 100644 --- a/test/UnitTests/MSTest.Engine.UnitTests/Adapter_ExecuteRequestAsyncTests.cs +++ b/test/UnitTests/MSTest.Engine.UnitTests/Adapter_ExecuteRequestAsyncTests.cs @@ -77,14 +77,13 @@ await adapter.ExecuteRequestAsync(new( Platform.Extensions.Messages.TestNode lastNode = nodeStateChanges.Last().TestNode; _ = lastNode.Properties.Single(); Assert.AreEqual("Oh no!", lastNode.Properties.Single().Exception!.Message); - Assert.IsTrue( - lastNode.Properties.Single().Exception!.StackTrace! - .Contains(nameof(ExecutableNode_ThatThrows_ShouldReportError)), "lastNode properties should contain the name of the test"); + Assert.Contains( + nameof(ExecutableNode_ThatThrows_ShouldReportError), lastNode.Properties.Single().Exception!.StackTrace!, "lastNode properties should contain the name of the test"); TimingProperty timingProperty = lastNode.Properties.Single(); Assert.AreEqual(fakeClock.UsedTimes[0], timingProperty.GlobalTiming.StartTime); Assert.IsTrue(timingProperty.GlobalTiming.StartTime <= timingProperty.GlobalTiming.EndTime, "start time is before (or the same as) stop time"); Assert.AreEqual(fakeClock.UsedTimes[1], timingProperty.GlobalTiming.EndTime); - Assert.IsTrue(timingProperty.GlobalTiming.Duration.TotalMilliseconds > 0, $"duration should be greater than 0"); + Assert.IsGreaterThan(0, timingProperty.GlobalTiming.Duration.TotalMilliseconds, $"duration should be greater than 0"); } private sealed class FakeClock : IClock diff --git a/test/UnitTests/MSTest.Engine.UnitTests/BFSTestNodeVisitorTests.cs b/test/UnitTests/MSTest.Engine.UnitTests/BFSTestNodeVisitorTests.cs index da775f0875..0676c3dd5f 100644 --- a/test/UnitTests/MSTest.Engine.UnitTests/BFSTestNodeVisitorTests.cs +++ b/test/UnitTests/MSTest.Engine.UnitTests/BFSTestNodeVisitorTests.cs @@ -39,7 +39,7 @@ await visitor.VisitAsync((testNode, _) => }); // Assert - Assert.AreEqual(1, includedTestNodes.Count); + Assert.HasCount(1, includedTestNodes); Assert.AreEqual("ID1", includedTestNodes[0].StableUid); } @@ -76,7 +76,7 @@ await visitor.VisitAsync((testNode, _) => }); // Assert - Assert.AreEqual(2, includedTestNodes.Count); + Assert.HasCount(2, includedTestNodes); Assert.AreEqual("ID1", includedTestNodes[0].StableUid); Assert.AreEqual("ID2", includedTestNodes[1].StableUid); } @@ -114,7 +114,7 @@ await visitor.VisitAsync((testNode, _) => }); // Assert - Assert.AreEqual(1, includedTestNodes.Count); + Assert.HasCount(1, includedTestNodes); Assert.AreEqual("ID1", includedTestNodes[0].StableUid); } @@ -136,7 +136,7 @@ await visitor.VisitAsync((testNode, parentNodeUid) => }); // Assert - Assert.AreEqual(3, includedTestNodes.Count); + Assert.HasCount(3, includedTestNodes); Assert.AreEqual("ID1", includedTestNodes[0].Node.StableUid); Assert.IsNull(includedTestNodes[0].ParentNodeUid); @@ -165,7 +165,7 @@ await visitor.VisitAsync((testNode, parentNodeUid) => }); // Assert - Assert.AreEqual(1, includedTestNodes.Count); + Assert.HasCount(1, includedTestNodes); } [TestMethod] @@ -214,7 +214,7 @@ await visitor.VisitAsync((testNode, parentNodeUid) => }); // Assert - Assert.AreEqual(7, includedTestNodes.Count); + Assert.HasCount(7, includedTestNodes); Assert.AreEqual("MyModule", includedTestNodes[0].Node.StableUid); Assert.IsNull(includedTestNodes[0].ParentNodeUid); diff --git a/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/TrxTests.cs b/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/TrxTests.cs index 17ce5c64e7..1dd7387681 100644 --- a/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/TrxTests.cs +++ b/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/TrxTests.cs @@ -68,7 +68,7 @@ public async Task TrxReportEngine_GenerateReportAsyncWithNotExecutedTests_TrxExe XDocument xml = memoryStream.TrxContent; AssertTrxOutcome(xml, "Completed"); string trxContent = xml.ToString(); - Assert.IsTrue(trxContent.Contains(@"notExecuted=""1""")); + Assert.Contains(@"notExecuted=""1""", trxContent); } [TestMethod] @@ -89,7 +89,7 @@ public async Task TrxReportEngine_GenerateReportAsyncWithTimeoutTests_TrxTimeout XDocument xml = memoryStream.TrxContent; AssertTrxOutcome(xml, "Completed"); string trxContent = xml.ToString(); - Assert.IsTrue(trxContent.Contains(@"timeout=""1""")); + Assert.Contains(@"timeout=""1""", trxContent); } [TestMethod] @@ -405,7 +405,7 @@ public async Task TrxReportEngine_GenerateReportAsync_WithAdapterSupportTrxCapab XDocument xml = memoryStream.TrxContent; AssertTrxOutcome(xml, "Completed"); string trxContent = xml.ToString(); - Assert.IsTrue(trxContent.Contains(@"className=""TrxFullyQualifiedTypeName"), trxContent); + Assert.Contains(@"className=""TrxFullyQualifiedTypeName", trxContent, trxContent); } [TestMethod] diff --git a/test/UnitTests/Microsoft.Testing.Extensions.VSTestBridge.UnitTests/ObjectModel/ObjectModelConvertersTests.cs b/test/UnitTests/Microsoft.Testing.Extensions.VSTestBridge.UnitTests/ObjectModel/ObjectModelConvertersTests.cs index 0ee968124d..a619ae84ad 100644 --- a/test/UnitTests/Microsoft.Testing.Extensions.VSTestBridge.UnitTests/ObjectModel/ObjectModelConvertersTests.cs +++ b/test/UnitTests/Microsoft.Testing.Extensions.VSTestBridge.UnitTests/ObjectModel/ObjectModelConvertersTests.cs @@ -67,7 +67,7 @@ public void ToTestNode_WhenTestResultOutcomeIsFailed_TestNodePropertiesContainFa var testNode = testResult.ToTestNode(isTrxEnabled: false, useFullyQualifiedNameAsUid: false, null, new ConsoleCommandLineOptions(), ClientInfo); FailedTestNodeStateProperty[] failedTestNodeStateProperties = [.. testNode.Properties.OfType()]; - Assert.AreEqual(1, failedTestNodeStateProperties.Length); + Assert.HasCount(1, failedTestNodeStateProperties); Assert.IsTrue(failedTestNodeStateProperties[0].Exception is VSTestException); Assert.AreEqual(testResult.ErrorStackTrace, failedTestNodeStateProperties[0].Exception!.StackTrace); Assert.AreEqual(testResult.ErrorMessage, failedTestNodeStateProperties[0].Exception!.Message); @@ -85,7 +85,7 @@ public void ToTestNode_WhenTestResultHasMSTestDiscovererTestCategoryTestProperty var testNode = testResult.ToTestNode(isTrxEnabled: false, useFullyQualifiedNameAsUid: false, new NamedFeatureCapabilityWithVSTestProvider(), new ServerModeCommandLineOptions(), ClientInfo); TestMetadataProperty[] testMetadatas = [.. testNode.Properties.OfType()]; - Assert.AreEqual(1, testMetadatas.Length); + Assert.HasCount(1, testMetadatas); Assert.AreEqual("category1", testMetadatas[0].Key); Assert.AreEqual(string.Empty, testMetadatas[0].Value); } @@ -102,8 +102,8 @@ public void ToTestNode_WhenTestResultHasMSTestDiscovererTestCategoryTestProperty var testNode = testResult.ToTestNode(isTrxEnabled: true, useFullyQualifiedNameAsUid: false, new NamedFeatureCapabilityWithVSTestProvider(), new ServerModeCommandLineOptions(), ClientInfo); TrxCategoriesProperty[] trxCategoriesProperty = [.. testNode.Properties.OfType()]; - Assert.AreEqual(1, trxCategoriesProperty.Length); - Assert.AreEqual(1, trxCategoriesProperty[0].Categories.Length); + Assert.HasCount(1, trxCategoriesProperty); + Assert.HasCount(1, trxCategoriesProperty[0].Categories); Assert.AreEqual("category1", trxCategoriesProperty[0].Categories[0]); } @@ -119,7 +119,7 @@ public void ToTestNode_WhenTestCaseHasOriginalExecutorUriProperty_TestNodeProper var testNode = testCase.ToTestNode(isTrxEnabled: false, useFullyQualifiedNameAsUid: false, new NamedFeatureCapabilityWithVSTestProvider(), new ServerModeCommandLineOptions(), ClientInfo); SerializableKeyValuePairStringProperty[] serializableKeyValuePairStringProperty = [.. testNode.Properties.OfType()]; - Assert.AreEqual(3, serializableKeyValuePairStringProperty.Length); + Assert.HasCount(3, serializableKeyValuePairStringProperty); Assert.AreEqual(VSTestTestNodeProperties.OriginalExecutorUriPropertyName, serializableKeyValuePairStringProperty[0].Key); Assert.AreEqual("https://vs.com/", serializableKeyValuePairStringProperty[0].Value); } @@ -142,7 +142,7 @@ public void ToTestNode_WhenTestResultHasNoFullyQualifiedTypeAndTrxEnabled_Throws string errorMessage = Assert.ThrowsExactly(() => testResult.ToTestNode(isTrxEnabled: true, useFullyQualifiedNameAsUid: false, null, new ConsoleCommandLineOptions(), ClientInfo)).Message; - Assert.IsTrue(errorMessage.Contains("Unable to parse fully qualified type name from test case: ")); + Assert.Contains("Unable to parse fully qualified type name from test case: ", errorMessage); } [TestMethod] @@ -175,10 +175,10 @@ public void ToTestNode_WhenTestResultOutcomeIsNotFoundWithoutSetErrorMessage_Tes var testNode = testResult.ToTestNode(isTrxEnabled: false, useFullyQualifiedNameAsUid: false, null, new ConsoleCommandLineOptions(), ClientInfo); ErrorTestNodeStateProperty[] errorTestNodeStateProperties = [.. testNode.Properties.OfType()]; - Assert.AreEqual(1, errorTestNodeStateProperties.Length); + Assert.HasCount(1, errorTestNodeStateProperties); Assert.IsTrue(errorTestNodeStateProperties[0].Exception is VSTestException); Assert.AreEqual(testResult.ErrorStackTrace, errorTestNodeStateProperties[0].Exception!.StackTrace); - Assert.IsTrue(errorTestNodeStateProperties[0].Exception!.Message.Contains("Not found")); + Assert.Contains("Not found", errorTestNodeStateProperties[0].Exception!.Message); } [TestMethod] @@ -191,7 +191,7 @@ public void ToTestNode_WhenTestResultOutcomeIsSkipped_TestNodePropertiesContainS var testNode = testResult.ToTestNode(isTrxEnabled: false, useFullyQualifiedNameAsUid: false, null, new ConsoleCommandLineOptions(), ClientInfo); SkippedTestNodeStateProperty[] skipTestNodeStateProperties = [.. testNode.Properties.OfType()]; - Assert.AreEqual(1, skipTestNodeStateProperties.Length); + Assert.HasCount(1, skipTestNodeStateProperties); } [TestMethod] @@ -204,7 +204,7 @@ public void ToTestNode_WhenTestResultOutcomeIsNone_TestNodePropertiesContainSkip var testNode = testResult.ToTestNode(isTrxEnabled: false, useFullyQualifiedNameAsUid: false, null, new ConsoleCommandLineOptions(), ClientInfo); SkippedTestNodeStateProperty[] skipTestNodeStateProperties = [.. testNode.Properties.OfType()]; - Assert.AreEqual(1, skipTestNodeStateProperties.Length); + Assert.HasCount(1, skipTestNodeStateProperties); } [TestMethod] @@ -217,7 +217,7 @@ public void ToTestNode_WhenTestResultOutcomeIsPassed_TestNodePropertiesContainPa var testNode = testResult.ToTestNode(isTrxEnabled: false, useFullyQualifiedNameAsUid: false, null, new ConsoleCommandLineOptions(), ClientInfo); PassedTestNodeStateProperty[] passedTestNodeStateProperties = [.. testNode.Properties.OfType()]; - Assert.AreEqual(1, passedTestNodeStateProperties.Length); + Assert.HasCount(1, passedTestNodeStateProperties); } [TestMethod] @@ -228,7 +228,7 @@ public void ToTestNode_WhenTestCaseHasUidAndDisplayNameWithWellKnownClient_TestN var testNode = testCase.ToTestNode(isTrxEnabled: false, useFullyQualifiedNameAsUid: false, new NamedFeatureCapabilityWithVSTestProvider(), new ServerModeCommandLineOptions(), ClientInfo); SerializableKeyValuePairStringProperty[] errorTestNodeStateProperties = [.. testNode.Properties.OfType()]; - Assert.AreEqual(2, errorTestNodeStateProperties.Length, "Expected 2 SerializableKeyValuePairStringProperty"); + Assert.HasCount(2, errorTestNodeStateProperties); Assert.AreEqual("vstest.TestCase.FullyQualifiedName", errorTestNodeStateProperties[0].Key); Assert.AreEqual("SomeFqn", errorTestNodeStateProperties[0].Value); Assert.AreEqual("vstest.TestCase.Id", errorTestNodeStateProperties[1].Key); @@ -246,7 +246,7 @@ public void ToTestNode_WhenTestResultHasTraits_TestNodePropertiesContainIt() var testNode = testResult.ToTestNode(isTrxEnabled: false, useFullyQualifiedNameAsUid: false, new NamedFeatureCapabilityWithVSTestProvider(), new ServerModeCommandLineOptions(), ClientInfo); TestMetadataProperty[] testMetadatas = [.. testNode.Properties.OfType()]; - Assert.AreEqual(1, testMetadatas.Length); + Assert.HasCount(1, testMetadatas); Assert.AreEqual("key", testMetadatas[0].Key); Assert.AreEqual("value", testMetadatas[0].Value); } @@ -267,7 +267,7 @@ public void ToTestNode_WhenTestResultHasMultipleStandardOutputMessages_TestNodeP var testNode = testResult.ToTestNode(isTrxEnabled: false, useFullyQualifiedNameAsUid: false, new NamedFeatureCapabilityWithVSTestProvider(), new ServerModeCommandLineOptions(), ClientInfo); StandardOutputProperty[] standardOutputProperties = [.. testNode.Properties.OfType()]; - Assert.AreEqual(1, standardOutputProperties.Length); + Assert.HasCount(1, standardOutputProperties); Assert.AreEqual($"message1{Environment.NewLine}message2", standardOutputProperties[0].StandardOutput); } @@ -287,7 +287,7 @@ public void ToTestNode_WhenTestResultHasMultipleStandardErrorMessages_TestNodePr var testNode = testResult.ToTestNode(isTrxEnabled: false, useFullyQualifiedNameAsUid: false, new NamedFeatureCapabilityWithVSTestProvider(), new ServerModeCommandLineOptions(), ClientInfo); StandardErrorProperty[] standardErrorProperties = [.. testNode.Properties.OfType()]; - Assert.AreEqual(1, standardErrorProperties.Length); + Assert.HasCount(1, standardErrorProperties); Assert.AreEqual($"message1{Environment.NewLine}message2", standardErrorProperties[0].StandardError); } diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/CommandLineHandlerTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/CommandLineHandlerTests.cs index ffbabc174b..4070f86876 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/CommandLineHandlerTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/CommandLineHandlerTests.cs @@ -275,8 +275,8 @@ public void GetOptionValue_OptionDoesNotExist_ReturnsNull() _outputDisplayMock.Setup(x => x.DisplayAsync(It.IsAny(), It.IsAny())) .Callback((IOutputDeviceDataProducer message, IOutputDeviceData data) => { - Assert.IsTrue(((TextOutputDeviceData)data).Text.Contains("Invalid command line arguments:")); - Assert.IsTrue(((TextOutputDeviceData)data).Text.Contains("Unexpected argument")); + Assert.Contains("Invalid command line arguments:", ((TextOutputDeviceData)data).Text); + Assert.Contains("Unexpected argument", ((TextOutputDeviceData)data).Text); }); CommandLineHandler commandLineHandler = new(parseResult, _extensionCommandLineOptionsProviders, _systemCommandLineOptionsProviders, diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Helpers/SystemAsyncMonitorTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Helpers/SystemAsyncMonitorTests.cs index aaf9ec1547..9a781e1922 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Helpers/SystemAsyncMonitorTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Helpers/SystemAsyncMonitorTests.cs @@ -25,7 +25,7 @@ public async Task AsyncMonitor_ShouldCorrectlyLock() // Give more time to be above 3s Thread.Sleep(500); - Assert.IsTrue(stopwatch.ElapsedMilliseconds > 3000); + Assert.IsGreaterThan(3000, stopwatch.ElapsedMilliseconds); async Task TestLock() { diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/IPCTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/IPCTests.cs index a70e296401..14c03ca924 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/IPCTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/IPCTests.cs @@ -57,10 +57,10 @@ public async Task SingleConnectionNamedPipeServer_MultipleConnection_Fails() await namedPipeClient1.ConnectAsync(_testContext.CancellationTokenSource.Token); waitException.Wait(); - Assert.AreEqual(1, openedPipe.Count); - Assert.AreEqual(1, exceptions.Count); + Assert.HasCount(1, openedPipe); + Assert.HasCount(1, exceptions); Assert.AreEqual(exceptions[0].GetType(), typeof(IOException)); - Assert.IsTrue(exceptions[0].Message.Contains("All pipe instances are busy.")); + Assert.Contains("All pipe instances are busy.", exceptions[0].Message); await waitTask; #if NETCOREAPP @@ -151,7 +151,7 @@ public async Task SingleConnectionNamedPipeServer_RequestReplySerialization_Succ { string currentString = RandomString(random.Next(1024, 1024 * 1024 * 2), random); await namedPipeClient.RequestReplyAsync(new TextMessage(currentString), CancellationToken.None); - Assert.AreEqual(1, receivedMessages.Count); + Assert.HasCount(1, receivedMessages); Assert.AreEqual(receivedMessages.Dequeue(), new TextMessage(currentString)); currentRound--; } diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Messages/AsynchronousMessageBusTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Messages/AsynchronousMessageBusTests.cs index dd45c96de9..1ead95cd3d 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Messages/AsynchronousMessageBusTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Messages/AsynchronousMessageBusTests.cs @@ -88,10 +88,10 @@ public async Task MessageBus_WhenConsumerProducesAndConsumesTheSameType_ShouldNo await proxy.DrainDataAsync(); // assert - Assert.AreEqual(1, consumerA.ConsumedData.Count); + Assert.HasCount(1, consumerA.ConsumedData); Assert.AreEqual(consumerBData, consumerA.ConsumedData[0]); - Assert.AreEqual(1, consumerB.ConsumedData.Count); + Assert.HasCount(1, consumerB.ConsumedData); Assert.AreEqual(consumerAData, consumerB.ConsumedData[0]); } diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Messages/PropertyBagTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Messages/PropertyBagTests.cs index cd65c20d4e..e45f9d5d25 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Messages/PropertyBagTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Messages/PropertyBagTests.cs @@ -40,14 +40,14 @@ public void AddGet_Of_TestNodeStateProperty_Succed() PropertyBag property = new(); Assert.IsFalse(property.Any()); - Assert.AreEqual(0, property.OfType().Length); + Assert.IsEmpty(property.OfType()); property.Add(PassedTestNodeStateProperty.CachedInstance); Assert.AreEqual(PassedTestNodeStateProperty.CachedInstance, property.Single()); Assert.AreEqual(PassedTestNodeStateProperty.CachedInstance, property.SingleOrDefault()); Assert.IsTrue(property.Any()); - Assert.AreEqual(1, property.OfType().Length); + Assert.HasCount(1, property.OfType()); } [TestMethod] @@ -120,7 +120,7 @@ public void OfType_Should_Return_CorrectObject() property.Add(PassedTestNodeStateProperty.CachedInstance); Assert.AreEqual(PassedTestNodeStateProperty.CachedInstance, property.OfType().Single()); - Assert.AreEqual(2, property.OfType().Length); + Assert.HasCount(2, property.OfType()); } [TestMethod] @@ -141,7 +141,7 @@ public void AsEnumerable_Should_Return_CorrectItems() list.Remove(prop); } - Assert.AreEqual(0, list.Count); + Assert.IsEmpty(list); list = [.. property.AsEnumerable()]; foreach (IProperty prop in property) @@ -149,7 +149,7 @@ public void AsEnumerable_Should_Return_CorrectItems() list.Remove(prop); } - Assert.AreEqual(0, list.Count); + Assert.IsEmpty(list); } [TestMethod] @@ -160,7 +160,7 @@ public void EmptyProperties_Should_NotFail() Assert.IsFalse(property.Any()); Assert.IsNull(property.SingleOrDefault()); Assert.ThrowsExactly(property.Single); - Assert.AreEqual(0, property.OfType().Length); + Assert.IsEmpty(property.OfType()); Assert.AreEqual(0, property.AsEnumerable().Count()); foreach (IProperty item in property) diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/ServerMode/ServerDataConsumerServiceTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/ServerMode/ServerDataConsumerServiceTests.cs index e1703f6e8d..8fe8ab2684 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/ServerMode/ServerDataConsumerServiceTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/ServerMode/ServerDataConsumerServiceTests.cs @@ -64,7 +64,7 @@ public async Task ConsumeAsync_WithTestNodeUpdatedMessage() await _service.ConsumeAsync(producer, testNode, CancellationToken.None).ConfigureAwait(false); List actual = _service.Artifacts; - Assert.AreEqual(0, actual.Count); + Assert.IsEmpty(actual); } [TestMethod] diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Services/ServiceProviderTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Services/ServiceProviderTests.cs index aff2e76fe8..431b5054a3 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Services/ServiceProviderTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Services/ServiceProviderTests.cs @@ -89,7 +89,7 @@ public void Clone_WithFilter_Succeeded() var clonedServiceProvider = (ServiceProvider)_serviceProvider.Clone(o => o is TestHostProcessLifetimeHandler); - Assert.AreEqual(1, clonedServiceProvider.Services.Count); + Assert.HasCount(1, clonedServiceProvider.Services); Assert.AreEqual(_serviceProvider.Services.ToArray()[0].GetType(), typeof(TestHostProcessLifetimeHandler)); } diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/TestApplicationBuilderTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/TestApplicationBuilderTests.cs index 316212ee06..48445513ee 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/TestApplicationBuilderTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/TestApplicationBuilderTests.cs @@ -93,8 +93,8 @@ public async Task TestHost_ComposeFactory_ShouldSucceed(bool withParameter) List compositeExtensions = []; IDataConsumer[] consumers = [.. (await testHostManager.BuildDataConsumersAsync(_serviceProvider, compositeExtensions)).Select(x => (IDataConsumer)x.Consumer)]; ITestSessionLifetimeHandler[] sessionLifetimeHandle = [.. (await testHostManager.BuildTestSessionLifetimeHandleAsync(_serviceProvider, compositeExtensions)).Select(x => (ITestSessionLifetimeHandler)x.TestSessionLifetimeHandler)]; - Assert.AreEqual(1, consumers.Length); - Assert.AreEqual(1, sessionLifetimeHandle.Length); + Assert.HasCount(1, consumers); + Assert.HasCount(1, sessionLifetimeHandle); Assert.AreEqual(compositeExtensions[0].GetInstance(), consumers[0]); Assert.AreEqual(compositeExtensions[0].GetInstance(), sessionLifetimeHandle[0]); } @@ -155,8 +155,8 @@ public async Task TestHostController_ComposeFactory_ShouldSucceed(bool withParam testHostControllerManager.AddProcessLifetimeHandler(compositeExtensionFactory); TestHostControllerConfiguration configuration = await testHostControllerManager.BuildAsync(_serviceProvider); Assert.IsTrue(configuration.RequireProcessRestart); - Assert.AreEqual(1, configuration.LifetimeHandlers.Length); - Assert.AreEqual(1, configuration.EnvironmentVariableProviders.Length); + Assert.HasCount(1, configuration.LifetimeHandlers); + Assert.HasCount(1, configuration.EnvironmentVariableProviders); Assert.AreEqual((object)configuration.LifetimeHandlers[0], configuration.EnvironmentVariableProviders[0]); Assert.AreEqual(((ICompositeExtensionFactory)compositeExtensionFactory).GetInstance(), configuration.LifetimeHandlers[0]); Assert.AreEqual(((ICompositeExtensionFactory)compositeExtensionFactory).GetInstance(), configuration.EnvironmentVariableProviders[0]); From ae5abbb54524ca5b2acc42c507479e402340b722 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Tue, 22 Jul 2025 14:29:35 +0200 Subject: [PATCH 271/541] Support unary not operator in TreeNodeFilter (#6127) --- .../Requests/TreeNodeFilter/OperatorKind.cs | 5 + .../Requests/TreeNodeFilter/TreeNodeFilter.cs | 19 +++- .../Requests/TreeNodeFilterTests.cs | 106 ++++++++++++++++++ 3 files changed, 129 insertions(+), 1 deletion(-) diff --git a/src/Platform/Microsoft.Testing.Platform/Requests/TreeNodeFilter/OperatorKind.cs b/src/Platform/Microsoft.Testing.Platform/Requests/TreeNodeFilter/OperatorKind.cs index b9c7da2819..68de3b9293 100644 --- a/src/Platform/Microsoft.Testing.Platform/Requests/TreeNodeFilter/OperatorKind.cs +++ b/src/Platform/Microsoft.Testing.Platform/Requests/TreeNodeFilter/OperatorKind.cs @@ -55,4 +55,9 @@ internal enum OperatorKind /// Operator used for combining multiple filters with a logical AND. /// And, + + /// + /// Operator used to negate an expression. + /// + UnaryNot, } diff --git a/src/Platform/Microsoft.Testing.Platform/Requests/TreeNodeFilter/TreeNodeFilter.cs b/src/Platform/Microsoft.Testing.Platform/Requests/TreeNodeFilter/TreeNodeFilter.cs index 45968ab863..e7d3eaff93 100644 --- a/src/Platform/Microsoft.Testing.Platform/Requests/TreeNodeFilter/TreeNodeFilter.cs +++ b/src/Platform/Microsoft.Testing.Platform/Requests/TreeNodeFilter/TreeNodeFilter.cs @@ -77,7 +77,7 @@ private static List ParseFilter(string filter) // of an expression operators are not allowed. bool isOperatorAllowed = false; bool isPropAllowed = false; - + bool lastWasOpenParen = false; OperatorKind topStackOperator; foreach (string token in TokenizeFilter(filter)) @@ -225,6 +225,10 @@ private static List ParseFilter(string filter) isPropAllowed = false; break; + case "!" when lastWasOpenParen: + operatorStack.Push(OperatorKind.UnaryNot); + break; + default: expressionStack.Push(new ValueExpression(token)); @@ -232,6 +236,8 @@ private static List ParseFilter(string filter) isPropAllowed = true; break; } + + lastWasOpenParen = token == "("; } // Note: What we should end with (as long as the expression is a valid filter) @@ -350,6 +356,11 @@ private static void ProcessStackOperator(OperatorKind op, Stack TokenizeFilter(string filter) yield return "!="; i++; } + else if (i - 1 >= 0 && filter[i - 1] == '(') + { + // Note: If we have a ! at the start of an expression, we should + // treat it as a NOT operator. + yield return "!"; + } else { goto default; diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Requests/TreeNodeFilterTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Requests/TreeNodeFilterTests.cs index 15b2b1794f..241cf0a1d9 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Requests/TreeNodeFilterTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Requests/TreeNodeFilterTests.cs @@ -80,6 +80,112 @@ public void AndExpression() Assert.IsFalse(filter.MatchesFilter("/ProjectC.UnitTests.SomeExtension", new PropertyBag())); } + [TestMethod] + public void NotExpression_DisallowSuffix() + { + TreeNodeFilter filter = new("/(!*UnitTests)"); + Assert.IsFalse(filter.MatchesFilter("/A.UnitTests", new PropertyBag())); + Assert.IsFalse(filter.MatchesFilter("/UnitTests", new PropertyBag())); + Assert.IsTrue(filter.MatchesFilter("/A", new PropertyBag())); + Assert.IsTrue(filter.MatchesFilter("/UnitTests.A", new PropertyBag())); + } + + [TestMethod] + public void NotExpression_DisallowPrefix() + { + TreeNodeFilter filter = new("/(!UnitTests*)"); + Assert.IsFalse(filter.MatchesFilter("/UnitTests.A", new PropertyBag())); + Assert.IsFalse(filter.MatchesFilter("/UnitTests", new PropertyBag())); + Assert.IsTrue(filter.MatchesFilter("/A", new PropertyBag())); + Assert.IsTrue(filter.MatchesFilter("/A.UnitTests", new PropertyBag())); + } + + [TestMethod] + public void NotExpression_DisallowContains() + { + TreeNodeFilter filter = new("/(!*UnitTests*)"); + Assert.IsFalse(filter.MatchesFilter("/UnitTests.A", new PropertyBag())); + Assert.IsFalse(filter.MatchesFilter("/A.UnitTests", new PropertyBag())); + Assert.IsFalse(filter.MatchesFilter("/UnitTests", new PropertyBag())); + Assert.IsTrue(filter.MatchesFilter("/A", new PropertyBag())); + } + + [TestMethod] + public void NotExpression_CombinedWithAND_Parenthesized() + { + // Matches anything except A*Z + TreeNodeFilter filter = new("/(!(A*&*Z))"); + Assert.IsFalse(filter.MatchesFilter("/AZ", new PropertyBag())); // !(true && true) ==> false + Assert.IsFalse(filter.MatchesFilter("/ABCZ", new PropertyBag())); // !(true && true) ==> false + Assert.IsTrue(filter.MatchesFilter("/C", new PropertyBag())); // !(false && false) ==> true + Assert.IsTrue(filter.MatchesFilter("/A", new PropertyBag())); // !(true && false) ==> true + Assert.IsTrue(filter.MatchesFilter("/ABC", new PropertyBag())); // !(true && false) ==> true + Assert.IsTrue(filter.MatchesFilter("/Z", new PropertyBag())); // !(false && true) ==> true + Assert.IsTrue(filter.MatchesFilter("/XYZ", new PropertyBag())); // !(false && true) ==> true + } + + [TestMethod] + public void NotExpression_CombinedWithOR_Parenthesized() + { + // Doesn't match A*, and also doesn't match *Z + TreeNodeFilter filter = new("/(!(A*|*Z))"); + Assert.IsFalse(filter.MatchesFilter("/AZ", new PropertyBag())); // !(true || true) ==> false + Assert.IsFalse(filter.MatchesFilter("/AB", new PropertyBag())); // !(true || false) ==> false + Assert.IsFalse(filter.MatchesFilter("/A", new PropertyBag())); // !(true || true) ==> false + Assert.IsFalse(filter.MatchesFilter("/ABZ", new PropertyBag())); // !(true || true) ==> false + Assert.IsFalse(filter.MatchesFilter("/YZ", new PropertyBag())); // !(false || true) ==> false + Assert.IsFalse(filter.MatchesFilter("/Z", new PropertyBag())); // !(false || true) ==> false + + Assert.IsTrue(filter.MatchesFilter("/C", new PropertyBag())); // !(false || false) ==> true + Assert.IsTrue(filter.MatchesFilter("/CA", new PropertyBag())); // !(false || false) ==> true + Assert.IsTrue(filter.MatchesFilter("/ZS", new PropertyBag())); // !(false || false) ==> true + Assert.IsTrue(filter.MatchesFilter("/ZA", new PropertyBag())); // !(false || false) ==> true + Assert.IsTrue(filter.MatchesFilter("/ZYYA", new PropertyBag())); // !(false || false) ==> true + } + + [TestMethod] + public void NotExpression_CombinedWithAND_NotParenthesized() + { + // Matches anything that doesn't start with A, but should end with Z + TreeNodeFilter filter = new("/(!A*&*Z)"); + + // Cases not ending with Z, filter doesn't match. + Assert.IsFalse(filter.MatchesFilter("/A", new PropertyBag())); + Assert.IsFalse(filter.MatchesFilter("/ZA", new PropertyBag())); + Assert.IsFalse(filter.MatchesFilter("/AZA", new PropertyBag())); + + // Cases ending with Z but starts with A. Filter shouldn't match. + Assert.IsFalse(filter.MatchesFilter("/AZ", new PropertyBag())); + Assert.IsFalse(filter.MatchesFilter("/ABZ", new PropertyBag())); + + // Cases ending with Z and don't start with A. Filter should match. + Assert.IsTrue(filter.MatchesFilter("/BAZ", new PropertyBag())); + Assert.IsTrue(filter.MatchesFilter("/BZ", new PropertyBag())); + } + + [TestMethod] + public void NotExpression_CombinedWithOR_NotParenthesized() + { + // Matches anything that either doesn't start with A, or ends with Z + TreeNodeFilter filter = new("/(!A*|*Z)"); + + // Cases not starting with A + Assert.IsTrue(filter.MatchesFilter("/Y", new PropertyBag())); + Assert.IsTrue(filter.MatchesFilter("/Z", new PropertyBag())); + Assert.IsTrue(filter.MatchesFilter("/ZA", new PropertyBag())); + Assert.IsTrue(filter.MatchesFilter("/ZAZ", new PropertyBag())); + Assert.IsTrue(filter.MatchesFilter("/YAZ", new PropertyBag())); + + // Cases starting with A, and ending with Z + Assert.IsTrue(filter.MatchesFilter("/AZ", new PropertyBag())); + Assert.IsTrue(filter.MatchesFilter("/ABZ", new PropertyBag())); + + // Cases starting with A, and not ending with Z + Assert.IsFalse(filter.MatchesFilter("/A", new PropertyBag())); + Assert.IsFalse(filter.MatchesFilter("/AB", new PropertyBag())); + Assert.IsFalse(filter.MatchesFilter("/AZB", new PropertyBag())); + } + [TestMethod] public void Parentheses_EnsuresOrdering() { From 3c171a81c7cc5637ce6819252f76b0e7e0539b2b Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Tue, 22 Jul 2025 16:30:35 +0200 Subject: [PATCH 272/541] Disable ThreadSafeStringWriterWritesLinesFromDifferentTasksSeparately (#6129) --- .../Services/ThreadSafeStringWriterTests.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/ThreadSafeStringWriterTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/ThreadSafeStringWriterTests.cs index 05d287b9d1..f58616a2cd 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/ThreadSafeStringWriterTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/ThreadSafeStringWriterTests.cs @@ -1,6 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +#if false using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; using TestFramework.ForTestingMSTest; @@ -84,9 +85,7 @@ public void ThreadSafeStringWriterWritesLinesFromDifferentTasksSeparately() while (exception != null && currentAttempt++ < 3); } -#pragma warning disable IDE0051 // Remove unused private members - Test is flaky. - private void ThreadSafeStringWriterWritesLinesIntoDifferentWritesSeparately() -#pragma warning restore IDE0051 // Remove unused private members + public void ThreadSafeStringWriterWritesLinesIntoDifferentWritesSeparately() { // Suppress the flow of parent context here because this test method will run in // a task already and we don't want the existing async context to interfere with this. @@ -129,3 +128,4 @@ private void ThreadSafeStringWriterWritesLinesIntoDifferentWritesSeparately() } } } +#endif From 60a28a7b3d9ab6fe19f88b431fbab3bfd7099adc Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Tue, 22 Jul 2025 16:56:39 +0200 Subject: [PATCH 273/541] Add analyzer to flow TestContext.CTS.Token (#6126) --- .../CodeFixResources.Designer.cs | 61 +- .../CodeFixResources.resx | 5 +- .../FlowTestContextCancellationTokenFixer.cs | 85 +++ .../PublicAPI.Unshipped.txt | 5 + .../xlf/CodeFixResources.cs.xlf | 5 + .../xlf/CodeFixResources.de.xlf | 5 + .../xlf/CodeFixResources.es.xlf | 5 + .../xlf/CodeFixResources.fr.xlf | 5 + .../xlf/CodeFixResources.it.xlf | 5 + .../xlf/CodeFixResources.ja.xlf | 5 + .../xlf/CodeFixResources.ko.xlf | 5 + .../xlf/CodeFixResources.pl.xlf | 5 + .../xlf/CodeFixResources.pt-BR.xlf | 5 + .../xlf/CodeFixResources.ru.xlf | 5 + .../xlf/CodeFixResources.tr.xlf | 5 + .../xlf/CodeFixResources.zh-Hans.xlf | 5 + .../xlf/CodeFixResources.zh-Hant.xlf | 5 + .../AnalyzerReleases.Unshipped.md | 1 + ...lowTestContextCancellationTokenAnalyzer.cs | 231 ++++++++ .../MSTest.Analyzers/Helpers/DiagnosticIds.cs | 1 + .../Helpers/WellKnownTypeNames.cs | 1 + .../MSTest.Analyzers/PublicAPI.Unshipped.txt | 4 + .../MSTest.Analyzers/Resources.Designer.cs | 27 + src/Analyzers/MSTest.Analyzers/Resources.resx | 9 + .../MSTest.Analyzers/xlf/Resources.cs.xlf | 15 + .../MSTest.Analyzers/xlf/Resources.de.xlf | 15 + .../MSTest.Analyzers/xlf/Resources.es.xlf | 15 + .../MSTest.Analyzers/xlf/Resources.fr.xlf | 15 + .../MSTest.Analyzers/xlf/Resources.it.xlf | 15 + .../MSTest.Analyzers/xlf/Resources.ja.xlf | 15 + .../MSTest.Analyzers/xlf/Resources.ko.xlf | 15 + .../MSTest.Analyzers/xlf/Resources.pl.xlf | 15 + .../MSTest.Analyzers/xlf/Resources.pt-BR.xlf | 15 + .../MSTest.Analyzers/xlf/Resources.ru.xlf | 15 + .../MSTest.Analyzers/xlf/Resources.tr.xlf | 15 + .../xlf/Resources.zh-Hans.xlf | 15 + .../xlf/Resources.zh-Hant.xlf | 15 + ...stContextCancellationTokenAnalyzerTests.cs | 534 ++++++++++++++++++ 38 files changed, 1197 insertions(+), 27 deletions(-) create mode 100644 src/Analyzers/MSTest.Analyzers.CodeFixes/FlowTestContextCancellationTokenFixer.cs create mode 100644 src/Analyzers/MSTest.Analyzers/FlowTestContextCancellationTokenAnalyzer.cs create mode 100644 test/UnitTests/MSTest.Analyzers.UnitTests/FlowTestContextCancellationTokenAnalyzerTests.cs diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/CodeFixResources.Designer.cs b/src/Analyzers/MSTest.Analyzers.CodeFixes/CodeFixResources.Designer.cs index 2ff93de26f..39751da4c0 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/CodeFixResources.Designer.cs +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/CodeFixResources.Designer.cs @@ -69,15 +69,6 @@ internal static string AddTestClassFix { } } - /// - /// Looks up a localized string similar to Change to 'class' and add '[TestClass]'. - /// - internal static string ChangeStructToClassAndAddTestClassFix { - get { - return ResourceManager.GetString("ChangeStructToClassAndAddTestClassFix", resourceCulture); - } - } - /// /// Looks up a localized string similar to Add '[TestMethod]'. /// @@ -123,6 +114,15 @@ internal static string ChangeMethodAccessibilityToPrivateFix { } } + /// + /// Looks up a localized string similar to Change to 'class' and add '[TestClass]'. + /// + internal static string ChangeStructToClassAndAddTestClassFix { + get { + return ResourceManager.GetString("ChangeStructToClassAndAddTestClassFix", resourceCulture); + } + } + /// /// Looks up a localized string similar to Fix actual/expected arguments order. /// @@ -141,6 +141,15 @@ internal static string FixSignatureCodeFix { } } + /// + /// Looks up a localized string similar to Pass 'TestContext.CancellationTokenSource.Token' argument to method call. + /// + internal static string PassCancellationTokenFix { + get { + return ResourceManager.GetString("PassCancellationTokenFix", resourceCulture); + } + } + /// /// Looks up a localized string similar to Replace 'DataTestMethod' with 'TestMethod'. /// @@ -195,6 +204,15 @@ internal static string ReplaceWithTestInitializeFix { } } + /// + /// Looks up a localized string similar to Use 'Assert.{0}' instead of 'StringAssert'. + /// + internal static string StringAssertToAssertTitle { + get { + return ResourceManager.GetString("StringAssertToAssertTitle", resourceCulture); + } + } + /// /// Looks up a localized string similar to Fix test class signature. /// @@ -241,38 +259,29 @@ internal static string UseAttributeOnTestMethodFix { } /// - /// Looks up a localized string similar to Use '{0}'. + /// Looks up a localized string similar to Use 'CooperativeCancellation = true'. /// - internal static string UseNewerAssertThrows { + internal static string UseCooperativeCancellationForTimeoutFix { get { - return ResourceManager.GetString("UseNewerAssertThrows", resourceCulture); + return ResourceManager.GetString("UseCooperativeCancellationForTimeoutFix", resourceCulture); } } /// /// Looks up a localized string similar to Use '{0}'. /// - internal static string UseProperAssertMethodsFix { - get { - return ResourceManager.GetString("UseProperAssertMethodsFix", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Use 'CooperativeCancellation = true'. - /// - internal static string UseCooperativeCancellationForTimeoutFix { + internal static string UseNewerAssertThrows { get { - return ResourceManager.GetString("UseCooperativeCancellationForTimeoutFix", resourceCulture); + return ResourceManager.GetString("UseNewerAssertThrows", resourceCulture); } } /// - /// Looks up a localized string similar to Use 'Assert.{0}' instead of 'StringAssert'. + /// Looks up a localized string similar to Use '{0}'. /// - internal static string StringAssertToAssertTitle { + internal static string UseProperAssertMethodsFix { get { - return ResourceManager.GetString("StringAssertToAssertTitle", resourceCulture); + return ResourceManager.GetString("UseProperAssertMethodsFix", resourceCulture); } } } diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/CodeFixResources.resx b/src/Analyzers/MSTest.Analyzers.CodeFixes/CodeFixResources.resx index f415177ca0..5c5033b0df 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/CodeFixResources.resx +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/CodeFixResources.resx @@ -189,4 +189,7 @@ Use 'Assert.{0}' instead of 'StringAssert' - + + Pass 'TestContext.CancellationTokenSource.Token' argument to method call + + \ No newline at end of file diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/FlowTestContextCancellationTokenFixer.cs b/src/Analyzers/MSTest.Analyzers.CodeFixes/FlowTestContextCancellationTokenFixer.cs new file mode 100644 index 0000000000..0941d05e6c --- /dev/null +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/FlowTestContextCancellationTokenFixer.cs @@ -0,0 +1,85 @@ +// 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.Immutable; +using System.Composition; + +using Analyzer.Utilities; + +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CodeActions; +using Microsoft.CodeAnalysis.CodeFixes; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Editing; +using Microsoft.CodeAnalysis.Text; + +using MSTest.Analyzers.Helpers; + +namespace MSTest.Analyzers; + +/// +/// Code fixer for . +/// +[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(FlowTestContextCancellationTokenFixer))] +[Shared] +public sealed class FlowTestContextCancellationTokenFixer : CodeFixProvider +{ + /// + public sealed override ImmutableArray FixableDiagnosticIds { get; } + = ImmutableArray.Create(DiagnosticIds.FlowTestContextCancellationTokenRuleId); + + /// + public override FixAllProvider GetFixAllProvider() + // See https://github.com/dotnet/roslyn/blob/main/docs/analyzers/FixAllProvider.md for more information on Fix All Providers + => WellKnownFixAllProviders.BatchFixer; + + /// + public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) + { + SyntaxNode root = await context.Document.GetRequiredSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); + Diagnostic diagnostic = context.Diagnostics[0]; + TextSpan diagnosticSpan = diagnostic.Location.SourceSpan; + + // Find the invocation expression identified by the diagnostic + SyntaxNode node = root.FindNode(diagnosticSpan, getInnermostNodeForTie: true); + if (node is not InvocationExpressionSyntax invocationExpression) + { + return; + } + + diagnostic.Properties.TryGetValue(FlowTestContextCancellationTokenAnalyzer.TestContextMemberNamePropertyKey, out string? testContextMemberName); + + // Register a code action that will invoke the fix + context.RegisterCodeFix( + CodeAction.Create( + title: CodeFixResources.PassCancellationTokenFix, + createChangedDocument: c => AddCancellationTokenParameterAsync(context.Document, invocationExpression, testContextMemberName, c), + equivalenceKey: "AddTestContextCancellationToken"), + diagnostic); + } + + private static async Task AddCancellationTokenParameterAsync( + Document document, + InvocationExpressionSyntax invocationExpression, + string? testContextMemberName, + CancellationToken cancellationToken) + { + DocumentEditor editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false); + + // Create the TestContext.CancellationTokenSource.Token expression + MemberAccessExpressionSyntax testContextExpression = SyntaxFactory.MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + SyntaxFactory.MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + SyntaxFactory.IdentifierName(testContextMemberName ?? "testContext"), + SyntaxFactory.IdentifierName("CancellationTokenSource")), + SyntaxFactory.IdentifierName("Token")); + + ArgumentListSyntax currentArguments = invocationExpression.ArgumentList; + SeparatedSyntaxList newArguments = currentArguments.Arguments.Add(SyntaxFactory.Argument(testContextExpression)); + InvocationExpressionSyntax newInvocation = invocationExpression.WithArgumentList(currentArguments.WithArguments(newArguments)); + editor.ReplaceNode(invocationExpression, newInvocation); + return editor.GetChangedDocument(); + } +} diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/PublicAPI.Unshipped.txt b/src/Analyzers/MSTest.Analyzers.CodeFixes/PublicAPI.Unshipped.txt index 79fa2eb4ff..a0766dd232 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/PublicAPI.Unshipped.txt +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/PublicAPI.Unshipped.txt @@ -1,4 +1,9 @@ #nullable enable +MSTest.Analyzers.FlowTestContextCancellationTokenFixer +MSTest.Analyzers.FlowTestContextCancellationTokenFixer.FlowTestContextCancellationTokenFixer() -> void +override MSTest.Analyzers.FlowTestContextCancellationTokenFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! +override sealed MSTest.Analyzers.FlowTestContextCancellationTokenFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray +override sealed MSTest.Analyzers.FlowTestContextCancellationTokenFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! MSTest.Analyzers.CodeFixes.StringAssertToAssertFixer MSTest.Analyzers.CodeFixes.StringAssertToAssertFixer.StringAssertToAssertFixer() -> void MSTest.Analyzers.PreferTestMethodOverDataTestMethodFixer diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.cs.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.cs.xlf index 2ae6c3610c..0bed0e5896 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.cs.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.cs.xlf @@ -47,6 +47,11 @@ Opravit podpis + + Pass 'TestContext.CancellationTokenSource.Token' argument to method call + Pass 'TestContext.CancellationTokenSource.Token' argument to method call + + Replace 'DataTestMethod' with 'TestMethod' Nahradit DataTestMethod hodnotou TestMethod diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.de.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.de.xlf index 42fedd0e72..ebd4251925 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.de.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.de.xlf @@ -47,6 +47,11 @@ Signatur korrigieren + + Pass 'TestContext.CancellationTokenSource.Token' argument to method call + Pass 'TestContext.CancellationTokenSource.Token' argument to method call + + Replace 'DataTestMethod' with 'TestMethod' „DataTestMethod“ durch „TestMethod“ ersetzen diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.es.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.es.xlf index d07684cc08..491cd0f467 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.es.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.es.xlf @@ -47,6 +47,11 @@ Corregir firma + + Pass 'TestContext.CancellationTokenSource.Token' argument to method call + Pass 'TestContext.CancellationTokenSource.Token' argument to method call + + Replace 'DataTestMethod' with 'TestMethod' Reemplazar "DataTestMethod" por "TestMethod" diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.fr.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.fr.xlf index e907d183fa..06cdb16af6 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.fr.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.fr.xlf @@ -47,6 +47,11 @@ Corriger la signature numérique + + Pass 'TestContext.CancellationTokenSource.Token' argument to method call + Pass 'TestContext.CancellationTokenSource.Token' argument to method call + + Replace 'DataTestMethod' with 'TestMethod' Remplacer « DataTestMethod » par « TestMethod » diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.it.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.it.xlf index 38466813aa..77bca2130a 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.it.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.it.xlf @@ -47,6 +47,11 @@ Correggi firma + + Pass 'TestContext.CancellationTokenSource.Token' argument to method call + Pass 'TestContext.CancellationTokenSource.Token' argument to method call + + Replace 'DataTestMethod' with 'TestMethod' Sostituisci 'DataTestMethod' con 'TestMethod' diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ja.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ja.xlf index 82e36dee3a..6290453cd1 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ja.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ja.xlf @@ -47,6 +47,11 @@ 署名の修正 + + Pass 'TestContext.CancellationTokenSource.Token' argument to method call + Pass 'TestContext.CancellationTokenSource.Token' argument to method call + + Replace 'DataTestMethod' with 'TestMethod' 'DataTestMethod' を 'TestMethod' に置き換えます diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ko.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ko.xlf index 8951ecc21b..efe585755b 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ko.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ko.xlf @@ -47,6 +47,11 @@ 서명 수정 + + Pass 'TestContext.CancellationTokenSource.Token' argument to method call + Pass 'TestContext.CancellationTokenSource.Token' argument to method call + + Replace 'DataTestMethod' with 'TestMethod' 'DataTestMethod'를 'TestMethod'로 바꾸기 diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pl.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pl.xlf index 602784038f..9784b9ae35 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pl.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pl.xlf @@ -47,6 +47,11 @@ Popraw podpis + + Pass 'TestContext.CancellationTokenSource.Token' argument to method call + Pass 'TestContext.CancellationTokenSource.Token' argument to method call + + Replace 'DataTestMethod' with 'TestMethod' Zastąp element „DataTestMethod” elementem „TestMethod” diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pt-BR.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pt-BR.xlf index c47d5b1c8d..0340b1af02 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pt-BR.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pt-BR.xlf @@ -47,6 +47,11 @@ Corrigir assinatura + + Pass 'TestContext.CancellationTokenSource.Token' argument to method call + Pass 'TestContext.CancellationTokenSource.Token' argument to method call + + Replace 'DataTestMethod' with 'TestMethod' Substitua 'DataTestMethod' por 'TestMethod' diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ru.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ru.xlf index e9105ad784..3c4a91f10f 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ru.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ru.xlf @@ -47,6 +47,11 @@ Исправить подпись + + Pass 'TestContext.CancellationTokenSource.Token' argument to method call + Pass 'TestContext.CancellationTokenSource.Token' argument to method call + + Replace 'DataTestMethod' with 'TestMethod' Заменить "DataTestMethod" на "TestMethod" diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.tr.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.tr.xlf index 5e61d92acd..51ed7e16a1 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.tr.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.tr.xlf @@ -47,6 +47,11 @@ İmzayı düzelt + + Pass 'TestContext.CancellationTokenSource.Token' argument to method call + Pass 'TestContext.CancellationTokenSource.Token' argument to method call + + Replace 'DataTestMethod' with 'TestMethod' 'DataTestMethod' yöntemini 'TestMethod' ile değiştirin diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hans.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hans.xlf index 177c517350..0843af0b17 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hans.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hans.xlf @@ -47,6 +47,11 @@ 修复签名 + + Pass 'TestContext.CancellationTokenSource.Token' argument to method call + Pass 'TestContext.CancellationTokenSource.Token' argument to method call + + Replace 'DataTestMethod' with 'TestMethod' 将 'DataTestMethod' 替换为 'TestMethod' diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hant.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hant.xlf index 9ab35a648a..2d948f4f46 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hant.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hant.xlf @@ -47,6 +47,11 @@ 修正簽章 + + Pass 'TestContext.CancellationTokenSource.Token' argument to method call + Pass 'TestContext.CancellationTokenSource.Token' argument to method call + + Replace 'DataTestMethod' with 'TestMethod' 將 'DataTestMethod' 取代為 'TestMethod' diff --git a/src/Analyzers/MSTest.Analyzers/AnalyzerReleases.Unshipped.md b/src/Analyzers/MSTest.Analyzers/AnalyzerReleases.Unshipped.md index ff09804347..7f47cac255 100644 --- a/src/Analyzers/MSTest.Analyzers/AnalyzerReleases.Unshipped.md +++ b/src/Analyzers/MSTest.Analyzers/AnalyzerReleases.Unshipped.md @@ -9,6 +9,7 @@ MSTEST0044 | Design | Warning | PreferTestMethodOverDataTestMethodAnalyzer, [Doc MSTEST0045 | Usage | Info | UseCooperativeCancellationForTimeoutAnalyzer, [Documentation](https://learn.microsoft.com/dotnet/core/testing/mstest-analyzers/mstest0045) MSTEST0046 | Usage | Info | StringAssertToAssertAnalyzer, [Documentation](https://learn.microsoft.com/dotnet/core/testing/mstest-analyzers/mstest0046) MSTEST0048 | Usage | Warning | TestContextPropertyUsageAnalyzer, [Documentation](https://learn.microsoft.com/dotnet/core/testing/mstest-analyzers/mstest0047) +MSTEST0049 | Usage | Info | FlowTestContextCancellationTokenAnalyzer, [Documentation](https://learn.microsoft.com/dotnet/core/testing/mstest-analyzers/mstest0049) ### Changed Rules diff --git a/src/Analyzers/MSTest.Analyzers/FlowTestContextCancellationTokenAnalyzer.cs b/src/Analyzers/MSTest.Analyzers/FlowTestContextCancellationTokenAnalyzer.cs new file mode 100644 index 0000000000..cf38e10478 --- /dev/null +++ b/src/Analyzers/MSTest.Analyzers/FlowTestContextCancellationTokenAnalyzer.cs @@ -0,0 +1,231 @@ +// 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.Immutable; + +using Analyzer.Utilities.Extensions; + +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Diagnostics; +using Microsoft.CodeAnalysis.Operations; + +using MSTest.Analyzers.Helpers; + +namespace MSTest.Analyzers; + +/// +/// MSTEST0049: . +/// +[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] +public sealed class FlowTestContextCancellationTokenAnalyzer : DiagnosticAnalyzer +{ + private static readonly LocalizableResourceString Title = new(nameof(Resources.FlowTestContextCancellationTokenTitle), Resources.ResourceManager, typeof(Resources)); + private static readonly LocalizableResourceString Description = new(nameof(Resources.FlowTestContextCancellationTokenDescription), Resources.ResourceManager, typeof(Resources)); + private static readonly LocalizableResourceString MessageFormat = new(nameof(Resources.FlowTestContextCancellationTokenMessageFormat), Resources.ResourceManager, typeof(Resources)); + + internal const string TestContextMemberNamePropertyKey = nameof(TestContextMemberNamePropertyKey); + + internal static readonly DiagnosticDescriptor FlowTestContextCancellationTokenRule = DiagnosticDescriptorHelper.Create( + DiagnosticIds.FlowTestContextCancellationTokenRuleId, + Title, + MessageFormat, + Description, + Category.Usage, + DiagnosticSeverity.Info, + isEnabledByDefault: true); + + /// + public override ImmutableArray SupportedDiagnostics { get; } + = ImmutableArray.Create(FlowTestContextCancellationTokenRule); + + /// + public override void Initialize(AnalysisContext context) + { + context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); + context.EnableConcurrentExecution(); + + context.RegisterCompilationStartAction(context => + { + // Get the required symbols + if (!context.Compilation.TryGetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemThreadingCancellationToken, out INamedTypeSymbol? cancellationTokenSymbol) || + !context.Compilation.TryGetOrCreateTypeByMetadataName(WellKnownTypeNames.MicrosoftVisualStudioTestToolsUnitTestingTestContext, out INamedTypeSymbol? testContextSymbol) || + !context.Compilation.TryGetOrCreateTypeByMetadataName(WellKnownTypeNames.MicrosoftVisualStudioTestToolsUnitTestingClassCleanupAttribute, out INamedTypeSymbol? classCleanupAttributeSymbol) || + !context.Compilation.TryGetOrCreateTypeByMetadataName(WellKnownTypeNames.MicrosoftVisualStudioTestToolsUnitTestingAssemblyCleanupAttribute, out INamedTypeSymbol? assemblyCleanupAttributeSymbol) || + !context.Compilation.TryGetOrCreateTypeByMetadataName(WellKnownTypeNames.MicrosoftVisualStudioTestToolsUnitTestingTestMethodAttribute, out INamedTypeSymbol? testMethodAttributeSymbol)) + { + return; + } + + context.RegisterOperationAction( + context => AnalyzeInvocation(context, cancellationTokenSymbol, testContextSymbol, classCleanupAttributeSymbol, assemblyCleanupAttributeSymbol, testMethodAttributeSymbol), + OperationKind.Invocation); + }); + } + + private static void AnalyzeInvocation( + OperationAnalysisContext context, + INamedTypeSymbol cancellationTokenSymbol, + INamedTypeSymbol testContextSymbol, + INamedTypeSymbol classCleanupAttributeSymbol, + INamedTypeSymbol assemblyCleanupAttributeSymbol, + INamedTypeSymbol testMethodAttributeSymbol) + { + var invocationOperation = (IInvocationOperation)context.Operation; + IMethodSymbol method = invocationOperation.TargetMethod; + + // Check if we're in a context where a TestContext is already available or could be made available. + if (!HasOrCouldHaveTestContextInScope(context.ContainingSymbol, testContextSymbol, classCleanupAttributeSymbol, assemblyCleanupAttributeSymbol, testMethodAttributeSymbol, out string? testContextMemberNameInScope)) + { + return; + } + + IParameterSymbol? cancellationTokenParameter = method.Parameters.LastOrDefault(p => SymbolEqualityComparer.Default.Equals(p.Type, cancellationTokenSymbol)); + bool parameterHasDefaultValue = cancellationTokenParameter is not null && cancellationTokenParameter.HasExplicitDefaultValue; + if (cancellationTokenParameter is not null && !parameterHasDefaultValue) + { + // The called method has a required CancellationToken parameter. + // No need to report diagnostic, even if user is explicitly passing CancellationToken.None or default(CancellationToken). + // We consider it "intentional" if the user is passing it explicitly. + return; + } + + if (parameterHasDefaultValue && + invocationOperation.Arguments.FirstOrDefault(arg => SymbolEqualityComparer.Default.Equals(arg.Parameter, cancellationTokenParameter))?.ArgumentKind != ArgumentKind.Explicit) + { + // The called method has an optional CancellationToken parameter, but it was not explicitly provided. + ImmutableDictionary properties = ImmutableDictionary.Empty; + if (testContextMemberNameInScope is not null) + { + properties = properties.Add(TestContextMemberNamePropertyKey, testContextMemberNameInScope); + } + + context.ReportDiagnostic(invocationOperation.Syntax.CreateDiagnostic(FlowTestContextCancellationTokenRule, properties: GetPropertiesBag(testContextMemberNameInScope))); + return; + } + + // At this point, we want to only continue analysis if and only if the called method didn't have a CancellationToken parameter. + // In this case, we look for other overloads that might accept a CancellationToken. + if (cancellationTokenParameter is null && + HasOverloadWithCancellationToken(method, cancellationTokenSymbol)) + { + context.ReportDiagnostic(invocationOperation.Syntax.CreateDiagnostic(FlowTestContextCancellationTokenRule, properties: GetPropertiesBag(testContextMemberNameInScope))); + } + + static ImmutableDictionary GetPropertiesBag(string? testContextMemberNameInScope) + { + ImmutableDictionary properties = ImmutableDictionary.Empty; + if (testContextMemberNameInScope is not null) + { + properties = properties.Add(TestContextMemberNamePropertyKey, testContextMemberNameInScope); + } + + return properties; + } + } + + private static bool HasOverloadWithCancellationToken(IMethodSymbol method, INamedTypeSymbol cancellationTokenSymbol) + { + // Look for overloads of the same method that accept CancellationToken + INamedTypeSymbol containingType = method.ContainingType; + + foreach (ISymbol member in containingType.GetMembers(method.Name)) + { + if (member is IMethodSymbol candidateMethod && + candidateMethod.MethodKind == method.MethodKind && + candidateMethod.IsStatic == method.IsStatic) + { + // Check if this method has the same parameters plus a CancellationToken + if (IsCompatibleOverloadWithCancellationToken(method, candidateMethod, cancellationTokenSymbol)) + { + return true; + } + } + } + + return false; + } + + private static bool HasOrCouldHaveTestContextInScope( + ISymbol containingSymbol, + INamedTypeSymbol testContextSymbol, + INamedTypeSymbol classCleanupAttributeSymbol, + INamedTypeSymbol assemblyCleanupAttributeSymbol, + INamedTypeSymbol testMethodAttributeSymbol, + out string? testContextMemberNameInScope) + { + testContextMemberNameInScope = null; + + if (containingSymbol is not IMethodSymbol method) + { + return false; + } + + // We have a TestContext in scope (as a parameter) + if (method.Parameters.FirstOrDefault(p => testContextSymbol.Equals(p.Type, SymbolEqualityComparer.Default)) is { } testContextParameter) + { + testContextMemberNameInScope = testContextParameter.Name; + return true; + } + + // We have a TestContext in scope (as a field or property) + if (!method.IsStatic && + method.ContainingType.GetMembers().FirstOrDefault( + m => !m.IsStatic && m.Kind is SymbolKind.Field or SymbolKind.Property && testContextSymbol.Equals(m.GetMemberType(), SymbolEqualityComparer.Default)) is { } testContextMember) + { + testContextMember = (testContextMember as IFieldSymbol)?.AssociatedSymbol ?? testContextMember; + // Workaround https://github.com/dotnet/roslyn/issues/70208 + // https://github.com/dotnet/roslyn/blob/f25ae8e02a91169f45060951a168b233ad588ed3/src/Compilers/CSharp/Portable/Symbols/Synthesized/GeneratedNameKind.cs#L47 + testContextMemberNameInScope = testContextMember.Name.StartsWith('<') && testContextMember.Name.EndsWith(">P", StringComparison.Ordinal) + ? testContextMember.Name.Substring(1, testContextMember.Name.Length - 3) + : testContextMember.Name; + return true; + } + + // If we have AssemblyCleanup or ClassCleanup with no parameters, then we *could* have a TestContext in scope. + // Note that assembly/class cleanup method can optionally have a TestContext parameter, but it is not required. + // Also, for test methods (parameterized or not), we *could* have a TestContext in scope by adding a property to the test class (or injecting it via constructor). + ImmutableArray attributes = method.GetAttributes(); + foreach (AttributeData attribute in attributes) + { + if (method.Parameters.IsEmpty && + (classCleanupAttributeSymbol.Equals(attribute.AttributeClass, SymbolEqualityComparer.Default) || + assemblyCleanupAttributeSymbol.Equals(attribute.AttributeClass, SymbolEqualityComparer.Default))) + { + return true; + } + + if (attribute.AttributeClass?.Inherits(testMethodAttributeSymbol) == true) + { + return true; + } + } + + return false; + } + + private static bool IsCompatibleOverloadWithCancellationToken(IMethodSymbol originalMethod, IMethodSymbol candidateMethod, INamedTypeSymbol cancellationTokenSymbol) + { + // Check if the candidate method has all the same parameters as the original method plus a CancellationToken + ImmutableArray originalParams = originalMethod.Parameters; + ImmutableArray candidateParams = candidateMethod.Parameters; + + // The candidate should have one more parameter (the CancellationToken) + if (candidateParams.Length != originalParams.Length + 1) + { + return false; + } + + // Check if all original parameters match the first N parameters of the candidate + for (int i = 0; i < originalParams.Length; i++) + { + if (!SymbolEqualityComparer.Default.Equals(originalParams[i].Type, candidateParams[i].Type)) + { + return false; + } + } + + // Check if the last parameter is CancellationToken + IParameterSymbol lastParam = candidateParams[candidateParams.Length - 1]; + return SymbolEqualityComparer.Default.Equals(lastParam.Type, cancellationTokenSymbol); + } +} diff --git a/src/Analyzers/MSTest.Analyzers/Helpers/DiagnosticIds.cs b/src/Analyzers/MSTest.Analyzers/Helpers/DiagnosticIds.cs index 43d50724e4..cd6b9bae20 100644 --- a/src/Analyzers/MSTest.Analyzers/Helpers/DiagnosticIds.cs +++ b/src/Analyzers/MSTest.Analyzers/Helpers/DiagnosticIds.cs @@ -53,4 +53,5 @@ internal static class DiagnosticIds public const string StringAssertToAssertRuleId = "MSTEST0046"; public const string UnusedParameterSuppressorRuleId = "MSTEST0047"; public const string TestContextPropertyUsageRuleId = "MSTEST0048"; + public const string FlowTestContextCancellationTokenRuleId = "MSTEST0049"; } diff --git a/src/Analyzers/MSTest.Analyzers/Helpers/WellKnownTypeNames.cs b/src/Analyzers/MSTest.Analyzers/Helpers/WellKnownTypeNames.cs index 65389f66b6..380a3e7a03 100644 --- a/src/Analyzers/MSTest.Analyzers/Helpers/WellKnownTypeNames.cs +++ b/src/Analyzers/MSTest.Analyzers/Helpers/WellKnownTypeNames.cs @@ -50,6 +50,7 @@ internal static class WellKnownTypeNames public const string SystemIAsyncDisposable = "System.IAsyncDisposable"; public const string SystemIDisposable = "System.IDisposable"; public const string SystemReflectionMethodInfo = "System.Reflection.MethodInfo"; + public const string SystemThreadingCancellationToken = "System.Threading.CancellationToken"; public const string SystemThreadingTasksTask = "System.Threading.Tasks.Task"; public const string SystemThreadingTasksTask1 = "System.Threading.Tasks.Task`1"; public const string SystemThreadingTasksValueTask = "System.Threading.Tasks.ValueTask"; diff --git a/src/Analyzers/MSTest.Analyzers/PublicAPI.Unshipped.txt b/src/Analyzers/MSTest.Analyzers/PublicAPI.Unshipped.txt index 462739b1d3..5b61c23895 100644 --- a/src/Analyzers/MSTest.Analyzers/PublicAPI.Unshipped.txt +++ b/src/Analyzers/MSTest.Analyzers/PublicAPI.Unshipped.txt @@ -1,4 +1,8 @@ #nullable enable +MSTest.Analyzers.FlowTestContextCancellationTokenAnalyzer +MSTest.Analyzers.FlowTestContextCancellationTokenAnalyzer.FlowTestContextCancellationTokenAnalyzer() -> void +override MSTest.Analyzers.FlowTestContextCancellationTokenAnalyzer.Initialize(Microsoft.CodeAnalysis.Diagnostics.AnalysisContext! context) -> void +override MSTest.Analyzers.FlowTestContextCancellationTokenAnalyzer.SupportedDiagnostics.get -> System.Collections.Immutable.ImmutableArray MSTest.Analyzers.PreferTestMethodOverDataTestMethodAnalyzer MSTest.Analyzers.PreferTestMethodOverDataTestMethodAnalyzer.PreferTestMethodOverDataTestMethodAnalyzer() -> void override MSTest.Analyzers.PreferTestMethodOverDataTestMethodAnalyzer.Initialize(Microsoft.CodeAnalysis.Diagnostics.AnalysisContext! context) -> void diff --git a/src/Analyzers/MSTest.Analyzers/Resources.Designer.cs b/src/Analyzers/MSTest.Analyzers/Resources.Designer.cs index 9945dfaa28..bd040c4017 100644 --- a/src/Analyzers/MSTest.Analyzers/Resources.Designer.cs +++ b/src/Analyzers/MSTest.Analyzers/Resources.Designer.cs @@ -1329,5 +1329,32 @@ internal static string TestContextPropertyUsageDescription { return ResourceManager.GetString("TestContextPropertyUsageDescription", resourceCulture); } } + + /// + /// Looks up a localized string similar to When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationTokenSource.Token to enable cooperative cancellation and respect test timeouts. + /// + internal static string FlowTestContextCancellationTokenDescription { + get { + return ResourceManager.GetString("FlowTestContextCancellationTokenDescription", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationTokenSource.Token'. + /// + internal static string FlowTestContextCancellationTokenMessageFormat { + get { + return ResourceManager.GetString("FlowTestContextCancellationTokenMessageFormat", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Flow TestContext.CancellationToken to async operations. + /// + internal static string FlowTestContextCancellationTokenTitle { + get { + return ResourceManager.GetString("FlowTestContextCancellationTokenTitle", resourceCulture); + } + } } } diff --git a/src/Analyzers/MSTest.Analyzers/Resources.resx b/src/Analyzers/MSTest.Analyzers/Resources.resx index c21184b023..dfb6843781 100644 --- a/src/Analyzers/MSTest.Analyzers/Resources.resx +++ b/src/Analyzers/MSTest.Analyzers/Resources.resx @@ -624,4 +624,13 @@ The type declaring these methods should also respect the following rules: Some TestContext properties are only available during test execution and cannot be accessed in assembly initialize, class initialize, class cleanup, or assembly cleanup methods. + + Flow TestContext.CancellationToken to async operations + + + Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationTokenSource.Token' + + + When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationTokenSource.Token to enable cooperative cancellation and respect test timeouts. + diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf index 02fbb5012a..c3ed9f7c60 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf @@ -432,6 +432,21 @@ Typ deklarující tyto metody by měl také respektovat následující pravidla: Položka DynamicData by měla být platná. + + When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationTokenSource.Token to enable cooperative cancellation and respect test timeouts. + When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationTokenSource.Token to enable cooperative cancellation and respect test timeouts. + + + + Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationTokenSource.Token' + Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationTokenSource.Token' + + + + Flow TestContext.CancellationToken to async operations + Flow TestContext.CancellationToken to async operations + + Use 'Assert.Fail' instead of an always-failing 'Assert.{0}' assert Místo trvalého neúspěšného vyhodnocovacího výrazu „Assert.{0}“ použijte „Assert.Fail“. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf index add305ccd7..1340f34ec7 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf @@ -433,6 +433,21 @@ Der Typ, der diese Methoden deklariert, sollte auch die folgenden Regeln beachte DynamicData muss gültig sein. + + When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationTokenSource.Token to enable cooperative cancellation and respect test timeouts. + When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationTokenSource.Token to enable cooperative cancellation and respect test timeouts. + + + + Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationTokenSource.Token' + Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationTokenSource.Token' + + + + Flow TestContext.CancellationToken to async operations + Flow TestContext.CancellationToken to async operations + + Use 'Assert.Fail' instead of an always-failing 'Assert.{0}' assert Verwenden Sie „Assert.Fail“ anstelle einer Assert-Anweisung „Assert.{0}“, bei der immer ein Fehler auftritt. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf index 0f4618d872..35098fc7b0 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf @@ -432,6 +432,21 @@ El tipo que declara estos métodos también debe respetar las reglas siguientes: DynamicData debe ser válido + + When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationTokenSource.Token to enable cooperative cancellation and respect test timeouts. + When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationTokenSource.Token to enable cooperative cancellation and respect test timeouts. + + + + Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationTokenSource.Token' + Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationTokenSource.Token' + + + + Flow TestContext.CancellationToken to async operations + Flow TestContext.CancellationToken to async operations + + Use 'Assert.Fail' instead of an always-failing 'Assert.{0}' assert Usar "Assert.Fail" en lugar de una aserción 'Assert.{0}' que siempre tiene errores diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf index 1e2c0d9f70..6b526b9e70 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf @@ -432,6 +432,21 @@ Le type doit être une classe DynamicData doit être valide + + When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationTokenSource.Token to enable cooperative cancellation and respect test timeouts. + When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationTokenSource.Token to enable cooperative cancellation and respect test timeouts. + + + + Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationTokenSource.Token' + Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationTokenSource.Token' + + + + Flow TestContext.CancellationToken to async operations + Flow TestContext.CancellationToken to async operations + + Use 'Assert.Fail' instead of an always-failing 'Assert.{0}' assert Utilisez « Assert.Fail » à la place d’une assertion « Assert.{0} » toujours en échec diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf index 2e69adbeab..ad6f304f11 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf @@ -432,6 +432,21 @@ Anche il tipo che dichiara questi metodi deve rispettare le regole seguenti: DynamicData deve essere valido + + When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationTokenSource.Token to enable cooperative cancellation and respect test timeouts. + When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationTokenSource.Token to enable cooperative cancellation and respect test timeouts. + + + + Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationTokenSource.Token' + Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationTokenSource.Token' + + + + Flow TestContext.CancellationToken to async operations + Flow TestContext.CancellationToken to async operations + + Use 'Assert.Fail' instead of an always-failing 'Assert.{0}' assert Usare 'Assert.Fail' invece di un'asserzione 'Assert.{0}' che ha sempre esito negativo. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf index 3094fd9e81..c1b7d5cf9b 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf @@ -432,6 +432,21 @@ The type declaring these methods should also respect the following rules: DynamicData は有効である必要があります + + When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationTokenSource.Token to enable cooperative cancellation and respect test timeouts. + When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationTokenSource.Token to enable cooperative cancellation and respect test timeouts. + + + + Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationTokenSource.Token' + Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationTokenSource.Token' + + + + Flow TestContext.CancellationToken to async operations + Flow TestContext.CancellationToken to async operations + + Use 'Assert.Fail' instead of an always-failing 'Assert.{0}' assert 常に失敗している 'Assert.{0}' アサートの代わりに 'Assert.Fail' を使用する。 diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf index 119fd7fa19..be96e0afa4 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf @@ -432,6 +432,21 @@ The type declaring these methods should also respect the following rules: DynamicData는 유효해야 합니다. + + When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationTokenSource.Token to enable cooperative cancellation and respect test timeouts. + When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationTokenSource.Token to enable cooperative cancellation and respect test timeouts. + + + + Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationTokenSource.Token' + Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationTokenSource.Token' + + + + Flow TestContext.CancellationToken to async operations + Flow TestContext.CancellationToken to async operations + + Use 'Assert.Fail' instead of an always-failing 'Assert.{0}' assert 항상 실패하는 'Assert.{0}' 어설션 대신 'Assert.Fail'을 사용합니다. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf index 3dfa3d4c0a..575319d36b 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf @@ -432,6 +432,21 @@ Typ deklarujący te metody powinien również przestrzegać następujących regu Wartość DynamicData powinna być prawidłowa + + When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationTokenSource.Token to enable cooperative cancellation and respect test timeouts. + When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationTokenSource.Token to enable cooperative cancellation and respect test timeouts. + + + + Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationTokenSource.Token' + Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationTokenSource.Token' + + + + Flow TestContext.CancellationToken to async operations + Flow TestContext.CancellationToken to async operations + + Use 'Assert.Fail' instead of an always-failing 'Assert.{0}' assert Użyj trybu „Assert.Fail” zamiast kończącej się zawsze niepowodzeniem instrukcji „Assert.{0}” diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf index 5e85f598b5..9ebf0918c9 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf @@ -432,6 +432,21 @@ O tipo que declara esses métodos também deve respeitar as seguintes regras: DynamicData deve ser válido + + When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationTokenSource.Token to enable cooperative cancellation and respect test timeouts. + When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationTokenSource.Token to enable cooperative cancellation and respect test timeouts. + + + + Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationTokenSource.Token' + Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationTokenSource.Token' + + + + Flow TestContext.CancellationToken to async operations + Flow TestContext.CancellationToken to async operations + + Use 'Assert.Fail' instead of an always-failing 'Assert.{0}' assert Use "Assert.Fail" em vez de uma asserção "Assert.{0}" sempre com falha diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf index 60dc6019e3..60aefa847f 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf @@ -438,6 +438,21 @@ The type declaring these methods should also respect the following rules: Значение DynamicData должно быть допустимым + + When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationTokenSource.Token to enable cooperative cancellation and respect test timeouts. + When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationTokenSource.Token to enable cooperative cancellation and respect test timeouts. + + + + Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationTokenSource.Token' + Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationTokenSource.Token' + + + + Flow TestContext.CancellationToken to async operations + Flow TestContext.CancellationToken to async operations + + Use 'Assert.Fail' instead of an always-failing 'Assert.{0}' assert Используйте "Assert.Fail" вместо утверждения с постоянным сбоем "Assert.{0}" diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf index d1fd2bbc3f..8e6cc678b5 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf @@ -432,6 +432,21 @@ Bu yöntemleri bildiren tipin ayrıca aşağıdaki kurallara uyması gerekir: DynamicData geçerli olmalıdır + + When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationTokenSource.Token to enable cooperative cancellation and respect test timeouts. + When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationTokenSource.Token to enable cooperative cancellation and respect test timeouts. + + + + Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationTokenSource.Token' + Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationTokenSource.Token' + + + + Flow TestContext.CancellationToken to async operations + Flow TestContext.CancellationToken to async operations + + Use 'Assert.Fail' instead of an always-failing 'Assert.{0}' assert Her zaman başarısız olan 'Assert.{0}' onaylaması yerine 'Assert.Fail' seçeneğini kullanın diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf index 34953062c7..8e611d2ddd 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf @@ -432,6 +432,21 @@ The type declaring these methods should also respect the following rules: DynamicData 应有效 + + When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationTokenSource.Token to enable cooperative cancellation and respect test timeouts. + When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationTokenSource.Token to enable cooperative cancellation and respect test timeouts. + + + + Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationTokenSource.Token' + Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationTokenSource.Token' + + + + Flow TestContext.CancellationToken to async operations + Flow TestContext.CancellationToken to async operations + + Use 'Assert.Fail' instead of an always-failing 'Assert.{0}' assert 使用 “Assert.Fail” 而不是始终失败的 “Assert.{0}” 断言 diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf index 182a4b2d03..0d770a8b2e 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf @@ -432,6 +432,21 @@ The type declaring these methods should also respect the following rules: DynamicData 應該有效 + + When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationTokenSource.Token to enable cooperative cancellation and respect test timeouts. + When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationTokenSource.Token to enable cooperative cancellation and respect test timeouts. + + + + Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationTokenSource.Token' + Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationTokenSource.Token' + + + + Flow TestContext.CancellationToken to async operations + Flow TestContext.CancellationToken to async operations + + Use 'Assert.Fail' instead of an always-failing 'Assert.{0}' assert 使用 'Assert.Fail',而不是一直失敗的 'Assert.{0}' 聲明 diff --git a/test/UnitTests/MSTest.Analyzers.UnitTests/FlowTestContextCancellationTokenAnalyzerTests.cs b/test/UnitTests/MSTest.Analyzers.UnitTests/FlowTestContextCancellationTokenAnalyzerTests.cs new file mode 100644 index 0000000000..95022f5cb7 --- /dev/null +++ b/test/UnitTests/MSTest.Analyzers.UnitTests/FlowTestContextCancellationTokenAnalyzerTests.cs @@ -0,0 +1,534 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using VerifyCS = MSTest.Analyzers.Test.CSharpCodeFixVerifier< + MSTest.Analyzers.FlowTestContextCancellationTokenAnalyzer, + MSTest.Analyzers.FlowTestContextCancellationTokenFixer>; + +namespace MSTest.Analyzers.Test; + +[TestClass] +public sealed class FlowTestContextCancellationTokenAnalyzerTests +{ + [TestMethod] + public async Task WhenTaskDelayWithoutCancellationToken_Diagnostic() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + using System.Threading; + using System.Threading.Tasks; + + [TestClass] + public class MyTestClass + { + public TestContext TestContext { get; set; } + + [TestMethod] + public async Task MyTestMethod() + { + await [|Task.Delay(1000)|]; + } + } + """; + + string fixedCode = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + using System.Threading; + using System.Threading.Tasks; + + [TestClass] + public class MyTestClass + { + public TestContext TestContext { get; set; } + + [TestMethod] + public async Task MyTestMethod() + { + await Task.Delay(1000, TestContext.CancellationTokenSource.Token); + } + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, fixedCode); + } + + [TestMethod] + public async Task WhenMethodCallAlreadyHasCancellationToken_NoDiagnostic() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + using System.Threading; + using System.Threading.Tasks; + + [TestClass] + public class MyTestClass + { + public TestContext TestContext { get; set; } + + [TestMethod] + public async Task MyTestMethod() + { + await Task.Delay(1000, TestContext.CancellationTokenSource.Token); + } + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, code); + } + + [TestMethod] + public async Task WhenNotInTestMethod_NoDiagnostic() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + using System.Threading; + using System.Threading.Tasks; + + public class MyClass + { + public async Task MyMethod() + { + await Task.Delay(1000); + } + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, code); + } + + [TestMethod] + public async Task WhenMethodHasNoOverloadWithCancellationToken_NoDiagnostic() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + using System; + using System.Threading; + using System.Threading.Tasks; + + [TestClass] + public class MyTestClass + { + public TestContext TestContext { get; set; } + + [TestMethod] + public void MyTestMethod() + { + Console.WriteLine("Hello World"); + } + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, code); + } + + [TestMethod] + public async Task WhenInTestInitialize_Diagnostic() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + using System.Threading; + using System.Threading.Tasks; + + [TestClass] + public class MyTestClass + { + public TestContext TestContext { get; set; } + + [TestInitialize] + public async Task TestInit() + { + await [|Task.Delay(1000)|]; + } + } + """; + + string fixedCode = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + using System.Threading; + using System.Threading.Tasks; + + [TestClass] + public class MyTestClass + { + public TestContext TestContext { get; set; } + + [TestInitialize] + public async Task TestInit() + { + await Task.Delay(1000, TestContext.CancellationTokenSource.Token); + } + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, fixedCode); + } + + [TestMethod] + public async Task WhenInTestCleanup_Diagnostic() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + using System.Threading; + using System.Threading.Tasks; + + [TestClass] + public class MyTestClass + { + public TestContext TestContext { get; set; } + + [TestCleanup] + public async Task TestCleanup() + { + await [|Task.Delay(1000)|]; + } + } + """; + + string fixedCode = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + using System.Threading; + using System.Threading.Tasks; + + [TestClass] + public class MyTestClass + { + public TestContext TestContext { get; set; } + + [TestCleanup] + public async Task TestCleanup() + { + await Task.Delay(1000, TestContext.CancellationTokenSource.Token); + } + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, fixedCode); + } + + [TestMethod] + public async Task WhenInClassInitialize_Diagnostic() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + using System.Threading; + using System.Threading.Tasks; + + [TestClass] + public class MyTestClass + { + [ClassInitialize] + public static async Task ClassInit(TestContext testContext) + { + await [|Task.Delay(1000)|]; + } + } + """; + + string fixedCode = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + using System.Threading; + using System.Threading.Tasks; + + [TestClass] + public class MyTestClass + { + [ClassInitialize] + public static async Task ClassInit(TestContext testContext) + { + await Task.Delay(1000, testContext.CancellationTokenSource.Token); + } + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, fixedCode); + } + + [TestMethod] + public async Task WhenInClassCleanupWithTestContextParameter_Diagnostic() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + using System.Threading; + using System.Threading.Tasks; + + [TestClass] + public class MyTestClass + { + [ClassCleanup] + public static async Task ClassCleanup(TestContext testContext) + { + await [|Task.Delay(1000)|]; + } + } + """; + + string fixedCode = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + using System.Threading; + using System.Threading.Tasks; + + [TestClass] + public class MyTestClass + { + [ClassCleanup] + public static async Task ClassCleanup(TestContext testContext) + { + await Task.Delay(1000, testContext.CancellationTokenSource.Token); + } + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, fixedCode); + } + + [TestMethod] + public async Task WhenInClassCleanupWithoutTestContextParameter_Diagnostic() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + using System.Threading; + using System.Threading.Tasks; + + [TestClass] + public class MyTestClass + { + [ClassCleanup] + public static async Task ClassCleanup() + { + await [|Task.Delay(1000)|]; + } + } + """; + + // Codefix doesn't yet handle the addition of TestContext parameter. + string fixedCode = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + using System.Threading; + using System.Threading.Tasks; + + [TestClass] + public class MyTestClass + { + [ClassCleanup] + public static async Task ClassCleanup() + { + await Task.Delay(1000, {|CS0103:testContext|}.CancellationTokenSource.Token); + } + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, fixedCode); + } + + [TestMethod] + public async Task WhenInTestMethodWithoutTestContextInScope_Diagnostic() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + using System.Threading; + using System.Threading.Tasks; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public async Task Test1() + { + await [|Task.Delay(1000)|]; + } + + [TestMethod] + [DataRow(0)] + [DataRow(1)] + public async Task Test2(int _) + { + await [|Task.Delay(1000)|]; + } + } + """; + + string fixedCode = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + using System.Threading; + using System.Threading.Tasks; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public async Task Test1() + { + await Task.Delay(1000, {|CS0103:testContext|}.CancellationTokenSource.Token); + } + + [TestMethod] + [DataRow(0)] + [DataRow(1)] + public async Task Test2(int _) + { + await Task.Delay(1000, {|CS0103:testContext|}.CancellationTokenSource.Token); + } + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, fixedCode); + } + + [TestMethod] + public async Task WhenInTestMethodWithTestContextFieldInScope_Diagnostic() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + using System.Threading; + using System.Threading.Tasks; + + [TestClass] + public class MyTestClass + { + private readonly TestContext _testContext; + + public MyTestClass(TestContext testContext) + => _testContext = testContext; + + [TestMethod] + public async Task Test1() + { + await [|Task.Delay(1000)|]; + } + } + """; + + string fixedCode = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + using System.Threading; + using System.Threading.Tasks; + + [TestClass] + public class MyTestClass + { + private readonly TestContext _testContext; + + public MyTestClass(TestContext testContext) + => _testContext = testContext; + + [TestMethod] + public async Task Test1() + { + await Task.Delay(1000, _testContext.CancellationTokenSource.Token); + } + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, fixedCode); + } + + [TestMethod] + public async Task WhenInTestMethodWithTestContextInScopeViaPrimaryConstructor_Diagnostic() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + using System.Threading; + using System.Threading.Tasks; + + [TestClass] + public class MyTestClass(TestContext MyTestContext) + { + [TestMethod] + public async Task Test1() + { + _ = MyTestContext; + await [|Task.Delay(1000)|]; + } + } + """; + + string fixedCode = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + using System.Threading; + using System.Threading.Tasks; + + [TestClass] + public class MyTestClass(TestContext MyTestContext) + { + [TestMethod] + public async Task Test1() + { + _ = MyTestContext; + await Task.Delay(1000, MyTestContext.CancellationTokenSource.Token); + } + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, fixedCode); + } + + [TestMethod] + public async Task WhenWithCancellationTokenNone_NoDiagnostic() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + using System.Threading; + using System.Threading.Tasks; + + [TestClass] + public class MyTestClass + { + public TestContext TestContext { get; set; } + + [TestMethod] + public async Task MyTestMethod() + { + await Task.Delay(1000, CancellationToken.None); + } + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, code); + } + + [TestMethod] + public async Task WhenHttpClientMethodWithoutCancellationToken_Diagnostic() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + using System.Net.Http; + using System.Threading; + using System.Threading.Tasks; + + [TestClass] + public class MyTestClass + { + public TestContext TestContext { get; set; } + + [TestMethod] + public async Task MyTestMethod() + { + using var client = new HttpClient(); + var response = await [|client.GetAsync("https://example.com")|]; + } + } + """; + + string fixedCode = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + using System.Net.Http; + using System.Threading; + using System.Threading.Tasks; + + [TestClass] + public class MyTestClass + { + public TestContext TestContext { get; set; } + + [TestMethod] + public async Task MyTestMethod() + { + using var client = new HttpClient(); + var response = await client.GetAsync("https://example.com", TestContext.CancellationTokenSource.Token); + } + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, fixedCode); + } +} From 171ae1e9b5fb101f8c47ab2e8dff0fbb250d3bf9 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Tue, 22 Jul 2025 19:03:43 +0200 Subject: [PATCH 274/541] Report analyzer times in binlog (#6130) --- Directory.Build.props | 1 + 1 file changed, 1 insertion(+) diff --git a/Directory.Build.props b/Directory.Build.props index 92b7d2dad5..6a5ae30911 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -14,6 +14,7 @@ enable true enable + true From 73304f9fedf4442d6f87ef8b7ef64261f307a7ad Mon Sep 17 00:00:00 2001 From: Copilot <198982749+Copilot@users.noreply.github.com> Date: Wed, 23 Jul 2025 04:45:15 +0200 Subject: [PATCH 275/541] Fix MSTEST0037 codefix to preserve message arguments in collection count transformations (#6123) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: Evangelink <11340282+Evangelink@users.noreply.github.com> Co-authored-by: Amaury Levé --- .../UseProperAssertMethodsFixer.cs | 28 ++-- .../UseProperAssertMethodsAnalyzerTests.cs | 126 ++++++++++++++++++ 2 files changed, 144 insertions(+), 10 deletions(-) diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/UseProperAssertMethodsFixer.cs b/src/Analyzers/MSTest.Analyzers.CodeFixes/UseProperAssertMethodsFixer.cs index ddeb839fd7..3c5ef8c80f 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/UseProperAssertMethodsFixer.cs +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/UseProperAssertMethodsFixer.cs @@ -241,27 +241,35 @@ private static async Task FixAssertMethodForCollectionCountModeAsync( DocumentEditor editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false); FixInvocationMethodName(editor, simpleNameSyntax, properAssertMethodName); + // Preserve any additional arguments beyond the first two (expected/actual) + var additionalArguments = argumentList.Arguments.Skip(2).ToList(); + ArgumentListSyntax newArgumentList; if (properAssertMethodName == "IsEmpty") { - // For IsEmpty, we just need the collection argument - newArgumentList = argumentList.WithArguments( - SyntaxFactory.SeparatedList(new[] { SyntaxFactory.Argument(collectionExpression).WithAdditionalAnnotations(Formatter.Annotation) })); + // For IsEmpty, we just need the collection argument plus any additional arguments + var newArguments = new List + { + SyntaxFactory.Argument(collectionExpression).WithAdditionalAnnotations(Formatter.Annotation), + }; + newArguments.AddRange(additionalArguments); + newArgumentList = argumentList.WithArguments(SyntaxFactory.SeparatedList(newArguments)); } else // HasCount { - // For HasCount, we need count and collection arguments + // For HasCount, we need count and collection arguments plus any additional arguments // additionalLocations[3] should contain the count expression if (additionalLocations.Count > 3 && root.FindNode(additionalLocations[3].SourceSpan) is ArgumentSyntax countArgument) { - newArgumentList = argumentList.WithArguments( - SyntaxFactory.SeparatedList(new[] - { - SyntaxFactory.Argument(countArgument.Expression).WithAdditionalAnnotations(Formatter.Annotation), - SyntaxFactory.Argument(collectionExpression).WithAdditionalAnnotations(Formatter.Annotation), - })); + var newArguments = new List + { + SyntaxFactory.Argument(countArgument.Expression).WithAdditionalAnnotations(Formatter.Annotation), + SyntaxFactory.Argument(collectionExpression).WithAdditionalAnnotations(Formatter.Annotation), + }; + newArguments.AddRange(additionalArguments); + newArgumentList = argumentList.WithArguments(SyntaxFactory.SeparatedList(newArguments)); } else { diff --git a/test/UnitTests/MSTest.Analyzers.UnitTests/UseProperAssertMethodsAnalyzerTests.cs b/test/UnitTests/MSTest.Analyzers.UnitTests/UseProperAssertMethodsAnalyzerTests.cs index 227bd1fd20..991e03496a 100644 --- a/test/UnitTests/MSTest.Analyzers.UnitTests/UseProperAssertMethodsAnalyzerTests.cs +++ b/test/UnitTests/MSTest.Analyzers.UnitTests/UseProperAssertMethodsAnalyzerTests.cs @@ -1866,5 +1866,131 @@ public void MyTestMethod() await VerifyCS.VerifyAnalyzerAsync(code); } + [TestMethod] + public async Task WhenAssertAreEqualWithCollectionCountAndMessage_HasCount() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + using System.Collections.Generic; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + var myCollection = new List { 1, 2 }; + {|#0:Assert.AreEqual(2, myCollection.Count, "Wrong number of elements")|}; + } + } + """; + + string fixedCode = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + using System.Collections.Generic; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + var myCollection = new List { 1, 2 }; + Assert.HasCount(2, myCollection, "Wrong number of elements"); + } + } + """; + + await VerifyCS.VerifyCodeFixAsync( + code, + // /0/Test0.cs(11,9): info MSTEST0037: Use 'Assert.HasCount' instead of 'Assert.AreEqual' + VerifyCS.DiagnosticIgnoringAdditionalLocations().WithLocation(0).WithArguments("HasCount", "AreEqual"), + fixedCode); + } + + [TestMethod] + public async Task WhenAssertAreEqualWithCollectionCountZeroAndMessage_IsEmpty() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + using System.Collections.Generic; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + var list = new List(); + {|#0:Assert.AreEqual(0, list.Count, "Collection should be empty")|}; + } + } + """; + + string fixedCode = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + using System.Collections.Generic; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + var list = new List(); + Assert.IsEmpty(list, "Collection should be empty"); + } + } + """; + + await VerifyCS.VerifyCodeFixAsync( + code, + // /0/Test0.cs(11,9): info MSTEST0037: Use 'Assert.IsEmpty' instead of 'Assert.AreEqual' + VerifyCS.DiagnosticIgnoringAdditionalLocations().WithLocation(0).WithArguments("IsEmpty", "AreEqual"), + fixedCode); + } + + [TestMethod] + public async Task WhenAssertAreEqualWithCollectionCountAndMultipleParameters() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + using System.Collections.Generic; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + var list = new List { 1, 2, 3 }; + {|#0:Assert.AreEqual(3, list.Count, "Wrong count: expected {0} but was {1}", 3, list.Count)|}; + } + } + """; + + string fixedCode = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + using System.Collections.Generic; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + var list = new List { 1, 2, 3 }; + Assert.HasCount(3, list, "Wrong count: expected {0} but was {1}", 3, list.Count); + } + } + """; + + await VerifyCS.VerifyCodeFixAsync( + code, + // /0/Test0.cs(11,9): info MSTEST0037: Use 'Assert.HasCount' instead of 'Assert.AreEqual' + VerifyCS.DiagnosticIgnoringAdditionalLocations().WithLocation(0).WithArguments("HasCount", "AreEqual"), + fixedCode); + } + #endregion } From ccd9f10998158a50af2f6fff39abf54fd22bdd94 Mon Sep 17 00:00:00 2001 From: dotnet bot Date: Wed, 23 Jul 2025 04:57:25 +0200 Subject: [PATCH 276/541] Localized file check-in by OneLocBuild Task: Build definition ID 1218: Build ID 2755993 --- src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf | 6 +++--- src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf | 6 +++--- src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf | 6 +++--- src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf | 6 +++--- src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf | 6 +++--- 5 files changed, 15 insertions(+), 15 deletions(-) diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf index 1340f34ec7..b6caeaf386 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf @@ -887,17 +887,17 @@ Der Typ, der diese Methoden deklariert, sollte auch die folgenden Regeln beachte TestContext property cannot be accessed in this context - TestContext property cannot be accessed in this context + Auf die TestContext-Eigenschaft kann in diesem Kontext nicht zugegriffen werden TestContext property '{0}' cannot be accessed in '{1}' method - TestContext property '{0}' cannot be accessed in '{1}' method + Auf die TestContext-Eigenschaft „{0}“ kann in der Methode „{1}“ nicht zugegriffen werden Some TestContext properties are only available during test execution and cannot be accessed in assembly initialize, class initialize, class cleanup, or assembly cleanup methods. - Some TestContext properties are only available during test execution and cannot be accessed in assembly initialize, class initialize, class cleanup, or assembly cleanup methods. + Einige TestContext-Eigenschaften sind nur während der Testausführung verfügbar und können nicht in Assemblyinitialisierungs-, Klasseninitialisierungs-, Klassenbereinigungs- oder Assemblybereinigungsmethoden aufgerufen werden. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf index 60aefa847f..d90854fd5b 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf @@ -898,17 +898,17 @@ The type declaring these methods should also respect the following rules: TestContext property cannot be accessed in this context - TestContext property cannot be accessed in this context + Свойство TestContext недоступно в этом контексте TestContext property '{0}' cannot be accessed in '{1}' method - TestContext property '{0}' cannot be accessed in '{1}' method + Свойство TestContext "{0}" недоступно в методе "{1}" Some TestContext properties are only available during test execution and cannot be accessed in assembly initialize, class initialize, class cleanup, or assembly cleanup methods. - Some TestContext properties are only available during test execution and cannot be accessed in assembly initialize, class initialize, class cleanup, or assembly cleanup methods. + Некоторые свойства TestContext доступны только во время выполнения теста и недоступны в методах инициализации сборки, инициализации класса, очистки класса или очистки сборки. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf index 8e6cc678b5..56d299a314 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf @@ -888,17 +888,17 @@ Bu yöntemleri bildiren tipin ayrıca aşağıdaki kurallara uyması gerekir: TestContext property cannot be accessed in this context - TestContext property cannot be accessed in this context + TestContext özelliğine bu bağlamda erişilemiyor TestContext property '{0}' cannot be accessed in '{1}' method - TestContext property '{0}' cannot be accessed in '{1}' method + TestContext '{0}' özelliğine '{1}' yönteminde erişilemiyor Some TestContext properties are only available during test execution and cannot be accessed in assembly initialize, class initialize, class cleanup, or assembly cleanup methods. - Some TestContext properties are only available during test execution and cannot be accessed in assembly initialize, class initialize, class cleanup, or assembly cleanup methods. + Bazı TestContext özellikleri yalnızca test yürütmesi sırasında kullanılabilir ve derleme başlatma, sınıf başlatma, sınıf temizleme veya derleme temizleme yöntemlerinde erişilemez. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf index 8e611d2ddd..f6710015b2 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf @@ -886,17 +886,17 @@ The type declaring these methods should also respect the following rules: TestContext property cannot be accessed in this context - TestContext property cannot be accessed in this context + 无法在此上下文中访问 TestContext 属性 TestContext property '{0}' cannot be accessed in '{1}' method - TestContext property '{0}' cannot be accessed in '{1}' method + 无法在 ‘{1}’ 方法中访问 TestContext 属性 ‘{0}’ Some TestContext properties are only available during test execution and cannot be accessed in assembly initialize, class initialize, class cleanup, or assembly cleanup methods. - Some TestContext properties are only available during test execution and cannot be accessed in assembly initialize, class initialize, class cleanup, or assembly cleanup methods. + 一些 TestContext 属性仅在测试执行期间可用,并且无法在程序集初始化、类初始化、类清理或程序集清理方法中访问。 diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf index 0d770a8b2e..a4e05e11a1 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf @@ -886,17 +886,17 @@ The type declaring these methods should also respect the following rules: TestContext property cannot be accessed in this context - TestContext property cannot be accessed in this context + 無法在此內容中存取 TestContext 屬性 TestContext property '{0}' cannot be accessed in '{1}' method - TestContext property '{0}' cannot be accessed in '{1}' method + 無法在 '{1}' 方法中存取 TestContext 屬性 '{0}' Some TestContext properties are only available during test execution and cannot be accessed in assembly initialize, class initialize, class cleanup, or assembly cleanup methods. - Some TestContext properties are only available during test execution and cannot be accessed in assembly initialize, class initialize, class cleanup, or assembly cleanup methods. + 某些 TestContext 屬性僅在測試執行期間可供使用,無法在組件初始化、類別初始化、類別清理或組件清理方法中存取。 From 7d305158d16bc674ed85e897b3e5b842867877d8 Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Wed, 23 Jul 2025 07:22:59 +0000 Subject: [PATCH 277/541] [main] Update dependencies from microsoft/testfx (#6133) Co-authored-by: dotnet-maestro[bot] Co-authored-by: Youssef1313 --- eng/Version.Details.xml | 8 +- eng/Versions.props | 4 +- .../UnhandledExceptionPolicyTests.cs | 6 +- .../DataRowAttributeGenerationTests.cs | 32 +++--- .../Generators/DynamicDataAttributeTests.cs | 6 +- .../IgnoreAttributeGenerationTests.cs | 4 +- .../Generators/StaticMethodGenerationTests.cs | 4 +- .../Generators/TestNodesGeneratorTests.cs | 42 ++++---- .../Helpers/CountDownEventTests.cs | 8 +- .../Helpers/SystemAsyncMonitorTests.cs | 6 +- .../Helpers/TaskExtensionsTests.cs | 27 ++--- .../IPC/IPCTests.cs | 99 ++++++++++--------- .../Logging/FileLoggerTests.cs | 9 +- .../Messages/AsynchronousMessageBusTests.cs | 6 +- 14 files changed, 144 insertions(+), 117 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index d937350ea9..f9e81efd4f 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -17,13 +17,13 @@ https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage 6140a1b569c1205f4f596d4752c95a43c0f06d06 - + https://github.com/microsoft/testfx - 4a8fcdaacd6ff086be895fc4aaf9e5c7d49e9f24 + 171ae1e9b5fb101f8c47ab2e8dff0fbb250d3bf9 - + https://github.com/microsoft/testfx - 4a8fcdaacd6ff086be895fc4aaf9e5c7d49e9f24 + 171ae1e9b5fb101f8c47ab2e8dff0fbb250d3bf9 diff --git a/eng/Versions.props b/eng/Versions.props index 5ee36231a6..a11f56d827 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -10,7 +10,7 @@ 10.0.0-beta.25367.5 18.0.0-preview.25371.1 - 3.10.0-preview.25371.5 - 1.8.0-preview.25371.5 + 3.10.0-preview.25372.9 + 1.8.0-preview.25372.9 diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/UnhandledExceptionPolicyTests.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/UnhandledExceptionPolicyTests.cs index dcfe88cffe..57398ce7e5 100644 --- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/UnhandledExceptionPolicyTests.cs +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/UnhandledExceptionPolicyTests.cs @@ -15,6 +15,8 @@ public enum Mode Default, } + public TestContext TestContext { get; set; } + internal static IEnumerable<(Mode Mode, string Arguments)> ModeProvider() { foreach (string tfm in TargetFrameworks.All) @@ -36,7 +38,7 @@ public async Task UnhandledExceptionPolicy_ConfigFile_UnobservedTaskException_Sh await clone.CopyDirectoryAsync(testHost.DirectoryName, clone.Path, retainAttributes: !RuntimeInformation.IsOSPlatform(OSPlatform.Windows)); testHost = TestInfrastructure.TestHost.LocateFrom(clone.Path, "UnhandledExceptionPolicyTests"); string configFileName = Path.Combine(testHost.DirectoryName, "UnhandledExceptionPolicyTests.testconfig.json"); - string contentFile = await File.ReadAllTextAsync(Path.Combine(testHost.DirectoryName, "UnhandledExceptionPolicyTests.testconfig.json")); + string contentFile = await File.ReadAllTextAsync(Path.Combine(testHost.DirectoryName, "UnhandledExceptionPolicyTests.testconfig.json"), TestContext.CancellationTokenSource.Token); TestHostResult? testHostResult; switch (mode) @@ -93,7 +95,7 @@ public async Task UnhandledExceptionPolicy_EnvironmentVariable_UnhandledExceptio await clone.CopyDirectoryAsync(testHost.DirectoryName, clone.Path, retainAttributes: !RuntimeInformation.IsOSPlatform(OSPlatform.Windows)); testHost = TestInfrastructure.TestHost.LocateFrom(clone.Path, "UnhandledExceptionPolicyTests"); string configFileName = Path.Combine(testHost.DirectoryName, "UnhandledExceptionPolicyTests.testconfig.json"); - string contentFile = await File.ReadAllTextAsync(Path.Combine(testHost.DirectoryName, "UnhandledExceptionPolicyTests.testconfig.json")); + string contentFile = await File.ReadAllTextAsync(Path.Combine(testHost.DirectoryName, "UnhandledExceptionPolicyTests.testconfig.json"), TestContext.CancellationTokenSource.Token); TestHostResult? testHostResult; switch (mode) diff --git a/test/UnitTests/MSTest.SourceGeneration.UnitTests/Generators/DataRowAttributeGenerationTests.cs b/test/UnitTests/MSTest.SourceGeneration.UnitTests/Generators/DataRowAttributeGenerationTests.cs index 352b28d89f..905e697241 100644 --- a/test/UnitTests/MSTest.SourceGeneration.UnitTests/Generators/DataRowAttributeGenerationTests.cs +++ b/test/UnitTests/MSTest.SourceGeneration.UnitTests/Generators/DataRowAttributeGenerationTests.cs @@ -13,6 +13,8 @@ namespace Microsoft.Testing.Framework.SourceGeneration.UnitTests.Generators; [TestClass] public sealed class DataRowAttributeGenerationTests : TestBase { + public TestContext TestContext { get; set; } + [TestMethod] public async Task DataRowAttribute_HandlesPrimitiveTypes() { @@ -98,7 +100,7 @@ public Task MethodWithUShort(ushort s) SyntaxTree? testClassTree = generatorResult.GeneratedTrees.FirstOrDefault(r => r.FilePath.EndsWith("TestClass.g.cs", StringComparison.OrdinalIgnoreCase)); testClassTree.Should().NotBeNull(); - SourceText testClass = await testClassTree!.GetTextAsync(); + SourceText testClass = await testClassTree!.GetTextAsync(TestContext.CancellationTokenSource.Token); testClass.Should().ContainSourceCode(""" GetArguments = static () => new MSTF::InternalUnsafeTestArgumentsEntry[] @@ -213,7 +215,7 @@ public Task TestMethod(string s, int i, bool b, double d) SyntaxTree? testClassTree = generatorResult.GeneratedTrees.FirstOrDefault(r => r.FilePath.EndsWith("TestClass.g.cs", StringComparison.OrdinalIgnoreCase)); testClassTree.Should().NotBeNull(); - SourceText testClass = await testClassTree!.GetTextAsync(); + SourceText testClass = await testClassTree!.GetTextAsync(TestContext.CancellationTokenSource.Token); testClass.Should().ContainSourceCode(""" GetArguments = static () => new MSTF::InternalUnsafeTestArgumentsEntry<(string s, int i)>[] @@ -257,7 +259,7 @@ public Task TestMethod(string a) SyntaxTree? testClassTree = generatorResult.GeneratedTrees.FirstOrDefault(r => r.FilePath.EndsWith("TestClass.g.cs", StringComparison.OrdinalIgnoreCase)); testClassTree.Should().NotBeNull(); - SourceText testClass = await testClassTree!.GetTextAsync(); + SourceText testClass = await testClassTree!.GetTextAsync(TestContext.CancellationTokenSource.Token); testClass.Should().ContainSourceCode(""" GetArguments = static () => new MSTF::InternalUnsafeTestArgumentsEntry[] @@ -301,7 +303,7 @@ public Task TestMethod(Type a) SyntaxTree? testClassTree = generatorResult.GeneratedTrees.FirstOrDefault(r => r.FilePath.EndsWith("TestClass.g.cs", StringComparison.OrdinalIgnoreCase)); testClassTree.Should().NotBeNull(); - SourceText testClass = await testClassTree!.GetTextAsync(); + SourceText testClass = await testClassTree!.GetTextAsync(TestContext.CancellationTokenSource.Token); testClass.Should().ContainSourceCode(""" GetArguments = static () => new MSTF::InternalUnsafeTestArgumentsEntry[] @@ -348,7 +350,7 @@ public Task TestMethod(MyEnum a) SyntaxTree? testClassTree = generatorResult.GeneratedTrees.FirstOrDefault(r => r.FilePath.EndsWith("TestClass.g.cs", StringComparison.OrdinalIgnoreCase)); testClassTree.Should().NotBeNull(); - SourceText testClass = await testClassTree!.GetTextAsync(); + SourceText testClass = await testClassTree!.GetTextAsync(TestContext.CancellationTokenSource.Token); testClass.Should().ContainSourceCode(""" GetArguments = static () => new MSTF::InternalUnsafeTestArgumentsEntry[] @@ -408,7 +410,7 @@ public Task TestMethod(MyEnum a) SyntaxTree? testClassTree = generatorResult.GeneratedTrees.FirstOrDefault(r => r.FilePath.EndsWith("TestClass.g.cs", StringComparison.OrdinalIgnoreCase)); testClassTree.Should().NotBeNull(); - SourceText testClass = await testClassTree!.GetTextAsync(); + SourceText testClass = await testClassTree!.GetTextAsync(TestContext.CancellationTokenSource.Token); testClass.Should().ContainSourceCode(""" GetArguments = static () => new MSTF::InternalUnsafeTestArgumentsEntry[] @@ -462,7 +464,7 @@ public Task TestMethod(ConflictingNamespace.MyEnum a) SyntaxTree? testClassTree = generatorResult.GeneratedTrees.FirstOrDefault(r => r.FilePath.EndsWith("TestClass.g.cs", StringComparison.OrdinalIgnoreCase)); testClassTree.Should().NotBeNull(); - SourceText testClass = await testClassTree!.GetTextAsync(); + SourceText testClass = await testClassTree!.GetTextAsync(TestContext.CancellationTokenSource.Token); testClass.Should().ContainSourceCode(""" GetArguments = static () => new MSTF::InternalUnsafeTestArgumentsEntry[] @@ -511,7 +513,7 @@ public Task TestMethod1(string s, object a) SyntaxTree? testClassTree = generatorResult.GeneratedTrees.FirstOrDefault(r => r.FilePath.EndsWith("TestClass.g.cs", StringComparison.OrdinalIgnoreCase)); testClassTree.Should().NotBeNull(); - SourceText testClass = await testClassTree!.GetTextAsync(); + SourceText testClass = await testClassTree!.GetTextAsync(TestContext.CancellationTokenSource.Token); testClass.Should().ContainSourceCode(""" GetArguments = static () => new MSTF::InternalUnsafeTestArgumentsEntry[] @@ -565,7 +567,7 @@ public Task TestMethod2(string a, string b) SyntaxTree? testClassTree = generatorResult.GeneratedTrees.FirstOrDefault(r => r.FilePath.EndsWith("TestClass.g.cs", StringComparison.OrdinalIgnoreCase)); testClassTree.Should().NotBeNull(); - SourceText testClass = await testClassTree!.GetTextAsync(); + SourceText testClass = await testClassTree!.GetTextAsync(TestContext.CancellationTokenSource.Token); testClass.Should().ContainSourceCode(""" // The test method is parameterized but no argument was specified. @@ -646,7 +648,7 @@ public Task OneObjectArray(object[] args) SyntaxTree? testClassTree = generatorResult.GeneratedTrees.FirstOrDefault(r => r.FilePath.EndsWith("TestClass.g.cs", StringComparison.OrdinalIgnoreCase)); testClassTree.Should().NotBeNull(); - SourceText testClass = await testClassTree!.GetTextAsync(); + SourceText testClass = await testClassTree!.GetTextAsync(TestContext.CancellationTokenSource.Token); testClass.Should().ContainSourceCode(""" GetArguments = static () => new MSTF::InternalUnsafeTestArgumentsEntry[] @@ -683,7 +685,7 @@ public Task OneIntArray(int[] args) SyntaxTree? testClassTree = generatorResult.GeneratedTrees.FirstOrDefault(r => r.FilePath.EndsWith("TestClass.g.cs", StringComparison.OrdinalIgnoreCase)); testClassTree.Should().NotBeNull(); - SourceText testClass = await testClassTree!.GetTextAsync(); + SourceText testClass = await testClassTree!.GetTextAsync(TestContext.CancellationTokenSource.Token); testClass.Should().ContainSourceCode(""" GetArguments = static () => new MSTF::InternalUnsafeTestArgumentsEntry[] @@ -720,7 +722,7 @@ public Task OneStringArray(string[] args) SyntaxTree? testClassTree = generatorResult.GeneratedTrees.FirstOrDefault(r => r.FilePath.EndsWith("TestClass.g.cs", StringComparison.OrdinalIgnoreCase)); testClassTree.Should().NotBeNull(); - SourceText testClass = await testClassTree!.GetTextAsync(); + SourceText testClass = await testClassTree!.GetTextAsync(TestContext.CancellationTokenSource.Token); testClass.Should().ContainSourceCode(""" GetArguments = static () => new MSTF::InternalUnsafeTestArgumentsEntry[] @@ -756,7 +758,7 @@ public Task OneParamsObjectArray2(object[] args) SyntaxTree? testClassTree = generatorResult.GeneratedTrees.FirstOrDefault(r => r.FilePath.EndsWith("TestClass.g.cs", StringComparison.OrdinalIgnoreCase)); testClassTree.Should().NotBeNull(); - SourceText testClass = await testClassTree!.GetTextAsync(); + SourceText testClass = await testClassTree!.GetTextAsync(TestContext.CancellationTokenSource.Token); testClass.Should().ContainSourceCode(""" GetArguments = static () => new MSTF::InternalUnsafeTestArgumentsEntry[] @@ -794,7 +796,7 @@ public Task OneIntArray(object[] args) SyntaxTree? testClassTree = generatorResult.GeneratedTrees.FirstOrDefault(r => r.FilePath.EndsWith("TestClass.g.cs", StringComparison.OrdinalIgnoreCase)); testClassTree.Should().NotBeNull(); - SourceText testClass = await testClassTree!.GetTextAsync(); + SourceText testClass = await testClassTree!.GetTextAsync(TestContext.CancellationTokenSource.Token); testClass.Should().ContainSourceCode(""" GetArguments = static () => new MSTF::InternalUnsafeTestArgumentsEntry[] @@ -831,7 +833,7 @@ public Task TwoObjectArrays(object[] args, object[] args2) SyntaxTree? testClassTree = generatorResult.GeneratedTrees.FirstOrDefault(r => r.FilePath.EndsWith("TestClass.g.cs", StringComparison.OrdinalIgnoreCase)); testClassTree.Should().NotBeNull(); - SourceText testClass = await testClassTree!.GetTextAsync(); + SourceText testClass = await testClassTree!.GetTextAsync(TestContext.CancellationTokenSource.Token); testClass.Should().ContainSourceCode(""" GetArguments = static () => new MSTF::InternalUnsafeTestArgumentsEntry<(object[] args, object[] args2)>[] diff --git a/test/UnitTests/MSTest.SourceGeneration.UnitTests/Generators/DynamicDataAttributeTests.cs b/test/UnitTests/MSTest.SourceGeneration.UnitTests/Generators/DynamicDataAttributeTests.cs index 1016eaf683..21c0def72c 100644 --- a/test/UnitTests/MSTest.SourceGeneration.UnitTests/Generators/DynamicDataAttributeTests.cs +++ b/test/UnitTests/MSTest.SourceGeneration.UnitTests/Generators/DynamicDataAttributeTests.cs @@ -13,6 +13,8 @@ namespace Microsoft.Testing.Framework.SourceGeneration.UnitTests.Generators; [TestClass] public sealed class DynamicDataAttributeGenerationTests : TestBase { + public TestContext TestContext { get; set; } + [TestMethod] public async Task DynamicDataAttribute_TakesDataFromProperty() { @@ -47,7 +49,7 @@ public void TestMethod(int expected, int actualPlus1) SyntaxTree? testClassTree = generatorResult.GeneratedTrees.FirstOrDefault(r => r.FilePath.EndsWith("TestClass.g.cs", StringComparison.OrdinalIgnoreCase)); testClassTree.Should().NotBeNull(); - SourceText testClass = await testClassTree!.GetTextAsync(); + SourceText testClass = await testClassTree!.GetTextAsync(TestContext.CancellationTokenSource.Token); testClass.Should().ContainSourceCode(""" GetArguments = static () => { @@ -99,7 +101,7 @@ public static IEnumerable Data() => new[] SyntaxTree? testClassTree = generatorResult.GeneratedTrees.FirstOrDefault(r => r.FilePath.EndsWith("TestClass.g.cs", StringComparison.OrdinalIgnoreCase)); testClassTree.Should().NotBeNull(); - SourceText testClass = await testClassTree!.GetTextAsync(); + SourceText testClass = await testClassTree!.GetTextAsync(TestContext.CancellationTokenSource.Token); testClass.Should().ContainSourceCode(""" GetArguments = static () => { diff --git a/test/UnitTests/MSTest.SourceGeneration.UnitTests/Generators/IgnoreAttributeGenerationTests.cs b/test/UnitTests/MSTest.SourceGeneration.UnitTests/Generators/IgnoreAttributeGenerationTests.cs index 26e69d96c2..402f796376 100644 --- a/test/UnitTests/MSTest.SourceGeneration.UnitTests/Generators/IgnoreAttributeGenerationTests.cs +++ b/test/UnitTests/MSTest.SourceGeneration.UnitTests/Generators/IgnoreAttributeGenerationTests.cs @@ -13,6 +13,8 @@ namespace Microsoft.Testing.Framework.SourceGeneration.UnitTests.Generators; [TestClass] public sealed class IgnoreAttributeGenerationTests : TestBase { + public TestContext TestContext { get; set; } + [TestMethod] public async Task IgnoreAttribute_OnMethodExcludesTheMethodFromCompilation() { @@ -62,7 +64,7 @@ public void IgnoredVoidMethodWithReason() { } SyntaxTree? testClassTree = generatorResult.GeneratedTrees.FirstOrDefault(r => r.FilePath.EndsWith("TestClass.g.cs", StringComparison.OrdinalIgnoreCase)); testClassTree.Should().NotBeNull(); - SourceText testClass = await testClassTree!.GetTextAsync(); + SourceText testClass = await testClassTree!.GetTextAsync(TestContext.CancellationTokenSource.Token); testClass.Should().ContainSourceCode("""StableUid = "TestAssembly.MyNamespace.TestClass.TestMethod1()","""); diff --git a/test/UnitTests/MSTest.SourceGeneration.UnitTests/Generators/StaticMethodGenerationTests.cs b/test/UnitTests/MSTest.SourceGeneration.UnitTests/Generators/StaticMethodGenerationTests.cs index 8a5a7de839..d536926a30 100644 --- a/test/UnitTests/MSTest.SourceGeneration.UnitTests/Generators/StaticMethodGenerationTests.cs +++ b/test/UnitTests/MSTest.SourceGeneration.UnitTests/Generators/StaticMethodGenerationTests.cs @@ -13,6 +13,8 @@ namespace Microsoft.Testing.Framework.SourceGeneration.UnitTests.Generators; [TestClass] public sealed class StaticMethodGenerationTests { + public TestContext TestContext { get; set; } + [TestMethod] public async Task StaticMethods_StaticMethodsWontGenerateTests() { @@ -46,7 +48,7 @@ public static void StaticTestMethod() { } SyntaxTree? testClassTree = generatorResult.GeneratedTrees.FirstOrDefault(r => r.FilePath.EndsWith("TestClass.g.cs", StringComparison.OrdinalIgnoreCase)); testClassTree.Should().NotBeNull(); - SourceText testClass = await testClassTree!.GetTextAsync(); + SourceText testClass = await testClassTree!.GetTextAsync(TestContext.CancellationTokenSource.Token); testClass.Should().ContainSourceCode("""StableUid = "TestAssembly.MyNamespace.TestClass.TestMethod1()","""); diff --git a/test/UnitTests/MSTest.SourceGeneration.UnitTests/Generators/TestNodesGeneratorTests.cs b/test/UnitTests/MSTest.SourceGeneration.UnitTests/Generators/TestNodesGeneratorTests.cs index 7d3c831a9b..c528c601ba 100644 --- a/test/UnitTests/MSTest.SourceGeneration.UnitTests/Generators/TestNodesGeneratorTests.cs +++ b/test/UnitTests/MSTest.SourceGeneration.UnitTests/Generators/TestNodesGeneratorTests.cs @@ -13,6 +13,8 @@ namespace Microsoft.Testing.Framework.SourceGeneration.UnitTests.Generators; [TestClass] public sealed class TestNodesGeneratorTests : TestBase { + public TestContext TestContext { get; set; } + [DataRow("class", "public")] [DataRow("class", "internal")] [DataRow("record", "public")] @@ -44,7 +46,7 @@ public Task TestMethod() generatorResult.AssertSuccessfulGeneration(); generatorResult.GeneratedTrees.Should().HaveCount(3); - SourceText myTypeSource = await generatorResult.RunResult.GeneratedTrees[0].GetTextAsync(); + SourceText myTypeSource = await generatorResult.RunResult.GeneratedTrees[0].GetTextAsync(TestContext.CancellationTokenSource.Token); myTypeSource.Should().ContainSourceCode(""" public static readonly MSTF::TestNode TestNode = new MSTF::TestNode { @@ -89,7 +91,7 @@ public Task TestMethod() }; """); - SourceText rootSource = await generatorResult.RunResult.GeneratedTrees[1].GetTextAsync(); + SourceText rootSource = await generatorResult.RunResult.GeneratedTrees[1].GetTextAsync(TestContext.CancellationTokenSource.Token); rootSource.Should().ContainSourceCode(""" MSTF::TestNode root = new MSTF::TestNode { @@ -223,7 +225,7 @@ public Task TestMethod() generatorResult.AssertSuccessfulGeneration(); generatorResult.GeneratedTrees.Should().HaveCount(3); - SourceText myTypeSource = await generatorResult.RunResult.GeneratedTrees[0].GetTextAsync(); + SourceText myTypeSource = await generatorResult.RunResult.GeneratedTrees[0].GetTextAsync(TestContext.CancellationTokenSource.Token); myTypeSource.Should().ContainSourceCode(""" public static readonly MSTF::TestNode TestNode = new MSTF::TestNode { @@ -330,7 +332,7 @@ public Task TestMethod() generatorResult.AssertSuccessfulGeneration(); generatorResult.GeneratedTrees.Should().HaveCount(4); - SourceText myBaseClassSource = await generatorResult.GeneratedTrees[0].GetTextAsync(); + SourceText myBaseClassSource = await generatorResult.GeneratedTrees[0].GetTextAsync(TestContext.CancellationTokenSource.Token); myBaseClassSource.Should().ContainSourceCode(""" public static readonly MSTF::TestNode TestNode = new MSTF::TestNode { @@ -375,7 +377,7 @@ public Task TestMethod() }; """); - SourceText myTypeSource = await generatorResult.GeneratedTrees[1].GetTextAsync(); + SourceText myTypeSource = await generatorResult.GeneratedTrees[1].GetTextAsync(TestContext.CancellationTokenSource.Token); myTypeSource.Should().ContainSourceCode(""" public static readonly MSTF::TestNode TestNode = new MSTF::TestNode { @@ -488,7 +490,7 @@ public Task TestMethod() generatorResult.AssertSuccessfulGeneration(); generatorResult.RunResult.GeneratedTrees.Should().HaveCount(3); - SourceText testClass = await generatorResult.GeneratedTrees[0].GetTextAsync(); + SourceText testClass = await generatorResult.GeneratedTrees[0].GetTextAsync(TestContext.CancellationTokenSource.Token); testClass.Should().ContainSourceCode( "public static readonly MSTF::TestNode TestNode = new MSTF::TestNode", @@ -533,7 +535,7 @@ public Task TestMethod2() SyntaxTree? testClassTree = generatorResult.GeneratedTrees.FirstOrDefault(r => r.FilePath.EndsWith("TestSubClass.g.cs", StringComparison.OrdinalIgnoreCase)); testClassTree.Should().NotBeNull(); - SourceText testClass = await testClassTree!.GetTextAsync(); + SourceText testClass = await testClassTree!.GetTextAsync(TestContext.CancellationTokenSource.Token); testClass.Should().ContainSourceCode(""" new MSTF::InternalUnsafeAsyncActionTestNode { @@ -589,7 +591,7 @@ public Task TestMethod() generatorResult.AssertSuccessfulGeneration(); generatorResult.RunResult.GeneratedTrees.Should().HaveCount(3); - SourceText myTypeSource = await generatorResult.GeneratedTrees[0].GetTextAsync(); + SourceText myTypeSource = await generatorResult.GeneratedTrees[0].GetTextAsync(TestContext.CancellationTokenSource.Token); myTypeSource.Should().ContainSourceCode(""" public static readonly MSTF::TestNode TestNode = new MSTF::TestNode { @@ -601,7 +603,7 @@ public Task TestMethod() }, """); - SourceText rootSource = await generatorResult.GeneratedTrees[1].GetTextAsync(); + SourceText rootSource = await generatorResult.GeneratedTrees[1].GetTextAsync(TestContext.CancellationTokenSource.Token); rootSource.Should().ContainSourceCode(""" MSTF::TestNode root = new MSTF::TestNode { @@ -666,7 +668,7 @@ public Task TestMethod() generatorResult.AssertSuccessfulGeneration(); generatorResult.GeneratedTrees.Should().HaveCount(4); - SourceText rootSource = await generatorResult.RunResult.GeneratedTrees[2].GetTextAsync(); + SourceText rootSource = await generatorResult.RunResult.GeneratedTrees[2].GetTextAsync(TestContext.CancellationTokenSource.Token); rootSource.Should().ContainSourceCode(""" ColGen::List namespace1Tests = new(); namespace1Tests.Add(MyNamespace_MyType1.TestNode); @@ -728,7 +730,7 @@ public Task InitializeAsync(InitializationContext context) generatorResult.AssertSuccessfulGeneration(); generatorResult.GeneratedTrees.Should().HaveCount(2); - SourceText myTypeSource = await generatorResult.RunResult.GeneratedTrees[0].GetTextAsync(); + SourceText myTypeSource = await generatorResult.RunResult.GeneratedTrees[0].GetTextAsync(TestContext.CancellationTokenSource.Token); // The test node for the type should not have a test node for the InitializeAsync method. myTypeSource.Should().NotContain("StableUid = \"TestAssembly.MyNamespace.MyType.InitializeAsync\""); @@ -786,7 +788,7 @@ public Task CleanupAsync(CleanupContext context) generatorResult.AssertSuccessfulGeneration(); generatorResult.GeneratedTrees.Should().HaveCount(2); - SourceText myTypeSource = await generatorResult.RunResult.GeneratedTrees[0].GetTextAsync(); + SourceText myTypeSource = await generatorResult.RunResult.GeneratedTrees[0].GetTextAsync(TestContext.CancellationTokenSource.Token); // The test node for the type should not have a test node for the CleanupAsync method. myTypeSource.Should().NotContain("StableUid = \"TestAssembly.MyNamespace.MyType.CleanupAsync\""); @@ -851,7 +853,7 @@ public void Dispose() generatorResult.AssertSuccessfulGeneration(); generatorResult.GeneratedTrees.Should().HaveCount(2); - SourceText myTypeSource = await generatorResult.RunResult.GeneratedTrees[0].GetTextAsync(); + SourceText myTypeSource = await generatorResult.RunResult.GeneratedTrees[0].GetTextAsync(TestContext.CancellationTokenSource.Token); // The test node for the type should not have a test node for the Dispose method. myTypeSource.Should().NotContain("StableUid = \"TestAssembly.MyNamespace.MyType.Dispose\""); @@ -909,7 +911,7 @@ public ValueTask DisposeAsync() generatorResult.AssertSuccessfulGeneration(); generatorResult.GeneratedTrees.Should().HaveCount(2); - SourceText myTypeSource = await generatorResult.RunResult.GeneratedTrees[0].GetTextAsync(); + SourceText myTypeSource = await generatorResult.RunResult.GeneratedTrees[0].GetTextAsync(TestContext.CancellationTokenSource.Token); // The test node for the type should not have a test node for the DisposeAsync method. myTypeSource.Should().NotContain("StableUid = \"TestAssembly.MyNamespace.MyType.DisposeAsync\""); @@ -971,7 +973,7 @@ public void Dispose() generatorResult.AssertSuccessfulGeneration(); generatorResult.GeneratedTrees.Should().HaveCount(2); - SourceText myTypeSource = await generatorResult.RunResult.GeneratedTrees[0].GetTextAsync(); + SourceText myTypeSource = await generatorResult.RunResult.GeneratedTrees[0].GetTextAsync(TestContext.CancellationTokenSource.Token); // The body of the test node for the method should call only DisposeAsync after calling the test method. myTypeSource.Should().ContainSourceCode(""" @@ -1046,21 +1048,21 @@ public Task CleanupAsync(CleanupContext context) generatorResult.AssertSuccessfulGeneration(); generatorResult.GeneratedTrees.Should().HaveCount(4); - SourceText myClass1Source = await generatorResult.RunResult.GeneratedTrees[0].GetTextAsync(); + SourceText myClass1Source = await generatorResult.RunResult.GeneratedTrees[0].GetTextAsync(TestContext.CancellationTokenSource.Token); myClass1Source.Should().ContainSourceCode(""" new MSTF::InternalUnsafeAsyncActionTestNode { StableUid = "TestAssembly.MyNamespace.MyClass1.TestMethod()", """); - SourceText myClass2Source = await generatorResult.RunResult.GeneratedTrees[1].GetTextAsync(); + SourceText myClass2Source = await generatorResult.RunResult.GeneratedTrees[1].GetTextAsync(TestContext.CancellationTokenSource.Token); myClass2Source.Should().ContainSourceCode(""" new MSTF::InternalUnsafeAsyncActionTestNode { StableUid = "TestAssembly.MyNamespace.MyClass2.TestMethod()", """); - SourceText myClass3Source = await generatorResult.RunResult.GeneratedTrees[2].GetTextAsync(); + SourceText myClass3Source = await generatorResult.RunResult.GeneratedTrees[2].GetTextAsync(TestContext.CancellationTokenSource.Token); myClass3Source.Should().ContainSourceCode(""" new MSTF::InternalUnsafeAsyncActionTestNode { @@ -1116,7 +1118,7 @@ public Task TestMethod4() generatorResult.AssertFailedGeneration("*error CS0619: 'MyType.TestMethod4()' is obsolete*"); generatorResult.GeneratedTrees.Should().HaveCount(3); - SourceText myTypeSource = await generatorResult.RunResult.GeneratedTrees[0].GetTextAsync(); + SourceText myTypeSource = await generatorResult.RunResult.GeneratedTrees[0].GetTextAsync(TestContext.CancellationTokenSource.Token); myTypeSource.Should().ContainSourceCode(""" #pragma warning disable CS0612 // Type or member is obsolete await instance.TestMethod1(); @@ -1200,7 +1202,7 @@ public Task TestMethod2() generatorResult.AssertSuccessfulGeneration(); generatorResult.GeneratedTrees.Should().HaveCount(3); - SourceText myTypeSource = await generatorResult.RunResult.GeneratedTrees[0].GetTextAsync(); + SourceText myTypeSource = await generatorResult.RunResult.GeneratedTrees[0].GetTextAsync(TestContext.CancellationTokenSource.Token); myTypeSource.Should().ContainSourceCode(""" public static class MyNamespace_MyType { diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Helpers/CountDownEventTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Helpers/CountDownEventTests.cs index ee938ad28a..5659911c9d 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Helpers/CountDownEventTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Helpers/CountDownEventTests.cs @@ -8,6 +8,8 @@ namespace Microsoft.Testing.Platform.UnitTests; [TestClass] public sealed class CountDownEventTests { + public TestContext TestContext { get; set; } + [TestMethod] public async Task CountDownEvent_WaitAsync_Succeeded() { @@ -15,11 +17,11 @@ public async Task CountDownEvent_WaitAsync_Succeeded() Task waiter1 = Task.Run(() => countdownEvent.WaitAsync(CancellationToken.None)); Task waiter2 = Task.Run(() => countdownEvent.WaitAsync(CancellationToken.None)); - await Task.Delay(500); + await Task.Delay(500, TestContext.CancellationTokenSource.Token); countdownEvent.Signal(); - await Task.Delay(500); + await Task.Delay(500, TestContext.CancellationTokenSource.Token); countdownEvent.Signal(); - await Task.Delay(500); + await Task.Delay(500, TestContext.CancellationTokenSource.Token); countdownEvent.Signal(); await waiter1.TimeoutAfterAsync(TimeSpan.FromSeconds(30)); diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Helpers/SystemAsyncMonitorTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Helpers/SystemAsyncMonitorTests.cs index 9a781e1922..966a695bb3 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Helpers/SystemAsyncMonitorTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Helpers/SystemAsyncMonitorTests.cs @@ -8,6 +8,8 @@ namespace Microsoft.Testing.Platform.UnitTests; [TestClass] public sealed class SystemAsyncMonitorTests { + public TestContext TestContext { get; set; } + [TestMethod] public async Task AsyncMonitor_ShouldCorrectlyLock() { @@ -17,7 +19,7 @@ public async Task AsyncMonitor_ShouldCorrectlyLock() var stopwatch = Stopwatch.StartNew(); for (int i = 0; i < 3; i++) { - tasks.Add(Task.Run(TestLock)); + tasks.Add(Task.Run(TestLock, TestContext.CancellationTokenSource.Token)); } await Task.WhenAll([.. tasks]); @@ -37,7 +39,7 @@ async Task TestLock() } lockState = true; - await Task.Delay(1000); + await Task.Delay(1000, TestContext.CancellationTokenSource.Token); lockState = false; } } diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Helpers/TaskExtensionsTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Helpers/TaskExtensionsTests.cs index 6712aef3f0..cc51318fd9 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Helpers/TaskExtensionsTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Helpers/TaskExtensionsTests.cs @@ -8,22 +8,24 @@ namespace Microsoft.Testing.Platform.UnitTests; [TestClass] public sealed class TaskExtensionsTests { + public TestContext TestContext { get; set; } + [TestMethod] public async Task TimeoutAfterAsync_Succeeds() => await Assert.ThrowsAsync(async () => - await Task.Delay(TimeSpan.FromSeconds(60)).TimeoutAfterAsync(TimeSpan.FromSeconds(2))); + await Task.Delay(TimeSpan.FromSeconds(60), TestContext.CancellationTokenSource.Token).TimeoutAfterAsync(TimeSpan.FromSeconds(2))); [TestMethod] public async Task TimeoutAfterAsync_CancellationToken_Succeeds() => await Assert.ThrowsAsync(async () => - await Task.Delay(TimeSpan.FromSeconds(60)).TimeoutAfterAsync( + await Task.Delay(TimeSpan.FromSeconds(60), TestContext.CancellationTokenSource.Token).TimeoutAfterAsync( TimeSpan.FromSeconds(30), new CancellationTokenSource(TimeSpan.FromSeconds(2)).Token)); [TestMethod] public async Task TimeoutAfterAsync_CancellationTokenNone_Succeeds() => await Assert.ThrowsAsync(async () => - await Task.Delay(TimeSpan.FromSeconds(60)).TimeoutAfterAsync( + await Task.Delay(TimeSpan.FromSeconds(60), TestContext.CancellationTokenSource.Token).TimeoutAfterAsync( TimeSpan.FromSeconds(2), CancellationToken.None)); @@ -75,15 +77,16 @@ public async Task CancellationAsync_ObserveException_Succeeds() { ManualResetEvent waitException = new(false); await Assert.ThrowsAsync(async () - => await Task.Run(async () => - { - await Task.Delay(TimeSpan.FromSeconds(10)); - waitException.Set(); - throw new InvalidOperationException(); - }).WithCancellationAsync(new CancellationTokenSource(TimeSpan.FromSeconds(1)).Token)); + => await Task.Run( + async () => + { + await Task.Delay(TimeSpan.FromSeconds(10), TestContext.CancellationTokenSource.Token); + waitException.Set(); + throw new InvalidOperationException(); + }, TestContext.CancellationTokenSource.Token).WithCancellationAsync(new CancellationTokenSource(TimeSpan.FromSeconds(1)).Token)); waitException.WaitOne(); - await Task.Delay(TimeSpan.FromSeconds(4)); + await Task.Delay(TimeSpan.FromSeconds(4), TestContext.CancellationTokenSource.Token); }, 3, TimeSpan.FromSeconds(3)); [TestMethod] @@ -95,7 +98,7 @@ public async Task CancellationAsyncWithReturnValue_ObserveException_Succeeds() await Assert.ThrowsAsync(async () => await Task.Run(async () => { - await Task.Delay(TimeSpan.FromSeconds(10)); + await Task.Delay(TimeSpan.FromSeconds(10), TestContext.CancellationTokenSource.Token); try { return 2; @@ -110,7 +113,7 @@ await Assert.ThrowsAsync(async () }).WithCancellationAsync(new CancellationTokenSource(TimeSpan.FromSeconds(1)).Token)); waitException.WaitOne(); - await Task.Delay(TimeSpan.FromSeconds(4)); + await Task.Delay(TimeSpan.FromSeconds(4), TestContext.CancellationTokenSource.Token); }, 3, TimeSpan.FromSeconds(3)); private static async Task DoSomething() diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/IPCTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/IPCTests.cs index 14c03ca924..b8025f25bd 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/IPCTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/IPCTests.cs @@ -28,34 +28,35 @@ public async Task SingleConnectionNamedPipeServer_MultipleConnection_Fails() List exceptions = []; ManualResetEventSlim waitException = new(false); - var waitTask = Task.Run(async () => - { - try + var waitTask = Task.Run( + async () => { - while (true) + try { - NamedPipeServer singleConnectionNamedPipeServer = new( - pipeNameDescription, - async _ => await Task.FromResult(VoidResponse.CachedInstance), - new SystemEnvironment(), - new Mock().Object, - new SystemTask(), - _testContext.CancellationTokenSource.Token); - - await singleConnectionNamedPipeServer.WaitConnectionAsync(_testContext.CancellationTokenSource.Token); - openedPipe.Add(singleConnectionNamedPipeServer); + while (true) + { + NamedPipeServer singleConnectionNamedPipeServer = new( + pipeNameDescription, + async _ => await Task.FromResult(VoidResponse.CachedInstance), + new SystemEnvironment(), + new Mock().Object, + new SystemTask(), + _testContext.CancellationTokenSource.Token); + + await singleConnectionNamedPipeServer.WaitConnectionAsync(_testContext.CancellationTokenSource.Token); + openedPipe.Add(singleConnectionNamedPipeServer); + } } - } - catch (Exception ex) - { - exceptions.Add(ex); - waitException.Set(); - } - }); + catch (Exception ex) + { + exceptions.Add(ex); + waitException.Set(); + } + }, _testContext.CancellationTokenSource.Token); NamedPipeClient namedPipeClient1 = new(pipeNameDescription.Name); await namedPipeClient1.ConnectAsync(_testContext.CancellationTokenSource.Token); - waitException.Wait(); + waitException.Wait(_testContext.CancellationTokenSource.Token); Assert.HasCount(1, openedPipe); Assert.HasCount(1, exceptions); @@ -95,29 +96,30 @@ public async Task SingleConnectionNamedPipeServer_RequestReplySerialization_Succ namedPipeClient.RegisterSerializer(new LongMessageSerializer(), typeof(LongMessage)); ManualResetEventSlim manualResetEventSlim = new(false); - var clientConnected = Task.Run(async () => - { - while (true) + var clientConnected = Task.Run( + async () => { - try - { - await namedPipeClient.ConnectAsync(CancellationToken.None); - manualResetEventSlim.Set(); - break; - } - catch (OperationCanceledException ct) when (ct.CancellationToken == _testContext.CancellationTokenSource.Token) - { - throw new OperationCanceledException("SingleConnectionNamedPipeServer_RequestReplySerialization_Succeeded cancellation during connect, testContext.CancellationTokenSource.Token"); - } - catch (OperationCanceledException) - { - throw new OperationCanceledException("SingleConnectionNamedPipeServer_RequestReplySerialization_Succeeded cancellation during connect"); - } - catch (Exception) + while (true) { + try + { + await namedPipeClient.ConnectAsync(CancellationToken.None); + manualResetEventSlim.Set(); + break; + } + catch (OperationCanceledException ct) when (ct.CancellationToken == _testContext.CancellationTokenSource.Token) + { + throw new OperationCanceledException("SingleConnectionNamedPipeServer_RequestReplySerialization_Succeeded cancellation during connect, testContext.CancellationTokenSource.Token"); + } + catch (OperationCanceledException) + { + throw new OperationCanceledException("SingleConnectionNamedPipeServer_RequestReplySerialization_Succeeded cancellation during connect"); + } + catch (Exception) + { + } } - } - }); + }, _testContext.CancellationTokenSource.Token); NamedPipeServer singleConnectionNamedPipeServer = new( pipeNameDescription, request => @@ -134,7 +136,7 @@ public async Task SingleConnectionNamedPipeServer_RequestReplySerialization_Succ singleConnectionNamedPipeServer.RegisterSerializer(new IntMessageSerializer(), typeof(IntMessage)); singleConnectionNamedPipeServer.RegisterSerializer(new LongMessageSerializer(), typeof(LongMessage)); await singleConnectionNamedPipeServer.WaitConnectionAsync(CancellationToken.None); - manualResetEventSlim.Wait(); + manualResetEventSlim.Wait(_testContext.CancellationTokenSource.Token); await clientConnected.WithCancellationAsync(CancellationToken.None); @@ -200,11 +202,12 @@ public async Task ConnectionNamedPipeServer_MultipleConnection_Succeeds() int connectionCompleted = 0; foreach (NamedPipeServer namedPipeServer in pipes) { - waitConnectionTask.Add(Task.Run(async () => - { - await namedPipeServer.WaitConnectionAsync(_testContext.CancellationTokenSource.Token); - Interlocked.Increment(ref connectionCompleted); - })); + waitConnectionTask.Add(Task.Run( + async () => + { + await namedPipeServer.WaitConnectionAsync(_testContext.CancellationTokenSource.Token); + Interlocked.Increment(ref connectionCompleted); + }, _testContext.CancellationTokenSource.Token)); } List connectedClients = []; diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Logging/FileLoggerTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Logging/FileLoggerTests.cs index 1919fe223a..fce8ad8527 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Logging/FileLoggerTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Logging/FileLoggerTests.cs @@ -11,6 +11,9 @@ namespace Microsoft.Testing.Platform.UnitTests; [TestClass] public sealed class FileLoggerTests : IDisposable { + // https://github.com/microsoft/testfx/issues/6136 + public TestContext TestContext { get; set; } = null!; + private const string LogFolder = "aaa"; private const string LogPrefix = "bbb"; private const string FileName = "ccc"; @@ -173,15 +176,15 @@ public async Task Log_WhenSyncFlush_StreamWriterIsCalledOnlyWhenLogLevelAllowsIt if (LogTestHelpers.IsLogEnabled(defaultLogLevel, currentLogLevel)) { - await _memoryStream.FlushAsync(); + await _memoryStream.FlushAsync(TestContext.CancellationTokenSource.Token); int iteration = 0; while (_memoryStream.Length == 0 && iteration < 10) { iteration++; - await Task.Delay(200); + await Task.Delay(200, TestContext.CancellationTokenSource.Token); } - await _memoryStream.FlushAsync(); + await _memoryStream.FlushAsync(TestContext.CancellationTokenSource.Token); _mockConsole.Verify(x => x.WriteLine(It.IsAny()), Times.Never); Assert.AreEqual($"[00:00:00.000 Test - {currentLogLevel}] Message{Environment.NewLine}", Encoding.Default.GetString(_memoryStream.ToArray())); diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Messages/AsynchronousMessageBusTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Messages/AsynchronousMessageBusTests.cs index 1ead95cd3d..afcbfd4392 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Messages/AsynchronousMessageBusTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Messages/AsynchronousMessageBusTests.cs @@ -13,6 +13,8 @@ namespace Microsoft.Testing.Platform.UnitTests; [TestClass] public sealed class AsynchronousMessageBusTests { + public TestContext TestContext { get; set; } + [TestMethod] public async Task UnexpectedTypePublished_ShouldFail() { @@ -105,7 +107,7 @@ public async Task Consumers_ConsumeData_ShouldNotMissAnyPayload() Random random = new(); for (int i = 0; i < totalConsumers; i++) { - DummyConsumer dummyConsumer = new(async _ => await Task.Delay(random.Next(40, 80))); + DummyConsumer dummyConsumer = new(async _ => await Task.Delay(random.Next(40, 80), TestContext.CancellationTokenSource.Token)); dummyConsumers.Add(dummyConsumer); } @@ -120,7 +122,7 @@ public async Task Consumers_ConsumeData_ShouldNotMissAnyPayload() proxy.SetBuiltMessageBus(asynchronousMessageBus); DummyConsumer.DummyProducer producer = new(); - await Task.WhenAll([.. Enumerable.Range(1, totalPayloads).Select(i => Task.Run(async () => await proxy.PublishAsync(producer, new DummyConsumer.DummyData { Data = i })))]); + await Task.WhenAll([.. Enumerable.Range(1, totalPayloads).Select(i => Task.Run(async () => await proxy.PublishAsync(producer, new DummyConsumer.DummyData { Data = i }), TestContext.CancellationTokenSource.Token))]); await proxy.DrainDataAsync(); From 952a52b7d8cfd17d2b435e2bd3ca53f0b5a87db3 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Wed, 23 Jul 2025 21:18:06 +0200 Subject: [PATCH 278/541] Fix nullability suppressor for TestContext when explicit constructor is declared (#6139) --- ...llableReferenceNotInitializedSuppressor.cs | 17 +++- ...eReferenceNotInitializedSuppressorTests.cs | 89 ++++++++----------- 2 files changed, 51 insertions(+), 55 deletions(-) diff --git a/src/Analyzers/MSTest.Analyzers/NonNullableReferenceNotInitializedSuppressor.cs b/src/Analyzers/MSTest.Analyzers/NonNullableReferenceNotInitializedSuppressor.cs index ccb701e511..0b866fc77a 100644 --- a/src/Analyzers/MSTest.Analyzers/NonNullableReferenceNotInitializedSuppressor.cs +++ b/src/Analyzers/MSTest.Analyzers/NonNullableReferenceNotInitializedSuppressor.cs @@ -41,19 +41,28 @@ public override void ReportSuppressions(SuppressionAnalysisContext context) foreach (Diagnostic diagnostic in context.ReportedDiagnostics) { - // The diagnostic is reported on the test method - if (diagnostic.Location.SourceTree is not { } tree) + // The main diagnostic location isn't always pointing to the TestContext property. + // It can point to the constructor. + // The additional locations will have the right thing. + // See https://github.com/dotnet/roslyn/issues/79188#issuecomment-3017087900. + // It was an intentional design to include the additional locations specifically for DiagnosticSuppressor scenarios. + // So it is safe to use AdditionalLocations here. We are not relying on an implementation detail here. + // However, we still fallback to diagnostic.Location just in case Roslyn regresses the AdditionalLocations behavior. + // Such regression happened in the past in Roslyn. + // See https://github.com/dotnet/roslyn/issues/66037 + Location location = diagnostic.AdditionalLocations.Count >= 1 ? diagnostic.AdditionalLocations[0] : diagnostic.Location; + if (location.SourceTree is not { } tree) { continue; } SyntaxNode root = tree.GetRoot(context.CancellationToken); - SyntaxNode node = root.FindNode(diagnostic.Location.SourceSpan, getInnermostNodeForTie: true); + SyntaxNode node = root.FindNode(location.SourceSpan, getInnermostNodeForTie: true); SemanticModel semanticModel = context.GetSemanticModel(tree); ISymbol? declaredSymbol = semanticModel.GetDeclaredSymbol(node, context.CancellationToken); if (declaredSymbol is IPropertySymbol property - && string.Equals(property.Name, "TestContext", StringComparison.OrdinalIgnoreCase) + && string.Equals(property.Name, "TestContext", StringComparison.Ordinal) && SymbolEqualityComparer.Default.Equals(testContextSymbol, property.GetMethod?.ReturnType) && property.ContainingType.GetAttributes().Any(attr => attr.AttributeClass.Inherits(testClassAttributeSymbol))) { diff --git a/test/UnitTests/MSTest.Analyzers.UnitTests/NonNullableReferenceNotInitializedSuppressorTests.cs b/test/UnitTests/MSTest.Analyzers.UnitTests/NonNullableReferenceNotInitializedSuppressorTests.cs index 7f553df797..7fb1ece97f 100644 --- a/test/UnitTests/MSTest.Analyzers.UnitTests/NonNullableReferenceNotInitializedSuppressorTests.cs +++ b/test/UnitTests/MSTest.Analyzers.UnitTests/NonNullableReferenceNotInitializedSuppressorTests.cs @@ -1,13 +1,10 @@ // 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.Immutable; - -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; +using Microsoft.CodeAnalysis.Testing; using VerifyCS = MSTest.Analyzers.Test.CSharpCodeFixVerifier< - MSTest.Analyzers.UnitTests.NonNullableReferenceNotInitializedSuppressorTests.DoNothingAnalyzer, + MSTest.Analyzers.NonNullableReferenceNotInitializedSuppressor, Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>; namespace MSTest.Analyzers.UnitTests; @@ -27,20 +24,11 @@ public async Task TestContextPropertyOnTestClass_DiagnosticIsSuppressed() [TestClass] public class SomeClass { - public TestContext [|TestContext|] { get; set; } + public TestContext {|#0:TestContext|} { get; set; } } "; - // Verify issues are reported - await new VerifyCS.Test - { - TestState = { Sources = { code } }, - }.RunAsync(); - - await new TestWithSuppressor - { - TestState = { Sources = { code } }, - }.RunAsync(); + await VerifySingleSuppressionAsync(code, isSuppressed: true); } [TestMethod] @@ -54,56 +42,55 @@ public async Task TestContextPropertyOnNonTestClass_DiagnosticIsNotSuppressed() public class SomeClass { - public TestContext [|TestContext|] { get; set; } + public TestContext {|#0:TestContext|} { get; set; } } "; - // Verify issues are reported - await new VerifyCS.Test - { - TestState = { Sources = { code } }, - }.RunAsync(); - - await new TestWithSuppressor - { - TestState = { Sources = { code } }, - }.RunAsync(); + await VerifySingleSuppressionAsync(code, isSuppressed: false); } - [DiagnosticAnalyzer(LanguageNames.CSharp)] - [SuppressMessage("MicrosoftCodeAnalysisCorrectness", "RS1038:Compiler extensions should be implemented in assemblies with compiler-provided references", Justification = "For suppression test only.")] - [SuppressMessage("MicrosoftCodeAnalysisCorrectness", "RS1036:Specify analyzer banned API enforcement setting", Justification = "For suppression test only.")] - [SuppressMessage("MicrosoftCodeAnalysisCorrectness", "RS1041:Compiler extensions should be implemented in assemblies targeting netstandard2.0", Justification = "For suppression test only.")] - public class DoNothingAnalyzer : DiagnosticAnalyzer + [TestMethod] + public async Task TestContextPropertyOnTestClassConstructor_DiagnosticIsSuppressed() { - [SuppressMessage("MicrosoftCodeAnalysisDesign", "RS1017:DiagnosticId for analyzers must be a non-null constant.", Justification = "For suppression test only.")] - public static readonly DiagnosticDescriptor Rule = new(NonNullableReferenceNotInitializedSuppressor.Rule.SuppressedDiagnosticId, "Title", "Message", "Category", DiagnosticSeverity.Warning, isEnabledByDefault: true); + string code = @" +#nullable enable - public override ImmutableArray SupportedDiagnostics => [Rule]; +using System.Threading.Tasks; +using Microsoft.VisualStudio.TestTools.UnitTesting; - public override void Initialize(AnalysisContext context) - { - context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); - context.EnableConcurrentExecution(); +[TestClass] +public class SomeClass +{ + public {|#0:SomeClass|}() + { + } - context.RegisterSymbolAction(AnalyzeSymbol, SymbolKind.Property); - } + public TestContext TestContext { get; set; } +} +"; - private void AnalyzeSymbol(SymbolAnalysisContext context) - { - } + await VerifySingleSuppressionAsync(code, isSuppressed: true); } - internal sealed class TestWithSuppressor : VerifyCS.Test + private Task VerifySingleSuppressionAsync(string source, bool isSuppressed) + => VerifyDiagnosticsAsync(source, [(0, isSuppressed)]); + + private async Task VerifyDiagnosticsAsync(string source, List<(int Location, bool IsSuppressed)> diagnostics) { - protected override IEnumerable GetDiagnosticAnalyzers() + var test = new VerifyCS.Test { - foreach (DiagnosticAnalyzer analyzer in base.GetDiagnosticAnalyzers()) - { - yield return analyzer; - } + TestCode = source, + }; - yield return new NonNullableReferenceNotInitializedSuppressor(); + foreach ((int location, bool isSuppressed) in diagnostics) + { + test.ExpectedDiagnostics.Add(DiagnosticResult.CompilerError("CS8618") + .WithLocation(location) + .WithOptions(DiagnosticOptions.IgnoreAdditionalLocations) + .WithArguments("property", "TestContext") + .WithIsSuppressed(isSuppressed)); } + + await test.RunAsync(); } } From b8cd6bf61bf265a8fd4b758abde4a83da120638d Mon Sep 17 00:00:00 2001 From: dotnet bot Date: Wed, 23 Jul 2025 21:32:01 +0200 Subject: [PATCH 279/541] Localized file check-in by OneLocBuild Task: Build definition ID 1218: Build ID 2756566 --- src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf | 6 +++--- src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf | 6 +++--- src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf | 6 +++--- src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf | 6 +++--- src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf | 6 +++--- src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf | 6 +++--- src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf | 6 +++--- 7 files changed, 21 insertions(+), 21 deletions(-) diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf index c3ed9f7c60..39f3ae05bc 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf @@ -886,17 +886,17 @@ Typ deklarující tyto metody by měl také respektovat následující pravidla: TestContext property cannot be accessed in this context - TestContext property cannot be accessed in this context + Vlastnost TestContext není v tomto kontextu přístupná TestContext property '{0}' cannot be accessed in '{1}' method - TestContext property '{0}' cannot be accessed in '{1}' method + Vlastnost TestContext {0} není přístupná v metodě {1} Some TestContext properties are only available during test execution and cannot be accessed in assembly initialize, class initialize, class cleanup, or assembly cleanup methods. - Some TestContext properties are only available during test execution and cannot be accessed in assembly initialize, class initialize, class cleanup, or assembly cleanup methods. + Některé vlastnosti TestContext jsou k dispozici pouze během provádění testu a nelze k nim přistupovat v metodách inicializace sestavení, inicializace třídy, vyčištění třídy nebo vyčištění sestavení. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf index 35098fc7b0..a6734a9f4b 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf @@ -886,17 +886,17 @@ El tipo que declara estos métodos también debe respetar las reglas siguientes: TestContext property cannot be accessed in this context - TestContext property cannot be accessed in this context + No se puede tener acceso a la propiedad TestContext en este contexto TestContext property '{0}' cannot be accessed in '{1}' method - TestContext property '{0}' cannot be accessed in '{1}' method + No se puede tener acceso a la propiedad TestContext "{0}" en el método "{1}" Some TestContext properties are only available during test execution and cannot be accessed in assembly initialize, class initialize, class cleanup, or assembly cleanup methods. - Some TestContext properties are only available during test execution and cannot be accessed in assembly initialize, class initialize, class cleanup, or assembly cleanup methods. + Algunas propiedades de TestContext solo están disponibles durante la ejecución de la prueba y no se puede acceder a ellas en los métodos assembly initialize, class initialize, class cleanup o assembly cleanup. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf index 6b526b9e70..3faca25111 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf @@ -886,17 +886,17 @@ Le type doit être une classe TestContext property cannot be accessed in this context - TestContext property cannot be accessed in this context + Impossible d’accéder à la propriété TestContext dans ce contexte TestContext property '{0}' cannot be accessed in '{1}' method - TestContext property '{0}' cannot be accessed in '{1}' method + Impossible d’accéder à la propriété TestContext « {0} » dans la méthode « {1} » Some TestContext properties are only available during test execution and cannot be accessed in assembly initialize, class initialize, class cleanup, or assembly cleanup methods. - Some TestContext properties are only available during test execution and cannot be accessed in assembly initialize, class initialize, class cleanup, or assembly cleanup methods. + Certaines propriétés TestContext sont disponibles uniquement pendant l’exécution du test et ne sont pas accessibles dans les méthodes d’initialisation d’assembly, d’initialisation de classe, de nettoyage de classe ou de nettoyage d’assembly. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf index ad6f304f11..d72c9512ca 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf @@ -886,17 +886,17 @@ Anche il tipo che dichiara questi metodi deve rispettare le regole seguenti: TestContext property cannot be accessed in this context - TestContext property cannot be accessed in this context + Non è possibile accedere alla proprietà TestContext in questo contesto TestContext property '{0}' cannot be accessed in '{1}' method - TestContext property '{0}' cannot be accessed in '{1}' method + Non è possibile accedere alla proprietà TestContext '{0}' nel metodo '{1}' Some TestContext properties are only available during test execution and cannot be accessed in assembly initialize, class initialize, class cleanup, or assembly cleanup methods. - Some TestContext properties are only available during test execution and cannot be accessed in assembly initialize, class initialize, class cleanup, or assembly cleanup methods. + Alcune proprietà TestContext sono disponibili solo durante l'esecuzione dei test e non è possibile accedervi nei metodi di inizializzazione degli assembly, inizializzazione delle classi, pulizia delle classi o pulizia degli assembly. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf index c1b7d5cf9b..f218e8c841 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf @@ -886,17 +886,17 @@ The type declaring these methods should also respect the following rules: TestContext property cannot be accessed in this context - TestContext property cannot be accessed in this context + このコンテキストでは TestContext プロパティにアクセスできません TestContext property '{0}' cannot be accessed in '{1}' method - TestContext property '{0}' cannot be accessed in '{1}' method + TestContext プロパティ '{0}' に '{1}' メソッドでアクセスできません Some TestContext properties are only available during test execution and cannot be accessed in assembly initialize, class initialize, class cleanup, or assembly cleanup methods. - Some TestContext properties are only available during test execution and cannot be accessed in assembly initialize, class initialize, class cleanup, or assembly cleanup methods. + TestContext プロパティの一部はテストの実行中にのみ使用でき、assenbly initialize、class initialize、class cleanup、または assembly cleanup メソッドではアクセスできません。 diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf index be96e0afa4..1541ee5e1c 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf @@ -886,17 +886,17 @@ The type declaring these methods should also respect the following rules: TestContext property cannot be accessed in this context - TestContext property cannot be accessed in this context + 이 컨텍스트에서 TestContext 속성에 액세스할 수 없습니다. TestContext property '{0}' cannot be accessed in '{1}' method - TestContext property '{0}' cannot be accessed in '{1}' method + '{1}' 메서드에서 TestContext 속성 '{0}'에 액세스할 수 없습니다. Some TestContext properties are only available during test execution and cannot be accessed in assembly initialize, class initialize, class cleanup, or assembly cleanup methods. - Some TestContext properties are only available during test execution and cannot be accessed in assembly initialize, class initialize, class cleanup, or assembly cleanup methods. + 일부 TestContext 속성은 테스트 실행 중에만 사용할 수 있으며, 어셈블리 초기화, 클래스 초기화, 클래스 정리 또는 어셈블리 정리 메서드에서는 액세스할 수 없습니다. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf index 9ebf0918c9..d19aeb8037 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf @@ -886,17 +886,17 @@ O tipo que declara esses métodos também deve respeitar as seguintes regras: TestContext property cannot be accessed in this context - TestContext property cannot be accessed in this context + A propriedade TestContext não pode ser acessada neste contexto TestContext property '{0}' cannot be accessed in '{1}' method - TestContext property '{0}' cannot be accessed in '{1}' method + A propriedade "{0}" de TestContext não pode ser acessada no método "{1}" Some TestContext properties are only available during test execution and cannot be accessed in assembly initialize, class initialize, class cleanup, or assembly cleanup methods. - Some TestContext properties are only available during test execution and cannot be accessed in assembly initialize, class initialize, class cleanup, or assembly cleanup methods. + Algumas propriedades TestContext só estão disponíveis durante a execução do teste e não podem ser acessadas em métodos de inicialização de assembly, inicialização de classe, limpeza de classe ou limpeza de assembly. From 09650b0731799825f498d15baa673c6ae800f229 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Thu, 24 Jul 2025 05:23:14 +0200 Subject: [PATCH 280/541] Obsolete `TestTimeout` (#6144) --- .../TestFramework/Attributes/TestMethod/TestTimeout.cs | 5 +++++ .../TestFramework/Attributes/TestMethod/TimeoutAttribute.cs | 5 +++++ src/TestFramework/TestFramework/FrameworkConstants.cs | 1 + .../TestAssets/TimeoutTestProject/TimeoutTestClass.cs | 1 + 4 files changed, 12 insertions(+) diff --git a/src/TestFramework/TestFramework/Attributes/TestMethod/TestTimeout.cs b/src/TestFramework/TestFramework/Attributes/TestMethod/TestTimeout.cs index 3c5aab0c09..629d58628c 100644 --- a/src/TestFramework/TestFramework/Attributes/TestMethod/TestTimeout.cs +++ b/src/TestFramework/TestFramework/Attributes/TestMethod/TestTimeout.cs @@ -8,6 +8,11 @@ namespace Microsoft.VisualStudio.TestTools.UnitTesting; /// The type of the enumeration must match. /// [SuppressMessage("Microsoft.Design", "CA1008:EnumsShouldHaveZeroValue", Justification = "Compat reasons")] +#if NET6_0_OR_GREATER +[Obsolete(FrameworkConstants.TestTimeoutAttributeObsoleteMessage, error: false, DiagnosticId = "MSTESTOBS")] +#else +[Obsolete(FrameworkConstants.TestTimeoutAttributeObsoleteMessage, error: false)] +#endif public enum TestTimeout { /// diff --git a/src/TestFramework/TestFramework/Attributes/TestMethod/TimeoutAttribute.cs b/src/TestFramework/TestFramework/Attributes/TestMethod/TimeoutAttribute.cs index b57e1941b2..a23a6ba47e 100644 --- a/src/TestFramework/TestFramework/Attributes/TestMethod/TimeoutAttribute.cs +++ b/src/TestFramework/TestFramework/Attributes/TestMethod/TimeoutAttribute.cs @@ -23,6 +23,11 @@ public sealed class TimeoutAttribute : Attribute /// /// The timeout. /// +#if NET6_0_OR_GREATER + [Obsolete(FrameworkConstants.TestTimeoutAttributeObsoleteMessage, error: false, DiagnosticId = "MSTESTOBS")] +#else + [Obsolete(FrameworkConstants.TestTimeoutAttributeObsoleteMessage, error: false)] +#endif public TimeoutAttribute(TestTimeout timeout) => Timeout = (int)timeout; /// diff --git a/src/TestFramework/TestFramework/FrameworkConstants.cs b/src/TestFramework/TestFramework/FrameworkConstants.cs index 856f2f948c..f0bc8da76e 100644 --- a/src/TestFramework/TestFramework/FrameworkConstants.cs +++ b/src/TestFramework/TestFramework/FrameworkConstants.cs @@ -16,4 +16,5 @@ internal static class FrameworkConstants internal const string DoNotUseStringAssertReferenceEquals = "StringAssert.ReferenceEquals should not be used for Assertions. Please use StringAssert methods or Assert.AreSame & overloads instead."; internal const string DoNotUseCollectionAssertEquals = "CollectionAssert.Equals should not be used for Assertions. Please use CollectionAssert.AreEqual & overloads instead."; internal const string DoNotUseCollectionAssertReferenceEquals = "CollectionAssert.ReferenceEquals should not be used for Assertions. Please use CollectionAssert methods or Assert.AreSame & overloads instead."; + internal const string TestTimeoutAttributeObsoleteMessage = "The 'TestTimeout' attribute is obsolete and will be removed in v4. Consider removing the 'Timeout' attribute or use the 'Timeout' attribute with the 'int.MaxValue' for infinite timeout."; } diff --git a/test/IntegrationTests/TestAssets/TimeoutTestProject/TimeoutTestClass.cs b/test/IntegrationTests/TestAssets/TimeoutTestProject/TimeoutTestClass.cs index e2a9892a91..da1e4dcb05 100644 --- a/test/IntegrationTests/TestAssets/TimeoutTestProject/TimeoutTestClass.cs +++ b/test/IntegrationTests/TestAssets/TimeoutTestProject/TimeoutTestClass.cs @@ -5,6 +5,7 @@ namespace TimeoutTestProject; +#pragma warning disable CS0618 // Type or member is obsolete [TestClass] public class TimeoutTestClass { From 0831f5a26e35e1e9d909c92f8afd98a824d86688 Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Thu, 24 Jul 2025 03:35:14 +0000 Subject: [PATCH 281/541] [main] Update dependencies from dotnet/arcade (#6145) [main] Update dependencies from dotnet/arcade --- eng/Version.Details.xml | 12 +++--- eng/Versions.props | 2 +- eng/common/core-templates/job/job.yml | 2 + .../steps/install-microbuild.yml | 40 +++++++++++++++---- global.json | 2 +- 5 files changed, 43 insertions(+), 15 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index f9e81efd4f..993a5a53c2 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -1,17 +1,17 @@ - + https://github.com/dotnet/arcade - d777c20040bdc2e52b372fa98dcb84141ed692d3 + 2586309f3f8553152e2d1d54612e9199975f9cd4 - + https://github.com/dotnet/arcade - d777c20040bdc2e52b372fa98dcb84141ed692d3 + 2586309f3f8553152e2d1d54612e9199975f9cd4 - + https://github.com/dotnet/arcade - d777c20040bdc2e52b372fa98dcb84141ed692d3 + 2586309f3f8553152e2d1d54612e9199975f9cd4 https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage diff --git a/eng/Versions.props b/eng/Versions.props index a11f56d827..a98c005fcf 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -7,7 +7,7 @@ preview - 10.0.0-beta.25367.5 + 10.0.0-beta.25373.3 18.0.0-preview.25371.1 3.10.0-preview.25372.9 diff --git a/eng/common/core-templates/job/job.yml b/eng/common/core-templates/job/job.yml index 6badecba7b..d901325154 100644 --- a/eng/common/core-templates/job/job.yml +++ b/eng/common/core-templates/job/job.yml @@ -20,6 +20,7 @@ parameters: artifacts: '' enableMicrobuild: false enableMicrobuildForMacAndLinux: false + microbuildUseESRP: true enablePublishBuildArtifacts: false enablePublishBuildAssets: false enablePublishTestResults: false @@ -128,6 +129,7 @@ jobs: parameters: enableMicrobuild: ${{ parameters.enableMicrobuild }} enableMicrobuildForMacAndLinux: ${{ parameters.enableMicrobuildForMacAndLinux }} + microbuildUseESRP: ${{ parameters.microbuildUseESRP }} continueOnError: ${{ parameters.continueOnError }} - ${{ if and(eq(parameters.runAsPublic, 'false'), eq(variables['System.TeamProject'], 'internal')) }}: diff --git a/eng/common/core-templates/steps/install-microbuild.yml b/eng/common/core-templates/steps/install-microbuild.yml index f3064a7834..da30e67bc3 100644 --- a/eng/common/core-templates/steps/install-microbuild.yml +++ b/eng/common/core-templates/steps/install-microbuild.yml @@ -4,8 +4,16 @@ parameters: # Enable install tasks for MicroBuild on Mac and Linux # Will be ignored if 'enableMicrobuild' is false or 'Agent.Os' is 'Windows_NT' enableMicrobuildForMacAndLinux: false + # Determines whether the ESRP service connection information should be passed to the signing plugin. + # This overlaps with _SignType to some degree. We only need the service connection for real signing. + # It's important that the service connection not be passed to the MicroBuildSigningPlugin task in this place. + # Doing so will cause the service connection to be authorized for the pipeline, which isn't allowed and won't work for non-prod. + # Unfortunately, _SignType can't be used to exclude the use of the service connection in non-real sign scenarios. The + # variable is not available in template expression. _SignType has a very large proliferation across .NET, so replacing it is tough. + microbuildUseESRP: true # Location of the MicroBuild output folder microBuildOutputFolder: '$(Build.SourcesDirectory)' + continueOnError: false steps: @@ -21,19 +29,37 @@ steps: workingDirectory: ${{ parameters.microBuildOutputFolder }} condition: and(succeeded(), ne(variables['Agent.Os'], 'Windows_NT')) + - script: | + REM Check if ESRP is disabled while SignType is real + if /I "${{ parameters.microbuildUseESRP }}"=="false" if /I "$(_SignType)"=="real" ( + echo Error: ESRP must be enabled when SignType is real. + exit /b 1 + ) + displayName: 'Validate ESRP usage (Windows)' + condition: and(succeeded(), eq(variables['Agent.Os'], 'Windows_NT')) + - script: | + # Check if ESRP is disabled while SignType is real + if [ "${{ parameters.microbuildUseESRP }}" = "false" ] && [ "$(_SignType)" = "real" ]; then + echo "Error: ESRP must be enabled when SignType is real." + exit 1 + fi + displayName: 'Validate ESRP usage (Non-Windows)' + condition: and(succeeded(), ne(variables['Agent.Os'], 'Windows_NT')) + - task: MicroBuildSigningPlugin@4 displayName: Install MicroBuild plugin inputs: signType: $(_SignType) zipSources: false feedSource: https://dnceng.pkgs.visualstudio.com/_packaging/MicroBuildToolset/nuget/v3/index.json - ${{ if and(eq(parameters.enableMicrobuildForMacAndLinux, 'true'), ne(variables['Agent.Os'], 'Windows_NT')) }}: - azureSubscription: 'MicroBuild Signing Task (DevDiv)' - useEsrpCli: true - ${{ elseif eq(variables['System.TeamProject'], 'DevDiv') }}: - ConnectedPMEServiceName: 6cc74545-d7b9-4050-9dfa-ebefcc8961ea - ${{ else }}: - ConnectedPMEServiceName: 248d384a-b39b-46e3-8ad5-c2c210d5e7ca + ${{ if eq(parameters.microbuildUseESRP, true) }}: + ${{ if eq(parameters.enableMicrobuildForMacAndLinux, 'true') }}: + azureSubscription: 'MicroBuild Signing Task (DevDiv)' + useEsrpCli: true + ${{ elseif eq(variables['System.TeamProject'], 'DevDiv') }}: + ConnectedPMEServiceName: 6cc74545-d7b9-4050-9dfa-ebefcc8961ea + ${{ else }}: + ConnectedPMEServiceName: 248d384a-b39b-46e3-8ad5-c2c210d5e7ca env: TeamName: $(_TeamName) MicroBuildOutputFolderOverride: ${{ parameters.microBuildOutputFolder }} diff --git a/global.json b/global.json index 61875203a0..ee409d2fdc 100644 --- a/global.json +++ b/global.json @@ -33,7 +33,7 @@ "rollForward": "latestFeature" }, "msbuild-sdks": { - "Microsoft.DotNet.Arcade.Sdk": "10.0.0-beta.25367.5", + "Microsoft.DotNet.Arcade.Sdk": "10.0.0-beta.25373.3", "MSBuild.Sdk.Extras": "3.0.44" } } From cf172d008771a1cde38d67810ed42828d52cd98f Mon Sep 17 00:00:00 2001 From: dotnet bot Date: Thu, 24 Jul 2025 05:37:12 +0200 Subject: [PATCH 282/541] Localized file check-in by OneLocBuild Task: Build definition ID 1218: Build ID 2756861 --- .../xlf/CodeFixResources.cs.xlf | 2 +- .../xlf/CodeFixResources.de.xlf | 2 +- .../xlf/CodeFixResources.es.xlf | 2 +- .../xlf/CodeFixResources.pl.xlf | 2 +- .../xlf/CodeFixResources.pt-BR.xlf | 2 +- .../xlf/CodeFixResources.ru.xlf | 2 +- .../xlf/CodeFixResources.tr.xlf | 2 +- .../xlf/CodeFixResources.zh-Hans.xlf | 2 +- .../xlf/CodeFixResources.zh-Hant.xlf | 2 +- src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf | 6 +++--- src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf | 6 +++--- src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf | 6 +++--- src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf | 6 +++--- src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf | 12 ++++++------ .../MSTest.Analyzers/xlf/Resources.pt-BR.xlf | 6 +++--- src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf | 6 +++--- src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf | 6 +++--- .../MSTest.Analyzers/xlf/Resources.zh-Hant.xlf | 6 +++--- 18 files changed, 39 insertions(+), 39 deletions(-) diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.cs.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.cs.xlf index 0bed0e5896..7c85a47db8 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.cs.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.cs.xlf @@ -49,7 +49,7 @@ Pass 'TestContext.CancellationTokenSource.Token' argument to method call - Pass 'TestContext.CancellationTokenSource.Token' argument to method call + Předejte argument TestContext.CancellationTokenSource.Token volání metody. diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.de.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.de.xlf index ebd4251925..16776cafc7 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.de.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.de.xlf @@ -49,7 +49,7 @@ Pass 'TestContext.CancellationTokenSource.Token' argument to method call - Pass 'TestContext.CancellationTokenSource.Token' argument to method call + Argument „TestContext.CancellationTokenSource.Token“ an den Methodenaufruf übergeben diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.es.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.es.xlf index 491cd0f467..5fe2aeef20 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.es.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.es.xlf @@ -49,7 +49,7 @@ Pass 'TestContext.CancellationTokenSource.Token' argument to method call - Pass 'TestContext.CancellationTokenSource.Token' argument to method call + Pasa el argumento 'TestContext.CancellationTokenSource.Token' a la llamada de método diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pl.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pl.xlf index 9784b9ae35..310742cd01 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pl.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pl.xlf @@ -49,7 +49,7 @@ Pass 'TestContext.CancellationTokenSource.Token' argument to method call - Pass 'TestContext.CancellationTokenSource.Token' argument to method call + Przekaż argument „TestContext.CancellationTokenSource.Token” do wywołania metody diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pt-BR.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pt-BR.xlf index 0340b1af02..bd3d1f3de9 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pt-BR.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pt-BR.xlf @@ -49,7 +49,7 @@ Pass 'TestContext.CancellationTokenSource.Token' argument to method call - Pass 'TestContext.CancellationTokenSource.Token' argument to method call + Passe o argumento 'TestContext.CancellationTokenSource.Token' para a chamada do método diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ru.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ru.xlf index 3c4a91f10f..e39f5f059c 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ru.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ru.xlf @@ -49,7 +49,7 @@ Pass 'TestContext.CancellationTokenSource.Token' argument to method call - Pass 'TestContext.CancellationTokenSource.Token' argument to method call + Передайте аргумент "TestContext.CancellationTokenSource.Token" вызов метода diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.tr.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.tr.xlf index 51ed7e16a1..1d0141b71c 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.tr.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.tr.xlf @@ -49,7 +49,7 @@ Pass 'TestContext.CancellationTokenSource.Token' argument to method call - Pass 'TestContext.CancellationTokenSource.Token' argument to method call + ‘TestContext.CancellationTokenSource.Token’ bağımsız değişkeni metot çağrısına geçirin diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hans.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hans.xlf index 0843af0b17..271951cb89 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hans.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hans.xlf @@ -49,7 +49,7 @@ Pass 'TestContext.CancellationTokenSource.Token' argument to method call - Pass 'TestContext.CancellationTokenSource.Token' argument to method call + 将 'TestContext.CancellationTokenSource.Token' 参数传递给方法调用 diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hant.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hant.xlf index 2d948f4f46..d490fcbef8 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hant.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hant.xlf @@ -49,7 +49,7 @@ Pass 'TestContext.CancellationTokenSource.Token' argument to method call - Pass 'TestContext.CancellationTokenSource.Token' argument to method call + 將 'TestContext.CancellationTokenSource.Token' 引數傳遞給方法呼叫 diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf index 39f3ae05bc..bdebc0ae80 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf @@ -434,17 +434,17 @@ Typ deklarující tyto metody by měl také respektovat následující pravidla: When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationTokenSource.Token to enable cooperative cancellation and respect test timeouts. - When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationTokenSource.Token to enable cooperative cancellation and respect test timeouts. + Při volání asynchronních metod, které mají přetížení akceptující parametr CancellationToken, upřednostňujte použití přetížení s TestContext.CancellationTokenSource.Token, aby se umožnilo kooperativní rušení a dodržování časových limitů testů. Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationTokenSource.Token' - Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationTokenSource.Token' + Zvažte použití přetížení, které přijímá CancellationToken a předejte TestContext.CancellationTokenSource.Token. Flow TestContext.CancellationToken to async operations - Flow TestContext.CancellationToken to async operations + Přenesení TestContext.CancellationToken do asynchronních operací diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf index b6caeaf386..1dfb6a24fd 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf @@ -435,17 +435,17 @@ Der Typ, der diese Methoden deklariert, sollte auch die folgenden Regeln beachte When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationTokenSource.Token to enable cooperative cancellation and respect test timeouts. - When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationTokenSource.Token to enable cooperative cancellation and respect test timeouts. + Wenn Sie asynchrone Methoden aufrufen, die über Überladungen verfügen, die einen CancellationToken-Parameter akzeptieren, bevorzugen Sie die Verwendung der Überladung mit TestContext.CancellationTokenSource.Token, um einen kooperativen Abbruch zu ermöglichen und Testtimeouts zu berücksichtigen. Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationTokenSource.Token' - Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationTokenSource.Token' + Erwägen Sie die Verwendung der Überladung, die ein CancellationToken akzeptiert, und übergeben Sie „TestContext.CancellationTokenSource.Token“. Flow TestContext.CancellationToken to async operations - Flow TestContext.CancellationToken to async operations + Fluss von TestContext.CancellationToken zu asynchronen Vorgängen diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf index a6734a9f4b..29ae9ddffb 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf @@ -434,17 +434,17 @@ El tipo que declara estos métodos también debe respetar las reglas siguientes: When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationTokenSource.Token to enable cooperative cancellation and respect test timeouts. - When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationTokenSource.Token to enable cooperative cancellation and respect test timeouts. + Al llamar a métodos asincrónicos que tienen sobrecargas que aceptan un parámetro CancellationToken, es preferible utilizar la sobrecarga con TestContext.CancellationTokenSource.Token para habilitar la cancelación cooperativa y respetar los tiempos de espera de las pruebas. Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationTokenSource.Token' - Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationTokenSource.Token' + Considere utilizar la sobrecarga que acepta un CancellationToken y pase 'TestContext.CancellationTokenSource.Token' Flow TestContext.CancellationToken to async operations - Flow TestContext.CancellationToken to async operations + Flujo de TestContext.CancellationToken a operaciones asincrónicas diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf index f218e8c841..0fb49f127f 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf @@ -434,17 +434,17 @@ The type declaring these methods should also respect the following rules: When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationTokenSource.Token to enable cooperative cancellation and respect test timeouts. - When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationTokenSource.Token to enable cooperative cancellation and respect test timeouts. + CancellationToken パラメーターを受け入れるオーバーロードを持つ非同期メソッドを呼び出す場合は、TestContext.CancellationTokenSource.Token でオーバーロードを使用して協調的な取り消しを有効にし、テスト タイムアウトを考慮します。 Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationTokenSource.Token' - Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationTokenSource.Token' + CancellationToken を受け取り、'TestContext.CancellationTokenSource.Token' を渡すオーバーロードの使用を検討してください Flow TestContext.CancellationToken to async operations - Flow TestContext.CancellationToken to async operations + TestContext.CancellationToken を非同期操作にフローする diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf index 575319d36b..40475312a5 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf @@ -434,17 +434,17 @@ Typ deklarujący te metody powinien również przestrzegać następujących regu When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationTokenSource.Token to enable cooperative cancellation and respect test timeouts. - When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationTokenSource.Token to enable cooperative cancellation and respect test timeouts. + W przypadku wywoływania metod asynchronicznych, które mają przeciążenia akceptujące parametr CancellationToken, preferuj użycie przeciążenia z elementem TestContext.CancellationTokenSource.Token, aby umożliwić współpracujące anulowanie i uwzględnić limity czasu testu. Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationTokenSource.Token' - Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationTokenSource.Token' + Rozważ użycie przeciążenia akceptującego parametr CancellationToken i przekazanie elementu „TestContext.CancellationTokenSource.Token” Flow TestContext.CancellationToken to async operations - Flow TestContext.CancellationToken to async operations + Przekaż TestContext.CancellationToken do operacji asynchronicznych @@ -886,17 +886,17 @@ Typ deklarujący te metody powinien również przestrzegać następujących regu TestContext property cannot be accessed in this context - TestContext property cannot be accessed in this context + W tym kontekście nie można uzyskać dostępu do właściwości TestContext TestContext property '{0}' cannot be accessed in '{1}' method - TestContext property '{0}' cannot be accessed in '{1}' method + Nie można uzyskać dostępu do właściwości TestContext „{0}” w metodzie „{1}” Some TestContext properties are only available during test execution and cannot be accessed in assembly initialize, class initialize, class cleanup, or assembly cleanup methods. - Some TestContext properties are only available during test execution and cannot be accessed in assembly initialize, class initialize, class cleanup, or assembly cleanup methods. + Niektóre właściwości TestContext są dostępne tylko podczas wykonywania testu i nie można uzyskać do nich dostępu w metodach inicjowania, inicjowania klasy, oczyszczania klasy ani oczyszczania zestawów. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf index d19aeb8037..5964e79dbf 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf @@ -434,17 +434,17 @@ O tipo que declara esses métodos também deve respeitar as seguintes regras: When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationTokenSource.Token to enable cooperative cancellation and respect test timeouts. - When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationTokenSource.Token to enable cooperative cancellation and respect test timeouts. + Ao chamar métodos assíncronos que tenham sobrecargas que aceitam um parâmetro CancellationToken, prefira usar a sobrecarga com TestContext.CancellationTokenSource.Token para habilitar o cancelamento cooperativo e respeitar os tempos limite do teste. Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationTokenSource.Token' - Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationTokenSource.Token' + Considere usar a sobrecarga que aceita um CancellationToken e passar "TestContext.CancellationTokenSource.Token" Flow TestContext.CancellationToken to async operations - Flow TestContext.CancellationToken to async operations + Fluxo TestContext.CancellationToken para operações assíncronas diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf index d90854fd5b..44be21bae2 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf @@ -440,17 +440,17 @@ The type declaring these methods should also respect the following rules: When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationTokenSource.Token to enable cooperative cancellation and respect test timeouts. - When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationTokenSource.Token to enable cooperative cancellation and respect test timeouts. + При вызове асинхронных методов с перегрузками, принимающими параметр CancellationToken, рекомендуется использовать перегрузку с TestContext.CancellationTokenSource.Token, чтобы обеспечить кооперативную отмену и учитывать времена ожидания теста. Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationTokenSource.Token' - Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationTokenSource.Token' + Рассмотрите возможность использования перегрузки, которая принимает CancellationToken, и передавайте "TestContext.CancellationTokenSource.Token" Flow TestContext.CancellationToken to async operations - Flow TestContext.CancellationToken to async operations + Передача TestContext.CancellationToken в асинхронные операции diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf index 56d299a314..6fde92def0 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf @@ -434,17 +434,17 @@ Bu yöntemleri bildiren tipin ayrıca aşağıdaki kurallara uyması gerekir: When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationTokenSource.Token to enable cooperative cancellation and respect test timeouts. - When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationTokenSource.Token to enable cooperative cancellation and respect test timeouts. + CancellationToken parametresini kabul eden aşırı yüklemeleri olan asenkron yöntemleri çağırırken, işbirliğine dayalı iptal işlemini etkinleştirmek ve test zaman aşımlarını dikkate almak için TestContext.CancellationTokenSource.Token ile aşırı yüklemeyi kullanmayı tercih edin. Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationTokenSource.Token' - Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationTokenSource.Token' + CancellationToken'ı kabul eden aşırı yüklemeyi kullanmayı düşünün ve 'TestContext.CancellationTokenSource.Token'i geçirin. Flow TestContext.CancellationToken to async operations - Flow TestContext.CancellationToken to async operations + TestContext.CancellationToken'ı asenkron işlemler için akışa aktarın diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf index a4e05e11a1..edc388e035 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf @@ -434,17 +434,17 @@ The type declaring these methods should also respect the following rules: When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationTokenSource.Token to enable cooperative cancellation and respect test timeouts. - When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationTokenSource.Token to enable cooperative cancellation and respect test timeouts. + 在呼叫接受 CancellationToken 參數的多載非同步方法時,建議使用 TestContext.CancellationTokenSource.Token 的多載,以啟用共同取消並遵守測試逾時。 Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationTokenSource.Token' - Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationTokenSource.Token' + 請考慮使用接受 CancellationToken 的多載,並傳遞 'TestContext.CancellationTokenSource.Token' Flow TestContext.CancellationToken to async operations - Flow TestContext.CancellationToken to async operations + 將 TestContext.CancellationToken 傳遞給非同步作業 From 6651450b4bbec9e73ad7b5f6118539ea1c44e3e0 Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Thu, 24 Jul 2025 05:51:12 +0200 Subject: [PATCH 283/541] [main] Update dependencies from microsoft/testfx (#6146) Co-authored-by: dotnet-maestro[bot] --- eng/Version.Details.xml | 8 ++++---- eng/Versions.props | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index 993a5a53c2..a111b6068d 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -17,13 +17,13 @@ https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage 6140a1b569c1205f4f596d4752c95a43c0f06d06 - + https://github.com/microsoft/testfx - 171ae1e9b5fb101f8c47ab2e8dff0fbb250d3bf9 + 7d305158d16bc674ed85e897b3e5b842867877d8 - + https://github.com/microsoft/testfx - 171ae1e9b5fb101f8c47ab2e8dff0fbb250d3bf9 + 7d305158d16bc674ed85e897b3e5b842867877d8 diff --git a/eng/Versions.props b/eng/Versions.props index a98c005fcf..9d7f424fe3 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -10,7 +10,7 @@ 10.0.0-beta.25373.3 18.0.0-preview.25371.1 - 3.10.0-preview.25372.9 - 1.8.0-preview.25372.9 + 3.10.0-preview.25373.2 + 1.8.0-preview.25373.2 From 7ed80ce0280168c152e0084155a4d5ed7e90c1e2 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Thu, 24 Jul 2025 09:57:17 +0200 Subject: [PATCH 284/541] Don't track public API for irrelevant projects (#6148) --- .../MSTest.Analyzers.CodeFixes.csproj | 5 - .../PublicAPI.Shipped.txt | 116 ------------------ .../PublicAPI.Unshipped.txt | 21 ---- .../MSTest.Analyzers.Package.csproj | 5 - .../PublicAPI.Shipped.txt | 1 - .../PublicAPI.Unshipped.txt | 1 - .../MSTest.GlobalConfigsGenerator.csproj | 5 - .../PublicAPI.Shipped.txt | 1 - .../PublicAPI.Unshipped.txt | 1 - .../MSTest.Internal.Analyzers.csproj | 5 - .../PublicAPI.Shipped.txt | 5 - .../PublicAPI.Unshipped.txt | 1 - .../MSTest.SourceGeneration.csproj | 2 - .../PublicAPI.Shipped.txt | 1 - .../PublicAPI.Unshipped.txt | 1 - .../Microsoft.Testing.Platform.MSBuild.csproj | 5 - .../PublicAPI.Shipped.txt | 84 ------------- .../PublicAPI.Unshipped.txt | 1 - 18 files changed, 261 deletions(-) delete mode 100644 src/Analyzers/MSTest.Analyzers.CodeFixes/PublicAPI.Shipped.txt delete mode 100644 src/Analyzers/MSTest.Analyzers.CodeFixes/PublicAPI.Unshipped.txt delete mode 100644 src/Analyzers/MSTest.Analyzers.Package/PublicAPI.Shipped.txt delete mode 100644 src/Analyzers/MSTest.Analyzers.Package/PublicAPI.Unshipped.txt delete mode 100644 src/Analyzers/MSTest.GlobalConfigsGenerator/PublicAPI.Shipped.txt delete mode 100644 src/Analyzers/MSTest.GlobalConfigsGenerator/PublicAPI.Unshipped.txt delete mode 100644 src/Analyzers/MSTest.Internal.Analyzers/PublicAPI.Shipped.txt delete mode 100644 src/Analyzers/MSTest.Internal.Analyzers/PublicAPI.Unshipped.txt delete mode 100644 src/Analyzers/MSTest.SourceGeneration/PublicAPI.Shipped.txt delete mode 100644 src/Analyzers/MSTest.SourceGeneration/PublicAPI.Unshipped.txt delete mode 100644 src/Platform/Microsoft.Testing.Platform.MSBuild/PublicAPI.Shipped.txt delete mode 100644 src/Platform/Microsoft.Testing.Platform.MSBuild/PublicAPI.Unshipped.txt diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/MSTest.Analyzers.CodeFixes.csproj b/src/Analyzers/MSTest.Analyzers.CodeFixes/MSTest.Analyzers.CodeFixes.csproj index 42a1a88308..90c2706c8f 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/MSTest.Analyzers.CodeFixes.csproj +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/MSTest.Analyzers.CodeFixes.csproj @@ -6,11 +6,6 @@ MSTest.Analyzers - - - - - diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/PublicAPI.Shipped.txt b/src/Analyzers/MSTest.Analyzers.CodeFixes/PublicAPI.Shipped.txt deleted file mode 100644 index 712126dc7e..0000000000 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/PublicAPI.Shipped.txt +++ /dev/null @@ -1,116 +0,0 @@ -#nullable enable -MSTest.Analyzers.AddTestClassFixer -MSTest.Analyzers.AddTestClassFixer.AddTestClassFixer() -> void -MSTest.Analyzers.AssemblyCleanupShouldBeValidFixer -MSTest.Analyzers.AssemblyCleanupShouldBeValidFixer.AssemblyCleanupShouldBeValidFixer() -> void -MSTest.Analyzers.AssemblyInitializeShouldBeValidFixer -MSTest.Analyzers.AssemblyInitializeShouldBeValidFixer.AssemblyInitializeShouldBeValidFixer() -> void -MSTest.Analyzers.AssertionArgsShouldAvoidConditionalAccessFixer -MSTest.Analyzers.AssertionArgsShouldAvoidConditionalAccessFixer.AssertionArgsShouldAvoidConditionalAccessFixer() -> void -MSTest.Analyzers.AssertionArgsShouldBePassedInCorrectOrderFixer -MSTest.Analyzers.AssertionArgsShouldBePassedInCorrectOrderFixer.AssertionArgsShouldBePassedInCorrectOrderFixer() -> void -MSTest.Analyzers.AvoidAssertAreSameWithValueTypesFixer -MSTest.Analyzers.AvoidAssertAreSameWithValueTypesFixer.AvoidAssertAreSameWithValueTypesFixer() -> void -MSTest.Analyzers.AvoidExpectedExceptionAttributeFixer -MSTest.Analyzers.AvoidExpectedExceptionAttributeFixer.AvoidExpectedExceptionAttributeFixer() -> void -MSTest.Analyzers.ClassCleanupShouldBeValidFixer -MSTest.Analyzers.ClassCleanupShouldBeValidFixer.ClassCleanupShouldBeValidFixer() -> void -MSTest.Analyzers.ClassInitializeShouldBeValidFixer -MSTest.Analyzers.ClassInitializeShouldBeValidFixer.ClassInitializeShouldBeValidFixer() -> void -MSTest.Analyzers.PreferAssertFailOverAlwaysFalseConditionsFixer -MSTest.Analyzers.PreferAssertFailOverAlwaysFalseConditionsFixer.PreferAssertFailOverAlwaysFalseConditionsFixer() -> void -MSTest.Analyzers.PreferConstructorOverTestInitializeFixer -MSTest.Analyzers.PreferConstructorOverTestInitializeFixer.PreferConstructorOverTestInitializeFixer() -> void -MSTest.Analyzers.PreferDisposeOverTestCleanupFixer -MSTest.Analyzers.PreferDisposeOverTestCleanupFixer.PreferDisposeOverTestCleanupFixer() -> void -MSTest.Analyzers.PreferTestCleanupOverDisposeFixer -MSTest.Analyzers.PreferTestCleanupOverDisposeFixer.PreferTestCleanupOverDisposeFixer() -> void -MSTest.Analyzers.PreferTestInitializeOverConstructorFixer -MSTest.Analyzers.PreferTestInitializeOverConstructorFixer.PreferTestInitializeOverConstructorFixer() -> void -MSTest.Analyzers.PublicMethodShouldBeTestMethodFixer -MSTest.Analyzers.PublicMethodShouldBeTestMethodFixer.PublicMethodShouldBeTestMethodFixer() -> void -MSTest.Analyzers.TestClassShouldBeValidFixer -MSTest.Analyzers.TestClassShouldBeValidFixer.TestClassShouldBeValidFixer() -> void -MSTest.Analyzers.TestCleanupShouldBeValidFixer -MSTest.Analyzers.TestCleanupShouldBeValidFixer.TestCleanupShouldBeValidFixer() -> void -MSTest.Analyzers.TestContextShouldBeValidFixer -MSTest.Analyzers.TestContextShouldBeValidFixer.TestContextShouldBeValidFixer() -> void -MSTest.Analyzers.TestInitializeShouldBeValidFixer -MSTest.Analyzers.TestInitializeShouldBeValidFixer.TestInitializeShouldBeValidFixer() -> void -MSTest.Analyzers.TestMethodShouldBeValidCodeFixProvider -MSTest.Analyzers.TestMethodShouldBeValidCodeFixProvider.TestMethodShouldBeValidCodeFixProvider() -> void -MSTest.Analyzers.UseAttributeOnTestMethodFixer -MSTest.Analyzers.UseAttributeOnTestMethodFixer.UseAttributeOnTestMethodFixer() -> void -MSTest.Analyzers.UseNewerAssertThrowsFixer -MSTest.Analyzers.UseNewerAssertThrowsFixer.UseNewerAssertThrowsFixer() -> void -MSTest.Analyzers.UseProperAssertMethodsFixer -MSTest.Analyzers.UseProperAssertMethodsFixer.UseProperAssertMethodsFixer() -> void -override MSTest.Analyzers.AddTestClassFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! -override MSTest.Analyzers.AddTestClassFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! -override MSTest.Analyzers.AssemblyCleanupShouldBeValidFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! -override MSTest.Analyzers.AssemblyCleanupShouldBeValidFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! -override MSTest.Analyzers.AssemblyInitializeShouldBeValidFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! -override MSTest.Analyzers.AssemblyInitializeShouldBeValidFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! -override MSTest.Analyzers.AssertionArgsShouldAvoidConditionalAccessFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! -override MSTest.Analyzers.AssertionArgsShouldAvoidConditionalAccessFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! -override MSTest.Analyzers.AssertionArgsShouldBePassedInCorrectOrderFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! -override MSTest.Analyzers.AssertionArgsShouldBePassedInCorrectOrderFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! -override MSTest.Analyzers.AvoidAssertAreSameWithValueTypesFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! -override MSTest.Analyzers.AvoidAssertAreSameWithValueTypesFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! -override MSTest.Analyzers.AvoidExpectedExceptionAttributeFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! -override MSTest.Analyzers.ClassCleanupShouldBeValidFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! -override MSTest.Analyzers.ClassCleanupShouldBeValidFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! -override MSTest.Analyzers.ClassInitializeShouldBeValidFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! -override MSTest.Analyzers.ClassInitializeShouldBeValidFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! -override MSTest.Analyzers.PreferAssertFailOverAlwaysFalseConditionsFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! -override MSTest.Analyzers.PreferAssertFailOverAlwaysFalseConditionsFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! -override MSTest.Analyzers.PreferConstructorOverTestInitializeFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray -override MSTest.Analyzers.PreferConstructorOverTestInitializeFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! -override MSTest.Analyzers.PreferConstructorOverTestInitializeFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! -override MSTest.Analyzers.PreferDisposeOverTestCleanupFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray -override MSTest.Analyzers.PreferDisposeOverTestCleanupFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! -override MSTest.Analyzers.PreferDisposeOverTestCleanupFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! -override MSTest.Analyzers.PreferTestCleanupOverDisposeFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray -override MSTest.Analyzers.PreferTestCleanupOverDisposeFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! -override MSTest.Analyzers.PreferTestCleanupOverDisposeFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! -override MSTest.Analyzers.PreferTestInitializeOverConstructorFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray -override MSTest.Analyzers.PreferTestInitializeOverConstructorFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! -override MSTest.Analyzers.PreferTestInitializeOverConstructorFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! -override MSTest.Analyzers.PublicMethodShouldBeTestMethodFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray -override MSTest.Analyzers.PublicMethodShouldBeTestMethodFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! -override MSTest.Analyzers.PublicMethodShouldBeTestMethodFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! -override MSTest.Analyzers.TestClassShouldBeValidFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! -override MSTest.Analyzers.TestClassShouldBeValidFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! -override MSTest.Analyzers.TestCleanupShouldBeValidFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! -override MSTest.Analyzers.TestCleanupShouldBeValidFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! -override MSTest.Analyzers.TestContextShouldBeValidFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! -override MSTest.Analyzers.TestContextShouldBeValidFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! -override MSTest.Analyzers.TestInitializeShouldBeValidFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! -override MSTest.Analyzers.TestInitializeShouldBeValidFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! -override MSTest.Analyzers.TestMethodShouldBeValidCodeFixProvider.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray -override MSTest.Analyzers.TestMethodShouldBeValidCodeFixProvider.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! -override MSTest.Analyzers.TestMethodShouldBeValidCodeFixProvider.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! -override MSTest.Analyzers.UseAttributeOnTestMethodFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! -override MSTest.Analyzers.UseNewerAssertThrowsFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! -override MSTest.Analyzers.UseNewerAssertThrowsFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! -override MSTest.Analyzers.UseProperAssertMethodsFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! -override MSTest.Analyzers.UseProperAssertMethodsFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! -override sealed MSTest.Analyzers.AddTestClassFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray -override sealed MSTest.Analyzers.AssemblyCleanupShouldBeValidFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray -override sealed MSTest.Analyzers.AssemblyInitializeShouldBeValidFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray -override sealed MSTest.Analyzers.AssertionArgsShouldAvoidConditionalAccessFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray -override sealed MSTest.Analyzers.AssertionArgsShouldBePassedInCorrectOrderFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray -override sealed MSTest.Analyzers.AvoidAssertAreSameWithValueTypesFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray -override sealed MSTest.Analyzers.AvoidExpectedExceptionAttributeFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray -override sealed MSTest.Analyzers.AvoidExpectedExceptionAttributeFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! -override sealed MSTest.Analyzers.ClassCleanupShouldBeValidFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray -override sealed MSTest.Analyzers.ClassInitializeShouldBeValidFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray -override sealed MSTest.Analyzers.PreferAssertFailOverAlwaysFalseConditionsFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray -override sealed MSTest.Analyzers.TestClassShouldBeValidFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray -override sealed MSTest.Analyzers.TestCleanupShouldBeValidFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray -override sealed MSTest.Analyzers.TestContextShouldBeValidFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray -override sealed MSTest.Analyzers.TestInitializeShouldBeValidFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray -override sealed MSTest.Analyzers.UseAttributeOnTestMethodFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray -override sealed MSTest.Analyzers.UseAttributeOnTestMethodFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! -override sealed MSTest.Analyzers.UseNewerAssertThrowsFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray -override sealed MSTest.Analyzers.UseProperAssertMethodsFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/PublicAPI.Unshipped.txt b/src/Analyzers/MSTest.Analyzers.CodeFixes/PublicAPI.Unshipped.txt deleted file mode 100644 index a0766dd232..0000000000 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/PublicAPI.Unshipped.txt +++ /dev/null @@ -1,21 +0,0 @@ -#nullable enable -MSTest.Analyzers.FlowTestContextCancellationTokenFixer -MSTest.Analyzers.FlowTestContextCancellationTokenFixer.FlowTestContextCancellationTokenFixer() -> void -override MSTest.Analyzers.FlowTestContextCancellationTokenFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! -override sealed MSTest.Analyzers.FlowTestContextCancellationTokenFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray -override sealed MSTest.Analyzers.FlowTestContextCancellationTokenFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! -MSTest.Analyzers.CodeFixes.StringAssertToAssertFixer -MSTest.Analyzers.CodeFixes.StringAssertToAssertFixer.StringAssertToAssertFixer() -> void -MSTest.Analyzers.PreferTestMethodOverDataTestMethodFixer -MSTest.Analyzers.PreferTestMethodOverDataTestMethodFixer.PreferTestMethodOverDataTestMethodFixer() -> void -override MSTest.Analyzers.CodeFixes.StringAssertToAssertFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray -override MSTest.Analyzers.CodeFixes.StringAssertToAssertFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! -override MSTest.Analyzers.PreferTestMethodOverDataTestMethodFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray -override MSTest.Analyzers.PreferTestMethodOverDataTestMethodFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! -override MSTest.Analyzers.PreferTestMethodOverDataTestMethodFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! -MSTest.Analyzers.UseCooperativeCancellationForTimeoutFixer -MSTest.Analyzers.UseCooperativeCancellationForTimeoutFixer.UseCooperativeCancellationForTimeoutFixer() -> void -override MSTest.Analyzers.UseCooperativeCancellationForTimeoutFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! -override sealed MSTest.Analyzers.UseCooperativeCancellationForTimeoutFixer.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray -override sealed MSTest.Analyzers.UseCooperativeCancellationForTimeoutFixer.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task! -override sealed MSTest.Analyzers.CodeFixes.StringAssertToAssertFixer.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider! diff --git a/src/Analyzers/MSTest.Analyzers.Package/MSTest.Analyzers.Package.csproj b/src/Analyzers/MSTest.Analyzers.Package/MSTest.Analyzers.Package.csproj index 71244cd642..0631e8b43c 100644 --- a/src/Analyzers/MSTest.Analyzers.Package/MSTest.Analyzers.Package.csproj +++ b/src/Analyzers/MSTest.Analyzers.Package/MSTest.Analyzers.Package.csproj @@ -21,11 +21,6 @@ $(TargetsForTfmSpecificContentInPackage);_AddAnalyzersToOutput - - - - - diff --git a/src/Analyzers/MSTest.Analyzers.Package/PublicAPI.Shipped.txt b/src/Analyzers/MSTest.Analyzers.Package/PublicAPI.Shipped.txt deleted file mode 100644 index 7dc5c58110..0000000000 --- a/src/Analyzers/MSTest.Analyzers.Package/PublicAPI.Shipped.txt +++ /dev/null @@ -1 +0,0 @@ -#nullable enable diff --git a/src/Analyzers/MSTest.Analyzers.Package/PublicAPI.Unshipped.txt b/src/Analyzers/MSTest.Analyzers.Package/PublicAPI.Unshipped.txt deleted file mode 100644 index 7dc5c58110..0000000000 --- a/src/Analyzers/MSTest.Analyzers.Package/PublicAPI.Unshipped.txt +++ /dev/null @@ -1 +0,0 @@ -#nullable enable diff --git a/src/Analyzers/MSTest.GlobalConfigsGenerator/MSTest.GlobalConfigsGenerator.csproj b/src/Analyzers/MSTest.GlobalConfigsGenerator/MSTest.GlobalConfigsGenerator.csproj index 9fad71fb91..f224aa6f8a 100644 --- a/src/Analyzers/MSTest.GlobalConfigsGenerator/MSTest.GlobalConfigsGenerator.csproj +++ b/src/Analyzers/MSTest.GlobalConfigsGenerator/MSTest.GlobalConfigsGenerator.csproj @@ -7,11 +7,6 @@ false - - - - - diff --git a/src/Analyzers/MSTest.GlobalConfigsGenerator/PublicAPI.Shipped.txt b/src/Analyzers/MSTest.GlobalConfigsGenerator/PublicAPI.Shipped.txt deleted file mode 100644 index 7dc5c58110..0000000000 --- a/src/Analyzers/MSTest.GlobalConfigsGenerator/PublicAPI.Shipped.txt +++ /dev/null @@ -1 +0,0 @@ -#nullable enable diff --git a/src/Analyzers/MSTest.GlobalConfigsGenerator/PublicAPI.Unshipped.txt b/src/Analyzers/MSTest.GlobalConfigsGenerator/PublicAPI.Unshipped.txt deleted file mode 100644 index 7dc5c58110..0000000000 --- a/src/Analyzers/MSTest.GlobalConfigsGenerator/PublicAPI.Unshipped.txt +++ /dev/null @@ -1 +0,0 @@ -#nullable enable diff --git a/src/Analyzers/MSTest.Internal.Analyzers/MSTest.Internal.Analyzers.csproj b/src/Analyzers/MSTest.Internal.Analyzers/MSTest.Internal.Analyzers.csproj index a06c6a49e7..d2e12ea51d 100644 --- a/src/Analyzers/MSTest.Internal.Analyzers/MSTest.Internal.Analyzers.csproj +++ b/src/Analyzers/MSTest.Internal.Analyzers/MSTest.Internal.Analyzers.csproj @@ -10,11 +10,6 @@ *$(MSBuildProjectFile)* - - - - - diff --git a/src/Analyzers/MSTest.Internal.Analyzers/PublicAPI.Shipped.txt b/src/Analyzers/MSTest.Internal.Analyzers/PublicAPI.Shipped.txt deleted file mode 100644 index 8e80ba85b6..0000000000 --- a/src/Analyzers/MSTest.Internal.Analyzers/PublicAPI.Shipped.txt +++ /dev/null @@ -1,5 +0,0 @@ -#nullable enable -MSTest.Internal.Analyzers.MSTestObsoleteTypesSuppressor -MSTest.Internal.Analyzers.MSTestObsoleteTypesSuppressor.MSTestObsoleteTypesSuppressor() -> void -override MSTest.Internal.Analyzers.MSTestObsoleteTypesSuppressor.ReportSuppressions(Microsoft.CodeAnalysis.Diagnostics.SuppressionAnalysisContext context) -> void -override MSTest.Internal.Analyzers.MSTestObsoleteTypesSuppressor.SupportedSuppressions.get -> System.Collections.Immutable.ImmutableArray diff --git a/src/Analyzers/MSTest.Internal.Analyzers/PublicAPI.Unshipped.txt b/src/Analyzers/MSTest.Internal.Analyzers/PublicAPI.Unshipped.txt deleted file mode 100644 index 7dc5c58110..0000000000 --- a/src/Analyzers/MSTest.Internal.Analyzers/PublicAPI.Unshipped.txt +++ /dev/null @@ -1 +0,0 @@ -#nullable enable diff --git a/src/Analyzers/MSTest.SourceGeneration/MSTest.SourceGeneration.csproj b/src/Analyzers/MSTest.SourceGeneration/MSTest.SourceGeneration.csproj index bd8d24cc2d..af7c69027c 100644 --- a/src/Analyzers/MSTest.SourceGeneration/MSTest.SourceGeneration.csproj +++ b/src/Analyzers/MSTest.SourceGeneration/MSTest.SourceGeneration.csproj @@ -33,8 +33,6 @@ This package provides the C# source generators for MSTest test framework.]]> - - diff --git a/src/Analyzers/MSTest.SourceGeneration/PublicAPI.Shipped.txt b/src/Analyzers/MSTest.SourceGeneration/PublicAPI.Shipped.txt deleted file mode 100644 index 7dc5c58110..0000000000 --- a/src/Analyzers/MSTest.SourceGeneration/PublicAPI.Shipped.txt +++ /dev/null @@ -1 +0,0 @@ -#nullable enable diff --git a/src/Analyzers/MSTest.SourceGeneration/PublicAPI.Unshipped.txt b/src/Analyzers/MSTest.SourceGeneration/PublicAPI.Unshipped.txt deleted file mode 100644 index 7dc5c58110..0000000000 --- a/src/Analyzers/MSTest.SourceGeneration/PublicAPI.Unshipped.txt +++ /dev/null @@ -1 +0,0 @@ -#nullable enable diff --git a/src/Platform/Microsoft.Testing.Platform.MSBuild/Microsoft.Testing.Platform.MSBuild.csproj b/src/Platform/Microsoft.Testing.Platform.MSBuild/Microsoft.Testing.Platform.MSBuild.csproj index d8cadaf227..57274bc055 100644 --- a/src/Platform/Microsoft.Testing.Platform.MSBuild/Microsoft.Testing.Platform.MSBuild.csproj +++ b/src/Platform/Microsoft.Testing.Platform.MSBuild/Microsoft.Testing.Platform.MSBuild.csproj @@ -51,11 +51,6 @@ This package provides MSBuild integration of the platform, its extensions and co - - - - - diff --git a/src/Platform/Microsoft.Testing.Platform.MSBuild/PublicAPI.Shipped.txt b/src/Platform/Microsoft.Testing.Platform.MSBuild/PublicAPI.Shipped.txt deleted file mode 100644 index 7276566dda..0000000000 --- a/src/Platform/Microsoft.Testing.Platform.MSBuild/PublicAPI.Shipped.txt +++ /dev/null @@ -1,84 +0,0 @@ -#nullable enable -Microsoft.Testing.Platform.MSBuild.ConfigurationFileTask -Microsoft.Testing.Platform.MSBuild.ConfigurationFileTask.AssemblyName.get -> Microsoft.Build.Framework.ITaskItem! -Microsoft.Testing.Platform.MSBuild.ConfigurationFileTask.AssemblyName.set -> void -Microsoft.Testing.Platform.MSBuild.ConfigurationFileTask.ConfigurationFileTask() -> void -Microsoft.Testing.Platform.MSBuild.ConfigurationFileTask.FinalTestingPlatformConfigurationFile.get -> Microsoft.Build.Framework.ITaskItem! -Microsoft.Testing.Platform.MSBuild.ConfigurationFileTask.FinalTestingPlatformConfigurationFile.set -> void -Microsoft.Testing.Platform.MSBuild.ConfigurationFileTask.MSBuildProjectDirectory.get -> Microsoft.Build.Framework.ITaskItem! -Microsoft.Testing.Platform.MSBuild.ConfigurationFileTask.MSBuildProjectDirectory.set -> void -Microsoft.Testing.Platform.MSBuild.ConfigurationFileTask.OutputPath.get -> Microsoft.Build.Framework.ITaskItem! -Microsoft.Testing.Platform.MSBuild.ConfigurationFileTask.OutputPath.set -> void -Microsoft.Testing.Platform.MSBuild.ConfigurationFileTask.TestingPlatformConfigurationFileSource.get -> Microsoft.Build.Framework.ITaskItem! -Microsoft.Testing.Platform.MSBuild.ConfigurationFileTask.TestingPlatformConfigurationFileSource.set -> void -Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask -Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.AssemblyName.get -> Microsoft.Build.Framework.ITaskItem? -Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.AssemblyName.set -> void -Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.Dispose() -> void -Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.DotnetHostPath.get -> Microsoft.Build.Framework.ITaskItem? -Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.DotnetHostPath.set -> void -Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.InvokeTestingPlatformTask() -> void -Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.IsExecutable.get -> Microsoft.Build.Framework.ITaskItem? -Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.IsExecutable.set -> void -Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.NativeExecutableExtension.get -> Microsoft.Build.Framework.ITaskItem? -Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.NativeExecutableExtension.set -> void -Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.ProjectFullPath.get -> Microsoft.Build.Framework.ITaskItem! -Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.ProjectFullPath.set -> void -Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.TargetDir.get -> Microsoft.Build.Framework.ITaskItem? -Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.TargetDir.set -> void -Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.TargetFramework.get -> Microsoft.Build.Framework.ITaskItem! -Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.TargetFramework.set -> void -Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.TargetFrameworkIdentifier.get -> Microsoft.Build.Framework.ITaskItem! -Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.TargetFrameworkIdentifier.set -> void -Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.TargetPath.get -> Microsoft.Build.Framework.ITaskItem! -Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.TargetPath.set -> void -Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.TestArchitecture.get -> Microsoft.Build.Framework.ITaskItem! -Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.TestArchitecture.set -> void -Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.TestingPlatformCaptureOutput.get -> Microsoft.Build.Framework.ITaskItem! -Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.TestingPlatformCaptureOutput.set -> void -Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.TestingPlatformCommandLineArguments.get -> Microsoft.Build.Framework.ITaskItem? -Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.TestingPlatformCommandLineArguments.set -> void -Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.TestingPlatformShowTestsFailure.get -> Microsoft.Build.Framework.ITaskItem! -Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.TestingPlatformShowTestsFailure.set -> void -Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.UseAppHost.get -> Microsoft.Build.Framework.ITaskItem? -Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.UseAppHost.set -> void -Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.VSTestCLIRunSettings.get -> Microsoft.Build.Framework.ITaskItem![]? -Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.VSTestCLIRunSettings.set -> void -Microsoft.Testing.Platform.MSBuild.TestingPlatformEntryPointTask -Microsoft.Testing.Platform.MSBuild.TestingPlatformEntryPointTask.Language.get -> Microsoft.Build.Framework.ITaskItem! -Microsoft.Testing.Platform.MSBuild.TestingPlatformEntryPointTask.Language.set -> void -Microsoft.Testing.Platform.MSBuild.TestingPlatformEntryPointTask.RootNamespace.get -> string? -Microsoft.Testing.Platform.MSBuild.TestingPlatformEntryPointTask.RootNamespace.set -> void -Microsoft.Testing.Platform.MSBuild.TestingPlatformEntryPointTask.TestingPlatformEntryPointGeneratedFilePath.get -> Microsoft.Build.Framework.ITaskItem! -Microsoft.Testing.Platform.MSBuild.TestingPlatformEntryPointTask.TestingPlatformEntryPointGeneratedFilePath.set -> void -Microsoft.Testing.Platform.MSBuild.TestingPlatformEntryPointTask.TestingPlatformEntryPointSourcePath.get -> Microsoft.Build.Framework.ITaskItem! -Microsoft.Testing.Platform.MSBuild.TestingPlatformEntryPointTask.TestingPlatformEntryPointSourcePath.set -> void -Microsoft.Testing.Platform.MSBuild.TestingPlatformEntryPointTask.TestingPlatformEntryPointTask() -> void -Microsoft.Testing.Platform.MSBuild.TestingPlatformSelfRegisteredExtensions -Microsoft.Testing.Platform.MSBuild.TestingPlatformSelfRegisteredExtensions.Language.get -> Microsoft.Build.Framework.ITaskItem! -Microsoft.Testing.Platform.MSBuild.TestingPlatformSelfRegisteredExtensions.Language.set -> void -Microsoft.Testing.Platform.MSBuild.TestingPlatformSelfRegisteredExtensions.RootNamespace.get -> string? -Microsoft.Testing.Platform.MSBuild.TestingPlatformSelfRegisteredExtensions.RootNamespace.set -> void -Microsoft.Testing.Platform.MSBuild.TestingPlatformSelfRegisteredExtensions.SelfRegisteredExtensionsBuilderHook.get -> Microsoft.Build.Framework.ITaskItem![]! -Microsoft.Testing.Platform.MSBuild.TestingPlatformSelfRegisteredExtensions.SelfRegisteredExtensionsBuilderHook.set -> void -Microsoft.Testing.Platform.MSBuild.TestingPlatformSelfRegisteredExtensions.SelfRegisteredExtensionsGeneratedFilePath.get -> Microsoft.Build.Framework.ITaskItem! -Microsoft.Testing.Platform.MSBuild.TestingPlatformSelfRegisteredExtensions.SelfRegisteredExtensionsGeneratedFilePath.set -> void -Microsoft.Testing.Platform.MSBuild.TestingPlatformSelfRegisteredExtensions.SelfRegisteredExtensionsSourcePath.get -> Microsoft.Build.Framework.ITaskItem! -Microsoft.Testing.Platform.MSBuild.TestingPlatformSelfRegisteredExtensions.SelfRegisteredExtensionsSourcePath.set -> void -Microsoft.Testing.Platform.MSBuild.TestingPlatformSelfRegisteredExtensions.TestingPlatformSelfRegisteredExtensions() -> void -override Microsoft.Testing.Platform.MSBuild.ConfigurationFileTask.Execute() -> bool -override Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.Execute() -> bool -override Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.GenerateCommandLineCommands() -> string! -override Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.GenerateFullPathToTool() -> string? -override Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.HandleTaskExecutionErrors() -> bool -override Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.LogEventsFromTextOutput(string! singleLine, Microsoft.Build.Framework.MessageImportance messageImportance) -> void -override Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.LogToolCommand(string! message) -> void -override Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.ProcessStarted() -> void -override Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.StandardErrorLoggingImportance.get -> Microsoft.Build.Framework.MessageImportance -override Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.StandardOutputLoggingImportance.get -> Microsoft.Build.Framework.MessageImportance -override Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.ToolExe.get -> string! -override Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.ToolExe.set -> void -override Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.ToolName.get -> string! -override Microsoft.Testing.Platform.MSBuild.InvokeTestingPlatformTask.ValidateParameters() -> bool -override Microsoft.Testing.Platform.MSBuild.TestingPlatformEntryPointTask.Execute() -> bool -override Microsoft.Testing.Platform.MSBuild.TestingPlatformSelfRegisteredExtensions.Execute() -> bool diff --git a/src/Platform/Microsoft.Testing.Platform.MSBuild/PublicAPI.Unshipped.txt b/src/Platform/Microsoft.Testing.Platform.MSBuild/PublicAPI.Unshipped.txt deleted file mode 100644 index 7dc5c58110..0000000000 --- a/src/Platform/Microsoft.Testing.Platform.MSBuild/PublicAPI.Unshipped.txt +++ /dev/null @@ -1 +0,0 @@ -#nullable enable From 4744fca1052feb95f2d1440dd9f9ba51775ebe04 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Thu, 24 Jul 2025 15:58:31 +0200 Subject: [PATCH 285/541] Make ConditionBaseAttribute.IgnoreMessage settable (#6150) --- .../Attributes/TestMethod/CIConditionAttribute.cs | 6 ++---- .../Attributes/TestMethod/ConditionBaseAttribute.cs | 4 ++-- .../TestFramework/Attributes/TestMethod/IgnoreAttribute.cs | 6 ++---- .../Attributes/TestMethod/OSConditionAttribute.cs | 6 ++---- .../TestFramework/PublicAPI/PublicAPI.Unshipped.txt | 6 ++++++ 5 files changed, 14 insertions(+), 14 deletions(-) diff --git a/src/TestFramework/TestFramework/Attributes/TestMethod/CIConditionAttribute.cs b/src/TestFramework/TestFramework/Attributes/TestMethod/CIConditionAttribute.cs index 89bf7ace40..e4ae082e85 100644 --- a/src/TestFramework/TestFramework/Attributes/TestMethod/CIConditionAttribute.cs +++ b/src/TestFramework/TestFramework/Attributes/TestMethod/CIConditionAttribute.cs @@ -37,10 +37,8 @@ internal CIConditionAttribute(ConditionMode mode, IEnvironment environment) /// public override bool ShouldRun => IsCIEnvironment(); - /// - /// Gets the ignore message (in case returns ). - /// - public override string? IgnoreMessage { get; } + /// + public override string? IgnoreMessage { get; set; } /// /// Gets the group name for this attribute. diff --git a/src/TestFramework/TestFramework/Attributes/TestMethod/ConditionBaseAttribute.cs b/src/TestFramework/TestFramework/Attributes/TestMethod/ConditionBaseAttribute.cs index 3d5edc7905..ed94a814d3 100644 --- a/src/TestFramework/TestFramework/Attributes/TestMethod/ConditionBaseAttribute.cs +++ b/src/TestFramework/TestFramework/Attributes/TestMethod/ConditionBaseAttribute.cs @@ -25,10 +25,10 @@ protected ConditionBaseAttribute(ConditionMode mode) public ConditionMode Mode { get; } /// - /// Gets the ignore message (in case returns ) indicating + /// Gets or sets the ignore message (in case returns ) indicating /// the reason for ignoring the test method or test class. /// - public abstract string? IgnoreMessage { get; } + public virtual string? IgnoreMessage { get; set; } /// /// Gets the group name for this attribute. This is relevant when multiple diff --git a/src/TestFramework/TestFramework/Attributes/TestMethod/IgnoreAttribute.cs b/src/TestFramework/TestFramework/Attributes/TestMethod/IgnoreAttribute.cs index bab35c458d..122ae1fccf 100644 --- a/src/TestFramework/TestFramework/Attributes/TestMethod/IgnoreAttribute.cs +++ b/src/TestFramework/TestFramework/Attributes/TestMethod/IgnoreAttribute.cs @@ -30,10 +30,8 @@ public IgnoreAttribute(string? message) : base(ConditionMode.Include) => IgnoreMessage = message; - /// - /// Gets the ignore message indicating the reason for ignoring the test method or test class. - /// - public override string? IgnoreMessage { get; } + /// + public override string? IgnoreMessage { get; set; } /// public override bool ShouldRun => false; diff --git a/src/TestFramework/TestFramework/Attributes/TestMethod/OSConditionAttribute.cs b/src/TestFramework/TestFramework/Attributes/TestMethod/OSConditionAttribute.cs index fdc05ac0e7..63a8e6db00 100644 --- a/src/TestFramework/TestFramework/Attributes/TestMethod/OSConditionAttribute.cs +++ b/src/TestFramework/TestFramework/Attributes/TestMethod/OSConditionAttribute.cs @@ -79,10 +79,8 @@ public override bool ShouldRun } #endif - /// - /// Gets the ignore message (in case returns ). - /// - public override string? IgnoreMessage { get; } + /// + public override string? IgnoreMessage { get; set; } /// /// Gets the group name for this attribute. diff --git a/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Unshipped.txt b/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Unshipped.txt index 766c80085b..71d9a68b4f 100644 --- a/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Unshipped.txt +++ b/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Unshipped.txt @@ -5,11 +5,14 @@ Microsoft.VisualStudio.TestTools.UnitTesting.CIConditionAttribute.CIConditionAtt Microsoft.VisualStudio.TestTools.UnitTesting.ConditionBaseAttribute.Mode.get -> Microsoft.VisualStudio.TestTools.UnitTesting.ConditionMode override Microsoft.VisualStudio.TestTools.UnitTesting.CIConditionAttribute.GroupName.get -> string! override Microsoft.VisualStudio.TestTools.UnitTesting.CIConditionAttribute.IgnoreMessage.get -> string? +override Microsoft.VisualStudio.TestTools.UnitTesting.CIConditionAttribute.IgnoreMessage.set -> void override Microsoft.VisualStudio.TestTools.UnitTesting.CIConditionAttribute.ShouldRun.get -> bool Microsoft.VisualStudio.TestTools.UnitTesting.DynamicDataAttribute.DynamicDataAttribute(string! dynamicDataSourceName, params object?[]! dynamicDataSourceArguments) -> void Microsoft.VisualStudio.TestTools.UnitTesting.DynamicDataAttribute.DynamicDataAttribute(string! dynamicDataSourceName, System.Type! dynamicDataDeclaringType, params object?[]! dynamicDataSourceArguments) -> void Microsoft.VisualStudio.TestTools.UnitTesting.TestDataRow.TestCategories.get -> System.Collections.Generic.IList? Microsoft.VisualStudio.TestTools.UnitTesting.TestDataRow.TestCategories.set -> void +override Microsoft.VisualStudio.TestTools.UnitTesting.IgnoreAttribute.IgnoreMessage.set -> void +override Microsoft.VisualStudio.TestTools.UnitTesting.OSConditionAttribute.IgnoreMessage.set -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.ContainsSingle(System.Func! predicate, System.Collections.Generic.IEnumerable! collection, string! message = "") -> T static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.DoesNotEndWith(string? substring, string? value, string! message = "") -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.DoesNotEndWith(string? substring, string? value, System.StringComparison comparisonType, string! message = "") -> void @@ -41,3 +44,6 @@ static Microsoft.VisualStudio.TestTools.UnitTesting.CollectionAssert.Equals(obje static Microsoft.VisualStudio.TestTools.UnitTesting.CollectionAssert.ReferenceEquals(object? objA, object? objB) -> bool static Microsoft.VisualStudio.TestTools.UnitTesting.StringAssert.Equals(object? objA, object? objB) -> bool static Microsoft.VisualStudio.TestTools.UnitTesting.StringAssert.ReferenceEquals(object? objA, object? objB) -> bool +*REMOVED*abstract Microsoft.VisualStudio.TestTools.UnitTesting.ConditionBaseAttribute.IgnoreMessage.get -> string? +virtual Microsoft.VisualStudio.TestTools.UnitTesting.ConditionBaseAttribute.IgnoreMessage.get -> string? +virtual Microsoft.VisualStudio.TestTools.UnitTesting.ConditionBaseAttribute.IgnoreMessage.set -> void From 28854b4091adfe74390c8011ebac860899295aff Mon Sep 17 00:00:00 2001 From: dotnet bot Date: Thu, 24 Jul 2025 16:12:57 +0200 Subject: [PATCH 286/541] Localized file check-in by OneLocBuild Task: Build definition ID 1218: Build ID 2757164 --- .../MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ja.xlf | 2 +- .../MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ko.xlf | 2 +- src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf | 6 +++--- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ja.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ja.xlf index 6290453cd1..94549b537e 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ja.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ja.xlf @@ -49,7 +49,7 @@ Pass 'TestContext.CancellationTokenSource.Token' argument to method call - Pass 'TestContext.CancellationTokenSource.Token' argument to method call + 'TestContext.CancellationTokenSource.Token' 引数をメソッド呼び出しに渡す diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ko.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ko.xlf index efe585755b..1d3b2b6c7d 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ko.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ko.xlf @@ -49,7 +49,7 @@ Pass 'TestContext.CancellationTokenSource.Token' argument to method call - Pass 'TestContext.CancellationTokenSource.Token' argument to method call + 메서드 호출에 'TestContext.CancellationTokenSource.Token' 인수 전달 diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf index 1541ee5e1c..c8bbae9794 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf @@ -434,17 +434,17 @@ The type declaring these methods should also respect the following rules: When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationTokenSource.Token to enable cooperative cancellation and respect test timeouts. - When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationTokenSource.Token to enable cooperative cancellation and respect test timeouts. + CancellationToken 매개변수를 허용하는 오버로드가 있는 비동기 메서드를 호출할 때는 협력적 취소를 활성화하고 테스트 시간 제한을 준수하기 위해 TestContext.CancellationTokenSource.Token이 있는 오버로드를 사용하는 것이 좋습니다. Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationTokenSource.Token' - Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationTokenSource.Token' + CancellationToken을 수락하고 'TestContext.CancellationTokenSource.Token'을 전달하는 오버로드를 사용하는 것이 좋습니다. Flow TestContext.CancellationToken to async operations - Flow TestContext.CancellationToken to async operations + 비동기 작업으로 TestContext.CancellationToken 흐름 From b2570d428ec78f88a9c1f31dd3d5442ca9492291 Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Thu, 24 Jul 2025 14:47:33 +0000 Subject: [PATCH 287/541] [main] Update dependencies from dotnet/arcade (#6153) [main] Update dependencies from dotnet/arcade --- eng/Version.Details.xml | 12 ++++++------ eng/Versions.props | 2 +- global.json | 2 +- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index a111b6068d..8d3a1a528c 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -1,17 +1,17 @@ - + https://github.com/dotnet/arcade - 2586309f3f8553152e2d1d54612e9199975f9cd4 + e109adc7869da8c617d6d096564bb3b77fb7743a - + https://github.com/dotnet/arcade - 2586309f3f8553152e2d1d54612e9199975f9cd4 + e109adc7869da8c617d6d096564bb3b77fb7743a - + https://github.com/dotnet/arcade - 2586309f3f8553152e2d1d54612e9199975f9cd4 + e109adc7869da8c617d6d096564bb3b77fb7743a https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage diff --git a/eng/Versions.props b/eng/Versions.props index 9d7f424fe3..95ec431330 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -7,7 +7,7 @@ preview - 10.0.0-beta.25373.3 + 10.0.0-beta.25374.1 18.0.0-preview.25371.1 3.10.0-preview.25373.2 diff --git a/global.json b/global.json index ee409d2fdc..e21809870e 100644 --- a/global.json +++ b/global.json @@ -33,7 +33,7 @@ "rollForward": "latestFeature" }, "msbuild-sdks": { - "Microsoft.DotNet.Arcade.Sdk": "10.0.0-beta.25373.3", + "Microsoft.DotNet.Arcade.Sdk": "10.0.0-beta.25374.1", "MSBuild.Sdk.Extras": "3.0.44" } } From 44bbf31076f765817daccd144f05da70a5db27f1 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Thu, 24 Jul 2025 19:14:04 +0200 Subject: [PATCH 288/541] Comment out AttachCurrentProcessToParentVSProcess (#6155) --- samples/Playground/Program.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/Playground/Program.cs b/samples/Playground/Program.cs index c5c842a040..8e12c8794c 100644 --- a/samples/Playground/Program.cs +++ b/samples/Playground/Program.cs @@ -26,7 +26,7 @@ public static async Task Main(string[] args) { #if NETCOREAPP // To attach to the children - Microsoft.Testing.TestInfrastructure.DebuggerUtility.AttachCurrentProcessToParentVSProcess(); + // Microsoft.Testing.TestInfrastructure.DebuggerUtility.AttachCurrentProcessToParentVSProcess(); #endif ITestApplicationBuilder testApplicationBuilder = await TestApplication.CreateBuilderAsync(args); From f88801a4d05368d768ea1c340698898084767b8c Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Thu, 24 Jul 2025 22:24:04 +0200 Subject: [PATCH 289/541] Add trigger for main and rel/* branches (#6159) --- azure-pipelines.yml | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/azure-pipelines.yml b/azure-pipelines.yml index 6a746387a5..710fce4b49 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -1,3 +1,9 @@ +trigger: + branches: + include: + - main + - rel/* + # Branch(es) that trigger(s) build(s) on PR pr: branches: From bdaedfdcb237d4fe395ac1265af3702df6421b0b Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Fri, 25 Jul 2025 02:56:55 +0000 Subject: [PATCH 290/541] [main] Update dependencies from devdiv/DevDiv/vs-code-coverage, dotnet/arcade (#6160) [main] Update dependencies from devdiv/DevDiv/vs-code-coverage, dotnet/arcade --- eng/Version.Details.xml | 16 ++++++++-------- eng/Versions.props | 4 ++-- eng/common/core-templates/jobs/jobs.yml | 3 --- eng/common/core-templates/jobs/source-build.yml | 16 ---------------- global.json | 2 +- 5 files changed, 11 insertions(+), 30 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index 8d3a1a528c..26094f4c02 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -1,21 +1,21 @@ - + https://github.com/dotnet/arcade - e109adc7869da8c617d6d096564bb3b77fb7743a + 0fbc9e8711fa91e68c2bf3db376fb83b46f4ac35 - + https://github.com/dotnet/arcade - e109adc7869da8c617d6d096564bb3b77fb7743a + 0fbc9e8711fa91e68c2bf3db376fb83b46f4ac35 - + https://github.com/dotnet/arcade - e109adc7869da8c617d6d096564bb3b77fb7743a + 0fbc9e8711fa91e68c2bf3db376fb83b46f4ac35 - + https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage - 6140a1b569c1205f4f596d4752c95a43c0f06d06 + 01f3783a04ed68557a209cc7c1c0d25cfcc7b21e https://github.com/microsoft/testfx diff --git a/eng/Versions.props b/eng/Versions.props index 95ec431330..32e083dfd5 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -7,8 +7,8 @@ preview - 10.0.0-beta.25374.1 - 18.0.0-preview.25371.1 + 10.0.0-beta.25374.3 + 18.0.0-preview.25374.3 3.10.0-preview.25373.2 1.8.0-preview.25373.2 diff --git a/eng/common/core-templates/jobs/jobs.yml b/eng/common/core-templates/jobs/jobs.yml index bf35b78faa..2f992b2c6e 100644 --- a/eng/common/core-templates/jobs/jobs.yml +++ b/eng/common/core-templates/jobs/jobs.yml @@ -83,7 +83,6 @@ jobs: - template: /eng/common/core-templates/jobs/source-build.yml parameters: is1ESPipeline: ${{ parameters.is1ESPipeline }} - allCompletedJobId: Source_Build_Complete ${{ each parameter in parameters.sourceBuildParameters }}: ${{ parameter.key }}: ${{ parameter.value }} @@ -108,8 +107,6 @@ jobs: - ${{ if eq(parameters.publishBuildAssetsDependsOn, '') }}: - ${{ each job in parameters.jobs }}: - ${{ job.job }} - - ${{ if eq(parameters.enableSourceBuild, true) }}: - - Source_Build_Complete runAsPublic: ${{ parameters.runAsPublic }} publishAssetsImmediately: ${{ or(parameters.publishAssetsImmediately, parameters.isAssetlessBuild) }} diff --git a/eng/common/core-templates/jobs/source-build.yml b/eng/common/core-templates/jobs/source-build.yml index df24c948ba..d92860cba2 100644 --- a/eng/common/core-templates/jobs/source-build.yml +++ b/eng/common/core-templates/jobs/source-build.yml @@ -2,12 +2,6 @@ parameters: # This template adds arcade-powered source-build to CI. A job is created for each platform, as # well as an optional server job that completes when all platform jobs complete. - # The name of the "join" job for all source-build platforms. If set to empty string, the job is - # not included. Existing repo pipelines can use this job depend on all source-build jobs - # completing without maintaining a separate list of every single job ID: just depend on this one - # server job. By default, not included. Recommended name if used: 'Source_Build_Complete'. - allCompletedJobId: '' - # See /eng/common/core-templates/job/source-build.yml jobNamePrefix: 'Source_Build' @@ -31,16 +25,6 @@ parameters: jobs: -- ${{ if ne(parameters.allCompletedJobId, '') }}: - - job: ${{ parameters.allCompletedJobId }} - displayName: Source-Build Complete - pool: server - dependsOn: - - ${{ each platform in parameters.platforms }}: - - ${{ parameters.jobNamePrefix }}_${{ platform.name }} - - ${{ if eq(length(parameters.platforms), 0) }}: - - ${{ parameters.jobNamePrefix }}_${{ parameters.defaultManagedPlatform.name }} - - ${{ each platform in parameters.platforms }}: - template: /eng/common/core-templates/job/source-build.yml parameters: diff --git a/global.json b/global.json index e21809870e..4f0b76518e 100644 --- a/global.json +++ b/global.json @@ -33,7 +33,7 @@ "rollForward": "latestFeature" }, "msbuild-sdks": { - "Microsoft.DotNet.Arcade.Sdk": "10.0.0-beta.25374.1", + "Microsoft.DotNet.Arcade.Sdk": "10.0.0-beta.25374.3", "MSBuild.Sdk.Extras": "3.0.44" } } From f1ea405d3997a828d15f68be2c239e9053ccb038 Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Fri, 25 Jul 2025 06:33:02 +0200 Subject: [PATCH 291/541] [main] Update dependencies from microsoft/testfx (#6161) Co-authored-by: dotnet-maestro[bot] --- eng/Version.Details.xml | 8 ++++---- eng/Versions.props | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index 26094f4c02..831a61e8c2 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -17,13 +17,13 @@ https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage 01f3783a04ed68557a209cc7c1c0d25cfcc7b21e - + https://github.com/microsoft/testfx - 7d305158d16bc674ed85e897b3e5b842867877d8 + 44bbf31076f765817daccd144f05da70a5db27f1 - + https://github.com/microsoft/testfx - 7d305158d16bc674ed85e897b3e5b842867877d8 + 44bbf31076f765817daccd144f05da70a5db27f1 diff --git a/eng/Versions.props b/eng/Versions.props index 32e083dfd5..e0f159c088 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -10,7 +10,7 @@ 10.0.0-beta.25374.3 18.0.0-preview.25374.3 - 3.10.0-preview.25373.2 - 1.8.0-preview.25373.2 + 3.10.0-preview.25374.7 + 1.8.0-preview.25374.7 From ae647aeaa26428d19e808fc6acdfefc5d998fab9 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Fri, 25 Jul 2025 17:01:42 +0200 Subject: [PATCH 292/541] Stabilize TestConfigJson_WithoutRunSettings_BuildSuccess (#6173) --- .../ConfigurationSettingsTests.cs | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/ConfigurationSettingsTests.cs b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/ConfigurationSettingsTests.cs index 8637871e8b..8886430a27 100644 --- a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/ConfigurationSettingsTests.cs +++ b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/ConfigurationSettingsTests.cs @@ -208,13 +208,13 @@ public sealed class TestAssetFixture() : TestAssetFixtureBase(AcceptanceFixture. { "mstest": { "timeout": { - "assemblyInitialize": 300, - "assemblyCleanup": 300, - "classInitialize": 200, - "classCleanup": 200, - "testInitialize": 100, - "testCleanup": 100, - "test": 60, + "assemblyInitialize": 300000, + "assemblyCleanup": 300000, + "classInitialize": 200000, + "classCleanup": 200000, + "testInitialize": 100000, + "testCleanup": 100000, + "test": 60000, "useCooperativeCancellation": true }, "parallelism": { From 94209b5e456e8db85790366fff876ff74fc1cd0a Mon Sep 17 00:00:00 2001 From: dotnet bot Date: Fri, 25 Jul 2025 08:17:29 -0700 Subject: [PATCH 293/541] Localized file check-in by OneLocBuild Task: Build definition ID 1218: Build ID 2758085 --- .../MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.fr.xlf | 2 +- .../MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.it.xlf | 2 +- src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf | 6 +++--- src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf | 6 +++--- src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf | 6 +++--- 5 files changed, 11 insertions(+), 11 deletions(-) diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.fr.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.fr.xlf index 06cdb16af6..821c7fe651 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.fr.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.fr.xlf @@ -49,7 +49,7 @@ Pass 'TestContext.CancellationTokenSource.Token' argument to method call - Pass 'TestContext.CancellationTokenSource.Token' argument to method call + Passer l’argument « TestContext.CancellationTokenSource.Token » à l’appel de méthode diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.it.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.it.xlf index 77bca2130a..31788d3248 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.it.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.it.xlf @@ -49,7 +49,7 @@ Pass 'TestContext.CancellationTokenSource.Token' argument to method call - Pass 'TestContext.CancellationTokenSource.Token' argument to method call + Passare l'argomento 'TestContext.CancellationTokenSource.Token' alla chiamata al metodo diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf index 3faca25111..68b1201f73 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf @@ -434,17 +434,17 @@ Le type doit être une classe When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationTokenSource.Token to enable cooperative cancellation and respect test timeouts. - When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationTokenSource.Token to enable cooperative cancellation and respect test timeouts. + Lors de l’appel de méthodes asynchrones qui ont des surcharges acceptant un paramètre CancellationToken, préférez utiliser la surcharge avec TestContext.CancellationTokenSource.Token pour activer l’annulation collaborative et respecter les délais d’expiration des tests. Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationTokenSource.Token' - Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationTokenSource.Token' + Envisagez d’utiliser la surcharge qui accepte un CancellationToken et passe « TestContext.CancellationTokenSource.Token » Flow TestContext.CancellationToken to async operations - Flow TestContext.CancellationToken to async operations + Transmettez TestContext.CancellationToken aux opérations asynchrones diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf index d72c9512ca..7ea0d3f1b2 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf @@ -434,17 +434,17 @@ Anche il tipo che dichiara questi metodi deve rispettare le regole seguenti: When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationTokenSource.Token to enable cooperative cancellation and respect test timeouts. - When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationTokenSource.Token to enable cooperative cancellation and respect test timeouts. + Quando si chiamano metodi asincroni con overload che accettano un parametro CancellationToken, preferire l'uso dell'overload con TestContext.CancellationTokenSource.Token per abilitare l'annullamento cooperativo e rispettare i timeout di test. Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationTokenSource.Token' - Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationTokenSource.Token' + Valutare la possibilità di usare l'overload che accetta un CancellationToken e a passare 'TestContext.CancellationTokenSource.Token' Flow TestContext.CancellationToken to async operations - Flow TestContext.CancellationToken to async operations + Flusso da TestContext.CancellationToken a operazioni asincrone diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf index f6710015b2..a4888413c7 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf @@ -434,17 +434,17 @@ The type declaring these methods should also respect the following rules: When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationTokenSource.Token to enable cooperative cancellation and respect test timeouts. - When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationTokenSource.Token to enable cooperative cancellation and respect test timeouts. + 在调用包含接受 CancellationToken 参数的重载的异步方法时,建议使用 TestContext.CancellationTokenSource.Token 的重载,以启用协作取消并遵守测试超时。 Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationTokenSource.Token' - Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationTokenSource.Token' + 请考虑使用接受 CancellationToken 的重载,并传递 'TestContext.CancellationTokenSource.Token' Flow TestContext.CancellationToken to async operations - Flow TestContext.CancellationToken to async operations + 将 TestContext.CancellationToken 传递给异步操作 From 811e03b79ad207e9206e4828f0c9590a94ddfbbe Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Sat, 26 Jul 2025 07:29:31 +0200 Subject: [PATCH 294/541] [main] Update dependencies from microsoft/testfx (#6183) Co-authored-by: dotnet-maestro[bot] --- eng/Version.Details.xml | 8 ++++---- eng/Versions.props | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index 831a61e8c2..6bc417b709 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -17,13 +17,13 @@ https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage 01f3783a04ed68557a209cc7c1c0d25cfcc7b21e - + https://github.com/microsoft/testfx - 44bbf31076f765817daccd144f05da70a5db27f1 + f1ea405d3997a828d15f68be2c239e9053ccb038 - + https://github.com/microsoft/testfx - 44bbf31076f765817daccd144f05da70a5db27f1 + f1ea405d3997a828d15f68be2c239e9053ccb038 diff --git a/eng/Versions.props b/eng/Versions.props index e0f159c088..8107aa8a71 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -10,7 +10,7 @@ 10.0.0-beta.25374.3 18.0.0-preview.25374.3 - 3.10.0-preview.25374.7 - 1.8.0-preview.25374.7 + 3.10.0-preview.25374.11 + 1.8.0-preview.25374.11 From 58122f027a0ccc812b8d7ce5419f5426efc661c0 Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Sat, 26 Jul 2025 05:29:59 +0000 Subject: [PATCH 295/541] [main] Update dependencies from devdiv/DevDiv/vs-code-coverage, dotnet/arcade (#6182) [main] Update dependencies from devdiv/DevDiv/vs-code-coverage, dotnet/arcade --- eng/Version.Details.xml | 16 ++++++++-------- eng/Versions.props | 4 ++-- global.json | 2 +- 3 files changed, 11 insertions(+), 11 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index 6bc417b709..0608c50dd4 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -1,21 +1,21 @@ - + https://github.com/dotnet/arcade - 0fbc9e8711fa91e68c2bf3db376fb83b46f4ac35 + e2fed65f9c524d12c64876194ae4ce177b935bb3 - + https://github.com/dotnet/arcade - 0fbc9e8711fa91e68c2bf3db376fb83b46f4ac35 + e2fed65f9c524d12c64876194ae4ce177b935bb3 - + https://github.com/dotnet/arcade - 0fbc9e8711fa91e68c2bf3db376fb83b46f4ac35 + e2fed65f9c524d12c64876194ae4ce177b935bb3 - + https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage - 01f3783a04ed68557a209cc7c1c0d25cfcc7b21e + ce4ee3b08227666176a26a37ff3be1f93a7bc25e https://github.com/microsoft/testfx diff --git a/eng/Versions.props b/eng/Versions.props index 8107aa8a71..f6c76bc626 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -7,8 +7,8 @@ preview - 10.0.0-beta.25374.3 - 18.0.0-preview.25374.3 + 10.0.0-beta.25374.4 + 18.0.0-preview.25375.2 3.10.0-preview.25374.11 1.8.0-preview.25374.11 diff --git a/global.json b/global.json index 4f0b76518e..0966c00fae 100644 --- a/global.json +++ b/global.json @@ -33,7 +33,7 @@ "rollForward": "latestFeature" }, "msbuild-sdks": { - "Microsoft.DotNet.Arcade.Sdk": "10.0.0-beta.25374.3", + "Microsoft.DotNet.Arcade.Sdk": "10.0.0-beta.25374.4", "MSBuild.Sdk.Extras": "3.0.44" } } From ba837ecb61aa9bf52dba06cd310d95f31d4b733b Mon Sep 17 00:00:00 2001 From: Martin Costello Date: Mon, 28 Jul 2025 06:27:52 +0100 Subject: [PATCH 296/541] Fix incorrect comments (#6189) --- .../MSTest.Analyzers/StringAssertToAssertAnalyzer.cs | 2 +- .../StringAssertToAssertAnalyzerTests.cs | 12 ++++++------ 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/src/Analyzers/MSTest.Analyzers/StringAssertToAssertAnalyzer.cs b/src/Analyzers/MSTest.Analyzers/StringAssertToAssertAnalyzer.cs index a1a689fd4a..eb0f44ffaf 100644 --- a/src/Analyzers/MSTest.Analyzers/StringAssertToAssertAnalyzer.cs +++ b/src/Analyzers/MSTest.Analyzers/StringAssertToAssertAnalyzer.cs @@ -14,7 +14,7 @@ namespace MSTest.Analyzers; /// -/// MSTEST0045: Use 'Assert' instead of 'StringAssert'. +/// MSTEST0046: Use 'Assert' instead of 'StringAssert'. /// /// /// The analyzer captures StringAssert method calls and suggests using equivalent Assert methods: diff --git a/test/UnitTests/MSTest.Analyzers.UnitTests/StringAssertToAssertAnalyzerTests.cs b/test/UnitTests/MSTest.Analyzers.UnitTests/StringAssertToAssertAnalyzerTests.cs index 8930230794..7f41a59d10 100644 --- a/test/UnitTests/MSTest.Analyzers.UnitTests/StringAssertToAssertAnalyzerTests.cs +++ b/test/UnitTests/MSTest.Analyzers.UnitTests/StringAssertToAssertAnalyzerTests.cs @@ -47,7 +47,7 @@ public void MyTestMethod() await VerifyCS.VerifyCodeFixAsync( code, - // /0/Test0.cs(11,9): info MSTEST0045: Use 'Assert.Contains' instead of 'StringAssert.Contains' + // /0/Test0.cs(11,9): info MSTEST0046: Use 'Assert.Contains' instead of 'StringAssert.Contains' VerifyCS.DiagnosticIgnoringAdditionalLocations().WithLocation(0).WithArguments("Contains", "Contains"), fixedCode); } @@ -89,7 +89,7 @@ public void MyTestMethod() await VerifyCS.VerifyCodeFixAsync( code, - // /0/Test0.cs(11,9): info MSTEST0045: Use 'Assert.StartsWith' instead of 'StringAssert.StartsWith' + // /0/Test0.cs(11,9): info MSTEST0046: Use 'Assert.StartsWith' instead of 'StringAssert.StartsWith' VerifyCS.DiagnosticIgnoringAdditionalLocations().WithLocation(0).WithArguments("StartsWith", "StartsWith"), fixedCode); } @@ -131,7 +131,7 @@ public void MyTestMethod() await VerifyCS.VerifyCodeFixAsync( code, - // /0/Test0.cs(11,9): info MSTEST0045: Use 'Assert.EndsWith' instead of 'StringAssert.EndsWith' + // /0/Test0.cs(11,9): info MSTEST0046: Use 'Assert.EndsWith' instead of 'StringAssert.EndsWith' VerifyCS.DiagnosticIgnoringAdditionalLocations().WithLocation(0).WithArguments("EndsWith", "EndsWith"), fixedCode); } @@ -175,7 +175,7 @@ public void MyTestMethod() await VerifyCS.VerifyCodeFixAsync( code, - // /0/Test0.cs(12,9): info MSTEST0045: Use 'Assert.MatchesRegex' instead of 'StringAssert.Matches' + // /0/Test0.cs(12,9): info MSTEST0046: Use 'Assert.MatchesRegex' instead of 'StringAssert.Matches' VerifyCS.DiagnosticIgnoringAdditionalLocations().WithLocation(0).WithArguments("MatchesRegex", "Matches"), fixedCode); } @@ -219,7 +219,7 @@ public void MyTestMethod() await VerifyCS.VerifyCodeFixAsync( code, - // /0/Test0.cs(12,9): info MSTEST0045: Use 'Assert.DoesNotMatchRegex' instead of 'StringAssert.DoesNotMatch' + // /0/Test0.cs(12,9): info MSTEST0046: Use 'Assert.DoesNotMatchRegex' instead of 'StringAssert.DoesNotMatch' VerifyCS.DiagnosticIgnoringAdditionalLocations().WithLocation(0).WithArguments("DoesNotMatchRegex", "DoesNotMatch"), fixedCode); } @@ -261,7 +261,7 @@ public void MyTestMethod() await VerifyCS.VerifyCodeFixAsync( code, - // /0/Test0.cs(11,9): info MSTEST0045: Use 'Assert.Contains' instead of 'StringAssert.Contains' + // /0/Test0.cs(11,9): info MSTEST0046: Use 'Assert.Contains' instead of 'StringAssert.Contains' VerifyCS.DiagnosticIgnoringAdditionalLocations().WithLocation(0).WithArguments("Contains", "Contains"), fixedCode); } From 0667d906348fca34017f19d0db11781fdd3546d1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Mon, 28 Jul 2025 08:13:50 +0200 Subject: [PATCH 297/541] Fix suppressors tests (#6172) --- .../UnusedParameterSuppressorTests.cs | 64 ++++++++++++- ...cSuffixTestFixtureMethodSuppressorTests.cs | 94 +++++++++++++------ ...UseAsyncSuffixTestMethodSuppressorTests.cs | 8 +- 3 files changed, 133 insertions(+), 33 deletions(-) diff --git a/test/UnitTests/MSTest.Analyzers.UnitTests/UnusedParameterSuppressorTests.cs b/test/UnitTests/MSTest.Analyzers.UnitTests/UnusedParameterSuppressorTests.cs index df1c94ea0d..b60b8d6403 100644 --- a/test/UnitTests/MSTest.Analyzers.UnitTests/UnusedParameterSuppressorTests.cs +++ b/test/UnitTests/MSTest.Analyzers.UnitTests/UnusedParameterSuppressorTests.cs @@ -25,7 +25,7 @@ public async Task AssemblyInitializeWithUnusedTestContext_DiagnosticIsSuppressed public class SomeClass { [AssemblyInitialize] - public static void Initialize(TestContext [|context|]) + public static void Initialize(TestContext {|#0:context|}) { // TestContext parameter is unused but required by MSTest } @@ -36,12 +36,26 @@ public static void Initialize(TestContext [|context|]) await new VerifyCS.Test { TestState = { Sources = { code } }, + ExpectedDiagnostics = + { + VerifyCS.Diagnostic(WarnForUnusedParameters.Rule) + .WithLocation(0) + .WithArguments("context") + .WithIsSuppressed(false), + }, }.RunAsync(); // Verify issue is suppressed with suppressor await new TestWithSuppressor { TestState = { Sources = { code } }, + ExpectedDiagnostics = + { + VerifyCS.Diagnostic(WarnForUnusedParameters.Rule) + .WithLocation(0) + .WithArguments("context") + .WithIsSuppressed(true), + }, }.RunAsync(); } @@ -55,7 +69,7 @@ public async Task ClassInitializeWithUnusedTestContext_DiagnosticIsSuppressed() public class SomeClass { [ClassInitialize] - public static void Initialize(TestContext [|context|]) + public static void Initialize(TestContext {|#0:context|}) { // TestContext parameter is unused but required by MSTest } @@ -66,12 +80,26 @@ public static void Initialize(TestContext [|context|]) await new VerifyCS.Test { TestState = { Sources = { code } }, + ExpectedDiagnostics = + { + VerifyCS.Diagnostic(WarnForUnusedParameters.Rule) + .WithLocation(0) + .WithArguments("context") + .WithIsSuppressed(false), + }, }.RunAsync(); // Verify issue is suppressed with suppressor await new TestWithSuppressor { TestState = { Sources = { code } }, + ExpectedDiagnostics = + { + VerifyCS.Diagnostic(WarnForUnusedParameters.Rule) + .WithLocation(0) + .WithArguments("context") + .WithIsSuppressed(true), + }, }.RunAsync(); } @@ -85,7 +113,7 @@ public async Task TestMethodWithUnusedParameter_DiagnosticIsNotSuppressed() public class SomeClass { [TestMethod] - public void TestMethod(int [|unusedParam|]) + public void TestMethod(int {|#0:unusedParam|}) { // This should not be suppressed } @@ -96,12 +124,26 @@ public void TestMethod(int [|unusedParam|]) await new VerifyCS.Test { TestState = { Sources = { code } }, + ExpectedDiagnostics = + { + VerifyCS.Diagnostic(WarnForUnusedParameters.Rule) + .WithLocation(0) + .WithArguments("unusedParam") + .WithIsSuppressed(false), + }, }.RunAsync(); // Verify issue is still reported with suppressor (not suppressed) await new TestWithSuppressor { TestState = { Sources = { code } }, + ExpectedDiagnostics = + { + VerifyCS.Diagnostic(WarnForUnusedParameters.Rule) + .WithLocation(0) + .WithArguments("unusedParam") + .WithIsSuppressed(false), + }, }.RunAsync(); } @@ -114,7 +156,7 @@ public async Task RegularMethodWithUnusedTestContext_DiagnosticIsNotSuppressed() [TestClass] public class SomeClass { - public void RegularMethod(TestContext [|context|]) + public void RegularMethod(TestContext {|#0:context|}) { // This should not be suppressed as it's not AssemblyInitialize or ClassInitialize } @@ -125,12 +167,26 @@ public void RegularMethod(TestContext [|context|]) await new VerifyCS.Test { TestState = { Sources = { code } }, + ExpectedDiagnostics = + { + VerifyCS.Diagnostic(WarnForUnusedParameters.Rule) + .WithLocation(0) + .WithArguments("context") + .WithIsSuppressed(false), + }, }.RunAsync(); // Verify issue is still reported with suppressor (not suppressed) await new TestWithSuppressor { TestState = { Sources = { code } }, + ExpectedDiagnostics = + { + VerifyCS.Diagnostic(WarnForUnusedParameters.Rule) + .WithLocation(0) + .WithArguments("context") + .WithIsSuppressed(false), + }, }.RunAsync(); } diff --git a/test/UnitTests/MSTest.Analyzers.UnitTests/UseAsyncSuffixTestFixtureMethodSuppressorTests.cs b/test/UnitTests/MSTest.Analyzers.UnitTests/UseAsyncSuffixTestFixtureMethodSuppressorTests.cs index b75ac12800..8badc85830 100644 --- a/test/UnitTests/MSTest.Analyzers.UnitTests/UseAsyncSuffixTestFixtureMethodSuppressorTests.cs +++ b/test/UnitTests/MSTest.Analyzers.UnitTests/UseAsyncSuffixTestFixtureMethodSuppressorTests.cs @@ -26,22 +26,22 @@ public async Task AsyncTestFixtureMethodsWithoutSuffix_DiagnosticIsSuppressed() public class SomeClass { [AssemblyInitialize] - public static async Task [|AssemblyInitialize|]() { } + public static async Task {|#0:AssemblyInitialize|}() { } [AssemblyCleanup] - public static async Task [|AssemblyCleanup|]() { } + public static async Task {|#1:AssemblyCleanup|}() { } [ClassInitialize] - public static async Task [|ClassInitialize|]() { } + public static async Task {|#2:ClassInitialize|}() { } [ClassCleanup] - public static async Task [|ClassCleanup|]() { } + public static async Task {|#3:ClassCleanup|}() { } [TestInitialize] - public async Task [|TestInitialize|]() { } + public async Task {|#4:TestInitialize|}() { } [TestCleanup] - public async Task [|TestCleanup|]() { } + public async Task {|#5:TestCleanup|}() { } } "; @@ -49,11 +49,53 @@ public class SomeClass await new VerifyCS.Test { TestState = { Sources = { code } }, + ExpectedDiagnostics = + { + VerifyCS.Diagnostic(WarnForMissingAsyncSuffix.Rule) + .WithLocation(0) + .WithIsSuppressed(false), + VerifyCS.Diagnostic(WarnForMissingAsyncSuffix.Rule) + .WithLocation(1) + .WithIsSuppressed(false), + VerifyCS.Diagnostic(WarnForMissingAsyncSuffix.Rule) + .WithLocation(2) + .WithIsSuppressed(false), + VerifyCS.Diagnostic(WarnForMissingAsyncSuffix.Rule) + .WithLocation(3) + .WithIsSuppressed(false), + VerifyCS.Diagnostic(WarnForMissingAsyncSuffix.Rule) + .WithLocation(4) + .WithIsSuppressed(false), + VerifyCS.Diagnostic(WarnForMissingAsyncSuffix.Rule) + .WithLocation(5) + .WithIsSuppressed(false), + }, }.RunAsync(); await new TestWithSuppressor { TestState = { Sources = { code } }, + ExpectedDiagnostics = + { + VerifyCS.Diagnostic(WarnForMissingAsyncSuffix.Rule) + .WithLocation(0) + .WithIsSuppressed(true), + VerifyCS.Diagnostic(WarnForMissingAsyncSuffix.Rule) + .WithLocation(1) + .WithIsSuppressed(true), + VerifyCS.Diagnostic(WarnForMissingAsyncSuffix.Rule) + .WithLocation(2) + .WithIsSuppressed(true), + VerifyCS.Diagnostic(WarnForMissingAsyncSuffix.Rule) + .WithLocation(3) + .WithIsSuppressed(true), + VerifyCS.Diagnostic(WarnForMissingAsyncSuffix.Rule) + .WithLocation(4) + .WithIsSuppressed(true), + VerifyCS.Diagnostic(WarnForMissingAsyncSuffix.Rule) + .WithLocation(5) + .WithIsSuppressed(true), + }, }.RunAsync(); } @@ -61,33 +103,31 @@ public class SomeClass public async Task AsyncTestMethodWithSuffix_NoDiagnostic() { string code = """ + using System.Threading.Tasks; + using Microsoft.VisualStudio.TestTools.UnitTesting; - using System.Threading.Tasks; - using Microsoft.VisualStudio.TestTools.UnitTesting; - - [TestClass] - public class SomeClass - { - [AssemblyInitialize] - public static async Task AssemblyInitializeAsync() { } - - [AssemblyCleanup] - public static async Task AssemblyCleanupAsync() { } + [TestClass] + public class SomeClass + { + [AssemblyInitialize] + public static async Task AssemblyInitializeAsync() { } - [ClassInitialize] - public static async Task ClassInitializeAsync() { } + [AssemblyCleanup] + public static async Task AssemblyCleanupAsync() { } - [ClassCleanup] - public static async Task ClassCleanupAsync() { } + [ClassInitialize] + public static async Task ClassInitializeAsync() { } - [TestInitialize] - public async Task TestInitializeAsync() { } + [ClassCleanup] + public static async Task ClassCleanupAsync() { } - [TestCleanup] - public async Task TestCleanupAsync() { } - } + [TestInitialize] + public async Task TestInitializeAsync() { } - """; + [TestCleanup] + public async Task TestCleanupAsync() { } + } + """; await new VerifyCS.Test { diff --git a/test/UnitTests/MSTest.Analyzers.UnitTests/UseAsyncSuffixTestMethodSuppressorTests.cs b/test/UnitTests/MSTest.Analyzers.UnitTests/UseAsyncSuffixTestMethodSuppressorTests.cs index 1bd51439f4..95acdb7338 100644 --- a/test/UnitTests/MSTest.Analyzers.UnitTests/UseAsyncSuffixTestMethodSuppressorTests.cs +++ b/test/UnitTests/MSTest.Analyzers.UnitTests/UseAsyncSuffixTestMethodSuppressorTests.cs @@ -28,7 +28,7 @@ public async Task AsyncTestMethodWithoutSuffix_DiagnosticIsSuppressed() public class SomeClass { [TestMethod] - public async Task [|TestMethod|]() { } + public async Task {|#0:TestMethod|}() { } } """; @@ -37,11 +37,13 @@ public class SomeClass await new VerifyCS.Test { TestState = { Sources = { code } }, + ExpectedDiagnostics = { VerifyCS.Diagnostic(WarnForMissingAsyncSuffix.Rule).WithLocation(0).WithIsSuppressed(false) }, }.RunAsync(); await new TestWithSuppressor { TestState = { Sources = { code } }, + ExpectedDiagnostics = { VerifyCS.Diagnostic(WarnForMissingAsyncSuffix.Rule).WithLocation(0).WithIsSuppressed(true) }, }.RunAsync(); } @@ -58,7 +60,7 @@ public async Task AsyncDataTestMethodWithoutSuffix_DiagnosticIsSuppressed() public class SomeClass { [DataTestMethod, DataRow(0)] - public async Task [|TestMethod|](int arg) { } + public async Task {|#0:TestMethod|}(int arg) { } } """; @@ -66,11 +68,13 @@ public class SomeClass await new VerifyCS.Test { TestState = { Sources = { code } }, + ExpectedDiagnostics = { VerifyCS.Diagnostic(WarnForMissingAsyncSuffix.Rule).WithLocation(0).WithIsSuppressed(false) }, }.RunAsync(); await new TestWithSuppressor { TestState = { Sources = { code } }, + ExpectedDiagnostics = { VerifyCS.Diagnostic(WarnForMissingAsyncSuffix.Rule).WithLocation(0).WithIsSuppressed(true) }, }.RunAsync(); } From 1eea4a371cfe62ba7c5ecbf1ed739c3b59e547cc Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Mon, 28 Jul 2025 09:06:32 +0200 Subject: [PATCH 298/541] Fix TestDifferentGenericMethodTestCases flakiness (#6192) --- .../GenericTestMethodTests.cs | 34 +++++++++---------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/GenericTestMethodTests.cs b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/GenericTestMethodTests.cs index 341830621f..99ee91910a 100644 --- a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/GenericTestMethodTests.cs +++ b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/GenericTestMethodTests.cs @@ -20,55 +20,55 @@ public async Task TestDifferentGenericMethodTestCases() testHostResult.AssertExitCodeIs(ExitCodes.AtLeastOneTestFailed); testHostResult.AssertOutputMatchesRegex( """ - failed AMethodWithBadConstraints \(0\) \(\d+ms\) + failed AMethodWithBadConstraints \(0\) \((\d+s )?\d+ms\) GenericArguments\[0], 'System\.Int32', on 'Void AMethodWithBadConstraints\[T]\(T\)' violates the constraint of type 'T'\. .+? - failed NonParameterizedTestMethod \(\d+ms\) + failed NonParameterizedTestMethod \((\d+s )?\d+ms\) The generic test method 'NonParameterizedTestMethod' doesn't have arguments, so the generic parameter cannot be inferred\. .+? - failed ParameterizedMethodSimple \(1\) \(\d+ms\) + failed ParameterizedMethodSimple \(1\) \((\d+s )?\d+ms\) Assert\.Fail failed\. Test method 'ParameterizedMethodSimple' did run with parameter '1' and type 'System\.Byte'\. .+? - failed ParameterizedMethodSimple \(2\) \(\d+ms\) + failed ParameterizedMethodSimple \(2\) \((\d+s )?\d+ms\) Assert\.Fail failed\. Test method 'ParameterizedMethodSimple' did run with parameter '2' and type 'System\.Int32'\. .+? - failed ParameterizedMethodSimple \("Hello world"\) \(\d+ms\) + failed ParameterizedMethodSimple \("Hello world"\) \((\d+s )?\d+ms\) Assert\.Fail failed\. Test method 'ParameterizedMethodSimple' did run with parameter 'Hello world' and type 'System\.String'\. .+? - failed ParameterizedMethodSimple \(null\) \(\d+ms\) + failed ParameterizedMethodSimple \(null\) \((\d+s )?\d+ms\) Test method TestClass\.ParameterizedMethodSimple threw exception: System\.InvalidOperationException: The type of the generic parameter 'T' could not be inferred\. - failed ParameterizedMethodTwoGenericParametersAndFourMethodParameters \(1,"Hello world",2,3\) \(\d+ms\) + failed ParameterizedMethodTwoGenericParametersAndFourMethodParameters \(1,"Hello world",2,3\) \((\d+s )?\d+ms\) Test method TestClass\.ParameterizedMethodTwoGenericParametersAndFourMethodParameters threw exception: System\.InvalidOperationException: Found two conflicting types for generic parameter 'T2'\. The conflicting types are 'System\.Byte' and 'System\.Int32'\. - failed ParameterizedMethodTwoGenericParametersAndFourMethodParameters \(null,"Hello world","Hello again",3\) \(\d+ms\) + failed ParameterizedMethodTwoGenericParametersAndFourMethodParameters \(null,"Hello world","Hello again",3\) \((\d+s )?\d+ms\) Assert\.Fail failed\. Test method 'ParameterizedMethodTwoGenericParametersAndFourMethodParameters' did run with parameters '', 'Hello world', 'Hello again', '3' and generic types 'System\.Int32', 'System\.String'\. .+? - failed ParameterizedMethodTwoGenericParametersAndFourMethodParameters \("Hello hello","Hello world",null,null\) \(\d+ms\) + failed ParameterizedMethodTwoGenericParametersAndFourMethodParameters \("Hello hello","Hello world",null,null\) \((\d+s )?\d+ms\) Test method TestClass\.ParameterizedMethodTwoGenericParametersAndFourMethodParameters threw exception: System\.InvalidOperationException: The type of the generic parameter 'T1' could not be inferred\. - failed ParameterizedMethodTwoGenericParametersAndFourMethodParameters \(null,null,null,null\) \(\d+ms\) + failed ParameterizedMethodTwoGenericParametersAndFourMethodParameters \(null,null,null,null\) \((\d+s )?\d+ms\) Test method TestClass\.ParameterizedMethodTwoGenericParametersAndFourMethodParameters threw exception: System\.InvalidOperationException: The type of the generic parameter 'T1' could not be inferred\. - failed ParameterizedMethodSimpleParams \(1\) \(\d+ms\) + failed ParameterizedMethodSimpleParams \(1\) \((\d+s )?\d+ms\) Cannot create an instance of T\[] because Type\.ContainsGenericParameters is true\. .+? - failed ParameterizedMethodSimpleParams \(1,2\) \(\d+ms\) + failed ParameterizedMethodSimpleParams \(1,2\) \((\d+s )?\d+ms\) Cannot create an instance of T\[] because Type\.ContainsGenericParameters is true\. .+? - failed ParameterizedMethodSimpleParams \("Hello world"\) \(\d+ms\) + failed ParameterizedMethodSimpleParams \("Hello world"\) \((\d+s )?\d+ms\) Cannot create an instance of T\[] because Type\.ContainsGenericParameters is true\. .+? - failed ParameterizedMethodSimpleParams \(null\) \(\d+ms\) + failed ParameterizedMethodSimpleParams \(null\) \((\d+s )?\d+ms\) Cannot create an instance of T\[] because Type\.ContainsGenericParameters is true\. .+? - failed ParameterizedMethodSimpleParams \(null,"Hello world"\) \(\d+ms\) + failed ParameterizedMethodSimpleParams \(null,"Hello world"\) \((\d+s )?\d+ms\) Cannot create an instance of T\[] because Type\.ContainsGenericParameters is true\. .+? - failed ParameterizedMethodWithNestedGeneric \(System\.Collections\.Generic\.List`1\[System.String],System\.Collections\.Generic\.List`1\[System.String]\) \(\d+ms\) + failed ParameterizedMethodWithNestedGeneric \(System\.Collections\.Generic\.List`1\[System.String],System\.Collections\.Generic\.List`1\[System.String]\) \((\d+s )?\d+ms\) Assert\.Fail failed\. Test method 'ParameterizedMethodWithNestedGeneric' did run with first list \[Hello, World] and second list \[Unit, Testing] .+? - failed ParameterizedMethodWithNestedGeneric \(System\.Collections\.Generic\.List`1\[System.Int32],System\.Collections\.Generic\.List`1\[System.Int32]\) \(\d+ms\) + failed ParameterizedMethodWithNestedGeneric \(System\.Collections\.Generic\.List`1\[System.Int32],System\.Collections\.Generic\.List`1\[System.Int32]\) \((\d+s )?\d+ms\) Assert\.Fail failed\. Test method 'ParameterizedMethodWithNestedGeneric' did run with first list \[0, 1] and second list \[2, 3] .+? """, RegexOptions.Singleline); From 6036b30f449247e89bfbcd479e16dda7d43d5417 Mon Sep 17 00:00:00 2001 From: Copilot <198982749+Copilot@users.noreply.github.com> Date: Mon, 28 Jul 2025 10:22:02 +0200 Subject: [PATCH 299/541] Fix codefix behavior for partial classes with TestCleanup and Dispose in different parts (#6164) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: Evangelink <11340282+Evangelink@users.noreply.github.com> Co-authored-by: Amaury Levé --- .../PreferDisposeOverTestCleanupFixer.cs | 67 +++++++-- ...eferDisposeOverTestCleanupAnalyzerTests.cs | 137 +++++++++++++++++- 2 files changed, 189 insertions(+), 15 deletions(-) diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/PreferDisposeOverTestCleanupFixer.cs b/src/Analyzers/MSTest.Analyzers.CodeFixes/PreferDisposeOverTestCleanupFixer.cs index af071e4a07..309ccadb67 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/PreferDisposeOverTestCleanupFixer.cs +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/PreferDisposeOverTestCleanupFixer.cs @@ -69,7 +69,7 @@ private static bool IsTestCleanupMethodValid(MethodDeclarationSyntax methodDecla methodDeclaration.ReturnType is PredefinedTypeSyntax predefinedType && predefinedType.Keyword.IsKind(SyntaxKind.VoidKeyword); - private static async Task AddDisposeAndBaseClassAsync( + private static async Task AddDisposeAndBaseClassAsync( Document document, MethodDeclarationSyntax testCleanupMethod, TypeDeclarationSyntax containingType, @@ -84,18 +84,50 @@ private static async Task AddDisposeAndBaseClassAsync( INamedTypeSymbol? iDisposableSymbol = semanticModel.Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemIDisposable); // Move the code from TestCleanup to Dispose method - MethodDeclarationSyntax? existingDisposeMethod = containingType.Members - .OfType() - .FirstOrDefault(m => semanticModel.GetDeclaredSymbol(m) is IMethodSymbol methodSymbol && methodSymbol.IsDisposeImplementation(iDisposableSymbol)); + // For partial classes, we need to check all parts of the type, not just the current partial declaration + Document? disposeDocument = null; + MethodDeclarationSyntax? existingDisposeMethod = null; + if (semanticModel.GetDeclaredSymbol(containingType, cancellationToken) is INamedTypeSymbol typeSymbol) + { + // Find existing Dispose method in any part of the partial class + IMethodSymbol? existingDisposeSymbol = typeSymbol.GetMembers("Dispose") + .OfType() + .FirstOrDefault(m => m.IsDisposeImplementation(iDisposableSymbol)); + + if (existingDisposeSymbol is not null) + { + // Find the syntax node for the existing Dispose method + foreach (SyntaxReference syntaxRef in existingDisposeSymbol.DeclaringSyntaxReferences) + { + if (await syntaxRef.GetSyntaxAsync(cancellationToken).ConfigureAwait(false) is MethodDeclarationSyntax methodSyntax) + { + existingDisposeMethod = methodSyntax; + // Find the document containing the Dispose method + foreach (Document projectDocument in document.Project.Documents) + { + SyntaxTree? docSyntaxTree = await projectDocument.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); + if (docSyntaxTree == syntaxRef.SyntaxTree) + { + disposeDocument = projectDocument; + break; + } + } + + break; + } + } + } + } BlockSyntax? cleanupBody = testCleanupMethod.Body; + Solution solution = document.Project.Solution; - if (existingDisposeMethod != null) + if (existingDisposeMethod is not null && disposeDocument is not null) { // Append the TestCleanup body to the existing Dispose method StatementSyntax[]? cleanupStatements = cleanupBody?.Statements.ToArray(); MethodDeclarationSyntax newDisposeMethod; - if (existingDisposeMethod.Body != null) + if (existingDisposeMethod.Body is not null) { BlockSyntax newDisposeBody = existingDisposeMethod.Body.AddStatements(cleanupStatements ?? []); newDisposeMethod = existingDisposeMethod.WithBody(newDisposeBody); @@ -105,8 +137,24 @@ private static async Task AddDisposeAndBaseClassAsync( newDisposeMethod = existingDisposeMethod.WithBody(cleanupBody); } - editor.ReplaceNode(existingDisposeMethod, newDisposeMethod); - editor.RemoveNode(testCleanupMethod); + if (disposeDocument.Id == document.Id) + { + // Both methods are in the same document, use single editor + editor.ReplaceNode(existingDisposeMethod, newDisposeMethod); + editor.RemoveNode(testCleanupMethod); + solution = solution.WithDocumentSyntaxRoot(document.Id, editor.GetChangedRoot()); + } + else + { + // Methods are in different documents, use separate editors + DocumentEditor disposeEditor = await DocumentEditor.CreateAsync(disposeDocument, cancellationToken).ConfigureAwait(false); + disposeEditor.ReplaceNode(existingDisposeMethod, newDisposeMethod); + solution = solution.WithDocumentSyntaxRoot(disposeDocument.Id, disposeEditor.GetChangedRoot()); + + // Remove the TestCleanup method from the current document + editor.RemoveNode(testCleanupMethod); + solution = solution.WithDocumentSyntaxRoot(document.Id, editor.GetChangedRoot()); + } } else { @@ -122,9 +170,10 @@ private static async Task AddDisposeAndBaseClassAsync( } editor.ReplaceNode(containingType, newParent); + solution = solution.WithDocumentSyntaxRoot(document.Id, editor.GetChangedRoot()); } - return editor.GetChangedDocument(); + return solution; } private static bool ImplementsIDisposable(TypeDeclarationSyntax typeDeclaration, INamedTypeSymbol iDisposableSymbol, SemanticModel semanticModel) diff --git a/test/UnitTests/MSTest.Analyzers.UnitTests/PreferDisposeOverTestCleanupAnalyzerTests.cs b/test/UnitTests/MSTest.Analyzers.UnitTests/PreferDisposeOverTestCleanupAnalyzerTests.cs index 1c6934bd3e..16a8b62191 100644 --- a/test/UnitTests/MSTest.Analyzers.UnitTests/PreferDisposeOverTestCleanupAnalyzerTests.cs +++ b/test/UnitTests/MSTest.Analyzers.UnitTests/PreferDisposeOverTestCleanupAnalyzerTests.cs @@ -161,7 +161,7 @@ public void Dispose() [TestMethod] public async Task WhenTestClassHasTestCleanup_AndHasDisposeInAnotherPartial_Diagnostic() { - // This scenario is currently broken. The test is to document the current behavior + // This scenario should now work correctly after fixing the codefix string code = """ using Microsoft.VisualStudio.TestTools.UnitTesting; using System; @@ -194,21 +194,146 @@ public partial class MyTestClass : IDisposable public void Dispose() { int x = 1; + int y = 1; } } [TestClass] - public partial class MyTestClass : IDisposable + public partial class MyTestClass { - public void {|CS0111:Dispose|}() - { - int y = 1; - } } """; await VerifyCS.VerifyCodeFixAsync(code, fixedCode); } + [TestMethod] + public async Task WhenTestClassHasTestCleanup_AndHasDisposeInAnotherPartialInDifferentFile_Diagnostic() + { + var test = new VerifyCS.Test + { + TestState = + { + Sources = + { + @" +using Microsoft.VisualStudio.TestTools.UnitTesting; +using System; + +public partial class MyTestClass : IDisposable +{ + public void Dispose() + { + int x = 1; + } +}", + @" +using Microsoft.VisualStudio.TestTools.UnitTesting; + +[TestClass] +public partial class MyTestClass +{ + [TestCleanup] + public void [|MyTestCleanup|]() + { + int y = 1; + } +}", + }, + }, + FixedState = + { + Sources = + { + @" +using Microsoft.VisualStudio.TestTools.UnitTesting; +using System; + +public partial class MyTestClass : IDisposable +{ + public void Dispose() + { + int x = 1; + int y = 1; + } +}", + @" +using Microsoft.VisualStudio.TestTools.UnitTesting; + +[TestClass] +public partial class MyTestClass +{ +}", + }, + }, + }; + + await test.RunAsync(); + } + + [TestMethod] + public async Task WhenTestClassHasTestCleanup_AndHasDisposeInAnotherPartialInDifferentFile_ReversedOrder_Diagnostic() + { + var test = new VerifyCS.Test + { + TestState = + { + Sources = + { + @" +using Microsoft.VisualStudio.TestTools.UnitTesting; + +[TestClass] +public partial class MyTestClass +{ + [TestCleanup] + public void [|MyTestCleanup|]() + { + int y = 1; + } +}", + @" +using Microsoft.VisualStudio.TestTools.UnitTesting; +using System; + +public partial class MyTestClass : IDisposable +{ + public void Dispose() + { + int x = 1; + } +}", + }, + }, + FixedState = + { + Sources = + { + @" +using Microsoft.VisualStudio.TestTools.UnitTesting; + +[TestClass] +public partial class MyTestClass +{ +}", + @" +using Microsoft.VisualStudio.TestTools.UnitTesting; +using System; + +public partial class MyTestClass : IDisposable +{ + public void Dispose() + { + int x = 1; + int y = 1; + } +}", + }, + }, + }; + + await test.RunAsync(); + } + [TestMethod] public async Task WhenTestClassHasTestCleanupTask_Diagnostic() { From 1d2304b83304e99a0712fe8a90bcbd30711ec374 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Mon, 28 Jul 2025 10:35:46 +0200 Subject: [PATCH 300/541] Add missing `Func` overload to ThrowsExactly (#6195) --- .../Assertions/Assert.ThrowsException.cs | 12 ++++++++++++ .../TestFramework/PublicAPI/PublicAPI.Unshipped.txt | 2 ++ .../Assertions/AssertTests.ThrowsExceptionTests.cs | 12 ++++++++++++ 3 files changed, 26 insertions(+) diff --git a/src/TestFramework/TestFramework/Assertions/Assert.ThrowsException.cs b/src/TestFramework/TestFramework/Assertions/Assert.ThrowsException.cs index 3ae76b2c63..b02272b50a 100644 --- a/src/TestFramework/TestFramework/Assertions/Assert.ThrowsException.cs +++ b/src/TestFramework/TestFramework/Assertions/Assert.ThrowsException.cs @@ -103,6 +103,11 @@ public AssertThrowsExactlyInterpolatedStringHandler(int literalLength, int forma } } + public AssertThrowsExactlyInterpolatedStringHandler(int literalLength, int formattedCount, Func action, out bool shouldAppend) + : this(literalLength, formattedCount, (Action)(() => _ = action()), out shouldAppend) + { + } + internal TException ComputeAssertion() { if (_state.FailAction is not null) @@ -300,6 +305,13 @@ public static TException ThrowsExactly(Action action, [InterpolatedS where TException : Exception => message.ComputeAssertion(); + /// +#pragma warning disable IDE0060 // Remove unused parameter - https://github.com/dotnet/roslyn/issues/76578 + public static TException ThrowsExactly(Func action, [InterpolatedStringHandlerArgument(nameof(action))] ref AssertThrowsExactlyInterpolatedStringHandler message) +#pragma warning restore IDE0060 // Remove unused parameter + where TException : Exception + => message.ComputeAssertion(); + /// /// Tests whether the code specified by delegate throws exact given exception /// of type (and not of derived type) and throws AssertFailedException diff --git a/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Unshipped.txt b/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Unshipped.txt index 71d9a68b4f..0abf8e4d29 100644 --- a/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Unshipped.txt +++ b/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Unshipped.txt @@ -1,5 +1,6 @@ #nullable enable Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AssertNonStrictThrowsInterpolatedStringHandler.AssertNonStrictThrowsInterpolatedStringHandler(int literalLength, int formattedCount, System.Func! action, out bool shouldAppend) -> void +Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AssertThrowsExactlyInterpolatedStringHandler.AssertThrowsExactlyInterpolatedStringHandler(int literalLength, int formattedCount, System.Func! action, out bool shouldAppend) -> void Microsoft.VisualStudio.TestTools.UnitTesting.CIConditionAttribute Microsoft.VisualStudio.TestTools.UnitTesting.CIConditionAttribute.CIConditionAttribute(Microsoft.VisualStudio.TestTools.UnitTesting.ConditionMode mode) -> void Microsoft.VisualStudio.TestTools.UnitTesting.ConditionBaseAttribute.Mode.get -> Microsoft.VisualStudio.TestTools.UnitTesting.ConditionMode @@ -36,6 +37,7 @@ static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.MatchesRegex(System.T static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.StartsWith(string? substring, string? value, string! message = "") -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.StartsWith(string? substring, string? value, System.StringComparison comparisonType, string! message = "") -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.Throws(System.Func! action, ref Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AssertNonStrictThrowsInterpolatedStringHandler message) -> TException! +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.ThrowsExactly(System.Func! action, ref Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AssertThrowsExactlyInterpolatedStringHandler message) -> TException! static Microsoft.VisualStudio.TestTools.UnitTesting.CollectionAssert.Instance.get -> Microsoft.VisualStudio.TestTools.UnitTesting.CollectionAssert! static Microsoft.VisualStudio.TestTools.UnitTesting.StringAssert.Instance.get -> Microsoft.VisualStudio.TestTools.UnitTesting.StringAssert! *REMOVED*static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.Contains(System.Collections.Generic.IEnumerable! collection, System.Func! predicate, string? message) -> void diff --git a/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.ThrowsExceptionTests.cs b/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.ThrowsExceptionTests.cs index e409bae51c..6ce17da296 100644 --- a/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.ThrowsExceptionTests.cs +++ b/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.ThrowsExceptionTests.cs @@ -214,6 +214,18 @@ public void Throws_WithInterpolation() Verify(ex2 is not null); } + public void ThrowsExactly_WithInterpolation() + { + static string GetString() => throw new Exception(); + +#pragma warning disable IDE0200 // Remove unnecessary lambda expression - intentionally testing overload resolution for this case. + Exception ex = Assert.ThrowsExactly(() => GetString(), $"Hello {GetString()}"); +#pragma warning restore IDE0200 // Remove unnecessary lambda expression + Exception ex2 = Assert.ThrowsExactly(GetString, $"Hello {GetString()}"); + Verify(ex is not null); + Verify(ex2 is not null); + } + public void ThrowsExactly_WhenExceptionIsDerivedFromExpectedType_ShouldThrow() { static void Action() => Assert.ThrowsExactly(() => throw new ArgumentNullException()); From a682b53c5f5b323e724a3468effe9739b26d62a5 Mon Sep 17 00:00:00 2001 From: Copilot <198982749+Copilot@users.noreply.github.com> Date: Mon, 28 Jul 2025 10:38:12 +0200 Subject: [PATCH 301/541] Fix MSTEST0037 to report on Assert.IsFalse with string and collection methods (#6178) Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: Evangelink <11340282+Evangelink@users.noreply.github.com> --- .../UseProperAssertMethodsAnalyzer.cs | 74 ++++++++++-- .../UseProperAssertMethodsAnalyzerTests.cs | 111 +++++++++++++++++- 2 files changed, 167 insertions(+), 18 deletions(-) diff --git a/src/Analyzers/MSTest.Analyzers/UseProperAssertMethodsAnalyzer.cs b/src/Analyzers/MSTest.Analyzers/UseProperAssertMethodsAnalyzer.cs index 5859cacb41..7b49b0bc40 100644 --- a/src/Analyzers/MSTest.Analyzers/UseProperAssertMethodsAnalyzer.cs +++ b/src/Analyzers/MSTest.Analyzers/UseProperAssertMethodsAnalyzer.cs @@ -48,11 +48,21 @@ namespace MSTest.Analyzers; /// /// /// +/// Assert.IsFalse(myString.[StartsWith|EndsWith|Contains]("...")) +/// +/// +/// +/// /// Assert.IsTrue(myCollection.Contains(...)) /// /// /// /// +/// Assert.IsFalse(myCollection.Contains(...)) +/// +/// +/// +/// /// Assert.[IsTrue|IsFalse](x [>|>=|<|<=] y) /// /// @@ -518,8 +528,7 @@ private static void AnalyzeIsTrueOrIsFalseInvocation(OperationAnalysisContext co StringMethodCheckStatus stringMethodStatus = RecognizeStringMethodCheck(conditionArgument, out SyntaxNode? stringExpr, out SyntaxNode? substringExpr); if (stringMethodStatus != StringMethodCheckStatus.Unknown) { - // For string methods, we only suggest when the condition is positive (IsTrue) - // Assert.IsFalse(str.StartsWith(...)) could suggest Assert.DoesNotStartWith, but that's less common + // Handle both IsTrue and IsFalse cases with string methods if (isTrueInvocation) { string properAssertMethod = stringMethodStatus switch @@ -541,29 +550,70 @@ private static void AnalyzeIsTrueOrIsFalseInvocation(OperationAnalysisContext co "IsTrue")); return; } - } - - // Check for collection method patterns: myCollection.Contains(...) - CollectionCheckStatus collectionMethodStatus = RecognizeCollectionMethodCheck(conditionArgument, out SyntaxNode? collectionExpr, out SyntaxNode? itemExpr); - if (collectionMethodStatus != CollectionCheckStatus.Unknown) - { - if (isTrueInvocation && collectionMethodStatus == CollectionCheckStatus.Contains) + else { - string properAssertMethod = "Contains"; + // For IsFalse with string methods, suggest the negative assertions + string properAssertMethod = stringMethodStatus switch + { + StringMethodCheckStatus.StartsWith => "DoesNotStartWith", + StringMethodCheckStatus.EndsWith => "DoesNotEndWith", + StringMethodCheckStatus.Contains => "DoesNotContain", + _ => throw new InvalidOperationException("Unexpected StringMethodCheckStatus value."), + }; ImmutableDictionary.Builder properties = ImmutableDictionary.CreateBuilder(); properties.Add(ProperAssertMethodNameKey, properAssertMethod); properties.Add(CodeFixModeKey, CodeFixModeAddArgument); context.ReportDiagnostic(context.Operation.CreateDiagnostic( Rule, - additionalLocations: ImmutableArray.Create(conditionArgument.Syntax.GetLocation(), itemExpr!.GetLocation(), collectionExpr!.GetLocation()), + additionalLocations: ImmutableArray.Create(conditionArgument.Syntax.GetLocation(), substringExpr!.GetLocation(), stringExpr!.GetLocation()), properties: properties.ToImmutable(), properAssertMethod, - "IsTrue")); + "IsFalse")); return; } } + // Check for collection method patterns: myCollection.Contains(...) + CollectionCheckStatus collectionMethodStatus = RecognizeCollectionMethodCheck(conditionArgument, out SyntaxNode? collectionExpr, out SyntaxNode? itemExpr); + if (collectionMethodStatus != CollectionCheckStatus.Unknown) + { + if (collectionMethodStatus == CollectionCheckStatus.Contains) + { + if (isTrueInvocation) + { + string properAssertMethod = "Contains"; + + ImmutableDictionary.Builder properties = ImmutableDictionary.CreateBuilder(); + properties.Add(ProperAssertMethodNameKey, properAssertMethod); + properties.Add(CodeFixModeKey, CodeFixModeAddArgument); + context.ReportDiagnostic(context.Operation.CreateDiagnostic( + Rule, + additionalLocations: ImmutableArray.Create(conditionArgument.Syntax.GetLocation(), itemExpr!.GetLocation(), collectionExpr!.GetLocation()), + properties: properties.ToImmutable(), + properAssertMethod, + "IsTrue")); + return; + } + else + { + // For IsFalse with collection Contains, suggest DoesNotContain + string properAssertMethod = "DoesNotContain"; + + ImmutableDictionary.Builder properties = ImmutableDictionary.CreateBuilder(); + properties.Add(ProperAssertMethodNameKey, properAssertMethod); + properties.Add(CodeFixModeKey, CodeFixModeAddArgument); + context.ReportDiagnostic(context.Operation.CreateDiagnostic( + Rule, + additionalLocations: ImmutableArray.Create(conditionArgument.Syntax.GetLocation(), itemExpr!.GetLocation(), collectionExpr!.GetLocation()), + properties: properties.ToImmutable(), + properAssertMethod, + "IsFalse")); + return; + } + } + } + // Check for comparison patterns: a > b, a >= b, a < b, a <= b ComparisonCheckStatus comparisonStatus = RecognizeComparisonCheck(conditionArgument, out SyntaxNode? leftExpr, out SyntaxNode? rightExpr); if (comparisonStatus != ComparisonCheckStatus.Unknown) diff --git a/test/UnitTests/MSTest.Analyzers.UnitTests/UseProperAssertMethodsAnalyzerTests.cs b/test/UnitTests/MSTest.Analyzers.UnitTests/UseProperAssertMethodsAnalyzerTests.cs index 991e03496a..53e6281640 100644 --- a/test/UnitTests/MSTest.Analyzers.UnitTests/UseProperAssertMethodsAnalyzerTests.cs +++ b/test/UnitTests/MSTest.Analyzers.UnitTests/UseProperAssertMethodsAnalyzerTests.cs @@ -1445,12 +1445,31 @@ public class MyTestClass public void MyTestMethod() { string myString = "Hello World"; - Assert.IsFalse(myString.StartsWith("Hello")); + {|#0:Assert.IsFalse(myString.StartsWith("Hello"))|}; } } """; - await VerifyCS.VerifyAnalyzerAsync(code); + string fixedCode = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + string myString = "Hello World"; + Assert.DoesNotStartWith("Hello", myString); + } + } + """; + + await VerifyCS.VerifyCodeFixAsync( + code, + // /0/Test0.cs(10,9): info MSTEST0037: Use 'Assert.DoesNotStartWith' instead of 'Assert.IsFalse' + VerifyCS.DiagnosticIgnoringAdditionalLocations().WithLocation(0).WithArguments("DoesNotStartWith", "IsFalse"), + fixedCode); } [TestMethod] @@ -1466,12 +1485,31 @@ public class MyTestClass public void MyTestMethod() { string myString = "Hello World"; - Assert.IsFalse(myString.EndsWith("World")); + {|#0:Assert.IsFalse(myString.EndsWith("World"))|}; } } """; - await VerifyCS.VerifyAnalyzerAsync(code); + string fixedCode = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + string myString = "Hello World"; + Assert.DoesNotEndWith("World", myString); + } + } + """; + + await VerifyCS.VerifyCodeFixAsync( + code, + // /0/Test0.cs(10,9): info MSTEST0037: Use 'Assert.DoesNotEndWith' instead of 'Assert.IsFalse' + VerifyCS.DiagnosticIgnoringAdditionalLocations().WithLocation(0).WithArguments("DoesNotEndWith", "IsFalse"), + fixedCode); } [TestMethod] @@ -1487,12 +1525,31 @@ public class MyTestClass public void MyTestMethod() { string myString = "Hello World"; - Assert.IsFalse(myString.Contains("test")); + {|#0:Assert.IsFalse(myString.Contains("test"))|}; } } """; - await VerifyCS.VerifyAnalyzerAsync(code); + string fixedCode = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + string myString = "Hello World"; + Assert.DoesNotContain("test", myString); + } + } + """; + + await VerifyCS.VerifyCodeFixAsync( + code, + // /0/Test0.cs(10,9): info MSTEST0037: Use 'Assert.DoesNotContain' instead of 'Assert.IsFalse' + VerifyCS.DiagnosticIgnoringAdditionalLocations().WithLocation(0).WithArguments("DoesNotContain", "IsFalse"), + fixedCode); } #endregion @@ -1541,6 +1598,48 @@ await VerifyCS.VerifyCodeFixAsync( fixedCode); } + [TestMethod] + public async Task WhenAssertIsFalseWithCollectionContains() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + using System.Collections.Generic; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + var list = new List { 1, 2, 3 }; + {|#0:Assert.IsFalse(list.Contains(4))|}; + } + } + """; + + string fixedCode = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + using System.Collections.Generic; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + var list = new List { 1, 2, 3 }; + Assert.DoesNotContain(4, list); + } + } + """; + + await VerifyCS.VerifyCodeFixAsync( + code, + // /0/Test0.cs(11,9): info MSTEST0037: Use 'Assert.DoesNotContain' instead of 'Assert.IsFalse' + VerifyCS.DiagnosticIgnoringAdditionalLocations().WithLocation(0).WithArguments("DoesNotContain", "IsFalse"), + fixedCode); + } + #endregion #region New test cases for comparisons From caba350847dee98c48ed42e357b099e4763b2bce Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Mon, 28 Jul 2025 12:58:49 +0200 Subject: [PATCH 302/541] Update named pipe (#6169) --- .../HangDumpActivityIndicator.cs | 2 +- .../HangDumpExtensions.cs | 5 +++-- .../RetryFailedTestsPipeServer.cs | 2 +- .../TrxReportExtensions.cs | 2 +- .../Tasks/InvokeTestingPlatformTask.cs | 2 +- .../Microsoft.Testing.Platform/IPC/NamedPipeServer.cs | 8 +++++--- .../Microsoft.Testing.Platform.UnitTests/IPC/IPCTests.cs | 6 +++--- 7 files changed, 15 insertions(+), 12 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Extensions.HangDump/HangDumpActivityIndicator.cs b/src/Platform/Microsoft.Testing.Extensions.HangDump/HangDumpActivityIndicator.cs index 2c8d105a5b..ed6a65341d 100644 --- a/src/Platform/Microsoft.Testing.Extensions.HangDump/HangDumpActivityIndicator.cs +++ b/src/Platform/Microsoft.Testing.Extensions.HangDump/HangDumpActivityIndicator.cs @@ -114,7 +114,7 @@ await _namedPipeClient.RequestReplyAsyncThe test application builder. public static void AddHangDumpProvider(this ITestApplicationBuilder builder) { - CurrentTestApplicationModuleInfo testApplicationModuleInfo = new(new SystemEnvironment(), new SystemProcessHandler()); + var environment = new SystemEnvironment(); + CurrentTestApplicationModuleInfo testApplicationModuleInfo = new(environment, new SystemProcessHandler()); string mutexSuffix = Guid.NewGuid().ToString("N"); - PipeNameDescription pipeNameDescription = NamedPipeServer.GetPipeName(Guid.NewGuid().ToString("N")); + PipeNameDescription pipeNameDescription = NamedPipeServer.GetPipeName(Guid.NewGuid().ToString("N"), environment); HangDumpConfiguration hangDumpConfiguration = new(testApplicationModuleInfo, pipeNameDescription, mutexSuffix); builder.TestHostControllers.AddProcessLifetimeHandler(serviceProvider diff --git a/src/Platform/Microsoft.Testing.Extensions.Retry/RetryFailedTestsPipeServer.cs b/src/Platform/Microsoft.Testing.Extensions.Retry/RetryFailedTestsPipeServer.cs index b516672563..0702dba543 100644 --- a/src/Platform/Microsoft.Testing.Extensions.Retry/RetryFailedTestsPipeServer.cs +++ b/src/Platform/Microsoft.Testing.Extensions.Retry/RetryFailedTestsPipeServer.cs @@ -19,7 +19,7 @@ internal sealed class RetryFailedTestsPipeServer : IDisposable public RetryFailedTestsPipeServer(IServiceProvider serviceProvider, string[] failedTests, ILogger logger) { - _pipeNameDescription = NamedPipeServer.GetPipeName(Guid.NewGuid().ToString("N")); + _pipeNameDescription = NamedPipeServer.GetPipeName(Guid.NewGuid().ToString("N"), serviceProvider.GetEnvironment()); logger.LogTrace($"Retry server pipe name: '{_pipeNameDescription.Name}'"); _singleConnectionNamedPipeServer = new NamedPipeServer(_pipeNameDescription, CallbackAsync, serviceProvider.GetEnvironment(), diff --git a/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxReportExtensions.cs b/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxReportExtensions.cs index dd204c9611..7962b07e30 100644 --- a/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxReportExtensions.cs +++ b/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxReportExtensions.cs @@ -56,7 +56,7 @@ public static void AddTrxReportProvider(this ITestApplicationBuilder builder) builder.CommandLine.AddProvider(() => commandLine); - PipeNameDescription pipeNameDescription = NamedPipeServer.GetPipeName(Guid.NewGuid().ToString("N")); + PipeNameDescription pipeNameDescription = NamedPipeServer.GetPipeName(Guid.NewGuid().ToString("N"), new SystemEnvironment()); var compositeLifeTimeHandler = new CompositeExtensionFactory(serviceProvider => { diff --git a/src/Platform/Microsoft.Testing.Platform.MSBuild/Tasks/InvokeTestingPlatformTask.cs b/src/Platform/Microsoft.Testing.Platform.MSBuild/Tasks/InvokeTestingPlatformTask.cs index 67c20441c5..7f75710fe4 100644 --- a/src/Platform/Microsoft.Testing.Platform.MSBuild/Tasks/InvokeTestingPlatformTask.cs +++ b/src/Platform/Microsoft.Testing.Platform.MSBuild/Tasks/InvokeTestingPlatformTask.cs @@ -54,7 +54,7 @@ public InvokeTestingPlatformTask() Debugger.Launch(); } - _pipeNameDescription = NamedPipeServer.GetPipeName(Guid.NewGuid().ToString("N")); + _pipeNameDescription = NamedPipeServer.GetPipeName(Guid.NewGuid().ToString("N"), new SystemEnvironment()); } internal InvokeTestingPlatformTask(IFileSystem fileSystem) => _fileSystem = fileSystem; diff --git a/src/Platform/Microsoft.Testing.Platform/IPC/NamedPipeServer.cs b/src/Platform/Microsoft.Testing.Platform/IPC/NamedPipeServer.cs index 6d03564086..0fb0d3a1f4 100644 --- a/src/Platform/Microsoft.Testing.Platform/IPC/NamedPipeServer.cs +++ b/src/Platform/Microsoft.Testing.Platform/IPC/NamedPipeServer.cs @@ -36,7 +36,7 @@ public NamedPipeServer( ILogger logger, ITask task, CancellationToken cancellationToken) - : this(GetPipeName(name), callback, environment, logger, task, cancellationToken) + : this(GetPipeName(name, environment), callback, environment, logger, task, cancellationToken) { } @@ -267,14 +267,16 @@ private async Task InternalLoopAsync(CancellationToken cancellationToken) } } - public static PipeNameDescription GetPipeName(string name) + public static PipeNameDescription GetPipeName(string name, IEnvironment environment) { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { return new PipeNameDescription($"testingplatform.pipe.{name.Replace('\\', '.')}", false); } - string directoryId = Path.Combine(Path.GetTempPath(), name); +#pragma warning disable RS0030 // Do not use banned APIs - We are using IEnvironment, but we still need the enum from the Environment class in BCL. This is safe. + string directoryId = Path.Combine(environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData, Environment.SpecialFolderOption.None), name); +#pragma warning disable RS0030 // Do not use banned APIs Directory.CreateDirectory(directoryId); return new PipeNameDescription( !Directory.Exists(directoryId) diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/IPCTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/IPCTests.cs index b8025f25bd..d8126aea94 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/IPCTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/IPCTests.cs @@ -22,7 +22,7 @@ public IPCTests(TestContext testContext) [TestMethod] public async Task SingleConnectionNamedPipeServer_MultipleConnection_Fails() { - PipeNameDescription pipeNameDescription = NamedPipeServer.GetPipeName(Guid.NewGuid().ToString("N")); + PipeNameDescription pipeNameDescription = NamedPipeServer.GetPipeName(Guid.NewGuid().ToString("N"), new SystemEnvironment()); List openedPipe = []; List exceptions = []; @@ -88,7 +88,7 @@ public async Task SingleConnectionNamedPipeServer_MultipleConnection_Fails() public async Task SingleConnectionNamedPipeServer_RequestReplySerialization_Succeeded() { Queue receivedMessages = new(); - PipeNameDescription pipeNameDescription = NamedPipeServer.GetPipeName(Guid.NewGuid().ToString("N")); + PipeNameDescription pipeNameDescription = NamedPipeServer.GetPipeName(Guid.NewGuid().ToString("N"), new SystemEnvironment()); NamedPipeClient namedPipeClient = new(pipeNameDescription.Name); namedPipeClient.RegisterSerializer(new VoidResponseSerializer(), typeof(VoidResponse)); namedPipeClient.RegisterSerializer(new TextMessageSerializer(), typeof(TextMessage)); @@ -172,7 +172,7 @@ public async Task SingleConnectionNamedPipeServer_RequestReplySerialization_Succ [TestMethod] public async Task ConnectionNamedPipeServer_MultipleConnection_Succeeds() { - PipeNameDescription pipeNameDescription = NamedPipeServer.GetPipeName(Guid.NewGuid().ToString("N")); + PipeNameDescription pipeNameDescription = NamedPipeServer.GetPipeName(Guid.NewGuid().ToString("N"), new SystemEnvironment()); List pipes = []; for (int i = 0; i < 3; i++) From 65b0ba531ddc67076138131411d2b87056a306b6 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Mon, 28 Jul 2025 13:27:21 +0200 Subject: [PATCH 303/541] Move MSTest.Analyzers.UnitTests to net472 instead of net462 (#6197) --- .../MSTest.Analyzers.UnitTests.csproj | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/test/UnitTests/MSTest.Analyzers.UnitTests/MSTest.Analyzers.UnitTests.csproj b/test/UnitTests/MSTest.Analyzers.UnitTests/MSTest.Analyzers.UnitTests.csproj index 555c1372a1..1bf57106ad 100644 --- a/test/UnitTests/MSTest.Analyzers.UnitTests/MSTest.Analyzers.UnitTests.csproj +++ b/test/UnitTests/MSTest.Analyzers.UnitTests/MSTest.Analyzers.UnitTests.csproj @@ -1,7 +1,8 @@  - net462;net6.0 + + net472;net6.0 net6.0 true true From a4bd1ac899aca2972c09e26b460b7406e62b1fda Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Mon, 28 Jul 2025 14:28:58 +0200 Subject: [PATCH 304/541] Add GlobalTestInitializeAttribute and GlobalTestCleanupAttribute (#6132) --- .../Execution/TestAssemblyInfo.cs | 4 + .../Execution/TestMethodInfo.cs | 118 ++++++- .../Execution/TypeCache.cs | 17 + .../AnalyzerReleases.Unshipped.md | 1 + .../GlobalTestFixtureShouldBeValidAnalyzer.cs | 74 +++++ .../MSTest.Analyzers/Helpers/DiagnosticIds.cs | 1 + .../Helpers/WellKnownTypeNames.cs | 2 + .../MSTest.Analyzers/PublicAPI.Unshipped.txt | 4 + .../MSTest.Analyzers/Resources.Designer.cs | 145 +++++---- src/Analyzers/MSTest.Analyzers/Resources.resx | 24 ++ .../TestClassShouldHaveTestMethodAnalyzer.cs | 10 +- .../UnusedParameterSuppressor.cs | 7 +- ...eAsyncSuffixTestFixtureMethodSuppressor.cs | 7 +- .../MSTest.Analyzers/xlf/Resources.cs.xlf | 45 +++ .../MSTest.Analyzers/xlf/Resources.de.xlf | 45 +++ .../MSTest.Analyzers/xlf/Resources.es.xlf | 45 +++ .../MSTest.Analyzers/xlf/Resources.fr.xlf | 45 +++ .../MSTest.Analyzers/xlf/Resources.it.xlf | 45 +++ .../MSTest.Analyzers/xlf/Resources.ja.xlf | 45 +++ .../MSTest.Analyzers/xlf/Resources.ko.xlf | 45 +++ .../MSTest.Analyzers/xlf/Resources.pl.xlf | 45 +++ .../MSTest.Analyzers/xlf/Resources.pt-BR.xlf | 45 +++ .../MSTest.Analyzers/xlf/Resources.ru.xlf | 45 +++ .../MSTest.Analyzers/xlf/Resources.tr.xlf | 45 +++ .../xlf/Resources.zh-Hans.xlf | 45 +++ .../xlf/Resources.zh-Hant.xlf | 45 +++ .../AnalyzerSeverityDecider.cs | 9 +- .../Cleanup/GlobalTestCleanupAttribute.cs | 14 + .../GlobalTestInitializeAttribute.cs | 14 + .../PublicAPI/PublicAPI.Unshipped.txt | 4 + .../LifecycleTests.cs | 249 +++++++++++++++ ...alTestFixtureShouldBeValidAnalyzerTests.cs | 301 ++++++++++++++++++ ...tClassShouldHaveTestMethodAnalyzerTests.cs | 61 ++++ .../UnusedParameterSuppressorTests.cs | 60 ++++ ...cSuffixTestFixtureMethodSuppressorTests.cs | 54 ++++ 35 files changed, 1699 insertions(+), 66 deletions(-) create mode 100644 src/Analyzers/MSTest.Analyzers/GlobalTestFixtureShouldBeValidAnalyzer.cs create mode 100644 src/TestFramework/TestFramework/Attributes/Lifecycle/Cleanup/GlobalTestCleanupAttribute.cs create mode 100644 src/TestFramework/TestFramework/Attributes/Lifecycle/Initialization/GlobalTestInitializeAttribute.cs create mode 100644 test/IntegrationTests/MSTest.Acceptance.IntegrationTests/LifecycleTests.cs create mode 100644 test/UnitTests/MSTest.Analyzers.UnitTests/GlobalTestFixtureShouldBeValidAnalyzerTests.cs diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestAssemblyInfo.cs b/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestAssemblyInfo.cs index 93e3f82295..c9afd88c68 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestAssemblyInfo.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestAssemblyInfo.cs @@ -31,6 +31,10 @@ public class TestAssemblyInfo internal TestAssemblyInfo(Assembly assembly) => Assembly = assembly; + internal List<(MethodInfo Method, TimeoutInfo? TimeoutInfo)> GlobalTestInitializations { get; } = []; + + internal List<(MethodInfo Method, TimeoutInfo? TimeoutInfo)> GlobalTestCleanups { get; } = []; + /// /// Gets AssemblyInitialize method for the assembly. /// diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestMethodInfo.cs b/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestMethodInfo.cs index ccbcfba1d9..97af7c95f6 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestMethodInfo.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestMethodInfo.cs @@ -382,8 +382,6 @@ private async Task ExecuteInternalAsync(object?[]? arguments, Cancel var result = new TestResult(); - // TODO remove dry violation with TestMethodRunner - _classInstance = CreateTestClassInstance(result); bool isExceptionThrown = false; bool hasTestInitializePassed = false; Exception? testRunnerException = null; @@ -394,12 +392,53 @@ private async Task ExecuteInternalAsync(object?[]? arguments, Cancel { try { - if (_classInstance != null && SetTestContext(_classInstance, result)) + // We invoke global test initialize methods before creating the test class instance. + // We consider the test class constructor as a "local" initialization. + // We want to invoke first the global initializations, then local ones, then test method. + // After that, we invoke local cleanups (including Dispose) and finally global cleanups at last. + foreach ((MethodInfo method, TimeoutInfo? timeoutInfo) in Parent.Parent.GlobalTestInitializations) + { + InvokeGlobalInitializeMethod(method, ref executionContext, timeoutInfo, timeoutTokenSource); + } + + // TODO remove dry violation with TestMethodRunner + bool setTestContextSucessful = false; + if (executionContext is null) + { + _classInstance = CreateTestClassInstance(result); + setTestContextSucessful = _classInstance != null && SetTestContext(_classInstance, result); + } + else + { + // The whole ExecuteInternalAsync method is already running on the execution context we got after class init. + // However, if the global test initialize call above is using a non-cooperative timeout, it will + // need to capture the execution context from the thread running it (after it has finished). + // This is the case when executionContext is not null (this code path). + // In this case, we want to ensure the constructor and setting TestContext are both run on the correct execution context. + // Also we re-capture the execution context in case constructor or TestContext setter modifies an async local value. + ExecutionContext updatedExecutionContext = executionContext; + ExecutionContextHelpers.RunOnContext(executionContext, () => + { + try + { + _classInstance = CreateTestClassInstance(result); + setTestContextSucessful = _classInstance != null && SetTestContext(_classInstance, result); + } + finally + { + updatedExecutionContext = ExecutionContext.Capture() ?? executionContext; + } + }); + + executionContext = updatedExecutionContext; + } + + if (setTestContextSucessful) { // For any failure after this point, we must run TestCleanup _isTestContextSet = true; - if (RunTestInitializeMethod(_classInstance, result, ref executionContext, timeoutTokenSource)) + if (RunTestInitializeMethod(_classInstance!, result, ref executionContext, timeoutTokenSource)) { hasTestInitializePassed = true; @@ -730,6 +769,11 @@ private static TestFailedException HandleMethodException(Exception ex, Exception { classInstanceAsDisposable.Dispose(); } + + foreach ((MethodInfo method, TimeoutInfo? timeoutInfo) in Parent.Parent.GlobalTestCleanups) + { + InvokeGlobalCleanupMethod(method, ref executionContext, timeoutInfo, timeoutTokenSource); + } } } catch (Exception ex) @@ -896,6 +940,39 @@ timeoutTokenSource is null return result; } + private TestFailedException? InvokeGlobalInitializeMethod(MethodInfo methodInfo, ref ExecutionContext? executionContext, TimeoutInfo? timeoutInfo, CancellationTokenSource? timeoutTokenSource) + { + int originalThreadId = Environment.CurrentManagedThreadId; + ExecutionContext? updatedExecutionContext = null; + TestFailedException? result = FixtureMethodRunner.RunWithTimeoutAndCancellation( + () => + { + methodInfo.InvokeAsSynchronousTask(null, [TestContext]); + if (originalThreadId != Environment.CurrentManagedThreadId) + { + // We ended up running on a different thread, because of use of non-cooperative timeout. + // Re-capture the execution context. + updatedExecutionContext = ExecutionContext.Capture(); + } + }, + TestContext!.Context.CancellationTokenSource, + timeoutInfo: timeoutInfo, + methodInfo, + executionContext, + Resource.TestInitializeWasCancelled, + Resource.TestInitializeTimedOut, + timeoutTokenSource is null + ? null + : (timeoutTokenSource, TimeoutInfo.Timeout)); + + if (updatedExecutionContext != null) + { + executionContext = updatedExecutionContext; + } + + return result; + } + private TestFailedException? InvokeCleanupMethod(MethodInfo methodInfo, object classInstance, ref ExecutionContext? executionContext, CancellationTokenSource? timeoutTokenSource) { TimeoutInfo? timeout = null; @@ -935,6 +1012,39 @@ timeoutTokenSource is null return result; } + private TestFailedException? InvokeGlobalCleanupMethod(MethodInfo methodInfo, ref ExecutionContext? executionContext, TimeoutInfo? timeoutInfo, CancellationTokenSource? timeoutTokenSource) + { + int originalThreadId = Environment.CurrentManagedThreadId; + ExecutionContext? updatedExecutionContext = null; + TestFailedException? result = FixtureMethodRunner.RunWithTimeoutAndCancellation( + () => + { + methodInfo.InvokeAsSynchronousTask(null, [TestContext]); + if (originalThreadId != Environment.CurrentManagedThreadId) + { + // We ended up running on a different thread, because of use of non-cooperative timeout. + // Re-capture the execution context. + updatedExecutionContext = ExecutionContext.Capture(); + } + }, + TestContext!.Context.CancellationTokenSource, + timeoutInfo: timeoutInfo, + methodInfo, + executionContext, + Resource.TestCleanupWasCancelled, + Resource.TestCleanupTimedOut, + timeoutTokenSource is null + ? null + : (timeoutTokenSource, TimeoutInfo.Timeout)); + + if (updatedExecutionContext != null) + { + executionContext = updatedExecutionContext; + } + + return result; + } + /// /// Sets the on . /// diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Execution/TypeCache.cs b/src/Adapter/MSTestAdapter.PlatformServices/Execution/TypeCache.cs index 2fc12e9f2e..3ac9676a1e 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Execution/TypeCache.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Execution/TypeCache.cs @@ -421,6 +421,23 @@ private TestAssemblyInfo GetAssemblyInfo(Assembly assembly) assemblyInfo.AssemblyCleanupMethod = methodInfo; assemblyInfo.AssemblyCleanupMethodTimeoutMilliseconds = @this.TryGetTimeoutInfo(methodInfo, FixtureKind.AssemblyCleanup); } + + if (methodInfo is { IsPublic: true, IsStatic: true, IsGenericMethod: false, DeclaringType.IsGenericType: false, DeclaringType.IsPublic: true } && + methodInfo.GetParameters() is { } parameters && parameters.Length == 1 && parameters[0].ParameterType == typeof(TestContext) && + methodInfo.IsValidReturnType()) + { + bool isGlobalTestInitialize = @this._reflectionHelper.IsAttributeDefined(methodInfo, inherit: true); + bool isGlobalTestCleanup = @this._reflectionHelper.IsAttributeDefined(methodInfo, inherit: true); + if (isGlobalTestInitialize) + { + assemblyInfo.GlobalTestInitializations.Add((methodInfo, @this.TryGetTimeoutInfo(methodInfo, FixtureKind.TestInitialize))); + } + + if (isGlobalTestCleanup) + { + assemblyInfo.GlobalTestCleanups.Add((methodInfo, @this.TryGetTimeoutInfo(methodInfo, FixtureKind.TestCleanup))); + } + } } } diff --git a/src/Analyzers/MSTest.Analyzers/AnalyzerReleases.Unshipped.md b/src/Analyzers/MSTest.Analyzers/AnalyzerReleases.Unshipped.md index 7f47cac255..f230c697eb 100644 --- a/src/Analyzers/MSTest.Analyzers/AnalyzerReleases.Unshipped.md +++ b/src/Analyzers/MSTest.Analyzers/AnalyzerReleases.Unshipped.md @@ -10,6 +10,7 @@ MSTEST0045 | Usage | Info | UseCooperativeCancellationForTimeoutAnalyzer, [Docum MSTEST0046 | Usage | Info | StringAssertToAssertAnalyzer, [Documentation](https://learn.microsoft.com/dotnet/core/testing/mstest-analyzers/mstest0046) MSTEST0048 | Usage | Warning | TestContextPropertyUsageAnalyzer, [Documentation](https://learn.microsoft.com/dotnet/core/testing/mstest-analyzers/mstest0047) MSTEST0049 | Usage | Info | FlowTestContextCancellationTokenAnalyzer, [Documentation](https://learn.microsoft.com/dotnet/core/testing/mstest-analyzers/mstest0049) +MSTEST0050 | Usage | Error | GlobalTestFixtureShouldBeValidAnalyzer, [Documentation](https://learn.microsoft.com/dotnet/core/testing/mstest-analyzers/mstest0050) ### Changed Rules diff --git a/src/Analyzers/MSTest.Analyzers/GlobalTestFixtureShouldBeValidAnalyzer.cs b/src/Analyzers/MSTest.Analyzers/GlobalTestFixtureShouldBeValidAnalyzer.cs new file mode 100644 index 0000000000..f7b4a5c8a8 --- /dev/null +++ b/src/Analyzers/MSTest.Analyzers/GlobalTestFixtureShouldBeValidAnalyzer.cs @@ -0,0 +1,74 @@ +// 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.Immutable; + +using Analyzer.Utilities.Extensions; + +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Diagnostics; + +using MSTest.Analyzers.Helpers; + +namespace MSTest.Analyzers; + +/// +/// MSTEST0050: . +/// +[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] +public sealed class GlobalTestFixtureShouldBeValidAnalyzer : DiagnosticAnalyzer +{ + internal static readonly DiagnosticDescriptor Rule = DiagnosticDescriptorHelper.Create( + DiagnosticIds.GlobalTestFixtureShouldBeValidRuleId, + new LocalizableResourceString(nameof(Resources.GlobalTestFixtureShouldBeValidTitle), Resources.ResourceManager, typeof(Resources)), + new LocalizableResourceString(nameof(Resources.GlobalTestFixtureShouldBeValidMessageFormat), Resources.ResourceManager, typeof(Resources)), + new LocalizableResourceString(nameof(Resources.GlobalTestFixtureShouldBeValidDescription), Resources.ResourceManager, typeof(Resources)), + Category.Usage, + DiagnosticSeverity.Error, + isEnabledByDefault: true); + + /// + public override ImmutableArray SupportedDiagnostics { get; } = ImmutableArray.Create(Rule); + + /// + public override void Initialize(AnalysisContext context) + { + context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); + context.EnableConcurrentExecution(); + + context.RegisterCompilationStartAction(context => + { + if (context.Compilation.TryGetOrCreateTypeByMetadataName(WellKnownTypeNames.MicrosoftVisualStudioTestToolsUnitTestingTestContext, out INamedTypeSymbol? testContextSymbol) && + context.Compilation.TryGetOrCreateTypeByMetadataName(WellKnownTypeNames.MicrosoftVisualStudioTestToolsUnitTestingTestClassAttribute, out INamedTypeSymbol? testClassAttributeSymbol) && + context.Compilation.TryGetOrCreateTypeByMetadataName(WellKnownTypeNames.MicrosoftVisualStudioTestToolsUnitTestingGlobalTestInitializeAttribute, out INamedTypeSymbol? globalTestInitializeAttributeSymbol) && + context.Compilation.TryGetOrCreateTypeByMetadataName(WellKnownTypeNames.MicrosoftVisualStudioTestToolsUnitTestingGlobalTestCleanupAttribute, out INamedTypeSymbol? globalTestCleanupAttributeSymbol)) + { + INamedTypeSymbol? taskSymbol = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemThreadingTasksTask); + INamedTypeSymbol? valueTaskSymbol = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemThreadingTasksValueTask); + + context.RegisterSymbolAction( + context => AnalyzeSymbol(context, globalTestInitializeAttributeSymbol, globalTestCleanupAttributeSymbol, taskSymbol, valueTaskSymbol, testContextSymbol, testClassAttributeSymbol), + SymbolKind.Method); + } + }); + } + + private static void AnalyzeSymbol( + SymbolAnalysisContext context, + INamedTypeSymbol globalTestInitializeAttributeSymbol, + INamedTypeSymbol globalTestCleanupAttributeSymbol, + INamedTypeSymbol? taskSymbol, + INamedTypeSymbol? valueTaskSymbol, + INamedTypeSymbol testContextSymbol, + INamedTypeSymbol testClassAttributeSymbol) + { + var methodSymbol = (IMethodSymbol)context.Symbol; + + if ((methodSymbol.HasAttribute(globalTestInitializeAttributeSymbol) || methodSymbol.HasAttribute(globalTestCleanupAttributeSymbol)) && + !methodSymbol.HasValidFixtureMethodSignature(taskSymbol, valueTaskSymbol, canDiscoverInternals: false, shouldBeStatic: true, + allowGenericType: false, FixtureParameterMode.MustHaveTestContext, testContextSymbol, testClassAttributeSymbol, fixtureAllowInheritedTestClass: false, out _)) + { + context.ReportDiagnostic(methodSymbol.CreateDiagnostic(Rule, methodSymbol.Name)); + } + } +} diff --git a/src/Analyzers/MSTest.Analyzers/Helpers/DiagnosticIds.cs b/src/Analyzers/MSTest.Analyzers/Helpers/DiagnosticIds.cs index cd6b9bae20..5b31df82e2 100644 --- a/src/Analyzers/MSTest.Analyzers/Helpers/DiagnosticIds.cs +++ b/src/Analyzers/MSTest.Analyzers/Helpers/DiagnosticIds.cs @@ -54,4 +54,5 @@ internal static class DiagnosticIds public const string UnusedParameterSuppressorRuleId = "MSTEST0047"; public const string TestContextPropertyUsageRuleId = "MSTEST0048"; public const string FlowTestContextCancellationTokenRuleId = "MSTEST0049"; + public const string GlobalTestFixtureShouldBeValidRuleId = "MSTEST0050"; } diff --git a/src/Analyzers/MSTest.Analyzers/Helpers/WellKnownTypeNames.cs b/src/Analyzers/MSTest.Analyzers/Helpers/WellKnownTypeNames.cs index 380a3e7a03..8481ca81e1 100644 --- a/src/Analyzers/MSTest.Analyzers/Helpers/WellKnownTypeNames.cs +++ b/src/Analyzers/MSTest.Analyzers/Helpers/WellKnownTypeNames.cs @@ -27,6 +27,8 @@ internal static class WellKnownTypeNames public const string MicrosoftVisualStudioTestToolsUnitTestingDynamicDataSourceType = "Microsoft.VisualStudio.TestTools.UnitTesting.DynamicDataSourceType"; public const string MicrosoftVisualStudioTestToolsUnitTestingExpectedExceptionAttribute = "Microsoft.VisualStudio.TestTools.UnitTesting.ExpectedExceptionAttribute"; public const string MicrosoftVisualStudioTestToolsUnitTestingExpectedExceptionBaseAttribute = "Microsoft.VisualStudio.TestTools.UnitTesting.ExpectedExceptionBaseAttribute"; + public const string MicrosoftVisualStudioTestToolsUnitTestingGlobalTestCleanupAttribute = "Microsoft.VisualStudio.TestTools.UnitTesting.GlobalTestCleanupAttribute"; + public const string MicrosoftVisualStudioTestToolsUnitTestingGlobalTestInitializeAttribute = "Microsoft.VisualStudio.TestTools.UnitTesting.GlobalTestInitializeAttribute"; public const string MicrosoftVisualStudioTestToolsUnitTestingIgnoreAttribute = "Microsoft.VisualStudio.TestTools.UnitTesting.IgnoreAttribute"; public const string MicrosoftVisualStudioTestToolsUnitTestingInheritanceBehavior = "Microsoft.VisualStudio.TestTools.UnitTesting.InheritanceBehavior"; public const string MicrosoftVisualStudioTestToolsUnitTestingOwnerAttribute = "Microsoft.VisualStudio.TestTools.UnitTesting.OwnerAttribute"; diff --git a/src/Analyzers/MSTest.Analyzers/PublicAPI.Unshipped.txt b/src/Analyzers/MSTest.Analyzers/PublicAPI.Unshipped.txt index 5b61c23895..855fc462e3 100644 --- a/src/Analyzers/MSTest.Analyzers/PublicAPI.Unshipped.txt +++ b/src/Analyzers/MSTest.Analyzers/PublicAPI.Unshipped.txt @@ -1,10 +1,14 @@ #nullable enable MSTest.Analyzers.FlowTestContextCancellationTokenAnalyzer MSTest.Analyzers.FlowTestContextCancellationTokenAnalyzer.FlowTestContextCancellationTokenAnalyzer() -> void +MSTest.Analyzers.GlobalTestFixtureShouldBeValidAnalyzer +MSTest.Analyzers.GlobalTestFixtureShouldBeValidAnalyzer.GlobalTestFixtureShouldBeValidAnalyzer() -> void override MSTest.Analyzers.FlowTestContextCancellationTokenAnalyzer.Initialize(Microsoft.CodeAnalysis.Diagnostics.AnalysisContext! context) -> void override MSTest.Analyzers.FlowTestContextCancellationTokenAnalyzer.SupportedDiagnostics.get -> System.Collections.Immutable.ImmutableArray MSTest.Analyzers.PreferTestMethodOverDataTestMethodAnalyzer MSTest.Analyzers.PreferTestMethodOverDataTestMethodAnalyzer.PreferTestMethodOverDataTestMethodAnalyzer() -> void +override MSTest.Analyzers.GlobalTestFixtureShouldBeValidAnalyzer.Initialize(Microsoft.CodeAnalysis.Diagnostics.AnalysisContext! context) -> void +override MSTest.Analyzers.GlobalTestFixtureShouldBeValidAnalyzer.SupportedDiagnostics.get -> System.Collections.Immutable.ImmutableArray override MSTest.Analyzers.PreferTestMethodOverDataTestMethodAnalyzer.Initialize(Microsoft.CodeAnalysis.Diagnostics.AnalysisContext! context) -> void override MSTest.Analyzers.PreferTestMethodOverDataTestMethodAnalyzer.SupportedDiagnostics.get -> System.Collections.Immutable.ImmutableArray MSTest.Analyzers.UseCooperativeCancellationForTimeoutAnalyzer diff --git a/src/Analyzers/MSTest.Analyzers/Resources.Designer.cs b/src/Analyzers/MSTest.Analyzers/Resources.Designer.cs index bd040c4017..d81903f9ed 100644 --- a/src/Analyzers/MSTest.Analyzers/Resources.Designer.cs +++ b/src/Analyzers/MSTest.Analyzers/Resources.Designer.cs @@ -627,6 +627,70 @@ internal static string DynamicDataShouldBeValidTitle { } } + /// + /// Looks up a localized string similar to When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationTokenSource.Token to enable cooperative cancellation and respect test timeouts.. + /// + internal static string FlowTestContextCancellationTokenDescription { + get { + return ResourceManager.GetString("FlowTestContextCancellationTokenDescription", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationTokenSource.Token'. + /// + internal static string FlowTestContextCancellationTokenMessageFormat { + get { + return ResourceManager.GetString("FlowTestContextCancellationTokenMessageFormat", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Flow TestContext.CancellationToken to async operations. + /// + internal static string FlowTestContextCancellationTokenTitle { + get { + return ResourceManager.GetString("FlowTestContextCancellationTokenTitle", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Methods marked with '[GlobalTestInitialize]' or '[GlobalTestCleanup]' should follow the following layout to be valid: + ///-it can't be declared on a generic class + ///-it should be 'public' + ///-it should be 'static' + ///-it should not be 'async void' + ///-it should not be a special method (finalizer, operator...). + ///-it should not be generic + ///-it should take one parameter of type 'TestContext' + ///-return type should be 'void', 'Task' or 'ValueTask' + /// + ///The type declaring these methods should also respect the following rules: [rest of string was truncated]";. + /// + internal static string GlobalTestFixtureShouldBeValidDescription { + get { + return ResourceManager.GetString("GlobalTestFixtureShouldBeValidDescription", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Global test fixture method '{0}' signature is invalid. + /// + internal static string GlobalTestFixtureShouldBeValidMessageFormat { + get { + return ResourceManager.GetString("GlobalTestFixtureShouldBeValidMessageFormat", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to GlobalTestInitialize and GlobalTestCleanup methods should have valid layout. + /// + internal static string GlobalTestFixtureShouldBeValidTitle { + get { + return ResourceManager.GetString("GlobalTestFixtureShouldBeValidTitle", resourceCulture); + } + } + /// /// Looks up a localized string similar to Use 'Assert.Fail' instead of an always-failing 'Assert.{0}' assert. /// @@ -930,6 +994,33 @@ internal static string TestCleanupShouldBeValidTitle { } } + /// + /// Looks up a localized string similar to Some TestContext properties are only available during test execution and cannot be accessed in assembly initialize, class initialize, class cleanup, or assembly cleanup methods.. + /// + internal static string TestContextPropertyUsageDescription { + get { + return ResourceManager.GetString("TestContextPropertyUsageDescription", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to TestContext property '{0}' cannot be accessed in '{1}' method. + /// + internal static string TestContextPropertyUsageMessageFormat { + get { + return ResourceManager.GetString("TestContextPropertyUsageMessageFormat", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to TestContext property cannot be accessed in this context. + /// + internal static string TestContextPropertyUsageTitle { + get { + return ResourceManager.GetString("TestContextPropertyUsageTitle", resourceCulture); + } + } + /// /// Looks up a localized string similar to 'TestContext' should be a non-static field or property assigned in constructor or for a property set by MSTest, it should follow the layout: ///- it should be 'public' regardless of whether '[assembly: DiscoverInternals]' attribute is set or not. @@ -1302,59 +1393,5 @@ internal static string UseRetryWithTestMethodTitle { return ResourceManager.GetString("UseRetryWithTestMethodTitle", resourceCulture); } } - - /// - /// Looks up a localized string similar to TestContext property cannot be accessed in this context. - /// - internal static string TestContextPropertyUsageTitle { - get { - return ResourceManager.GetString("TestContextPropertyUsageTitle", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to TestContext property '{0}' cannot be accessed in '{1}' method. - /// - internal static string TestContextPropertyUsageMessageFormat { - get { - return ResourceManager.GetString("TestContextPropertyUsageMessageFormat", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Some TestContext properties are only available during test execution and cannot be accessed in assembly initialize, class initialize, class cleanup, or assembly cleanup methods. - /// - internal static string TestContextPropertyUsageDescription { - get { - return ResourceManager.GetString("TestContextPropertyUsageDescription", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationTokenSource.Token to enable cooperative cancellation and respect test timeouts. - /// - internal static string FlowTestContextCancellationTokenDescription { - get { - return ResourceManager.GetString("FlowTestContextCancellationTokenDescription", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationTokenSource.Token'. - /// - internal static string FlowTestContextCancellationTokenMessageFormat { - get { - return ResourceManager.GetString("FlowTestContextCancellationTokenMessageFormat", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Flow TestContext.CancellationToken to async operations. - /// - internal static string FlowTestContextCancellationTokenTitle { - get { - return ResourceManager.GetString("FlowTestContextCancellationTokenTitle", resourceCulture); - } - } } } diff --git a/src/Analyzers/MSTest.Analyzers/Resources.resx b/src/Analyzers/MSTest.Analyzers/Resources.resx index dfb6843781..45445b2d82 100644 --- a/src/Analyzers/MSTest.Analyzers/Resources.resx +++ b/src/Analyzers/MSTest.Analyzers/Resources.resx @@ -633,4 +633,28 @@ The type declaring these methods should also respect the following rules: When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationTokenSource.Token to enable cooperative cancellation and respect test timeouts. + + GlobalTestInitialize and GlobalTestCleanup methods should have valid layout + + + Global test fixture method '{0}' signature is invalid + + + Methods marked with '[GlobalTestInitialize]' or '[GlobalTestCleanup]' should follow the following layout to be valid: +-it can't be declared on a generic class +-it should be 'public' +-it should be 'static' +-it should not be 'async void' +-it should not be a special method (finalizer, operator...). +-it should not be generic +-it should take one parameter of type 'TestContext' +-return type should be 'void', 'Task' or 'ValueTask' + +The type declaring these methods should also respect the following rules: +-The type should be a class +-The class should be 'public' +-The class shouldn't be 'static' +-The class should be marked with '[TestClass]' (or a derived attribute) +-the class should not be generic. + diff --git a/src/Analyzers/MSTest.Analyzers/TestClassShouldHaveTestMethodAnalyzer.cs b/src/Analyzers/MSTest.Analyzers/TestClassShouldHaveTestMethodAnalyzer.cs index c8f38fac34..5ba9dde1b6 100644 --- a/src/Analyzers/MSTest.Analyzers/TestClassShouldHaveTestMethodAnalyzer.cs +++ b/src/Analyzers/MSTest.Analyzers/TestClassShouldHaveTestMethodAnalyzer.cs @@ -48,15 +48,17 @@ public override void Initialize(AnalysisContext context) INamedTypeSymbol? testMethodAttributeSymbol = context.Compilation.GetTypeByMetadataName(WellKnownTypeNames.MicrosoftVisualStudioTestToolsUnitTestingTestMethodAttribute); INamedTypeSymbol? assemblyInitializationAttributeSymbol = context.Compilation.GetTypeByMetadataName(WellKnownTypeNames.MicrosoftVisualStudioTestToolsUnitTestingAssemblyInitializeAttribute); INamedTypeSymbol? assemblyCleanupAttributeSymbol = context.Compilation.GetTypeByMetadataName(WellKnownTypeNames.MicrosoftVisualStudioTestToolsUnitTestingAssemblyCleanupAttribute); + INamedTypeSymbol? globalTestInitializeAttributeSymbol = context.Compilation.GetTypeByMetadataName(WellKnownTypeNames.MicrosoftVisualStudioTestToolsUnitTestingGlobalTestInitializeAttribute); + INamedTypeSymbol? globalTestCleanupAttributeSymbol = context.Compilation.GetTypeByMetadataName(WellKnownTypeNames.MicrosoftVisualStudioTestToolsUnitTestingGlobalTestCleanupAttribute); context.RegisterSymbolAction( - context => AnalyzeSymbol(context, testClassAttributeSymbol, testMethodAttributeSymbol, assemblyInitializationAttributeSymbol, assemblyCleanupAttributeSymbol), + context => AnalyzeSymbol(context, testClassAttributeSymbol, testMethodAttributeSymbol, assemblyInitializationAttributeSymbol, assemblyCleanupAttributeSymbol, globalTestInitializeAttributeSymbol, globalTestCleanupAttributeSymbol), SymbolKind.NamedType); } }); } private static void AnalyzeSymbol(SymbolAnalysisContext context, INamedTypeSymbol testClassAttributeSymbol, INamedTypeSymbol? testMethodAttributeSymbol, - INamedTypeSymbol? assemblyInitializationAttributeSymbol, INamedTypeSymbol? assemblyCleanupAttributeSymbol) + INamedTypeSymbol? assemblyInitializationAttributeSymbol, INamedTypeSymbol? assemblyCleanupAttributeSymbol, INamedTypeSymbol? globalTestInitializeAttributeSymbol, INamedTypeSymbol? globalTestCleanupAttributeSymbol) { var classSymbol = (INamedTypeSymbol)context.Symbol; @@ -91,7 +93,9 @@ private static void AnalyzeSymbol(SymbolAnalysisContext context, INamedTypeSymbo } if (SymbolEqualityComparer.Default.Equals(attribute.AttributeClass, assemblyInitializationAttributeSymbol) - || SymbolEqualityComparer.Default.Equals(attribute.AttributeClass, assemblyCleanupAttributeSymbol)) + || SymbolEqualityComparer.Default.Equals(attribute.AttributeClass, assemblyCleanupAttributeSymbol) + || SymbolEqualityComparer.Default.Equals(attribute.AttributeClass, globalTestInitializeAttributeSymbol) + || SymbolEqualityComparer.Default.Equals(attribute.AttributeClass, globalTestCleanupAttributeSymbol)) { hasAssemblyAttribute = true; } diff --git a/src/Analyzers/MSTest.Analyzers/UnusedParameterSuppressor.cs b/src/Analyzers/MSTest.Analyzers/UnusedParameterSuppressor.cs index 7919a526b8..3bc64d707f 100644 --- a/src/Analyzers/MSTest.Analyzers/UnusedParameterSuppressor.cs +++ b/src/Analyzers/MSTest.Analyzers/UnusedParameterSuppressor.cs @@ -38,6 +38,9 @@ public override void ReportSuppressions(SuppressionAnalysisContext context) return; } + INamedTypeSymbol? globalTestInitializeAttributeSymbol = context.Compilation.GetTypeByMetadataName(WellKnownTypeNames.MicrosoftVisualStudioTestToolsUnitTestingGlobalTestInitializeAttribute); + INamedTypeSymbol? globalTestCleanupAttributeSymbol = context.Compilation.GetTypeByMetadataName(WellKnownTypeNames.MicrosoftVisualStudioTestToolsUnitTestingGlobalTestCleanupAttribute); + foreach (Diagnostic diagnostic in context.ReportedDiagnostics) { // The diagnostic is reported on the parameter @@ -57,7 +60,9 @@ public override void ReportSuppressions(SuppressionAnalysisContext context) && parameter.ContainingSymbol is IMethodSymbol method && method.GetAttributes().Any(attr => SymbolEqualityComparer.Default.Equals(attr.AttributeClass, assemblyInitializeAttributeSymbol) || - SymbolEqualityComparer.Default.Equals(attr.AttributeClass, classInitializeAttributeSymbol))) + SymbolEqualityComparer.Default.Equals(attr.AttributeClass, classInitializeAttributeSymbol) || + SymbolEqualityComparer.Default.Equals(attr.AttributeClass, globalTestInitializeAttributeSymbol) || + SymbolEqualityComparer.Default.Equals(attr.AttributeClass, globalTestCleanupAttributeSymbol))) { context.ReportSuppression(Suppression.Create(Rule, diagnostic)); } diff --git a/src/Analyzers/MSTest.Analyzers/UseAsyncSuffixTestFixtureMethodSuppressor.cs b/src/Analyzers/MSTest.Analyzers/UseAsyncSuffixTestFixtureMethodSuppressor.cs index 9f7995e4cf..3cd37a4c22 100644 --- a/src/Analyzers/MSTest.Analyzers/UseAsyncSuffixTestFixtureMethodSuppressor.cs +++ b/src/Analyzers/MSTest.Analyzers/UseAsyncSuffixTestFixtureMethodSuppressor.cs @@ -41,6 +41,9 @@ public override void ReportSuppressions(SuppressionAnalysisContext context) return; } + INamedTypeSymbol? globalTestInitializeAttributeSymbol = context.Compilation.GetTypeByMetadataName(WellKnownTypeNames.MicrosoftVisualStudioTestToolsUnitTestingGlobalTestInitializeAttribute); + INamedTypeSymbol? globalTestCleanupAttributeSymbol = context.Compilation.GetTypeByMetadataName(WellKnownTypeNames.MicrosoftVisualStudioTestToolsUnitTestingGlobalTestCleanupAttribute); + foreach (Diagnostic diagnostic in context.ReportedDiagnostics) { // The diagnostic is reported on the test method @@ -61,7 +64,9 @@ public override void ReportSuppressions(SuppressionAnalysisContext context) || SymbolEqualityComparer.Default.Equals(attr.AttributeClass, classInitializeAttributeSymbol) || SymbolEqualityComparer.Default.Equals(attr.AttributeClass, classCleanupAttributeSymbol) || SymbolEqualityComparer.Default.Equals(attr.AttributeClass, testInitializeAttributeSymbol) - || SymbolEqualityComparer.Default.Equals(attr.AttributeClass, testCleanupAttributeSymbol))) + || SymbolEqualityComparer.Default.Equals(attr.AttributeClass, testCleanupAttributeSymbol) + || SymbolEqualityComparer.Default.Equals(attr.AttributeClass, globalTestInitializeAttributeSymbol) + || SymbolEqualityComparer.Default.Equals(attr.AttributeClass, globalTestCleanupAttributeSymbol))) { context.ReportSuppression(Suppression.Create(Rule, diagnostic)); } diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf index bdebc0ae80..e80dfe879f 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf @@ -447,6 +447,51 @@ Typ deklarující tyto metody by měl také respektovat následující pravidla: Přenesení TestContext.CancellationToken do asynchronních operací + + Methods marked with '[GlobalTestInitialize]' or '[GlobalTestCleanup]' should follow the following layout to be valid: +-it can't be declared on a generic class +-it should be 'public' +-it should be 'static' +-it should not be 'async void' +-it should not be a special method (finalizer, operator...). +-it should not be generic +-it should take one parameter of type 'TestContext' +-return type should be 'void', 'Task' or 'ValueTask' + +The type declaring these methods should also respect the following rules: +-The type should be a class +-The class should be 'public' +-The class shouldn't be 'static' +-The class should be marked with '[TestClass]' (or a derived attribute) +-the class should not be generic. + Methods marked with '[GlobalTestInitialize]' or '[GlobalTestCleanup]' should follow the following layout to be valid: +-it can't be declared on a generic class +-it should be 'public' +-it should be 'static' +-it should not be 'async void' +-it should not be a special method (finalizer, operator...). +-it should not be generic +-it should take one parameter of type 'TestContext' +-return type should be 'void', 'Task' or 'ValueTask' + +The type declaring these methods should also respect the following rules: +-The type should be a class +-The class should be 'public' +-The class shouldn't be 'static' +-The class should be marked with '[TestClass]' (or a derived attribute) +-the class should not be generic. + + + + Global test fixture method '{0}' signature is invalid + Global test fixture method '{0}' signature is invalid + + + + GlobalTestInitialize and GlobalTestCleanup methods should have valid layout + GlobalTestInitialize and GlobalTestCleanup methods should have valid layout + + Use 'Assert.Fail' instead of an always-failing 'Assert.{0}' assert Místo trvalého neúspěšného vyhodnocovacího výrazu „Assert.{0}“ použijte „Assert.Fail“. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf index 1dfb6a24fd..cda5a5f789 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf @@ -448,6 +448,51 @@ Der Typ, der diese Methoden deklariert, sollte auch die folgenden Regeln beachte Fluss von TestContext.CancellationToken zu asynchronen Vorgängen + + Methods marked with '[GlobalTestInitialize]' or '[GlobalTestCleanup]' should follow the following layout to be valid: +-it can't be declared on a generic class +-it should be 'public' +-it should be 'static' +-it should not be 'async void' +-it should not be a special method (finalizer, operator...). +-it should not be generic +-it should take one parameter of type 'TestContext' +-return type should be 'void', 'Task' or 'ValueTask' + +The type declaring these methods should also respect the following rules: +-The type should be a class +-The class should be 'public' +-The class shouldn't be 'static' +-The class should be marked with '[TestClass]' (or a derived attribute) +-the class should not be generic. + Methods marked with '[GlobalTestInitialize]' or '[GlobalTestCleanup]' should follow the following layout to be valid: +-it can't be declared on a generic class +-it should be 'public' +-it should be 'static' +-it should not be 'async void' +-it should not be a special method (finalizer, operator...). +-it should not be generic +-it should take one parameter of type 'TestContext' +-return type should be 'void', 'Task' or 'ValueTask' + +The type declaring these methods should also respect the following rules: +-The type should be a class +-The class should be 'public' +-The class shouldn't be 'static' +-The class should be marked with '[TestClass]' (or a derived attribute) +-the class should not be generic. + + + + Global test fixture method '{0}' signature is invalid + Global test fixture method '{0}' signature is invalid + + + + GlobalTestInitialize and GlobalTestCleanup methods should have valid layout + GlobalTestInitialize and GlobalTestCleanup methods should have valid layout + + Use 'Assert.Fail' instead of an always-failing 'Assert.{0}' assert Verwenden Sie „Assert.Fail“ anstelle einer Assert-Anweisung „Assert.{0}“, bei der immer ein Fehler auftritt. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf index 29ae9ddffb..602c9c1dd8 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf @@ -447,6 +447,51 @@ El tipo que declara estos métodos también debe respetar las reglas siguientes: Flujo de TestContext.CancellationToken a operaciones asincrónicas + + Methods marked with '[GlobalTestInitialize]' or '[GlobalTestCleanup]' should follow the following layout to be valid: +-it can't be declared on a generic class +-it should be 'public' +-it should be 'static' +-it should not be 'async void' +-it should not be a special method (finalizer, operator...). +-it should not be generic +-it should take one parameter of type 'TestContext' +-return type should be 'void', 'Task' or 'ValueTask' + +The type declaring these methods should also respect the following rules: +-The type should be a class +-The class should be 'public' +-The class shouldn't be 'static' +-The class should be marked with '[TestClass]' (or a derived attribute) +-the class should not be generic. + Methods marked with '[GlobalTestInitialize]' or '[GlobalTestCleanup]' should follow the following layout to be valid: +-it can't be declared on a generic class +-it should be 'public' +-it should be 'static' +-it should not be 'async void' +-it should not be a special method (finalizer, operator...). +-it should not be generic +-it should take one parameter of type 'TestContext' +-return type should be 'void', 'Task' or 'ValueTask' + +The type declaring these methods should also respect the following rules: +-The type should be a class +-The class should be 'public' +-The class shouldn't be 'static' +-The class should be marked with '[TestClass]' (or a derived attribute) +-the class should not be generic. + + + + Global test fixture method '{0}' signature is invalid + Global test fixture method '{0}' signature is invalid + + + + GlobalTestInitialize and GlobalTestCleanup methods should have valid layout + GlobalTestInitialize and GlobalTestCleanup methods should have valid layout + + Use 'Assert.Fail' instead of an always-failing 'Assert.{0}' assert Usar "Assert.Fail" en lugar de una aserción 'Assert.{0}' que siempre tiene errores diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf index 68b1201f73..98163c1a21 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf @@ -447,6 +447,51 @@ Le type doit être une classe Transmettez TestContext.CancellationToken aux opérations asynchrones + + Methods marked with '[GlobalTestInitialize]' or '[GlobalTestCleanup]' should follow the following layout to be valid: +-it can't be declared on a generic class +-it should be 'public' +-it should be 'static' +-it should not be 'async void' +-it should not be a special method (finalizer, operator...). +-it should not be generic +-it should take one parameter of type 'TestContext' +-return type should be 'void', 'Task' or 'ValueTask' + +The type declaring these methods should also respect the following rules: +-The type should be a class +-The class should be 'public' +-The class shouldn't be 'static' +-The class should be marked with '[TestClass]' (or a derived attribute) +-the class should not be generic. + Methods marked with '[GlobalTestInitialize]' or '[GlobalTestCleanup]' should follow the following layout to be valid: +-it can't be declared on a generic class +-it should be 'public' +-it should be 'static' +-it should not be 'async void' +-it should not be a special method (finalizer, operator...). +-it should not be generic +-it should take one parameter of type 'TestContext' +-return type should be 'void', 'Task' or 'ValueTask' + +The type declaring these methods should also respect the following rules: +-The type should be a class +-The class should be 'public' +-The class shouldn't be 'static' +-The class should be marked with '[TestClass]' (or a derived attribute) +-the class should not be generic. + + + + Global test fixture method '{0}' signature is invalid + Global test fixture method '{0}' signature is invalid + + + + GlobalTestInitialize and GlobalTestCleanup methods should have valid layout + GlobalTestInitialize and GlobalTestCleanup methods should have valid layout + + Use 'Assert.Fail' instead of an always-failing 'Assert.{0}' assert Utilisez « Assert.Fail » à la place d’une assertion « Assert.{0} » toujours en échec diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf index 7ea0d3f1b2..5f583a4779 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf @@ -447,6 +447,51 @@ Anche il tipo che dichiara questi metodi deve rispettare le regole seguenti: Flusso da TestContext.CancellationToken a operazioni asincrone + + Methods marked with '[GlobalTestInitialize]' or '[GlobalTestCleanup]' should follow the following layout to be valid: +-it can't be declared on a generic class +-it should be 'public' +-it should be 'static' +-it should not be 'async void' +-it should not be a special method (finalizer, operator...). +-it should not be generic +-it should take one parameter of type 'TestContext' +-return type should be 'void', 'Task' or 'ValueTask' + +The type declaring these methods should also respect the following rules: +-The type should be a class +-The class should be 'public' +-The class shouldn't be 'static' +-The class should be marked with '[TestClass]' (or a derived attribute) +-the class should not be generic. + Methods marked with '[GlobalTestInitialize]' or '[GlobalTestCleanup]' should follow the following layout to be valid: +-it can't be declared on a generic class +-it should be 'public' +-it should be 'static' +-it should not be 'async void' +-it should not be a special method (finalizer, operator...). +-it should not be generic +-it should take one parameter of type 'TestContext' +-return type should be 'void', 'Task' or 'ValueTask' + +The type declaring these methods should also respect the following rules: +-The type should be a class +-The class should be 'public' +-The class shouldn't be 'static' +-The class should be marked with '[TestClass]' (or a derived attribute) +-the class should not be generic. + + + + Global test fixture method '{0}' signature is invalid + Global test fixture method '{0}' signature is invalid + + + + GlobalTestInitialize and GlobalTestCleanup methods should have valid layout + GlobalTestInitialize and GlobalTestCleanup methods should have valid layout + + Use 'Assert.Fail' instead of an always-failing 'Assert.{0}' assert Usare 'Assert.Fail' invece di un'asserzione 'Assert.{0}' che ha sempre esito negativo. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf index 0fb49f127f..36c0e5e429 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf @@ -447,6 +447,51 @@ The type declaring these methods should also respect the following rules: TestContext.CancellationToken を非同期操作にフローする + + Methods marked with '[GlobalTestInitialize]' or '[GlobalTestCleanup]' should follow the following layout to be valid: +-it can't be declared on a generic class +-it should be 'public' +-it should be 'static' +-it should not be 'async void' +-it should not be a special method (finalizer, operator...). +-it should not be generic +-it should take one parameter of type 'TestContext' +-return type should be 'void', 'Task' or 'ValueTask' + +The type declaring these methods should also respect the following rules: +-The type should be a class +-The class should be 'public' +-The class shouldn't be 'static' +-The class should be marked with '[TestClass]' (or a derived attribute) +-the class should not be generic. + Methods marked with '[GlobalTestInitialize]' or '[GlobalTestCleanup]' should follow the following layout to be valid: +-it can't be declared on a generic class +-it should be 'public' +-it should be 'static' +-it should not be 'async void' +-it should not be a special method (finalizer, operator...). +-it should not be generic +-it should take one parameter of type 'TestContext' +-return type should be 'void', 'Task' or 'ValueTask' + +The type declaring these methods should also respect the following rules: +-The type should be a class +-The class should be 'public' +-The class shouldn't be 'static' +-The class should be marked with '[TestClass]' (or a derived attribute) +-the class should not be generic. + + + + Global test fixture method '{0}' signature is invalid + Global test fixture method '{0}' signature is invalid + + + + GlobalTestInitialize and GlobalTestCleanup methods should have valid layout + GlobalTestInitialize and GlobalTestCleanup methods should have valid layout + + Use 'Assert.Fail' instead of an always-failing 'Assert.{0}' assert 常に失敗している 'Assert.{0}' アサートの代わりに 'Assert.Fail' を使用する。 diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf index c8bbae9794..e7a46259d4 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf @@ -447,6 +447,51 @@ The type declaring these methods should also respect the following rules: 비동기 작업으로 TestContext.CancellationToken 흐름 + + Methods marked with '[GlobalTestInitialize]' or '[GlobalTestCleanup]' should follow the following layout to be valid: +-it can't be declared on a generic class +-it should be 'public' +-it should be 'static' +-it should not be 'async void' +-it should not be a special method (finalizer, operator...). +-it should not be generic +-it should take one parameter of type 'TestContext' +-return type should be 'void', 'Task' or 'ValueTask' + +The type declaring these methods should also respect the following rules: +-The type should be a class +-The class should be 'public' +-The class shouldn't be 'static' +-The class should be marked with '[TestClass]' (or a derived attribute) +-the class should not be generic. + Methods marked with '[GlobalTestInitialize]' or '[GlobalTestCleanup]' should follow the following layout to be valid: +-it can't be declared on a generic class +-it should be 'public' +-it should be 'static' +-it should not be 'async void' +-it should not be a special method (finalizer, operator...). +-it should not be generic +-it should take one parameter of type 'TestContext' +-return type should be 'void', 'Task' or 'ValueTask' + +The type declaring these methods should also respect the following rules: +-The type should be a class +-The class should be 'public' +-The class shouldn't be 'static' +-The class should be marked with '[TestClass]' (or a derived attribute) +-the class should not be generic. + + + + Global test fixture method '{0}' signature is invalid + Global test fixture method '{0}' signature is invalid + + + + GlobalTestInitialize and GlobalTestCleanup methods should have valid layout + GlobalTestInitialize and GlobalTestCleanup methods should have valid layout + + Use 'Assert.Fail' instead of an always-failing 'Assert.{0}' assert 항상 실패하는 'Assert.{0}' 어설션 대신 'Assert.Fail'을 사용합니다. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf index 40475312a5..793e4af278 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf @@ -447,6 +447,51 @@ Typ deklarujący te metody powinien również przestrzegać następujących regu Przekaż TestContext.CancellationToken do operacji asynchronicznych + + Methods marked with '[GlobalTestInitialize]' or '[GlobalTestCleanup]' should follow the following layout to be valid: +-it can't be declared on a generic class +-it should be 'public' +-it should be 'static' +-it should not be 'async void' +-it should not be a special method (finalizer, operator...). +-it should not be generic +-it should take one parameter of type 'TestContext' +-return type should be 'void', 'Task' or 'ValueTask' + +The type declaring these methods should also respect the following rules: +-The type should be a class +-The class should be 'public' +-The class shouldn't be 'static' +-The class should be marked with '[TestClass]' (or a derived attribute) +-the class should not be generic. + Methods marked with '[GlobalTestInitialize]' or '[GlobalTestCleanup]' should follow the following layout to be valid: +-it can't be declared on a generic class +-it should be 'public' +-it should be 'static' +-it should not be 'async void' +-it should not be a special method (finalizer, operator...). +-it should not be generic +-it should take one parameter of type 'TestContext' +-return type should be 'void', 'Task' or 'ValueTask' + +The type declaring these methods should also respect the following rules: +-The type should be a class +-The class should be 'public' +-The class shouldn't be 'static' +-The class should be marked with '[TestClass]' (or a derived attribute) +-the class should not be generic. + + + + Global test fixture method '{0}' signature is invalid + Global test fixture method '{0}' signature is invalid + + + + GlobalTestInitialize and GlobalTestCleanup methods should have valid layout + GlobalTestInitialize and GlobalTestCleanup methods should have valid layout + + Use 'Assert.Fail' instead of an always-failing 'Assert.{0}' assert Użyj trybu „Assert.Fail” zamiast kończącej się zawsze niepowodzeniem instrukcji „Assert.{0}” diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf index 5964e79dbf..17c17381a8 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf @@ -447,6 +447,51 @@ O tipo que declara esses métodos também deve respeitar as seguintes regras: Fluxo TestContext.CancellationToken para operações assíncronas + + Methods marked with '[GlobalTestInitialize]' or '[GlobalTestCleanup]' should follow the following layout to be valid: +-it can't be declared on a generic class +-it should be 'public' +-it should be 'static' +-it should not be 'async void' +-it should not be a special method (finalizer, operator...). +-it should not be generic +-it should take one parameter of type 'TestContext' +-return type should be 'void', 'Task' or 'ValueTask' + +The type declaring these methods should also respect the following rules: +-The type should be a class +-The class should be 'public' +-The class shouldn't be 'static' +-The class should be marked with '[TestClass]' (or a derived attribute) +-the class should not be generic. + Methods marked with '[GlobalTestInitialize]' or '[GlobalTestCleanup]' should follow the following layout to be valid: +-it can't be declared on a generic class +-it should be 'public' +-it should be 'static' +-it should not be 'async void' +-it should not be a special method (finalizer, operator...). +-it should not be generic +-it should take one parameter of type 'TestContext' +-return type should be 'void', 'Task' or 'ValueTask' + +The type declaring these methods should also respect the following rules: +-The type should be a class +-The class should be 'public' +-The class shouldn't be 'static' +-The class should be marked with '[TestClass]' (or a derived attribute) +-the class should not be generic. + + + + Global test fixture method '{0}' signature is invalid + Global test fixture method '{0}' signature is invalid + + + + GlobalTestInitialize and GlobalTestCleanup methods should have valid layout + GlobalTestInitialize and GlobalTestCleanup methods should have valid layout + + Use 'Assert.Fail' instead of an always-failing 'Assert.{0}' assert Use "Assert.Fail" em vez de uma asserção "Assert.{0}" sempre com falha diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf index 44be21bae2..00e73f807d 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf @@ -453,6 +453,51 @@ The type declaring these methods should also respect the following rules: Передача TestContext.CancellationToken в асинхронные операции + + Methods marked with '[GlobalTestInitialize]' or '[GlobalTestCleanup]' should follow the following layout to be valid: +-it can't be declared on a generic class +-it should be 'public' +-it should be 'static' +-it should not be 'async void' +-it should not be a special method (finalizer, operator...). +-it should not be generic +-it should take one parameter of type 'TestContext' +-return type should be 'void', 'Task' or 'ValueTask' + +The type declaring these methods should also respect the following rules: +-The type should be a class +-The class should be 'public' +-The class shouldn't be 'static' +-The class should be marked with '[TestClass]' (or a derived attribute) +-the class should not be generic. + Methods marked with '[GlobalTestInitialize]' or '[GlobalTestCleanup]' should follow the following layout to be valid: +-it can't be declared on a generic class +-it should be 'public' +-it should be 'static' +-it should not be 'async void' +-it should not be a special method (finalizer, operator...). +-it should not be generic +-it should take one parameter of type 'TestContext' +-return type should be 'void', 'Task' or 'ValueTask' + +The type declaring these methods should also respect the following rules: +-The type should be a class +-The class should be 'public' +-The class shouldn't be 'static' +-The class should be marked with '[TestClass]' (or a derived attribute) +-the class should not be generic. + + + + Global test fixture method '{0}' signature is invalid + Global test fixture method '{0}' signature is invalid + + + + GlobalTestInitialize and GlobalTestCleanup methods should have valid layout + GlobalTestInitialize and GlobalTestCleanup methods should have valid layout + + Use 'Assert.Fail' instead of an always-failing 'Assert.{0}' assert Используйте "Assert.Fail" вместо утверждения с постоянным сбоем "Assert.{0}" diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf index 6fde92def0..c1cccecf1c 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf @@ -447,6 +447,51 @@ Bu yöntemleri bildiren tipin ayrıca aşağıdaki kurallara uyması gerekir: TestContext.CancellationToken'ı asenkron işlemler için akışa aktarın + + Methods marked with '[GlobalTestInitialize]' or '[GlobalTestCleanup]' should follow the following layout to be valid: +-it can't be declared on a generic class +-it should be 'public' +-it should be 'static' +-it should not be 'async void' +-it should not be a special method (finalizer, operator...). +-it should not be generic +-it should take one parameter of type 'TestContext' +-return type should be 'void', 'Task' or 'ValueTask' + +The type declaring these methods should also respect the following rules: +-The type should be a class +-The class should be 'public' +-The class shouldn't be 'static' +-The class should be marked with '[TestClass]' (or a derived attribute) +-the class should not be generic. + Methods marked with '[GlobalTestInitialize]' or '[GlobalTestCleanup]' should follow the following layout to be valid: +-it can't be declared on a generic class +-it should be 'public' +-it should be 'static' +-it should not be 'async void' +-it should not be a special method (finalizer, operator...). +-it should not be generic +-it should take one parameter of type 'TestContext' +-return type should be 'void', 'Task' or 'ValueTask' + +The type declaring these methods should also respect the following rules: +-The type should be a class +-The class should be 'public' +-The class shouldn't be 'static' +-The class should be marked with '[TestClass]' (or a derived attribute) +-the class should not be generic. + + + + Global test fixture method '{0}' signature is invalid + Global test fixture method '{0}' signature is invalid + + + + GlobalTestInitialize and GlobalTestCleanup methods should have valid layout + GlobalTestInitialize and GlobalTestCleanup methods should have valid layout + + Use 'Assert.Fail' instead of an always-failing 'Assert.{0}' assert Her zaman başarısız olan 'Assert.{0}' onaylaması yerine 'Assert.Fail' seçeneğini kullanın diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf index a4888413c7..2afde7d45e 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf @@ -447,6 +447,51 @@ The type declaring these methods should also respect the following rules: 将 TestContext.CancellationToken 传递给异步操作 + + Methods marked with '[GlobalTestInitialize]' or '[GlobalTestCleanup]' should follow the following layout to be valid: +-it can't be declared on a generic class +-it should be 'public' +-it should be 'static' +-it should not be 'async void' +-it should not be a special method (finalizer, operator...). +-it should not be generic +-it should take one parameter of type 'TestContext' +-return type should be 'void', 'Task' or 'ValueTask' + +The type declaring these methods should also respect the following rules: +-The type should be a class +-The class should be 'public' +-The class shouldn't be 'static' +-The class should be marked with '[TestClass]' (or a derived attribute) +-the class should not be generic. + Methods marked with '[GlobalTestInitialize]' or '[GlobalTestCleanup]' should follow the following layout to be valid: +-it can't be declared on a generic class +-it should be 'public' +-it should be 'static' +-it should not be 'async void' +-it should not be a special method (finalizer, operator...). +-it should not be generic +-it should take one parameter of type 'TestContext' +-return type should be 'void', 'Task' or 'ValueTask' + +The type declaring these methods should also respect the following rules: +-The type should be a class +-The class should be 'public' +-The class shouldn't be 'static' +-The class should be marked with '[TestClass]' (or a derived attribute) +-the class should not be generic. + + + + Global test fixture method '{0}' signature is invalid + Global test fixture method '{0}' signature is invalid + + + + GlobalTestInitialize and GlobalTestCleanup methods should have valid layout + GlobalTestInitialize and GlobalTestCleanup methods should have valid layout + + Use 'Assert.Fail' instead of an always-failing 'Assert.{0}' assert 使用 “Assert.Fail” 而不是始终失败的 “Assert.{0}” 断言 diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf index edc388e035..069c97013d 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf @@ -447,6 +447,51 @@ The type declaring these methods should also respect the following rules: 將 TestContext.CancellationToken 傳遞給非同步作業 + + Methods marked with '[GlobalTestInitialize]' or '[GlobalTestCleanup]' should follow the following layout to be valid: +-it can't be declared on a generic class +-it should be 'public' +-it should be 'static' +-it should not be 'async void' +-it should not be a special method (finalizer, operator...). +-it should not be generic +-it should take one parameter of type 'TestContext' +-return type should be 'void', 'Task' or 'ValueTask' + +The type declaring these methods should also respect the following rules: +-The type should be a class +-The class should be 'public' +-The class shouldn't be 'static' +-The class should be marked with '[TestClass]' (or a derived attribute) +-the class should not be generic. + Methods marked with '[GlobalTestInitialize]' or '[GlobalTestCleanup]' should follow the following layout to be valid: +-it can't be declared on a generic class +-it should be 'public' +-it should be 'static' +-it should not be 'async void' +-it should not be a special method (finalizer, operator...). +-it should not be generic +-it should take one parameter of type 'TestContext' +-return type should be 'void', 'Task' or 'ValueTask' + +The type declaring these methods should also respect the following rules: +-The type should be a class +-The class should be 'public' +-The class shouldn't be 'static' +-The class should be marked with '[TestClass]' (or a derived attribute) +-the class should not be generic. + + + + Global test fixture method '{0}' signature is invalid + Global test fixture method '{0}' signature is invalid + + + + GlobalTestInitialize and GlobalTestCleanup methods should have valid layout + GlobalTestInitialize and GlobalTestCleanup methods should have valid layout + + Use 'Assert.Fail' instead of an always-failing 'Assert.{0}' assert 使用 'Assert.Fail',而不是一直失敗的 'Assert.{0}' 聲明 diff --git a/src/Analyzers/MSTest.GlobalConfigsGenerator/AnalyzerSeverityDecider.cs b/src/Analyzers/MSTest.GlobalConfigsGenerator/AnalyzerSeverityDecider.cs index adf182083e..ac1370ab38 100644 --- a/src/Analyzers/MSTest.GlobalConfigsGenerator/AnalyzerSeverityDecider.cs +++ b/src/Analyzers/MSTest.GlobalConfigsGenerator/AnalyzerSeverityDecider.cs @@ -86,7 +86,8 @@ internal static class AnalyzerSeverityDecider if (rule.IsEnabledByDefault && rule.DefaultSeverity >= DiagnosticSeverity.Info) { // Recommended mode will elevate info to warning only if the rule is enabled by default. - return DiagnosticSeverity.Warning; + // In addition, if the rule is already error by default, we keep it as error. So, choose the max between warning and default severity. + return (DiagnosticSeverity)Math.Max((int)rule.DefaultSeverity, (int)DiagnosticSeverity.Warning); } if (rule.DefaultSeverity >= DiagnosticSeverity.Warning) @@ -117,6 +118,8 @@ internal static class AnalyzerSeverityDecider return rule.IsEnabledByDefault ? rule.DefaultSeverity : null; } - private static DiagnosticSeverity? DecideForModeNone(DiagnosticDescriptor _) - => null; + private static DiagnosticSeverity? DecideForModeNone(DiagnosticDescriptor rule) + // Even with 'None' mode, we still keep the rules that are errors by default. + // Such rules are likely to be critical and shouldn't be suppressed by MSTestAnalysisMode None. + => rule.DefaultSeverity == DiagnosticSeverity.Error ? DiagnosticSeverity.Error : null; } diff --git a/src/TestFramework/TestFramework/Attributes/Lifecycle/Cleanup/GlobalTestCleanupAttribute.cs b/src/TestFramework/TestFramework/Attributes/Lifecycle/Cleanup/GlobalTestCleanupAttribute.cs new file mode 100644 index 0000000000..fcb06aad7b --- /dev/null +++ b/src/TestFramework/TestFramework/Attributes/Lifecycle/Cleanup/GlobalTestCleanupAttribute.cs @@ -0,0 +1,14 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +namespace Microsoft.VisualStudio.TestTools.UnitTesting; + +/// +/// A global test cleanup attribute that applies to every test method in the assembly. +/// The method to which this attribute is applied must be public, static, non-generic, has a single parameter of type TestContext, and either returns void or a Task. +/// +/// +/// Multiple methods with this attribute in the assembly is allowed, but there is no guarantee of the order in which they will be executed. +/// +[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] +public sealed class GlobalTestCleanupAttribute : Attribute; diff --git a/src/TestFramework/TestFramework/Attributes/Lifecycle/Initialization/GlobalTestInitializeAttribute.cs b/src/TestFramework/TestFramework/Attributes/Lifecycle/Initialization/GlobalTestInitializeAttribute.cs new file mode 100644 index 0000000000..ae7b0be236 --- /dev/null +++ b/src/TestFramework/TestFramework/Attributes/Lifecycle/Initialization/GlobalTestInitializeAttribute.cs @@ -0,0 +1,14 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +namespace Microsoft.VisualStudio.TestTools.UnitTesting; + +/// +/// A global test initialize attribute that applies to every test method in the assembly. +/// The method to which this attribute is applied must be public, static, non-generic, has a single parameter of type TestContext, and either returns void or a Task. +/// +/// +/// Multiple methods with this attribute in the assembly is allowed, but there is no guarantee of the order in which they will be executed. In addition, TimeoutAttribute isn't supported on methods with this attribute. +/// +[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] +public sealed class GlobalTestInitializeAttribute : Attribute; diff --git a/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Unshipped.txt b/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Unshipped.txt index 0abf8e4d29..abe780feb5 100644 --- a/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Unshipped.txt +++ b/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Unshipped.txt @@ -4,6 +4,10 @@ Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AssertThrowsExactlyInterpola Microsoft.VisualStudio.TestTools.UnitTesting.CIConditionAttribute Microsoft.VisualStudio.TestTools.UnitTesting.CIConditionAttribute.CIConditionAttribute(Microsoft.VisualStudio.TestTools.UnitTesting.ConditionMode mode) -> void Microsoft.VisualStudio.TestTools.UnitTesting.ConditionBaseAttribute.Mode.get -> Microsoft.VisualStudio.TestTools.UnitTesting.ConditionMode +Microsoft.VisualStudio.TestTools.UnitTesting.GlobalTestCleanupAttribute +Microsoft.VisualStudio.TestTools.UnitTesting.GlobalTestCleanupAttribute.GlobalTestCleanupAttribute() -> void +Microsoft.VisualStudio.TestTools.UnitTesting.GlobalTestInitializeAttribute +Microsoft.VisualStudio.TestTools.UnitTesting.GlobalTestInitializeAttribute.GlobalTestInitializeAttribute() -> void override Microsoft.VisualStudio.TestTools.UnitTesting.CIConditionAttribute.GroupName.get -> string! override Microsoft.VisualStudio.TestTools.UnitTesting.CIConditionAttribute.IgnoreMessage.get -> string? override Microsoft.VisualStudio.TestTools.UnitTesting.CIConditionAttribute.IgnoreMessage.set -> void diff --git a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/LifecycleTests.cs b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/LifecycleTests.cs new file mode 100644 index 0000000000..98ceefdc11 --- /dev/null +++ b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/LifecycleTests.cs @@ -0,0 +1,249 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using Microsoft.Testing.Platform.Acceptance.IntegrationTests; +using Microsoft.Testing.Platform.Acceptance.IntegrationTests.Helpers; +using Microsoft.Testing.Platform.Helpers; + +namespace MSTest.Acceptance.IntegrationTests; + +[TestClass] +public sealed class LifecycleTests : AcceptanceTestBase +{ + [TestMethod] + [DynamicData(nameof(TargetFrameworks.AllForDynamicData), typeof(TargetFrameworks))] + public async Task LifecycleTest(string tfm) + { + var testHost = TestHost.LocateFrom(AssetFixture.ProjectPath, TestAssetFixture.ProjectName, tfm); + TestHostResult testHostResult = await testHost.ExecuteAsync("--settings my.runsettings"); + + testHostResult.AssertExitCodeIs(ExitCodes.Success); + testHostResult.AssertOutputContainsSummary(failed: 0, passed: 4, skipped: 0); + // Order is: + // - Assembly initialize + // - foreach test class + // - ClassInitialize + // - foreach test: + // - GlobalTestInitialize + // - ctor + // - TestContext property setter + // - TestInitialize + // - TestMethod + // - TestCleanup + // - Dispose + // - GlobalTestCleanup + // - ClassCleanup + // - AssemblyCleanup + testHostResult.AssertOutputContains(""" + AssemblyInitialize called. + TestClass1.ClassInitialize called. + GlobalTestInitialize called for 'TestMethodParameterized (0)'. + TestClass1 constructor called. + TestContext property set for TestClass1. + TestClass1.TestInitialize for 'TestMethodParameterized (0)' is called. + TestMethodParameterized called with: 0 + TestClass1.TestCleanup for 'TestMethodParameterized (0)' is called. + TestClass1 disposed. + GlobalTestCleanup called for 'TestMethodParameterized (0)'. + GlobalTestInitialize called for 'TestMethodParameterized (1)'. + TestClass1 constructor called. + TestContext property set for TestClass1. + TestClass1.TestInitialize for 'TestMethodParameterized (1)' is called. + TestMethodParameterized called with: 1 + TestClass1.TestCleanup for 'TestMethodParameterized (1)' is called. + TestClass1 disposed. + GlobalTestCleanup called for 'TestMethodParameterized (1)'. + GlobalTestInitialize called for 'TestMethodNonParameterized'. + TestClass1 constructor called. + TestContext property set for TestClass1. + TestClass1.TestInitialize for 'TestMethodNonParameterized' is called. + TestMethodNonParameterized called + TestClass1.TestCleanup for 'TestMethodNonParameterized' is called. + TestClass1 disposed. + GlobalTestCleanup called for 'TestMethodNonParameterized'. + TestClass1.ClassCleanup called. + TestClass2.ClassInitialize called. + GlobalTestInitialize called for 'TestMethodFromTestClass2'. + TestClass2 constructor called. + TestContext property set for TestClass2. + TestClass2.TestInitialize for 'TestMethodFromTestClass2' is called. + TestMethodFromTestClass2 called + TestClass2.TestCleanup for 'TestMethodFromTestClass2' is called. + TestClass2 disposed. + GlobalTestCleanup called for 'TestMethodFromTestClass2'. + TestClass2.ClassCleanup called. + AssemblyCleanup called. + """); + } + + public sealed class TestAssetFixture() : TestAssetFixtureBase(AcceptanceFixture.NuGetGlobalPackagesFolder) + { + public const string ProjectName = "LifecycleTests"; + + public string ProjectPath => GetAssetPath(ProjectName); + + public override IEnumerable<(string ID, string Name, string Code)> GetAssetsToGenerate() + { + yield return (ProjectName, ProjectName, + SourceCode + .PatchTargetFrameworks(TargetFrameworks.All) + .PatchCodeWithReplace("$MSTestVersion$", MSTestVersion)); + } + + private const string SourceCode = """ +#file LifecycleTests.csproj + + + + Exe + true + $TargetFrameworks$ + preview + + + + + + + + + + PreserveNewest + + + + +#file TestClass1.cs +using System; +using System.Collections.Generic; +using System.Text; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +[TestClass] +public static class Fixtures +{ + [AssemblyInitialize] + public static void AssemblyInitialize(TestContext context) + => Console.WriteLine("AssemblyInitialize called."); + + [AssemblyCleanup] + public static void AssemblyCleanup(TestContext context) + => Console.WriteLine("AssemblyCleanup called."); + + [GlobalTestInitialize] + public static void GlobalTestInitialize(TestContext context) + => Console.WriteLine($"GlobalTestInitialize called for '{context.TestDisplayName}'."); + + [GlobalTestCleanup] + public static void GlobalTestCleanup(TestContext context) + => Console.WriteLine($"GlobalTestCleanup called for '{context.TestDisplayName}'."); +} + +[TestClass] +public class TestClass1 : IDisposable +{ + public TestClass1() + { + Console.WriteLine("TestClass1 constructor called."); + } + + public TestContext TestContext + { + get => field; + set + { + field = value; + Console.WriteLine("TestContext property set for TestClass1."); + } + } + + [TestInitialize] + public void TestInitialize() + { + Console.WriteLine($"TestClass1.TestInitialize for '{TestContext.TestDisplayName}' is called."); + } + + [TestCleanup] + public void TestCleanup() + { + Console.WriteLine($"TestClass1.TestCleanup for '{TestContext.TestDisplayName}' is called."); + } + + [ClassInitialize] + public static void ClassInitialize(TestContext context) + => Console.WriteLine("TestClass1.ClassInitialize called."); + + [ClassCleanup] + public static void ClassCleanup(TestContext context) + => Console.WriteLine("TestClass1.ClassCleanup called."); + + [TestMethod] + [DataRow(0)] + [DataRow(1)] + public void TestMethodParameterized(int a) + => Console.WriteLine($"TestMethodParameterized called with: {a}"); + + [TestMethod] + public void TestMethodNonParameterized() + => Console.WriteLine("TestMethodNonParameterized called"); + + public void Dispose() + => Console.WriteLine("TestClass1 disposed."); +} + +[TestClass] +public class TestClass2 : IDisposable +{ + public TestClass2() + { + Console.WriteLine("TestClass2 constructor called."); + } + + public TestContext TestContext + { + get => field; + set + { + field = value; + Console.WriteLine("TestContext property set for TestClass2."); + } + } + + [TestInitialize] + public void TestInitialize() + { + Console.WriteLine($"TestClass2.TestInitialize for '{TestContext.TestDisplayName}' is called."); + } + + [TestCleanup] + public void TestCleanup() + { + Console.WriteLine($"TestClass2.TestCleanup for '{TestContext.TestDisplayName}' is called."); + } + + [ClassInitialize] + public static void ClassInitialize(TestContext context) + => Console.WriteLine("TestClass2.ClassInitialize called."); + + [ClassCleanup] + public static void ClassCleanup(TestContext context) + => Console.WriteLine("TestClass2.ClassCleanup called."); + + [TestMethod] + public void TestMethodFromTestClass2() + => Console.WriteLine("TestMethodFromTestClass2 called"); + + public void Dispose() + => Console.WriteLine("TestClass2 disposed."); +} + +#file my.runsettings + + + false + EndOfClass + + +"""; + } +} diff --git a/test/UnitTests/MSTest.Analyzers.UnitTests/GlobalTestFixtureShouldBeValidAnalyzerTests.cs b/test/UnitTests/MSTest.Analyzers.UnitTests/GlobalTestFixtureShouldBeValidAnalyzerTests.cs new file mode 100644 index 0000000000..74f754c64e --- /dev/null +++ b/test/UnitTests/MSTest.Analyzers.UnitTests/GlobalTestFixtureShouldBeValidAnalyzerTests.cs @@ -0,0 +1,301 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using VerifyCS = MSTest.Analyzers.Test.CSharpCodeFixVerifier< + MSTest.Analyzers.GlobalTestFixtureShouldBeValidAnalyzer, + Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>; + +namespace MSTest.Analyzers.Test; + +[TestClass] +public sealed class GlobalTestFixtureShouldBeValidAnalyzerTests +{ + [TestMethod] + public async Task WhenGlobalTestInitializeIsValid_NoDiagnostic() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [GlobalTestInitialize] + public static void GlobalTestInitialize(TestContext testContext) + { + } + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, code); + } + + [TestMethod] + public async Task WhenGlobalTestCleanupIsValid_NoDiagnostic() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [GlobalTestCleanup] + public static void GlobalTestCleanup(TestContext testContext) + { + } + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, code); + } + + [TestMethod] + public async Task WhenGlobalTestInitializeIsAsyncTask_NoDiagnostic() + { + string code = """ + using System.Threading.Tasks; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [GlobalTestInitialize] + public static async Task GlobalTestInitialize(TestContext testContext) + { + await Task.Delay(100); + } + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, code); + } + + [TestMethod] + public async Task WhenGlobalTestCleanupIsAsyncValueTask_NoDiagnostic() + { + string code = """ + using System.Threading.Tasks; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [GlobalTestCleanup] + public static async ValueTask GlobalTestCleanup(TestContext testContext) + { + await Task.Delay(100); + } + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, code); + } + + [TestMethod] + public async Task WhenGlobalTestInitializeIsNotStatic_Diagnostic() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [GlobalTestInitialize] + public void [|GlobalTestInitialize|](TestContext testContext) + { + } + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, code); + } + + [TestMethod] + public async Task WhenGlobalTestCleanupIsNotPublic_Diagnostic() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [GlobalTestCleanup] + private static void [|GlobalTestCleanup|](TestContext testContext) + { + } + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, code); + } + + [TestMethod] + public async Task WhenGlobalTestInitializeHasNoParameters_Diagnostic() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [GlobalTestInitialize] + public static void [|GlobalTestInitialize|]() + { + } + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, code); + } + + [TestMethod] + public async Task WhenGlobalTestCleanupHasWrongParameterType_Diagnostic() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [GlobalTestCleanup] + public static void [|GlobalTestCleanup|](string param) + { + } + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, code); + } + + [TestMethod] + public async Task WhenGlobalTestInitializeHasTooManyParameters_Diagnostic() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [GlobalTestInitialize] + public static void [|GlobalTestInitialize|](TestContext testContext, string extraParam) + { + } + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, code); + } + + [TestMethod] + public async Task WhenGlobalTestCleanupIsGeneric_Diagnostic() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [GlobalTestCleanup] + public static void [|GlobalTestCleanup|](TestContext testContext) + { + } + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, code); + } + + [TestMethod] + public async Task WhenGlobalTestInitializeIsAsyncVoid_Diagnostic() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [GlobalTestInitialize] + public static async void [|GlobalTestInitialize|](TestContext testContext) + { + } + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, code); + } + + [TestMethod] + public async Task WhenGlobalTestCleanupReturnsInt_Diagnostic() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [GlobalTestCleanup] + public static int [|GlobalTestCleanup|](TestContext testContext) + { + return 0; + } + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, code); + } + + [TestMethod] + public async Task WhenGlobalTestCleanupInInternalClassWithoutDiscoverInternals_Diagnostic() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + internal class MyTestClass + { + [GlobalTestCleanup] + public static void [|GlobalTestCleanup|](TestContext testContext) + { + } + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, code); + } + + [TestMethod] + public async Task WhenGlobalTestInitializeInStaticClass_NoDiagnostic() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public static class MyTestClass + { + [GlobalTestInitialize] + public static void GlobalTestInitialize(TestContext testContext) + { + } + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, code); + } + + [TestMethod] + public async Task WhenGlobalTestCleanupInClassWithoutTestClassAttribute_Diagnostic() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + public class MyTestClass + { + [GlobalTestCleanup] + public static void [|GlobalTestCleanup|](TestContext testContext) + { + } + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, code); + } +} diff --git a/test/UnitTests/MSTest.Analyzers.UnitTests/TestClassShouldHaveTestMethodAnalyzerTests.cs b/test/UnitTests/MSTest.Analyzers.UnitTests/TestClassShouldHaveTestMethodAnalyzerTests.cs index 46bff4564b..e92555de5b 100644 --- a/test/UnitTests/MSTest.Analyzers.UnitTests/TestClassShouldHaveTestMethodAnalyzerTests.cs +++ b/test/UnitTests/MSTest.Analyzers.UnitTests/TestClassShouldHaveTestMethodAnalyzerTests.cs @@ -287,4 +287,65 @@ await VerifyCS.VerifyAnalyzerAsync( .WithLocation(0) .WithArguments("Derived")); } + + [TestMethod] + public async Task WhenStaticTestClassWithGlobalTestInitialize_DoesNotHaveTestMethod_NoDiagnostic() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public static class MyTestClass + { + [GlobalTestInitialize] + public static void GlobalTestInitialize(TestContext context) + { + } + } + """; + + await VerifyCS.VerifyAnalyzerAsync(code); + } + + [TestMethod] + public async Task WhenStaticTestClassWithGlobalTestCleanup_DoesNotHaveTestMethod_NoDiagnostic() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public static class MyTestClass + { + [GlobalTestCleanup] + public static void GlobalTestCleanup(TestContext context) + { + } + } + """; + + await VerifyCS.VerifyAnalyzerAsync(code); + } + + [TestMethod] + public async Task WhenNonStaticTestClassWithGlobalTestInitialize_DoesNotHaveTestMethod_Diagnostic() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class {|#0:MyTestClass|} + { + [GlobalTestInitialize] + public static void GlobalTestInitialize(TestContext context) + { + } + } + """; + + await VerifyCS.VerifyAnalyzerAsync( + code, + VerifyCS.Diagnostic(TestClassShouldHaveTestMethodAnalyzer.TestClassShouldHaveTestMethodRule) + .WithLocation(0) + .WithArguments("MyTestClass")); + } } diff --git a/test/UnitTests/MSTest.Analyzers.UnitTests/UnusedParameterSuppressorTests.cs b/test/UnitTests/MSTest.Analyzers.UnitTests/UnusedParameterSuppressorTests.cs index b60b8d6403..d620499902 100644 --- a/test/UnitTests/MSTest.Analyzers.UnitTests/UnusedParameterSuppressorTests.cs +++ b/test/UnitTests/MSTest.Analyzers.UnitTests/UnusedParameterSuppressorTests.cs @@ -103,6 +103,66 @@ public static void Initialize(TestContext {|#0:context|}) }.RunAsync(); } + [TestMethod] + public async Task GlobalTestInitializeWithUnusedTestContext_DiagnosticIsSuppressed() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public static class SomeClass + { + [GlobalTestInitialize] + public static void Initialize(TestContext [|context|]) + { + // TestContext parameter is unused but required by MSTest + } + } + """; + + // Verify issue is reported without suppressor + await new VerifyCS.Test + { + TestState = { Sources = { code } }, + }.RunAsync(); + + // Verify issue is suppressed with suppressor + await new TestWithSuppressor + { + TestState = { Sources = { code } }, + }.RunAsync(); + } + + [TestMethod] + public async Task GlobalTestCleanupWithUnusedTestContext_DiagnosticIsSuppressed() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public static class SomeClass + { + [GlobalTestCleanup] + public static void Cleanup(TestContext [|context|]) + { + // TestContext parameter is unused but required by MSTest + } + } + """; + + // Verify issue is reported without suppressor + await new VerifyCS.Test + { + TestState = { Sources = { code } }, + }.RunAsync(); + + // Verify issue is suppressed with suppressor + await new TestWithSuppressor + { + TestState = { Sources = { code } }, + }.RunAsync(); + } + [TestMethod] public async Task TestMethodWithUnusedParameter_DiagnosticIsNotSuppressed() { diff --git a/test/UnitTests/MSTest.Analyzers.UnitTests/UseAsyncSuffixTestFixtureMethodSuppressorTests.cs b/test/UnitTests/MSTest.Analyzers.UnitTests/UseAsyncSuffixTestFixtureMethodSuppressorTests.cs index 8badc85830..d72f02d562 100644 --- a/test/UnitTests/MSTest.Analyzers.UnitTests/UseAsyncSuffixTestFixtureMethodSuppressorTests.cs +++ b/test/UnitTests/MSTest.Analyzers.UnitTests/UseAsyncSuffixTestFixtureMethodSuppressorTests.cs @@ -99,6 +99,54 @@ public class SomeClass }.RunAsync(); } + [TestMethod] + public async Task GlobalTestMethodsWithoutAsyncSuffix_DiagnosticIsSuppressed() + { + string code = @" +using System.Threading.Tasks; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +[TestClass] +public static class SomeClass +{ + [GlobalTestInitialize] + public static async Task {|#0:GlobalTestInitialize|}(TestContext context) { } + + [GlobalTestCleanup] + public static async Task {|#1:GlobalTestCleanup|}(TestContext context) { } +} +"; + + // Verify issues Are reported + await new VerifyCS.Test + { + TestState = { Sources = { code } }, + ExpectedDiagnostics = + { + VerifyCS.Diagnostic(WarnForMissingAsyncSuffix.Rule) + .WithLocation(0) + .WithIsSuppressed(false), + VerifyCS.Diagnostic(WarnForMissingAsyncSuffix.Rule) + .WithLocation(1) + .WithIsSuppressed(false), + }, + }.RunAsync(); + + await new TestWithSuppressor + { + TestState = { Sources = { code } }, + ExpectedDiagnostics = + { + VerifyCS.Diagnostic(WarnForMissingAsyncSuffix.Rule) + .WithLocation(0) + .WithIsSuppressed(true), + VerifyCS.Diagnostic(WarnForMissingAsyncSuffix.Rule) + .WithLocation(1) + .WithIsSuppressed(true), + }, + }.RunAsync(); + } + [TestMethod] public async Task AsyncTestMethodWithSuffix_NoDiagnostic() { @@ -126,6 +174,12 @@ public async Task TestInitializeAsync() { } [TestCleanup] public async Task TestCleanupAsync() { } + + [GlobalTestInitialize] + public static async Task GlobalTestInitializeAsync(TestContext context) { } + + [GlobalTestCleanup] + public static async Task GlobalTestCleanupAsync(TestContext context) { } } """; From 4517f8a354d3e066d8e44796b37a1064b6bfd8a7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Mon, 28 Jul 2025 14:36:08 +0200 Subject: [PATCH 305/541] Bump runtimes (#6199) --- global.json | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/global.json b/global.json index 0966c00fae..90d31ae135 100644 --- a/global.json +++ b/global.json @@ -6,16 +6,16 @@ "3.1.32", "6.0.36", "7.0.20", - "8.0.14", - "9.0.3" + "8.0.18", + "9.0.7" ], "dotnet/x86": [ "3.1.32", "6.0.36", - "9.0.3" + "9.0.7" ], "aspnetcore": [ - "9.0.3" + "9.0.7" ] }, "vs": { From 98b8b7dbe331a9a1623129882e842fd2806b71bf Mon Sep 17 00:00:00 2001 From: Copilot <198982749+Copilot@users.noreply.github.com> Date: Mon, 28 Jul 2025 20:04:49 +0200 Subject: [PATCH 306/541] Add timeout tests for GlobalTestInitializeAttribute and GlobalTestCleanupAttribute (#6200) Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: Evangelink <11340282+Evangelink@users.noreply.github.com> --- .../TimeoutTests.cs | 153 ++++++++++++++++++ 1 file changed, 153 insertions(+) diff --git a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/TimeoutTests.cs b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/TimeoutTests.cs index 05cab7771b..e6cbc2c257 100644 --- a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/TimeoutTests.cs +++ b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/TimeoutTests.cs @@ -21,6 +21,8 @@ public class TimeoutTests : AcceptanceTestBase ["baseClassCleanup"] = ("TestClassBase.ClassCleanupBase", "Class cleanup", "BASE_CLASSCLEANUP", "ClassCleanupTimeout"), ["testInit"] = ("TestClass.TestInit", "Test initialize", "TESTINIT", "TestInitializeTimeout"), ["testCleanup"] = ("TestClass.TestCleanupMethod", "Test cleanup", "TESTCLEANUP", "TestCleanupTimeout"), + ["globalTestInit"] = ("TestClass.GlobalTestInit", "Test initialize", "GLOBALTESTINIT", "TestInitializeTimeout"), + ["globalTestCleanup"] = ("TestClass.GlobalTestCleanupMethod", "Test cleanup", "GLOBALTESTCLEANUP", "TestCleanupTimeout"), }; [TestMethod] @@ -155,6 +157,50 @@ public async Task AssemblyCleanup_WhenTimeoutExpires_FromRunSettings_AssemblyCle public async Task AssemblyCleanup_WhenTimeoutExpires_AssemblyCleanupIsCanceled_AttributeTakesPrecedence(string tfm) => await RunAndAssertWithRunSettingsAsync(tfm, 25000, true, "assemblyCleanup"); + [TestMethod] + [DynamicData(nameof(TargetFrameworks.AllForDynamicData), typeof(TargetFrameworks))] + public async Task GlobalTestInit_WhenTestContextCanceled_GlobalTestInitializeTaskIsCanceled(string tfm) + => await RunAndAssertTestWasCanceledAsync(AssetFixture.CodeWithSixtySecTimeoutAssetPath, TestAssetFixture.CodeWithSixtySecTimeout, + tfm, "TESTCONTEXT_CANCEL_", "globalTestInit"); + + [TestMethod] + [DynamicData(nameof(TargetFrameworks.AllForDynamicData), typeof(TargetFrameworks))] + public async Task GlobalTestInit_WhenTimeoutExpires_GlobalTestInitializeTaskIsCanceled(string tfm) + => await RunAndAssertTestTimedOutAsync(AssetFixture.CodeWithOneSecTimeoutAssetPath, TestAssetFixture.CodeWithOneSecTimeout, + tfm, "LONG_WAIT_", "globalTestInit"); + + [TestMethod] + [DynamicData(nameof(TargetFrameworks.AllForDynamicData), typeof(TargetFrameworks))] + public async Task GlobalTestInit_WhenTimeoutExpiresAndTestContextTokenIsUsed_GlobalTestInitializeExits(string tfm) + => await RunAndAssertTestTimedOutAsync(AssetFixture.CodeWithOneSecTimeoutAssetPath, TestAssetFixture.CodeWithOneSecTimeout, tfm, + "TIMEOUT_", "globalTestInit"); + + [TestMethod] + [DynamicData(nameof(TargetFrameworks.AllForDynamicData), typeof(TargetFrameworks))] + public async Task GlobalTestInit_WhenTimeoutExpires_FromRunSettings_GlobalTestInitializeIsCanceled(string tfm) + => await RunAndAssertWithRunSettingsAsync(tfm, 300, false, "globalTestInit"); + + [TestMethod] + [DynamicData(nameof(TargetFrameworks.AllForDynamicData), typeof(TargetFrameworks))] + public async Task GlobalTestInit_WhenTimeoutExpires_GlobalTestInitializeIsCanceled_AttributeTakesPrecedence(string tfm) + => await RunAndAssertWithRunSettingsAsync(tfm, 25000, true, "globalTestInit"); + + [TestMethod] + [DynamicData(nameof(TargetFrameworks.AllForDynamicData), typeof(TargetFrameworks))] + public async Task GlobalTestCleanup_WhenTimeoutExpires_GlobalTestCleanupTaskIsCanceled(string tfm) + => await RunAndAssertTestTimedOutAsync(AssetFixture.CodeWithOneSecTimeoutAssetPath, TestAssetFixture.CodeWithOneSecTimeout, tfm, + "LONG_WAIT_", "globalTestCleanup"); + + [TestMethod] + [DynamicData(nameof(TargetFrameworks.AllForDynamicData), typeof(TargetFrameworks))] + public async Task GlobalTestCleanup_WhenTimeoutExpires_FromRunSettings_GlobalTestCleanupIsCanceled(string tfm) + => await RunAndAssertWithRunSettingsAsync(tfm, 300, false, "globalTestCleanup"); + + [TestMethod] + [DynamicData(nameof(TargetFrameworks.AllForDynamicData), typeof(TargetFrameworks))] + public async Task GlobalTestCleanup_WhenTimeoutExpires_GlobalTestCleanupIsCanceled_AttributeTakesPrecedence(string tfm) + => await RunAndAssertWithRunSettingsAsync(tfm, 25000, true, "globalTestCleanup"); + [TestMethod] [DynamicData(nameof(TargetFrameworks.AllForDynamicData), typeof(TargetFrameworks))] public async Task TestInitialize_WhenTimeoutExpires_TestInitializeTaskIsCanceled(string tfm) @@ -275,6 +321,36 @@ public async Task CooperativeCancellation_WhenTestCleanupTimeoutExpires_StepThro testHostResult.AssertOutputDoesNotContain("TestCleanup completed"); } + [TestMethod] + [DynamicData(nameof(TargetFrameworks.AllForDynamicData), typeof(TargetFrameworks))] + public async Task CooperativeCancellation_WhenGlobalTestInitTimeoutExpires_StepThrows(string tfm) + { + var testHost = TestHost.LocateFrom(AssetFixture.CooperativeTimeoutAssetPath, TestAssetFixture.CooperativeTimeout, tfm); + TestHostResult testHostResult = await testHost.ExecuteAsync( + "--settings my.runsettings", + new() { ["TASKDELAY_GLOBALTESTINIT"] = "1" }); + + testHostResult.AssertOutputContains("GlobalTestInit started"); + testHostResult.AssertOutputContains("Test initialize method 'TestClass.GlobalTestInit' timed out after 1000ms"); + testHostResult.AssertOutputDoesNotContain("GlobalTestInit Thread.Sleep completed"); + testHostResult.AssertOutputDoesNotContain("GlobalTestInit completed"); + } + + [TestMethod] + [DynamicData(nameof(TargetFrameworks.AllForDynamicData), typeof(TargetFrameworks))] + public async Task CooperativeCancellation_WhenGlobalTestCleanupTimeoutExpires_StepThrows(string tfm) + { + var testHost = TestHost.LocateFrom(AssetFixture.CooperativeTimeoutAssetPath, TestAssetFixture.CooperativeTimeout, tfm); + TestHostResult testHostResult = await testHost.ExecuteAsync( + "--settings my.runsettings", + new() { ["TASKDELAY_GLOBALTESTCLEANUP"] = "1" }); + + testHostResult.AssertOutputContains("GlobalTestCleanup started"); + testHostResult.AssertOutputContains("Test cleanup method 'TestClass.GlobalTestCleanup' timed out after 1000ms"); + testHostResult.AssertOutputDoesNotContain("GlobalTestCleanup Thread.Sleep completed"); + testHostResult.AssertOutputDoesNotContain("GlobalTestCleanup completed"); + } + [TestMethod] [DynamicData(nameof(TargetFrameworks.AllForDynamicData), typeof(TargetFrameworks))] public async Task CooperativeCancellation_WhenAssemblyInitTimeoutExpiresAndUserChecksToken_StepThrows(string tfm) @@ -363,6 +439,36 @@ public async Task CooperativeCancellation_WhenTestCleanupTimeoutExpiresAndUserCh testHostResult.AssertOutputContains("Test cleanup method 'TestClass.TestCleanup' timed out after 1000ms"); } + [TestMethod] + [DynamicData(nameof(TargetFrameworks.AllForDynamicData), typeof(TargetFrameworks))] + public async Task CooperativeCancellation_WhenGlobalTestInitTimeoutExpiresAndUserChecksToken_StepThrows(string tfm) + { + var testHost = TestHost.LocateFrom(AssetFixture.CooperativeTimeoutAssetPath, TestAssetFixture.CooperativeTimeout, tfm); + TestHostResult testHostResult = await testHost.ExecuteAsync( + "--settings my.runsettings", + new() { ["CHECKTOKEN_GLOBALTESTINIT"] = "1" }); + + testHostResult.AssertOutputContains("GlobalTestInit started"); + testHostResult.AssertOutputContains("GlobalTestInit Thread.Sleep completed"); + testHostResult.AssertOutputContains("Test initialize method 'TestClass.GlobalTestInit' timed out after 1000ms"); + testHostResult.AssertOutputDoesNotContain("GlobalTestInit completed"); + } + + [TestMethod] + [DynamicData(nameof(TargetFrameworks.AllForDynamicData), typeof(TargetFrameworks))] + public async Task CooperativeCancellation_WhenGlobalTestCleanupTimeoutExpiresAndUserChecksToken_StepThrows(string tfm) + { + var testHost = TestHost.LocateFrom(AssetFixture.CooperativeTimeoutAssetPath, TestAssetFixture.CooperativeTimeout, tfm); + TestHostResult testHostResult = await testHost.ExecuteAsync( + "--settings my.runsettings", + new() { ["CHECKTOKEN_GLOBALTESTCLEANUP"] = "1" }); + + testHostResult.AssertOutputContains("GlobalTestCleanup started"); + testHostResult.AssertOutputContains("GlobalTestCleanup Thread.Sleep completed"); + testHostResult.AssertOutputContains("Test cleanup method 'TestClass.GlobalTestCleanup' timed out after 1000ms"); + testHostResult.AssertOutputDoesNotContain("GlobalTestCleanup completed"); + } + private static async Task RunAndAssertTestWasCanceledAsync(string rootFolder, string assetName, string tfm, string envVarPrefix, string entryKind) { var testHost = TestHost.LocateFrom(rootFolder, assetName, tfm); @@ -701,6 +807,16 @@ public async Task TestInit() public async Task TestCleanup() => await DoWork("TESTCLEANUP", "TestCleanup", TestContext); + [Timeout(1000, CooperativeCancellation = true)] + [GlobalTestInitialize] + public static async Task GlobalTestInit(TestContext testContext) + => await DoWork("GLOBALTESTINIT", "GlobalTestInit", testContext); + + [Timeout(1000, CooperativeCancellation = true)] + [GlobalTestCleanup] + public static async Task GlobalTestCleanup(TestContext testContext) + => await DoWork("GLOBALTESTCLEANUP", "GlobalTestCleanup", testContext); + [TestMethod] public void TestMethod() { @@ -900,6 +1016,43 @@ public async Task TestCleanupMethod() } } + $TimeoutAttribute$ + [GlobalTestInitialize] + public static async Task GlobalTestInit(TestContext testContext) + { + if (Environment.GetEnvironmentVariable("TESTCONTEXT_CANCEL_GLOBALTESTINIT") == "1") + { + testContext.CancellationTokenSource.Cancel(); + await Task.Delay(10_000); + } + else if (Environment.GetEnvironmentVariable("LONG_WAIT_GLOBALTESTINIT") == "1") + { + await Task.Delay(10_000); + } + else if (Environment.GetEnvironmentVariable("TIMEOUT_GLOBALTESTINIT") == "1") + { + await Task.Delay(60_000, testContext.CancellationTokenSource.Token); + } + else + { + await Task.CompletedTask; + } + } + + $TimeoutAttribute$ + [GlobalTestCleanup] + public static async Task GlobalTestCleanupMethod(TestContext testContext) + { + if (Environment.GetEnvironmentVariable("LONG_WAIT_GLOBALTESTCLEANUP") == "1" || Environment.GetEnvironmentVariable("TIMEOUT_GLOBALTESTCLEANUP") == "1") + { + await Task.Delay(10_000); + } + else + { + await Task.CompletedTask; + } + } + [TestMethod] public Task Test1() => Task.CompletedTask; } From 0cac9bac26ed5b2717fe1e81fdd0211b00cc348e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Mon, 28 Jul 2025 20:21:24 +0200 Subject: [PATCH 307/541] Use arcade target instead of local (#6140) Co-authored-by: Youssef1313 --- Directory.Build.props | 2 +- azure-pipelines-official.yml | 4 + azure-pipelines.yml | 6 +- .../TestingPlatform.Runner.targets | 91 ------------------- .../TestingPlatformRunner.targets | 3 - test/Directory.Build.targets | 29 +++--- 6 files changed, 23 insertions(+), 112 deletions(-) delete mode 100644 eng/TestingPlatformRunner/TestingPlatform.Runner.targets delete mode 100644 eng/TestingPlatformRunner/TestingPlatformRunner.targets diff --git a/Directory.Build.props b/Directory.Build.props index 6a5ae30911..2f31b2c195 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -66,7 +66,7 @@ - TestingPlatformRunner + Microsoft.Testing.Platform diff --git a/azure-pipelines-official.yml b/azure-pipelines-official.yml index 7af415966c..0a9fc65b62 100644 --- a/azure-pipelines-official.yml +++ b/azure-pipelines-official.yml @@ -149,6 +149,8 @@ extends: /bl:$(BUILD.SOURCESDIRECTORY)\artifacts\TestResults\$(_BuildConfig)\TestStep.binlog name: Test displayName: Test + env: + TESTINGPLATFORM_DEFAULT_HANG_TIMEOUT: 5m - task: CopyFiles@2 displayName: 'Copy binlogs' @@ -217,6 +219,8 @@ extends: ./test.sh --configuration $(_BuildConfig) --ci --test --integrationTest --nobl /bl:$(BUILD.SOURCESDIRECTORY)\artifacts\TestResults\$(_BuildConfig)\TestStep.binlog name: Test displayName: Tests + env: + TESTINGPLATFORM_DEFAULT_HANG_TIMEOUT: 5m - task: 1ES.PublishBuildArtifacts@1 displayName: 'Publish Test Results folders' diff --git a/azure-pipelines.yml b/azure-pipelines.yml index 710fce4b49..52908637ec 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -121,7 +121,7 @@ stages: # Because the build step is using -ci flag, restore is done in a local .packages directory. # We need to pass NUGET_PACKAGES so that when dotnet test is doing evaluation phase on the projects, it can resolve .props/.targets from packages and import them. # Otherwise, props/targets are not imported. It's important that they are imported so that IsTestingPlatformApplication ends up being set. - - script: dotnet test -c $(_BuildConfig) --no-build -bl:$(BUILD.SOURCESDIRECTORY)\artifacts\TestResults\$(_BuildConfig)\TestStep.binlog --no-progress + - script: dotnet test -c $(_BuildConfig) --no-build -bl:$(BUILD.SOURCESDIRECTORY)\artifacts\TestResults\$(_BuildConfig)\TestStep.binlog --no-progress -p:UsingDotNetTest=true name: Test displayName: Test env: @@ -199,7 +199,7 @@ stages: # Because the build step is using -ci flag, restore is done in a local .packages directory. # We need to pass NUGET_PACKAGES so that when dotnet test is doing evaluation phase on the projects, it can resolve .props/.targets from packages and import them. # Otherwise, props/targets are not imported. It's important that they are imported so that IsTestingPlatformApplication ends up being set. - - script: dotnet test --solution NonWindowsTests.slnf -c $(_BuildConfig) --no-build -bl:$(BUILD.SOURCESDIRECTORY)\artifacts\TestResults\$(_BuildConfig)\TestStep.binlog --no-progress + - script: dotnet test --solution NonWindowsTests.slnf -c $(_BuildConfig) --no-build -bl:$(BUILD.SOURCESDIRECTORY)/artifacts/TestResults/$(_BuildConfig)/TestStep.binlog --no-progress -p:UsingDotNetTest=true name: Test displayName: Test env: @@ -263,7 +263,7 @@ stages: # Because the build step is using -ci flag, restore is done in a local .packages directory. # We need to pass NUGET_PACKAGES so that when dotnet test is doing evaluation phase on the projects, it can resolve .props/.targets from packages and import them. # Otherwise, props/targets are not imported. It's important that they are imported so that IsTestingPlatformApplication ends up being set. - - script: dotnet test --solution NonWindowsTests.slnf -c $(_BuildConfig) --no-build -bl:$(BUILD.SOURCESDIRECTORY)\artifacts\TestResults\$(_BuildConfig)\TestStep.binlog --no-progress + - script: dotnet test --solution NonWindowsTests.slnf -c $(_BuildConfig) --no-build -bl:$(BUILD.SOURCESDIRECTORY)/artifacts/TestResults/$(_BuildConfig)/TestStep.binlog --no-progress -p:UsingDotNetTest=true name: Test displayName: Test env: diff --git a/eng/TestingPlatformRunner/TestingPlatform.Runner.targets b/eng/TestingPlatformRunner/TestingPlatform.Runner.targets deleted file mode 100644 index 6088a84863..0000000000 --- a/eng/TestingPlatformRunner/TestingPlatform.Runner.targets +++ /dev/null @@ -1,91 +0,0 @@ - - - - <_TestEnvironment>%(TestToRun.EnvironmentDisplay) - <_TestAssembly>%(TestToRun.Identity) - <_TestRuntime>%(TestToRun.TestRuntime) - <_TestTimeout>%(TestToRun.TestTimeout) - <_TestRunnerAdditionalArguments>%(TestToRun.TestRunnerAdditionalArguments) - - - - <_TestResultDirectory>$([System.IO.Path]::GetDirectoryName('%(TestToRun.ResultsTrxPath)')) - <_TestResultTrxFileName>$([System.IO.Path]::GetFileName('%(TestToRun.ResultsTrxPath)')) - - - - <_TargetFileNameNoExt>$([System.IO.Path]::GetFileNameWithoutExtension('$(_TestAssembly)')) - <_TargetDir>$([System.IO.Path]::GetDirectoryName('$(_TestAssembly)'))\ - <_CoreRuntimeConfigPath>$(_TargetDir)$(_TargetFileNameNoExt).runtimeconfig.json - <_CoreDepsPath>$(_TargetDir)$(_TargetFileNameNoExt).deps.json - - <_TestRunner Condition="'%(TestToRun.Architecture)'=='x86' And Exists('$(DotNetRoot)x86\dotnet.exe')">$(DotNetRoot)x86\dotnet.exe - <_TestRunner Condition="'$(_TestRunner)'==''">$(DotNetTool) - - <_TestRunnerArgs>exec --depsfile "$(_CoreDepsPath)" --runtimeconfig "$(_CoreRuntimeConfigPath)" $(TestRuntimeAdditionalArguments) "$(_TestAssembly)" --report-trx --report-trx-filename "$(_TestResultTrxFileName)" --results-directory "$(_TestResultDirectory)" --report-azdo $(_TestRunnerAdditionalArguments) - - - - <_TestRunner Condition="'$(_TestRunner)'==''">$(_TestAssembly) - <_TestRunnerArgs>--results-directory "$(_TestResultDirectory)" $(_TestRunnerAdditionalArguments) - - - - <_TestRunnerCommand>"$(_TestRunner)" $(_TestRunnerArgs) - - - <_TestRunnerCommand Condition="'$(TestCaptureOutput)' != 'false'">$(_TestRunnerCommand) > "%(TestToRun.ResultsStdOutPath)" 2>&1 - - - - <_OutputFiles Include="%(TestToRun.ResultsTrxPath)" /> - <_OutputFiles Include="%(TestToRun.ResultsHtmlPath)" /> - <_OutputFiles Include="%(TestToRun.ResultsStdOutPath)" /> - - - - - - - - - - - - - - - - - - <_ResultsFileToDisplay>%(TestToRun.ResultsHtmlPath) - <_ResultsFileToDisplay Condition="!Exists('$(_ResultsFileToDisplay)')">%(TestToRun.ResultsStdOutPath) - - - - - - - - - - diff --git a/eng/TestingPlatformRunner/TestingPlatformRunner.targets b/eng/TestingPlatformRunner/TestingPlatformRunner.targets deleted file mode 100644 index 1814b7ea47..0000000000 --- a/eng/TestingPlatformRunner/TestingPlatformRunner.targets +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/test/Directory.Build.targets b/test/Directory.Build.targets index cfdb45cae2..8d8896cb3d 100644 --- a/test/Directory.Build.targets +++ b/test/Directory.Build.targets @@ -13,23 +13,24 @@ Recommended - - $(TestRunnerAdditionalArguments) --diagnostic --diagnostic-output-directory $(RepoRoot)artifacts/log/$(Configuration) --diagnostic-output-fileprefix $(ModuleName) --diagnostic-verbosity trace - $(TestRunnerAdditionalArguments) --crashdump - $(TestRunnerAdditionalArguments) --hangdump --hangdump-timeout 15m - $(TestRunnerAdditionalArguments) --coverage --coverage-settings $(RepoRoot)test/coverage.config --coverage-output $(ModuleName).coverage - + $(TestingPlatformCommandLineArguments) --diagnostic --diagnostic-output-directory $(RepoRoot)artifacts/log/$(Configuration) --diagnostic-output-fileprefix $(ModuleName) --diagnostic-verbosity trace + $(TestingPlatformCommandLineArguments) --crashdump + $(TestingPlatformCommandLineArguments) --hangdump --hangdump-timeout 15m + $(TestingPlatformCommandLineArguments) --report-azdo + $(TestingPlatformCommandLineArguments) --coverage --coverage-settings $(RepoRoot)test/coverage.config --coverage-output $(ModuleName).coverage - + + + + + + + + + <_TestArchitecture>$(PlatformTarget) <_TestArchitecture Condition="'$(PlatformTarget)' == '' or '$(PlatformTarget)' == 'AnyCpu'">x64 - - <_ResultFileNameNoExt>$(MSBuildProjectName)_$(TargetFramework)_$(_TestArchitecture) - $(ArtifactsTestResultsDir)$(_ResultFileNameNoExt).trx - <_TestResultTrxFileName>$([System.IO.Path]::GetFileName('$(ResultsTrxPath)')) - <_TestResultDirectory>$([System.IO.Path]::GetDirectoryName('$(ResultsTrxPath)')) - $(TestingPlatformCommandLineArguments) --report-trx --report-trx-filename "$(_TestResultTrxFileName)" --results-directory "$(_TestResultDirectory)" --report-azdo $(TestRunnerAdditionalArguments) - + $(TestingPlatformCommandLineArguments) --report-trx --report-trx-filename $(MSBuildProjectName)_$(TargetFramework)_$(_TestArchitecture).trx --results-directory $(ArtifactsTestResultsDir) From 84ff9f064af0dcd6fec6e7c8008631991543afbd Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Tue, 29 Jul 2025 04:34:19 +0000 Subject: [PATCH 308/541] [main] Update dependencies from devdiv/DevDiv/vs-code-coverage (#6206) [main] Update dependencies from devdiv/DevDiv/vs-code-coverage --- eng/Version.Details.xml | 4 ++-- eng/Versions.props | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index 0608c50dd4..d9c5bce390 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -13,9 +13,9 @@ https://github.com/dotnet/arcade e2fed65f9c524d12c64876194ae4ce177b935bb3 - + https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage - ce4ee3b08227666176a26a37ff3be1f93a7bc25e + 4fa8f0c467e38db87fae04266d98e4288dad4697 https://github.com/microsoft/testfx diff --git a/eng/Versions.props b/eng/Versions.props index f6c76bc626..e06c442cbe 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -8,7 +8,7 @@ 10.0.0-beta.25374.4 - 18.0.0-preview.25375.2 + 18.0.0-preview.25378.1 3.10.0-preview.25374.11 1.8.0-preview.25374.11 From 986e25b6cc084c8406496c8a529c5a7ccd4c3ac2 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Tue, 29 Jul 2025 08:27:46 +0200 Subject: [PATCH 309/541] Fix official pipeline (#6208) --- azure-pipelines-official.yml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/azure-pipelines-official.yml b/azure-pipelines-official.yml index 0a9fc65b62..353e76967e 100644 --- a/azure-pipelines-official.yml +++ b/azure-pipelines-official.yml @@ -151,6 +151,7 @@ extends: displayName: Test env: TESTINGPLATFORM_DEFAULT_HANG_TIMEOUT: 5m + DOTNET_ROOT: $(Build.SourcesDirectory)/.dotnet - task: CopyFiles@2 displayName: 'Copy binlogs' @@ -216,11 +217,12 @@ extends: # -ci is allowing to import some environment variables and some required configurations - script: | chmod +x ./test.sh - ./test.sh --configuration $(_BuildConfig) --ci --test --integrationTest --nobl /bl:$(BUILD.SOURCESDIRECTORY)\artifacts\TestResults\$(_BuildConfig)\TestStep.binlog + ./test.sh --configuration $(_BuildConfig) --ci --test --integrationTest --nobl /bl:$(BUILD.SOURCESDIRECTORY)/artifacts/TestResults/$(_BuildConfig)/TestStep.binlog name: Test displayName: Tests env: TESTINGPLATFORM_DEFAULT_HANG_TIMEOUT: 5m + DOTNET_ROOT: $(Build.SourcesDirectory)/.dotnet - task: 1ES.PublishBuildArtifacts@1 displayName: 'Publish Test Results folders' From cc914af4e905f2d6f0866dabc1bbf358905a8060 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Tue, 29 Jul 2025 08:30:17 +0200 Subject: [PATCH 310/541] Update azure-pipeline.yml (#6209) --- azure-pipelines-official.yml | 1 - azure-pipelines.yml | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/azure-pipelines-official.yml b/azure-pipelines-official.yml index 353e76967e..f35ab0002d 100644 --- a/azure-pipelines-official.yml +++ b/azure-pipelines-official.yml @@ -4,7 +4,6 @@ trigger: include: - main - rel/* - - dev/v4 exclude: - rel/2.* - rel/3.0.* diff --git a/azure-pipelines.yml b/azure-pipelines.yml index 52908637ec..8ec5bd75e4 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -10,7 +10,6 @@ pr: include: - main - rel/* - - dev/v4 paths: exclude: - .github/* @@ -23,6 +22,7 @@ pr: - README.md - SECURITY.md - src/**/*.xlf + - azure-pipelines-official.yml parameters: # This option should be used with caution. This is useful for unblocking circular deps issue with testanywhere From 5a41cf4835aebba9cc22b87b9d50049936509092 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Tue, 29 Jul 2025 09:19:09 +0200 Subject: [PATCH 311/541] [rel/3.10] Use stable CC (#6211) --- eng/Version.Details.xml | 4 ++-- eng/Versions.props | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index d9c5bce390..10799facb8 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -13,9 +13,9 @@ https://github.com/dotnet/arcade e2fed65f9c524d12c64876194ae4ce177b935bb3 - + https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage - 4fa8f0c467e38db87fae04266d98e4288dad4697 + 005149fac82d93baa64fa87c3bae1004c9cd11e1 https://github.com/microsoft/testfx diff --git a/eng/Versions.props b/eng/Versions.props index e06c442cbe..543ac123ff 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -8,7 +8,7 @@ 10.0.0-beta.25374.4 - 18.0.0-preview.25378.1 + 17.14.2 3.10.0-preview.25374.11 1.8.0-preview.25374.11 From 6c2cc86623dee8304bbda7a86ca49000152292b6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Tue, 29 Jul 2025 10:16:37 +0200 Subject: [PATCH 312/541] Make main target 3.11/1.9 (#6212) --- eng/Versions.props | 4 +- .../PublicAPI/PublicAPI.Shipped.txt | 2 + .../PublicAPI/PublicAPI.Unshipped.txt | 2 - .../AnalyzerReleases.Shipped.md | 22 +++++++- .../AnalyzerReleases.Unshipped.md | 18 ------- .../MSTest.Analyzers/PublicAPI.Shipped.txt | 24 +++++++++ .../MSTest.Analyzers/PublicAPI.Unshipped.txt | 24 --------- .../PublicAPI.Shipped.txt | 1 + .../PublicAPI.Unshipped.txt | 1 - .../PublicAPI/PublicAPI.Shipped.txt | 4 +- .../PublicAPI/PublicAPI.Unshipped.txt | 4 -- .../PublicAPI/PublicAPI.Shipped.txt | 53 +++++++++++++++++- .../PublicAPI/PublicAPI.Unshipped.txt | 54 ------------------- 13 files changed, 105 insertions(+), 108 deletions(-) diff --git a/eng/Versions.props b/eng/Versions.props index 543ac123ff..bd61238afa 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -1,9 +1,9 @@ - 3.10.0 + 3.11.0 - 1.8.0 + 1.9.0 preview diff --git a/src/Adapter/MSTestAdapter.PlatformServices/PublicAPI/PublicAPI.Shipped.txt b/src/Adapter/MSTestAdapter.PlatformServices/PublicAPI/PublicAPI.Shipped.txt index feb5effa2e..d60473368b 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/PublicAPI/PublicAPI.Shipped.txt +++ b/src/Adapter/MSTestAdapter.PlatformServices/PublicAPI/PublicAPI.Shipped.txt @@ -221,6 +221,7 @@ Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.TestContextIm Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.TestContextImplementation.AddProperty(string! propertyName, string! propertyValue) -> void Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.TestContextImplementation.ClearDiagnosticMessages() -> void Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.TestContextImplementation.Context.get -> Microsoft.VisualStudio.TestTools.UnitTesting.TestContext! +Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.TestContextImplementation.Dispose() -> void Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.TestContextImplementation.GetDiagnosticMessages() -> string? Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.TestContextImplementation.GetResultFiles() -> System.Collections.Generic.IList? Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.TestContextImplementation.SetDataConnection(object? dbConnection) -> void @@ -288,3 +289,4 @@ static Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.MSTestSettings.Run static Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.RunConfigurationSettings.PopulateSettings(Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter.IDiscoveryContext? context) -> Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.RunConfigurationSettings! virtual Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestMethodInfo.Invoke(object?[]? arguments) -> Microsoft.VisualStudio.TestTools.UnitTesting.TestResult! virtual Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestMethodInfo.InvokeAsync(object?[]? arguments) -> System.Threading.Tasks.Task! +virtual Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.TestContextImplementation.Dispose(bool disposing) -> void diff --git a/src/Adapter/MSTestAdapter.PlatformServices/PublicAPI/PublicAPI.Unshipped.txt b/src/Adapter/MSTestAdapter.PlatformServices/PublicAPI/PublicAPI.Unshipped.txt index 043a57fc4f..7dc5c58110 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/PublicAPI/PublicAPI.Unshipped.txt +++ b/src/Adapter/MSTestAdapter.PlatformServices/PublicAPI/PublicAPI.Unshipped.txt @@ -1,3 +1 @@ #nullable enable -Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.TestContextImplementation.Dispose() -> void -virtual Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.TestContextImplementation.Dispose(bool disposing) -> void diff --git a/src/Analyzers/MSTest.Analyzers/AnalyzerReleases.Shipped.md b/src/Analyzers/MSTest.Analyzers/AnalyzerReleases.Shipped.md index d0c52ee782..343cb53a91 100644 --- a/src/Analyzers/MSTest.Analyzers/AnalyzerReleases.Shipped.md +++ b/src/Analyzers/MSTest.Analyzers/AnalyzerReleases.Shipped.md @@ -1,4 +1,24 @@ -## Release 3.9.0 +## Release 3.10.0 + +### New Rules + +Rule ID | Category | Severity | Notes +--------|----------|----------|------- +MSTEST0044 | Design | Warning | PreferTestMethodOverDataTestMethodAnalyzer, [Documentation](https://learn.microsoft.com/dotnet/core/testing/mstest-analyzers/mstest0044) +MSTEST0045 | Usage | Info | UseCooperativeCancellationForTimeoutAnalyzer, [Documentation](https://learn.microsoft.com/dotnet/core/testing/mstest-analyzers/mstest0045) +MSTEST0046 | Usage | Info | StringAssertToAssertAnalyzer, [Documentation](https://learn.microsoft.com/dotnet/core/testing/mstest-analyzers/mstest0046) +MSTEST0048 | Usage | Warning | TestContextPropertyUsageAnalyzer, [Documentation](https://learn.microsoft.com/dotnet/core/testing/mstest-analyzers/mstest0047) +MSTEST0049 | Usage | Info | FlowTestContextCancellationTokenAnalyzer, [Documentation](https://learn.microsoft.com/dotnet/core/testing/mstest-analyzers/mstest0049) +MSTEST0050 | Usage | Error | GlobalTestFixtureShouldBeValidAnalyzer, [Documentation](https://learn.microsoft.com/dotnet/core/testing/mstest-analyzers/mstest0050) + +### Changed Rules + +Rule ID | New Category | New Severity | Old Category | Old Severity | Notes +--------|--------------|--------------|--------------|--------------|------- +MSTEST0006 | Design | Warning | Design | Info | AvoidExpectedExceptionAttributeAnalyzer +MSTEST0039 | Usage | Warning | Usage | Info | UseNewerAssertThrowsAnalyzer + +## Release 3.9.0 ### New Rules diff --git a/src/Analyzers/MSTest.Analyzers/AnalyzerReleases.Unshipped.md b/src/Analyzers/MSTest.Analyzers/AnalyzerReleases.Unshipped.md index f230c697eb..f2b7fad657 100644 --- a/src/Analyzers/MSTest.Analyzers/AnalyzerReleases.Unshipped.md +++ b/src/Analyzers/MSTest.Analyzers/AnalyzerReleases.Unshipped.md @@ -1,20 +1,2 @@ ; Unshipped analyzer release ; https://github.com/dotnet/roslyn-analyzers/blob/main/src/Microsoft.CodeAnalysis.Analyzers/ReleaseTrackingAnalyzers.Help.md - -### New Rules - -Rule ID | Category | Severity | Notes ---------|----------|----------|------- -MSTEST0044 | Design | Warning | PreferTestMethodOverDataTestMethodAnalyzer, [Documentation](https://learn.microsoft.com/dotnet/core/testing/mstest-analyzers/mstest0044) -MSTEST0045 | Usage | Info | UseCooperativeCancellationForTimeoutAnalyzer, [Documentation](https://learn.microsoft.com/dotnet/core/testing/mstest-analyzers/mstest0045) -MSTEST0046 | Usage | Info | StringAssertToAssertAnalyzer, [Documentation](https://learn.microsoft.com/dotnet/core/testing/mstest-analyzers/mstest0046) -MSTEST0048 | Usage | Warning | TestContextPropertyUsageAnalyzer, [Documentation](https://learn.microsoft.com/dotnet/core/testing/mstest-analyzers/mstest0047) -MSTEST0049 | Usage | Info | FlowTestContextCancellationTokenAnalyzer, [Documentation](https://learn.microsoft.com/dotnet/core/testing/mstest-analyzers/mstest0049) -MSTEST0050 | Usage | Error | GlobalTestFixtureShouldBeValidAnalyzer, [Documentation](https://learn.microsoft.com/dotnet/core/testing/mstest-analyzers/mstest0050) - -### Changed Rules - -Rule ID | New Category | New Severity | Old Category | Old Severity | Notes ---------|--------------|--------------|--------------|--------------|------- -MSTEST0006 | Design | Warning | Design | Info | AvoidExpectedExceptionAttributeAnalyzer -MSTEST0039 | Usage | Warning | Usage | Info | UseNewerAssertThrowsAnalyzer diff --git a/src/Analyzers/MSTest.Analyzers/PublicAPI.Shipped.txt b/src/Analyzers/MSTest.Analyzers/PublicAPI.Shipped.txt index 8c2dc7036b..0e6cde55f8 100644 --- a/src/Analyzers/MSTest.Analyzers/PublicAPI.Shipped.txt +++ b/src/Analyzers/MSTest.Analyzers/PublicAPI.Shipped.txt @@ -31,6 +31,10 @@ MSTest.Analyzers.DuplicateDataRowAnalyzer MSTest.Analyzers.DuplicateDataRowAnalyzer.DuplicateDataRowAnalyzer() -> void MSTest.Analyzers.DynamicDataShouldBeValidAnalyzer MSTest.Analyzers.DynamicDataShouldBeValidAnalyzer.DynamicDataShouldBeValidAnalyzer() -> void +MSTest.Analyzers.FlowTestContextCancellationTokenAnalyzer +MSTest.Analyzers.FlowTestContextCancellationTokenAnalyzer.FlowTestContextCancellationTokenAnalyzer() -> void +MSTest.Analyzers.GlobalTestFixtureShouldBeValidAnalyzer +MSTest.Analyzers.GlobalTestFixtureShouldBeValidAnalyzer.GlobalTestFixtureShouldBeValidAnalyzer() -> void MSTest.Analyzers.NonNullableReferenceNotInitializedSuppressor MSTest.Analyzers.NonNullableReferenceNotInitializedSuppressor.NonNullableReferenceNotInitializedSuppressor() -> void MSTest.Analyzers.PreferAssertFailOverAlwaysFalseConditionsAnalyzer @@ -43,6 +47,8 @@ MSTest.Analyzers.PreferTestCleanupOverDisposeAnalyzer MSTest.Analyzers.PreferTestCleanupOverDisposeAnalyzer.PreferTestCleanupOverDisposeAnalyzer() -> void MSTest.Analyzers.PreferTestInitializeOverConstructorAnalyzer MSTest.Analyzers.PreferTestInitializeOverConstructorAnalyzer.PreferTestInitializeOverConstructorAnalyzer() -> void +MSTest.Analyzers.PreferTestMethodOverDataTestMethodAnalyzer +MSTest.Analyzers.PreferTestMethodOverDataTestMethodAnalyzer.PreferTestMethodOverDataTestMethodAnalyzer() -> void MSTest.Analyzers.PublicMethodShouldBeTestMethodAnalyzer MSTest.Analyzers.PublicMethodShouldBeTestMethodAnalyzer.PublicMethodShouldBeTestMethodAnalyzer() -> void MSTest.Analyzers.PublicTypeShouldBeTestClassAnalyzer @@ -55,6 +61,8 @@ MSTest.Analyzers.TestClassShouldHaveTestMethodAnalyzer MSTest.Analyzers.TestClassShouldHaveTestMethodAnalyzer.TestClassShouldHaveTestMethodAnalyzer() -> void MSTest.Analyzers.TestCleanupShouldBeValidAnalyzer MSTest.Analyzers.TestCleanupShouldBeValidAnalyzer.TestCleanupShouldBeValidAnalyzer() -> void +MSTest.Analyzers.TestContextPropertyUsageAnalyzer +MSTest.Analyzers.TestContextPropertyUsageAnalyzer.TestContextPropertyUsageAnalyzer() -> void MSTest.Analyzers.TestContextShouldBeValidAnalyzer MSTest.Analyzers.TestContextShouldBeValidAnalyzer.TestContextShouldBeValidAnalyzer() -> void MSTest.Analyzers.TestInitializeShouldBeValidAnalyzer @@ -65,6 +73,8 @@ MSTest.Analyzers.TestMethodShouldNotBeIgnoredAnalyzer MSTest.Analyzers.TestMethodShouldNotBeIgnoredAnalyzer.TestMethodShouldNotBeIgnoredAnalyzer() -> void MSTest.Analyzers.TypeContainingTestMethodShouldBeATestClassAnalyzer MSTest.Analyzers.TypeContainingTestMethodShouldBeATestClassAnalyzer.TypeContainingTestMethodShouldBeATestClassAnalyzer() -> void +MSTest.Analyzers.UnusedParameterSuppressor +MSTest.Analyzers.UnusedParameterSuppressor.UnusedParameterSuppressor() -> void MSTest.Analyzers.UseAsyncSuffixTestFixtureMethodSuppressor MSTest.Analyzers.UseAsyncSuffixTestFixtureMethodSuppressor.UseAsyncSuffixTestFixtureMethodSuppressor() -> void MSTest.Analyzers.UseAsyncSuffixTestMethodSuppressor @@ -75,6 +85,8 @@ MSTest.Analyzers.UseClassCleanupBehaviorEndOfClassAnalyzer MSTest.Analyzers.UseClassCleanupBehaviorEndOfClassAnalyzer.UseClassCleanupBehaviorEndOfClassAnalyzer() -> void MSTest.Analyzers.UseConditionBaseWithTestClassAnalyzer MSTest.Analyzers.UseConditionBaseWithTestClassAnalyzer.UseConditionBaseWithTestClassAnalyzer() -> void +MSTest.Analyzers.UseCooperativeCancellationForTimeoutAnalyzer +MSTest.Analyzers.UseCooperativeCancellationForTimeoutAnalyzer.UseCooperativeCancellationForTimeoutAnalyzer() -> void MSTest.Analyzers.UseDeploymentItemWithTestMethodOrTestClassAnalyzer MSTest.Analyzers.UseDeploymentItemWithTestMethodOrTestClassAnalyzer.UseDeploymentItemWithTestMethodOrTestClassAnalyzer() -> void MSTest.Analyzers.UseParallelizeAttributeAnalyzer @@ -113,6 +125,10 @@ override MSTest.Analyzers.DuplicateDataRowAnalyzer.Initialize(Microsoft.CodeAnal override MSTest.Analyzers.DuplicateDataRowAnalyzer.SupportedDiagnostics.get -> System.Collections.Immutable.ImmutableArray override MSTest.Analyzers.DynamicDataShouldBeValidAnalyzer.Initialize(Microsoft.CodeAnalysis.Diagnostics.AnalysisContext! context) -> void override MSTest.Analyzers.DynamicDataShouldBeValidAnalyzer.SupportedDiagnostics.get -> System.Collections.Immutable.ImmutableArray +override MSTest.Analyzers.FlowTestContextCancellationTokenAnalyzer.Initialize(Microsoft.CodeAnalysis.Diagnostics.AnalysisContext! context) -> void +override MSTest.Analyzers.FlowTestContextCancellationTokenAnalyzer.SupportedDiagnostics.get -> System.Collections.Immutable.ImmutableArray +override MSTest.Analyzers.GlobalTestFixtureShouldBeValidAnalyzer.Initialize(Microsoft.CodeAnalysis.Diagnostics.AnalysisContext! context) -> void +override MSTest.Analyzers.GlobalTestFixtureShouldBeValidAnalyzer.SupportedDiagnostics.get -> System.Collections.Immutable.ImmutableArray override MSTest.Analyzers.NonNullableReferenceNotInitializedSuppressor.ReportSuppressions(Microsoft.CodeAnalysis.Diagnostics.SuppressionAnalysisContext context) -> void override MSTest.Analyzers.NonNullableReferenceNotInitializedSuppressor.SupportedSuppressions.get -> System.Collections.Immutable.ImmutableArray override MSTest.Analyzers.PreferAssertFailOverAlwaysFalseConditionsAnalyzer.Initialize(Microsoft.CodeAnalysis.Diagnostics.AnalysisContext! context) -> void @@ -125,6 +141,8 @@ override MSTest.Analyzers.PreferTestCleanupOverDisposeAnalyzer.Initialize(Micros override MSTest.Analyzers.PreferTestCleanupOverDisposeAnalyzer.SupportedDiagnostics.get -> System.Collections.Immutable.ImmutableArray override MSTest.Analyzers.PreferTestInitializeOverConstructorAnalyzer.Initialize(Microsoft.CodeAnalysis.Diagnostics.AnalysisContext! context) -> void override MSTest.Analyzers.PreferTestInitializeOverConstructorAnalyzer.SupportedDiagnostics.get -> System.Collections.Immutable.ImmutableArray +override MSTest.Analyzers.PreferTestMethodOverDataTestMethodAnalyzer.Initialize(Microsoft.CodeAnalysis.Diagnostics.AnalysisContext! context) -> void +override MSTest.Analyzers.PreferTestMethodOverDataTestMethodAnalyzer.SupportedDiagnostics.get -> System.Collections.Immutable.ImmutableArray override MSTest.Analyzers.PublicMethodShouldBeTestMethodAnalyzer.Initialize(Microsoft.CodeAnalysis.Diagnostics.AnalysisContext! context) -> void override MSTest.Analyzers.PublicMethodShouldBeTestMethodAnalyzer.SupportedDiagnostics.get -> System.Collections.Immutable.ImmutableArray override MSTest.Analyzers.PublicTypeShouldBeTestClassAnalyzer.Initialize(Microsoft.CodeAnalysis.Diagnostics.AnalysisContext! context) -> void @@ -137,6 +155,8 @@ override MSTest.Analyzers.TestClassShouldHaveTestMethodAnalyzer.Initialize(Micro override MSTest.Analyzers.TestClassShouldHaveTestMethodAnalyzer.SupportedDiagnostics.get -> System.Collections.Immutable.ImmutableArray override MSTest.Analyzers.TestCleanupShouldBeValidAnalyzer.Initialize(Microsoft.CodeAnalysis.Diagnostics.AnalysisContext! context) -> void override MSTest.Analyzers.TestCleanupShouldBeValidAnalyzer.SupportedDiagnostics.get -> System.Collections.Immutable.ImmutableArray +override MSTest.Analyzers.TestContextPropertyUsageAnalyzer.Initialize(Microsoft.CodeAnalysis.Diagnostics.AnalysisContext! context) -> void +override MSTest.Analyzers.TestContextPropertyUsageAnalyzer.SupportedDiagnostics.get -> System.Collections.Immutable.ImmutableArray override MSTest.Analyzers.TestContextShouldBeValidAnalyzer.Initialize(Microsoft.CodeAnalysis.Diagnostics.AnalysisContext! context) -> void override MSTest.Analyzers.TestContextShouldBeValidAnalyzer.SupportedDiagnostics.get -> System.Collections.Immutable.ImmutableArray override MSTest.Analyzers.TestInitializeShouldBeValidAnalyzer.Initialize(Microsoft.CodeAnalysis.Diagnostics.AnalysisContext! context) -> void @@ -147,6 +167,8 @@ override MSTest.Analyzers.TestMethodShouldNotBeIgnoredAnalyzer.Initialize(Micros override MSTest.Analyzers.TestMethodShouldNotBeIgnoredAnalyzer.SupportedDiagnostics.get -> System.Collections.Immutable.ImmutableArray override MSTest.Analyzers.TypeContainingTestMethodShouldBeATestClassAnalyzer.Initialize(Microsoft.CodeAnalysis.Diagnostics.AnalysisContext! context) -> void override MSTest.Analyzers.TypeContainingTestMethodShouldBeATestClassAnalyzer.SupportedDiagnostics.get -> System.Collections.Immutable.ImmutableArray +override MSTest.Analyzers.UnusedParameterSuppressor.ReportSuppressions(Microsoft.CodeAnalysis.Diagnostics.SuppressionAnalysisContext context) -> void +override MSTest.Analyzers.UnusedParameterSuppressor.SupportedSuppressions.get -> System.Collections.Immutable.ImmutableArray override MSTest.Analyzers.UseAsyncSuffixTestFixtureMethodSuppressor.ReportSuppressions(Microsoft.CodeAnalysis.Diagnostics.SuppressionAnalysisContext context) -> void override MSTest.Analyzers.UseAsyncSuffixTestFixtureMethodSuppressor.SupportedSuppressions.get -> System.Collections.Immutable.ImmutableArray override MSTest.Analyzers.UseAsyncSuffixTestMethodSuppressor.ReportSuppressions(Microsoft.CodeAnalysis.Diagnostics.SuppressionAnalysisContext context) -> void @@ -157,6 +179,8 @@ override MSTest.Analyzers.UseClassCleanupBehaviorEndOfClassAnalyzer.Initialize(M override MSTest.Analyzers.UseClassCleanupBehaviorEndOfClassAnalyzer.SupportedDiagnostics.get -> System.Collections.Immutable.ImmutableArray override MSTest.Analyzers.UseConditionBaseWithTestClassAnalyzer.Initialize(Microsoft.CodeAnalysis.Diagnostics.AnalysisContext! context) -> void override MSTest.Analyzers.UseConditionBaseWithTestClassAnalyzer.SupportedDiagnostics.get -> System.Collections.Immutable.ImmutableArray +override MSTest.Analyzers.UseCooperativeCancellationForTimeoutAnalyzer.Initialize(Microsoft.CodeAnalysis.Diagnostics.AnalysisContext! context) -> void +override MSTest.Analyzers.UseCooperativeCancellationForTimeoutAnalyzer.SupportedDiagnostics.get -> System.Collections.Immutable.ImmutableArray override MSTest.Analyzers.UseDeploymentItemWithTestMethodOrTestClassAnalyzer.Initialize(Microsoft.CodeAnalysis.Diagnostics.AnalysisContext! context) -> void override MSTest.Analyzers.UseDeploymentItemWithTestMethodOrTestClassAnalyzer.SupportedDiagnostics.get -> System.Collections.Immutable.ImmutableArray override MSTest.Analyzers.UseParallelizeAttributeAnalyzer.Initialize(Microsoft.CodeAnalysis.Diagnostics.AnalysisContext! context) -> void diff --git a/src/Analyzers/MSTest.Analyzers/PublicAPI.Unshipped.txt b/src/Analyzers/MSTest.Analyzers/PublicAPI.Unshipped.txt index 855fc462e3..7dc5c58110 100644 --- a/src/Analyzers/MSTest.Analyzers/PublicAPI.Unshipped.txt +++ b/src/Analyzers/MSTest.Analyzers/PublicAPI.Unshipped.txt @@ -1,25 +1 @@ #nullable enable -MSTest.Analyzers.FlowTestContextCancellationTokenAnalyzer -MSTest.Analyzers.FlowTestContextCancellationTokenAnalyzer.FlowTestContextCancellationTokenAnalyzer() -> void -MSTest.Analyzers.GlobalTestFixtureShouldBeValidAnalyzer -MSTest.Analyzers.GlobalTestFixtureShouldBeValidAnalyzer.GlobalTestFixtureShouldBeValidAnalyzer() -> void -override MSTest.Analyzers.FlowTestContextCancellationTokenAnalyzer.Initialize(Microsoft.CodeAnalysis.Diagnostics.AnalysisContext! context) -> void -override MSTest.Analyzers.FlowTestContextCancellationTokenAnalyzer.SupportedDiagnostics.get -> System.Collections.Immutable.ImmutableArray -MSTest.Analyzers.PreferTestMethodOverDataTestMethodAnalyzer -MSTest.Analyzers.PreferTestMethodOverDataTestMethodAnalyzer.PreferTestMethodOverDataTestMethodAnalyzer() -> void -override MSTest.Analyzers.GlobalTestFixtureShouldBeValidAnalyzer.Initialize(Microsoft.CodeAnalysis.Diagnostics.AnalysisContext! context) -> void -override MSTest.Analyzers.GlobalTestFixtureShouldBeValidAnalyzer.SupportedDiagnostics.get -> System.Collections.Immutable.ImmutableArray -override MSTest.Analyzers.PreferTestMethodOverDataTestMethodAnalyzer.Initialize(Microsoft.CodeAnalysis.Diagnostics.AnalysisContext! context) -> void -override MSTest.Analyzers.PreferTestMethodOverDataTestMethodAnalyzer.SupportedDiagnostics.get -> System.Collections.Immutable.ImmutableArray -MSTest.Analyzers.UseCooperativeCancellationForTimeoutAnalyzer -MSTest.Analyzers.UseCooperativeCancellationForTimeoutAnalyzer.UseCooperativeCancellationForTimeoutAnalyzer() -> void -override MSTest.Analyzers.UseCooperativeCancellationForTimeoutAnalyzer.Initialize(Microsoft.CodeAnalysis.Diagnostics.AnalysisContext! context) -> void -override MSTest.Analyzers.UseCooperativeCancellationForTimeoutAnalyzer.SupportedDiagnostics.get -> System.Collections.Immutable.ImmutableArray -MSTest.Analyzers.UnusedParameterSuppressor -MSTest.Analyzers.UnusedParameterSuppressor.UnusedParameterSuppressor() -> void -override MSTest.Analyzers.UnusedParameterSuppressor.ReportSuppressions(Microsoft.CodeAnalysis.Diagnostics.SuppressionAnalysisContext context) -> void -override MSTest.Analyzers.UnusedParameterSuppressor.SupportedSuppressions.get -> System.Collections.Immutable.ImmutableArray -MSTest.Analyzers.TestContextPropertyUsageAnalyzer -MSTest.Analyzers.TestContextPropertyUsageAnalyzer.TestContextPropertyUsageAnalyzer() -> void -override MSTest.Analyzers.TestContextPropertyUsageAnalyzer.Initialize(Microsoft.CodeAnalysis.Diagnostics.AnalysisContext! context) -> void -override MSTest.Analyzers.TestContextPropertyUsageAnalyzer.SupportedDiagnostics.get -> System.Collections.Immutable.ImmutableArray diff --git a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/PublicAPI.Shipped.txt b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/PublicAPI.Shipped.txt index 16d6e94640..8af37ceb0c 100644 --- a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/PublicAPI.Shipped.txt +++ b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/PublicAPI.Shipped.txt @@ -57,3 +57,4 @@ static Microsoft.Testing.Extensions.VSTestBridge.Helpers.TestApplicationBuilderE static Microsoft.Testing.Extensions.VSTestBridge.Requests.VSTestDiscoverTestExecutionRequestFactory.CreateRequest(Microsoft.Testing.Platform.Requests.DiscoverTestExecutionRequest! discoverTestExecutionRequest, Microsoft.Testing.Extensions.VSTestBridge.VSTestBridgedTestFrameworkBase! adapterExtension, string![]! testAssemblyPaths, System.Threading.CancellationToken cancellationToken) -> Microsoft.Testing.Extensions.VSTestBridge.Requests.VSTestDiscoverTestExecutionRequest! static Microsoft.Testing.Extensions.VSTestBridge.Requests.VSTestRunTestExecutionRequestFactory.CreateRequest(Microsoft.Testing.Platform.Requests.RunTestExecutionRequest! runTestExecutionRequest, Microsoft.Testing.Extensions.VSTestBridge.VSTestBridgedTestFrameworkBase! adapterExtension, string![]! testAssemblyPaths, System.Threading.CancellationToken cancellationToken) -> Microsoft.Testing.Extensions.VSTestBridge.Requests.VSTestRunTestExecutionRequest! virtual Microsoft.Testing.Extensions.VSTestBridge.SynchronizedSingleSessionVSTestBridgedTestFramework.Dispose(bool disposing) -> void +virtual Microsoft.Testing.Extensions.VSTestBridge.VSTestBridgedTestFrameworkBase.UseFullyQualifiedNameAsTestNodeUid.get -> bool diff --git a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/PublicAPI.Unshipped.txt b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/PublicAPI.Unshipped.txt index a0e14e5ed0..7dc5c58110 100644 --- a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/PublicAPI.Unshipped.txt +++ b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/PublicAPI.Unshipped.txt @@ -1,2 +1 @@ #nullable enable -virtual Microsoft.Testing.Extensions.VSTestBridge.VSTestBridgedTestFrameworkBase.UseFullyQualifiedNameAsTestNodeUid.get -> bool diff --git a/src/Platform/Microsoft.Testing.Platform/PublicAPI/PublicAPI.Shipped.txt b/src/Platform/Microsoft.Testing.Platform/PublicAPI/PublicAPI.Shipped.txt index a3663087b9..66e9adb2ec 100644 --- a/src/Platform/Microsoft.Testing.Platform/PublicAPI/PublicAPI.Shipped.txt +++ b/src/Platform/Microsoft.Testing.Platform/PublicAPI/PublicAPI.Shipped.txt @@ -93,7 +93,7 @@ Microsoft.Testing.Platform.Builder.ITestApplicationBuilder.BuildAsync() -> Syste Microsoft.Testing.Platform.Builder.ITestApplicationBuilder.CommandLine.get -> Microsoft.Testing.Platform.CommandLine.ICommandLineManager! Microsoft.Testing.Platform.Builder.ITestApplicationBuilder.Configuration.get -> Microsoft.Testing.Platform.Configurations.IConfigurationManager! Microsoft.Testing.Platform.Builder.ITestApplicationBuilder.Logging.get -> Microsoft.Testing.Platform.Logging.ILoggingManager! -Microsoft.Testing.Platform.Builder.ITestApplicationBuilder.RegisterTestFramework(System.Func! capabilitiesFactory, System.Func! adapterFactory) -> Microsoft.Testing.Platform.Builder.ITestApplicationBuilder! +Microsoft.Testing.Platform.Builder.ITestApplicationBuilder.RegisterTestFramework(System.Func! capabilitiesFactory, System.Func! frameworkFactory) -> Microsoft.Testing.Platform.Builder.ITestApplicationBuilder! Microsoft.Testing.Platform.Builder.ITestApplicationBuilder.TestHost.get -> Microsoft.Testing.Platform.TestHost.ITestHostManager! Microsoft.Testing.Platform.Builder.ITestApplicationBuilder.TestHostControllers.get -> Microsoft.Testing.Platform.TestHostControllers.ITestHostControllersManager! Microsoft.Testing.Platform.Builder.TestApplication @@ -358,6 +358,7 @@ Microsoft.Testing.Platform.Extensions.TestHost.IDataConsumer.DataTypesConsumed.g Microsoft.Testing.Platform.Extensions.TestHost.ITestApplicationLifecycleCallbacks Microsoft.Testing.Platform.Extensions.TestHost.ITestApplicationLifecycleCallbacks.AfterRunAsync(int exitCode, System.Threading.CancellationToken cancellation) -> System.Threading.Tasks.Task! Microsoft.Testing.Platform.Extensions.TestHost.ITestApplicationLifecycleCallbacks.BeforeRunAsync(System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task! +Microsoft.Testing.Platform.Extensions.TestHost.ITestHostApplicationLifetime Microsoft.Testing.Platform.Extensions.TestHost.ITestHostExtension Microsoft.Testing.Platform.Extensions.TestHost.ITestSessionLifetimeHandler Microsoft.Testing.Platform.Extensions.TestHost.ITestSessionLifetimeHandler.OnTestSessionFinishingAsync(Microsoft.Testing.Platform.TestHost.SessionUid sessionUid, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task! @@ -463,6 +464,7 @@ Microsoft.Testing.Platform.TestHost.ITestHostManager Microsoft.Testing.Platform.TestHost.ITestHostManager.AddDataConsumer(System.Func! dataConsumerFactory) -> void Microsoft.Testing.Platform.TestHost.ITestHostManager.AddDataConsumer(Microsoft.Testing.Platform.Extensions.CompositeExtensionFactory! compositeServiceFactory) -> void Microsoft.Testing.Platform.TestHost.ITestHostManager.AddTestApplicationLifecycleCallbacks(System.Func! testApplicationLifecycleCallbacks) -> void +Microsoft.Testing.Platform.TestHost.ITestHostManager.AddTestHostApplicationLifetime(System.Func! testHostApplicationLifetimeFactory) -> void Microsoft.Testing.Platform.TestHost.ITestHostManager.AddTestSessionLifetimeHandle(System.Func! testSessionLifetimeHandleFactory) -> void Microsoft.Testing.Platform.TestHost.ITestHostManager.AddTestSessionLifetimeHandle(Microsoft.Testing.Platform.Extensions.CompositeExtensionFactory! compositeServiceFactory) -> void Microsoft.Testing.Platform.TestHost.SessionUid diff --git a/src/Platform/Microsoft.Testing.Platform/PublicAPI/PublicAPI.Unshipped.txt b/src/Platform/Microsoft.Testing.Platform/PublicAPI/PublicAPI.Unshipped.txt index 200755b523..7dc5c58110 100644 --- a/src/Platform/Microsoft.Testing.Platform/PublicAPI/PublicAPI.Unshipped.txt +++ b/src/Platform/Microsoft.Testing.Platform/PublicAPI/PublicAPI.Unshipped.txt @@ -1,5 +1 @@ #nullable enable -Microsoft.Testing.Platform.Builder.ITestApplicationBuilder.RegisterTestFramework(System.Func! capabilitiesFactory, System.Func! frameworkFactory) -> Microsoft.Testing.Platform.Builder.ITestApplicationBuilder! -*REMOVED*Microsoft.Testing.Platform.Builder.ITestApplicationBuilder.RegisterTestFramework(System.Func! capabilitiesFactory, System.Func! adapterFactory) -> Microsoft.Testing.Platform.Builder.ITestApplicationBuilder! -Microsoft.Testing.Platform.Extensions.TestHost.ITestHostApplicationLifetime -Microsoft.Testing.Platform.TestHost.ITestHostManager.AddTestHostApplicationLifetime(System.Func! testHostApplicationLifetimeFactory) -> void diff --git a/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Shipped.txt b/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Shipped.txt index e05ec781bb..7954d442eb 100644 --- a/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Shipped.txt +++ b/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Shipped.txt @@ -8,7 +8,6 @@ [MSTESTEXP]Microsoft.VisualStudio.TestTools.UnitTesting.RetryResult.AddResult(Microsoft.VisualStudio.TestTools.UnitTesting.TestResult![]! testResults) -> void [MSTESTEXP]Microsoft.VisualStudio.TestTools.UnitTesting.RetryResult.RetryResult() -> void abstract Microsoft.VisualStudio.TestTools.UnitTesting.ConditionBaseAttribute.GroupName.get -> string! -abstract Microsoft.VisualStudio.TestTools.UnitTesting.ConditionBaseAttribute.IgnoreMessage.get -> string? abstract Microsoft.VisualStudio.TestTools.UnitTesting.ConditionBaseAttribute.ShouldRun.get -> bool abstract Microsoft.VisualStudio.TestTools.UnitTesting.ExpectedExceptionBaseAttribute.Verify(System.Exception! exception) -> void abstract Microsoft.VisualStudio.TestTools.UnitTesting.TestCategoryBaseAttribute.TestCategories.get -> System.Collections.Generic.IList! @@ -218,6 +217,7 @@ Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AssertNonStrictThrowsInterpo Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AssertNonStrictThrowsInterpolatedStringHandler.AppendLiteral(string! value) -> void Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AssertNonStrictThrowsInterpolatedStringHandler.AssertNonStrictThrowsInterpolatedStringHandler() -> void Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AssertNonStrictThrowsInterpolatedStringHandler.AssertNonStrictThrowsInterpolatedStringHandler(int literalLength, int formattedCount, System.Action! action, out bool shouldAppend) -> void +Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AssertNonStrictThrowsInterpolatedStringHandler.AssertNonStrictThrowsInterpolatedStringHandler(int literalLength, int formattedCount, System.Func! action, out bool shouldAppend) -> void Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AssertSingleInterpolatedStringHandler Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AssertSingleInterpolatedStringHandler.AppendFormatted(object? value, int alignment = 0, string? format = null) -> void Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AssertSingleInterpolatedStringHandler.AppendFormatted(string? value, int alignment = 0, string? format = null) -> void @@ -240,6 +240,7 @@ Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AssertThrowsExactlyInterpola Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AssertThrowsExactlyInterpolatedStringHandler.AppendLiteral(string! value) -> void Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AssertThrowsExactlyInterpolatedStringHandler.AssertThrowsExactlyInterpolatedStringHandler() -> void Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AssertThrowsExactlyInterpolatedStringHandler.AssertThrowsExactlyInterpolatedStringHandler(int literalLength, int formattedCount, System.Action! action, out bool shouldAppend) -> void +Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AssertThrowsExactlyInterpolatedStringHandler.AssertThrowsExactlyInterpolatedStringHandler(int literalLength, int formattedCount, System.Func! action, out bool shouldAppend) -> void Microsoft.VisualStudio.TestTools.UnitTesting.AssertFailedException Microsoft.VisualStudio.TestTools.UnitTesting.AssertFailedException.AssertFailedException() -> void Microsoft.VisualStudio.TestTools.UnitTesting.AssertFailedException.AssertFailedException(string! msg, System.Exception! ex) -> void @@ -250,6 +251,8 @@ Microsoft.VisualStudio.TestTools.UnitTesting.AssertInconclusiveException.AssertI Microsoft.VisualStudio.TestTools.UnitTesting.AssertInconclusiveException.AssertInconclusiveException(string! msg, System.Exception! ex) -> void Microsoft.VisualStudio.TestTools.UnitTesting.AssertInconclusiveException.AssertInconclusiveException(string! msg) -> void Microsoft.VisualStudio.TestTools.UnitTesting.AssertInconclusiveException.AssertInconclusiveException(System.Runtime.Serialization.SerializationInfo! info, System.Runtime.Serialization.StreamingContext context) -> void +Microsoft.VisualStudio.TestTools.UnitTesting.CIConditionAttribute +Microsoft.VisualStudio.TestTools.UnitTesting.CIConditionAttribute.CIConditionAttribute(Microsoft.VisualStudio.TestTools.UnitTesting.ConditionMode mode) -> void Microsoft.VisualStudio.TestTools.UnitTesting.ClassCleanupAttribute Microsoft.VisualStudio.TestTools.UnitTesting.ClassCleanupAttribute.ClassCleanupAttribute() -> void Microsoft.VisualStudio.TestTools.UnitTesting.ClassCleanupAttribute.ClassCleanupAttribute(Microsoft.VisualStudio.TestTools.UnitTesting.ClassCleanupBehavior cleanupBehavior) -> void @@ -271,6 +274,7 @@ Microsoft.VisualStudio.TestTools.UnitTesting.ClassInitializeAttribute.Inheritanc Microsoft.VisualStudio.TestTools.UnitTesting.CollectionAssert Microsoft.VisualStudio.TestTools.UnitTesting.ConditionBaseAttribute Microsoft.VisualStudio.TestTools.UnitTesting.ConditionBaseAttribute.ConditionBaseAttribute(Microsoft.VisualStudio.TestTools.UnitTesting.ConditionMode mode) -> void +Microsoft.VisualStudio.TestTools.UnitTesting.ConditionBaseAttribute.Mode.get -> Microsoft.VisualStudio.TestTools.UnitTesting.ConditionMode Microsoft.VisualStudio.TestTools.UnitTesting.ConditionMode Microsoft.VisualStudio.TestTools.UnitTesting.ConditionMode.Exclude = 1 -> Microsoft.VisualStudio.TestTools.UnitTesting.ConditionMode Microsoft.VisualStudio.TestTools.UnitTesting.ConditionMode.Include = 0 -> Microsoft.VisualStudio.TestTools.UnitTesting.ConditionMode @@ -320,7 +324,9 @@ Microsoft.VisualStudio.TestTools.UnitTesting.DoNotParallelizeAttribute Microsoft.VisualStudio.TestTools.UnitTesting.DoNotParallelizeAttribute.DoNotParallelizeAttribute() -> void Microsoft.VisualStudio.TestTools.UnitTesting.DynamicDataAttribute Microsoft.VisualStudio.TestTools.UnitTesting.DynamicDataAttribute.DynamicDataAttribute(string! dynamicDataSourceName, Microsoft.VisualStudio.TestTools.UnitTesting.DynamicDataSourceType dynamicDataSourceType) -> void +Microsoft.VisualStudio.TestTools.UnitTesting.DynamicDataAttribute.DynamicDataAttribute(string! dynamicDataSourceName, params object?[]! dynamicDataSourceArguments) -> void Microsoft.VisualStudio.TestTools.UnitTesting.DynamicDataAttribute.DynamicDataAttribute(string! dynamicDataSourceName, System.Type! dynamicDataDeclaringType, Microsoft.VisualStudio.TestTools.UnitTesting.DynamicDataSourceType dynamicDataSourceType) -> void +Microsoft.VisualStudio.TestTools.UnitTesting.DynamicDataAttribute.DynamicDataAttribute(string! dynamicDataSourceName, System.Type! dynamicDataDeclaringType, params object?[]! dynamicDataSourceArguments) -> void Microsoft.VisualStudio.TestTools.UnitTesting.DynamicDataAttribute.DynamicDataAttribute(string! dynamicDataSourceName, System.Type! dynamicDataDeclaringType) -> void Microsoft.VisualStudio.TestTools.UnitTesting.DynamicDataAttribute.DynamicDataAttribute(string! dynamicDataSourceName) -> void Microsoft.VisualStudio.TestTools.UnitTesting.DynamicDataAttribute.DynamicDataDisplayName.get -> string? @@ -362,6 +368,10 @@ Microsoft.VisualStudio.TestTools.UnitTesting.GenericParameterHelper.GetEnumerato Microsoft.VisualStudio.TestTools.UnitTesting.GitHubWorkItemAttribute Microsoft.VisualStudio.TestTools.UnitTesting.GitHubWorkItemAttribute.GitHubWorkItemAttribute(string! url) -> void Microsoft.VisualStudio.TestTools.UnitTesting.GitHubWorkItemAttribute.Url.get -> string! +Microsoft.VisualStudio.TestTools.UnitTesting.GlobalTestCleanupAttribute +Microsoft.VisualStudio.TestTools.UnitTesting.GlobalTestCleanupAttribute.GlobalTestCleanupAttribute() -> void +Microsoft.VisualStudio.TestTools.UnitTesting.GlobalTestInitializeAttribute +Microsoft.VisualStudio.TestTools.UnitTesting.GlobalTestInitializeAttribute.GlobalTestInitializeAttribute() -> void Microsoft.VisualStudio.TestTools.UnitTesting.IgnoreAttribute Microsoft.VisualStudio.TestTools.UnitTesting.IgnoreAttribute.IgnoreAttribute() -> void Microsoft.VisualStudio.TestTools.UnitTesting.IgnoreAttribute.IgnoreAttribute(string? message) -> void @@ -443,6 +453,8 @@ Microsoft.VisualStudio.TestTools.UnitTesting.TestDataRow.DisplayName.get -> s Microsoft.VisualStudio.TestTools.UnitTesting.TestDataRow.DisplayName.set -> void Microsoft.VisualStudio.TestTools.UnitTesting.TestDataRow.IgnoreMessage.get -> string? Microsoft.VisualStudio.TestTools.UnitTesting.TestDataRow.IgnoreMessage.set -> void +Microsoft.VisualStudio.TestTools.UnitTesting.TestDataRow.TestCategories.get -> System.Collections.Generic.IList? +Microsoft.VisualStudio.TestTools.UnitTesting.TestDataRow.TestCategories.set -> void Microsoft.VisualStudio.TestTools.UnitTesting.TestDataRow.TestDataRow(T value) -> void Microsoft.VisualStudio.TestTools.UnitTesting.TestDataRow.Value.get -> T Microsoft.VisualStudio.TestTools.UnitTesting.TestDataSourceDiscoveryAttribute @@ -533,13 +545,19 @@ Microsoft.VisualStudio.TestTools.UnitTesting.UnitTestOutcome.Unknown = 7 -> Micr Microsoft.VisualStudio.TestTools.UnitTesting.WorkItemAttribute Microsoft.VisualStudio.TestTools.UnitTesting.WorkItemAttribute.Id.get -> int Microsoft.VisualStudio.TestTools.UnitTesting.WorkItemAttribute.WorkItemAttribute(int id) -> void +override Microsoft.VisualStudio.TestTools.UnitTesting.CIConditionAttribute.GroupName.get -> string! +override Microsoft.VisualStudio.TestTools.UnitTesting.CIConditionAttribute.IgnoreMessage.get -> string? +override Microsoft.VisualStudio.TestTools.UnitTesting.CIConditionAttribute.IgnoreMessage.set -> void +override Microsoft.VisualStudio.TestTools.UnitTesting.CIConditionAttribute.ShouldRun.get -> bool override Microsoft.VisualStudio.TestTools.UnitTesting.GenericParameterHelper.Equals(object? obj) -> bool override Microsoft.VisualStudio.TestTools.UnitTesting.GenericParameterHelper.GetHashCode() -> int override Microsoft.VisualStudio.TestTools.UnitTesting.IgnoreAttribute.GroupName.get -> string! override Microsoft.VisualStudio.TestTools.UnitTesting.IgnoreAttribute.IgnoreMessage.get -> string? +override Microsoft.VisualStudio.TestTools.UnitTesting.IgnoreAttribute.IgnoreMessage.set -> void override Microsoft.VisualStudio.TestTools.UnitTesting.IgnoreAttribute.ShouldRun.get -> bool override Microsoft.VisualStudio.TestTools.UnitTesting.OSConditionAttribute.GroupName.get -> string! override Microsoft.VisualStudio.TestTools.UnitTesting.OSConditionAttribute.IgnoreMessage.get -> string? +override Microsoft.VisualStudio.TestTools.UnitTesting.OSConditionAttribute.IgnoreMessage.set -> void override Microsoft.VisualStudio.TestTools.UnitTesting.OSConditionAttribute.ShouldRun.get -> bool override Microsoft.VisualStudio.TestTools.UnitTesting.TestCategoryAttribute.TestCategories.get -> System.Collections.Generic.IList! static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(decimal expected, decimal actual, decimal delta, ref Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AssertNonGenericAreEqualInterpolatedStringHandler message) -> void @@ -625,6 +643,7 @@ static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.Contains(string! subs static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.Contains(string! substring, string! value, System.StringComparison comparisonType) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.Contains(string! substring, string! value) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.Contains(System.Func! predicate, System.Collections.Generic.IEnumerable! collection, string? message, params object?[]? parameters) -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.Contains(System.Func! predicate, System.Collections.Generic.IEnumerable! collection, string? message) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.Contains(System.Func! predicate, System.Collections.Generic.IEnumerable! collection) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.Contains(T expected, System.Collections.Generic.IEnumerable! collection, string? message, params object?[]? parameters) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.Contains(T expected, System.Collections.Generic.IEnumerable! collection, string? message) -> void @@ -636,6 +655,7 @@ static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.ContainsSingle(Sys static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.ContainsSingle(System.Collections.Generic.IEnumerable! collection, string? message, params object?[]? parameters) -> T static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.ContainsSingle(System.Collections.Generic.IEnumerable! collection, string? message) -> T static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.ContainsSingle(System.Collections.Generic.IEnumerable! collection) -> T +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.ContainsSingle(System.Func! predicate, System.Collections.Generic.IEnumerable! collection, string! message = "") -> T static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.DoesNotContain(string! substring, string! value, string? message, params object?[]? parameters) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.DoesNotContain(string! substring, string! value, string? message) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.DoesNotContain(string! substring, string! value, System.StringComparison comparisonType, string? message, params object?[]? parameters) -> void @@ -651,6 +671,14 @@ static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.DoesNotContain(T e static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.DoesNotContain(T expected, System.Collections.Generic.IEnumerable! collection, System.Collections.Generic.IEqualityComparer! comparer, string? message) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.DoesNotContain(T expected, System.Collections.Generic.IEnumerable! collection, System.Collections.Generic.IEqualityComparer! comparer) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.DoesNotContain(T expected, System.Collections.Generic.IEnumerable! collection) -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.DoesNotEndWith(string? substring, string? value, string! message = "") -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.DoesNotEndWith(string? substring, string? value, System.StringComparison comparisonType, string! message = "") -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.DoesNotMatchRegex(string? pattern, string? value, string! message = "") -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.DoesNotMatchRegex(System.Text.RegularExpressions.Regex? pattern, string? value, string! message = "") -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.DoesNotStartWith(string? substring, string? value, string! message = "") -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.DoesNotStartWith(string? substring, string? value, System.StringComparison comparisonType, string! message = "") -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.EndsWith(string? substring, string? value, string! message = "") -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.EndsWith(string? substring, string? value, System.StringComparison comparisonType, string! message = "") -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.Equals(object? objA, object? objB) -> bool static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.Fail() -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.Fail(string? message, params object?[]? parameters) -> void @@ -662,6 +690,7 @@ static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.HasCount(int expec static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.Inconclusive() -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.Inconclusive(string? message, params object?[]? parameters) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.Inconclusive(string? message) -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.Instance.get -> Microsoft.VisualStudio.TestTools.UnitTesting.Assert! static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsEmpty(System.Collections.Generic.IEnumerable! collection, ref Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AssertCountInterpolatedStringHandler message) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsEmpty(System.Collections.Generic.IEnumerable! collection, string? message, params object?[]? parameters) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsEmpty(System.Collections.Generic.IEnumerable! collection, string? message) -> void @@ -674,6 +703,9 @@ static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsFalse(bool? conditi static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsFalse(bool? condition, string? message, params object?[]? parameters) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsFalse(bool? condition, string? message) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsFalse(bool? condition) -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsGreaterThan(T lowerBound, T value, string! message = "") -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsGreaterThanOrEqualTo(T lowerBound, T value, string! message = "") -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsInRange(T minValue, T maxValue, T value, string! message = "") -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsInstanceOfType(object? value, System.Type? expectedType, ref Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AssertIsInstanceOfTypeInterpolatedStringHandler message) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsInstanceOfType(object? value, System.Type? expectedType, string? message, params object?[]? parameters) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsInstanceOfType(object? value, System.Type? expectedType, string? message) -> void @@ -686,6 +718,9 @@ static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsInstanceOfType(o static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsInstanceOfType(object? value, string? message, params object?[]? parameters) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsInstanceOfType(object? value, string? message) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsInstanceOfType(object? value) -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsLessThan(T upperBound, T value, string! message = "") -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsLessThanOrEqualTo(T upperBound, T value, string! message = "") -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsNegative(T value, string! message = "") -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsNotEmpty(System.Collections.Generic.IEnumerable! collection, ref Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AssertIsNotEmptyInterpolatedStringHandler message) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsNotEmpty(System.Collections.Generic.IEnumerable! collection, string? message, params object?[]? parameters) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsNotEmpty(System.Collections.Generic.IEnumerable! collection, string? message) -> void @@ -706,6 +741,7 @@ static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsNull(object? value, static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsNull(object? value, string? message, params object?[]? parameters) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsNull(object? value, string? message) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsNull(object? value) -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsPositive(T value, string! message = "") -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsTrue(bool condition, ref Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AssertIsTrueInterpolatedStringHandler message) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsTrue(bool condition, string? message, params object?[]? parameters) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsTrue(bool condition, string? message) -> void @@ -714,11 +750,17 @@ static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsTrue(bool? conditio static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsTrue(bool? condition, string? message, params object?[]? parameters) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsTrue(bool? condition, string? message) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsTrue(bool? condition) -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.MatchesRegex(string? pattern, string? value, string! message = "") -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.MatchesRegex(System.Text.RegularExpressions.Regex? pattern, string? value, string! message = "") -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.ReferenceEquals(object? objA, object? objB) -> bool static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.ReplaceNullChars(string? input) -> string? +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.StartsWith(string? substring, string? value, string! message = "") -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.StartsWith(string? substring, string? value, System.StringComparison comparisonType, string! message = "") -> void static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.That.get -> Microsoft.VisualStudio.TestTools.UnitTesting.Assert! static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.Throws(System.Action! action, ref Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AssertNonStrictThrowsInterpolatedStringHandler message) -> TException! static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.Throws(System.Action! action, string! message = "", params object![]! messageArgs) -> TException! static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.Throws(System.Action! action, System.Func! messageBuilder) -> TException! +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.Throws(System.Func! action, ref Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AssertNonStrictThrowsInterpolatedStringHandler message) -> TException! static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.Throws(System.Func! action, string! message = "", params object![]! messageArgs) -> TException! static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.Throws(System.Func! action, System.Func! messageBuilder) -> TException! static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.ThrowsAsync(System.Func! action, string! message = "", params object![]! messageArgs) -> System.Threading.Tasks.Task! @@ -726,6 +768,7 @@ static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.ThrowsAsync(System.Action! action, ref Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AssertThrowsExactlyInterpolatedStringHandler message) -> TException! static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.ThrowsExactly(System.Action! action, string! message = "", params object![]! messageArgs) -> TException! static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.ThrowsExactly(System.Action! action, System.Func! messageBuilder) -> TException! +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.ThrowsExactly(System.Func! action, ref Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AssertThrowsExactlyInterpolatedStringHandler message) -> TException! static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.ThrowsExactly(System.Func! action, string! message = "", params object![]! messageArgs) -> TException! static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.ThrowsExactly(System.Func! action, System.Func! messageBuilder) -> TException! static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.ThrowsExactlyAsync(System.Func! action, string! message = "", params object![]! messageArgs) -> System.Threading.Tasks.Task! @@ -778,12 +821,15 @@ static Microsoft.VisualStudio.TestTools.UnitTesting.CollectionAssert.Contains(Sy static Microsoft.VisualStudio.TestTools.UnitTesting.CollectionAssert.DoesNotContain(System.Collections.ICollection? collection, object? element, string? message, params object?[]? parameters) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.CollectionAssert.DoesNotContain(System.Collections.ICollection? collection, object? element, string? message) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.CollectionAssert.DoesNotContain(System.Collections.ICollection? collection, object? element) -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.CollectionAssert.Equals(object? objA, object? objB) -> bool +static Microsoft.VisualStudio.TestTools.UnitTesting.CollectionAssert.Instance.get -> Microsoft.VisualStudio.TestTools.UnitTesting.CollectionAssert! static Microsoft.VisualStudio.TestTools.UnitTesting.CollectionAssert.IsNotSubsetOf(System.Collections.ICollection? subset, System.Collections.ICollection? superset, string? message, params object?[]? parameters) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.CollectionAssert.IsNotSubsetOf(System.Collections.ICollection? subset, System.Collections.ICollection? superset, string? message) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.CollectionAssert.IsNotSubsetOf(System.Collections.ICollection? subset, System.Collections.ICollection? superset) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.CollectionAssert.IsSubsetOf(System.Collections.ICollection? subset, System.Collections.ICollection? superset, string? message, params object?[]? parameters) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.CollectionAssert.IsSubsetOf(System.Collections.ICollection? subset, System.Collections.ICollection? superset, string? message) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.CollectionAssert.IsSubsetOf(System.Collections.ICollection? subset, System.Collections.ICollection? superset) -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.CollectionAssert.ReferenceEquals(object? objA, object? objB) -> bool static Microsoft.VisualStudio.TestTools.UnitTesting.CollectionAssert.That.get -> Microsoft.VisualStudio.TestTools.UnitTesting.CollectionAssert! static Microsoft.VisualStudio.TestTools.UnitTesting.DataRowAttribute.TestIdGenerationStrategy.get -> Microsoft.VisualStudio.TestTools.UnitTesting.TestIdGenerationStrategy static Microsoft.VisualStudio.TestTools.UnitTesting.Logging.Logger.LogMessage(string! format, params object?[]! args) -> void @@ -803,9 +849,12 @@ static Microsoft.VisualStudio.TestTools.UnitTesting.StringAssert.EndsWith(string static Microsoft.VisualStudio.TestTools.UnitTesting.StringAssert.EndsWith(string? value, string? substring, string? message) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.StringAssert.EndsWith(string? value, string? substring, System.StringComparison comparisonType) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.StringAssert.EndsWith(string? value, string? substring) -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.StringAssert.Equals(object? objA, object? objB) -> bool +static Microsoft.VisualStudio.TestTools.UnitTesting.StringAssert.Instance.get -> Microsoft.VisualStudio.TestTools.UnitTesting.StringAssert! static Microsoft.VisualStudio.TestTools.UnitTesting.StringAssert.Matches(string? value, System.Text.RegularExpressions.Regex? pattern, string? message, params object?[]? parameters) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.StringAssert.Matches(string? value, System.Text.RegularExpressions.Regex? pattern, string? message) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.StringAssert.Matches(string? value, System.Text.RegularExpressions.Regex? pattern) -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.StringAssert.ReferenceEquals(object? objA, object? objB) -> bool static Microsoft.VisualStudio.TestTools.UnitTesting.StringAssert.StartsWith(string? value, string? substring, string? message, params object?[]? parameters) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.StringAssert.StartsWith(string? value, string? substring, string? message, System.StringComparison comparisonType, params object?[]? parameters) -> void static Microsoft.VisualStudio.TestTools.UnitTesting.StringAssert.StartsWith(string? value, string? substring, string? message, System.StringComparison comparisonType) -> void @@ -816,6 +865,8 @@ static Microsoft.VisualStudio.TestTools.UnitTesting.StringAssert.That.get -> Mic static readonly Microsoft.VisualStudio.TestTools.UnitTesting.ClassCleanupExecutionAttribute.DefaultClassCleanupLifecycle -> Microsoft.VisualStudio.TestTools.UnitTesting.ClassCleanupBehavior static readonly Microsoft.VisualStudio.TestTools.UnitTesting.DataSourceAttribute.DefaultDataAccessMethod -> Microsoft.VisualStudio.TestTools.UnitTesting.DataAccessMethod static readonly Microsoft.VisualStudio.TestTools.UnitTesting.DataSourceAttribute.DefaultProviderName -> string! +virtual Microsoft.VisualStudio.TestTools.UnitTesting.ConditionBaseAttribute.IgnoreMessage.get -> string? +virtual Microsoft.VisualStudio.TestTools.UnitTesting.ConditionBaseAttribute.IgnoreMessage.set -> void virtual Microsoft.VisualStudio.TestTools.UnitTesting.DataRowAttribute.GetDisplayName(System.Reflection.MethodInfo! methodInfo, object?[]? data) -> string? virtual Microsoft.VisualStudio.TestTools.UnitTesting.ExpectedExceptionBaseAttribute.NoExceptionMessage.get -> string! virtual Microsoft.VisualStudio.TestTools.UnitTesting.Logging.Logger.LogMessageHandler.Invoke(string! message) -> void diff --git a/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Unshipped.txt b/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Unshipped.txt index abe780feb5..7dc5c58110 100644 --- a/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Unshipped.txt +++ b/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Unshipped.txt @@ -1,55 +1 @@ #nullable enable -Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AssertNonStrictThrowsInterpolatedStringHandler.AssertNonStrictThrowsInterpolatedStringHandler(int literalLength, int formattedCount, System.Func! action, out bool shouldAppend) -> void -Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AssertThrowsExactlyInterpolatedStringHandler.AssertThrowsExactlyInterpolatedStringHandler(int literalLength, int formattedCount, System.Func! action, out bool shouldAppend) -> void -Microsoft.VisualStudio.TestTools.UnitTesting.CIConditionAttribute -Microsoft.VisualStudio.TestTools.UnitTesting.CIConditionAttribute.CIConditionAttribute(Microsoft.VisualStudio.TestTools.UnitTesting.ConditionMode mode) -> void -Microsoft.VisualStudio.TestTools.UnitTesting.ConditionBaseAttribute.Mode.get -> Microsoft.VisualStudio.TestTools.UnitTesting.ConditionMode -Microsoft.VisualStudio.TestTools.UnitTesting.GlobalTestCleanupAttribute -Microsoft.VisualStudio.TestTools.UnitTesting.GlobalTestCleanupAttribute.GlobalTestCleanupAttribute() -> void -Microsoft.VisualStudio.TestTools.UnitTesting.GlobalTestInitializeAttribute -Microsoft.VisualStudio.TestTools.UnitTesting.GlobalTestInitializeAttribute.GlobalTestInitializeAttribute() -> void -override Microsoft.VisualStudio.TestTools.UnitTesting.CIConditionAttribute.GroupName.get -> string! -override Microsoft.VisualStudio.TestTools.UnitTesting.CIConditionAttribute.IgnoreMessage.get -> string? -override Microsoft.VisualStudio.TestTools.UnitTesting.CIConditionAttribute.IgnoreMessage.set -> void -override Microsoft.VisualStudio.TestTools.UnitTesting.CIConditionAttribute.ShouldRun.get -> bool -Microsoft.VisualStudio.TestTools.UnitTesting.DynamicDataAttribute.DynamicDataAttribute(string! dynamicDataSourceName, params object?[]! dynamicDataSourceArguments) -> void -Microsoft.VisualStudio.TestTools.UnitTesting.DynamicDataAttribute.DynamicDataAttribute(string! dynamicDataSourceName, System.Type! dynamicDataDeclaringType, params object?[]! dynamicDataSourceArguments) -> void -Microsoft.VisualStudio.TestTools.UnitTesting.TestDataRow.TestCategories.get -> System.Collections.Generic.IList? -Microsoft.VisualStudio.TestTools.UnitTesting.TestDataRow.TestCategories.set -> void -override Microsoft.VisualStudio.TestTools.UnitTesting.IgnoreAttribute.IgnoreMessage.set -> void -override Microsoft.VisualStudio.TestTools.UnitTesting.OSConditionAttribute.IgnoreMessage.set -> void -static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.ContainsSingle(System.Func! predicate, System.Collections.Generic.IEnumerable! collection, string! message = "") -> T -static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.DoesNotEndWith(string? substring, string? value, string! message = "") -> void -static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.DoesNotEndWith(string? substring, string? value, System.StringComparison comparisonType, string! message = "") -> void -static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.DoesNotMatchRegex(string? pattern, string? value, string! message = "") -> void -static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.DoesNotMatchRegex(System.Text.RegularExpressions.Regex? pattern, string? value, string! message = "") -> void -static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.DoesNotStartWith(string? substring, string? value, string! message = "") -> void -static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.DoesNotStartWith(string? substring, string? value, System.StringComparison comparisonType, string! message = "") -> void -static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.EndsWith(string? substring, string? value, string! message = "") -> void -static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.EndsWith(string? substring, string? value, System.StringComparison comparisonType, string! message = "") -> void -static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsGreaterThan(T lowerBound, T value, string! message = "") -> void -static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsGreaterThanOrEqualTo(T lowerBound, T value, string! message = "") -> void -static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.Instance.get -> Microsoft.VisualStudio.TestTools.UnitTesting.Assert! -static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.Contains(System.Func! predicate, System.Collections.Generic.IEnumerable! collection, string? message) -> void -static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsInRange(T minValue, T maxValue, T value, string! message = "") -> void -static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsLessThan(T upperBound, T value, string! message = "") -> void -static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsLessThanOrEqualTo(T upperBound, T value, string! message = "") -> void -static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsNegative(T value, string! message = "") -> void -static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsPositive(T value, string! message = "") -> void -static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.MatchesRegex(string? pattern, string? value, string! message = "") -> void -static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.MatchesRegex(System.Text.RegularExpressions.Regex? pattern, string? value, string! message = "") -> void -static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.StartsWith(string? substring, string? value, string! message = "") -> void -static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.StartsWith(string? substring, string? value, System.StringComparison comparisonType, string! message = "") -> void -static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.Throws(System.Func! action, ref Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AssertNonStrictThrowsInterpolatedStringHandler message) -> TException! -static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.ThrowsExactly(System.Func! action, ref Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AssertThrowsExactlyInterpolatedStringHandler message) -> TException! -static Microsoft.VisualStudio.TestTools.UnitTesting.CollectionAssert.Instance.get -> Microsoft.VisualStudio.TestTools.UnitTesting.CollectionAssert! -static Microsoft.VisualStudio.TestTools.UnitTesting.StringAssert.Instance.get -> Microsoft.VisualStudio.TestTools.UnitTesting.StringAssert! -*REMOVED*static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.Contains(System.Collections.Generic.IEnumerable! collection, System.Func! predicate, string? message) -> void -static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.ReferenceEquals(object? objA, object? objB) -> bool -static Microsoft.VisualStudio.TestTools.UnitTesting.CollectionAssert.Equals(object? objA, object? objB) -> bool -static Microsoft.VisualStudio.TestTools.UnitTesting.CollectionAssert.ReferenceEquals(object? objA, object? objB) -> bool -static Microsoft.VisualStudio.TestTools.UnitTesting.StringAssert.Equals(object? objA, object? objB) -> bool -static Microsoft.VisualStudio.TestTools.UnitTesting.StringAssert.ReferenceEquals(object? objA, object? objB) -> bool -*REMOVED*abstract Microsoft.VisualStudio.TestTools.UnitTesting.ConditionBaseAttribute.IgnoreMessage.get -> string? -virtual Microsoft.VisualStudio.TestTools.UnitTesting.ConditionBaseAttribute.IgnoreMessage.get -> string? -virtual Microsoft.VisualStudio.TestTools.UnitTesting.ConditionBaseAttribute.IgnoreMessage.set -> void From 708b4326a89dcb0016d120237c49295aa6878991 Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Tue, 29 Jul 2025 10:45:16 +0200 Subject: [PATCH 313/541] [main] Update dependencies from microsoft/testfx (#6207) Co-authored-by: dotnet-maestro[bot] --- eng/Version.Details.xml | 8 ++++---- eng/Versions.props | 4 ++-- .../AnalyzersTests.cs | 2 +- .../TimeoutTests.cs | 14 ++++---------- .../TrxTests.cs | 2 +- .../Terminal/TerminalTestReporterTests.cs | 2 +- 6 files changed, 13 insertions(+), 19 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index 10799facb8..6b89395102 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -17,13 +17,13 @@ https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage 005149fac82d93baa64fa87c3bae1004c9cd11e1 - + https://github.com/microsoft/testfx - f1ea405d3997a828d15f68be2c239e9053ccb038 + 4517f8a354d3e066d8e44796b37a1064b6bfd8a7 - + https://github.com/microsoft/testfx - f1ea405d3997a828d15f68be2c239e9053ccb038 + 4517f8a354d3e066d8e44796b37a1064b6bfd8a7 diff --git a/eng/Versions.props b/eng/Versions.props index bd61238afa..6e9255b2a6 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -10,7 +10,7 @@ 10.0.0-beta.25374.4 17.14.2 - 3.10.0-preview.25374.11 - 1.8.0-preview.25374.11 + 3.10.0-preview.25378.9 + 1.8.0-preview.25378.9 diff --git a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/AnalyzersTests.cs b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/AnalyzersTests.cs index bf6d87b7c3..b1dea06401 100644 --- a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/AnalyzersTests.cs +++ b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/AnalyzersTests.cs @@ -238,7 +238,7 @@ private static async Task AssertAnalysisModeAsync(string mode, string[] contains foreach (string doesNotContainElement in doesNotContain) { - Assert.IsFalse(output.Contains(doesNotContainElement), $"Expected to not find '{doesNotContainElement}' for analysisMode {mode}"); + Assert.DoesNotContain(doesNotContainElement, output, $"Expected to not find '{doesNotContainElement}' for analysisMode {mode}"); } } } diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/TimeoutTests.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/TimeoutTests.cs index 0e0bdc1db7..334a4f09e0 100644 --- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/TimeoutTests.cs +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/TimeoutTests.cs @@ -47,7 +47,7 @@ public async Task TimeoutWithValidArg_WithTestTimeOut_OutputContainsCancelingMes TestHostResult testHostResult = await testHost.ExecuteAsync("--timeout 1s"); testHostResult.AssertExitCodeIsNot(ExitCodes.Success); - testHostResult.StandardOutput.Contains("Canceling the test session"); + testHostResult.AssertOutputContains("Canceling the test session"); } [DynamicData(nameof(TargetFrameworks.AllForDynamicData), typeof(TargetFrameworks))] @@ -58,9 +58,7 @@ public async Task TimeoutWithValidArg_WithSecondAsSuffix_WithTestNotTimeOut_Outp TestHostResult testHostResult = await testHost.ExecuteAsync("--timeout 12.5s"); testHostResult.AssertExitCodeIs(ExitCodes.ZeroTests); - - string output = testHostResult.StandardOutput; - Assert.IsFalse(output.Contains("Canceling the test session")); + testHostResult.AssertOutputDoesNotContain("Canceling the test session"); } [DynamicData(nameof(TargetFrameworks.AllForDynamicData), typeof(TargetFrameworks))] @@ -71,9 +69,7 @@ public async Task TimeoutWithValidArg_WithMinuteAsSuffix_WithTestNotTimeOut_Outp TestHostResult testHostResult = await testHost.ExecuteAsync("--timeout 1m"); testHostResult.AssertExitCodeIs(ExitCodes.ZeroTests); - - string output = testHostResult.StandardOutput; - Assert.IsFalse(output.Contains("Canceling the test session")); + testHostResult.AssertOutputDoesNotContain("Canceling the test session"); } [DynamicData(nameof(TargetFrameworks.AllForDynamicData), typeof(TargetFrameworks))] @@ -84,9 +80,7 @@ public async Task TimeoutWithValidArg_WithHourAsSuffix_WithTestNotTimeOut_Output TestHostResult testHostResult = await testHost.ExecuteAsync("--timeout 1h"); testHostResult.AssertExitCodeIs(ExitCodes.ZeroTests); - - string output = testHostResult.StandardOutput; - Assert.IsFalse(output.Contains("Canceling the test session")); + testHostResult.AssertOutputDoesNotContain("Canceling the test session"); } public sealed class TestAssetFixture() : TestAssetFixtureBase(AcceptanceFixture.NuGetGlobalPackagesFolder) diff --git a/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/TrxTests.cs b/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/TrxTests.cs index 1dd7387681..0226f9bde0 100644 --- a/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/TrxTests.cs +++ b/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/TrxTests.cs @@ -47,7 +47,7 @@ public async Task TrxReportEngine_GenerateReportAsyncWithNullAdapterSupportTrxCa XDocument xml = memoryStream.TrxContent; AssertTrxOutcome(xml, "Completed"); string trxContent = xml.ToString(); - Assert.IsFalse(trxContent.Contains(@"className=")); + Assert.DoesNotContain(@"className=", trxContent); } [TestMethod] diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/OutputDevice/Terminal/TerminalTestReporterTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/OutputDevice/Terminal/TerminalTestReporterTests.cs index f8d8a9b240..cfba5bf030 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/OutputDevice/Terminal/TerminalTestReporterTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/OutputDevice/Terminal/TerminalTestReporterTests.cs @@ -35,7 +35,7 @@ public void AppendStackFrameFormatsStackTraceLineCorrectly() Assert.Contains(" at Microsoft.Testing.Platform.UnitTests.TerminalTestReporterTests.AppendStackFrameFormatsStackTraceLineCorrectly()", terminal.Output); #endif // Line number without the respective file - Assert.IsFalse(terminal.Output.Contains(" :0")); + Assert.DoesNotContain(" :0", terminal.Output); } // Code with line when we have symbols From 502e46adf92e5d6375b6180bbeb81ea52a17dfe6 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Tue, 29 Jul 2025 12:36:21 +0200 Subject: [PATCH 314/541] Revert "[rel/3.10] Use stable CC" (#6217) --- eng/Version.Details.xml | 4 ++-- eng/Versions.props | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index 6b89395102..be83519ca3 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -13,9 +13,9 @@ https://github.com/dotnet/arcade e2fed65f9c524d12c64876194ae4ce177b935bb3 - + https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage - 005149fac82d93baa64fa87c3bae1004c9cd11e1 + 4fa8f0c467e38db87fae04266d98e4288dad4697 https://github.com/microsoft/testfx diff --git a/eng/Versions.props b/eng/Versions.props index 6e9255b2a6..e2f3be8483 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -8,7 +8,7 @@ 10.0.0-beta.25374.4 - 17.14.2 + 18.0.0-preview.25378.1 3.10.0-preview.25378.9 1.8.0-preview.25378.9 From 6f587e16963ab1f0c8ede949194739f795d97ebb Mon Sep 17 00:00:00 2001 From: dotnet bot Date: Tue, 29 Jul 2025 03:56:56 -0700 Subject: [PATCH 315/541] Localized file check-in by OneLocBuild Task: Build definition ID 1218: Build ID 2760457 --- .../xlf/Resources.zh-Hans.xlf | 34 +++++++++---------- .../xlf/Resources.zh-Hant.xlf | 34 +++++++++---------- 2 files changed, 34 insertions(+), 34 deletions(-) diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf index 2afde7d45e..fce3905e91 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf @@ -464,32 +464,32 @@ The type declaring these methods should also respect the following rules: -The class shouldn't be 'static' -The class should be marked with '[TestClass]' (or a derived attribute) -the class should not be generic. - Methods marked with '[GlobalTestInitialize]' or '[GlobalTestCleanup]' should follow the following layout to be valid: --it can't be declared on a generic class --it should be 'public' --it should be 'static' --it should not be 'async void' --it should not be a special method (finalizer, operator...). --it should not be generic --it should take one parameter of type 'TestContext' --return type should be 'void', 'Task' or 'ValueTask' + 标记有 "[GlobalTestInitialize]" 或 "[GlobalTestCleanup]" 的方法应遵循以下布局才会有效: +- 不能在泛型类上声明它 +- 它应为 "public" +- 它应为 "static" +- 它不应为 "async void" +- 它不应是特殊方法(终结器、运算符...)。 +- 它不应是泛型的 +- 它应采用 "TestContext" 类型的一个参数 +- 返回类型应为 "void"、"Task" 或 "ValueTask" -The type declaring these methods should also respect the following rules: --The type should be a class --The class should be 'public' --The class shouldn't be 'static' --The class should be marked with '[TestClass]' (or a derived attribute) --the class should not be generic. +声明这些方法的类型还应遵循以下规则: +- 类型应为类 +- 类应该为 "public" +- 类不应为 "static" +- 应使用 "[TestClass]"(或派生属性)标记类 +- 类不应是泛型的。 Global test fixture method '{0}' signature is invalid - Global test fixture method '{0}' signature is invalid + 全局测试固定例程方法 "{0}" 签名无效 GlobalTestInitialize and GlobalTestCleanup methods should have valid layout - GlobalTestInitialize and GlobalTestCleanup methods should have valid layout + GlobalTestInitialize 和 GlobalTestCleanup 方法应具有有效的布局 diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf index 069c97013d..992bf1f44a 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf @@ -464,32 +464,32 @@ The type declaring these methods should also respect the following rules: -The class shouldn't be 'static' -The class should be marked with '[TestClass]' (or a derived attribute) -the class should not be generic. - Methods marked with '[GlobalTestInitialize]' or '[GlobalTestCleanup]' should follow the following layout to be valid: --it can't be declared on a generic class --it should be 'public' --it should be 'static' --it should not be 'async void' --it should not be a special method (finalizer, operator...). --it should not be generic --it should take one parameter of type 'TestContext' --return type should be 'void', 'Task' or 'ValueTask' + 標示為 '[GlobalTestInitialize]' 或 '[GlobalTestCleanup]' 的方法應該遵循下列配置才能有效: +-其不能在泛型類別上宣告 +-其應為 'public' +-其應為 'static' +-其不應為 'async void' +-其不應為特殊方法 (完成項、運算子...)。 +-其不應為泛型 +-其應該接受類型為 'TestContext' 的一個參數 +-傳回類型應為 'void'、'Task' 或 'ValueTask' -The type declaring these methods should also respect the following rules: --The type should be a class --The class should be 'public' --The class shouldn't be 'static' --The class should be marked with '[TestClass]' (or a derived attribute) --the class should not be generic. +宣告這些方法的類型還應遵循以下規則: +-類型應為類別 +-類別應為 'public' +-類別不應為 'static' +-類別應標示為 '[TestClass]' (或衍生屬性) +-類別不應為泛型。 Global test fixture method '{0}' signature is invalid - Global test fixture method '{0}' signature is invalid + 全域測試固件方法 '{0}' 的簽名無效 GlobalTestInitialize and GlobalTestCleanup methods should have valid layout - GlobalTestInitialize and GlobalTestCleanup methods should have valid layout + GlobalTestInitialize 和 GlobalTestCleanup 方法應具備有效的配置 From 88abaa8b08bbe6422a507f624c519c4274457b9d Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Tue, 29 Jul 2025 15:25:18 +0200 Subject: [PATCH 316/541] Add post-build.yml back (#6219) --- azure-pipelines-official.yml | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/azure-pipelines-official.yml b/azure-pipelines-official.yml index f35ab0002d..982eec0b70 100644 --- a/azure-pipelines-official.yml +++ b/azure-pipelines-official.yml @@ -90,8 +90,7 @@ extends: enablePublishTestResults: true testResultsFormat: 'vstest' enablePublishBuildAssets: true - # For final version build, don't publish to internal feeds. - isAssetlessBuild: ${{ parameters.isRTM }} + enablePublishUsingPipelines: true enableTelemetry: true jobs: - job: Windows @@ -238,6 +237,4 @@ extends: LclSource: lclFilesfromPackage LclPackageId: 'LCL-JUNO-PROD-TESTFX' - # For stable versions avoid publishing them to internal feeds. - - ${{ if eq(parameters.isRTM, False) }}: - - template: eng\common\templates-official\post-build\post-build.yml@self + - template: eng\common\templates-official\post-build\post-build.yml@self From fb20b61a0982e93e119f468bd0d396b8f73a27ea Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Tue, 29 Jul 2025 17:32:57 +0200 Subject: [PATCH 317/541] Add 3.10 release notes (#6221) --- docs/Changelog-Platform.md | 76 +++++++++++++++++++++++++ docs/Changelog.md | 110 ++++++++++++++++++++++++++++++++++--- 2 files changed, 177 insertions(+), 9 deletions(-) diff --git a/docs/Changelog-Platform.md b/docs/Changelog-Platform.md index 13fda7dd6c..91fcfbfa1b 100644 --- a/docs/Changelog-Platform.md +++ b/docs/Changelog-Platform.md @@ -4,6 +4,82 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) +## [1.8.0] - 2025-07-29 + +See full log [of v3.9.3...v3.10.0](https://github.com/microsoft/testfx/compare/v3.9.3...v3.10.0) + +### Added + +* Enable filtering with `TestMetadataProperty` in the treenode filter by @thomhurst in [#5679](https://github.com/microsoft/testfx/pull/5679) +* Show colors in AzDo and GH actions by @nohwnd in [#5535](https://github.com/microsoft/testfx/pull/5535) +* Handle metadata properties in TrxReport by @Youssef1313 in [#5891](https://github.com/microsoft/testfx/pull/5891) +* Obsolete `ITestApplicationLifecycleCallbacks` and add `ITestHostApplicationLifetime` by @Youssef1313 in [#5889](https://github.com/microsoft/testfx/pull/5889) +* Fix TrxReport not including test ignore reason by @Youssef1313 in [#5896](https://github.com/microsoft/testfx/pull/5896) +* Support `--filter-uid` on console by @Youssef1313 in [#6002](https://github.com/microsoft/testfx/pull/6002) +* Support unary not operator in TreeNodeFilter by @Youssef1313 in [#6127](https://github.com/microsoft/testfx/pull/6127) + +### Fixed + +* Fix MTP timeout parsing to use invariant culture instead of current culture by @Copilot in [#5705](https://github.com/microsoft/testfx/pull/5705) +* Add lifecycle callbacks to test host orchestrator by @Youssef1313 in [#5717](https://github.com/microsoft/testfx/pull/5717) +* Avoid potential clash with default TRX file name by @Youssef1313 in [#5939](https://github.com/microsoft/testfx/pull/5939) +* Ensure TestRun id for retries is the same in TRX by @Youssef1313 in [#5945](https://github.com/microsoft/testfx/pull/5945) +* Do not create TestResults dir for help and info options by @Evangelink in [#6020](https://github.com/microsoft/testfx/pull/6020) + +### Housekeeping + +* remove redundant Empty constructor and mark as warning by @SimonCropp in [#5378](https://github.com/microsoft/testfx/pull/5378) +* use char based APIs in TryUnescape by @SimonCropp in [#5608](https://github.com/microsoft/testfx/pull/5608) +* attribute param nullability in TryUnescape by @SimonCropp in [#5609](https://github.com/microsoft/testfx/pull/5609) +* Cleanup TestApplicationResult by @Youssef1313 in [#5615](https://github.com/microsoft/testfx/pull/5615) +* remove redundant fields by @SimonCropp in [#5610](https://github.com/microsoft/testfx/pull/5610) +* Rename RegisterTestFramework adapterFactory parameter to frameworkFactory by @Copilot in [#5691](https://github.com/microsoft/testfx/pull/5691) +* prefer specific scoped variables by @SimonCropp in [#5611](https://github.com/microsoft/testfx/pull/5611) +* \[VSTestBridge] Avoid creating Uri instance for every test case. by @Youssef1313 in [#5743](https://github.com/microsoft/testfx/pull/5743) +* avoid redundant string builder instance in ValidateTestHostEnvironmentVariablesAsync by @SimonCropp in [#5905](https://github.com/microsoft/testfx/pull/5905) +* remove redundant assignment in TryGetOptionArgumentList by @SimonCropp in [#5908](https://github.com/microsoft/testfx/pull/5908) +* remove redundant environment instance in TestHostBuilder by @SimonCropp in [#5914](https://github.com/microsoft/testfx/pull/5914) +* Avoid keeping instance of process in DotnetMuxerLocator by @SimonCropp in [#5911](https://github.com/microsoft/testfx/pull/5911) +* Add ProcessId to IEnvironment by @SimonCropp in [#5913](https://github.com/microsoft/testfx/pull/5913) +* CrashDumpEnvironmentVariableProvider prefixes can be static by @SimonCropp in [#5909](https://github.com/microsoft/testfx/pull/5909) +* remove unused SystemProcessHandler parameter by @SimonCropp in [#5918](https://github.com/microsoft/testfx/pull/5918) +* missing using in AttachDebuggerIfNeeded by @SimonCropp in [#5919](https://github.com/microsoft/testfx/pull/5919) +* redundant null checks in TrxProcessLifetimeHandler by @SimonCropp in [#5960](https://github.com/microsoft/testfx/pull/5960) +* remove redundant BuildConsumerProducersAsync by @SimonCropp in [#5962](https://github.com/microsoft/testfx/pull/5962) +* remove non generic ActionResult by @SimonCropp in [#5959](https://github.com/microsoft/testfx/pull/5959) +* fix nullablity in FromFailedTest by @SimonCropp in [#5971](https://github.com/microsoft/testfx/pull/5971) +* make dicts in NamedPipeBase strong typed by @SimonCropp in [#5973](https://github.com/microsoft/testfx/pull/5973) +* simplify reading installLocation content by @SimonCropp in [#5968](https://github.com/microsoft/testfx/pull/5968) +* update Polyfill and use Process.Kill by @SimonCropp in [#5943](https://github.com/microsoft/testfx/pull/5943) +* Simplify IProcess.MainModule by @SimonCropp in [#5955](https://github.com/microsoft/testfx/pull/5955) +* use ReadExactly from Polyfill by @SimonCropp in [#5972](https://github.com/microsoft/testfx/pull/5972) +* suppress TPEXP warning for solution by @SimonCropp in [#5984](https://github.com/microsoft/testfx/pull/5984) +* use ReadAllTextAsync from polyfill by @SimonCropp in [#5953](https://github.com/microsoft/testfx/pull/5953) +* use TryAdd instead of TryGetValue and Add in Async MessageBus by @SimonCropp in [#5963](https://github.com/microsoft/testfx/pull/5963) +* use XElement.LoadAsync in TrxCompareTool by @SimonCropp in [#5975](https://github.com/microsoft/testfx/pull/5975) +* fix RunSettingsEnvironmentVariableProvider file name by @SimonCropp in [#6007](https://github.com/microsoft/testfx/pull/6007) +* fix nullability of TestProgressState.DiscoveredTests by @SimonCropp in [#6011](https://github.com/microsoft/testfx/pull/6011) +* remove Uid from DiscoveredTests by @SimonCropp in [#6019](https://github.com/microsoft/testfx/pull/6019) +* remove predicate from RetryHelper by @SimonCropp in [#6027](https://github.com/microsoft/testfx/pull/6027) +* update Polyfill and simplify SHA256 usage by @SimonCropp in [#6029](https://github.com/microsoft/testfx/pull/6029) +* simplify TrxCompareTool using an inner type instead of tuples by @SimonCropp in [#6024](https://github.com/microsoft/testfx/pull/6024) +* reduce some linq alloc in AppendTestDiscoverySummary by @SimonCropp in [#6025](https://github.com/microsoft/testfx/pull/6025) +* fix Syncronous typo by @SimonCropp in [#6048](https://github.com/microsoft/testfx/pull/6048) + +### Artifacts + +* Microsoft.Testing.Platform: [1.8.0](https://www.nuget.org/packages/Microsoft.Testing.Platform/1.8.0) +* Microsoft.Testing.Platform.MSBuild: [1.8.0](https://www.nuget.org/packages/Microsoft.Testing.Platform.MSBuild/1.8.0) +* Microsoft.Testing.Extensions.CrashDump: [1.8.0](https://www.nuget.org/packages/Microsoft.Testing.Extensions.CrashDump/1.8.0) +* Microsoft.Testing.Extensions.HangDump: [1.8.0](https://www.nuget.org/packages/Microsoft.Testing.Extensions.HangDump/1.8.0) +* Microsoft.Testing.Extensions.HotReload: [1.8.0](https://www.nuget.org/packages/Microsoft.Testing.Extensions.HotReload/1.8.0) +* Microsoft.Testing.Extensions.Retry: [1.8.0](https://www.nuget.org/packages/Microsoft.Testing.Extensions.Retry/1.8.0) +* Microsoft.Testing.Extensions.Telemetry: [1.8.0](https://www.nuget.org/packages/Microsoft.Testing.Extensions.Telemetry/1.8.0) +* Microsoft.Testing.Extensions.TrxReport: [1.8.0](https://www.nuget.org/packages/Microsoft.Testing.Extensions.TrxReport/1.8.0) +* Microsoft.Testing.Extensions.TrxReport.Abstractions: [1.8.0](https://www.nuget.org/packages/Microsoft.Testing.Extensions.TrxReport.Abstractions/1.8.0) +* Microsoft.Testing.Extensions.VSTestBridge: [1.8.0](https://www.nuget.org/packages/Microsoft.Testing.Extensions.VSTestBridge/1.8.0) +* Microsoft.Testing.Extensions.AzureDevOpsReport [1.0.0-alpha.25379.8](https://www.nuget.org/packages/Microsoft.Testing.Extensions.AzureDevOpsReport/1.0.0-alpha.25379.8) + ## [1.7.3] - 2025-06-17 See full log [of v3.9.2...v3.9.3](https://github.com/microsoft/testfx/compare/v3.9.2...v3.9.3) diff --git a/docs/Changelog.md b/docs/Changelog.md index 350f80b081..07b7757c2f 100644 --- a/docs/Changelog.md +++ b/docs/Changelog.md @@ -4,6 +4,107 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) +## [3.10.0] - 2025-07-29 + +See full log [of v3.9.3...v3.10.0](https://github.com/microsoft/testfx/compare/v3.9.3...v3.10.0) + +### Added + +* Inherit OwnerAttribute and PriorityAttribute from TestPropertyAttribute by @Youssef1313 in [#5591](https://github.com/microsoft/testfx/pull/5591) +* Better handling of MSTest.TestAdapter under .NET Standard by @Youssef1313 in [#5647](https://github.com/microsoft/testfx/pull/5647) +* Add implicit using even when not using MSTest.Sdk by @Youssef1313 in [#5589](https://github.com/microsoft/testfx/pull/5589) +* Allow serialization of DateOnly/TimeOnly for parameterized tests by @Youssef1313 in [#5676](https://github.com/microsoft/testfx/pull/5676) +* Implement analyzer/codefix to move from DataTestMethodAttribute to TestMethodAttribute by @Copilot in [#5706](https://github.com/microsoft/testfx/pull/5706) +* Error if framework/adapter versions are mismatched at runtime by @Youssef1313 in [#5703](https://github.com/microsoft/testfx/pull/5703) +* Add predicate-based overloads for Assert.ContainsSingle API by @Copilot in [#5767](https://github.com/microsoft/testfx/pull/5767) +* Add Assert.IsInRange API with three overloads by @Copilot in [#5765](https://github.com/microsoft/testfx/pull/5765) +* Add comparison Assert APIs (IsGreaterThan, IsLessThan, IsPositive, IsNegative) by @Copilot in [#5790](https://github.com/microsoft/testfx/pull/5790) +* Add analyzer to suggest using cooperative cancellation for timeout by @Copilot in [#5786](https://github.com/microsoft/testfx/pull/5786) +* Deprecates `That` property and suggest `Instance` instead by @Evangelink in [#5811](https://github.com/microsoft/testfx/pull/5811) +* Improve error message for all Assert.Contains.cs APIs by @Copilot in [#5793](https://github.com/microsoft/testfx/pull/5793) +* Add Assert StartsWith/DoesNotStartWith, EndsWith/DoesNotEndsWith, MatchesRegex/DoesNotMatchRegex by @Evangelink in [#5768](https://github.com/microsoft/testfx/pull/5768) +* Obsolete Assert.Equals and add obsolete Assert.ReferenceEquals by @Copilot in [#5815](https://github.com/microsoft/testfx/pull/5815) +* Bump AvoidExpectedExceptionAttributeAnalyzer to warning by @Youssef1313 in [#5864](https://github.com/microsoft/testfx/pull/5864) +* Bump UseNewerAssertThrowsAnalyzer to warning by @Youssef1313 in [#5863](https://github.com/microsoft/testfx/pull/5863) +* Add analyzer and code fix to migrate from StringAssert to Assert APIs by @Copilot in [#5792](https://github.com/microsoft/testfx/pull/5792) +* Improve DataRow type mismatch error messages with descriptive parameter information by @Copilot in [#5819](https://github.com/microsoft/testfx/pull/5819) +* Inherit DescriptionAttribute from TestPropertyAttribute by @Youssef1313 in [#6004](https://github.com/microsoft/testfx/pull/6004) +* Add CIConditionAttribute to support CI-specific test execution control by @Copilot in [#5797](https://github.com/microsoft/testfx/pull/5797) +* Obsolete CssIteration and CssProjectStructure attributes for v3.10 by @Copilot in [#5981](https://github.com/microsoft/testfx/pull/5981) +* Support passing arguments to DynamicData methods by @Youssef1313 in [#5892](https://github.com/microsoft/testfx/pull/5892) +* Add TestCategories property to ITestDataRow for per-test-case categorization by @Copilot in [#5795](https://github.com/microsoft/testfx/pull/5795) +* Add diagnostic suppressor for IDE0060 warnings on TestContext parameters in MSTest fixture methods by @Copilot in [#6055](https://github.com/microsoft/testfx/pull/6055) +* Add analyzer for incorrect TestContext property usage in fixture methods by @Copilot in [#5990](https://github.com/microsoft/testfx/pull/5990) +* Update UseProperAssertMethodsAnalyzer to handle more use cases by @Copilot in [#6058](https://github.com/microsoft/testfx/pull/6058) +* Add analyzer to flow TestContext.CTS.Token by @Youssef1313 in [#6126](https://github.com/microsoft/testfx/pull/6126) +* Obsolete `TestTimeout` by @Evangelink in [#6144](https://github.com/microsoft/testfx/pull/6144) +* Make ConditionBaseAttribute.IgnoreMessage settable by @Evangelink in [#6150](https://github.com/microsoft/testfx/pull/6150) +* Add GlobalTestInitializeAttribute and GlobalTestCleanupAttribute by @Youssef1313 in [#6132](https://github.com/microsoft/testfx/pull/6132) + +### Fixed + +* OSConditionAttribute: Make ignore message depend on ConditionMode by @Youssef1313 in [#5587](https://github.com/microsoft/testfx/pull/5587) +* Fix MSTEST0004 analyzer to recognize TestClass-derived attributes by @Copilot in [#5600](https://github.com/microsoft/testfx/pull/5600) +* Fix MSTEST0005 false positive when using null-checking with TestContext constructor parameter by @Copilot in [#5601](https://github.com/microsoft/testfx/pull/5601) +* Fix async void analyzer to detect StringAssert and CollectionAssert by @Copilot in [#5650](https://github.com/microsoft/testfx/pull/5650) +* Fix leak in TestRunCancellationToken by @Youssef1313 in [#5730](https://github.com/microsoft/testfx/pull/5730) +* Fix TraceListenerManager thread safety issue by @Youssef1313 in [#5750](https://github.com/microsoft/testfx/pull/5750) +* Store the actual data to instead of deserializing by @Youssef1313 in [#5778](https://github.com/microsoft/testfx/pull/5778) +* Fix STA regression when async method completes asynchronously between sync methods by @Youssef1313 in [#5922](https://github.com/microsoft/testfx/pull/5922) +* Call GetDisplayName with the right arguments when tuples are used by @Youssef1313 in [#5929](https://github.com/microsoft/testfx/pull/5929) +* Fix MSTEST0020 codefix placing code in static constructors by @Copilot in [#5935](https://github.com/microsoft/testfx/pull/5935) +* Fix MSTEST0020 codefix constructor added in place of the TestInitialize method by @Copilot in [#5944](https://github.com/microsoft/testfx/pull/5944) +* Fix TypeContainingTestMethodShouldBeATestClassAnalyzer to handle structs with TestMethod by @Copilot in [#5818](https://github.com/microsoft/testfx/pull/5818) +* MSTest configuration improvement by @Youssef1313 in [#6078](https://github.com/microsoft/testfx/pull/6078) +* Fix nullability suppressor for TestContext when explicit constructor is declared by @Youssef1313 in [#6139](https://github.com/microsoft/testfx/pull/6139) +* Fix codefix behavior for partial classes with TestCleanup and Dispose in different parts by @Copilot in [#6164](https://github.com/microsoft/testfx/pull/6164) +* Add missing `Func` overload to ThrowsExactly by @Youssef1313 in [#6195](https://github.com/microsoft/testfx/pull/6195) + +### Housekeeping + +* Simplify reflection by @Youssef1313 in [#4702](https://github.com/microsoft/testfx/pull/4702) +* remove redudnant cast to IReadOnlyList and add a not null ckeck in AssemblyEnumeratorTests by @SimonCropp in [#5402](https://github.com/microsoft/testfx/pull/5402) +* use more collection expressions and mark as error in editorconfig by @SimonCropp in [#5377](https://github.com/microsoft/testfx/pull/5377) +* Add `copilot-instructions.md` by @Evangelink in [#5798](https://github.com/microsoft/testfx/pull/5798) +* Move files from adapter to platform services project by @Evangelink in [#5713](https://github.com/microsoft/testfx/pull/5713) +* Use ConfigureAwait(false) by @Youssef1313 in [#5719](https://github.com/microsoft/testfx/pull/5719) +* Add Dependabot configuration for .NET SDK updates by @JamieMagee in [#5861](https://github.com/microsoft/testfx/pull/5861) +* projects should inherit defined constants by @SimonCropp in [#5893](https://github.com/microsoft/testfx/pull/5893) +* check logging level in BridgedTraceLogger by @SimonCropp in [#5904](https://github.com/microsoft/testfx/pull/5904) +* fix nullability of CreateBindCtx by @SimonCropp in [#5907](https://github.com/microsoft/testfx/pull/5907) +* remove-zero-width-spaces-from-banned-symbols by @SimonCropp in [#5912](https://github.com/microsoft/testfx/pull/5912) +* use some string interpolation by @SimonCropp in [#5915](https://github.com/microsoft/testfx/pull/5915) +* use char based overloads by @SimonCropp in [#5916](https://github.com/microsoft/testfx/pull/5916) +* use some computed properties by @SimonCropp in [#5961](https://github.com/microsoft/testfx/pull/5961) +* remove some dead consts in EngineConstants by @SimonCropp in [#5967](https://github.com/microsoft/testfx/pull/5967) +* redundant null check in TryAddSearchDirectoriesSpecifiedInRunSettingsToAssemblyResolver by @SimonCropp in [#5966](https://github.com/microsoft/testfx/pull/5966) +* avoid dictionary lookups using TryAdd by @SimonCropp in [#5983](https://github.com/microsoft/testfx/pull/5983) +* remove redundnant escapedClassFullName in AppendAssemblyTestNodeBuilderContent by @SimonCropp in [#6012](https://github.com/microsoft/testfx/pull/6012) +* use the in built StringBuilder append char count by @SimonCropp in [#6013](https://github.com/microsoft/testfx/pull/6013) +* remove some un-used variables by @SimonCropp in [#6010](https://github.com/microsoft/testfx/pull/6010) +* Dont generate documentation for tests and samples by @SimonCropp in [#5441](https://github.com/microsoft/testfx/pull/5441) +* remove some empty type declarations by @SimonCropp in [#6041](https://github.com/microsoft/testfx/pull/6041) +* simplify IsNaN checks by @SimonCropp in [#6043](https://github.com/microsoft/testfx/pull/6043) +* use some exception filters by @SimonCropp in [#6049](https://github.com/microsoft/testfx/pull/6049) +* remove some un-used polyfills by @SimonCropp in [#6042](https://github.com/microsoft/testfx/pull/6042) +* fix Coxtext typo by @SimonCropp in [#6051](https://github.com/microsoft/testfx/pull/6051) +* Fix incorrect comments by @martincostello in [#6189](https://github.com/microsoft/testfx/pull/6189) + +### New Contributors + +* @JamieMagee made their first contribution in [#5861](https://github.com/microsoft/testfx/pull/5861) +* @martincostello made their first contribution in [#6198](https://github.com/microsoft/testfx/pull/6189) + +### Artifacts + +* MSTest: [3.10.0](https://www.nuget.org/packages/MSTest/3.10.0) +* MSTest.TestFramework: [3.10.0](https://www.nuget.org/packages/MSTest.TestFramework/3.10.0) +* MSTest.TestAdapter: [3.10.0](https://www.nuget.org/packages/MSTest.TestAdapter/3.10.0) +* MSTest.Analyzers: [3.10.0](https://www.nuget.org/packages/MSTest.Analyzers/3.10.0) +* MSTest.Sdk: [3.10.0](https://www.nuget.org/packages/MSTest.Sdk/3.10.0) +* MSTest.SourceGeneration: [1.0.0-alpha.25379.8](https://www.nuget.org/packages/MSTest.SourceGeneration/1.0.0-alpha.25379.8) +* MSTest.Engine: [1.0.0-alpha.25379.8](https://www.nuget.org/packages/MSTest.Engine/1.0.0-alpha.25379.8) + ## [3.9.3] - 2025-06-17 See full log [of v3.9.2...v3.9.3](https://github.com/microsoft/testfx/compare/v3.9.2...v3.9.3) @@ -731,10 +832,6 @@ See full log [of v3.5.2...v3.6.0](https://github.com/microsoft/testfx/compare/v3 See full log [of v3.5.1...v3.5.2](https://github.com/microsoft/testfx/compare/v3.5.1...v3.5.2) -### Fixed - -* Update dependencies from devdiv/DevDiv/vs-code-coverage by @dotnet-maestro in [#3533](https://github.com/microsoft/testfx/pull/3533) - ### Artifacts * MSTest: [3.5.2](https://www.nuget.org/packages/MSTest/3.5.2) @@ -1161,10 +1258,7 @@ See full log [of v3.2.0...v.3.2.1](https://github.com/microsoft/testfx/compare/v * MSTEST0002: fix false-positive with static TestClass (#2182) by @Evangelink in [#2199](https://github.com/microsoft/testfx/pull/2199) * Bump version of coverage and platform by @Evangelink in [#2280](https://github.com/microsoft/testfx/pull/2280) -* [rel/3.2] Update dependencies from devdiv/DevDiv/vs-code-coverage by @dotnet-maestro in [#2315](https://github.com/microsoft/testfx/pull/2315) * Fix command line output validation (#2314) by @MarcoRossignoli in [#2317](https://github.com/microsoft/testfx/pull/2317) -* [rel/3.2] Update dependencies from microsoft/testanywhere by @dotnet-maestro in [#2320](https://github.com/microsoft/testfx/pull/2320) -* [rel/3.2] Update dependencies from microsoft/testanywhere by @dotnet-maestro in [#2326](https://github.com/microsoft/testfx/pull/2326) ### Housekeeping @@ -1764,7 +1858,6 @@ A list of changes since last release are available [of v2.2.10...v2.3.0-preview- * [Assert failure messages](https://github.com/microsoft/testfx/pull/1172) * [Ensure assertions do not fail with FormatException](https://github.com/microsoft/testfx/pull/1126) * [Prevent format exceptions when parameters array is empty](https://github.com/microsoft/testfx/pull/1124) -* [\[main\] Update dependencies from dotnet/arcade](https://github.com/microsoft/testfx/pull/1098) ### Fixed @@ -1794,7 +1887,6 @@ A list of changes since last release are available [of v2.2.10-preview-20220414- * [Update description of the Nuget packages](https://github.com/microsoft/testfx/pull/981) * [Converted files to utf-8 so they can be diffed.](https://github.com/microsoft/testfx/pull/1070) -* [Update dependencies from https://github.com/dotnet/arcade build 20220425.6](https://github.com/microsoft/testfx/pull/1087) * [Run dotnet format whitespace](https://github.com/microsoft/testfx/pull/1085) ### Fixed From 4f142b58d33aba6ea571d265af598f34c1aa9627 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Tue, 29 Jul 2025 20:03:22 +0200 Subject: [PATCH 318/541] Update aspire version (#6225) --- Directory.Packages.props | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Directory.Packages.props b/Directory.Packages.props index 7c8ac71080..c3a27a7605 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -12,7 +12,7 @@ false - 9.0.0 + 9.4.0 17.11.4 3.11.0 4.10.0 From 44db59e0e37fcd3ea004b6103974f4e1e56d969d Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Tue, 29 Jul 2025 20:03:48 +0200 Subject: [PATCH 319/541] Update Playwright version (#6224) --- Directory.Packages.props | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Directory.Packages.props b/Directory.Packages.props index c3a27a7605..674c59ac55 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -22,7 +22,7 @@ 6.2.14 17.13.0 - 1.50.0 + 1.54.0 17.14.1 1.5.0-preview.24577.4 4.5.4 From 8ce85d648205940b47b043d85c15c73a7c0a4b9f Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Tue, 29 Jul 2025 20:51:32 +0200 Subject: [PATCH 320/541] Add compat overload for GetPipeName (#6227) --- .../Microsoft.Testing.Platform/IPC/NamedPipeServer.cs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/Platform/Microsoft.Testing.Platform/IPC/NamedPipeServer.cs b/src/Platform/Microsoft.Testing.Platform/IPC/NamedPipeServer.cs index 0fb0d3a1f4..2d2a8f0aa4 100644 --- a/src/Platform/Microsoft.Testing.Platform/IPC/NamedPipeServer.cs +++ b/src/Platform/Microsoft.Testing.Platform/IPC/NamedPipeServer.cs @@ -267,6 +267,14 @@ private async Task InternalLoopAsync(CancellationToken cancellationToken) } } + // For compatibility only. + // Old versions of MTP used to have this overload without IEnvironment. + // Extensions (e.g, TRX) calls into this overload. + // If core MTP is updated, but old version of TRX is still used, it will try to call this overload at runtime. + // Without it, MissingMethodException will be thrown at runtime. + public static PipeNameDescription GetPipeName(string name) + => GetPipeName(name, new SystemEnvironment()); + public static PipeNameDescription GetPipeName(string name, IEnvironment environment) { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) From 1e683a5711892737442b733dc4feccd3195dfd3c Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Tue, 29 Jul 2025 22:49:26 +0200 Subject: [PATCH 321/541] Avoid generate package on build (#6231) --- .../MSTest.Analyzers.Package/MSTest.Analyzers.Package.csproj | 1 - .../MSTest.SourceGeneration/MSTest.SourceGeneration.csproj | 2 -- 2 files changed, 3 deletions(-) diff --git a/src/Analyzers/MSTest.Analyzers.Package/MSTest.Analyzers.Package.csproj b/src/Analyzers/MSTest.Analyzers.Package/MSTest.Analyzers.Package.csproj index 0631e8b43c..9a8b279bdb 100644 --- a/src/Analyzers/MSTest.Analyzers.Package/MSTest.Analyzers.Package.csproj +++ b/src/Analyzers/MSTest.Analyzers.Package/MSTest.Analyzers.Package.csproj @@ -4,7 +4,6 @@ netstandard2.0 false true - true diff --git a/src/Analyzers/MSTest.SourceGeneration/MSTest.SourceGeneration.csproj b/src/Analyzers/MSTest.SourceGeneration/MSTest.SourceGeneration.csproj index af7c69027c..4f3d375201 100644 --- a/src/Analyzers/MSTest.SourceGeneration/MSTest.SourceGeneration.csproj +++ b/src/Analyzers/MSTest.SourceGeneration/MSTest.SourceGeneration.csproj @@ -3,8 +3,6 @@ netstandard2.0 - - true false NU5128 From f822bb9cfb379c5d49b6a138504bea8f0093ca7b Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Tue, 29 Jul 2025 22:51:25 +0200 Subject: [PATCH 322/541] Update public samples to 3.10 (#6222) --- samples/public/Directory.Build.props | 10 +++++----- samples/public/global.json | 2 +- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/samples/public/Directory.Build.props b/samples/public/Directory.Build.props index fe854da07b..83c8a8c552 100644 --- a/samples/public/Directory.Build.props +++ b/samples/public/Directory.Build.props @@ -1,12 +1,12 @@ - 9.0.0 + 9.4.0 17.14.2 - 3.9.2 - 1.0.0-alpha.25256.6 - 1.50.0 - 1.7.0 + 3.10.0 + 1.0.0-alpha.25379.8 + 1.54.0 + 1.8.0 17.13.0 false $(NoWarn);SA0001;EnableGenerateDocumentationFile diff --git a/samples/public/global.json b/samples/public/global.json index 0026bd52f7..ede0260933 100644 --- a/samples/public/global.json +++ b/samples/public/global.json @@ -1,5 +1,5 @@ { "msbuild-sdks": { - "MSTest.Sdk": "3.9.2" + "MSTest.Sdk": "3.10.0" } } From e847f76e9a014e151814e683b361e3fc66ee5ea9 Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Wed, 30 Jul 2025 05:07:38 +0000 Subject: [PATCH 323/541] [main] Update dependencies from devdiv/DevDiv/vs-code-coverage, dotnet/arcade (#6235) [main] Update dependencies from devdiv/DevDiv/vs-code-coverage, dotnet/arcade --- eng/Version.Details.xml | 16 ++++++++-------- eng/Versions.props | 4 ++-- global.json | 2 +- 3 files changed, 11 insertions(+), 11 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index be83519ca3..445ee4c993 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -1,21 +1,21 @@ - + https://github.com/dotnet/arcade - e2fed65f9c524d12c64876194ae4ce177b935bb3 + 8df06d38fb9183c3fdff5077b670eb35f0cb3f31 - + https://github.com/dotnet/arcade - e2fed65f9c524d12c64876194ae4ce177b935bb3 + 8df06d38fb9183c3fdff5077b670eb35f0cb3f31 - + https://github.com/dotnet/arcade - e2fed65f9c524d12c64876194ae4ce177b935bb3 + 8df06d38fb9183c3fdff5077b670eb35f0cb3f31 - + https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage - 4fa8f0c467e38db87fae04266d98e4288dad4697 + 23601926c69466349912ac82a09b791098af451c https://github.com/microsoft/testfx diff --git a/eng/Versions.props b/eng/Versions.props index e2f3be8483..531418cec2 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -7,8 +7,8 @@ preview - 10.0.0-beta.25374.4 - 18.0.0-preview.25378.1 + 10.0.0-beta.25379.3 + 18.0.0-preview.25379.1 3.10.0-preview.25378.9 1.8.0-preview.25378.9 diff --git a/global.json b/global.json index 90d31ae135..988d17a92a 100644 --- a/global.json +++ b/global.json @@ -33,7 +33,7 @@ "rollForward": "latestFeature" }, "msbuild-sdks": { - "Microsoft.DotNet.Arcade.Sdk": "10.0.0-beta.25374.4", + "Microsoft.DotNet.Arcade.Sdk": "10.0.0-beta.25379.3", "MSBuild.Sdk.Extras": "3.0.44" } } From 0616c05c9d5494ad570c09bd65dece2a41e6d31b Mon Sep 17 00:00:00 2001 From: dotnet bot Date: Tue, 29 Jul 2025 22:21:36 -0700 Subject: [PATCH 324/541] Localized file check-in by OneLocBuild Task: Build definition ID 1218: Build ID 2761068 --- .../MSTest.Analyzers/xlf/Resources.de.xlf | 34 +++++++++---------- .../MSTest.Analyzers/xlf/Resources.es.xlf | 34 +++++++++---------- .../MSTest.Analyzers/xlf/Resources.fr.xlf | 34 +++++++++---------- .../MSTest.Analyzers/xlf/Resources.it.xlf | 34 +++++++++---------- .../MSTest.Analyzers/xlf/Resources.ja.xlf | 34 +++++++++---------- .../MSTest.Analyzers/xlf/Resources.ko.xlf | 34 +++++++++---------- .../MSTest.Analyzers/xlf/Resources.pl.xlf | 34 +++++++++---------- .../MSTest.Analyzers/xlf/Resources.pt-BR.xlf | 34 +++++++++---------- .../MSTest.Analyzers/xlf/Resources.ru.xlf | 34 +++++++++---------- .../MSTest.Analyzers/xlf/Resources.tr.xlf | 34 +++++++++---------- 10 files changed, 170 insertions(+), 170 deletions(-) diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf index cda5a5f789..5ca054556d 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf @@ -465,32 +465,32 @@ The type declaring these methods should also respect the following rules: -The class shouldn't be 'static' -The class should be marked with '[TestClass]' (or a derived attribute) -the class should not be generic. - Methods marked with '[GlobalTestInitialize]' or '[GlobalTestCleanup]' should follow the following layout to be valid: --it can't be declared on a generic class --it should be 'public' --it should be 'static' --it should not be 'async void' --it should not be a special method (finalizer, operator...). --it should not be generic --it should take one parameter of type 'TestContext' --return type should be 'void', 'Task' or 'ValueTask' + Methoden, die mit „[GlobalTestInitialize]“ oder „[GlobalTestCleanup]“ gekennzeichnet sind, sollten dem folgenden Layout folgen, um gültig zu sein: +– kann nicht für eine generische Klasse deklariert werden +– muss „public“ sein +– muss „static“ sein +– darf nicht „async void“ sein +– darf keine spezielle Methode sein (Finalizer, Operator...). +– darf nicht „generic“ sein +– muss einen Parameter vom Typ „TestContext“ annehmen +– der Rückgabetyp muss „void“, „Task“ oder „ValueTask“ sein -The type declaring these methods should also respect the following rules: --The type should be a class --The class should be 'public' --The class shouldn't be 'static' --The class should be marked with '[TestClass]' (or a derived attribute) --the class should not be generic. +Der Typ, der diese Methoden deklariert, sollte auch die folgenden Regeln beachten: +– Der Typ sollte eine Klasse sein +– Die Klasse sollte „public“ sein +– Die Klasse darf nicht „static“ sein +– Die Klasse muss mit „[TestClass]“ (oder einem abgeleiteten Attribut) markiert werden +– die Klasse darf nicht generisch sein. Global test fixture method '{0}' signature is invalid - Global test fixture method '{0}' signature is invalid + Die Signatur der globalen Testfixierungsmethode „{0}“ ist ungültig GlobalTestInitialize and GlobalTestCleanup methods should have valid layout - GlobalTestInitialize and GlobalTestCleanup methods should have valid layout + Die Methoden „GlobalTestInitialize“ und „GlobalTestCleanup“ müssen ein gültiges Layout aufweisen diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf index 602c9c1dd8..7f56748641 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf @@ -464,32 +464,32 @@ The type declaring these methods should also respect the following rules: -The class shouldn't be 'static' -The class should be marked with '[TestClass]' (or a derived attribute) -the class should not be generic. - Methods marked with '[GlobalTestInitialize]' or '[GlobalTestCleanup]' should follow the following layout to be valid: --it can't be declared on a generic class --it should be 'public' --it should be 'static' --it should not be 'async void' --it should not be a special method (finalizer, operator...). --it should not be generic --it should take one parameter of type 'TestContext' --return type should be 'void', 'Task' or 'ValueTask' + Los métodos marcados con '[GlobalTestInitialize]' o '[GlobalTestCleanup]' deben seguir el siguiente diseño para ser válidos: +-no se puede declarar en una clase genérica +- debería ser 'público' +- debería estar 'estático' +-no debe ser 'async void' +-no debe ser un método especial (finalizador, operador...). +-no debe ser genérico +-debe tomar un parámetro de tipo 'TestContext' +- El tipo de valor devuelto debe ser 'void', 'Task' o 'ValueTask' -The type declaring these methods should also respect the following rules: --The type should be a class --The class should be 'public' --The class shouldn't be 'static' --The class should be marked with '[TestClass]' (or a derived attribute) --the class should not be generic. +El tipo que declara estos métodos también debe respetar las reglas siguientes: +-El tipo debe ser una clase +-La clase debe ser 'public' +-La clase no debe ser 'static' +-La clase debe marcarse con '[TestClass]' (o un atributo derivado) +-la clase no debe ser genérica. Global test fixture method '{0}' signature is invalid - Global test fixture method '{0}' signature is invalid + La firma del método del accesorio de pruebas global '{0}' no es válida GlobalTestInitialize and GlobalTestCleanup methods should have valid layout - GlobalTestInitialize and GlobalTestCleanup methods should have valid layout + Los métodos GlobalTestInitialize y GlobalTestCleanup deben tener un diseño válido diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf index 98163c1a21..d9296f52a6 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf @@ -464,32 +464,32 @@ The type declaring these methods should also respect the following rules: -The class shouldn't be 'static' -The class should be marked with '[TestClass]' (or a derived attribute) -the class should not be generic. - Methods marked with '[GlobalTestInitialize]' or '[GlobalTestCleanup]' should follow the following layout to be valid: --it can't be declared on a generic class --it should be 'public' --it should be 'static' --it should not be 'async void' --it should not be a special method (finalizer, operator...). --it should not be generic --it should take one parameter of type 'TestContext' --return type should be 'void', 'Task' or 'ValueTask' + Les méthodes marquées par « [GlobalTestInitialize] » ou « [GlobalTestCleanup] » doivent respecter le schéma suivant pour être valides : +- elle ne peut pas être déclarée dans une classe générique +– elle doit être « public » +– elle doit être « static » +– elle ne doit pas être « async void » +– il ne doit pas s’agir d’une méthode spéciale (finaliseur, opérateur...). +– elle ne doit pas être générique +– il doit prendre un paramètre de type « TestContext » +- le type de retour doit être « void », « Task » ou « ValueTask » -The type declaring these methods should also respect the following rules: --The type should be a class --The class should be 'public' --The class shouldn't be 'static' --The class should be marked with '[TestClass]' (or a derived attribute) --the class should not be generic. +Le type déclarant ces méthodes doit également respecter les règles suivantes : +- le type doit être une classe +- la classe doit être « public » +- la classe ne doit pas être « static » +- la classe doit être marquée par « [TestClass] » (ou un attribut dérivé) +- la classe ne doit pas être générique. Global test fixture method '{0}' signature is invalid - Global test fixture method '{0}' signature is invalid + La signature de la méthode « {0} » de la fixture de test globale est invalide GlobalTestInitialize and GlobalTestCleanup methods should have valid layout - GlobalTestInitialize and GlobalTestCleanup methods should have valid layout + Les méthodes GlobalTestInitialize et GlobalTestCleanup doivent avoir une structure valide diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf index 5f583a4779..9f587e84bb 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf @@ -464,32 +464,32 @@ The type declaring these methods should also respect the following rules: -The class shouldn't be 'static' -The class should be marked with '[TestClass]' (or a derived attribute) -the class should not be generic. - Methods marked with '[GlobalTestInitialize]' or '[GlobalTestCleanup]' should follow the following layout to be valid: --it can't be declared on a generic class --it should be 'public' --it should be 'static' --it should not be 'async void' --it should not be a special method (finalizer, operator...). --it should not be generic --it should take one parameter of type 'TestContext' --return type should be 'void', 'Task' or 'ValueTask' + I metodi contrassegnati con ‘[GlobalTestInitialize]’ o ‘[GlobalTestCleanup]’ devono seguire il layout seguente per essere validi: +- Non può essere dichiarato in una classe generica +- Deve essere 'public' +- Deve essere 'static' +- Non deve essere 'async void' +- Non deve essere un metodo speciale (finalizzatore, operatore...). +- Non deve essere generico +- Deve accettare un parametro di tipo 'TestContext' +- Il tipo restituito deve essere 'void', 'Task' o 'ValueTask' -The type declaring these methods should also respect the following rules: --The type should be a class --The class should be 'public' --The class shouldn't be 'static' --The class should be marked with '[TestClass]' (or a derived attribute) --the class should not be generic. +Anche il tipo che dichiara questi metodi deve rispettare le regole seguenti: +- Il tipo deve essere una classe +- La classe deve essere 'public' +- La classe non deve essere 'static' +- La classe deve essere contrassegnata con '[TestClass]' (o un attributo derivato) +- La classe non deve essere generica. Global test fixture method '{0}' signature is invalid - Global test fixture method '{0}' signature is invalid + La firma del metodo di fixture di test globale '{0}' non è valida GlobalTestInitialize and GlobalTestCleanup methods should have valid layout - GlobalTestInitialize and GlobalTestCleanup methods should have valid layout + I metodi GlobalTestInitialize e GlobalTestCleanup devono avere un layout valido diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf index 36c0e5e429..f3572dc873 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf @@ -464,32 +464,32 @@ The type declaring these methods should also respect the following rules: -The class shouldn't be 'static' -The class should be marked with '[TestClass]' (or a derived attribute) -the class should not be generic. - Methods marked with '[GlobalTestInitialize]' or '[GlobalTestCleanup]' should follow the following layout to be valid: --it can't be declared on a generic class --it should be 'public' --it should be 'static' --it should not be 'async void' --it should not be a special method (finalizer, operator...). --it should not be generic --it should take one parameter of type 'TestContext' --return type should be 'void', 'Task' or 'ValueTask' + '[GlobalTestInitialize]' または '[GlobalTestCleanup]' でマークされたメソッドを有効にするには、次のレイアウトに従う必要があります: +- ジェネリック クラスで宣言することはできません +- 'public' である必要があります +- 'static' である必要があります +- 'async void' にすることはできません +- 特殊なメソッド (ファイナライザー、演算子...) にすることはできません。 +- ジェネリックにすることはできません +- 'TestContext' 型のパラメーターを 1 つ受け取る必要があります +- 戻り値の型が 'void'、'Task'、または 'ValueTask' である必要があります -The type declaring these methods should also respect the following rules: --The type should be a class --The class should be 'public' --The class shouldn't be 'static' --The class should be marked with '[TestClass]' (or a derived attribute) --the class should not be generic. +これらのメソッドを宣言する型も、次の規則に従う必要があります: +- 型はクラスである必要があります +-クラスは 'public' である必要があります +- クラスを 'static' にすることはできません +- クラスは '[TestClass]' (または派生属性) でマークする必要があります +- クラスをジェネリックにすることはできません。 Global test fixture method '{0}' signature is invalid - Global test fixture method '{0}' signature is invalid + グローバル テスト フィクスチャ メソッド '{0}' シグネチャが無効です GlobalTestInitialize and GlobalTestCleanup methods should have valid layout - GlobalTestInitialize and GlobalTestCleanup methods should have valid layout + GlobalTestInitialize および GlobalTestCleanup メソッドには有効なレイアウトが必要です diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf index e7a46259d4..e088c8f658 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf @@ -464,32 +464,32 @@ The type declaring these methods should also respect the following rules: -The class shouldn't be 'static' -The class should be marked with '[TestClass]' (or a derived attribute) -the class should not be generic. - Methods marked with '[GlobalTestInitialize]' or '[GlobalTestCleanup]' should follow the following layout to be valid: --it can't be declared on a generic class --it should be 'public' --it should be 'static' --it should not be 'async void' --it should not be a special method (finalizer, operator...). --it should not be generic --it should take one parameter of type 'TestContext' --return type should be 'void', 'Task' or 'ValueTask' + '[GlobalTestInitialize]' 또는 '[GlobalTestCleanup]'으로 표시된 메서드는 다음 레이아웃을 따라야 유효합니다. +- 제네릭 클래스에서 선언할 수 없습니다. +- 'public'이어야 합니다. +- 'static'이어야 합니다. +- 'async void'가 아니어야 합니다. +- 특수 메서드(종료자, 연산자...)가 아니어야 합니다. +- 제네릭이 아니어야 합니다. +- 'TestContext' 형식의 매개 변수를 하나 사용해야 합니다. +- 반환 형식은 'void', 'Task' 또는 'ValueTask'여야 합니다. -The type declaring these methods should also respect the following rules: --The type should be a class --The class should be 'public' --The class shouldn't be 'static' --The class should be marked with '[TestClass]' (or a derived attribute) --the class should not be generic. +이러한 메서드를 선언하는 형식은 다음 규칙도 준수해야 합니다. +- 형식은 클래스여야 합니다. +-클래스는 'public'이어야 합니다. +- 클래스는 'static'이 되어서는 안 됩니다. +- 클래스는 '[TestClass]'(또는 파생 특성)로 표시되어야 합니다. +- 클래스는 제네릭이 아니어야 합니다. Global test fixture method '{0}' signature is invalid - Global test fixture method '{0}' signature is invalid + 전역 테스트 fixture 메서드 '{0}' 시그니처가 잘못되었습니다. GlobalTestInitialize and GlobalTestCleanup methods should have valid layout - GlobalTestInitialize and GlobalTestCleanup methods should have valid layout + GlobalTestInitialize 및 GlobalTestCleanup 메서드에는 유효한 레이아웃이 있어야 합니다. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf index 793e4af278..de09b7c71d 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf @@ -464,32 +464,32 @@ The type declaring these methods should also respect the following rules: -The class shouldn't be 'static' -The class should be marked with '[TestClass]' (or a derived attribute) -the class should not be generic. - Methods marked with '[GlobalTestInitialize]' or '[GlobalTestCleanup]' should follow the following layout to be valid: --it can't be declared on a generic class --it should be 'public' --it should be 'static' --it should not be 'async void' --it should not be a special method (finalizer, operator...). --it should not be generic --it should take one parameter of type 'TestContext' --return type should be 'void', 'Task' or 'ValueTask' + Metody oznaczone znakiem „[GlobalTestInitialize]” lub „[GlobalTestCleanup]” powinny być zgodne z następującym układem, aby były prawidłowe: +— nie może być zadeklarowana w klasie ogólnej +— powinna być typu „public” +— powinna mieć wartość „static” +— nie powinna to być wartość „async void” +— nie powinna to być metoda specjalna (finalizator, operator...). +— nie powinna być ogólna +— powinna przyjmować jeden parametr typu „TestContext” +— zwracany typ powinien mieć wartość „void”, „Taks” lub „ValueTask” -The type declaring these methods should also respect the following rules: --The type should be a class --The class should be 'public' --The class shouldn't be 'static' --The class should be marked with '[TestClass]' (or a derived attribute) --the class should not be generic. +Typ deklarujący te metody powinien również przestrzegać następujących reguł: +— typ powinien być klasą +— klasa powinna być „publiczna” +— klasa nie powinna mieć wartości „static” +— klasa powinna być oznaczona „[TestClass]” (lub atrybutem pochodnym) +— klasa nie powinna być ogólna. Global test fixture method '{0}' signature is invalid - Global test fixture method '{0}' signature is invalid + Podpis globalnej metody warunków początkowych testu „{0}” jest nieprawidłowy GlobalTestInitialize and GlobalTestCleanup methods should have valid layout - GlobalTestInitialize and GlobalTestCleanup methods should have valid layout + Metody GlobalTestInitialize i GlobalTestCleanup powinny mieć prawidłowy układ diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf index 17c17381a8..eea0cceb35 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf @@ -464,32 +464,32 @@ The type declaring these methods should also respect the following rules: -The class shouldn't be 'static' -The class should be marked with '[TestClass]' (or a derived attribute) -the class should not be generic. - Methods marked with '[GlobalTestInitialize]' or '[GlobalTestCleanup]' should follow the following layout to be valid: --it can't be declared on a generic class --it should be 'public' --it should be 'static' --it should not be 'async void' --it should not be a special method (finalizer, operator...). --it should not be generic --it should take one parameter of type 'TestContext' --return type should be 'void', 'Task' or 'ValueTask' + Os métodos marcados com "[GlobalTestInitialize]" ou "[GlobalTestCleanup]" devem seguir o seguinte layout para serem válidos: +-não podem ser declarados em uma classe genérica +-devem ser "públicos" +-devem ser "estáticos" +-não devem ser "nulos assíncronos" +-não devem ser um método especial (finalizador, operador...). +-não devem ser genéricos +-devem usar um parâmetro do tipo “TestContext” +-o tipo de retorno deve ser “nulo”, “Tarefa” ou “ValueTask” -The type declaring these methods should also respect the following rules: --The type should be a class --The class should be 'public' --The class shouldn't be 'static' --The class should be marked with '[TestClass]' (or a derived attribute) --the class should not be generic. +O tipo que declara esses métodos também deve respeitar as seguintes regras: +-O tipo deve ser uma classe +-A classe deve ser "público" +-A classe não deve ser “estático” +-A classe deve ser marcada com “[TestClass]” (ou um atributo derivado) +-a classe não deve ser genérica. Global test fixture method '{0}' signature is invalid - Global test fixture method '{0}' signature is invalid + A assinatura do método de acessório de teste global "{0}" é inválida GlobalTestInitialize and GlobalTestCleanup methods should have valid layout - GlobalTestInitialize and GlobalTestCleanup methods should have valid layout + Os métodos GlobalTestInitialize e GlobalTestCleanup devem ter um layout válido diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf index 00e73f807d..ef026326fb 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf @@ -470,32 +470,32 @@ The type declaring these methods should also respect the following rules: -The class shouldn't be 'static' -The class should be marked with '[TestClass]' (or a derived attribute) -the class should not be generic. - Methods marked with '[GlobalTestInitialize]' or '[GlobalTestCleanup]' should follow the following layout to be valid: --it can't be declared on a generic class --it should be 'public' --it should be 'static' --it should not be 'async void' --it should not be a special method (finalizer, operator...). --it should not be generic --it should take one parameter of type 'TestContext' --return type should be 'void', 'Task' or 'ValueTask' + Чтобы метод, помеченный "[GlobalTestInitialize]" или "[GlobalTestCleanup]", был допустимым, он должен соответствовать следующей структуре: +– не может быть объявлен для универсального класса ("generic") +– должен быть общедоступным ("public") +– должен быть статическим ("static") +– не должен быть асинхронным и не возвращающим значения ("async void") +– не должен быть специальным (метод завершения, оператор…). +– не должен быть общим ("generic") +– должен принимать один параметр типа "TestContext" +– должен иметь тип возвращаемого значения "void", "Task" или "ValueTask" -The type declaring these methods should also respect the following rules: --The type should be a class --The class should be 'public' --The class shouldn't be 'static' --The class should be marked with '[TestClass]' (or a derived attribute) --the class should not be generic. +Тип, объявляющий такие методы, также должен соответствовать следующим правилам: +– должен быть классом +– класс должен быть общедоступным ("public") +– не должен быть статическим ("static") +– должен быть помечен как "[TestClass]" (или производный атрибут) +– не должен быть универсальным ("generic"). Global test fixture method '{0}' signature is invalid - Global test fixture method '{0}' signature is invalid + Подпись метода глобального средства тестирования "{0}" недопустима GlobalTestInitialize and GlobalTestCleanup methods should have valid layout - GlobalTestInitialize and GlobalTestCleanup methods should have valid layout + Методы GlobalTestInitialize и GlobalTestCleanup должны использовать допустимый макет diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf index c1cccecf1c..4f8789a5ae 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf @@ -464,32 +464,32 @@ The type declaring these methods should also respect the following rules: -The class shouldn't be 'static' -The class should be marked with '[TestClass]' (or a derived attribute) -the class should not be generic. - Methods marked with '[GlobalTestInitialize]' or '[GlobalTestCleanup]' should follow the following layout to be valid: --it can't be declared on a generic class --it should be 'public' --it should be 'static' --it should not be 'async void' --it should not be a special method (finalizer, operator...). --it should not be generic --it should take one parameter of type 'TestContext' --return type should be 'void', 'Task' or 'ValueTask' + ‘[GlobalTestInitialize]’ veya ‘[GlobalTestCleanup]’ ile işaretlenmiş yöntemlerin geçerli olabilmesi için şu düzeni izlemesi gerekir: +-genel bir sınıfta tanımlanamaz +-'public' olmalıdır +-'static' olmalıdır +-'async void' olmamalıdır +-özel bir metot (sonlandırıcı, işleç...) olmamalıdır. +- genel olmamalıdır +- 'TestContext' türünden bir parametre almalıdır +- dönüş türü 'void', 'Task' veya 'ValueTask' olmalıdır -The type declaring these methods should also respect the following rules: --The type should be a class --The class should be 'public' --The class shouldn't be 'static' --The class should be marked with '[TestClass]' (or a derived attribute) --the class should not be generic. +Bu metotları bildiren türün ayrıca aşağıdaki kurallara uyması gerekir: +-Tür bir sınıf olmalıdır +-Sınıf ‘public’ olmalıdır +-Sınıf 'static' olmamalıdır +-Sınıf '[TestClass]' (veya türetilmiş bir öznitelik) ile işaretlenmelidir +-sınıf genel olmamalıdır. Global test fixture method '{0}' signature is invalid - Global test fixture method '{0}' signature is invalid + Global test düzeni yöntemi ‘{0}’ imzası geçersiz GlobalTestInitialize and GlobalTestCleanup methods should have valid layout - GlobalTestInitialize and GlobalTestCleanup methods should have valid layout + GlobalTestInitialize ve GlobalTestCleanup yöntemleri geçerli bir düzene sahip olmalıdır From 231dddf3c55674ea5b2ba4ae39a39165f9e73b23 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Wed, 30 Jul 2025 07:44:00 +0200 Subject: [PATCH 325/541] Allow to opt-out of Microsoft.NET.Test.Sdk (#6233) --- src/Package/MSTest.Sdk/Sdk/Runner/ClassicEngine.targets | 1 + 1 file changed, 1 insertion(+) diff --git a/src/Package/MSTest.Sdk/Sdk/Runner/ClassicEngine.targets b/src/Package/MSTest.Sdk/Sdk/Runner/ClassicEngine.targets index 0ba5bac6c4..7f0480c71f 100644 --- a/src/Package/MSTest.Sdk/Sdk/Runner/ClassicEngine.targets +++ b/src/Package/MSTest.Sdk/Sdk/Runner/ClassicEngine.targets @@ -48,6 +48,7 @@ - 3.10.0-preview.25378.9 - 1.8.0-preview.25378.9 + 3.11.0-preview.25379.21 + 1.9.0-preview.25379.21 From b7df22b733a41ada756fd714b033c90e80a80b90 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Wed, 30 Jul 2025 09:22:22 +0200 Subject: [PATCH 327/541] Improve assertions for DotnetMuxerResult.ExitCode (#6240) --- .../AssemblyResolutionTests.cs | 2 +- .../SdkTests.cs | 20 +++++++++---------- .../Helpers/AcceptanceAssert.cs | 6 ++++++ .../MSBuildTests.GenerateEntryPoint.cs | 2 +- .../RetryFailedTestsTests.cs | 2 +- 5 files changed, 19 insertions(+), 13 deletions(-) diff --git a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/AssemblyResolutionTests.cs b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/AssemblyResolutionTests.cs index 1cad3bfabc..a96f5ddca5 100644 --- a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/AssemblyResolutionTests.cs +++ b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/AssemblyResolutionTests.cs @@ -69,7 +69,7 @@ public async Task InitializeAsync() { VSSolution solution = CreateTestAsset(); DotnetMuxerResult result = await DotnetCli.RunAsync($"build -nodeReuse:false {solution.SolutionFile} -c Release", AcceptanceFixture.NuGetGlobalPackagesFolder.Path); - Assert.AreEqual(0, result.ExitCode); + result.AssertExitCodeIs(0); TestHost = TestHost.LocateFrom(solution.Projects.Skip(1).Single().FolderPath, TestProjectName, TargetFramework); MainDllFolder = MoveMainDllToDifferentTempDirectory(); diff --git a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/SdkTests.cs b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/SdkTests.cs index 4d6885fd96..cefe929e52 100644 --- a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/SdkTests.cs +++ b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/SdkTests.cs @@ -65,7 +65,7 @@ public async Task RunTests_With_VSTest(string multiTfm, BuildConfiguration build .PatchCodeWithReplace("$ExtraProperties$", "true")); DotnetMuxerResult compilationResult = await DotnetCli.RunAsync($"test -c {buildConfiguration} {testAsset.TargetAssetPath}", AcceptanceFixture.NuGetGlobalPackagesFolder.Path, workingDirectory: testAsset.TargetAssetPath); - Assert.AreEqual(0, compilationResult.ExitCode); + compilationResult.AssertExitCodeIs(0); compilationResult.AssertOutputMatchesRegex(@"Passed! - Failed: 0, Passed: 1, Skipped: 0, Total: 1, Duration: .* [m]?s - MSTestSdk.dll \(net9\.0\)"); #if !SKIP_INTERMEDIATE_TARGET_FRAMEWORKS @@ -92,7 +92,7 @@ public async Task RunTests_With_MSTestRunner_DotnetTest(string multiTfm, BuildCo .PatchCodeWithReplace("$ExtraProperties$", string.Empty)); DotnetMuxerResult compilationResult = await DotnetCli.RunAsync($"test -c {buildConfiguration} {testAsset.TargetAssetPath}", AcceptanceFixture.NuGetGlobalPackagesFolder.Path, workingDirectory: testAsset.TargetAssetPath); - Assert.AreEqual(0, compilationResult.ExitCode); + compilationResult.AssertExitCodeIs(0); compilationResult.AssertOutputMatchesRegex(@"Tests succeeded: .* \[net9\.0|x64\]"); #if !SKIP_INTERMEDIATE_TARGET_FRAMEWORKS @@ -119,7 +119,7 @@ public async Task RunTests_With_MSTestRunner_Standalone(string multiTfm, BuildCo .PatchCodeWithReplace("$ExtraProperties$", string.Empty)); DotnetMuxerResult compilationResult = await DotnetCli.RunAsync($"build -c {buildConfiguration} {testAsset.TargetAssetPath}", AcceptanceFixture.NuGetGlobalPackagesFolder.Path); - Assert.AreEqual(0, compilationResult.ExitCode); + compilationResult.AssertExitCodeIs(0); foreach (string tfm in multiTfm.Split(";")) { var testHost = TestHost.LocateFrom(testAsset.TargetAssetPath, AssetName, tfm, buildConfiguration: buildConfiguration); @@ -140,7 +140,7 @@ public async Task RunTests_With_CentralPackageManagement_Standalone(string multi .PatchCodeWithReplace("$ExtraProperties$", string.Empty)); DotnetMuxerResult compilationResult = await DotnetCli.RunAsync($"build -c {buildConfiguration} {testAsset.TargetAssetPath}", AcceptanceFixture.NuGetGlobalPackagesFolder.Path); - Assert.AreEqual(0, compilationResult.ExitCode); + compilationResult.AssertExitCodeIs(0); foreach (string tfm in multiTfm.Split(";")) { var testHost = TestHost.LocateFrom(testAsset.TargetAssetPath, AssetName, tfm, buildConfiguration: buildConfiguration); @@ -195,7 +195,7 @@ public async Task RunTests_With_MSTestRunner_Standalone_Selectively_Enabled_Exte .PatchCodeWithReplace("$ExtraProperties$", msbuildExtensionEnableFragment)); DotnetMuxerResult compilationResult = await DotnetCli.RunAsync($"build -c {buildConfiguration} {testAsset.TargetAssetPath}", AcceptanceFixture.NuGetGlobalPackagesFolder.Path); - Assert.AreEqual(0, compilationResult.ExitCode); + compilationResult.AssertExitCodeIs(0); foreach (string tfm in multiTfm.Split(";")) { var testHost = TestHost.LocateFrom(testAsset.TargetAssetPath, AssetName, tfm, buildConfiguration: buildConfiguration); @@ -219,7 +219,7 @@ public async Task RunTests_With_MSTestRunner_Standalone_EnableAll_Extensions(str .PatchCodeWithReplace("$ExtraProperties$", "AllMicrosoft")); DotnetMuxerResult compilationResult = await DotnetCli.RunAsync($"build -c {buildConfiguration} {testAsset.TargetAssetPath}", AcceptanceFixture.NuGetGlobalPackagesFolder.Path); - Assert.AreEqual(0, compilationResult.ExitCode); + compilationResult.AssertExitCodeIs(0); foreach (string tfm in multiTfm.Split(";")) { var testHost = TestHost.LocateFrom(testAsset.TargetAssetPath, AssetName, tfm, buildConfiguration: buildConfiguration); @@ -249,7 +249,7 @@ public async Task RunTests_With_MSTestRunner_Standalone_Enable_Default_Extension .PatchCodeWithReplace("$ExtraProperties$", enableDefaultExtensions ? string.Empty : "None")); DotnetMuxerResult compilationResult = await DotnetCli.RunAsync($"build -c {buildConfiguration} {testAsset.TargetAssetPath}", AcceptanceFixture.NuGetGlobalPackagesFolder.Path); - Assert.AreEqual(0, compilationResult.ExitCode); + compilationResult.AssertExitCodeIs(0); foreach (string tfm in multiTfm.Split(";")) { var testHost = TestHost.LocateFrom(testAsset.TargetAssetPath, AssetName, tfm, buildConfiguration: buildConfiguration); @@ -277,7 +277,7 @@ public async Task Invalid_TestingProfile_Name_Should_Fail(string multiTfm, Build .PatchCodeWithReplace("$ExtraProperties$", "WrongName")); DotnetMuxerResult compilationResult = await DotnetCli.RunAsync($"build -c {buildConfiguration} {testAsset.TargetAssetPath}", AcceptanceFixture.NuGetGlobalPackagesFolder.Path, failIfReturnValueIsNotZero: false); - Assert.AreEqual(1, compilationResult.ExitCode); + compilationResult.AssertExitCodeIs(1); compilationResult.AssertOutputContains("Invalid value for property TestingExtensionsProfile. Valid values are 'Default', 'AllMicrosoft' and 'None'."); } @@ -406,7 +406,7 @@ public async Task EnableAspireProperty_WhenUsingVSTest_AllowsToRunAspireTests() workingDirectory: AssetFixture.AspireProjectPath, warnAsError: false, suppressPreviewDotNetMessage: false); - Assert.AreEqual(0, dotnetTestResult.ExitCode); + dotnetTestResult.AssertExitCodeIs(0); // Ensure output contains the right platform banner dotnetTestResult.AssertOutputContains("VSTest version"); dotnetTestResult.AssertOutputContains("Passed! - Failed: 0, Passed: 1, Skipped: 0, Total: 1"); @@ -424,7 +424,7 @@ public async Task SettingIsTestApplicationToFalseReducesAddedExtensionsAndMakesP DotnetMuxerResult compilationResult = await DotnetCli.RunAsync($"test {testAsset.TargetAssetPath}", AcceptanceFixture.NuGetGlobalPackagesFolder.Path, workingDirectory: testAsset.TargetAssetPath); - Assert.AreEqual(0, compilationResult.ExitCode); + compilationResult.AssertExitCodeIs(0); SL.Build binLog = SL.Serialization.Read(compilationResult.BinlogPath!); SL.Task cscTask = binLog.FindChildrenRecursive(task => task.Name == "Csc").Single(); diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/Helpers/AcceptanceAssert.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/Helpers/AcceptanceAssert.cs index 0669e768d1..8dd818cefa 100644 --- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/Helpers/AcceptanceAssert.cs +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/Helpers/AcceptanceAssert.cs @@ -87,6 +87,12 @@ public static void AssertOutputDoesNotMatchRegex(this TestHostResult testHostRes public static void AssertOutputContains(this TestHostResult testHostResult, string value, [CallerMemberName] string? callerMemberName = null, [CallerFilePath] string? callerFilePath = null, [CallerLineNumber] int callerLineNumber = 0) => Assert.Contains(value, testHostResult.StandardOutput, GenerateFailedAssertionMessage(testHostResult, callerMemberName: callerMemberName, callerFilePath: callerFilePath, callerLineNumber: callerLineNumber), StringComparison.Ordinal); + public static void AssertExitCodeIs(this DotnetMuxerResult testHostResult, int exitCode, [CallerMemberName] string? callerMemberName = null, [CallerFilePath] string? callerFilePath = null, [CallerLineNumber] int callerLineNumber = 0) + => Assert.AreEqual(exitCode, testHostResult.ExitCode, GenerateFailedAssertionMessage(testHostResult, callerMemberName: callerMemberName, callerFilePath: callerFilePath, callerLineNumber: callerLineNumber)); + + public static void AssertExitCodeIsNot(this DotnetMuxerResult testHostResult, int exitCode, [CallerMemberName] string? callerMemberName = null, [CallerFilePath] string? callerFilePath = null, [CallerLineNumber] int callerLineNumber = 0) + => Assert.AreNotEqual(exitCode, testHostResult.ExitCode, GenerateFailedAssertionMessage(testHostResult, callerMemberName: callerMemberName, callerFilePath: callerFilePath, callerLineNumber: callerLineNumber)); + public static void AssertOutputContains(this DotnetMuxerResult dotnetMuxerResult, string value, [CallerMemberName] string? callerMemberName = null, [CallerFilePath] string? callerFilePath = null, [CallerLineNumber] int callerLineNumber = 0) => Assert.Contains(value, dotnetMuxerResult.StandardOutput, GenerateFailedAssertionMessage(dotnetMuxerResult, callerMemberName: callerMemberName, callerFilePath: callerFilePath, callerLineNumber: callerLineNumber), StringComparison.Ordinal); diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/MSBuildTests.GenerateEntryPoint.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/MSBuildTests.GenerateEntryPoint.cs index ff2364b1fb..2f7e11173c 100644 --- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/MSBuildTests.GenerateEntryPoint.cs +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/MSBuildTests.GenerateEntryPoint.cs @@ -26,7 +26,7 @@ public async Task When_GenerateTestingPlatformEntryPoint_IsFalse_NoEntryPointInj Assert.AreEqual("Target \"_GenerateTestingPlatformEntryPoint\" skipped, due to false condition; ( '$(GenerateTestingPlatformEntryPoint)' == 'true' ) was evaluated as ( 'False' == 'true' ).", ((SL.Message)generateTestingPlatformEntryPoint.Children[0]).Text); SL.Target includeGenerateTestingPlatformEntryPointIntoCompilation = binLog.FindChildrenRecursive().Single(t => t.Name == "_IncludeGenerateTestingPlatformEntryPointIntoCompilation"); Assert.IsEmpty(includeGenerateTestingPlatformEntryPointIntoCompilation.Children); - Assert.AreNotEqual(0, compilationResult.ExitCode); + compilationResult.AssertExitCodeIsNot(0); } [DynamicData(nameof(GetBuildMatrixTfmBuildVerbConfiguration), typeof(AcceptanceTestBase))] diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/RetryFailedTestsTests.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/RetryFailedTestsTests.cs index b58782582a..cb4a6221fd 100644 --- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/RetryFailedTestsTests.cs +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/RetryFailedTestsTests.cs @@ -197,7 +197,7 @@ public async Task RetryFailedTests_PassingFromFirstTime_UsingOldDotnetTest_MoveF AcceptanceFixture.NuGetGlobalPackagesFolder.Path, workingDirectory: AssetFixture.TargetAssetPath); - Assert.AreEqual(ExitCodes.Success, result.ExitCode); + result.AssertExitCodeIs(ExitCodes.Success); // File names are on the form: RetryFailedTests_tfm_architecture.log string[] logFilesFromInvokeTestingPlatformTask = Directory.GetFiles(resultDirectory, "RetryFailedTests_*_*.log"); From c361e3dead28416c03b83c5e1b5166bea4fe6af2 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Wed, 30 Jul 2025 09:22:51 +0200 Subject: [PATCH 328/541] Remove PublicAPI files for analyzers project (#6230) --- .editorconfig | 3 - .globalconfig | 10 + .../MSTest.Analyzers/PublicAPI.Shipped.txt | 189 ------------------ .../MSTest.Analyzers/PublicAPI.Unshipped.txt | 1 - 4 files changed, 10 insertions(+), 193 deletions(-) create mode 100644 .globalconfig delete mode 100644 src/Analyzers/MSTest.Analyzers/PublicAPI.Shipped.txt delete mode 100644 src/Analyzers/MSTest.Analyzers/PublicAPI.Unshipped.txt diff --git a/.editorconfig b/.editorconfig index 76c9203e22..2fa5b7363d 100644 --- a/.editorconfig +++ b/.editorconfig @@ -465,9 +465,6 @@ dotnet_diagnostic.CA2245.severity = warning # CA2248: Provide correct enum argument to Enum.HasFlag dotnet_diagnostic.CA2248.severity = warning -# RS0016: Only enable if API files are present -dotnet_public_api_analyzer.require_api_files = true - # RS0041: Do not use 'Obsolete' attribute dotnet_diagnostic.RS0041.severity = none diff --git a/.globalconfig b/.globalconfig new file mode 100644 index 0000000000..cd088247ab --- /dev/null +++ b/.globalconfig @@ -0,0 +1,10 @@ +is_global = true + +# RS0016: Only enable if API files are present +# This should NOT be in .editorconfig. +# .editorconfig is a per-file (syntax tree) concept. +# The public API analyzer will attempt to get the options for the **first tree**. +# The first tree could be a file outside of our repo (e.g, a source-only package like Polyfill) +# By having this option here in .globalconfig, we ensure it's picked up correctly regardless of what the first tree is. +# See comments in https://github.com/microsoft/testfx/pull/6230 for clarification. +dotnet_public_api_analyzer.require_api_files = true diff --git a/src/Analyzers/MSTest.Analyzers/PublicAPI.Shipped.txt b/src/Analyzers/MSTest.Analyzers/PublicAPI.Shipped.txt deleted file mode 100644 index 0e6cde55f8..0000000000 --- a/src/Analyzers/MSTest.Analyzers/PublicAPI.Shipped.txt +++ /dev/null @@ -1,189 +0,0 @@ -#nullable enable -MSTest.Analyzers.AssemblyCleanupShouldBeValidAnalyzer -MSTest.Analyzers.AssemblyCleanupShouldBeValidAnalyzer.AssemblyCleanupShouldBeValidAnalyzer() -> void -MSTest.Analyzers.AssemblyInitializeShouldBeValidAnalyzer -MSTest.Analyzers.AssemblyInitializeShouldBeValidAnalyzer.AssemblyInitializeShouldBeValidAnalyzer() -> void -MSTest.Analyzers.AssertionArgsShouldAvoidConditionalAccessAnalyzer -MSTest.Analyzers.AssertionArgsShouldAvoidConditionalAccessAnalyzer.AssertionArgsShouldAvoidConditionalAccessAnalyzer() -> void -MSTest.Analyzers.AssertionArgsShouldBePassedInCorrectOrderAnalyzer -MSTest.Analyzers.AssertionArgsShouldBePassedInCorrectOrderAnalyzer.AssertionArgsShouldBePassedInCorrectOrderAnalyzer() -> void -MSTest.Analyzers.AvoidAssertAreSameWithValueTypesAnalyzer -MSTest.Analyzers.AvoidAssertAreSameWithValueTypesAnalyzer.AvoidAssertAreSameWithValueTypesAnalyzer() -> void -MSTest.Analyzers.AvoidExpectedExceptionAttributeAnalyzer -MSTest.Analyzers.AvoidExpectedExceptionAttributeAnalyzer.AvoidExpectedExceptionAttributeAnalyzer() -> void -MSTest.Analyzers.AvoidUsingAssertsInAsyncVoidContextAnalyzer -MSTest.Analyzers.AvoidUsingAssertsInAsyncVoidContextAnalyzer.AvoidUsingAssertsInAsyncVoidContextAnalyzer() -> void -MSTest.Analyzers.ClassCleanupShouldBeValidAnalyzer -MSTest.Analyzers.ClassCleanupShouldBeValidAnalyzer.ClassCleanupShouldBeValidAnalyzer() -> void -MSTest.Analyzers.ClassInitializeShouldBeValidAnalyzer -MSTest.Analyzers.ClassInitializeShouldBeValidAnalyzer.ClassInitializeShouldBeValidAnalyzer() -> void -MSTest.Analyzers.DataRowShouldBeValidAnalyzer -MSTest.Analyzers.DataRowShouldBeValidAnalyzer.DataRowShouldBeValidAnalyzer() -> void -MSTest.Analyzers.DoNotNegateBooleanAssertionAnalyzer -MSTest.Analyzers.DoNotNegateBooleanAssertionAnalyzer.DoNotNegateBooleanAssertionAnalyzer() -> void -MSTest.Analyzers.DoNotStoreStaticTestContextAnalyzer -MSTest.Analyzers.DoNotStoreStaticTestContextAnalyzer.DoNotStoreStaticTestContextAnalyzer() -> void -MSTest.Analyzers.DoNotUseShadowingAnalyzer -MSTest.Analyzers.DoNotUseShadowingAnalyzer.DoNotUseShadowingAnalyzer() -> void -MSTest.Analyzers.DoNotUseSystemDescriptionAttributeAnalyzer -MSTest.Analyzers.DoNotUseSystemDescriptionAttributeAnalyzer.DoNotUseSystemDescriptionAttributeAnalyzer() -> void -MSTest.Analyzers.DuplicateDataRowAnalyzer -MSTest.Analyzers.DuplicateDataRowAnalyzer.DuplicateDataRowAnalyzer() -> void -MSTest.Analyzers.DynamicDataShouldBeValidAnalyzer -MSTest.Analyzers.DynamicDataShouldBeValidAnalyzer.DynamicDataShouldBeValidAnalyzer() -> void -MSTest.Analyzers.FlowTestContextCancellationTokenAnalyzer -MSTest.Analyzers.FlowTestContextCancellationTokenAnalyzer.FlowTestContextCancellationTokenAnalyzer() -> void -MSTest.Analyzers.GlobalTestFixtureShouldBeValidAnalyzer -MSTest.Analyzers.GlobalTestFixtureShouldBeValidAnalyzer.GlobalTestFixtureShouldBeValidAnalyzer() -> void -MSTest.Analyzers.NonNullableReferenceNotInitializedSuppressor -MSTest.Analyzers.NonNullableReferenceNotInitializedSuppressor.NonNullableReferenceNotInitializedSuppressor() -> void -MSTest.Analyzers.PreferAssertFailOverAlwaysFalseConditionsAnalyzer -MSTest.Analyzers.PreferAssertFailOverAlwaysFalseConditionsAnalyzer.PreferAssertFailOverAlwaysFalseConditionsAnalyzer() -> void -MSTest.Analyzers.PreferConstructorOverTestInitializeAnalyzer -MSTest.Analyzers.PreferConstructorOverTestInitializeAnalyzer.PreferConstructorOverTestInitializeAnalyzer() -> void -MSTest.Analyzers.PreferDisposeOverTestCleanupAnalyzer -MSTest.Analyzers.PreferDisposeOverTestCleanupAnalyzer.PreferDisposeOverTestCleanupAnalyzer() -> void -MSTest.Analyzers.PreferTestCleanupOverDisposeAnalyzer -MSTest.Analyzers.PreferTestCleanupOverDisposeAnalyzer.PreferTestCleanupOverDisposeAnalyzer() -> void -MSTest.Analyzers.PreferTestInitializeOverConstructorAnalyzer -MSTest.Analyzers.PreferTestInitializeOverConstructorAnalyzer.PreferTestInitializeOverConstructorAnalyzer() -> void -MSTest.Analyzers.PreferTestMethodOverDataTestMethodAnalyzer -MSTest.Analyzers.PreferTestMethodOverDataTestMethodAnalyzer.PreferTestMethodOverDataTestMethodAnalyzer() -> void -MSTest.Analyzers.PublicMethodShouldBeTestMethodAnalyzer -MSTest.Analyzers.PublicMethodShouldBeTestMethodAnalyzer.PublicMethodShouldBeTestMethodAnalyzer() -> void -MSTest.Analyzers.PublicTypeShouldBeTestClassAnalyzer -MSTest.Analyzers.PublicTypeShouldBeTestClassAnalyzer.PublicTypeShouldBeTestClassAnalyzer() -> void -MSTest.Analyzers.ReviewAlwaysTrueAssertConditionAnalyzer -MSTest.Analyzers.ReviewAlwaysTrueAssertConditionAnalyzer.ReviewAlwaysTrueAssertConditionAnalyzer() -> void -MSTest.Analyzers.TestClassShouldBeValidAnalyzer -MSTest.Analyzers.TestClassShouldBeValidAnalyzer.TestClassShouldBeValidAnalyzer() -> void -MSTest.Analyzers.TestClassShouldHaveTestMethodAnalyzer -MSTest.Analyzers.TestClassShouldHaveTestMethodAnalyzer.TestClassShouldHaveTestMethodAnalyzer() -> void -MSTest.Analyzers.TestCleanupShouldBeValidAnalyzer -MSTest.Analyzers.TestCleanupShouldBeValidAnalyzer.TestCleanupShouldBeValidAnalyzer() -> void -MSTest.Analyzers.TestContextPropertyUsageAnalyzer -MSTest.Analyzers.TestContextPropertyUsageAnalyzer.TestContextPropertyUsageAnalyzer() -> void -MSTest.Analyzers.TestContextShouldBeValidAnalyzer -MSTest.Analyzers.TestContextShouldBeValidAnalyzer.TestContextShouldBeValidAnalyzer() -> void -MSTest.Analyzers.TestInitializeShouldBeValidAnalyzer -MSTest.Analyzers.TestInitializeShouldBeValidAnalyzer.TestInitializeShouldBeValidAnalyzer() -> void -MSTest.Analyzers.TestMethodShouldBeValidAnalyzer -MSTest.Analyzers.TestMethodShouldBeValidAnalyzer.TestMethodShouldBeValidAnalyzer() -> void -MSTest.Analyzers.TestMethodShouldNotBeIgnoredAnalyzer -MSTest.Analyzers.TestMethodShouldNotBeIgnoredAnalyzer.TestMethodShouldNotBeIgnoredAnalyzer() -> void -MSTest.Analyzers.TypeContainingTestMethodShouldBeATestClassAnalyzer -MSTest.Analyzers.TypeContainingTestMethodShouldBeATestClassAnalyzer.TypeContainingTestMethodShouldBeATestClassAnalyzer() -> void -MSTest.Analyzers.UnusedParameterSuppressor -MSTest.Analyzers.UnusedParameterSuppressor.UnusedParameterSuppressor() -> void -MSTest.Analyzers.UseAsyncSuffixTestFixtureMethodSuppressor -MSTest.Analyzers.UseAsyncSuffixTestFixtureMethodSuppressor.UseAsyncSuffixTestFixtureMethodSuppressor() -> void -MSTest.Analyzers.UseAsyncSuffixTestMethodSuppressor -MSTest.Analyzers.UseAsyncSuffixTestMethodSuppressor.UseAsyncSuffixTestMethodSuppressor() -> void -MSTest.Analyzers.UseAttributeOnTestMethodAnalyzer -MSTest.Analyzers.UseAttributeOnTestMethodAnalyzer.UseAttributeOnTestMethodAnalyzer() -> void -MSTest.Analyzers.UseClassCleanupBehaviorEndOfClassAnalyzer -MSTest.Analyzers.UseClassCleanupBehaviorEndOfClassAnalyzer.UseClassCleanupBehaviorEndOfClassAnalyzer() -> void -MSTest.Analyzers.UseConditionBaseWithTestClassAnalyzer -MSTest.Analyzers.UseConditionBaseWithTestClassAnalyzer.UseConditionBaseWithTestClassAnalyzer() -> void -MSTest.Analyzers.UseCooperativeCancellationForTimeoutAnalyzer -MSTest.Analyzers.UseCooperativeCancellationForTimeoutAnalyzer.UseCooperativeCancellationForTimeoutAnalyzer() -> void -MSTest.Analyzers.UseDeploymentItemWithTestMethodOrTestClassAnalyzer -MSTest.Analyzers.UseDeploymentItemWithTestMethodOrTestClassAnalyzer.UseDeploymentItemWithTestMethodOrTestClassAnalyzer() -> void -MSTest.Analyzers.UseParallelizeAttributeAnalyzer -MSTest.Analyzers.UseParallelizeAttributeAnalyzer.UseParallelizeAttributeAnalyzer() -> void -MSTest.Analyzers.UseRetryWithTestMethodAnalyzer -MSTest.Analyzers.UseRetryWithTestMethodAnalyzer.UseRetryWithTestMethodAnalyzer() -> void -override MSTest.Analyzers.AssemblyCleanupShouldBeValidAnalyzer.Initialize(Microsoft.CodeAnalysis.Diagnostics.AnalysisContext! context) -> void -override MSTest.Analyzers.AssemblyCleanupShouldBeValidAnalyzer.SupportedDiagnostics.get -> System.Collections.Immutable.ImmutableArray -override MSTest.Analyzers.AssemblyInitializeShouldBeValidAnalyzer.Initialize(Microsoft.CodeAnalysis.Diagnostics.AnalysisContext! context) -> void -override MSTest.Analyzers.AssemblyInitializeShouldBeValidAnalyzer.SupportedDiagnostics.get -> System.Collections.Immutable.ImmutableArray -override MSTest.Analyzers.AssertionArgsShouldAvoidConditionalAccessAnalyzer.Initialize(Microsoft.CodeAnalysis.Diagnostics.AnalysisContext! context) -> void -override MSTest.Analyzers.AssertionArgsShouldAvoidConditionalAccessAnalyzer.SupportedDiagnostics.get -> System.Collections.Immutable.ImmutableArray -override MSTest.Analyzers.AssertionArgsShouldBePassedInCorrectOrderAnalyzer.Initialize(Microsoft.CodeAnalysis.Diagnostics.AnalysisContext! context) -> void -override MSTest.Analyzers.AssertionArgsShouldBePassedInCorrectOrderAnalyzer.SupportedDiagnostics.get -> System.Collections.Immutable.ImmutableArray -override MSTest.Analyzers.AvoidAssertAreSameWithValueTypesAnalyzer.Initialize(Microsoft.CodeAnalysis.Diagnostics.AnalysisContext! context) -> void -override MSTest.Analyzers.AvoidAssertAreSameWithValueTypesAnalyzer.SupportedDiagnostics.get -> System.Collections.Immutable.ImmutableArray -override MSTest.Analyzers.AvoidExpectedExceptionAttributeAnalyzer.Initialize(Microsoft.CodeAnalysis.Diagnostics.AnalysisContext! context) -> void -override MSTest.Analyzers.AvoidExpectedExceptionAttributeAnalyzer.SupportedDiagnostics.get -> System.Collections.Immutable.ImmutableArray -override MSTest.Analyzers.AvoidUsingAssertsInAsyncVoidContextAnalyzer.Initialize(Microsoft.CodeAnalysis.Diagnostics.AnalysisContext! context) -> void -override MSTest.Analyzers.AvoidUsingAssertsInAsyncVoidContextAnalyzer.SupportedDiagnostics.get -> System.Collections.Immutable.ImmutableArray -override MSTest.Analyzers.ClassCleanupShouldBeValidAnalyzer.Initialize(Microsoft.CodeAnalysis.Diagnostics.AnalysisContext! context) -> void -override MSTest.Analyzers.ClassCleanupShouldBeValidAnalyzer.SupportedDiagnostics.get -> System.Collections.Immutable.ImmutableArray -override MSTest.Analyzers.ClassInitializeShouldBeValidAnalyzer.Initialize(Microsoft.CodeAnalysis.Diagnostics.AnalysisContext! context) -> void -override MSTest.Analyzers.ClassInitializeShouldBeValidAnalyzer.SupportedDiagnostics.get -> System.Collections.Immutable.ImmutableArray -override MSTest.Analyzers.DataRowShouldBeValidAnalyzer.Initialize(Microsoft.CodeAnalysis.Diagnostics.AnalysisContext! context) -> void -override MSTest.Analyzers.DataRowShouldBeValidAnalyzer.SupportedDiagnostics.get -> System.Collections.Immutable.ImmutableArray -override MSTest.Analyzers.DoNotNegateBooleanAssertionAnalyzer.Initialize(Microsoft.CodeAnalysis.Diagnostics.AnalysisContext! context) -> void -override MSTest.Analyzers.DoNotNegateBooleanAssertionAnalyzer.SupportedDiagnostics.get -> System.Collections.Immutable.ImmutableArray -override MSTest.Analyzers.DoNotStoreStaticTestContextAnalyzer.Initialize(Microsoft.CodeAnalysis.Diagnostics.AnalysisContext! context) -> void -override MSTest.Analyzers.DoNotStoreStaticTestContextAnalyzer.SupportedDiagnostics.get -> System.Collections.Immutable.ImmutableArray -override MSTest.Analyzers.DoNotUseShadowingAnalyzer.Initialize(Microsoft.CodeAnalysis.Diagnostics.AnalysisContext! context) -> void -override MSTest.Analyzers.DoNotUseShadowingAnalyzer.SupportedDiagnostics.get -> System.Collections.Immutable.ImmutableArray -override MSTest.Analyzers.DoNotUseSystemDescriptionAttributeAnalyzer.Initialize(Microsoft.CodeAnalysis.Diagnostics.AnalysisContext! context) -> void -override MSTest.Analyzers.DoNotUseSystemDescriptionAttributeAnalyzer.SupportedDiagnostics.get -> System.Collections.Immutable.ImmutableArray -override MSTest.Analyzers.DuplicateDataRowAnalyzer.Initialize(Microsoft.CodeAnalysis.Diagnostics.AnalysisContext! context) -> void -override MSTest.Analyzers.DuplicateDataRowAnalyzer.SupportedDiagnostics.get -> System.Collections.Immutable.ImmutableArray -override MSTest.Analyzers.DynamicDataShouldBeValidAnalyzer.Initialize(Microsoft.CodeAnalysis.Diagnostics.AnalysisContext! context) -> void -override MSTest.Analyzers.DynamicDataShouldBeValidAnalyzer.SupportedDiagnostics.get -> System.Collections.Immutable.ImmutableArray -override MSTest.Analyzers.FlowTestContextCancellationTokenAnalyzer.Initialize(Microsoft.CodeAnalysis.Diagnostics.AnalysisContext! context) -> void -override MSTest.Analyzers.FlowTestContextCancellationTokenAnalyzer.SupportedDiagnostics.get -> System.Collections.Immutable.ImmutableArray -override MSTest.Analyzers.GlobalTestFixtureShouldBeValidAnalyzer.Initialize(Microsoft.CodeAnalysis.Diagnostics.AnalysisContext! context) -> void -override MSTest.Analyzers.GlobalTestFixtureShouldBeValidAnalyzer.SupportedDiagnostics.get -> System.Collections.Immutable.ImmutableArray -override MSTest.Analyzers.NonNullableReferenceNotInitializedSuppressor.ReportSuppressions(Microsoft.CodeAnalysis.Diagnostics.SuppressionAnalysisContext context) -> void -override MSTest.Analyzers.NonNullableReferenceNotInitializedSuppressor.SupportedSuppressions.get -> System.Collections.Immutable.ImmutableArray -override MSTest.Analyzers.PreferAssertFailOverAlwaysFalseConditionsAnalyzer.Initialize(Microsoft.CodeAnalysis.Diagnostics.AnalysisContext! context) -> void -override MSTest.Analyzers.PreferAssertFailOverAlwaysFalseConditionsAnalyzer.SupportedDiagnostics.get -> System.Collections.Immutable.ImmutableArray -override MSTest.Analyzers.PreferConstructorOverTestInitializeAnalyzer.Initialize(Microsoft.CodeAnalysis.Diagnostics.AnalysisContext! context) -> void -override MSTest.Analyzers.PreferConstructorOverTestInitializeAnalyzer.SupportedDiagnostics.get -> System.Collections.Immutable.ImmutableArray -override MSTest.Analyzers.PreferDisposeOverTestCleanupAnalyzer.Initialize(Microsoft.CodeAnalysis.Diagnostics.AnalysisContext! context) -> void -override MSTest.Analyzers.PreferDisposeOverTestCleanupAnalyzer.SupportedDiagnostics.get -> System.Collections.Immutable.ImmutableArray -override MSTest.Analyzers.PreferTestCleanupOverDisposeAnalyzer.Initialize(Microsoft.CodeAnalysis.Diagnostics.AnalysisContext! context) -> void -override MSTest.Analyzers.PreferTestCleanupOverDisposeAnalyzer.SupportedDiagnostics.get -> System.Collections.Immutable.ImmutableArray -override MSTest.Analyzers.PreferTestInitializeOverConstructorAnalyzer.Initialize(Microsoft.CodeAnalysis.Diagnostics.AnalysisContext! context) -> void -override MSTest.Analyzers.PreferTestInitializeOverConstructorAnalyzer.SupportedDiagnostics.get -> System.Collections.Immutable.ImmutableArray -override MSTest.Analyzers.PreferTestMethodOverDataTestMethodAnalyzer.Initialize(Microsoft.CodeAnalysis.Diagnostics.AnalysisContext! context) -> void -override MSTest.Analyzers.PreferTestMethodOverDataTestMethodAnalyzer.SupportedDiagnostics.get -> System.Collections.Immutable.ImmutableArray -override MSTest.Analyzers.PublicMethodShouldBeTestMethodAnalyzer.Initialize(Microsoft.CodeAnalysis.Diagnostics.AnalysisContext! context) -> void -override MSTest.Analyzers.PublicMethodShouldBeTestMethodAnalyzer.SupportedDiagnostics.get -> System.Collections.Immutable.ImmutableArray -override MSTest.Analyzers.PublicTypeShouldBeTestClassAnalyzer.Initialize(Microsoft.CodeAnalysis.Diagnostics.AnalysisContext! context) -> void -override MSTest.Analyzers.PublicTypeShouldBeTestClassAnalyzer.SupportedDiagnostics.get -> System.Collections.Immutable.ImmutableArray -override MSTest.Analyzers.ReviewAlwaysTrueAssertConditionAnalyzer.Initialize(Microsoft.CodeAnalysis.Diagnostics.AnalysisContext! context) -> void -override MSTest.Analyzers.ReviewAlwaysTrueAssertConditionAnalyzer.SupportedDiagnostics.get -> System.Collections.Immutable.ImmutableArray -override MSTest.Analyzers.TestClassShouldBeValidAnalyzer.Initialize(Microsoft.CodeAnalysis.Diagnostics.AnalysisContext! context) -> void -override MSTest.Analyzers.TestClassShouldBeValidAnalyzer.SupportedDiagnostics.get -> System.Collections.Immutable.ImmutableArray -override MSTest.Analyzers.TestClassShouldHaveTestMethodAnalyzer.Initialize(Microsoft.CodeAnalysis.Diagnostics.AnalysisContext! context) -> void -override MSTest.Analyzers.TestClassShouldHaveTestMethodAnalyzer.SupportedDiagnostics.get -> System.Collections.Immutable.ImmutableArray -override MSTest.Analyzers.TestCleanupShouldBeValidAnalyzer.Initialize(Microsoft.CodeAnalysis.Diagnostics.AnalysisContext! context) -> void -override MSTest.Analyzers.TestCleanupShouldBeValidAnalyzer.SupportedDiagnostics.get -> System.Collections.Immutable.ImmutableArray -override MSTest.Analyzers.TestContextPropertyUsageAnalyzer.Initialize(Microsoft.CodeAnalysis.Diagnostics.AnalysisContext! context) -> void -override MSTest.Analyzers.TestContextPropertyUsageAnalyzer.SupportedDiagnostics.get -> System.Collections.Immutable.ImmutableArray -override MSTest.Analyzers.TestContextShouldBeValidAnalyzer.Initialize(Microsoft.CodeAnalysis.Diagnostics.AnalysisContext! context) -> void -override MSTest.Analyzers.TestContextShouldBeValidAnalyzer.SupportedDiagnostics.get -> System.Collections.Immutable.ImmutableArray -override MSTest.Analyzers.TestInitializeShouldBeValidAnalyzer.Initialize(Microsoft.CodeAnalysis.Diagnostics.AnalysisContext! context) -> void -override MSTest.Analyzers.TestInitializeShouldBeValidAnalyzer.SupportedDiagnostics.get -> System.Collections.Immutable.ImmutableArray -override MSTest.Analyzers.TestMethodShouldBeValidAnalyzer.Initialize(Microsoft.CodeAnalysis.Diagnostics.AnalysisContext! context) -> void -override MSTest.Analyzers.TestMethodShouldBeValidAnalyzer.SupportedDiagnostics.get -> System.Collections.Immutable.ImmutableArray -override MSTest.Analyzers.TestMethodShouldNotBeIgnoredAnalyzer.Initialize(Microsoft.CodeAnalysis.Diagnostics.AnalysisContext! context) -> void -override MSTest.Analyzers.TestMethodShouldNotBeIgnoredAnalyzer.SupportedDiagnostics.get -> System.Collections.Immutable.ImmutableArray -override MSTest.Analyzers.TypeContainingTestMethodShouldBeATestClassAnalyzer.Initialize(Microsoft.CodeAnalysis.Diagnostics.AnalysisContext! context) -> void -override MSTest.Analyzers.TypeContainingTestMethodShouldBeATestClassAnalyzer.SupportedDiagnostics.get -> System.Collections.Immutable.ImmutableArray -override MSTest.Analyzers.UnusedParameterSuppressor.ReportSuppressions(Microsoft.CodeAnalysis.Diagnostics.SuppressionAnalysisContext context) -> void -override MSTest.Analyzers.UnusedParameterSuppressor.SupportedSuppressions.get -> System.Collections.Immutable.ImmutableArray -override MSTest.Analyzers.UseAsyncSuffixTestFixtureMethodSuppressor.ReportSuppressions(Microsoft.CodeAnalysis.Diagnostics.SuppressionAnalysisContext context) -> void -override MSTest.Analyzers.UseAsyncSuffixTestFixtureMethodSuppressor.SupportedSuppressions.get -> System.Collections.Immutable.ImmutableArray -override MSTest.Analyzers.UseAsyncSuffixTestMethodSuppressor.ReportSuppressions(Microsoft.CodeAnalysis.Diagnostics.SuppressionAnalysisContext context) -> void -override MSTest.Analyzers.UseAsyncSuffixTestMethodSuppressor.SupportedSuppressions.get -> System.Collections.Immutable.ImmutableArray -override MSTest.Analyzers.UseAttributeOnTestMethodAnalyzer.Initialize(Microsoft.CodeAnalysis.Diagnostics.AnalysisContext! context) -> void -override MSTest.Analyzers.UseAttributeOnTestMethodAnalyzer.SupportedDiagnostics.get -> System.Collections.Immutable.ImmutableArray -override MSTest.Analyzers.UseClassCleanupBehaviorEndOfClassAnalyzer.Initialize(Microsoft.CodeAnalysis.Diagnostics.AnalysisContext! context) -> void -override MSTest.Analyzers.UseClassCleanupBehaviorEndOfClassAnalyzer.SupportedDiagnostics.get -> System.Collections.Immutable.ImmutableArray -override MSTest.Analyzers.UseConditionBaseWithTestClassAnalyzer.Initialize(Microsoft.CodeAnalysis.Diagnostics.AnalysisContext! context) -> void -override MSTest.Analyzers.UseConditionBaseWithTestClassAnalyzer.SupportedDiagnostics.get -> System.Collections.Immutable.ImmutableArray -override MSTest.Analyzers.UseCooperativeCancellationForTimeoutAnalyzer.Initialize(Microsoft.CodeAnalysis.Diagnostics.AnalysisContext! context) -> void -override MSTest.Analyzers.UseCooperativeCancellationForTimeoutAnalyzer.SupportedDiagnostics.get -> System.Collections.Immutable.ImmutableArray -override MSTest.Analyzers.UseDeploymentItemWithTestMethodOrTestClassAnalyzer.Initialize(Microsoft.CodeAnalysis.Diagnostics.AnalysisContext! context) -> void -override MSTest.Analyzers.UseDeploymentItemWithTestMethodOrTestClassAnalyzer.SupportedDiagnostics.get -> System.Collections.Immutable.ImmutableArray -override MSTest.Analyzers.UseParallelizeAttributeAnalyzer.Initialize(Microsoft.CodeAnalysis.Diagnostics.AnalysisContext! context) -> void -override MSTest.Analyzers.UseParallelizeAttributeAnalyzer.SupportedDiagnostics.get -> System.Collections.Immutable.ImmutableArray -override MSTest.Analyzers.UseRetryWithTestMethodAnalyzer.Initialize(Microsoft.CodeAnalysis.Diagnostics.AnalysisContext! context) -> void -override MSTest.Analyzers.UseRetryWithTestMethodAnalyzer.SupportedDiagnostics.get -> System.Collections.Immutable.ImmutableArray diff --git a/src/Analyzers/MSTest.Analyzers/PublicAPI.Unshipped.txt b/src/Analyzers/MSTest.Analyzers/PublicAPI.Unshipped.txt deleted file mode 100644 index 7dc5c58110..0000000000 --- a/src/Analyzers/MSTest.Analyzers/PublicAPI.Unshipped.txt +++ /dev/null @@ -1 +0,0 @@ -#nullable enable From d879f669ec5a48dddc72641b9fbcc3710a7c4061 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Wed, 30 Jul 2025 09:25:44 +0200 Subject: [PATCH 329/541] Remove timeout in test infra (#6241) --- .../NativeAotTests.cs | 1 - .../SdkTests.cs | 3 +-- .../CommandLine.cs | 23 ++----------------- .../DotnetCli.cs | 13 +++++------ .../DotnetMuxer.cs | 10 ++++---- .../TestHost.cs | 6 ++--- 6 files changed, 15 insertions(+), 41 deletions(-) diff --git a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/NativeAotTests.cs b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/NativeAotTests.cs index b404a0039e..785fe47106 100644 --- a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/NativeAotTests.cs +++ b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/NativeAotTests.cs @@ -112,7 +112,6 @@ await DotnetCli.RunAsync( DotnetMuxerResult compilationResult = await DotnetCli.RunAsync( $"publish -m:1 -nodeReuse:false {generator.TargetAssetPath} -r {RID}", AcceptanceFixture.NuGetGlobalPackagesFolder.Path, - timeoutInSeconds: 90, retryCount: 0); compilationResult.AssertOutputContains("Generating native code"); diff --git a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/SdkTests.cs b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/SdkTests.cs index cefe929e52..2a2ceeb800 100644 --- a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/SdkTests.cs +++ b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/SdkTests.cs @@ -311,8 +311,7 @@ public async Task NativeAot_Smoke_Test_Windows() $"publish -r {RID} -f net9.0 {testAsset.TargetAssetPath}", AcceptanceFixture.NuGetGlobalPackagesFolder.Path, // We prefer to use the outer retry mechanism as we need some extra checks - retryCount: 0, - timeoutInSeconds: 180); + retryCount: 0); compilationResult.AssertOutputContains("Generating native code"); compilationResult.AssertOutputDoesNotContain("warning"); diff --git a/test/Utilities/Microsoft.Testing.TestInfrastructure/CommandLine.cs b/test/Utilities/Microsoft.Testing.TestInfrastructure/CommandLine.cs index d2e33f7df4..52059a16b5 100644 --- a/test/Utilities/Microsoft.Testing.TestInfrastructure/CommandLine.cs +++ b/test/Utilities/Microsoft.Testing.TestInfrastructure/CommandLine.cs @@ -71,8 +71,7 @@ public async Task RunAsyncAndReturnExitCodeAsync( string commandLine, IDictionary? environmentVariables = null, string? workingDirectory = null, - bool cleanDefaultEnvironmentVariableIfCustomAreProvided = false, - int timeoutInSeconds = 10000) + bool cleanDefaultEnvironmentVariableIfCustomAreProvided = false) { await s_maxOutstandingCommands_semaphore.WaitAsync(); try @@ -91,25 +90,7 @@ public async Task RunAsyncAndReturnExitCodeAsync( }; _process = ProcessFactory.Start(startInfo, cleanDefaultEnvironmentVariableIfCustomAreProvided); - Task exited = _process.WaitForExitAsync(); - int seconds = timeoutInSeconds; - CancellationTokenSource stopTheTimer = new(); - var timedOut = Task.Delay(TimeSpan.FromSeconds(seconds), stopTheTimer.Token); - if (await Task.WhenAny(exited, timedOut) == exited) - { - await stopTheTimer.CancelAsync(); - return await exited; - } - else - { - _process.Kill(); - throw new TimeoutException( - $""" - Timeout after {seconds}s on command line: '{commandLine}' - STD: {StandardOutput} - ERR: {ErrorOutput} - """); - } + return await _process.WaitForExitAsync(); } finally { diff --git a/test/Utilities/Microsoft.Testing.TestInfrastructure/DotnetCli.cs b/test/Utilities/Microsoft.Testing.TestInfrastructure/DotnetCli.cs index 61ec18e1b8..a7fc3a6784 100644 --- a/test/Utilities/Microsoft.Testing.TestInfrastructure/DotnetCli.cs +++ b/test/Utilities/Microsoft.Testing.TestInfrastructure/DotnetCli.cs @@ -54,7 +54,6 @@ public static async Task RunAsync( Dictionary? environmentVariables = null, bool failIfReturnValueIsNotZero = true, bool disableTelemetry = true, - int timeoutInSeconds = 10000, int retryCount = 5, bool disableCodeCoverage = true, bool warnAsError = true, @@ -110,7 +109,7 @@ public static async Task RunAsync( if (DoNotRetry) { - return await CallTheMuxerAsync(args, environmentVariables, workingDirectory, timeoutInSeconds, failIfReturnValueIsNotZero, callerMemberName); + return await CallTheMuxerAsync(args, environmentVariables, workingDirectory, failIfReturnValueIsNotZero, callerMemberName); } else { @@ -118,7 +117,7 @@ public static async Task RunAsync( return await Policy .Handle() .WaitAndRetryAsync(delay) - .ExecuteAsync(async () => await CallTheMuxerAsync(args, environmentVariables, workingDirectory, timeoutInSeconds, failIfReturnValueIsNotZero, callerMemberName)); + .ExecuteAsync(async () => await CallTheMuxerAsync(args, environmentVariables, workingDirectory, failIfReturnValueIsNotZero, callerMemberName)); } } finally @@ -131,13 +130,13 @@ private static bool IsDotNetTestWithExeOrDll(string args) => args.StartsWith("test ", StringComparison.Ordinal) && (args.Contains(".dll") || args.Contains(".exe")); // Workaround NuGet issue https://github.com/NuGet/Home/issues/14064 - private static async Task CallTheMuxerAsync(string args, Dictionary environmentVariables, string? workingDirectory, int timeoutInSeconds, bool failIfReturnValueIsNotZero, string binlogBaseFileName) + private static async Task CallTheMuxerAsync(string args, Dictionary environmentVariables, string? workingDirectory, bool failIfReturnValueIsNotZero, string binlogBaseFileName) => await Policy .Handle(ex => ex.Message.Contains("MSB4236")) .WaitAndRetryAsync(retryCount: 3, sleepDurationProvider: static _ => TimeSpan.FromSeconds(2)) - .ExecuteAsync(async () => await CallTheMuxerCoreAsync(args, environmentVariables, workingDirectory, timeoutInSeconds, failIfReturnValueIsNotZero, binlogBaseFileName)); + .ExecuteAsync(async () => await CallTheMuxerCoreAsync(args, environmentVariables, workingDirectory, failIfReturnValueIsNotZero, binlogBaseFileName)); - private static async Task CallTheMuxerCoreAsync(string args, Dictionary environmentVariables, string? workingDirectory, int timeoutInSeconds, bool failIfReturnValueIsNotZero, string binlogBaseFileName) + private static async Task CallTheMuxerCoreAsync(string args, Dictionary environmentVariables, string? workingDirectory, bool failIfReturnValueIsNotZero, string binlogBaseFileName) { if (args.StartsWith("dotnet ", StringComparison.OrdinalIgnoreCase)) { @@ -161,7 +160,7 @@ private static async Task CallTheMuxerCoreAsync(string args, } using DotnetMuxer dotnet = new(environmentVariables); - int exitCode = await dotnet.ExecuteAsync(args, workingDirectory, timeoutInSeconds); + int exitCode = await dotnet.ExecuteAsync(args, workingDirectory); if (dotnet.StandardError.Contains("Invalid runtimeconfig.json")) { diff --git a/test/Utilities/Microsoft.Testing.TestInfrastructure/DotnetMuxer.cs b/test/Utilities/Microsoft.Testing.TestInfrastructure/DotnetMuxer.cs index c799142b28..d25c5b96e8 100644 --- a/test/Utilities/Microsoft.Testing.TestInfrastructure/DotnetMuxer.cs +++ b/test/Utilities/Microsoft.Testing.TestInfrastructure/DotnetMuxer.cs @@ -92,20 +92,18 @@ protected virtual void Dispose(bool disposing) _isDisposed = true; } - public async Task ExecuteAsync(string arguments, string? workingDirectory = null, int timeoutInSeconds = 10000) - => await ExecuteAsync(arguments, workingDirectory, _environmentVariables, timeoutInSeconds); + public async Task ExecuteAsync(string arguments, string? workingDirectory = null) + => await ExecuteAsync(arguments, workingDirectory, _environmentVariables); public async Task ExecuteAsync( string arguments, string? workingDirectory, - IDictionary environmentVariables, - int timeoutInSeconds = 10000) + IDictionary environmentVariables) => await _commandLine.RunAsyncAndReturnExitCodeAsync( $"{_dotnet} {arguments}", environmentVariables, workingDirectory: workingDirectory, - cleanDefaultEnvironmentVariableIfCustomAreProvided: true, - timeoutInSeconds: timeoutInSeconds); + cleanDefaultEnvironmentVariableIfCustomAreProvided: true); private static IDictionary MergeEnvironmentVariables( IDictionary environmentVariables1, diff --git a/test/Utilities/Microsoft.Testing.TestInfrastructure/TestHost.cs b/test/Utilities/Microsoft.Testing.TestInfrastructure/TestHost.cs index 4187c76c72..a490fab4f1 100644 --- a/test/Utilities/Microsoft.Testing.TestInfrastructure/TestHost.cs +++ b/test/Utilities/Microsoft.Testing.TestInfrastructure/TestHost.cs @@ -40,8 +40,7 @@ public static int MaxOutstandingExecutions public async Task ExecuteAsync( string? command = null, Dictionary? environmentVariables = null, - bool disableTelemetry = true, - int timeoutSeconds = 10000) + bool disableTelemetry = true) { await s_maxOutstandingExecutions_semaphore.WaitAsync(); try @@ -93,8 +92,7 @@ public async Task ExecuteAsync( $"{FullName} --no-ansi --no-progress {finalArguments}", environmentVariables: environmentVariables, workingDirectory: null, - cleanDefaultEnvironmentVariableIfCustomAreProvided: true, - timeoutInSeconds: timeoutSeconds); + cleanDefaultEnvironmentVariableIfCustomAreProvided: true); string fullCommand = command is not null ? $"{FullName} {command}" : FullName; return new TestHostResult(fullCommand, exitCode, commandLine.StandardOutput, commandLine.StandardOutputLines, commandLine.ErrorOutput, commandLine.ErrorOutputLines); }); From 2be942bf41995960231f8ffb0e75a0f5d517f9f3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Wed, 30 Jul 2025 12:23:07 +0200 Subject: [PATCH 330/541] Integration tests are using MSTest (#6234) --- .../MSTest.IntegrationTests/ClsTests.cs | 2 + .../DiscoverInternalsTests.cs | 4 + .../Extensions/VerifyE2E.cs | 19 +- .../FSharpTestProjectTests.cs | 2 + .../MSTest.IntegrationTests.csproj | 17 +- .../NoNamespaceTests.cs | 17 +- .../MSTest.IntegrationTests/OutputTests.cs | 42 +- .../DataExtensibilityTests.cs | 10 +- .../Parameterized tests/DataRowTests.cs | 15 + .../Parameterized tests/DataSourceTests.cs | 6 +- .../Parameterized tests/DynamicDataTests.cs | 6 +- .../MSTest.IntegrationTests/Program.cs | 4 +- .../TestCategoriesFromTestDataRowTests.cs | 15 +- .../TestId.DefaultStrategy.cs | 42 +- .../TestId.DisplayNameStrategy.cs | 28 +- .../TestId.FullyQualifiedStrategy.cs | 42 +- .../TestId.LegacyStrategy.cs | 27 +- .../Utilities/CLITestBase.discovery.cs | 10 +- .../AssertExtensibilityTests.cs | 2 + .../DeploymentTests.cs | 40 +- .../DesktopCSharpCLITests.cs | 9 + .../FixturesTests.cs | 11 + ...testConsoleWrapper.IntegrationTests.csproj | 18 +- .../ParallelExecutionTests.cs | 8 +- .../DataExtensibilityTests.cs | 5 + .../Parameterized tests/DataRowTests.cs | 12 + .../Parameterized tests/DataSourceTests.cs | 7 +- .../Parameterized tests/DynamicDataTests.cs | 2 + .../Program.cs | 4 +- .../SuiteLifeCycleTests.cs | 869 ++++++++++-------- .../TestProjectFSharpTests.cs | 2 + .../TimeoutTests.cs | 14 +- .../Automation.CLI/Automation.CLI.csproj | 6 +- .../Automation.CLI/CLITestBase.common.cs | 12 +- .../Automation.CLI/CLITestBase.e2e.cs | 50 +- 35 files changed, 801 insertions(+), 578 deletions(-) diff --git a/test/IntegrationTests/MSTest.IntegrationTests/ClsTests.cs b/test/IntegrationTests/MSTest.IntegrationTests/ClsTests.cs index bd821151c9..295cf445c3 100644 --- a/test/IntegrationTests/MSTest.IntegrationTests/ClsTests.cs +++ b/test/IntegrationTests/MSTest.IntegrationTests/ClsTests.cs @@ -5,12 +5,14 @@ namespace MSTest.IntegrationTests; +[TestClass] public class ClsTests : CLITestBase { private const string TestAssetName = "ClsTestProject"; // This test in itself is not so important. What matters is that the asset gets build. If we regress and start having // the [DataRow] attribute no longer CLS compliant, the build will raise a warning in VS (and the build will fail in CI). + [TestMethod] public async Task TestsAreRun() { // Arrange diff --git a/test/IntegrationTests/MSTest.IntegrationTests/DiscoverInternalsTests.cs b/test/IntegrationTests/MSTest.IntegrationTests/DiscoverInternalsTests.cs index 2f3c14c430..742bc2db03 100644 --- a/test/IntegrationTests/MSTest.IntegrationTests/DiscoverInternalsTests.cs +++ b/test/IntegrationTests/MSTest.IntegrationTests/DiscoverInternalsTests.cs @@ -5,10 +5,12 @@ namespace MSTest.IntegrationTests; +[TestClass] public class DiscoverInternalsTests : CLITestBase { private const string TestAsset = "DiscoverInternalsProject"; + [TestMethod] public async Task InternalTestClassesAreDiscoveredWhenTheDiscoverInternalsAttributeIsPresent() { // Arrange @@ -25,6 +27,7 @@ public async Task InternalTestClassesAreDiscoveredWhenTheDiscoverInternalsAttrib "NestedInternalClass_TestMethod1"); } + [TestMethod] public void AnInternalTestClassDerivedFromAPublicAbstractGenericBaseClassForAnInternalTypeIsDiscovered() { // Arrange @@ -39,6 +42,7 @@ public void AnInternalTestClassDerivedFromAPublicAbstractGenericBaseClassForAnIn "EqualityIsCaseInsensitive"); } + [TestMethod] public async Task AnInternalTypeCanBeUsedInADynamicDataTestMethod() { string assemblyPath = Path.IsPathRooted(TestAsset) ? TestAsset : GetAssetFullPath(TestAsset); diff --git a/test/IntegrationTests/MSTest.IntegrationTests/Extensions/VerifyE2E.cs b/test/IntegrationTests/MSTest.IntegrationTests/Extensions/VerifyE2E.cs index 741071face..e646ddf142 100644 --- a/test/IntegrationTests/MSTest.IntegrationTests/Extensions/VerifyE2E.cs +++ b/test/IntegrationTests/MSTest.IntegrationTests/Extensions/VerifyE2E.cs @@ -1,8 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. -using FluentAssertions; - using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter; using Microsoft.VisualStudio.TestPlatform.ObjectModel; @@ -58,16 +56,17 @@ private static void ContainsTestsDiscovered(IEnumerable discoveredTest { if (matchCount) { - discoveredTests.Should().HaveSameCount(expectedTests); + Assert.AreEqual(expectedTests.Count(), discoveredTests.Count()); } foreach (string test in expectedTests) { // Test Discovery run was expecting to discover \"{test}\", but it has not discovered. - discoveredTests.Should().Contain( + Assert.Contains( p => test.Equals(p.FullyQualifiedName, StringComparison.Ordinal) || test.Equals(p.DisplayName, StringComparison.Ordinal) - || test.Equals(p.DisplayName, StringComparison.Ordinal)); + || test.Equals(p.DisplayName, StringComparison.Ordinal), + discoveredTests); } } @@ -82,10 +81,11 @@ private static void ContainsExpectedTestsWithOutcome(IEnumerable tes foreach (string test in expectedTests) { - tests.Should().Contain( + Assert.Contains( p => test.Equals(p.TestCase.FullyQualifiedName, StringComparison.Ordinal) || test.Equals(p.DisplayName, StringComparison.Ordinal) - || test.Equals(p.TestCase.DisplayName, StringComparison.Ordinal)); + || test.Equals(p.TestCase.DisplayName, StringComparison.Ordinal), + tests); } } @@ -100,9 +100,10 @@ private static void ContainsExpectedTestsWithOutcome(IEnumerable tes foreach (string test in expectedTests) { - tests.Should().Contain(p => p.DisplayName == test); + Assert.Contains(p => p.DisplayName == test, tests); } } - private static void AssertOutcomeCount(IEnumerable actual, TestOutcome expectedOutcome, int expectedCount) => actual.Where(i => i.Outcome == expectedOutcome).Should().HaveCount(expectedCount); + private static void AssertOutcomeCount(IEnumerable actual, TestOutcome expectedOutcome, int expectedCount) + => Assert.HasCount(expectedCount, actual.Where(i => i.Outcome == expectedOutcome)); } diff --git a/test/IntegrationTests/MSTest.IntegrationTests/FSharpTestProjectTests.cs b/test/IntegrationTests/MSTest.IntegrationTests/FSharpTestProjectTests.cs index 59713dd4d3..ba1053f2fe 100644 --- a/test/IntegrationTests/MSTest.IntegrationTests/FSharpTestProjectTests.cs +++ b/test/IntegrationTests/MSTest.IntegrationTests/FSharpTestProjectTests.cs @@ -5,10 +5,12 @@ namespace MSTest.IntegrationTests; +[TestClass] public class FSharpTestProjectTests : CLITestBase { private const string TestAssetName = "FSharpTestProject"; + [TestMethod] public async Task TestFSharpTestsWithSpaceAndDotInName() { // Arrange diff --git a/test/IntegrationTests/MSTest.IntegrationTests/MSTest.IntegrationTests.csproj b/test/IntegrationTests/MSTest.IntegrationTests/MSTest.IntegrationTests.csproj index cb81bfbdf0..a611d2e477 100644 --- a/test/IntegrationTests/MSTest.IntegrationTests/MSTest.IntegrationTests.csproj +++ b/test/IntegrationTests/MSTest.IntegrationTests/MSTest.IntegrationTests.csproj @@ -4,8 +4,9 @@ $(NetFrameworkMinimum) false $(NoWarn),1685 - true Exe + true + true @@ -13,17 +14,21 @@ - - - - - + Analyzer false + + Analyzer + false + + + Analyzer + false + diff --git a/test/IntegrationTests/MSTest.IntegrationTests/NoNamespaceTests.cs b/test/IntegrationTests/MSTest.IntegrationTests/NoNamespaceTests.cs index ee2b1d55f1..2138a7b6c1 100644 --- a/test/IntegrationTests/MSTest.IntegrationTests/NoNamespaceTests.cs +++ b/test/IntegrationTests/MSTest.IntegrationTests/NoNamespaceTests.cs @@ -1,8 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. -using FluentAssertions; - using Microsoft.MSTestV2.CLIAutomation; using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Extensions; @@ -10,17 +8,19 @@ namespace MSTest.IntegrationTests; +[TestClass] public class NoNamespaceTests : CLITestBase { private const string TestAssetName = "HierarchyProject"; + [TestMethod] public void TestsAreDiscoveredWithExpectedHierarchy() { // Arrange & Act System.Collections.Immutable.ImmutableArray testCases = DiscoverTests(GetAssetFullPath(TestAssetName)); // Assert - testCases.Should().HaveCount(2); + Assert.HasCount(2, testCases, "Should discover exactly 2 tests with hierarchy information"); VerifyHierarchy(testCases[0], null!, "ClassWithNoNamespace", "MyMethodUnderTest"); VerifyHierarchy(testCases[1], "SomeNamespace.WithMultipleLevels", "ClassWithNamespace", "MyMethodUnderTest"); @@ -29,12 +29,13 @@ public void TestsAreDiscoveredWithExpectedHierarchy() private static void VerifyHierarchy(TestCase testCase, string expectedNamespace, string expectedClassName, string expectedMethodName) { string[]? hierarchy = testCase.GetPropertyValue(TestCaseExtensions.HierarchyProperty) as string[]; - hierarchy.Should().HaveCount(4); + Assert.IsNotNull(hierarchy); + Assert.HasCount(4, hierarchy); // This level is always null. - hierarchy![0].Should().BeNull(); - hierarchy[1].Should().Be(expectedNamespace); - hierarchy[2].Should().Be(expectedClassName); - hierarchy[3].Should().Be(expectedMethodName); + Assert.IsNull(hierarchy[0]); + Assert.AreEqual(expectedNamespace, hierarchy[1]); + Assert.AreEqual(expectedClassName, hierarchy[2]); + Assert.AreEqual(expectedMethodName, hierarchy[3]); } } diff --git a/test/IntegrationTests/MSTest.IntegrationTests/OutputTests.cs b/test/IntegrationTests/MSTest.IntegrationTests/OutputTests.cs index c7720d0655..02a68522af 100644 --- a/test/IntegrationTests/MSTest.IntegrationTests/OutputTests.cs +++ b/test/IntegrationTests/MSTest.IntegrationTests/OutputTests.cs @@ -1,8 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. -using FluentAssertions; - using Microsoft.MSTestV2.CLIAutomation; using Microsoft.VisualStudio.TestPlatform.ObjectModel; @@ -10,15 +8,18 @@ namespace MSTest.IntegrationTests; +[TestClass] public class OutputTests : CLITestBase { private const string TestAssetName = "OutputTestProject"; -#pragma warning disable IDE0051 // Remove unused private members - test is failing in CI. - private async Task OutputIsNotMixedWhenTestsRunInParallel() => await ValidateOutputForClassAsync("UnitTest1"); + [TestMethod] + [Ignore("Fails on CI.")] + public async Task OutputIsNotMixedWhenTestsRunInParallel() => await ValidateOutputForClassAsync("UnitTest1"); - private async Task OutputIsNotMixedWhenAsyncTestsRunInParallel() => await ValidateOutputForClassAsync("UnitTest2"); -#pragma warning restore IDE0051 // Remove unused private members + [TestMethod] + [Ignore("Fails on CI.")] + public async Task OutputIsNotMixedWhenAsyncTestsRunInParallel() => await ValidateOutputForClassAsync("UnitTest2"); private static async Task ValidateOutputForClassAsync(string className) { @@ -30,18 +31,18 @@ private static async Task ValidateOutputForClassAsync(string className) // Act var testCases = DiscoverTests(assemblyPath).Where(tc => tc.FullyQualifiedName.Contains(className)).ToList(); - testCases.Should().HaveCount(3); - testCases.Should().NotContainNulls(); + Assert.HasCount(3, testCases); + CollectionAssert.AllItemsAreNotNull(testCases, "All test cases should be non-null."); System.Collections.Immutable.ImmutableArray testResults = await RunTestsAsync(testCases); - testResults.Should().HaveCount(3); - testResults.Should().NotContainNulls(); + Assert.HasCount(3, testResults); + CollectionAssert.AllItemsAreNotNull(testResults, "All test results should be non-null."); // Assert // Ensure that some tests are running in parallel, because otherwise the output just works correctly. DateTimeOffset firstEnd = testResults.Min(t => t.EndTime); bool someStartedBeforeFirstEnded = testResults.Where(t => t.EndTime != firstEnd).Any(t => firstEnd > t.StartTime); - someStartedBeforeFirstEnded.Should().BeTrue("Tests must run in parallel, but there were no other tests that started, before the first one ended."); + Assert.IsTrue(someStartedBeforeFirstEnded, "Tests must run in parallel, but there were no other tests that started, before the first one ended."); ValidateOutputsAreNotMixed(testResults, "TestMethod1", ["TestMethod2", "TestMethod3"]); ValidateOutputsAreNotMixed(testResults, "TestMethod2", ["TestMethod1", "TestMethod3"]); @@ -75,22 +76,21 @@ private static void ValidateOutputIsNotMixed(IEnumerable testResults TestResult testMethod = testResults.Single(t => t.DisplayName == methodName); // Test method {methodName} was not found. - testMethod.Should().NotBeNull(); - TestResultMessage message = testMethod.Messages.SingleOrDefault(messageFilter); + TestResultMessage? message = testMethod.Messages.SingleOrDefault(messageFilter); // Message for {testMethod.DisplayName} was not found. All messages: { string.Join(Environment.NewLine, testMethod.Messages.Select(m => $"{m.Category} - {m.Text}")) } - message.Should().NotBeNull(); - message.Text.Should().Contain(methodName); - message.Text.Should().Contain("TestInitialize"); - message.Text.Should().Contain("TestCleanup"); - message.Text.Should().NotContainAny(shouldNotContain); + Assert.IsNotNull(message); + Assert.IsNotNull(message.Text); + Assert.Contains(methodName, message.Text); + Assert.Contains("TestInitialize", message.Text); + Assert.Contains("TestCleanup", message.Text); + Assert.IsFalse(shouldNotContain.Any(message.Text.Contains)); } private static void ValidateInitializeAndCleanup(IEnumerable testResults, Func messageFilter) { // It is not deterministic where the class initialize and class cleanup will run, so we look at all tests, to make sure it is includes somewhere. string output = string.Join(Environment.NewLine, testResults.SelectMany(r => r.Messages).Where(messageFilter).Select(m => m.Text)); - output.Should().NotBeNull(); var failureMessageBuilder = new StringBuilder(); foreach (TestResult testResult in testResults) { @@ -105,7 +105,7 @@ private static void ValidateInitializeAndCleanup(IEnumerable testRes } string becauseMessage = failureMessageBuilder.ToString(); - output.Should().Contain("ClassInitialize", because: becauseMessage); - output.Should().Contain("ClassCleanup", because: becauseMessage); + Assert.Contains("ClassInitialize", output, becauseMessage); + Assert.Contains("ClassCleanup", output, becauseMessage); } } diff --git a/test/IntegrationTests/MSTest.IntegrationTests/Parameterized tests/DataExtensibilityTests.cs b/test/IntegrationTests/MSTest.IntegrationTests/Parameterized tests/DataExtensibilityTests.cs index 9fba8ddfa5..e2cf8722b0 100644 --- a/test/IntegrationTests/MSTest.IntegrationTests/Parameterized tests/DataExtensibilityTests.cs +++ b/test/IntegrationTests/MSTest.IntegrationTests/Parameterized tests/DataExtensibilityTests.cs @@ -10,6 +10,7 @@ namespace MSTest.IntegrationTests; +[TestClass] public class DataExtensibilityTests : CLITestBase { private const string TestAssetName = "FxExtensibilityTestProject"; @@ -19,7 +20,7 @@ public class DataExtensibilityTests : CLITestBase - Ignored tests are discovered during discovery - Ignored tests are not expanded (DataRow, DataSource, etc) */ - + [TestMethod] public async Task CustomTestDataSourceTests() { // Arrange @@ -33,6 +34,7 @@ public async Task CustomTestDataSourceTests() VerifyE2E.ContainsTestsPassed(testResults, "CustomTestDataSourceTestMethod1 (1,2,3)", "CustomTestDataSourceTestMethod1 (4,5,6)"); } + [TestMethod] public async Task CustomEmptyTestDataSourceTests() { // Arrange @@ -46,6 +48,7 @@ public async Task CustomEmptyTestDataSourceTests() VerifyE2E.ContainsTestsFailed(testResults, [null!]); } + [TestMethod] public async Task AssertExtensibilityTests() { // Arrange @@ -59,6 +62,7 @@ public async Task AssertExtensibilityTests() VerifyE2E.ContainsTestsFailed(testResults, "BasicFailingAssertExtensionTest", "ChainedFailingAssertExtensionTest"); } + [TestMethod] public async Task ExecuteCustomTestExtensibilityTests() { // Arrange @@ -86,6 +90,7 @@ public async Task ExecuteCustomTestExtensibilityTests() "CustomTestClass1 - Execution number 3"); } + [TestMethod] public async Task ExecuteCustomTestExtensibilityWithTestDataTests() { // Arrange @@ -112,6 +117,7 @@ public async Task ExecuteCustomTestExtensibilityWithTestDataTests() "CustomTestMethod2 (\"C\")"); } + [TestMethod] public async Task WhenUsingCustomITestDataSourceWithExpansionDisabled_RespectSetting() { // Arrange @@ -122,7 +128,7 @@ public async Task WhenUsingCustomITestDataSourceWithExpansionDisabled_RespectSet ImmutableArray testResults = await RunTestsAsync(testCases); // Assert - Verify(testCases.Length == 1); + Assert.HasCount(1, testCases); VerifyE2E.TestsPassed( testResults, diff --git a/test/IntegrationTests/MSTest.IntegrationTests/Parameterized tests/DataRowTests.cs b/test/IntegrationTests/MSTest.IntegrationTests/Parameterized tests/DataRowTests.cs index ce287aa5e5..3eec60fd53 100644 --- a/test/IntegrationTests/MSTest.IntegrationTests/Parameterized tests/DataRowTests.cs +++ b/test/IntegrationTests/MSTest.IntegrationTests/Parameterized tests/DataRowTests.cs @@ -5,10 +5,12 @@ namespace MSTest.IntegrationTests; +[TestClass] public class DataRowTests : CLITestBase { private const string TestAssetName = "DataRowTestProject"; + [TestMethod] public async Task ExecuteOnlyDerivedClassDataRowsWhenBothBaseAndDerivedClassHasDataRows_SimpleDataRows() { // Arrange @@ -28,6 +30,7 @@ public async Task ExecuteOnlyDerivedClassDataRowsWhenBothBaseAndDerivedClassHasD "DataRowTestMethod (\"DerivedString2\")"); } + [TestMethod] public async Task ExecuteOnlyDerivedClassDataRowsWhenItOverridesBaseClassDataRows_SimpleDataRows() { // Arrange @@ -44,6 +47,7 @@ public async Task ExecuteOnlyDerivedClassDataRowsWhenItOverridesBaseClassDataRow "DataRowTestMethod (\"DerivedString2\")"); } + [TestMethod] public async Task DataRowsExecuteWithRequiredAndOptionalParameters() { // Arrange @@ -61,6 +65,7 @@ public async Task DataRowsExecuteWithRequiredAndOptionalParameters() "DataRowTestMethodWithSomeOptionalParameters (123,\"DerivedOptionalString2\",\"DerivedOptionalString3\")"); } + [TestMethod] public async Task DataRowsExecuteWithParamsArrayParameter() { // Arrange @@ -79,6 +84,7 @@ public async Task DataRowsExecuteWithParamsArrayParameter() "DataRowTestMethodWithParamsParameters (2,\"DerivedParamsArg1\",\"DerivedParamsArg2\",\"DerivedParamsArg3\")"); } + [TestMethod] public async Task DataRowsFailWhenInvalidArgumentsProvided() { // Arrange @@ -96,6 +102,7 @@ public async Task DataRowsFailWhenInvalidArgumentsProvided() "DataRowTestMethodFailsWithInvalidArguments (2,\"DerivedRequiredArgument\",\"DerivedOptionalArgument\",\"DerivedExtraArgument\")"); } + [TestMethod] public async Task DataRowsShouldSerializeDoublesProperly() { // Arrange @@ -112,6 +119,7 @@ public async Task DataRowsShouldSerializeDoublesProperly() "DataRowTestDouble (10.02,20.02)"); } + [TestMethod] public async Task DataRowsShouldSerializeMixedTypesProperly() { // Arrange @@ -127,6 +135,7 @@ public async Task DataRowsShouldSerializeMixedTypesProperly() "DataRowTestMixed (10,10,10,10,10,10,10,\"10\")"); } + [TestMethod] public async Task DataRowsShouldSerializeEnumsProperly() { // Arrange @@ -145,6 +154,7 @@ public async Task DataRowsShouldSerializeEnumsProperly() "DataRowEnums (Gamma)"); } + [TestMethod] public async Task DataRowsShouldHandleNonSerializableValues() { // Arrange @@ -166,6 +176,7 @@ public async Task DataRowsShouldHandleNonSerializableValues() "DataRowNonSerializable (DataRowTestProject.DataRowTests_DerivedClass)"); } + [TestMethod] public async Task ExecuteDataRowTests_Enums() { // Arrange @@ -241,6 +252,7 @@ public async Task ExecuteDataRowTests_Enums() VerifyE2E.FailedTestCount(testResults, 0); } + [TestMethod] public async Task ExecuteDataRowTests_NonSerializablePaths() { // Arrange @@ -259,6 +271,7 @@ public async Task ExecuteDataRowTests_NonSerializablePaths() VerifyE2E.FailedTestCount(testResults, 0); } + [TestMethod] public async Task ExecuteDataRowTests_Regular() { // Arrange @@ -320,6 +333,7 @@ public async Task ExecuteDataRowTests_Regular() "DataRowTestMethodFailsWithInvalidArguments (2,\"DerivedRequiredArgument\",\"DerivedOptionalArgument\",\"DerivedExtraArgument\")"); } + [TestMethod] public async Task GetDisplayName_AfterOverriding_GetsTheNewDisplayName() { // Arrange @@ -334,6 +348,7 @@ public async Task GetDisplayName_AfterOverriding_GetsTheNewDisplayName() "Overridden DisplayName"); } + [TestMethod] public async Task ParameterizedTestsWithTestMethodSettingDisplayName_DataIsPrefixWithDisplayName() { // Arrange diff --git a/test/IntegrationTests/MSTest.IntegrationTests/Parameterized tests/DataSourceTests.cs b/test/IntegrationTests/MSTest.IntegrationTests/Parameterized tests/DataSourceTests.cs index beba2bdf32..e66d4c0cb0 100644 --- a/test/IntegrationTests/MSTest.IntegrationTests/Parameterized tests/DataSourceTests.cs +++ b/test/IntegrationTests/MSTest.IntegrationTests/Parameterized tests/DataSourceTests.cs @@ -5,13 +5,15 @@ namespace MSTest.IntegrationTests; +[TestClass] public class DataSourceTests : CLITestBase { private const string TestAssetName = "DataSourceTestProject"; - // TODO @haplois | @evangelink: This test fails under CI - will be fixed in a future PR (Marked as private to ignore the test) #pragma warning disable IDE0051 // Remove unused private members - private async Task ExecuteCsvTestDataSourceTests() + [TestMethod] + [Ignore("This test is ignored because it fails under CI. It will be fixed in a future PR.")] + public async Task ExecuteCsvTestDataSourceTests() #pragma warning restore IDE0051 // Remove unused private members { // Arrange diff --git a/test/IntegrationTests/MSTest.IntegrationTests/Parameterized tests/DynamicDataTests.cs b/test/IntegrationTests/MSTest.IntegrationTests/Parameterized tests/DynamicDataTests.cs index d271d9063c..0cdf9e25c4 100644 --- a/test/IntegrationTests/MSTest.IntegrationTests/Parameterized tests/DynamicDataTests.cs +++ b/test/IntegrationTests/MSTest.IntegrationTests/Parameterized tests/DynamicDataTests.cs @@ -10,10 +10,12 @@ namespace MSTest.IntegrationTests; +[TestClass] public class DynamicDataTests : CLITestBase { private const string TestAssetName = "DynamicDataTestProject"; + [TestMethod] public async Task ExecuteDynamicDataTests() { // Arrange @@ -84,6 +86,7 @@ public async Task ExecuteDynamicDataTests() VerifyE2E.FailedTestCount(testResults, 0); } + [TestMethod] public async Task ExecuteDynamicDataTestsWithCategoryFilter() { // Arrange @@ -102,6 +105,7 @@ public async Task ExecuteDynamicDataTestsWithCategoryFilter() VerifyE2E.FailedTestCount(testResults, 0); } + [TestMethod] public async Task ExecuteNonExpandableDynamicDataTests() { // Arrange @@ -112,7 +116,7 @@ public async Task ExecuteNonExpandableDynamicDataTests() ImmutableArray testResults = await RunTestsAsync(testCases); // Assert - Verify(testCases.Length == 6); + Assert.HasCount(6, testCases); VerifyE2E.TestsPassed( testResults, diff --git a/test/IntegrationTests/MSTest.IntegrationTests/Program.cs b/test/IntegrationTests/MSTest.IntegrationTests/Program.cs index ce5734f730..55b5a5adf2 100644 --- a/test/IntegrationTests/MSTest.IntegrationTests/Program.cs +++ b/test/IntegrationTests/MSTest.IntegrationTests/Program.cs @@ -3,7 +3,7 @@ using Microsoft.Testing.Extensions; -using TestFramework.ForTestingMSTest; +[assembly: Parallelize(Scope = Microsoft.VisualStudio.TestTools.UnitTesting.ExecutionScope.MethodLevel, Workers = 0)] ITestApplicationBuilder builder = await TestApplication.CreateBuilderAsync(args); @@ -16,7 +16,7 @@ builder.AddRetryProvider(); builder.AddAzureDevOpsProvider(); -builder.AddInternalTestFramework(); +builder.AddMSTest(() => [Assembly.GetEntryAssembly()!]); ITestApplication app = await builder.BuildAsync(); return await app.RunAsync(); diff --git a/test/IntegrationTests/MSTest.IntegrationTests/TestCategoriesFromTestDataRowTests.cs b/test/IntegrationTests/MSTest.IntegrationTests/TestCategoriesFromTestDataRowTests.cs index 878cf09f4f..f187829357 100644 --- a/test/IntegrationTests/MSTest.IntegrationTests/TestCategoriesFromTestDataRowTests.cs +++ b/test/IntegrationTests/MSTest.IntegrationTests/TestCategoriesFromTestDataRowTests.cs @@ -5,6 +5,7 @@ namespace MSTest.IntegrationTests; +[TestClass] public class TestCategoriesFromTestDataRowTests : CLITestBase { private const string TestAssetName = "TestCategoriesFromTestDataRowProject"; @@ -19,10 +20,10 @@ public void TestCategoriesFromTestDataRow_ShouldDiscoverTestsWithIntegrationCate System.Collections.Immutable.ImmutableArray testCases = DiscoverTests(assemblyPath, "TestCategory~Integration"); // Assert - Should discover the test that has Integration category from TestDataRow - Assert.AreEqual(1, testCases.Length, "Should discover exactly 1 test with Integration category"); + Assert.HasCount(1, testCases, "Should discover exactly 1 test with Integration category"); Microsoft.VisualStudio.TestPlatform.ObjectModel.TestCase integrationTest = testCases[0]; - Assert.IsTrue(integrationTest.DisplayName.Contains("Integration and Slow"), "Should be the test with Integration and Slow categories"); + Assert.Contains("Integration and Slow", integrationTest.DisplayName, "Should be the test with Integration and Slow categories"); } [TestMethod] @@ -35,10 +36,10 @@ public void TestCategoriesFromTestDataRow_ShouldDiscoverTestsWithUnitCategory() System.Collections.Immutable.ImmutableArray testCases = DiscoverTests(assemblyPath, "TestCategory~Unit"); // Assert - Should discover the test that has Unit category from TestDataRow - Assert.AreEqual(1, testCases.Length, "Should discover exactly 1 test with Unit category"); + Assert.HasCount(1, testCases, "Should discover exactly 1 test with Unit category"); Microsoft.VisualStudio.TestPlatform.ObjectModel.TestCase unitTest = testCases[0]; - Assert.IsTrue(unitTest.DisplayName.Contains("Unit and Fast"), "Should be the test with Unit and Fast categories"); + Assert.Contains("Unit and Fast", unitTest.DisplayName, "Should be the test with Unit and Fast categories"); } [TestMethod] @@ -54,14 +55,14 @@ public void TestCategoriesFromTestDataRow_ShouldCombineMethodAndDataCategories() System.Collections.Immutable.ImmutableArray dataLevelTests = DiscoverTests(assemblyPath, "TestCategory~DataLevel"); // Assert - The same test should be found by both filters since categories are merged - Assert.AreEqual(1, methodLevelTests.Length, "Should discover exactly 1 test with MethodLevel category"); - Assert.AreEqual(1, dataLevelTests.Length, "Should discover exactly 1 test with DataLevel category"); + Assert.HasCount(1, methodLevelTests, "Should discover exactly 1 test with MethodLevel category"); + Assert.HasCount(1, dataLevelTests, "Should discover exactly 1 test with DataLevel category"); Microsoft.VisualStudio.TestPlatform.ObjectModel.TestCase methodTest = methodLevelTests[0]; Microsoft.VisualStudio.TestPlatform.ObjectModel.TestCase dataTest = dataLevelTests[0]; Assert.AreEqual(methodTest.FullyQualifiedName, dataTest.FullyQualifiedName, "Both filters should find the same test"); - Assert.IsTrue(methodTest.DisplayName.Contains("method and data categories"), "Should be the test with combined categories"); + Assert.Contains("method and data categories", methodTest.DisplayName, "Should be the test with combined categories"); } [TestMethod] diff --git a/test/IntegrationTests/MSTest.IntegrationTests/TestId.DefaultStrategy.cs b/test/IntegrationTests/MSTest.IntegrationTests/TestId.DefaultStrategy.cs index dc33ae9ad5..fece8ae805 100644 --- a/test/IntegrationTests/MSTest.IntegrationTests/TestId.DefaultStrategy.cs +++ b/test/IntegrationTests/MSTest.IntegrationTests/TestId.DefaultStrategy.cs @@ -1,8 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. -using FluentAssertions; - using Microsoft.MSTestV2.CLIAutomation; namespace MSTest.IntegrationTests; @@ -11,6 +9,7 @@ public partial class TestId : CLITestBase { private const string DefaultStrategyDll = "TestIdProject.DefaultStrategy"; + [TestMethod] public async Task TestIdUniqueness_DataRowArray_DefaultStrategy() { // Arrange @@ -29,9 +28,12 @@ public async Task TestIdUniqueness_DataRowArray_DefaultStrategy() "DataRowArraysTests (0,[0,0,0])"); // We cannot assert the expected ID as it is path dependent - testResults.Select(x => x.TestCase.Id.ToString()).Should().OnlyHaveUniqueItems(); + CollectionAssert.AllItemsAreUnique( + testResults.Select(x => x.TestCase.Id.ToString()).ToList(), + "Test IDs should be unique."); } + [TestMethod] public async Task TestIdUniqueness_DataRowString_DefaultStrategy() { // Arrange @@ -51,9 +53,12 @@ public async Task TestIdUniqueness_DataRowString_DefaultStrategy() "DataRowStringTests (\" \")"); // We cannot assert the expected ID as it is path dependent - testResults.Select(x => x.TestCase.Id.ToString()).Should().OnlyHaveUniqueItems(); + CollectionAssert.AllItemsAreUnique( + testResults.Select(x => x.TestCase.Id.ToString()).ToList(), + "Test IDs should be unique."); } + [TestMethod] public async Task TestIdUniqueness_DynamicDataArrays_DefaultStrategy() { // Arrange @@ -72,9 +77,12 @@ public async Task TestIdUniqueness_DynamicDataArrays_DefaultStrategy() "DynamicDataArraysTests (0,[0,0,0])"); // We cannot assert the expected ID as it is path dependent - testResults.Select(x => x.TestCase.Id.ToString()).Should().OnlyHaveUniqueItems(); + CollectionAssert.AllItemsAreUnique( + testResults.Select(x => x.TestCase.Id.ToString()).ToList(), + "Test IDs should be unique."); } + [TestMethod] public async Task TestIdUniqueness_DynamicDataTuple_DefaultStrategy() { // Arrange @@ -92,9 +100,12 @@ public async Task TestIdUniqueness_DynamicDataTuple_DefaultStrategy() "DynamicDataTuplesTests ((1, text, False))"); // We cannot assert the expected ID as it is path dependent - testResults.Select(x => x.TestCase.Id.ToString()).Should().OnlyHaveUniqueItems(); + CollectionAssert.AllItemsAreUnique( + testResults.Select(x => x.TestCase.Id.ToString()).ToList(), + "Test IDs should be unique."); } + [TestMethod] public async Task TestIdUniqueness_DynamicDataGenericCollections_DefaultStrategy() { // Arrange @@ -114,9 +125,12 @@ public async Task TestIdUniqueness_DynamicDataGenericCollections_DefaultStrategy "DynamicDataGenericCollectionsTests (System.Collections.Generic.List`1[System.Int32],System.Collections.Generic.List`1[System.String],System.Collections.Generic.List`1[System.Boolean])"); // We cannot assert the expected ID as it is path dependent - testResults.Select(x => x.TestCase.Id.ToString()).Should().OnlyHaveUniqueItems(); + CollectionAssert.AllItemsAreUnique( + testResults.Select(x => x.TestCase.Id.ToString()).ToList(), + "Test IDs should be unique."); } + [TestMethod] public async Task TestIdUniqueness_TestDataSourceArrays_DefaultStrategy() { // Arrange @@ -135,9 +149,12 @@ public async Task TestIdUniqueness_TestDataSourceArrays_DefaultStrategy() "Custom name"); // We cannot assert the expected ID as it is path dependent - testResults.Select(x => x.TestCase.Id.ToString()).Should().OnlyHaveUniqueItems(); + CollectionAssert.AllItemsAreUnique( + testResults.Select(x => x.TestCase.Id.ToString()).ToList(), + "Test IDs should be unique."); } + [TestMethod] public async Task TestIdUniqueness_TestDataSourceTuples_DefaultStrategy() { // Arrange @@ -155,9 +172,12 @@ public async Task TestIdUniqueness_TestDataSourceTuples_DefaultStrategy() "Custom name"); // We cannot assert the expected ID as it is path dependent - testResults.Select(x => x.TestCase.Id.ToString()).Should().OnlyHaveUniqueItems(); + CollectionAssert.AllItemsAreUnique( + testResults.Select(x => x.TestCase.Id.ToString()).ToList(), + "Test IDs should be unique."); } + [TestMethod] public async Task TestIdUniqueness_TestDataSourceGenericCollections_DefaultStrategy() { // Arrange @@ -177,6 +197,8 @@ public async Task TestIdUniqueness_TestDataSourceGenericCollections_DefaultStrat "Custom name"); // We cannot assert the expected ID as it is path dependent - testResults.Select(x => x.TestCase.Id.ToString()).Should().OnlyHaveUniqueItems(); + CollectionAssert.AllItemsAreUnique( + testResults.Select(x => x.TestCase.Id.ToString()).ToList(), + "Test IDs should be unique."); } } diff --git a/test/IntegrationTests/MSTest.IntegrationTests/TestId.DisplayNameStrategy.cs b/test/IntegrationTests/MSTest.IntegrationTests/TestId.DisplayNameStrategy.cs index 5f927acbf4..ec72fa6764 100644 --- a/test/IntegrationTests/MSTest.IntegrationTests/TestId.DisplayNameStrategy.cs +++ b/test/IntegrationTests/MSTest.IntegrationTests/TestId.DisplayNameStrategy.cs @@ -1,8 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. -using FluentAssertions; - using Microsoft.MSTestV2.CLIAutomation; namespace MSTest.IntegrationTests; @@ -11,6 +9,7 @@ public partial class TestId : CLITestBase { private const string DisplayNameStrategyDll = "TestIdProject.DisplayNameStrategy"; + [TestMethod] public async Task TestIdUniqueness_DataRowArray_DisplayNameStrategy() { // Arrange @@ -29,9 +28,10 @@ public async Task TestIdUniqueness_DataRowArray_DisplayNameStrategy() "DataRowArraysTests (0,System.Int32[])"); // We cannot assert the expected ID as it is path dependent - testResults.Select(x => x.TestCase.Id.ToString()).Distinct().Should().ContainSingle(); + Assert.ContainsSingle(testResults.Select(x => x.TestCase.Id.ToString()).Distinct()); } + [TestMethod] public async Task TestIdUniqueness_DataRowString_DisplayNameStrategy() { // Arrange @@ -52,9 +52,10 @@ public async Task TestIdUniqueness_DataRowString_DisplayNameStrategy() // We cannot assert the expected ID as it is path dependent. // First two display names are equals so we have the same ID for them - testResults.Select(x => x.TestCase.Id.ToString()).Distinct().Should().HaveCount(3); + Assert.HasCount(3, testResults.Select(x => x.TestCase.Id.ToString()).Distinct()); } + [TestMethod] public async Task TestIdUniqueness_DynamicDataArrays_DisplayNameStrategy() { // Arrange @@ -73,9 +74,10 @@ public async Task TestIdUniqueness_DynamicDataArrays_DisplayNameStrategy() "DynamicDataArraysTests (0,System.Int32[])"); // We cannot assert the expected ID as it is path dependent - testResults.Select(x => x.TestCase.Id.ToString()).Distinct().Should().ContainSingle(); + Assert.ContainsSingle(testResults.Select(x => x.TestCase.Id.ToString()).Distinct()); } + [TestMethod] public async Task TestIdUniqueness_DynamicDataTuple_DisplayNameStrategy() { // Arrange @@ -93,9 +95,12 @@ public async Task TestIdUniqueness_DynamicDataTuple_DisplayNameStrategy() "DynamicDataTuplesTests ((1, text, False))"); // We cannot assert the expected ID as it is path dependent - testResults.Select(x => x.TestCase.Id.ToString()).Should().OnlyHaveUniqueItems(); + CollectionAssert.AllItemsAreUnique( + testResults.Select(x => x.TestCase.Id.ToString()).ToList(), + "Test IDs should be unique."); } + [TestMethod] public async Task TestIdUniqueness_DynamicDataGenericCollections_DisplayNameStrategy() { // Arrange @@ -115,9 +120,10 @@ public async Task TestIdUniqueness_DynamicDataGenericCollections_DisplayNameStra "DynamicDataGenericCollectionsTests (System.Collections.Generic.List`1[System.Int32],System.Collections.Generic.List`1[System.String],System.Collections.Generic.List`1[System.Boolean])"); // We cannot assert the expected ID as it is path dependent - testResults.Select(x => x.TestCase.Id.ToString()).Distinct().Should().ContainSingle(); + Assert.ContainsSingle(testResults.Select(x => x.TestCase.Id.ToString()).Distinct()); } + [TestMethod] public async Task TestIdUniqueness_TestDataSourceArrays_DisplayNameStrategy() { // Arrange @@ -136,9 +142,10 @@ public async Task TestIdUniqueness_TestDataSourceArrays_DisplayNameStrategy() "Custom name"); // We cannot assert the expected ID as it is path dependent - testResults.Select(x => x.TestCase.Id.ToString()).Distinct().Should().ContainSingle(); + Assert.ContainsSingle(testResults.Select(x => x.TestCase.Id.ToString()).Distinct()); } + [TestMethod] public async Task TestIdUniqueness_TestDataSourceTuples_DisplayNameStrategy() { // Arrange @@ -156,9 +163,10 @@ public async Task TestIdUniqueness_TestDataSourceTuples_DisplayNameStrategy() "Custom name"); // We cannot assert the expected ID as it is path dependent - testResults.Select(x => x.TestCase.Id.ToString()).Distinct().Should().ContainSingle(); + Assert.ContainsSingle(testResults.Select(x => x.TestCase.Id.ToString()).Distinct()); } + [TestMethod] public async Task TestIdUniqueness_TestDataSourceGenericCollections_DisplayNameStrategy() { // Arrange @@ -178,6 +186,6 @@ public async Task TestIdUniqueness_TestDataSourceGenericCollections_DisplayNameS "Custom name"); // We cannot assert the expected ID as it is path dependent - testResults.Select(x => x.TestCase.Id.ToString()).Distinct().Should().ContainSingle(); + Assert.ContainsSingle(testResults.Select(x => x.TestCase.Id.ToString()).Distinct()); } } diff --git a/test/IntegrationTests/MSTest.IntegrationTests/TestId.FullyQualifiedStrategy.cs b/test/IntegrationTests/MSTest.IntegrationTests/TestId.FullyQualifiedStrategy.cs index 20512351bb..c65ad9d171 100644 --- a/test/IntegrationTests/MSTest.IntegrationTests/TestId.FullyQualifiedStrategy.cs +++ b/test/IntegrationTests/MSTest.IntegrationTests/TestId.FullyQualifiedStrategy.cs @@ -3,8 +3,6 @@ using System.Collections.Immutable; -using FluentAssertions; - using Microsoft.MSTestV2.CLIAutomation; namespace MSTest.IntegrationTests; @@ -13,6 +11,7 @@ public partial class TestId : CLITestBase { private const string FullyQualifiedStrategyDll = "TestIdProject.FullyQualifiedStrategy"; + [TestMethod] public async Task TestIdUniqueness_DataRowArray_FullyQualifiedStrategy() { // Arrange @@ -31,9 +30,12 @@ public async Task TestIdUniqueness_DataRowArray_FullyQualifiedStrategy() "DataRowArraysTests (0,[0,0,0])"); // We cannot assert the expected ID as it is path dependent - testResults.Select(x => x.TestCase.Id.ToString()).Should().OnlyHaveUniqueItems(); + CollectionAssert.AllItemsAreUnique( + testResults.Select(x => x.TestCase.Id.ToString()).ToList(), + "Test IDs should be unique."); } + [TestMethod] public async Task TestIdUniqueness_DataRowString_FullyQualifiedStrategy() { // Arrange @@ -53,9 +55,12 @@ public async Task TestIdUniqueness_DataRowString_FullyQualifiedStrategy() "DataRowStringTests (\" \")"); // We cannot assert the expected ID as it is path dependent - testResults.Select(x => x.TestCase.Id.ToString()).Should().OnlyHaveUniqueItems(); + CollectionAssert.AllItemsAreUnique( + testResults.Select(x => x.TestCase.Id.ToString()).ToList(), + "Test IDs should be unique."); } + [TestMethod] public async Task TestIdUniqueness_DynamicDataArrays_FullyQualifiedStrategy() { // Arrange @@ -74,9 +79,12 @@ public async Task TestIdUniqueness_DynamicDataArrays_FullyQualifiedStrategy() "DynamicDataArraysTests (0,[0,0,0])"); // We cannot assert the expected ID as it is path dependent - testResults.Select(x => x.TestCase.Id.ToString()).Should().OnlyHaveUniqueItems(); + CollectionAssert.AllItemsAreUnique( + testResults.Select(x => x.TestCase.Id.ToString()).ToList(), + "Test IDs should be unique."); } + [TestMethod] public async Task TestIdUniqueness_DynamicDataTuple_FullyQualifiedStrategy() { // Arrange @@ -94,9 +102,12 @@ public async Task TestIdUniqueness_DynamicDataTuple_FullyQualifiedStrategy() "DynamicDataTuplesTests ((1, text, False))"); // We cannot assert the expected ID as it is path dependent - testResults.Select(x => x.TestCase.Id.ToString()).Should().OnlyHaveUniqueItems(); + CollectionAssert.AllItemsAreUnique( + testResults.Select(x => x.TestCase.Id.ToString()).ToList(), + "Test IDs should be unique."); } + [TestMethod] public async Task TestIdUniqueness_DynamicDataGenericCollections_FullyQualifiedStrategy() { // Arrange @@ -116,9 +127,12 @@ public async Task TestIdUniqueness_DynamicDataGenericCollections_FullyQualifiedS "DynamicDataGenericCollectionsTests (System.Collections.Generic.List`1[System.Int32],System.Collections.Generic.List`1[System.String],System.Collections.Generic.List`1[System.Boolean])"); // We cannot assert the expected ID as it is path dependent - testResults.Select(x => x.TestCase.Id.ToString()).Should().OnlyHaveUniqueItems(); + CollectionAssert.AllItemsAreUnique( + testResults.Select(x => x.TestCase.Id.ToString()).ToList(), + "Test IDs should be unique."); } + [TestMethod] public async Task TestIdUniqueness_TestDataSourceArrays_FullyQualifiedStrategy() { // Arrange @@ -137,9 +151,12 @@ public async Task TestIdUniqueness_TestDataSourceArrays_FullyQualifiedStrategy() "Custom name"); // We cannot assert the expected ID as it is path dependent - testResults.Select(x => x.TestCase.Id.ToString()).Should().OnlyHaveUniqueItems(); + CollectionAssert.AllItemsAreUnique( + testResults.Select(x => x.TestCase.Id.ToString()).ToList(), + "Test IDs should be unique."); } + [TestMethod] public async Task TestIdUniqueness_TestDataSourceTuples_FullyQualifiedStrategy() { // Arrange @@ -157,9 +174,12 @@ public async Task TestIdUniqueness_TestDataSourceTuples_FullyQualifiedStrategy() "Custom name"); // We cannot assert the expected ID as it is path dependent - testResults.Select(x => x.TestCase.Id.ToString()).Should().OnlyHaveUniqueItems(); + CollectionAssert.AllItemsAreUnique( + testResults.Select(x => x.TestCase.Id.ToString()).ToList(), + "Test IDs should be unique."); } + [TestMethod] public async Task TestIdUniqueness_TestDataSourceGenericCollections_FullyQualifiedStrategy() { // Arrange @@ -179,6 +199,8 @@ public async Task TestIdUniqueness_TestDataSourceGenericCollections_FullyQualifi "Custom name"); // We cannot assert the expected ID as it is path dependent - testResults.Select(x => x.TestCase.Id.ToString()).Should().OnlyHaveUniqueItems(); + CollectionAssert.AllItemsAreUnique( + testResults.Select(x => x.TestCase.Id.ToString()).ToList(), + "Test IDs should be unique."); } } diff --git a/test/IntegrationTests/MSTest.IntegrationTests/TestId.LegacyStrategy.cs b/test/IntegrationTests/MSTest.IntegrationTests/TestId.LegacyStrategy.cs index ce2863edfc..daddcdca9e 100644 --- a/test/IntegrationTests/MSTest.IntegrationTests/TestId.LegacyStrategy.cs +++ b/test/IntegrationTests/MSTest.IntegrationTests/TestId.LegacyStrategy.cs @@ -1,16 +1,16 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. -using FluentAssertions; - using Microsoft.MSTestV2.CLIAutomation; namespace MSTest.IntegrationTests; +[TestClass] public partial class TestId : CLITestBase { private const string LegacyStrategyDll = "TestIdProject.LegacyStrategy"; + [TestMethod] public async Task TestIdUniqueness_DataRowArray_LegacyStrategy() { // Arrange @@ -30,9 +30,10 @@ public async Task TestIdUniqueness_DataRowArray_LegacyStrategy() "DataRowArraysTests (0,System.Int32[])"); // We cannot assert the expected ID as it is path dependent - testResults.Select(x => x.TestCase.Id.ToString()).Distinct().Should().ContainSingle(); + Assert.ContainsSingle(testResults.Select(x => x.TestCase.Id.ToString()).Distinct()); } + [TestMethod] public async Task TestIdUniqueness_DataRowString_LegacyStrategy() { // Arrange @@ -53,9 +54,10 @@ public async Task TestIdUniqueness_DataRowString_LegacyStrategy() "DataRowStringTests ( )"); // We cannot assert the expected ID as it is path dependent - testResults.Select(x => x.TestCase.Id.ToString()).Distinct().Should().ContainSingle(); + Assert.ContainsSingle(testResults.Select(x => x.TestCase.Id.ToString()).Distinct()); } + [TestMethod] public async Task TestIdUniqueness_DynamicDataArrays_LegacyStrategy() { // Arrange @@ -75,9 +77,10 @@ public async Task TestIdUniqueness_DynamicDataArrays_LegacyStrategy() "DynamicDataArraysTests (0,System.Int32[])"); // We cannot assert the expected ID as it is path dependent - testResults.Select(x => x.TestCase.Id.ToString()).Distinct().Should().ContainSingle(); + Assert.ContainsSingle(testResults.Select(x => x.TestCase.Id.ToString()).Distinct()); } + [TestMethod] public async Task TestIdUniqueness_DynamicDataTuple_LegacyStrategy() { // Arrange @@ -96,9 +99,10 @@ public async Task TestIdUniqueness_DynamicDataTuple_LegacyStrategy() "DynamicDataTuplesTests ((1, text, False))"); // We cannot assert the expected ID as it is path dependent - testResults.Select(x => x.TestCase.Id.ToString()).Distinct().Should().ContainSingle(); + Assert.ContainsSingle(testResults.Select(x => x.TestCase.Id.ToString()).Distinct()); } + [TestMethod] public async Task TestIdUniqueness_DynamicDataGenericCollections_LegacyStrategy() { // Arrange @@ -119,9 +123,10 @@ public async Task TestIdUniqueness_DynamicDataGenericCollections_LegacyStrategy( "DynamicDataGenericCollectionsTests (System.Collections.Generic.List`1[System.Int32],System.Collections.Generic.List`1[System.String],System.Collections.Generic.List`1[System.Boolean])"); // We cannot assert the expected ID as it is path dependent - testResults.Select(x => x.TestCase.Id.ToString()).Distinct().Should().ContainSingle(); + Assert.ContainsSingle(testResults.Select(x => x.TestCase.Id.ToString()).Distinct()); } + [TestMethod] public async Task TestIdUniqueness_TestDataSourceArrays_LegacyStrategy() { // Arrange @@ -141,9 +146,10 @@ public async Task TestIdUniqueness_TestDataSourceArrays_LegacyStrategy() "Custom name"); // We cannot assert the expected ID as it is path dependent - testResults.Select(x => x.TestCase.Id.ToString()).Distinct().Should().ContainSingle(); + Assert.ContainsSingle(testResults.Select(x => x.TestCase.Id.ToString()).Distinct()); } + [TestMethod] public async Task TestIdUniqueness_TestDataSourceTuples_LegacyStrategy() { // Arrange @@ -162,9 +168,10 @@ public async Task TestIdUniqueness_TestDataSourceTuples_LegacyStrategy() "Custom name"); // We cannot assert the expected ID as it is path dependent - testResults.Select(x => x.TestCase.Id.ToString()).Distinct().Should().ContainSingle(); + Assert.ContainsSingle(testResults.Select(x => x.TestCase.Id.ToString()).Distinct()); } + [TestMethod] public async Task TestIdUniqueness_TestDataSourceGenericCollections_LegacyStrategy() { // Arrange @@ -185,6 +192,6 @@ public async Task TestIdUniqueness_TestDataSourceGenericCollections_LegacyStrate "Custom name"); // We cannot assert the expected ID as it is path dependent - testResults.Select(x => x.TestCase.Id.ToString()).Distinct().Should().ContainSingle(); + Assert.ContainsSingle(testResults.Select(x => x.TestCase.Id.ToString()).Distinct()); } } diff --git a/test/IntegrationTests/MSTest.IntegrationTests/Utilities/CLITestBase.discovery.cs b/test/IntegrationTests/MSTest.IntegrationTests/Utilities/CLITestBase.discovery.cs index 4b9b678643..f5023b31fe 100644 --- a/test/IntegrationTests/MSTest.IntegrationTests/Utilities/CLITestBase.discovery.cs +++ b/test/IntegrationTests/MSTest.IntegrationTests/Utilities/CLITestBase.discovery.cs @@ -5,21 +5,17 @@ using DiscoveryAndExecutionTests.Utilities; -using FluentAssertions; - using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter; using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution; using Microsoft.VisualStudio.TestPlatform.ObjectModel; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging; -using TestFramework.ForTestingMSTest; - using TestResult = Microsoft.VisualStudio.TestPlatform.ObjectModel.TestResult; namespace Microsoft.MSTestV2.CLIAutomation; -public partial class CLITestBase : TestContainer +public abstract partial class CLITestBase { internal static ImmutableArray DiscoverTests(string assemblyPath, string? testCaseFilter = null) { @@ -102,14 +98,14 @@ private sealed class InternalFrameworkHandle : IFrameworkHandle public void RecordResult(TestResult testResult) { - testResult.Should().NotBeNull(); + Assert.IsNotNull(testResult, "Test result should not be null."); _activeResults.Add(testResult); } public ImmutableArray GetFlattenedTestResults() { var allTestResults = _testResults.SelectMany(i => i.Value).ToImmutableArray(); - allTestResults.Should().NotContainNulls(); + CollectionAssert.AllItemsAreNotNull(allTestResults, "All test results should be non-null."); return allTestResults; } diff --git a/test/IntegrationTests/MSTest.VstestConsoleWrapper.IntegrationTests/AssertExtensibilityTests.cs b/test/IntegrationTests/MSTest.VstestConsoleWrapper.IntegrationTests/AssertExtensibilityTests.cs index 743d862540..d5b8455e9b 100644 --- a/test/IntegrationTests/MSTest.VstestConsoleWrapper.IntegrationTests/AssertExtensibilityTests.cs +++ b/test/IntegrationTests/MSTest.VstestConsoleWrapper.IntegrationTests/AssertExtensibilityTests.cs @@ -5,10 +5,12 @@ namespace MSTest.VstestConsoleWrapper.IntegrationTests; +[TestClass] public class AssertExtensibilityTests : CLITestBase { private const string TestAssetName = "FxExtensibilityTestProject"; + [TestMethod] public void ExecuteAssertExtensibilityTests() { InvokeVsTestForExecution([TestAssetName]); diff --git a/test/IntegrationTests/MSTest.VstestConsoleWrapper.IntegrationTests/DeploymentTests.cs b/test/IntegrationTests/MSTest.VstestConsoleWrapper.IntegrationTests/DeploymentTests.cs index 4ef5aaf14c..4161e1bd75 100644 --- a/test/IntegrationTests/MSTest.VstestConsoleWrapper.IntegrationTests/DeploymentTests.cs +++ b/test/IntegrationTests/MSTest.VstestConsoleWrapper.IntegrationTests/DeploymentTests.cs @@ -5,6 +5,7 @@ namespace MSTest.VstestConsoleWrapper.IntegrationTests; +[TestClass] public class DeploymentTests : CLITestBase { private const string TestAssetNever = "DeploymentTestProject.Never"; @@ -18,26 +19,19 @@ public class DeploymentTests : CLITestBase """; - public void ValidateTestSourceDependencyDeployment_net462() - => ValidateTestSourceDependencyDeployment("net462"); - - public void ValidateTestSourceDependencyDeployment_netcoreapp31() - => ValidateTestSourceDependencyDeployment("netcoreapp3.1"); - - private void ValidateTestSourceDependencyDeployment(string targetFramework) + [TestMethod] + [DataRow("net462")] + [DataRow("netcoreapp3.1")] + public void ValidateTestSourceDependencyDeployment(string targetFramework) { InvokeVsTestForExecution([TestAssetNever], targetFramework: targetFramework); ValidatePassedTestsContain("DeploymentTestProject.DeploymentTestProject.FailIfFilePresent", "DeploymentTestProject.DeploymentTestProject.PassIfDeclaredFilesPresent"); ValidateFailedTestsContain(true, "DeploymentTestProject.DeploymentTestProject.PassIfFilePresent"); } - public void ValidateTestSourceLocationDeployment_net462() - => ValidateTestSourceLocationDeployment("net462"); - - [SuppressMessage("CodeQuality", "IDE0051:Remove unused private members", Justification = "This is currently ignored and that's why we marked it as private")] - private void ValidateTestSourceLocationDeployment_netcoreapp31() - => ValidateTestSourceLocationDeployment("netcoreapp3.1"); - + [TestMethod] + [DataRow("net462")] + [DataRow("netcoreapp3.1", IgnoreMessage = "This is currently ignored and that's why we marked it as private")] public void ValidateTestSourceLocationDeployment(string targetFramework) { InvokeVsTestForExecution([TestAssetPreserveNewest], RunSetting, "DeploymentTestProject", targetFramework: targetFramework); @@ -45,24 +39,18 @@ public void ValidateTestSourceLocationDeployment(string targetFramework) ValidateFailedTestsContain(true, "DeploymentTestProject.DeploymentTestProject.FailIfFilePresent"); } - public void ValidateDirectoryDeployment_net462() - => ValidateDirectoryDeployment("net462"); - - public void ValidateDirectoryDeployment_netcoreapp31() - => ValidateDirectoryDeployment("netcoreapp3.1"); - + [TestMethod] + [DataRow("net462")] + [DataRow("netcoreapp3.1")] public void ValidateDirectoryDeployment(string targetFramework) { InvokeVsTestForExecution([TestAssetPreserveNewest], testCaseFilter: "DirectoryDeploymentTests", targetFramework: targetFramework); ValidatePassedTestsContain("DeploymentTestProject.PreserveNewest.DirectoryDeploymentTests.DirectoryWithForwardSlash", "DeploymentTestProject.PreserveNewest.DirectoryDeploymentTests.DirectoryWithBackSlash"); } - public void ValidateFileDeployment_net462() - => ValidateFileDeployment("net462"); - - public void ValidateFileDeployment_netcoreapp31() - => ValidateFileDeployment("netcoreapp3.1"); - + [TestMethod] + [DataRow("net462")] + [DataRow("netcoreapp3.1")] public void ValidateFileDeployment(string targetFramework) { InvokeVsTestForExecution([TestAssetPreserveNewest], testCaseFilter: "FileDeploymentTests", targetFramework: targetFramework); diff --git a/test/IntegrationTests/MSTest.VstestConsoleWrapper.IntegrationTests/DesktopCSharpCLITests.cs b/test/IntegrationTests/MSTest.VstestConsoleWrapper.IntegrationTests/DesktopCSharpCLITests.cs index f6dc092dbb..6cf82a8af4 100644 --- a/test/IntegrationTests/MSTest.VstestConsoleWrapper.IntegrationTests/DesktopCSharpCLITests.cs +++ b/test/IntegrationTests/MSTest.VstestConsoleWrapper.IntegrationTests/DesktopCSharpCLITests.cs @@ -5,6 +5,7 @@ namespace MSTest.VstestConsoleWrapper.IntegrationTests; +[TestClass] public class DesktopCSharpCLITests : CLITestBase { private const string X86DebugTestProject = "DesktopTestProjectx86Debug"; @@ -20,48 +21,56 @@ public class DesktopCSharpCLITests : CLITestBase """; + [TestMethod] public void DiscoverTestsx86Debug() { string[] sources = [X86DebugTestProject]; DoDiscoveryAndValidateDiscoveredTests(sources); } + [TestMethod] public void DiscoverTestsx64Debug() { string[] sources = [X64DebugTestProject]; DoDiscoveryAndValidateDiscoveredTests(sources, RunSetting); } + [TestMethod] public void DiscoverTestsx86Release() { string[] sources = [X86ReleaseTestProject]; DoDiscoveryAndValidateDiscoveredTests(sources); } + [TestMethod] public void DiscoverTestsx64Release() { string[] sources = [X64ReleaseTestProject]; DoDiscoveryAndValidateDiscoveredTests(sources, RunSetting); } + [TestMethod] public void RunAllTestsx86Debug() { string[] sources = [X86DebugTestProject]; RunAllTestsAndValidateResults(sources); } + [TestMethod] public void RunAllTestsx64Debug() { string[] sources = [X64DebugTestProject]; RunAllTestsAndValidateResults(sources, RunSetting); } + [TestMethod] public void RunAllTestsx86Release() { string[] sources = [X86ReleaseTestProject]; RunAllTestsAndValidateResults(sources); } + [TestMethod] public void RunAllTestsx64Release() { string[] sources = [X64ReleaseTestProject]; diff --git a/test/IntegrationTests/MSTest.VstestConsoleWrapper.IntegrationTests/FixturesTests.cs b/test/IntegrationTests/MSTest.VstestConsoleWrapper.IntegrationTests/FixturesTests.cs index a9a3cde76c..2396ba5300 100644 --- a/test/IntegrationTests/MSTest.VstestConsoleWrapper.IntegrationTests/FixturesTests.cs +++ b/test/IntegrationTests/MSTest.VstestConsoleWrapper.IntegrationTests/FixturesTests.cs @@ -5,6 +5,7 @@ namespace MSTest.VstestConsoleWrapper.IntegrationTests; +[TestClass] public class FixturesTests : CLITestBase { private const string AssetName = "FixturesTestProject"; @@ -26,6 +27,7 @@ public class FixturesTests : CLITestBase PassingTest ]; + [TestMethod] public void FixturesDisabled_DoesNotReport_FixtureTests() { string runSettings = GetRunSettings(false, true, true, true, true, true); @@ -39,6 +41,7 @@ public void FixturesDisabled_DoesNotReport_FixtureTests() ValidatePassedTests([TestMethod, PassingTest]); } + [TestMethod] public void FixturesEnabled_DoesReport_FixtureTests() { string runSettings = GetRunSettings(true, true, true, true, true, true); @@ -54,6 +57,7 @@ public void FixturesEnabled_DoesReport_FixtureTests() ValidatePassedTests(_tests); } + [TestMethod] public void AssemblyInitialize_Fails_TestMethod_Class_Skipped() { string runSettings = GetRunSettings(true, false, true, true, true, true); @@ -65,6 +69,7 @@ public void AssemblyInitialize_Fails_TestMethod_Class_Skipped() ValidateSkippedTests([ClassInitialize, ClassCleanup]); } + [TestMethod] public void AssemblyCleanup_OnlyFails_AssemblyCleanup() { string runSettings = GetRunSettings(true, true, false, true, true, true); @@ -75,6 +80,7 @@ public void AssemblyCleanup_OnlyFails_AssemblyCleanup() ValidateFailedTests(false, [AssemblyCleanup, TestMethod]); } + [TestMethod] public void ClassInitialize_OnlyFails_ClassInitialize() { string runSettings = GetRunSettings(true, true, true, false, true, true); @@ -84,6 +90,7 @@ public void ClassInitialize_OnlyFails_ClassInitialize() ValidatePassedTests([AssemblyInitialize, AssemblyCleanup, ClassCleanup]); } + [TestMethod] public void ClassCleanup_OnlyFails_ClassCleanup() { string runSettings = GetRunSettings(true, true, true, true, false, true); @@ -94,6 +101,7 @@ public void ClassCleanup_OnlyFails_ClassCleanup() ValidateFailedTests(false, [ClassCleanup, TestMethod]); } + [TestMethod] public void RunOnlyFixtures_DoesNot_Run_Fixtures() { string runSettings = GetRunSettings(true, true, true, true, true, true); @@ -110,6 +118,7 @@ public void RunOnlyFixtures_DoesNot_Run_Fixtures() ValidateSkippedTests([AssemblyCleanup, ClassCleanup]); } + [TestMethod] public void RunSingleTest_Runs_Assembly_And_Class_Fixtures() { string runSettings = GetRunSettings(true, true, true, true, true, true); @@ -118,6 +127,7 @@ public void RunSingleTest_Runs_Assembly_And_Class_Fixtures() ValidatePassedTests([AssemblyInitialize, AssemblyCleanup, ClassInitialize, ClassCleanup, PassingTest]); } + [TestMethod] public void RunSingleTest_AssemblyInitialize_Failure_Skips_ClassFixtures() { string runSettings = GetRunSettings(true, false, true, true, true, true); @@ -129,6 +139,7 @@ public void RunSingleTest_AssemblyInitialize_Failure_Skips_ClassFixtures() ValidateSkippedTests([ClassInitialize, ClassCleanup]); } + [TestMethod] public void RunSingleTest_ClassInitialize_Failure_Runs_AssemblyFixtures() { string runSettings = GetRunSettings(true, true, true, false, true, true); diff --git a/test/IntegrationTests/MSTest.VstestConsoleWrapper.IntegrationTests/MSTest.VstestConsoleWrapper.IntegrationTests.csproj b/test/IntegrationTests/MSTest.VstestConsoleWrapper.IntegrationTests/MSTest.VstestConsoleWrapper.IntegrationTests.csproj index a6fda4dbae..f474a84d3d 100644 --- a/test/IntegrationTests/MSTest.VstestConsoleWrapper.IntegrationTests/MSTest.VstestConsoleWrapper.IntegrationTests.csproj +++ b/test/IntegrationTests/MSTest.VstestConsoleWrapper.IntegrationTests/MSTest.VstestConsoleWrapper.IntegrationTests.csproj @@ -2,14 +2,26 @@ $(NetFrameworkMinimum) - true - - false + true + true Exe + + + Analyzer + false + + + Analyzer + false + + + Analyzer + false + diff --git a/test/IntegrationTests/MSTest.VstestConsoleWrapper.IntegrationTests/ParallelExecutionTests.cs b/test/IntegrationTests/MSTest.VstestConsoleWrapper.IntegrationTests/ParallelExecutionTests.cs index f2af2f9661..c14b3efa9a 100644 --- a/test/IntegrationTests/MSTest.VstestConsoleWrapper.IntegrationTests/ParallelExecutionTests.cs +++ b/test/IntegrationTests/MSTest.VstestConsoleWrapper.IntegrationTests/ParallelExecutionTests.cs @@ -1,12 +1,11 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. -using FluentAssertions.Execution; - using Microsoft.MSTestV2.CLIAutomation; namespace MSTest.VstestConsoleWrapper.IntegrationTests; +[TestClass] public class ParallelExecutionTests : CLITestBase { private const string ClassParallelTestAssetName = "ParallelClassesTestProject"; @@ -15,6 +14,7 @@ public class ParallelExecutionTests : CLITestBase private const int TestMethodWaitTimeInMS = 1000; private const int OverheadTimeInMS = 4000; + [TestMethod] public async Task AllMethodsShouldRunInParallel() { const int maxAttempts = 10; @@ -31,7 +31,7 @@ public async Task AllMethodsShouldRunInParallel() } // Timer validation sometimes get flacky. So retrying the test if it fails. - catch (AssertionFailedException ex) when (i != maxAttempts && ex.Message.Contains("Test Run was expected to not exceed")) + catch (AssertFailedException ex) when (i != maxAttempts && ex.Message.Contains("Test Run was expected to not exceed")) { await Task.Delay(2000); } @@ -48,6 +48,7 @@ public async Task AllMethodsShouldRunInParallel() "ParallelMethodsTestProject.UnitTest2.SimpleTest22"); } + [TestMethod] public void AllClassesShouldRunInParallel() { InvokeVsTestForExecution([ClassParallelTestAssetName]); @@ -70,6 +71,7 @@ public void AllClassesShouldRunInParallel() "ParallelClassesTestProject.UnitTest3.SimpleTest32"); } + [TestMethod] public void NothingShouldRunInParallel() { const string RunSetting = diff --git a/test/IntegrationTests/MSTest.VstestConsoleWrapper.IntegrationTests/Parameterized tests/DataExtensibilityTests.cs b/test/IntegrationTests/MSTest.VstestConsoleWrapper.IntegrationTests/Parameterized tests/DataExtensibilityTests.cs index 44f953da41..572568187c 100644 --- a/test/IntegrationTests/MSTest.VstestConsoleWrapper.IntegrationTests/Parameterized tests/DataExtensibilityTests.cs +++ b/test/IntegrationTests/MSTest.VstestConsoleWrapper.IntegrationTests/Parameterized tests/DataExtensibilityTests.cs @@ -5,10 +5,12 @@ namespace MSTest.VstestConsoleWrapper.IntegrationTests; +[TestClass] public class DataExtensibilityTests : CLITestBase { private const string TestAssetName = "FxExtensibilityTestProject"; + [TestMethod] public void ExecuteTestDataSourceExtensibilityTests() { InvokeVsTestForExecution([TestAssetName]); @@ -16,6 +18,7 @@ public void ExecuteTestDataSourceExtensibilityTests() ValidateFailedTestsContain(false, "FxExtensibilityTestProject.TestDataSourceExTests.CustomEmptyTestDataSourceTestMethod"); } + [TestMethod] public void ExecuteDynamicDataExtensibilityTests() { InvokeVsTestForExecution([TestAssetName]); @@ -41,6 +44,7 @@ public void ExecuteDynamicDataExtensibilityTests() "FxExtensibilityTestProject.DynamicDataExMoreTests.DynamicEmptyDataTestMethod6"); } + [TestMethod] public void ExecuteCustomTestExtensibilityTests() { InvokeVsTestForExecution([TestAssetName]); @@ -60,6 +64,7 @@ public void ExecuteCustomTestExtensibilityTests() "CustomTestClass1 - Execution number 3"); } + [TestMethod] public void ExecuteCustomTestExtensibilityWithTestDataTests() { InvokeVsTestForExecution([TestAssetName], testCaseFilter: "FullyQualifiedName~CustomTestExTests.CustomTestMethod2"); diff --git a/test/IntegrationTests/MSTest.VstestConsoleWrapper.IntegrationTests/Parameterized tests/DataRowTests.cs b/test/IntegrationTests/MSTest.VstestConsoleWrapper.IntegrationTests/Parameterized tests/DataRowTests.cs index 1af7da9450..0493b83be6 100644 --- a/test/IntegrationTests/MSTest.VstestConsoleWrapper.IntegrationTests/Parameterized tests/DataRowTests.cs +++ b/test/IntegrationTests/MSTest.VstestConsoleWrapper.IntegrationTests/Parameterized tests/DataRowTests.cs @@ -5,10 +5,12 @@ namespace MSTest.VstestConsoleWrapper.IntegrationTests; +[TestClass] public class DataRowTests : CLITestBase { private const string TestAssetName = "DataRowTestProject"; + [TestMethod] public void ExecuteOnlyDerivedClassDataRowsWhenBothBaseAndDerivedClassHasDataRows_SimpleDataRows() { InvokeVsTestForExecution([TestAssetName], testCaseFilter: "TestCategory~DataRowSimple"); @@ -26,6 +28,7 @@ public void ExecuteOnlyDerivedClassDataRowsWhenBothBaseAndDerivedClassHasDataRow ValidatePassedTestsCount(5); } + [TestMethod] public void GetDisplayName_AfterOverriding_GetsTheNewDisplayName() { InvokeVsTestForExecution([TestAssetName], testCaseFilter: "TestCategory~OverriddenGetDisplayName"); @@ -36,6 +39,7 @@ public void GetDisplayName_AfterOverriding_GetsTheNewDisplayName() ValidatePassedTestsCount(1); } + [TestMethod] public void ParameterizedTestsWithTestMethodSettingDisplayName_DataIsPrefixWithDisplayName() { InvokeVsTestForExecution([TestAssetName], testCaseFilter: "TestCategory~OverriddenTestMethodDisplayNameForParameterizedTest"); @@ -47,6 +51,7 @@ public void ParameterizedTestsWithTestMethodSettingDisplayName_DataIsPrefixWithD ValidatePassedTestsCount(2); } + [TestMethod] public void ExecuteOnlyDerivedClassDataRowsWhenItOverridesBaseClassDataRows_SimpleDataRows() { InvokeVsTestForExecution([TestAssetName], testCaseFilter: "FullyQualifiedName~DerivedClass&TestCategory~DataRowSimple"); @@ -59,6 +64,7 @@ public void ExecuteOnlyDerivedClassDataRowsWhenItOverridesBaseClassDataRows_Simp ValidatePassedTestsCount(2); } + [TestMethod] public void DataRowsExecuteWithRequiredAndOptionalParameters() { InvokeVsTestForExecution([TestAssetName], testCaseFilter: "TestCategory~DataRowSomeOptional"); @@ -72,6 +78,7 @@ public void DataRowsExecuteWithRequiredAndOptionalParameters() ValidatePassedTestsCount(3); } + [TestMethod] public void DataRowsExecuteWithAllOptionalParameters() { InvokeVsTestForExecution([TestAssetName], testCaseFilter: "TestCategory~DataRowAllOptional"); @@ -86,6 +93,7 @@ public void DataRowsExecuteWithAllOptionalParameters() ValidatePassedTestsCount(4); } + [TestMethod] public void DataRowsExecuteWithParamsArrayParameter() { InvokeVsTestForExecution([TestAssetName], testCaseFilter: "TestCategory~DataRowParamsArgument"); @@ -100,6 +108,7 @@ public void DataRowsExecuteWithParamsArrayParameter() ValidatePassedTestsCount(4); } + [TestMethod] public void DataRowsFailWhenInvalidArgumentsProvided() { InvokeVsTestForExecution([TestAssetName], testCaseFilter: "FullyQualifiedName~DataRowTests_Regular&TestCategory~DataRowOptionalInvalidArguments"); @@ -114,6 +123,7 @@ public void DataRowsFailWhenInvalidArgumentsProvided() ValidateFailedTestsCount(3); } + [TestMethod] public void ExecuteDataRowTests_Enums() { // Arrange & Act @@ -186,6 +196,7 @@ public void ExecuteDataRowTests_Enums() ValidateFailedTestsCount(0); } + [TestMethod] public void ExecuteDataRowTests_NonSerializablePaths() { // Arrange & Act @@ -202,6 +213,7 @@ public void ExecuteDataRowTests_NonSerializablePaths() ValidateFailedTestsCount(0); } + [TestMethod] public void ExecuteRegular_DataRowTests() { // Arrange & Act diff --git a/test/IntegrationTests/MSTest.VstestConsoleWrapper.IntegrationTests/Parameterized tests/DataSourceTests.cs b/test/IntegrationTests/MSTest.VstestConsoleWrapper.IntegrationTests/Parameterized tests/DataSourceTests.cs index 31a41e6d4a..80ff920ce3 100644 --- a/test/IntegrationTests/MSTest.VstestConsoleWrapper.IntegrationTests/Parameterized tests/DataSourceTests.cs +++ b/test/IntegrationTests/MSTest.VstestConsoleWrapper.IntegrationTests/Parameterized tests/DataSourceTests.cs @@ -5,13 +5,14 @@ namespace MSTest.VstestConsoleWrapper.IntegrationTests; +[TestClass] public class DataSourceTests : CLITestBase { private const string TestAssetName = "DataSourceTestProject"; - // TODO @haplois | @evangelink - [SuppressMessage("CodeQuality", "IDE0051:Remove unused private members", Justification = "This test fails under CI - will be fixed in a future PR (marked as private to ignore the test)")] - private void ExecuteCsvTestDataSourceTests() + [TestMethod] + [Ignore("This test fails under CI - will be fixed in a future PR (marked as private to ignore the test)")] + public void ExecuteCsvTestDataSourceTests() { // Arrange & Act InvokeVsTestForExecution( diff --git a/test/IntegrationTests/MSTest.VstestConsoleWrapper.IntegrationTests/Parameterized tests/DynamicDataTests.cs b/test/IntegrationTests/MSTest.VstestConsoleWrapper.IntegrationTests/Parameterized tests/DynamicDataTests.cs index ab9083a04b..b0e6dd89f8 100644 --- a/test/IntegrationTests/MSTest.VstestConsoleWrapper.IntegrationTests/Parameterized tests/DynamicDataTests.cs +++ b/test/IntegrationTests/MSTest.VstestConsoleWrapper.IntegrationTests/Parameterized tests/DynamicDataTests.cs @@ -5,10 +5,12 @@ namespace MSTest.VstestConsoleWrapper.IntegrationTests; +[TestClass] public class DynamicDataTests : CLITestBase { private const string TestAssetName = "DynamicDataTestProject"; + [TestMethod] public void ExecuteDynamicDataTests() { // Arrange & Act diff --git a/test/IntegrationTests/MSTest.VstestConsoleWrapper.IntegrationTests/Program.cs b/test/IntegrationTests/MSTest.VstestConsoleWrapper.IntegrationTests/Program.cs index ce5734f730..e1b9e97e60 100644 --- a/test/IntegrationTests/MSTest.VstestConsoleWrapper.IntegrationTests/Program.cs +++ b/test/IntegrationTests/MSTest.VstestConsoleWrapper.IntegrationTests/Program.cs @@ -3,7 +3,7 @@ using Microsoft.Testing.Extensions; -using TestFramework.ForTestingMSTest; +[assembly: DoNotParallelize] ITestApplicationBuilder builder = await TestApplication.CreateBuilderAsync(args); @@ -16,7 +16,7 @@ builder.AddRetryProvider(); builder.AddAzureDevOpsProvider(); -builder.AddInternalTestFramework(); +builder.AddMSTest(() => [Assembly.GetEntryAssembly()!]); ITestApplication app = await builder.BuildAsync(); return await app.RunAsync(); diff --git a/test/IntegrationTests/MSTest.VstestConsoleWrapper.IntegrationTests/SuiteLifeCycleTests.cs b/test/IntegrationTests/MSTest.VstestConsoleWrapper.IntegrationTests/SuiteLifeCycleTests.cs index c46587f782..605adeb1d0 100644 --- a/test/IntegrationTests/MSTest.VstestConsoleWrapper.IntegrationTests/SuiteLifeCycleTests.cs +++ b/test/IntegrationTests/MSTest.VstestConsoleWrapper.IntegrationTests/SuiteLifeCycleTests.cs @@ -1,155 +1,34 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. -using FluentAssertions; - using Microsoft.MSTestV2.CLIAutomation; +using Microsoft.VisualStudio.TestPlatform.ObjectModel; + +using TestResult = Microsoft.VisualStudio.TestPlatform.ObjectModel.TestResult; namespace MSTest.VstestConsoleWrapper.IntegrationTests; +[TestClass] public class SuiteLifeCycleTests : CLITestBase { private const string TestAssetName = "SuiteLifeCycleTestProject"; private static readonly string[] WindowsLineReturn = ["\r\n"]; - public void ValidateTestRunLifecycle_net6() => ValidateTestRunLifecycle("net6.0"); - - public void ValidateTestRunLifecycle_net462() => ValidateTestRunLifecycle("net462"); - - public void ValidateInheritanceBehavior() - { - InvokeVsTestForExecution( - [TestAssetName], - testCaseFilter: "FullyQualifiedName~LifecycleInheritance", - targetFramework: "net462"); - - RunEventsHandler.PassedTests.Should().HaveCount(10); - - Microsoft.VisualStudio.TestPlatform.ObjectModel.TestResult testMethod1 = RunEventsHandler.PassedTests.Single(x => x.TestCase.FullyQualifiedName.EndsWith("TestClassDerived_EndOfClass.TestMethod", StringComparison.Ordinal)); - testMethod1.Messages[0].Text.Should().Be( - """ - Console: AssemblyInit was called - TestClassBaseEndOfClass: ClassInitialize - TestClassDerived_EndOfClass: TestMethod - TestClassBaseEndOfClass: ClassCleanup - - """); - - Microsoft.VisualStudio.TestPlatform.ObjectModel.TestResult testMethod2 = RunEventsHandler.PassedTests.Single(x => x.TestCase.FullyQualifiedName.EndsWith("TestClassDerived_EndOfAssembly.TestMethod", StringComparison.Ordinal)); - testMethod2.Messages[0].Text.Should().Be( - """ - TestClassBaseEndOfAssembly: ClassInitialize - TestClassDerived_EndOfAssembly: TestMethod - - """); - - Microsoft.VisualStudio.TestPlatform.ObjectModel.TestResult testMethod3 = RunEventsHandler.PassedTests.Single(x => x.TestCase.FullyQualifiedName.EndsWith("TestClassDerivedEndOfClass_EndOfClassEndOfClass.TestMethod", StringComparison.Ordinal)); - testMethod3.Messages[0].Text.Should().Be( - """ - TestClassBaseEndOfClass: ClassInitialize - TestClassIntermediateEndOfClassBaseEndOfClass: ClassInitialize - TestClassDerivedEndOfClass_EndOfClassEndOfClass: TestMethod - TestClassDerivedEndOfClass_EndOfClassEndOfClass: ClassCleanup - TestClassIntermediateEndOfClassBaseEndOfClass: ClassCleanup - TestClassBaseEndOfClass: ClassCleanup - - """); - - Microsoft.VisualStudio.TestPlatform.ObjectModel.TestResult testMethod4 = RunEventsHandler.PassedTests.Single(x => x.TestCase.FullyQualifiedName.EndsWith("TestClassDerived_EndOfClassEndOfClass.TestMethod", StringComparison.Ordinal)); - testMethod4.Messages[0].Text.Should().Be( - """ - TestClassBaseEndOfClass: ClassInitialize - TestClassIntermediateEndOfClassBaseEndOfClass: ClassInitialize - TestClassDerived_EndOfClassEndOfClass: TestMethod - TestClassIntermediateEndOfClassBaseEndOfClass: ClassCleanup - TestClassBaseEndOfClass: ClassCleanup - - """); - - Microsoft.VisualStudio.TestPlatform.ObjectModel.TestResult testMethod5 = RunEventsHandler.PassedTests.Single(x => x.TestCase.FullyQualifiedName.EndsWith("TestClassDerivedEndOfClass_EndOfClassEndOfAssembly.TestMethod", StringComparison.Ordinal)); - testMethod5.Messages[0].Text.Should().Be( - """ - TestClassBaseEndOfAssembly: ClassInitialize - TestClassIntermediateEndOfClassBaseEndOfAssembly: ClassInitialize - TestClassDerivedEndOfClass_EndOfClassEndOfAssembly: TestMethod - TestClassDerivedEndOfClass_EndOfClassEndOfAssembly: ClassCleanup - TestClassIntermediateEndOfClassBaseEndOfAssembly: ClassCleanup - TestClassBaseEndOfAssembly: ClassCleanup - - """); - - Microsoft.VisualStudio.TestPlatform.ObjectModel.TestResult testMethod6 = RunEventsHandler.PassedTests.Single(x => x.TestCase.FullyQualifiedName.EndsWith("TestClassDerived_EndOfClassEndOfAssembly.TestMethod", StringComparison.Ordinal)); - testMethod6.Messages[0].Text.Should().Be( - """ - TestClassBaseEndOfAssembly: ClassInitialize - TestClassIntermediateEndOfClassBaseEndOfAssembly: ClassInitialize - TestClassDerived_EndOfClassEndOfAssembly: TestMethod - TestClassIntermediateEndOfClassBaseEndOfAssembly: ClassCleanup - TestClassBaseEndOfAssembly: ClassCleanup - - """); - - Microsoft.VisualStudio.TestPlatform.ObjectModel.TestResult testMethod7 = RunEventsHandler.PassedTests.Single(x => x.TestCase.FullyQualifiedName.EndsWith("TestClassDerivedEndOfClass_EndOfAssemblyEndOfClass.TestMethod", StringComparison.Ordinal)); - testMethod7.Messages[0].Text.Should().Be( - """ - TestClassBaseEndOfClass: ClassInitialize - TestClassIntermediateEndOfAssemblyBaseEndOfClass: ClassInitialize - TestClassDerivedEndOfClass_EndOfAssemblyEndOfClass: TestMethod - TestClassDerivedEndOfClass_EndOfAssemblyEndOfClass: ClassCleanup - TestClassIntermediateEndOfAssemblyBaseEndOfClass: ClassCleanup - TestClassBaseEndOfClass: ClassCleanup - - """); - - Microsoft.VisualStudio.TestPlatform.ObjectModel.TestResult testMethod8 = RunEventsHandler.PassedTests.Single(x => x.TestCase.FullyQualifiedName.EndsWith("TestClassDerived_EndOfAssemblyEndOfClass.TestMethod", StringComparison.Ordinal)); - testMethod8.Messages[0].Text.Should().Be( - """ - TestClassBaseEndOfClass: ClassInitialize - TestClassIntermediateEndOfAssemblyBaseEndOfClass: ClassInitialize - TestClassDerived_EndOfAssemblyEndOfClass: TestMethod - TestClassIntermediateEndOfAssemblyBaseEndOfClass: ClassCleanup - TestClassBaseEndOfClass: ClassCleanup - - """); - - Microsoft.VisualStudio.TestPlatform.ObjectModel.TestResult testMethod9 = RunEventsHandler.PassedTests.Single(x => x.TestCase.FullyQualifiedName.EndsWith("TestClassDerivedEndOfClass_EndOfAssemblyEndOfAssembly.TestMethod", StringComparison.Ordinal)); - testMethod9.Messages[0].Text.Should().Be( - """ - TestClassBaseEndOfAssembly: ClassInitialize - TestClassIntermediateEndOfAssemblyBaseEndOfAssembly: ClassInitialize - TestClassDerivedEndOfClass_EndOfAssemblyEndOfAssembly: TestMethod - TestClassDerivedEndOfClass_EndOfAssemblyEndOfAssembly: ClassCleanup - TestClassIntermediateEndOfAssemblyBaseEndOfAssembly: ClassCleanup - TestClassBaseEndOfAssembly: ClassCleanup - - """); - - Microsoft.VisualStudio.TestPlatform.ObjectModel.TestResult testMethod10 = RunEventsHandler.PassedTests.Single(x => x.TestCase.FullyQualifiedName.EndsWith("TestClassDerived_EndOfAssemblyEndOfAssembly.TestMethod", StringComparison.Ordinal)); - testMethod10.Messages[0].Text.Should().Be( - """ - TestClassBaseEndOfAssembly: ClassInitialize - TestClassIntermediateEndOfAssemblyBaseEndOfAssembly: ClassInitialize - TestClassDerived_EndOfAssemblyEndOfAssembly: TestMethod - TestClassIntermediateEndOfAssemblyBaseEndOfAssembly: ClassCleanup - TestClassBaseEndOfAssembly: ClassCleanup - TestClassBaseEndOfAssembly: ClassCleanup - Console: AssemblyCleanup was called - - """); - } - - private void ValidateTestRunLifecycle(string targetFramework) + [TestMethod] + [DataRow("net462")] + [DataRow("net6.0")] + public void ValidateTestRunLifecycle(string targetFramework) { InvokeVsTestForExecution( [TestAssetName], testCaseFilter: "FullyQualifiedName~SuiteLifeCycleTestProject", targetFramework: targetFramework); - RunEventsHandler.PassedTests.Should().HaveCount(27); // The inherit class tests are called twice. + Assert.HasCount(27, RunEventsHandler.PassedTests); // The inherit class tests are called twice. - Microsoft.VisualStudio.TestPlatform.ObjectModel.TestResult caseClassCleanup = RunEventsHandler.PassedTests.Single(x => x.TestCase.FullyQualifiedName.Contains("LifeCycleClassCleanup.TestMethod")); - caseClassCleanup.Outcome.Should().Be(Microsoft.VisualStudio.TestPlatform.ObjectModel.TestOutcome.Passed); - caseClassCleanup.Messages.Should().HaveCount(3); - caseClassCleanup.Messages[0].Text.Should().Be( + TestResult caseClassCleanup = RunEventsHandler.PassedTests.Single(x => x.TestCase.FullyQualifiedName.Contains("LifeCycleClassCleanup.TestMethod")); + Assert.AreEqual(TestOutcome.Passed, caseClassCleanup.Outcome); + Assert.HasCount(3, caseClassCleanup.Messages); + Assert.AreEqual( $""" Console: AssemblyInit was called Console: LifeCycleClassCleanup.ClassInitialize was called @@ -161,8 +40,9 @@ private void ValidateTestRunLifecycle(string targetFramework) ? "Console: LifeCycleClassCleanup.DisposeAsync was called\r\nConsole: LifeCycleClassCleanup.Dispose was called" : "Console: LifeCycleClassCleanup.Dispose was called")} - """); - caseClassCleanup.Messages[1].Text.Should().Be( + """, + caseClassCleanup.Messages[0].Text); + Assert.AreEqual( $""" @@ -179,8 +59,9 @@ private void ValidateTestRunLifecycle(string targetFramework) + GenerateTraceDebugPrefixedMessage("LifeCycleClassCleanup.Dispose was called") : GenerateTraceDebugPrefixedMessage("LifeCycleClassCleanup.Dispose was called"))} - """); - caseClassCleanup.Messages[2].Text.Should().Be( + """, + caseClassCleanup.Messages[1].Text); + Assert.AreEqual( $""" @@ -195,15 +76,16 @@ LifeCycleClassCleanup.TestCleanup was called ? "LifeCycleClassCleanup.DisposeAsync was called\r\nLifeCycleClassCleanup.Dispose was called" : "LifeCycleClassCleanup.Dispose was called")} - """); + """, + caseClassCleanup.Messages[2].Text); - Microsoft.VisualStudio.TestPlatform.ObjectModel.TestResult caseClassCleanupEndOfAssembly = RunEventsHandler.PassedTests.Single(x => x.TestCase.FullyQualifiedName.Contains("LifeCycleClassCleanupEndOfAssembly.TestMethod")); - caseClassCleanupEndOfAssembly.Outcome.Should().Be(Microsoft.VisualStudio.TestPlatform.ObjectModel.TestOutcome.Passed); + TestResult caseClassCleanupEndOfAssembly = RunEventsHandler.PassedTests.Single(x => x.TestCase.FullyQualifiedName.Contains("LifeCycleClassCleanupEndOfAssembly.TestMethod")); + Assert.AreEqual(TestOutcome.Passed, caseClassCleanupEndOfAssembly.Outcome); // We don't see "LifeCycleClassCleanupEndOfAssembly.ClassCleanup was called" because it will be attached to the // latest test run. - caseClassCleanupEndOfAssembly.Messages.Should().HaveCount(3); - caseClassCleanupEndOfAssembly.Messages[0].Text.Should().Be( + Assert.HasCount(3, caseClassCleanupEndOfAssembly.Messages); + Assert.AreEqual( $""" Console: LifeCycleClassCleanupEndOfAssembly.ClassInitialize was called Console: LifeCycleClassCleanupEndOfAssembly.ctor was called @@ -214,8 +96,9 @@ LifeCycleClassCleanup.TestCleanup was called ? "Console: LifeCycleClassCleanupEndOfAssembly.DisposeAsync was called\r\nConsole: LifeCycleClassCleanupEndOfAssembly.Dispose was called" : "Console: LifeCycleClassCleanupEndOfAssembly.Dispose was called")} - """); - caseClassCleanupEndOfAssembly.Messages[1].Text.Should().Be( + """, + caseClassCleanupEndOfAssembly.Messages[0].Text); + Assert.AreEqual( $""" @@ -231,8 +114,9 @@ LifeCycleClassCleanup.TestCleanup was called + GenerateTraceDebugPrefixedMessage("LifeCycleClassCleanupEndOfAssembly.Dispose was called") : GenerateTraceDebugPrefixedMessage("LifeCycleClassCleanupEndOfAssembly.Dispose was called"))} - """); - caseClassCleanupEndOfAssembly.Messages[2].Text.Should().Be( + """, + caseClassCleanupEndOfAssembly.Messages[1].Text); + Assert.AreEqual( $""" @@ -246,12 +130,13 @@ LifeCycleClassCleanupEndOfAssembly.TestCleanup was called ? "LifeCycleClassCleanupEndOfAssembly.DisposeAsync was called\r\nLifeCycleClassCleanupEndOfAssembly.Dispose was called" : "LifeCycleClassCleanupEndOfAssembly.Dispose was called")} - """); + """, + caseClassCleanupEndOfAssembly.Messages[2].Text); - Microsoft.VisualStudio.TestPlatform.ObjectModel.TestResult caseClassCleanupEndOfClass = RunEventsHandler.PassedTests.Single(x => x.TestCase.FullyQualifiedName.Contains("LifeCycleClassCleanupEndOfClass.TestMethod")); - caseClassCleanupEndOfClass.Outcome.Should().Be(Microsoft.VisualStudio.TestPlatform.ObjectModel.TestOutcome.Passed); - caseClassCleanupEndOfClass.Messages.Should().HaveCount(3); - caseClassCleanupEndOfClass.Messages[0].Text.Should().Be( + TestResult caseClassCleanupEndOfClass = RunEventsHandler.PassedTests.Single(x => x.TestCase.FullyQualifiedName.Contains("LifeCycleClassCleanupEndOfClass.TestMethod")); + Assert.AreEqual(TestOutcome.Passed, caseClassCleanupEndOfClass.Outcome); + Assert.HasCount(3, caseClassCleanupEndOfClass.Messages); + Assert.AreEqual( $""" Console: LifeCycleClassCleanupEndOfClass.ClassInitialize was called Console: LifeCycleClassCleanupEndOfClass.ctor was called @@ -263,8 +148,9 @@ LifeCycleClassCleanupEndOfAssembly.TestCleanup was called : "Console: LifeCycleClassCleanupEndOfClass.Dispose was called")} Console: LifeCycleClassCleanupEndOfClass.ClassCleanup was called - """); - caseClassCleanupEndOfClass.Messages[1].Text.Should().Be( + """, + caseClassCleanupEndOfClass.Messages[0].Text); + Assert.AreEqual( $""" @@ -281,8 +167,9 @@ LifeCycleClassCleanupEndOfAssembly.TestCleanup was called : GenerateTraceDebugPrefixedMessage("LifeCycleClassCleanupEndOfClass.Dispose was called"))} {GenerateTraceDebugPrefixedMessage("LifeCycleClassCleanupEndOfClass.ClassCleanup was called")} - """); - caseClassCleanupEndOfClass.Messages[2].Text.Should().Be( + """, + caseClassCleanupEndOfClass.Messages[1].Text); + Assert.AreEqual( $""" @@ -297,12 +184,13 @@ LifeCycleClassCleanupEndOfClass.TestCleanup was called : "LifeCycleClassCleanupEndOfClass.Dispose was called")} LifeCycleClassCleanupEndOfClass.ClassCleanup was called - """); + """, + caseClassCleanupEndOfClass.Messages[2].Text); - Microsoft.VisualStudio.TestPlatform.ObjectModel.TestResult caseClassInitializeAndCleanupBeforeEachDerivedClass = RunEventsHandler.PassedTests.Single(x => x.TestCase.FullyQualifiedName.Contains("LifeCycleClassInitializeAndCleanupBeforeEachDerivedClass.TestMethod")); - caseClassInitializeAndCleanupBeforeEachDerivedClass.Outcome.Should().Be(Microsoft.VisualStudio.TestPlatform.ObjectModel.TestOutcome.Passed); - caseClassInitializeAndCleanupBeforeEachDerivedClass.Messages.Should().HaveCount(3); - caseClassInitializeAndCleanupBeforeEachDerivedClass.Messages[0].Text.Should().Be( + TestResult caseClassInitializeAndCleanupBeforeEachDerivedClass = RunEventsHandler.PassedTests.Single(x => x.TestCase.FullyQualifiedName.Contains("LifeCycleClassInitializeAndCleanupBeforeEachDerivedClass.TestMethod")); + Assert.AreEqual(TestOutcome.Passed, caseClassInitializeAndCleanupBeforeEachDerivedClass.Outcome); + Assert.HasCount(3, caseClassInitializeAndCleanupBeforeEachDerivedClass.Messages); + Assert.AreEqual( $""" Console: LifeCycleClassInitializeAndCleanupBeforeEachDerivedClass.ClassInitialize was called Console: LifeCycleClassInitializeAndCleanupBeforeEachDerivedClass.ctor was called @@ -313,8 +201,9 @@ LifeCycleClassCleanupEndOfClass.ClassCleanup was called ? "Console: LifeCycleClassInitializeAndCleanupBeforeEachDerivedClass.DisposeAsync was called\r\nConsole: LifeCycleClassInitializeAndCleanupBeforeEachDerivedClass.Dispose was called" : "Console: LifeCycleClassInitializeAndCleanupBeforeEachDerivedClass.Dispose was called")} - """); - caseClassInitializeAndCleanupBeforeEachDerivedClass.Messages[1].Text.Should().Be( + """, + caseClassInitializeAndCleanupBeforeEachDerivedClass.Messages[0].Text); + Assert.AreEqual( $""" @@ -330,8 +219,9 @@ LifeCycleClassCleanupEndOfClass.ClassCleanup was called + GenerateTraceDebugPrefixedMessage("LifeCycleClassInitializeAndCleanupBeforeEachDerivedClass.Dispose was called") : GenerateTraceDebugPrefixedMessage("LifeCycleClassInitializeAndCleanupBeforeEachDerivedClass.Dispose was called"))} - """); - caseClassInitializeAndCleanupBeforeEachDerivedClass.Messages[2].Text.Should().Be( + """, + caseClassInitializeAndCleanupBeforeEachDerivedClass.Messages[1].Text); + Assert.AreEqual( $""" @@ -345,12 +235,13 @@ LifeCycleClassInitializeAndCleanupBeforeEachDerivedClass.TestCleanup was called ? "LifeCycleClassInitializeAndCleanupBeforeEachDerivedClass.DisposeAsync was called\r\nLifeCycleClassInitializeAndCleanupBeforeEachDerivedClass.Dispose was called" : "LifeCycleClassInitializeAndCleanupBeforeEachDerivedClass.Dispose was called")} - """); + """, + caseClassInitializeAndCleanupBeforeEachDerivedClass.Messages[2].Text); - Microsoft.VisualStudio.TestPlatform.ObjectModel.TestResult caseClassInitializeAndCleanupNone = RunEventsHandler.PassedTests.Single(x => x.TestCase.FullyQualifiedName.Contains("LifeCycleClassInitializeAndCleanupNone.TestMethod")); - caseClassInitializeAndCleanupNone.Outcome.Should().Be(Microsoft.VisualStudio.TestPlatform.ObjectModel.TestOutcome.Passed); - caseClassInitializeAndCleanupNone.Messages.Should().HaveCount(3); - caseClassInitializeAndCleanupNone.Messages[0].Text.Should().Be( + TestResult caseClassInitializeAndCleanupNone = RunEventsHandler.PassedTests.Single(x => x.TestCase.FullyQualifiedName.Contains("LifeCycleClassInitializeAndCleanupNone.TestMethod")); + Assert.AreEqual(TestOutcome.Passed, caseClassInitializeAndCleanupNone.Outcome); + Assert.HasCount(3, caseClassInitializeAndCleanupNone.Messages); + Assert.AreEqual( $""" Console: LifeCycleClassInitializeAndCleanupNone.ClassInitialize was called Console: LifeCycleClassInitializeAndCleanupNone.ctor was called @@ -361,8 +252,9 @@ LifeCycleClassInitializeAndCleanupBeforeEachDerivedClass.TestCleanup was called ? "Console: LifeCycleClassInitializeAndCleanupNone.DisposeAsync was called\r\nConsole: LifeCycleClassInitializeAndCleanupNone.Dispose was called" : "Console: LifeCycleClassInitializeAndCleanupNone.Dispose was called")} - """); - caseClassInitializeAndCleanupNone.Messages[1].Text.Should().Be( + """, + caseClassInitializeAndCleanupNone.Messages[0].Text); + Assert.AreEqual( $""" @@ -378,8 +270,9 @@ LifeCycleClassInitializeAndCleanupBeforeEachDerivedClass.TestCleanup was called + GenerateTraceDebugPrefixedMessage("LifeCycleClassInitializeAndCleanupNone.Dispose was called") : GenerateTraceDebugPrefixedMessage("LifeCycleClassInitializeAndCleanupNone.Dispose was called"))} - """); - caseClassInitializeAndCleanupNone.Messages[2].Text.Should().Be( + """, + caseClassInitializeAndCleanupNone.Messages[1].Text); + Assert.AreEqual( $""" @@ -393,12 +286,13 @@ LifeCycleClassInitializeAndCleanupNone.TestCleanup was called ? "LifeCycleClassInitializeAndCleanupNone.DisposeAsync was called\r\nLifeCycleClassInitializeAndCleanupNone.Dispose was called" : "LifeCycleClassInitializeAndCleanupNone.Dispose was called")} - """); + """, + caseClassInitializeAndCleanupNone.Messages[2].Text); - Microsoft.VisualStudio.TestPlatform.ObjectModel.TestResult caseClassInitializeBeforeEachDerivedClassAndClassCleanupNone = RunEventsHandler.PassedTests.Single(x => x.TestCase.FullyQualifiedName.Contains("LifeCycleClassInitializeBeforeEachDerivedClassAndClassCleanupNone")); - caseClassInitializeBeforeEachDerivedClassAndClassCleanupNone.Outcome.Should().Be(Microsoft.VisualStudio.TestPlatform.ObjectModel.TestOutcome.Passed); - caseClassInitializeBeforeEachDerivedClassAndClassCleanupNone.Messages.Should().HaveCount(3); - caseClassInitializeBeforeEachDerivedClassAndClassCleanupNone.Messages[0].Text.Should().Be( + TestResult caseClassInitializeBeforeEachDerivedClassAndClassCleanupNone = RunEventsHandler.PassedTests.Single(x => x.TestCase.FullyQualifiedName.Contains("LifeCycleClassInitializeBeforeEachDerivedClassAndClassCleanupNone")); + Assert.AreEqual(TestOutcome.Passed, caseClassInitializeBeforeEachDerivedClassAndClassCleanupNone.Outcome); + Assert.HasCount(3, caseClassInitializeBeforeEachDerivedClassAndClassCleanupNone.Messages); + Assert.AreEqual( $""" Console: LifeCycleClassInitializeBeforeEachDerivedClassAndClassCleanupNone.ClassInitialize was called Console: LifeCycleClassInitializeBeforeEachDerivedClassAndClassCleanupNone.ctor was called @@ -409,8 +303,9 @@ LifeCycleClassInitializeAndCleanupNone.TestCleanup was called ? "Console: LifeCycleClassInitializeBeforeEachDerivedClassAndClassCleanupNone.DisposeAsync was called\r\nConsole: LifeCycleClassInitializeBeforeEachDerivedClassAndClassCleanupNone.Dispose was called" : "Console: LifeCycleClassInitializeBeforeEachDerivedClassAndClassCleanupNone.Dispose was called")} - """); - caseClassInitializeBeforeEachDerivedClassAndClassCleanupNone.Messages[1].Text.Should().Be( + """, + caseClassInitializeBeforeEachDerivedClassAndClassCleanupNone.Messages[0].Text); + Assert.AreEqual( $""" @@ -426,8 +321,9 @@ LifeCycleClassInitializeAndCleanupNone.TestCleanup was called + GenerateTraceDebugPrefixedMessage("LifeCycleClassInitializeBeforeEachDerivedClassAndClassCleanupNone.Dispose was called") : GenerateTraceDebugPrefixedMessage("LifeCycleClassInitializeBeforeEachDerivedClassAndClassCleanupNone.Dispose was called"))} - """); - caseClassInitializeBeforeEachDerivedClassAndClassCleanupNone.Messages[2].Text.Should().Be( + """, + caseClassInitializeBeforeEachDerivedClassAndClassCleanupNone.Messages[1].Text); + Assert.AreEqual( $""" @@ -441,12 +337,13 @@ LifeCycleClassInitializeBeforeEachDerivedClassAndClassCleanupNone.TestCleanup wa ? "LifeCycleClassInitializeBeforeEachDerivedClassAndClassCleanupNone.DisposeAsync was called\r\nLifeCycleClassInitializeBeforeEachDerivedClassAndClassCleanupNone.Dispose was called" : "LifeCycleClassInitializeBeforeEachDerivedClassAndClassCleanupNone.Dispose was called")} - """); + """, + caseClassInitializeBeforeEachDerivedClassAndClassCleanupNone.Messages[2].Text); - Microsoft.VisualStudio.TestPlatform.ObjectModel.TestResult caseClassInitializeNoneAndClassCleanupBeforeEachDerivedClass = RunEventsHandler.PassedTests.Single(x => x.TestCase.FullyQualifiedName.Contains("LifeCycleClassInitializeNoneAndClassCleanupBeforeEachDerivedClass")); - caseClassInitializeNoneAndClassCleanupBeforeEachDerivedClass.Outcome.Should().Be(Microsoft.VisualStudio.TestPlatform.ObjectModel.TestOutcome.Passed); - caseClassInitializeNoneAndClassCleanupBeforeEachDerivedClass.Messages.Should().HaveCount(3); - caseClassInitializeNoneAndClassCleanupBeforeEachDerivedClass.Messages[0].Text.Should().Be( + TestResult caseClassInitializeNoneAndClassCleanupBeforeEachDerivedClass = RunEventsHandler.PassedTests.Single(x => x.TestCase.FullyQualifiedName.Contains("LifeCycleClassInitializeNoneAndClassCleanupBeforeEachDerivedClass")); + Assert.AreEqual(TestOutcome.Passed, caseClassInitializeNoneAndClassCleanupBeforeEachDerivedClass.Outcome); + Assert.HasCount(3, caseClassInitializeNoneAndClassCleanupBeforeEachDerivedClass.Messages); + Assert.AreEqual( $""" Console: LifeCycleClassInitializeNoneAndClassCleanupBeforeEachDerivedClass.ClassInitialize was called Console: LifeCycleClassInitializeNoneAndClassCleanupBeforeEachDerivedClass.ctor was called @@ -457,8 +354,9 @@ LifeCycleClassInitializeBeforeEachDerivedClassAndClassCleanupNone.TestCleanup wa ? "Console: LifeCycleClassInitializeNoneAndClassCleanupBeforeEachDerivedClass.DisposeAsync was called\r\nConsole: LifeCycleClassInitializeNoneAndClassCleanupBeforeEachDerivedClass.Dispose was called" : "Console: LifeCycleClassInitializeNoneAndClassCleanupBeforeEachDerivedClass.Dispose was called")} - """); - caseClassInitializeNoneAndClassCleanupBeforeEachDerivedClass.Messages[1].Text.Should().Be( + """, + caseClassInitializeNoneAndClassCleanupBeforeEachDerivedClass.Messages[0].Text); + Assert.AreEqual( $""" @@ -474,8 +372,9 @@ LifeCycleClassInitializeBeforeEachDerivedClassAndClassCleanupNone.TestCleanup wa + GenerateTraceDebugPrefixedMessage("LifeCycleClassInitializeNoneAndClassCleanupBeforeEachDerivedClass.Dispose was called") : GenerateTraceDebugPrefixedMessage("LifeCycleClassInitializeNoneAndClassCleanupBeforeEachDerivedClass.Dispose was called"))} - """); - caseClassInitializeNoneAndClassCleanupBeforeEachDerivedClass.Messages[2].Text.Should().Be( + """, + caseClassInitializeNoneAndClassCleanupBeforeEachDerivedClass.Messages[1].Text); + Assert.AreEqual( $""" @@ -489,12 +388,13 @@ LifeCycleClassInitializeNoneAndClassCleanupBeforeEachDerivedClass.TestCleanup wa ? "LifeCycleClassInitializeNoneAndClassCleanupBeforeEachDerivedClass.DisposeAsync was called\r\nLifeCycleClassInitializeNoneAndClassCleanupBeforeEachDerivedClass.Dispose was called" : "LifeCycleClassInitializeNoneAndClassCleanupBeforeEachDerivedClass.Dispose was called")} - """); + """, + caseClassInitializeNoneAndClassCleanupBeforeEachDerivedClass.Messages[2].Text); - Microsoft.VisualStudio.TestPlatform.ObjectModel.TestResult caseDerivedClassInitializeAndCleanupBeforeEachDerivedClass = RunEventsHandler.PassedTests.Single(x => x.TestCase.FullyQualifiedName.Contains("LifeCycleDerivedClassInitializeAndCleanupBeforeEachDerivedClass.DerivedClassTestMethod")); - caseDerivedClassInitializeAndCleanupBeforeEachDerivedClass.Outcome.Should().Be(Microsoft.VisualStudio.TestPlatform.ObjectModel.TestOutcome.Passed); - caseDerivedClassInitializeAndCleanupBeforeEachDerivedClass.Messages.Should().HaveCount(3); - caseDerivedClassInitializeAndCleanupBeforeEachDerivedClass.Messages[0].Text.Should().Be( + TestResult caseDerivedClassInitializeAndCleanupBeforeEachDerivedClass = RunEventsHandler.PassedTests.Single(x => x.TestCase.FullyQualifiedName.Contains("LifeCycleDerivedClassInitializeAndCleanupBeforeEachDerivedClass.DerivedClassTestMethod")); + Assert.AreEqual(TestOutcome.Passed, caseDerivedClassInitializeAndCleanupBeforeEachDerivedClass.Outcome); + Assert.HasCount(3, caseDerivedClassInitializeAndCleanupBeforeEachDerivedClass.Messages); + Assert.AreEqual( $""" Console: LifeCycleClassInitializeAndCleanupBeforeEachDerivedClass.ClassInitialize was called Console: LifeCycleDerivedClassInitializeAndCleanupBeforeEachDerivedClass.ClassInitialize was called @@ -509,8 +409,9 @@ LifeCycleClassInitializeNoneAndClassCleanupBeforeEachDerivedClass.TestCleanup wa ? "Console: LifeCycleClassInitializeAndCleanupBeforeEachDerivedClass.DisposeAsync was called\r\nConsole: LifeCycleClassInitializeAndCleanupBeforeEachDerivedClass.Dispose was called" : "Console: LifeCycleClassInitializeAndCleanupBeforeEachDerivedClass.Dispose was called")} - """); - caseDerivedClassInitializeAndCleanupBeforeEachDerivedClass.Messages[1].Text.Should().Be( + """, + caseDerivedClassInitializeAndCleanupBeforeEachDerivedClass.Messages[0].Text); + Assert.AreEqual( $""" @@ -530,8 +431,9 @@ LifeCycleClassInitializeNoneAndClassCleanupBeforeEachDerivedClass.TestCleanup wa + GenerateTraceDebugPrefixedMessage("LifeCycleClassInitializeAndCleanupBeforeEachDerivedClass.Dispose was called") : GenerateTraceDebugPrefixedMessage("LifeCycleClassInitializeAndCleanupBeforeEachDerivedClass.Dispose was called"))} - """); - caseDerivedClassInitializeAndCleanupBeforeEachDerivedClass.Messages[2].Text.Should().Be( + """, + caseDerivedClassInitializeAndCleanupBeforeEachDerivedClass.Messages[1].Text); + Assert.AreEqual( $""" @@ -549,13 +451,14 @@ LifeCycleClassInitializeAndCleanupBeforeEachDerivedClass.TestCleanup was called ? "LifeCycleClassInitializeAndCleanupBeforeEachDerivedClass.DisposeAsync was called\r\nLifeCycleClassInitializeAndCleanupBeforeEachDerivedClass.Dispose was called" : "LifeCycleClassInitializeAndCleanupBeforeEachDerivedClass.Dispose was called")} - """); + """, + caseDerivedClassInitializeAndCleanupBeforeEachDerivedClass.Messages[2].Text); // Test the parent test method. - Microsoft.VisualStudio.TestPlatform.ObjectModel.TestResult caseDerivedClassInitializeAndCleanupBeforeEachDerivedClassParentTestMethod = RunEventsHandler.PassedTests.Single(x => x.TestCase.FullyQualifiedName.Contains("LifeCycleDerivedClassInitializeAndCleanupBeforeEachDerivedClass.TestMethod")); - caseDerivedClassInitializeAndCleanupBeforeEachDerivedClassParentTestMethod.Outcome.Should().Be(Microsoft.VisualStudio.TestPlatform.ObjectModel.TestOutcome.Passed); - caseDerivedClassInitializeAndCleanupBeforeEachDerivedClassParentTestMethod.Messages.Should().HaveCount(3); - caseDerivedClassInitializeAndCleanupBeforeEachDerivedClassParentTestMethod.Messages[0].Text.Should().Be( + TestResult caseDerivedClassInitializeAndCleanupBeforeEachDerivedClassParentTestMethod = RunEventsHandler.PassedTests.Single(x => x.TestCase.FullyQualifiedName.Contains("LifeCycleDerivedClassInitializeAndCleanupBeforeEachDerivedClass.TestMethod")); + Assert.AreEqual(TestOutcome.Passed, caseDerivedClassInitializeAndCleanupBeforeEachDerivedClassParentTestMethod.Outcome); + Assert.HasCount(3, caseDerivedClassInitializeAndCleanupBeforeEachDerivedClassParentTestMethod.Messages); + Assert.AreEqual( $""" Console: LifeCycleClassInitializeAndCleanupBeforeEachDerivedClass.ctor was called Console: LifeCycleDerivedClassInitializeAndCleanupBeforeEachDerivedClass.ctor was called @@ -568,8 +471,9 @@ LifeCycleClassInitializeAndCleanupBeforeEachDerivedClass.TestCleanup was called ? "Console: LifeCycleClassInitializeAndCleanupBeforeEachDerivedClass.DisposeAsync was called\r\nConsole: LifeCycleClassInitializeAndCleanupBeforeEachDerivedClass.Dispose was called" : "Console: LifeCycleClassInitializeAndCleanupBeforeEachDerivedClass.Dispose was called")} - """); - caseDerivedClassInitializeAndCleanupBeforeEachDerivedClassParentTestMethod.Messages[1].Text.Should().Be( + """, + caseDerivedClassInitializeAndCleanupBeforeEachDerivedClassParentTestMethod.Messages[0].Text); + Assert.AreEqual( $""" @@ -587,8 +491,9 @@ LifeCycleClassInitializeAndCleanupBeforeEachDerivedClass.TestCleanup was called + GenerateTraceDebugPrefixedMessage("LifeCycleClassInitializeAndCleanupBeforeEachDerivedClass.Dispose was called") : GenerateTraceDebugPrefixedMessage("LifeCycleClassInitializeAndCleanupBeforeEachDerivedClass.Dispose was called"))} - """); - caseDerivedClassInitializeAndCleanupBeforeEachDerivedClassParentTestMethod.Messages[2].Text.Should().Be( + """, + caseDerivedClassInitializeAndCleanupBeforeEachDerivedClassParentTestMethod.Messages[1].Text); + Assert.AreEqual( $""" @@ -604,12 +509,13 @@ LifeCycleClassInitializeAndCleanupBeforeEachDerivedClass.TestCleanup was called ? "LifeCycleClassInitializeAndCleanupBeforeEachDerivedClass.DisposeAsync was called\r\nLifeCycleClassInitializeAndCleanupBeforeEachDerivedClass.Dispose was called" : "LifeCycleClassInitializeAndCleanupBeforeEachDerivedClass.Dispose was called")} - """); + """, + caseDerivedClassInitializeAndCleanupBeforeEachDerivedClassParentTestMethod.Messages[2].Text); - Microsoft.VisualStudio.TestPlatform.ObjectModel.TestResult caseDerivedClassInitializeAndCleanupNone = RunEventsHandler.PassedTests.Single(x => x.TestCase.FullyQualifiedName.Contains("LifeCycleDerivedClassInitializeAndCleanupNone.DerivedClassTestMethod")); - caseDerivedClassInitializeAndCleanupNone.Outcome.Should().Be(Microsoft.VisualStudio.TestPlatform.ObjectModel.TestOutcome.Passed); - caseDerivedClassInitializeAndCleanupNone.Messages.Should().HaveCount(3); - caseDerivedClassInitializeAndCleanupNone.Messages[0].Text.Should().Be( + TestResult caseDerivedClassInitializeAndCleanupNone = RunEventsHandler.PassedTests.Single(x => x.TestCase.FullyQualifiedName.Contains("LifeCycleDerivedClassInitializeAndCleanupNone.DerivedClassTestMethod")); + Assert.AreEqual(TestOutcome.Passed, caseDerivedClassInitializeAndCleanupNone.Outcome); + Assert.HasCount(3, caseDerivedClassInitializeAndCleanupNone.Messages); + Assert.AreEqual( $""" Console: LifeCycleDerivedClassInitializeAndCleanupNone.ClassInitialize was called Console: LifeCycleClassInitializeAndCleanupNone.ctor was called @@ -623,8 +529,9 @@ LifeCycleClassInitializeAndCleanupBeforeEachDerivedClass.TestCleanup was called ? "Console: LifeCycleClassInitializeAndCleanupNone.DisposeAsync was called\r\nConsole: LifeCycleClassInitializeAndCleanupNone.Dispose was called" : "Console: LifeCycleClassInitializeAndCleanupNone.Dispose was called")} - """); - caseDerivedClassInitializeAndCleanupNone.Messages[1].Text.Should().Be( + """, + caseDerivedClassInitializeAndCleanupNone.Messages[0].Text); + Assert.AreEqual( $""" @@ -643,8 +550,9 @@ LifeCycleClassInitializeAndCleanupBeforeEachDerivedClass.TestCleanup was called + GenerateTraceDebugPrefixedMessage("LifeCycleClassInitializeAndCleanupNone.Dispose was called") : GenerateTraceDebugPrefixedMessage("LifeCycleClassInitializeAndCleanupNone.Dispose was called"))} - """); - caseDerivedClassInitializeAndCleanupNone.Messages[2].Text.Should().Be( + """, + caseDerivedClassInitializeAndCleanupNone.Messages[1].Text); + Assert.AreEqual( $""" @@ -661,13 +569,14 @@ LifeCycleClassInitializeAndCleanupNone.TestCleanup was called ? "LifeCycleClassInitializeAndCleanupNone.DisposeAsync was called\r\nLifeCycleClassInitializeAndCleanupNone.Dispose was called" : "LifeCycleClassInitializeAndCleanupNone.Dispose was called")} - """); + """, + caseDerivedClassInitializeAndCleanupNone.Messages[2].Text); // Test the parent test method. - Microsoft.VisualStudio.TestPlatform.ObjectModel.TestResult caseDerivedClassInitializeAndCleanupNoneParentTestMethod = RunEventsHandler.PassedTests.Single(x => x.TestCase.FullyQualifiedName.Contains("LifeCycleDerivedClassInitializeAndCleanupNone.TestMethod")); - caseDerivedClassInitializeAndCleanupNoneParentTestMethod.Outcome.Should().Be(Microsoft.VisualStudio.TestPlatform.ObjectModel.TestOutcome.Passed); - caseDerivedClassInitializeAndCleanupNoneParentTestMethod.Messages.Should().HaveCount(3); - caseDerivedClassInitializeAndCleanupNoneParentTestMethod.Messages[0].Text.Should().Be( + TestResult caseDerivedClassInitializeAndCleanupNoneParentTestMethod = RunEventsHandler.PassedTests.Single(x => x.TestCase.FullyQualifiedName.Contains("LifeCycleDerivedClassInitializeAndCleanupNone.TestMethod")); + Assert.AreEqual(TestOutcome.Passed, caseDerivedClassInitializeAndCleanupNoneParentTestMethod.Outcome); + Assert.HasCount(3, caseDerivedClassInitializeAndCleanupNoneParentTestMethod.Messages); + Assert.AreEqual( $""" Console: LifeCycleClassInitializeAndCleanupNone.ctor was called Console: LifeCycleDerivedClassInitializeAndCleanupNone.ctor was called @@ -680,8 +589,9 @@ LifeCycleClassInitializeAndCleanupNone.TestCleanup was called ? "Console: LifeCycleClassInitializeAndCleanupNone.DisposeAsync was called\r\nConsole: LifeCycleClassInitializeAndCleanupNone.Dispose was called" : "Console: LifeCycleClassInitializeAndCleanupNone.Dispose was called")} - """); - caseDerivedClassInitializeAndCleanupNoneParentTestMethod.Messages[1].Text.Should().Be( + """, + caseDerivedClassInitializeAndCleanupNoneParentTestMethod.Messages[0].Text); + Assert.AreEqual( $""" @@ -699,8 +609,9 @@ LifeCycleClassInitializeAndCleanupNone.TestCleanup was called + GenerateTraceDebugPrefixedMessage("LifeCycleClassInitializeAndCleanupNone.Dispose was called") : GenerateTraceDebugPrefixedMessage("LifeCycleClassInitializeAndCleanupNone.Dispose was called"))} - """); - caseDerivedClassInitializeAndCleanupNoneParentTestMethod.Messages[2].Text.Should().Be( + """, + caseDerivedClassInitializeAndCleanupNoneParentTestMethod.Messages[1].Text); + Assert.AreEqual( $""" @@ -716,12 +627,13 @@ LifeCycleClassInitializeAndCleanupNone.TestCleanup was called ? "LifeCycleClassInitializeAndCleanupNone.DisposeAsync was called\r\nLifeCycleClassInitializeAndCleanupNone.Dispose was called" : "LifeCycleClassInitializeAndCleanupNone.Dispose was called")} - """); + """, + caseDerivedClassInitializeAndCleanupNoneParentTestMethod.Messages[2].Text); - Microsoft.VisualStudio.TestPlatform.ObjectModel.TestResult caseDerivedClassInitializeBeforeEachDerivedClassAndClassCleanupNone = RunEventsHandler.PassedTests.Single(x => x.TestCase.FullyQualifiedName.Contains("LifeCycleDerivedClassInitializeBeforeEachDerivedClassAndClassCleanupNone.DerivedClassTestMethod")); - caseDerivedClassInitializeBeforeEachDerivedClassAndClassCleanupNone.Outcome.Should().Be(Microsoft.VisualStudio.TestPlatform.ObjectModel.TestOutcome.Passed); - caseDerivedClassInitializeBeforeEachDerivedClassAndClassCleanupNone.Messages.Should().HaveCount(3); - caseDerivedClassInitializeBeforeEachDerivedClassAndClassCleanupNone.Messages[0].Text.Should().Be( + TestResult caseDerivedClassInitializeBeforeEachDerivedClassAndClassCleanupNone = RunEventsHandler.PassedTests.Single(x => x.TestCase.FullyQualifiedName.Contains("LifeCycleDerivedClassInitializeBeforeEachDerivedClassAndClassCleanupNone.DerivedClassTestMethod")); + Assert.AreEqual(TestOutcome.Passed, caseDerivedClassInitializeBeforeEachDerivedClassAndClassCleanupNone.Outcome); + Assert.HasCount(3, caseDerivedClassInitializeBeforeEachDerivedClassAndClassCleanupNone.Messages); + Assert.AreEqual( $""" Console: LifeCycleClassInitializeBeforeEachDerivedClassAndClassCleanupNone.ClassInitialize was called Console: LifeCycleDerivedClassInitializeBeforeEachDerivedClassAndClassCleanupNone.ClassInitialize was called @@ -736,8 +648,9 @@ LifeCycleClassInitializeAndCleanupNone.TestCleanup was called ? "Console: LifeCycleClassInitializeBeforeEachDerivedClassAndClassCleanupNone.DisposeAsync was called\r\nConsole: LifeCycleClassInitializeBeforeEachDerivedClassAndClassCleanupNone.Dispose was called" : "Console: LifeCycleClassInitializeBeforeEachDerivedClassAndClassCleanupNone.Dispose was called")} - """); - caseDerivedClassInitializeBeforeEachDerivedClassAndClassCleanupNone.Messages[1].Text.Should().Be( + """, + caseDerivedClassInitializeBeforeEachDerivedClassAndClassCleanupNone.Messages[0].Text); + Assert.AreEqual( $""" @@ -757,8 +670,9 @@ LifeCycleClassInitializeAndCleanupNone.TestCleanup was called + GenerateTraceDebugPrefixedMessage("LifeCycleClassInitializeBeforeEachDerivedClassAndClassCleanupNone.Dispose was called") : GenerateTraceDebugPrefixedMessage("LifeCycleClassInitializeBeforeEachDerivedClassAndClassCleanupNone.Dispose was called"))} - """); - caseDerivedClassInitializeBeforeEachDerivedClassAndClassCleanupNone.Messages[2].Text.Should().Be( + """, + caseDerivedClassInitializeBeforeEachDerivedClassAndClassCleanupNone.Messages[1].Text); + Assert.AreEqual( $""" @@ -776,13 +690,14 @@ LifeCycleClassInitializeBeforeEachDerivedClassAndClassCleanupNone.TestCleanup wa ? "LifeCycleClassInitializeBeforeEachDerivedClassAndClassCleanupNone.DisposeAsync was called\r\nLifeCycleClassInitializeBeforeEachDerivedClassAndClassCleanupNone.Dispose was called" : "LifeCycleClassInitializeBeforeEachDerivedClassAndClassCleanupNone.Dispose was called")} - """); + """, + caseDerivedClassInitializeBeforeEachDerivedClassAndClassCleanupNone.Messages[2].Text); // Test the parent test method. - Microsoft.VisualStudio.TestPlatform.ObjectModel.TestResult caseDerivedClassInitializeBeforeEachDerivedClassAndClassCleanupNoneParentTestMethod = RunEventsHandler.PassedTests.Single(x => x.TestCase.FullyQualifiedName.Contains("LifeCycleDerivedClassInitializeBeforeEachDerivedClassAndClassCleanupNone.TestMethod")); - caseDerivedClassInitializeBeforeEachDerivedClassAndClassCleanupNoneParentTestMethod.Outcome.Should().Be(Microsoft.VisualStudio.TestPlatform.ObjectModel.TestOutcome.Passed); - caseDerivedClassInitializeBeforeEachDerivedClassAndClassCleanupNoneParentTestMethod.Messages.Should().HaveCount(3); - caseDerivedClassInitializeBeforeEachDerivedClassAndClassCleanupNoneParentTestMethod.Messages[0].Text.Should().Be( + TestResult caseDerivedClassInitializeBeforeEachDerivedClassAndClassCleanupNoneParentTestMethod = RunEventsHandler.PassedTests.Single(x => x.TestCase.FullyQualifiedName.Contains("LifeCycleDerivedClassInitializeBeforeEachDerivedClassAndClassCleanupNone.TestMethod")); + Assert.AreEqual(TestOutcome.Passed, caseDerivedClassInitializeBeforeEachDerivedClassAndClassCleanupNoneParentTestMethod.Outcome); + Assert.HasCount(3, caseDerivedClassInitializeBeforeEachDerivedClassAndClassCleanupNoneParentTestMethod.Messages); + Assert.AreEqual( $""" Console: LifeCycleClassInitializeBeforeEachDerivedClassAndClassCleanupNone.ctor was called Console: LifeCycleDerivedClassInitializeBeforeEachDerivedClassAndClassCleanupNone.ctor was called @@ -795,8 +710,9 @@ LifeCycleClassInitializeBeforeEachDerivedClassAndClassCleanupNone.TestCleanup wa ? "Console: LifeCycleClassInitializeBeforeEachDerivedClassAndClassCleanupNone.DisposeAsync was called\r\nConsole: LifeCycleClassInitializeBeforeEachDerivedClassAndClassCleanupNone.Dispose was called" : "Console: LifeCycleClassInitializeBeforeEachDerivedClassAndClassCleanupNone.Dispose was called")} - """); - caseDerivedClassInitializeBeforeEachDerivedClassAndClassCleanupNoneParentTestMethod.Messages[1].Text.Should().Be( + """, + caseDerivedClassInitializeBeforeEachDerivedClassAndClassCleanupNoneParentTestMethod.Messages[0].Text); + Assert.AreEqual( $""" @@ -814,8 +730,9 @@ LifeCycleClassInitializeBeforeEachDerivedClassAndClassCleanupNone.TestCleanup wa + GenerateTraceDebugPrefixedMessage("LifeCycleClassInitializeBeforeEachDerivedClassAndClassCleanupNone.Dispose was called") : GenerateTraceDebugPrefixedMessage("LifeCycleClassInitializeBeforeEachDerivedClassAndClassCleanupNone.Dispose was called"))} - """); - caseDerivedClassInitializeBeforeEachDerivedClassAndClassCleanupNoneParentTestMethod.Messages[2].Text.Should().Be( + """, + caseDerivedClassInitializeBeforeEachDerivedClassAndClassCleanupNoneParentTestMethod.Messages[1].Text); + Assert.AreEqual( $""" @@ -831,12 +748,13 @@ LifeCycleClassInitializeBeforeEachDerivedClassAndClassCleanupNone.TestCleanup wa ? "LifeCycleClassInitializeBeforeEachDerivedClassAndClassCleanupNone.DisposeAsync was called\r\nLifeCycleClassInitializeBeforeEachDerivedClassAndClassCleanupNone.Dispose was called" : "LifeCycleClassInitializeBeforeEachDerivedClassAndClassCleanupNone.Dispose was called")} - """); + """, + caseDerivedClassInitializeBeforeEachDerivedClassAndClassCleanupNoneParentTestMethod.Messages[2].Text); - Microsoft.VisualStudio.TestPlatform.ObjectModel.TestResult caseDerivedClassInitializeNoneAndClassCleanupBeforeEachDerivedClass = RunEventsHandler.PassedTests.Single(x => x.TestCase.FullyQualifiedName.Contains("LifeCycleDerivedClassInitializeNoneAndClassCleanupBeforeEachDerivedClass.DerivedClassTestMethod")); - caseDerivedClassInitializeNoneAndClassCleanupBeforeEachDerivedClass.Outcome.Should().Be(Microsoft.VisualStudio.TestPlatform.ObjectModel.TestOutcome.Passed); - caseDerivedClassInitializeNoneAndClassCleanupBeforeEachDerivedClass.Messages.Should().HaveCount(3); - caseDerivedClassInitializeNoneAndClassCleanupBeforeEachDerivedClass.Messages[0].Text.Should().Be( + TestResult caseDerivedClassInitializeNoneAndClassCleanupBeforeEachDerivedClass = RunEventsHandler.PassedTests.Single(x => x.TestCase.FullyQualifiedName.Contains("LifeCycleDerivedClassInitializeNoneAndClassCleanupBeforeEachDerivedClass.DerivedClassTestMethod")); + Assert.AreEqual(TestOutcome.Passed, caseDerivedClassInitializeNoneAndClassCleanupBeforeEachDerivedClass.Outcome); + Assert.HasCount(3, caseDerivedClassInitializeNoneAndClassCleanupBeforeEachDerivedClass.Messages); + Assert.AreEqual( $""" Console: LifeCycleDerivedClassInitializeNoneAndClassCleanupBeforeEachDerivedClass.ClassInitialize was called Console: LifeCycleClassInitializeNoneAndClassCleanupBeforeEachDerivedClass.ctor was called @@ -850,8 +768,9 @@ LifeCycleClassInitializeBeforeEachDerivedClassAndClassCleanupNone.TestCleanup wa ? "Console: LifeCycleClassInitializeNoneAndClassCleanupBeforeEachDerivedClass.DisposeAsync was called\r\nConsole: LifeCycleClassInitializeNoneAndClassCleanupBeforeEachDerivedClass.Dispose was called" : "Console: LifeCycleClassInitializeNoneAndClassCleanupBeforeEachDerivedClass.Dispose was called")} - """); - caseDerivedClassInitializeNoneAndClassCleanupBeforeEachDerivedClass.Messages[1].Text.Should().Be( + """, + caseDerivedClassInitializeNoneAndClassCleanupBeforeEachDerivedClass.Messages[0].Text); + Assert.AreEqual( $""" @@ -870,8 +789,9 @@ LifeCycleClassInitializeBeforeEachDerivedClassAndClassCleanupNone.TestCleanup wa + GenerateTraceDebugPrefixedMessage("LifeCycleClassInitializeNoneAndClassCleanupBeforeEachDerivedClass.Dispose was called") : GenerateTraceDebugPrefixedMessage("LifeCycleClassInitializeNoneAndClassCleanupBeforeEachDerivedClass.Dispose was called"))} - """); - caseDerivedClassInitializeNoneAndClassCleanupBeforeEachDerivedClass.Messages[2].Text.Should().Be( + """, + caseDerivedClassInitializeNoneAndClassCleanupBeforeEachDerivedClass.Messages[1].Text); + Assert.AreEqual( $""" @@ -888,12 +808,13 @@ LifeCycleClassInitializeNoneAndClassCleanupBeforeEachDerivedClass.TestCleanup wa ? "LifeCycleClassInitializeNoneAndClassCleanupBeforeEachDerivedClass.DisposeAsync was called\r\nLifeCycleClassInitializeNoneAndClassCleanupBeforeEachDerivedClass.Dispose was called" : "LifeCycleClassInitializeNoneAndClassCleanupBeforeEachDerivedClass.Dispose was called")} - """); + """, + caseDerivedClassInitializeNoneAndClassCleanupBeforeEachDerivedClass.Messages[2].Text); - Microsoft.VisualStudio.TestPlatform.ObjectModel.TestResult caseClassCleanupEndOfAssemblyAndBeforeEachDerivedClass = RunEventsHandler.PassedTests.Single(x => x.TestCase.FullyQualifiedName.Contains("LifeCycleClassCleanupEndOfAssemblyAndBeforeEachDerivedClass.TestMethod")); - caseClassCleanupEndOfAssemblyAndBeforeEachDerivedClass.Outcome.Should().Be(Microsoft.VisualStudio.TestPlatform.ObjectModel.TestOutcome.Passed); - caseClassCleanupEndOfAssemblyAndBeforeEachDerivedClass.Messages.Should().HaveCount(3); - caseClassCleanupEndOfAssemblyAndBeforeEachDerivedClass.Messages[0].Text.Should().Be( + TestResult caseClassCleanupEndOfAssemblyAndBeforeEachDerivedClass = RunEventsHandler.PassedTests.Single(x => x.TestCase.FullyQualifiedName.Contains("LifeCycleClassCleanupEndOfAssemblyAndBeforeEachDerivedClass.TestMethod")); + Assert.AreEqual(TestOutcome.Passed, caseClassCleanupEndOfAssemblyAndBeforeEachDerivedClass.Outcome); + Assert.HasCount(3, caseClassCleanupEndOfAssemblyAndBeforeEachDerivedClass.Messages); + Assert.AreEqual( $""" Console: LifeCycleClassCleanupEndOfAssemblyAndBeforeEachDerivedClass.ClassInitialize was called Console: LifeCycleClassCleanupEndOfAssemblyAndBeforeEachDerivedClass.ctor was called @@ -904,8 +825,9 @@ LifeCycleClassInitializeNoneAndClassCleanupBeforeEachDerivedClass.TestCleanup wa ? "Console: LifeCycleClassCleanupEndOfAssemblyAndBeforeEachDerivedClass.DisposeAsync was called\r\nConsole: LifeCycleClassCleanupEndOfAssemblyAndBeforeEachDerivedClass.Dispose was called" : "Console: LifeCycleClassCleanupEndOfAssemblyAndBeforeEachDerivedClass.Dispose was called")} - """); - caseClassCleanupEndOfAssemblyAndBeforeEachDerivedClass.Messages[1].Text.Should().Be( + """, + caseClassCleanupEndOfAssemblyAndBeforeEachDerivedClass.Messages[0].Text); + Assert.AreEqual( $""" @@ -921,8 +843,9 @@ LifeCycleClassInitializeNoneAndClassCleanupBeforeEachDerivedClass.TestCleanup wa + GenerateTraceDebugPrefixedMessage("LifeCycleClassCleanupEndOfAssemblyAndBeforeEachDerivedClass.Dispose was called") : GenerateTraceDebugPrefixedMessage("LifeCycleClassCleanupEndOfAssemblyAndBeforeEachDerivedClass.Dispose was called"))} - """); - caseClassCleanupEndOfAssemblyAndBeforeEachDerivedClass.Messages[2].Text.Should().Be( + """, + caseClassCleanupEndOfAssemblyAndBeforeEachDerivedClass.Messages[1].Text); + Assert.AreEqual( $""" @@ -936,12 +859,13 @@ LifeCycleClassCleanupEndOfAssemblyAndBeforeEachDerivedClass.TestCleanup was call ? "LifeCycleClassCleanupEndOfAssemblyAndBeforeEachDerivedClass.DisposeAsync was called\r\nLifeCycleClassCleanupEndOfAssemblyAndBeforeEachDerivedClass.Dispose was called" : "LifeCycleClassCleanupEndOfAssemblyAndBeforeEachDerivedClass.Dispose was called")} - """); + """, + caseClassCleanupEndOfAssemblyAndBeforeEachDerivedClass.Messages[2].Text); - Microsoft.VisualStudio.TestPlatform.ObjectModel.TestResult caseClassCleanupEndOfAssemblyAndNone = RunEventsHandler.PassedTests.Single(x => x.TestCase.FullyQualifiedName.Contains("LifeCycleClassCleanupEndOfAssemblyAndNone.TestMethod")); - caseClassCleanupEndOfAssemblyAndNone.Outcome.Should().Be(Microsoft.VisualStudio.TestPlatform.ObjectModel.TestOutcome.Passed); - caseClassCleanupEndOfAssemblyAndNone.Messages.Should().HaveCount(3); - caseClassCleanupEndOfAssemblyAndNone.Messages[0].Text.Should().Be( + TestResult caseClassCleanupEndOfAssemblyAndNone = RunEventsHandler.PassedTests.Single(x => x.TestCase.FullyQualifiedName.Contains("LifeCycleClassCleanupEndOfAssemblyAndNone.TestMethod")); + Assert.AreEqual(TestOutcome.Passed, caseClassCleanupEndOfAssemblyAndNone.Outcome); + Assert.HasCount(3, caseClassCleanupEndOfAssemblyAndNone.Messages); + Assert.AreEqual( $""" Console: LifeCycleClassCleanupEndOfAssemblyAndNone.ClassInitialize was called Console: LifeCycleClassCleanupEndOfAssemblyAndNone.ctor was called @@ -952,8 +876,9 @@ LifeCycleClassCleanupEndOfAssemblyAndBeforeEachDerivedClass.TestCleanup was call ? "Console: LifeCycleClassCleanupEndOfAssemblyAndNone.DisposeAsync was called\r\nConsole: LifeCycleClassCleanupEndOfAssemblyAndNone.Dispose was called" : "Console: LifeCycleClassCleanupEndOfAssemblyAndNone.Dispose was called")} - """); - caseClassCleanupEndOfAssemblyAndNone.Messages[1].Text.Should().Be( + """, + caseClassCleanupEndOfAssemblyAndNone.Messages[0].Text); + Assert.AreEqual( $""" @@ -969,8 +894,9 @@ LifeCycleClassCleanupEndOfAssemblyAndBeforeEachDerivedClass.TestCleanup was call + GenerateTraceDebugPrefixedMessage("LifeCycleClassCleanupEndOfAssemblyAndNone.Dispose was called") : GenerateTraceDebugPrefixedMessage("LifeCycleClassCleanupEndOfAssemblyAndNone.Dispose was called"))} - """); - caseClassCleanupEndOfAssemblyAndNone.Messages[2].Text.Should().Be( + """, + caseClassCleanupEndOfAssemblyAndNone.Messages[1].Text); + Assert.AreEqual( $""" @@ -984,12 +910,13 @@ LifeCycleClassCleanupEndOfAssemblyAndNone.TestCleanup was called ? "LifeCycleClassCleanupEndOfAssemblyAndNone.DisposeAsync was called\r\nLifeCycleClassCleanupEndOfAssemblyAndNone.Dispose was called" : "LifeCycleClassCleanupEndOfAssemblyAndNone.Dispose was called")} - """); + """, + caseClassCleanupEndOfAssemblyAndNone.Messages[2].Text); - Microsoft.VisualStudio.TestPlatform.ObjectModel.TestResult caseClassCleanupEndOfClassAndBeforeEachDerivedClass = RunEventsHandler.PassedTests.Single(x => x.TestCase.FullyQualifiedName.Contains("LifeCycleClassCleanupEndOfClassAndBeforeEachDerivedClass.TestMethod")); - caseClassCleanupEndOfClassAndBeforeEachDerivedClass.Outcome.Should().Be(Microsoft.VisualStudio.TestPlatform.ObjectModel.TestOutcome.Passed); - caseClassCleanupEndOfClassAndBeforeEachDerivedClass.Messages.Should().HaveCount(3); - caseClassCleanupEndOfClassAndBeforeEachDerivedClass.Messages[0].Text.Should().Be( + TestResult caseClassCleanupEndOfClassAndBeforeEachDerivedClass = RunEventsHandler.PassedTests.Single(x => x.TestCase.FullyQualifiedName.Contains("LifeCycleClassCleanupEndOfClassAndBeforeEachDerivedClass.TestMethod")); + Assert.AreEqual(TestOutcome.Passed, caseClassCleanupEndOfClassAndBeforeEachDerivedClass.Outcome); + Assert.HasCount(3, caseClassCleanupEndOfClassAndBeforeEachDerivedClass.Messages); + Assert.AreEqual( $""" Console: LifeCycleClassCleanupEndOfClassAndBeforeEachDerivedClass.ClassInitialize was called Console: LifeCycleClassCleanupEndOfClassAndBeforeEachDerivedClass.ctor was called @@ -1001,8 +928,9 @@ LifeCycleClassCleanupEndOfAssemblyAndNone.TestCleanup was called : "Console: LifeCycleClassCleanupEndOfClassAndBeforeEachDerivedClass.Dispose was called")} Console: LifeCycleClassCleanupEndOfClassAndBeforeEachDerivedClass.ClassCleanup was called - """); - caseClassCleanupEndOfClassAndBeforeEachDerivedClass.Messages[1].Text.Should().Be( + """, + caseClassCleanupEndOfClassAndBeforeEachDerivedClass.Messages[0].Text); + Assert.AreEqual( $""" @@ -1019,8 +947,9 @@ LifeCycleClassCleanupEndOfAssemblyAndNone.TestCleanup was called : GenerateTraceDebugPrefixedMessage("LifeCycleClassCleanupEndOfClassAndBeforeEachDerivedClass.Dispose was called"))} {GenerateTraceDebugPrefixedMessage("LifeCycleClassCleanupEndOfClassAndBeforeEachDerivedClass.ClassCleanup was called")} - """); - caseClassCleanupEndOfClassAndBeforeEachDerivedClass.Messages[2].Text.Should().Be( + """, + caseClassCleanupEndOfClassAndBeforeEachDerivedClass.Messages[1].Text); + Assert.AreEqual( $""" @@ -1035,12 +964,13 @@ LifeCycleClassCleanupEndOfClassAndBeforeEachDerivedClass.TestCleanup was called : "LifeCycleClassCleanupEndOfClassAndBeforeEachDerivedClass.Dispose was called")} LifeCycleClassCleanupEndOfClassAndBeforeEachDerivedClass.ClassCleanup was called - """); + """, + caseClassCleanupEndOfClassAndBeforeEachDerivedClass.Messages[2].Text); - Microsoft.VisualStudio.TestPlatform.ObjectModel.TestResult caseClassCleanupEndOfClassAndNone = RunEventsHandler.PassedTests.Single(x => x.TestCase.FullyQualifiedName.Contains("LifeCycleClassCleanupEndOfClassAndNone.TestMethod")); - caseClassCleanupEndOfClassAndNone.Outcome.Should().Be(Microsoft.VisualStudio.TestPlatform.ObjectModel.TestOutcome.Passed); - caseClassCleanupEndOfClassAndNone.Messages.Should().HaveCount(3); - caseClassCleanupEndOfClassAndNone.Messages[0].Text.Should().Be( + TestResult caseClassCleanupEndOfClassAndNone = RunEventsHandler.PassedTests.Single(x => x.TestCase.FullyQualifiedName.Contains("LifeCycleClassCleanupEndOfClassAndNone.TestMethod")); + Assert.AreEqual(TestOutcome.Passed, caseClassCleanupEndOfClassAndNone.Outcome); + Assert.HasCount(3, caseClassCleanupEndOfClassAndNone.Messages); + Assert.AreEqual( $""" Console: LifeCycleClassCleanupEndOfClassAndNone.ClassInitialize was called Console: LifeCycleClassCleanupEndOfClassAndNone.ctor was called @@ -1052,8 +982,9 @@ LifeCycleClassCleanupEndOfClassAndBeforeEachDerivedClass.ClassCleanup was called : "Console: LifeCycleClassCleanupEndOfClassAndNone.Dispose was called")} Console: LifeCycleClassCleanupEndOfClassAndNone.ClassCleanup was called - """); - caseClassCleanupEndOfClassAndNone.Messages[1].Text.Should().Be( + """, + caseClassCleanupEndOfClassAndNone.Messages[0].Text); + Assert.AreEqual( $""" @@ -1070,8 +1001,9 @@ LifeCycleClassCleanupEndOfClassAndBeforeEachDerivedClass.ClassCleanup was called : GenerateTraceDebugPrefixedMessage("LifeCycleClassCleanupEndOfClassAndNone.Dispose was called"))} {GenerateTraceDebugPrefixedMessage("LifeCycleClassCleanupEndOfClassAndNone.ClassCleanup was called")} - """); - caseClassCleanupEndOfClassAndNone.Messages[2].Text.Should().Be( + """, + caseClassCleanupEndOfClassAndNone.Messages[1].Text); + Assert.AreEqual( $""" @@ -1086,12 +1018,13 @@ LifeCycleClassCleanupEndOfClassAndNone.TestCleanup was called : "LifeCycleClassCleanupEndOfClassAndNone.Dispose was called")} LifeCycleClassCleanupEndOfClassAndNone.ClassCleanup was called - """); + """, + caseClassCleanupEndOfClassAndNone.Messages[2].Text); - Microsoft.VisualStudio.TestPlatform.ObjectModel.TestResult caseDerivedClassCleanupEndOfAssemblyAndBeforeEachDerivedClass = RunEventsHandler.PassedTests.Single(x => x.TestCase.FullyQualifiedName.Contains("LifeCycleDerivedClassCleanupEndOfAssemblyAndBeforeEachDerivedClass.DerivedClassTestMethod")); - caseDerivedClassCleanupEndOfAssemblyAndBeforeEachDerivedClass.Outcome.Should().Be(Microsoft.VisualStudio.TestPlatform.ObjectModel.TestOutcome.Passed); - caseDerivedClassCleanupEndOfAssemblyAndBeforeEachDerivedClass.Messages.Should().HaveCount(3); - caseDerivedClassCleanupEndOfAssemblyAndBeforeEachDerivedClass.Messages[0].Text.Should().Be( + TestResult caseDerivedClassCleanupEndOfAssemblyAndBeforeEachDerivedClass = RunEventsHandler.PassedTests.Single(x => x.TestCase.FullyQualifiedName.Contains("LifeCycleDerivedClassCleanupEndOfAssemblyAndBeforeEachDerivedClass.DerivedClassTestMethod")); + Assert.AreEqual(TestOutcome.Passed, caseDerivedClassCleanupEndOfAssemblyAndBeforeEachDerivedClass.Outcome); + Assert.HasCount(3, caseDerivedClassCleanupEndOfAssemblyAndBeforeEachDerivedClass.Messages); + Assert.AreEqual( $""" Console: LifeCycleDerivedClassCleanupEndOfAssemblyAndBeforeEachDerivedClass.ClassInitialize was called Console: LifeCycleClassCleanupEndOfAssemblyAndBeforeEachDerivedClass.ctor was called @@ -1105,8 +1038,9 @@ LifeCycleClassCleanupEndOfClassAndNone.ClassCleanup was called ? "Console: LifeCycleClassCleanupEndOfAssemblyAndBeforeEachDerivedClass.DisposeAsync was called\r\nConsole: LifeCycleClassCleanupEndOfAssemblyAndBeforeEachDerivedClass.Dispose was called" : "Console: LifeCycleClassCleanupEndOfAssemblyAndBeforeEachDerivedClass.Dispose was called")} - """); - caseDerivedClassCleanupEndOfAssemblyAndBeforeEachDerivedClass.Messages[1].Text.Should().Be( + """, + caseDerivedClassCleanupEndOfAssemblyAndBeforeEachDerivedClass.Messages[0].Text); + Assert.AreEqual( $""" @@ -1125,8 +1059,9 @@ LifeCycleClassCleanupEndOfClassAndNone.ClassCleanup was called + GenerateTraceDebugPrefixedMessage("LifeCycleClassCleanupEndOfAssemblyAndBeforeEachDerivedClass.Dispose was called") : GenerateTraceDebugPrefixedMessage("LifeCycleClassCleanupEndOfAssemblyAndBeforeEachDerivedClass.Dispose was called"))} - """); - caseDerivedClassCleanupEndOfAssemblyAndBeforeEachDerivedClass.Messages[2].Text.Should().Be( + """, + caseDerivedClassCleanupEndOfAssemblyAndBeforeEachDerivedClass.Messages[1].Text); + Assert.AreEqual( $""" @@ -1143,12 +1078,13 @@ LifeCycleClassCleanupEndOfAssemblyAndBeforeEachDerivedClass.TestCleanup was call ? "LifeCycleClassCleanupEndOfAssemblyAndBeforeEachDerivedClass.DisposeAsync was called\r\nLifeCycleClassCleanupEndOfAssemblyAndBeforeEachDerivedClass.Dispose was called" : "LifeCycleClassCleanupEndOfAssemblyAndBeforeEachDerivedClass.Dispose was called")} - """); + """, + caseDerivedClassCleanupEndOfAssemblyAndBeforeEachDerivedClass.Messages[2].Text); - Microsoft.VisualStudio.TestPlatform.ObjectModel.TestResult caseDerivedClassCleanupEndOfAssemblyAndNone = RunEventsHandler.PassedTests.Single(x => x.TestCase.FullyQualifiedName.Contains("LifeCycleDerivedClassCleanupEndOfAssemblyAndNone.DerivedClassTestMethod")); - caseDerivedClassCleanupEndOfAssemblyAndNone.Outcome.Should().Be(Microsoft.VisualStudio.TestPlatform.ObjectModel.TestOutcome.Passed); - caseDerivedClassCleanupEndOfAssemblyAndNone.Messages.Should().HaveCount(3); - caseDerivedClassCleanupEndOfAssemblyAndNone.Messages[0].Text.Should().Be( + TestResult caseDerivedClassCleanupEndOfAssemblyAndNone = RunEventsHandler.PassedTests.Single(x => x.TestCase.FullyQualifiedName.Contains("LifeCycleDerivedClassCleanupEndOfAssemblyAndNone.DerivedClassTestMethod")); + Assert.AreEqual(TestOutcome.Passed, caseDerivedClassCleanupEndOfAssemblyAndNone.Outcome); + Assert.HasCount(3, caseDerivedClassCleanupEndOfAssemblyAndNone.Messages); + Assert.AreEqual( $""" Console: LifeCycleDerivedClassCleanupEndOfAssemblyAndNone.ClassInitialize was called Console: LifeCycleClassCleanupEndOfAssemblyAndNone.ctor was called @@ -1162,8 +1098,9 @@ LifeCycleClassCleanupEndOfAssemblyAndBeforeEachDerivedClass.TestCleanup was call ? "Console: LifeCycleClassCleanupEndOfAssemblyAndNone.DisposeAsync was called\r\nConsole: LifeCycleClassCleanupEndOfAssemblyAndNone.Dispose was called" : "Console: LifeCycleClassCleanupEndOfAssemblyAndNone.Dispose was called")} - """); - caseDerivedClassCleanupEndOfAssemblyAndNone.Messages[1].Text.Should().Be( + """, + caseDerivedClassCleanupEndOfAssemblyAndNone.Messages[0].Text); + Assert.AreEqual( $""" @@ -1182,8 +1119,9 @@ LifeCycleClassCleanupEndOfAssemblyAndBeforeEachDerivedClass.TestCleanup was call + GenerateTraceDebugPrefixedMessage("LifeCycleClassCleanupEndOfAssemblyAndNone.Dispose was called") : GenerateTraceDebugPrefixedMessage("LifeCycleClassCleanupEndOfAssemblyAndNone.Dispose was called"))} - """); - caseDerivedClassCleanupEndOfAssemblyAndNone.Messages[2].Text.Should().Be( + """, + caseDerivedClassCleanupEndOfAssemblyAndNone.Messages[1].Text); + Assert.AreEqual( $""" @@ -1200,11 +1138,12 @@ LifeCycleClassCleanupEndOfAssemblyAndNone.TestCleanup was called ? "LifeCycleClassCleanupEndOfAssemblyAndNone.DisposeAsync was called\r\nLifeCycleClassCleanupEndOfAssemblyAndNone.Dispose was called" : "LifeCycleClassCleanupEndOfAssemblyAndNone.Dispose was called")} - """); - Microsoft.VisualStudio.TestPlatform.ObjectModel.TestResult caseDerivedClassCleanupEndOfClassAndBeforeEachDerivedClass = RunEventsHandler.PassedTests.Single(x => x.TestCase.FullyQualifiedName.Contains("LifeCycleDerivedClassCleanupEndOfClassAndBeforeEachDerivedClass.DerivedClassTestMethod")); - caseDerivedClassCleanupEndOfClassAndBeforeEachDerivedClass.Outcome.Should().Be(Microsoft.VisualStudio.TestPlatform.ObjectModel.TestOutcome.Passed); - caseDerivedClassCleanupEndOfClassAndBeforeEachDerivedClass.Messages.Should().HaveCount(3); - caseDerivedClassCleanupEndOfClassAndBeforeEachDerivedClass.Messages[0].Text.Should().Be( + """, + caseDerivedClassCleanupEndOfAssemblyAndNone.Messages[2].Text); + TestResult caseDerivedClassCleanupEndOfClassAndBeforeEachDerivedClass = RunEventsHandler.PassedTests.Single(x => x.TestCase.FullyQualifiedName.Contains("LifeCycleDerivedClassCleanupEndOfClassAndBeforeEachDerivedClass.DerivedClassTestMethod")); + Assert.AreEqual(TestOutcome.Passed, caseDerivedClassCleanupEndOfClassAndBeforeEachDerivedClass.Outcome); + Assert.HasCount(3, caseDerivedClassCleanupEndOfClassAndBeforeEachDerivedClass.Messages); + Assert.AreEqual( $""" Console: LifeCycleDerivedClassCleanupEndOfClassAndBeforeEachDerivedClass.ClassInitialize was called Console: LifeCycleClassCleanupEndOfClassAndBeforeEachDerivedClass.ctor was called @@ -1218,8 +1157,9 @@ LifeCycleClassCleanupEndOfAssemblyAndNone.TestCleanup was called ? "Console: LifeCycleClassCleanupEndOfClassAndBeforeEachDerivedClass.DisposeAsync was called\r\nConsole: LifeCycleClassCleanupEndOfClassAndBeforeEachDerivedClass.Dispose was called" : "Console: LifeCycleClassCleanupEndOfClassAndBeforeEachDerivedClass.Dispose was called")} - """); - caseDerivedClassCleanupEndOfClassAndBeforeEachDerivedClass.Messages[1].Text.Should().Be( + """, + caseDerivedClassCleanupEndOfClassAndBeforeEachDerivedClass.Messages[0].Text); + Assert.AreEqual( $""" @@ -1238,8 +1178,9 @@ LifeCycleClassCleanupEndOfAssemblyAndNone.TestCleanup was called + GenerateTraceDebugPrefixedMessage("LifeCycleClassCleanupEndOfClassAndBeforeEachDerivedClass.Dispose was called") : GenerateTraceDebugPrefixedMessage("LifeCycleClassCleanupEndOfClassAndBeforeEachDerivedClass.Dispose was called"))} - """); - caseDerivedClassCleanupEndOfClassAndBeforeEachDerivedClass.Messages[2].Text.Should().Be( + """, + caseDerivedClassCleanupEndOfClassAndBeforeEachDerivedClass.Messages[1].Text); + Assert.AreEqual( $""" @@ -1256,12 +1197,13 @@ LifeCycleClassCleanupEndOfClassAndBeforeEachDerivedClass.TestCleanup was called ? "LifeCycleClassCleanupEndOfClassAndBeforeEachDerivedClass.DisposeAsync was called\r\nLifeCycleClassCleanupEndOfClassAndBeforeEachDerivedClass.Dispose was called" : "LifeCycleClassCleanupEndOfClassAndBeforeEachDerivedClass.Dispose was called")} - """); + """, + caseDerivedClassCleanupEndOfClassAndBeforeEachDerivedClass.Messages[2].Text); - Microsoft.VisualStudio.TestPlatform.ObjectModel.TestResult caseDerivedClassCleanupEndOfClassAndNone = RunEventsHandler.PassedTests.Single(x => x.TestCase.FullyQualifiedName.Contains("LifeCycleDerivedClassCleanupEndOfClassAndNone.DerivedClassTestMethod")); - caseDerivedClassCleanupEndOfClassAndNone.Outcome.Should().Be(Microsoft.VisualStudio.TestPlatform.ObjectModel.TestOutcome.Passed); - caseDerivedClassCleanupEndOfClassAndNone.Messages.Should().HaveCount(3); - caseDerivedClassCleanupEndOfClassAndNone.Messages[0].Text.Should().Be( + TestResult caseDerivedClassCleanupEndOfClassAndNone = RunEventsHandler.PassedTests.Single(x => x.TestCase.FullyQualifiedName.Contains("LifeCycleDerivedClassCleanupEndOfClassAndNone.DerivedClassTestMethod")); + Assert.AreEqual(TestOutcome.Passed, caseDerivedClassCleanupEndOfClassAndNone.Outcome); + Assert.HasCount(3, caseDerivedClassCleanupEndOfClassAndNone.Messages); + Assert.AreEqual( $""" Console: LifeCycleDerivedClassCleanupEndOfClassAndNone.ClassInitialize was called Console: LifeCycleClassCleanupEndOfClassAndNone.ctor was called @@ -1275,8 +1217,9 @@ LifeCycleClassCleanupEndOfClassAndBeforeEachDerivedClass.TestCleanup was called ? "Console: LifeCycleClassCleanupEndOfClassAndNone.DisposeAsync was called\r\nConsole: LifeCycleClassCleanupEndOfClassAndNone.Dispose was called" : "Console: LifeCycleClassCleanupEndOfClassAndNone.Dispose was called")} - """); - caseDerivedClassCleanupEndOfClassAndNone.Messages[1].Text.Should().Be( + """, + caseDerivedClassCleanupEndOfClassAndNone.Messages[0].Text); + Assert.AreEqual( $""" @@ -1295,8 +1238,9 @@ LifeCycleClassCleanupEndOfClassAndBeforeEachDerivedClass.TestCleanup was called + GenerateTraceDebugPrefixedMessage("LifeCycleClassCleanupEndOfClassAndNone.Dispose was called") : GenerateTraceDebugPrefixedMessage("LifeCycleClassCleanupEndOfClassAndNone.Dispose was called"))} - """); - caseDerivedClassCleanupEndOfClassAndNone.Messages[2].Text.Should().Be( + """, + caseDerivedClassCleanupEndOfClassAndNone.Messages[1].Text); + Assert.AreEqual( $""" @@ -1313,12 +1257,13 @@ LifeCycleClassCleanupEndOfClassAndNone.TestCleanup was called ? "LifeCycleClassCleanupEndOfClassAndNone.DisposeAsync was called\r\nLifeCycleClassCleanupEndOfClassAndNone.Dispose was called" : "LifeCycleClassCleanupEndOfClassAndNone.Dispose was called")} - """); + """, + caseDerivedClassCleanupEndOfClassAndNone.Messages[2].Text); - Microsoft.VisualStudio.TestPlatform.ObjectModel.TestResult caseDerivedClassCleanupEndOfAssemblyAndBeforeEachDerivedClassParentTestMethod = RunEventsHandler.PassedTests.Single(x => x.TestCase.FullyQualifiedName.Contains("LifeCycleDerivedClassCleanupEndOfAssemblyAndBeforeEachDerivedClass.TestMethod")); - caseDerivedClassCleanupEndOfAssemblyAndBeforeEachDerivedClassParentTestMethod.Outcome.Should().Be(Microsoft.VisualStudio.TestPlatform.ObjectModel.TestOutcome.Passed); - caseDerivedClassCleanupEndOfAssemblyAndBeforeEachDerivedClassParentTestMethod.Messages.Should().HaveCount(3); - caseDerivedClassCleanupEndOfAssemblyAndBeforeEachDerivedClassParentTestMethod.Messages[0].Text.Should().Be( + TestResult caseDerivedClassCleanupEndOfAssemblyAndBeforeEachDerivedClassParentTestMethod = RunEventsHandler.PassedTests.Single(x => x.TestCase.FullyQualifiedName.Contains("LifeCycleDerivedClassCleanupEndOfAssemblyAndBeforeEachDerivedClass.TestMethod")); + Assert.AreEqual(TestOutcome.Passed, caseDerivedClassCleanupEndOfAssemblyAndBeforeEachDerivedClassParentTestMethod.Outcome); + Assert.HasCount(3, caseDerivedClassCleanupEndOfAssemblyAndBeforeEachDerivedClassParentTestMethod.Messages); + Assert.AreEqual( $""" Console: LifeCycleClassCleanupEndOfAssemblyAndBeforeEachDerivedClass.ctor was called Console: LifeCycleDerivedClassCleanupEndOfAssemblyAndBeforeEachDerivedClass.ctor was called @@ -1331,8 +1276,9 @@ LifeCycleClassCleanupEndOfClassAndNone.TestCleanup was called ? "Console: LifeCycleClassCleanupEndOfAssemblyAndBeforeEachDerivedClass.DisposeAsync was called\r\nConsole: LifeCycleClassCleanupEndOfAssemblyAndBeforeEachDerivedClass.Dispose was called" : "Console: LifeCycleClassCleanupEndOfAssemblyAndBeforeEachDerivedClass.Dispose was called")} - """); - caseDerivedClassCleanupEndOfAssemblyAndBeforeEachDerivedClassParentTestMethod.Messages[1].Text.Should().Be( + """, + caseDerivedClassCleanupEndOfAssemblyAndBeforeEachDerivedClassParentTestMethod.Messages[0].Text); + Assert.AreEqual( $""" @@ -1350,8 +1296,9 @@ LifeCycleClassCleanupEndOfClassAndNone.TestCleanup was called + GenerateTraceDebugPrefixedMessage("LifeCycleClassCleanupEndOfAssemblyAndBeforeEachDerivedClass.Dispose was called") : GenerateTraceDebugPrefixedMessage("LifeCycleClassCleanupEndOfAssemblyAndBeforeEachDerivedClass.Dispose was called"))} - """); - caseDerivedClassCleanupEndOfAssemblyAndBeforeEachDerivedClassParentTestMethod.Messages[2].Text.Should().Be( + """, + caseDerivedClassCleanupEndOfAssemblyAndBeforeEachDerivedClassParentTestMethod.Messages[1].Text); + Assert.AreEqual( $""" @@ -1367,12 +1314,13 @@ LifeCycleClassCleanupEndOfAssemblyAndBeforeEachDerivedClass.TestCleanup was call ? "LifeCycleClassCleanupEndOfAssemblyAndBeforeEachDerivedClass.DisposeAsync was called\r\nLifeCycleClassCleanupEndOfAssemblyAndBeforeEachDerivedClass.Dispose was called" : "LifeCycleClassCleanupEndOfAssemblyAndBeforeEachDerivedClass.Dispose was called")} - """); + """, + caseDerivedClassCleanupEndOfAssemblyAndBeforeEachDerivedClassParentTestMethod.Messages[2].Text); - Microsoft.VisualStudio.TestPlatform.ObjectModel.TestResult caseDerivedClassCleanupEndOfAssemblyAndNoneParentTestMethod = RunEventsHandler.PassedTests.Single(x => x.TestCase.FullyQualifiedName.Contains("LifeCycleDerivedClassCleanupEndOfAssemblyAndNone.TestMethod")); - caseDerivedClassCleanupEndOfAssemblyAndNoneParentTestMethod.Outcome.Should().Be(Microsoft.VisualStudio.TestPlatform.ObjectModel.TestOutcome.Passed); - caseDerivedClassCleanupEndOfAssemblyAndNoneParentTestMethod.Messages.Should().HaveCount(3); - caseDerivedClassCleanupEndOfAssemblyAndNoneParentTestMethod.Messages[0].Text.Should().Be( + TestResult caseDerivedClassCleanupEndOfAssemblyAndNoneParentTestMethod = RunEventsHandler.PassedTests.Single(x => x.TestCase.FullyQualifiedName.Contains("LifeCycleDerivedClassCleanupEndOfAssemblyAndNone.TestMethod")); + Assert.AreEqual(TestOutcome.Passed, caseDerivedClassCleanupEndOfAssemblyAndNoneParentTestMethod.Outcome); + Assert.HasCount(3, caseDerivedClassCleanupEndOfAssemblyAndNoneParentTestMethod.Messages); + Assert.AreEqual( $""" Console: LifeCycleClassCleanupEndOfAssemblyAndNone.ctor was called Console: LifeCycleDerivedClassCleanupEndOfAssemblyAndNone.ctor was called @@ -1385,8 +1333,9 @@ LifeCycleClassCleanupEndOfAssemblyAndBeforeEachDerivedClass.TestCleanup was call ? "Console: LifeCycleClassCleanupEndOfAssemblyAndNone.DisposeAsync was called\r\nConsole: LifeCycleClassCleanupEndOfAssemblyAndNone.Dispose was called" : "Console: LifeCycleClassCleanupEndOfAssemblyAndNone.Dispose was called")} - """); - caseDerivedClassCleanupEndOfAssemblyAndNoneParentTestMethod.Messages[1].Text.Should().Be( + """, + caseDerivedClassCleanupEndOfAssemblyAndNoneParentTestMethod.Messages[0].Text); + Assert.AreEqual( $""" @@ -1404,8 +1353,9 @@ LifeCycleClassCleanupEndOfAssemblyAndBeforeEachDerivedClass.TestCleanup was call + GenerateTraceDebugPrefixedMessage("LifeCycleClassCleanupEndOfAssemblyAndNone.Dispose was called") : GenerateTraceDebugPrefixedMessage("LifeCycleClassCleanupEndOfAssemblyAndNone.Dispose was called"))} - """); - caseDerivedClassCleanupEndOfAssemblyAndNoneParentTestMethod.Messages[2].Text.Should().Be( + """, + caseDerivedClassCleanupEndOfAssemblyAndNoneParentTestMethod.Messages[1].Text); + Assert.AreEqual( $""" @@ -1421,11 +1371,12 @@ LifeCycleClassCleanupEndOfAssemblyAndNone.TestCleanup was called ? "LifeCycleClassCleanupEndOfAssemblyAndNone.DisposeAsync was called\r\nLifeCycleClassCleanupEndOfAssemblyAndNone.Dispose was called" : "LifeCycleClassCleanupEndOfAssemblyAndNone.Dispose was called")} - """); - Microsoft.VisualStudio.TestPlatform.ObjectModel.TestResult caseDerivedClassCleanupEndOfClassAndBeforeEachDerivedClassParentTestMethod = RunEventsHandler.PassedTests.Single(x => x.TestCase.FullyQualifiedName.Contains("LifeCycleDerivedClassCleanupEndOfClassAndBeforeEachDerivedClass.TestMethod")); - caseDerivedClassCleanupEndOfClassAndBeforeEachDerivedClassParentTestMethod.Outcome.Should().Be(Microsoft.VisualStudio.TestPlatform.ObjectModel.TestOutcome.Passed); - caseDerivedClassCleanupEndOfClassAndBeforeEachDerivedClassParentTestMethod.Messages.Should().HaveCount(3); - caseDerivedClassCleanupEndOfClassAndBeforeEachDerivedClassParentTestMethod.Messages[0].Text.Should().Be( + """, + caseDerivedClassCleanupEndOfAssemblyAndNoneParentTestMethod.Messages[2].Text); + TestResult caseDerivedClassCleanupEndOfClassAndBeforeEachDerivedClassParentTestMethod = RunEventsHandler.PassedTests.Single(x => x.TestCase.FullyQualifiedName.Contains("LifeCycleDerivedClassCleanupEndOfClassAndBeforeEachDerivedClass.TestMethod")); + Assert.AreEqual(TestOutcome.Passed, caseDerivedClassCleanupEndOfClassAndBeforeEachDerivedClassParentTestMethod.Outcome); + Assert.HasCount(3, caseDerivedClassCleanupEndOfClassAndBeforeEachDerivedClassParentTestMethod.Messages); + Assert.AreEqual( $""" Console: LifeCycleClassCleanupEndOfClassAndBeforeEachDerivedClass.ctor was called Console: LifeCycleDerivedClassCleanupEndOfClassAndBeforeEachDerivedClass.ctor was called @@ -1440,8 +1391,9 @@ LifeCycleClassCleanupEndOfAssemblyAndNone.TestCleanup was called Console: LifeCycleDerivedClassCleanupEndOfClassAndBeforeEachDerivedClass.ClassCleanup was called Console: LifeCycleClassCleanupEndOfClassAndBeforeEachDerivedClass.ClassCleanup was called - """); - caseDerivedClassCleanupEndOfClassAndBeforeEachDerivedClassParentTestMethod.Messages[1].Text.Should().Be( + """, + caseDerivedClassCleanupEndOfClassAndBeforeEachDerivedClassParentTestMethod.Messages[0].Text); + Assert.AreEqual( $""" @@ -1461,8 +1413,9 @@ LifeCycleClassCleanupEndOfAssemblyAndNone.TestCleanup was called {GenerateTraceDebugPrefixedMessage("LifeCycleDerivedClassCleanupEndOfClassAndBeforeEachDerivedClass.ClassCleanup was called")} {GenerateTraceDebugPrefixedMessage("LifeCycleClassCleanupEndOfClassAndBeforeEachDerivedClass.ClassCleanup was called")} - """); - caseDerivedClassCleanupEndOfClassAndBeforeEachDerivedClassParentTestMethod.Messages[2].Text.Should().Be( + """, + caseDerivedClassCleanupEndOfClassAndBeforeEachDerivedClassParentTestMethod.Messages[1].Text); + Assert.AreEqual( $""" @@ -1480,12 +1433,13 @@ LifeCycleClassCleanupEndOfClassAndBeforeEachDerivedClass.TestCleanup was called LifeCycleDerivedClassCleanupEndOfClassAndBeforeEachDerivedClass.ClassCleanup was called LifeCycleClassCleanupEndOfClassAndBeforeEachDerivedClass.ClassCleanup was called - """); + """, + caseDerivedClassCleanupEndOfClassAndBeforeEachDerivedClassParentTestMethod.Messages[2].Text); - Microsoft.VisualStudio.TestPlatform.ObjectModel.TestResult caseDerivedClassCleanupEndOfClassAndNoneParentTestMethod = RunEventsHandler.PassedTests.Single(x => x.TestCase.FullyQualifiedName.Contains("LifeCycleDerivedClassCleanupEndOfClassAndNone.TestMethod")); - caseDerivedClassCleanupEndOfClassAndNoneParentTestMethod.Outcome.Should().Be(Microsoft.VisualStudio.TestPlatform.ObjectModel.TestOutcome.Passed); - caseDerivedClassCleanupEndOfClassAndNoneParentTestMethod.Messages.Should().HaveCount(3); - caseDerivedClassCleanupEndOfClassAndNoneParentTestMethod.Messages[0].Text.Should().Be( + TestResult caseDerivedClassCleanupEndOfClassAndNoneParentTestMethod = RunEventsHandler.PassedTests.Single(x => x.TestCase.FullyQualifiedName.Contains("LifeCycleDerivedClassCleanupEndOfClassAndNone.TestMethod")); + Assert.AreEqual(TestOutcome.Passed, caseDerivedClassCleanupEndOfClassAndNoneParentTestMethod.Outcome); + Assert.HasCount(3, caseDerivedClassCleanupEndOfClassAndNoneParentTestMethod.Messages); + Assert.AreEqual( $""" Console: LifeCycleClassCleanupEndOfClassAndNone.ctor was called Console: LifeCycleDerivedClassCleanupEndOfClassAndNone.ctor was called @@ -1498,8 +1452,9 @@ LifeCycleClassCleanupEndOfClassAndBeforeEachDerivedClass.ClassCleanup was called ? "Console: LifeCycleClassCleanupEndOfClassAndNone.DisposeAsync was called\r\nConsole: LifeCycleClassCleanupEndOfClassAndNone.Dispose was called" : "Console: LifeCycleClassCleanupEndOfClassAndNone.Dispose was called")} - """); - caseDerivedClassCleanupEndOfClassAndNoneParentTestMethod.Messages[1].Text.Should().Be( + """, + caseDerivedClassCleanupEndOfClassAndNoneParentTestMethod.Messages[0].Text); + Assert.AreEqual( $""" @@ -1517,8 +1472,9 @@ LifeCycleClassCleanupEndOfClassAndBeforeEachDerivedClass.ClassCleanup was called + GenerateTraceDebugPrefixedMessage("LifeCycleClassCleanupEndOfClassAndNone.Dispose was called") : GenerateTraceDebugPrefixedMessage("LifeCycleClassCleanupEndOfClassAndNone.Dispose was called"))} - """); - caseDerivedClassCleanupEndOfClassAndNoneParentTestMethod.Messages[2].Text.Should().Be( + """, + caseDerivedClassCleanupEndOfClassAndNoneParentTestMethod.Messages[1].Text); + Assert.AreEqual( $""" @@ -1534,14 +1490,15 @@ LifeCycleClassCleanupEndOfClassAndNone.TestCleanup was called ? "LifeCycleClassCleanupEndOfClassAndNone.DisposeAsync was called\r\nLifeCycleClassCleanupEndOfClassAndNone.Dispose was called" : "LifeCycleClassCleanupEndOfClassAndNone.Dispose was called")} - """); + """, + caseDerivedClassCleanupEndOfClassAndNoneParentTestMethod.Messages[2].Text); // Test the parent test method. // We are seeing all the ClassCleanup EndOfAssembly (or nothing set - as it's the default) being reported // here as this is the last test to run. - Microsoft.VisualStudio.TestPlatform.ObjectModel.TestResult caseDerivedClassInitializeNoneAndClassCleanupBeforeEachDerivedClassParentTestMethod = RunEventsHandler.PassedTests.Single(x => x.TestCase.FullyQualifiedName.Contains("LifeCycleDerivedClassInitializeNoneAndClassCleanupBeforeEachDerivedClass.TestMethod")); - caseDerivedClassInitializeNoneAndClassCleanupBeforeEachDerivedClassParentTestMethod.Outcome.Should().Be(Microsoft.VisualStudio.TestPlatform.ObjectModel.TestOutcome.Passed); - caseDerivedClassInitializeNoneAndClassCleanupBeforeEachDerivedClassParentTestMethod.Messages.Should().HaveCount(3); + TestResult caseDerivedClassInitializeNoneAndClassCleanupBeforeEachDerivedClassParentTestMethod = RunEventsHandler.PassedTests.Single(x => x.TestCase.FullyQualifiedName.Contains("LifeCycleDerivedClassInitializeNoneAndClassCleanupBeforeEachDerivedClass.TestMethod")); + Assert.AreEqual(TestOutcome.Passed, caseDerivedClassInitializeNoneAndClassCleanupBeforeEachDerivedClassParentTestMethod.Outcome); + Assert.HasCount(3, caseDerivedClassInitializeNoneAndClassCleanupBeforeEachDerivedClassParentTestMethod.Messages); // Locally, netfx calls seems to be respecting the order of the cleanup while it is not stable for netcore. // But local order is not the same on various machines. I am not sure whether we should be committing to a @@ -1560,9 +1517,7 @@ LifeCycleClassCleanupEndOfClassAndNone.TestCleanup was called : "Console: LifeCycleClassInitializeNoneAndClassCleanupBeforeEachDerivedClass.Dispose was called")} """; - caseDerivedClassInitializeNoneAndClassCleanupBeforeEachDerivedClassParentTestMethod - .Messages[0].Text - .Should().StartWith(expectedStart); + Assert.StartsWith(expectedStart, caseDerivedClassInitializeNoneAndClassCleanupBeforeEachDerivedClassParentTestMethod.Messages[0].Text); string[] expectedRemainingMessages = """ @@ -1588,11 +1543,12 @@ LifeCycleClassCleanupEndOfClassAndNone.TestCleanup was called """ .Split(WindowsLineReturn, StringSplitOptions.None); - caseDerivedClassInitializeNoneAndClassCleanupBeforeEachDerivedClassParentTestMethod - .Messages[0].Text! - .Substring(expectedStart.Length) - .Split(WindowsLineReturn, StringSplitOptions.None) - .Should().BeEquivalentTo(expectedRemainingMessages); + CollectionAssert.AreEquivalent( + expectedRemainingMessages, + caseDerivedClassInitializeNoneAndClassCleanupBeforeEachDerivedClassParentTestMethod + .Messages[0].Text! + .Substring(expectedStart.Length) + .Split(WindowsLineReturn, StringSplitOptions.None)); expectedStart = $""" @@ -1613,9 +1569,7 @@ LifeCycleClassCleanupEndOfClassAndNone.TestCleanup was called : GenerateTraceDebugPrefixedMessage("LifeCycleClassInitializeNoneAndClassCleanupBeforeEachDerivedClass.Dispose was called"))} """; - caseDerivedClassInitializeNoneAndClassCleanupBeforeEachDerivedClassParentTestMethod - .Messages[1].Text - .Should().StartWith(expectedStart); + Assert.StartsWith(expectedStart, caseDerivedClassInitializeNoneAndClassCleanupBeforeEachDerivedClassParentTestMethod.Messages[1].Text); expectedRemainingMessages = $""" @@ -1641,11 +1595,12 @@ LifeCycleClassCleanupEndOfClassAndNone.TestCleanup was called """ .Split(["\r\n"], StringSplitOptions.None); - caseDerivedClassInitializeNoneAndClassCleanupBeforeEachDerivedClassParentTestMethod - .Messages[1].Text! - .Substring(expectedStart.Length) - .Split(["\r\n"], StringSplitOptions.None) - .Should().BeEquivalentTo(expectedRemainingMessages); + CollectionAssert.AreEquivalent( + expectedRemainingMessages, + caseDerivedClassInitializeNoneAndClassCleanupBeforeEachDerivedClassParentTestMethod + .Messages[1].Text! + .Substring(expectedStart.Length) + .Split(["\r\n"], StringSplitOptions.None)); expectedStart = $""" @@ -1664,9 +1619,7 @@ LifeCycleClassInitializeNoneAndClassCleanupBeforeEachDerivedClass.TestCleanup wa : "LifeCycleClassInitializeNoneAndClassCleanupBeforeEachDerivedClass.Dispose was called")} """; - caseDerivedClassInitializeNoneAndClassCleanupBeforeEachDerivedClassParentTestMethod - .Messages[2].Text - .Should().StartWith(expectedStart); + Assert.StartsWith(expectedStart, caseDerivedClassInitializeNoneAndClassCleanupBeforeEachDerivedClassParentTestMethod.Messages[2].Text); expectedRemainingMessages = """ @@ -1692,11 +1645,145 @@ AssemblyCleanup was called """ .Split(["\r\n"], StringSplitOptions.None); - caseDerivedClassInitializeNoneAndClassCleanupBeforeEachDerivedClassParentTestMethod - .Messages[2].Text! - .Substring(expectedStart.Length) - .Split(["\r\n"], StringSplitOptions.None) - .Should().BeEquivalentTo(expectedRemainingMessages); + CollectionAssert.AreEquivalent( + expectedRemainingMessages, + caseDerivedClassInitializeNoneAndClassCleanupBeforeEachDerivedClassParentTestMethod + .Messages[2].Text! + .Substring(expectedStart.Length) + .Split(["\r\n"], StringSplitOptions.None)); + } + + [TestMethod] + public void ValidateInheritanceBehavior() + { + InvokeVsTestForExecution( + [TestAssetName], + testCaseFilter: "FullyQualifiedName~LifecycleInheritance", + targetFramework: "net462"); + + Assert.HasCount(10, RunEventsHandler.PassedTests); + + TestResult testMethod1 = RunEventsHandler.PassedTests.Single(x => x.TestCase.FullyQualifiedName.EndsWith("TestClassDerived_EndOfClass.TestMethod", StringComparison.Ordinal)); + Assert.AreEqual( + """ + Console: AssemblyInit was called + TestClassBaseEndOfClass: ClassInitialize + TestClassDerived_EndOfClass: TestMethod + TestClassBaseEndOfClass: ClassCleanup + + """, + testMethod1.Messages[0].Text); + + TestResult testMethod2 = RunEventsHandler.PassedTests.Single(x => x.TestCase.FullyQualifiedName.EndsWith("TestClassDerived_EndOfAssembly.TestMethod", StringComparison.Ordinal)); + Assert.AreEqual( + """ + TestClassBaseEndOfAssembly: ClassInitialize + TestClassDerived_EndOfAssembly: TestMethod + + """, + testMethod2.Messages[0].Text); + + TestResult testMethod3 = RunEventsHandler.PassedTests.Single(x => x.TestCase.FullyQualifiedName.EndsWith("TestClassDerivedEndOfClass_EndOfClassEndOfClass.TestMethod", StringComparison.Ordinal)); + Assert.AreEqual( + """ + TestClassBaseEndOfClass: ClassInitialize + TestClassIntermediateEndOfClassBaseEndOfClass: ClassInitialize + TestClassDerivedEndOfClass_EndOfClassEndOfClass: TestMethod + TestClassDerivedEndOfClass_EndOfClassEndOfClass: ClassCleanup + TestClassIntermediateEndOfClassBaseEndOfClass: ClassCleanup + TestClassBaseEndOfClass: ClassCleanup + + """, + testMethod3.Messages[0].Text); + + TestResult testMethod4 = RunEventsHandler.PassedTests.Single(x => x.TestCase.FullyQualifiedName.EndsWith("TestClassDerived_EndOfClassEndOfClass.TestMethod", StringComparison.Ordinal)); + Assert.AreEqual( + """ + TestClassBaseEndOfClass: ClassInitialize + TestClassIntermediateEndOfClassBaseEndOfClass: ClassInitialize + TestClassDerived_EndOfClassEndOfClass: TestMethod + TestClassIntermediateEndOfClassBaseEndOfClass: ClassCleanup + TestClassBaseEndOfClass: ClassCleanup + + """, + testMethod4.Messages[0].Text); + + TestResult testMethod5 = RunEventsHandler.PassedTests.Single(x => x.TestCase.FullyQualifiedName.EndsWith("TestClassDerivedEndOfClass_EndOfClassEndOfAssembly.TestMethod", StringComparison.Ordinal)); + Assert.AreEqual( + """ + TestClassBaseEndOfAssembly: ClassInitialize + TestClassIntermediateEndOfClassBaseEndOfAssembly: ClassInitialize + TestClassDerivedEndOfClass_EndOfClassEndOfAssembly: TestMethod + TestClassDerivedEndOfClass_EndOfClassEndOfAssembly: ClassCleanup + TestClassIntermediateEndOfClassBaseEndOfAssembly: ClassCleanup + TestClassBaseEndOfAssembly: ClassCleanup + + """, + testMethod5.Messages[0].Text); + + TestResult testMethod6 = RunEventsHandler.PassedTests.Single(x => x.TestCase.FullyQualifiedName.EndsWith("TestClassDerived_EndOfClassEndOfAssembly.TestMethod", StringComparison.Ordinal)); + Assert.AreEqual( + """ + TestClassBaseEndOfAssembly: ClassInitialize + TestClassIntermediateEndOfClassBaseEndOfAssembly: ClassInitialize + TestClassDerived_EndOfClassEndOfAssembly: TestMethod + TestClassIntermediateEndOfClassBaseEndOfAssembly: ClassCleanup + TestClassBaseEndOfAssembly: ClassCleanup + + """, + testMethod6.Messages[0].Text); + + TestResult testMethod7 = RunEventsHandler.PassedTests.Single(x => x.TestCase.FullyQualifiedName.EndsWith("TestClassDerivedEndOfClass_EndOfAssemblyEndOfClass.TestMethod", StringComparison.Ordinal)); + Assert.AreEqual( + """ + TestClassBaseEndOfClass: ClassInitialize + TestClassIntermediateEndOfAssemblyBaseEndOfClass: ClassInitialize + TestClassDerivedEndOfClass_EndOfAssemblyEndOfClass: TestMethod + TestClassDerivedEndOfClass_EndOfAssemblyEndOfClass: ClassCleanup + TestClassIntermediateEndOfAssemblyBaseEndOfClass: ClassCleanup + TestClassBaseEndOfClass: ClassCleanup + + """, + testMethod7.Messages[0].Text); + + TestResult testMethod8 = RunEventsHandler.PassedTests.Single(x => x.TestCase.FullyQualifiedName.EndsWith("TestClassDerived_EndOfAssemblyEndOfClass.TestMethod", StringComparison.Ordinal)); + Assert.AreEqual( + """ + TestClassBaseEndOfClass: ClassInitialize + TestClassIntermediateEndOfAssemblyBaseEndOfClass: ClassInitialize + TestClassDerived_EndOfAssemblyEndOfClass: TestMethod + TestClassIntermediateEndOfAssemblyBaseEndOfClass: ClassCleanup + TestClassBaseEndOfClass: ClassCleanup + + """, + testMethod8.Messages[0].Text); + + TestResult testMethod9 = RunEventsHandler.PassedTests.Single(x => x.TestCase.FullyQualifiedName.EndsWith("TestClassDerivedEndOfClass_EndOfAssemblyEndOfAssembly.TestMethod", StringComparison.Ordinal)); + Assert.AreEqual( + """ + TestClassBaseEndOfAssembly: ClassInitialize + TestClassIntermediateEndOfAssemblyBaseEndOfAssembly: ClassInitialize + TestClassDerivedEndOfClass_EndOfAssemblyEndOfAssembly: TestMethod + TestClassDerivedEndOfClass_EndOfAssemblyEndOfAssembly: ClassCleanup + TestClassIntermediateEndOfAssemblyBaseEndOfAssembly: ClassCleanup + TestClassBaseEndOfAssembly: ClassCleanup + + """, + testMethod9.Messages[0].Text); + + TestResult testMethod10 = RunEventsHandler.PassedTests.Single(x => x.TestCase.FullyQualifiedName.EndsWith("TestClassDerived_EndOfAssemblyEndOfAssembly.TestMethod", StringComparison.Ordinal)); + Assert.AreEqual( + """ + TestClassBaseEndOfAssembly: ClassInitialize + TestClassIntermediateEndOfAssemblyBaseEndOfAssembly: ClassInitialize + TestClassDerived_EndOfAssemblyEndOfAssembly: TestMethod + TestClassIntermediateEndOfAssemblyBaseEndOfAssembly: ClassCleanup + TestClassBaseEndOfAssembly: ClassCleanup + TestClassBaseEndOfAssembly: ClassCleanup + Console: AssemblyCleanup was called + + """, + testMethod10.Messages[0].Text); } private static string GenerateTraceDebugPrefixedMessage(string message) diff --git a/test/IntegrationTests/MSTest.VstestConsoleWrapper.IntegrationTests/TestProjectFSharpTests.cs b/test/IntegrationTests/MSTest.VstestConsoleWrapper.IntegrationTests/TestProjectFSharpTests.cs index 10e8998336..472dbd5886 100644 --- a/test/IntegrationTests/MSTest.VstestConsoleWrapper.IntegrationTests/TestProjectFSharpTests.cs +++ b/test/IntegrationTests/MSTest.VstestConsoleWrapper.IntegrationTests/TestProjectFSharpTests.cs @@ -5,10 +5,12 @@ namespace MSTest.VstestConsoleWrapper.IntegrationTests; +[TestClass] public class TestProjectFSharpTests : CLITestBase { private const string TestAssetName = "FSharpTestProject"; + [TestMethod] public void ExecuteCustomTestExtensibilityTests() { InvokeVsTestForExecution([TestAssetName], targetFramework: "net472"); diff --git a/test/IntegrationTests/MSTest.VstestConsoleWrapper.IntegrationTests/TimeoutTests.cs b/test/IntegrationTests/MSTest.VstestConsoleWrapper.IntegrationTests/TimeoutTests.cs index d48e07480c..81358f7b32 100644 --- a/test/IntegrationTests/MSTest.VstestConsoleWrapper.IntegrationTests/TimeoutTests.cs +++ b/test/IntegrationTests/MSTest.VstestConsoleWrapper.IntegrationTests/TimeoutTests.cs @@ -1,21 +1,19 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. -using FluentAssertions; - using Microsoft.MSTestV2.CLIAutomation; namespace MSTest.VstestConsoleWrapper.IntegrationTests; +[TestClass] public class TimeoutTests : CLITestBase { private const string TestAssetName = "TimeoutTestProject"; - public void ValidateTimeoutTests_net462() => ValidateTimeoutTests("net462"); - - public void ValidateTimeoutTests_netcoreapp31() => ValidateTimeoutTests("netcoreapp3.1"); - - private void ValidateTimeoutTests(string targetFramework) + [TestMethod] + [DataRow("net462")] + [DataRow("netcoreapp3.1")] + public void ValidateTimeoutTests(string targetFramework) { InvokeVsTestForExecution([TestAssetName], testCaseFilter: "TimeoutTest|RegularTest", targetFramework: targetFramework); @@ -42,6 +40,6 @@ private void ValidateTimeoutTests(string targetFramework) GetAssetFullPath(TestAssetName, targetFramework: targetFramework), "..", "TimeoutTestOutput.txt"); - File.Exists(timeoutFile).Should().BeTrue(); + Assert.IsTrue(File.Exists(timeoutFile), $"Timeout output file not found: {timeoutFile}"); } } diff --git a/test/Utilities/Automation.CLI/Automation.CLI.csproj b/test/Utilities/Automation.CLI/Automation.CLI.csproj index f37826a486..6b62895628 100644 --- a/test/Utilities/Automation.CLI/Automation.CLI.csproj +++ b/test/Utilities/Automation.CLI/Automation.CLI.csproj @@ -1,19 +1,17 @@ - + $(NetFrameworkMinimum) - - - + diff --git a/test/Utilities/Automation.CLI/CLITestBase.common.cs b/test/Utilities/Automation.CLI/CLITestBase.common.cs index 32762b329b..8a59fa515c 100644 --- a/test/Utilities/Automation.CLI/CLITestBase.common.cs +++ b/test/Utilities/Automation.CLI/CLITestBase.common.cs @@ -1,13 +1,11 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. -using FluentAssertions; - -using TestFramework.ForTestingMSTest; +using Assert = Microsoft.VisualStudio.TestTools.UnitTesting.Assert; namespace Microsoft.MSTestV2.CLIAutomation; -public partial class CLITestBase : TestContainer +public abstract partial class CLITestBase { private const string Configuration = #if DEBUG @@ -45,7 +43,7 @@ protected static string GetArtifactsBinFolderPath() string assemblyLocation = Assembly.GetExecutingAssembly().Location; string artifactsBinFolder = Path.GetFullPath(Path.Combine(assemblyLocation, @"..\..\..\..")); - Directory.Exists(artifactsBinFolder).Should().BeTrue(); + Assert.IsTrue(Directory.Exists(artifactsBinFolder)); return artifactsBinFolder; } @@ -55,7 +53,7 @@ protected static string GetArtifactsTestResultsFolderPath() string assemblyLocation = Assembly.GetExecutingAssembly().Location; string artifactsFolder = Path.GetFullPath(Path.Combine(assemblyLocation, @"..\..\..\..\..")); - Directory.Exists(artifactsFolder).Should().BeTrue(); + Assert.IsTrue(Directory.Exists(artifactsFolder)); string testResultsFolder = Path.Combine(artifactsFolder, "TestResults", Configuration); Directory.CreateDirectory(testResultsFolder); @@ -68,7 +66,7 @@ protected static string GetAssetFullPath(string assetName, string? configuration configuration ??= Configuration; targetFramework ??= DefaultTargetFramework; string assetPath = Path.GetFullPath(Path.Combine(GetArtifactsBinFolderPath(), assetName, configuration, targetFramework, assetName + ".dll")); - File.Exists(assetPath).Should().BeTrue($"asset '{assetPath}' should exist"); + Assert.IsTrue(File.Exists(assetPath), $"asset '{assetPath}' should exist"); return assetPath; } diff --git a/test/Utilities/Automation.CLI/CLITestBase.e2e.cs b/test/Utilities/Automation.CLI/CLITestBase.e2e.cs index f49ad93ef1..76d01fb92b 100644 --- a/test/Utilities/Automation.CLI/CLITestBase.e2e.cs +++ b/test/Utilities/Automation.CLI/CLITestBase.e2e.cs @@ -1,21 +1,18 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. -using FluentAssertions; - using Microsoft.TestPlatform.VsTestConsole.TranslationLayer; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Client; - -using TestFramework.ForTestingMSTest; +using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Microsoft.MSTestV2.CLIAutomation; -public partial class CLITestBase : TestContainer +public abstract partial class CLITestBase { private static VsTestConsoleWrapper? s_vsTestConsoleWrapper; private DiscoveryEventsHandler? _discoveryEventsHandler; - public CLITestBase() + protected CLITestBase() { s_vsTestConsoleWrapper = new( GetConsoleRunnerPath(), @@ -73,14 +70,14 @@ public static string GetNugetPackageFolder() string nugetPackagesFolderPath = Environment.GetEnvironmentVariable("NUGET_PACKAGES"); if (!string.IsNullOrEmpty(nugetPackagesFolderPath)) { - Directory.Exists(nugetPackagesFolderPath).Should().BeTrue($"Found environment variable 'NUGET_PACKAGES' and NuGet package folder '{nugetPackagesFolderPath}' should exist"); + Assert.IsTrue(Directory.Exists(nugetPackagesFolderPath), $"Found environment variable 'NUGET_PACKAGES' and NuGet package folder '{nugetPackagesFolderPath}' should exist"); return nugetPackagesFolderPath; } string userProfile = Environment.GetEnvironmentVariable("USERPROFILE"); nugetPackagesFolderPath = Path.Combine(userProfile, ".nuget", "packages"); - Directory.Exists(nugetPackagesFolderPath).Should().BeTrue($"NuGet package folder '{nugetPackagesFolderPath}' should exist"); + Assert.IsTrue(Directory.Exists(nugetPackagesFolderPath), $"NuGet package folder '{nugetPackagesFolderPath}' should exist"); return nugetPackagesFolderPath; } @@ -122,13 +119,11 @@ public void ValidateDiscoveredTests(params string[] discoveredTestsList) { foreach (string test in discoveredTestsList) { - bool flag = _discoveryEventsHandler!.Tests.Contains(test) - || _discoveryEventsHandler.Tests.Contains(GetTestMethodName(test)); - flag.Should().BeTrue("Test '{0}' does not appear in discovered tests list.", test); + Assert.IsTrue(_discoveryEventsHandler!.Tests.Contains(test) || _discoveryEventsHandler.Tests.Contains(GetTestMethodName(test)), $"Test '{test}' does not appear in discovered tests list."); } // Make sure only expected number of tests are discovered and not more. - discoveredTestsList.Should().HaveSameCount(_discoveryEventsHandler!.Tests); + Assert.AreEqual(_discoveryEventsHandler!.Tests.Length, discoveredTestsList.Length); } /// @@ -144,7 +139,7 @@ public void ValidatePassedTests(params string[] passedTests) public void ValidatePassedTestsCount(int expectedPassedTestsCount) => // Make sure only expected number of tests passed and not more. - RunEventsHandler.PassedTests.Should().HaveCount(expectedPassedTestsCount); + Assert.HasCount(expectedPassedTestsCount, RunEventsHandler.PassedTests); /// /// Validates if the test results have the specified set of failed tests. @@ -181,7 +176,7 @@ public void ValidateFailedTests(bool validateStackTraceInfo, params string[] fai /// Expected failed tests count. public void ValidateFailedTestsCount(int expectedFailedTestsCount) => // Make sure only expected number of tests failed and not more. - RunEventsHandler.FailedTests.Should().HaveCount(expectedFailedTestsCount); + Assert.HasCount(expectedFailedTestsCount, RunEventsHandler.FailedTests); /// /// Validates if the test results have the specified set of skipped tests. @@ -191,8 +186,7 @@ public void ValidateFailedTestsCount(int expectedFailedTestsCount) => public void ValidateSkippedTests(params string[] skippedTests) { // Make sure only expected number of tests skipped and not more. - RunEventsHandler.SkippedTests.Should().HaveSameCount(skippedTests); - + Assert.AreEqual(skippedTests.Length, RunEventsHandler.SkippedTests.Count); ValidateSkippedTestsContain(skippedTests); } @@ -222,10 +216,11 @@ public void ValidatePassedTestsContain(params string[] passedTests) string failedOrSkippedMessage = isFailed ? " (Test failed)" : isSkipped ? " (Test skipped)" : string.Empty; - passedTestResults.Should().Contain( + Assert.Contains( p => test.Equals(p.TestCase.FullyQualifiedName, StringComparison.Ordinal) || test.Equals(p.DisplayName, StringComparison.Ordinal) || test.Equals(p.TestCase.DisplayName, StringComparison.Ordinal), + passedTestResults, $"Test '{test}' does not appear in passed tests list." + failedOrSkippedMessage); } } @@ -246,7 +241,7 @@ public void ValidateFailedTestsContain(bool validateStackTraceInfo, params strin { VisualStudio.TestPlatform.ObjectModel.TestResult testFound = RunEventsHandler.FailedTests.FirstOrDefault(f => test.Equals(f.TestCase?.FullyQualifiedName, StringComparison.Ordinal) || test.Equals(f.DisplayName, StringComparison.Ordinal)); - testFound.Should().NotBeNull("Test '{0}' does not appear in failed tests list.", test); + Assert.IsNotNull(testFound, "Test '{0}' does not appear in failed tests list.", test); #if DEBUG if (!validateStackTraceInfo) @@ -254,12 +249,15 @@ public void ValidateFailedTestsContain(bool validateStackTraceInfo, params strin continue; } - testFound.ErrorStackTrace.Should().NotBeNullOrWhiteSpace($"The test failure {testFound.DisplayName ?? testFound.TestCase.FullyQualifiedName} with message {testFound.ErrorMessage} lacks stack trace."); + Assert.IsFalse( + string.IsNullOrWhiteSpace(testFound.ErrorStackTrace), + $"The test failure {testFound.DisplayName ?? testFound.TestCase.FullyQualifiedName} with message {testFound.ErrorMessage} lacks stack trace."); // If test name is not empty, verify stack information as well. if (GetTestMethodName(test) is { Length: > 0 } testMethodName) { - testFound.ErrorStackTrace.Should().Contain(testMethodName, "No stack trace for failed test: {0}", test); + Assert.IsNotNull(testFound.ErrorStackTrace); + Assert.Contains(testMethodName, testFound.ErrorStackTrace, $"No stack trace for failed test: {test}"); } #endif } @@ -275,17 +273,17 @@ public void ValidateSkippedTestsContain(params string[] skippedTests) { foreach (string test in skippedTests) { - RunEventsHandler.SkippedTests.Should().Contain( + Assert.Contains( s => test.Equals(s.TestCase.FullyQualifiedName, StringComparison.Ordinal) || test.Equals(s.DisplayName, StringComparison.Ordinal), - "Test '{0}' does not appear in skipped tests list.", test); + RunEventsHandler.SkippedTests, + $"Test '{test}' does not appear in skipped tests list."); } } public void ValidateTestRunTime(int thresholdTime) - { - bool time = RunEventsHandler.ElapsedTimeInRunningTests >= 0 && RunEventsHandler.ElapsedTimeInRunningTests < thresholdTime; - time.Should().BeTrue($"Test Run was expected to not exceed {thresholdTime} but it took {RunEventsHandler.ElapsedTimeInRunningTests}"); - } + => Assert.IsTrue( + RunEventsHandler.ElapsedTimeInRunningTests >= 0 && RunEventsHandler.ElapsedTimeInRunningTests < thresholdTime, + $"Test Run was expected to not exceed {thresholdTime} but it took {RunEventsHandler.ElapsedTimeInRunningTests}"); /// /// Gets the test method name from full name. From 6f52f986b3872afbc5f7579abbb30aa923f97a19 Mon Sep 17 00:00:00 2001 From: Copilot <198982749+Copilot@users.noreply.github.com> Date: Wed, 30 Jul 2025 12:53:30 +0200 Subject: [PATCH 331/541] Add analyzer to flag Assert.Throws with multiple statements (MSTEST0050) (#6190) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: Evangelink <11340282+Evangelink@users.noreply.github.com> Co-authored-by: Amaury Levé --- Directory.Packages.props | 4 + .../AnalyzerReleases.Unshipped.md | 6 + ...owsShouldContainSingleStatementAnalyzer.cs | 122 ++++ .../MSTest.Analyzers/Helpers/DiagnosticIds.cs | 1 + .../MSTest.Analyzers/Resources.Designer.cs | 317 ++++----- src/Analyzers/MSTest.Analyzers/Resources.resx | 9 + .../MSTest.Analyzers/xlf/Resources.cs.xlf | 15 + .../MSTest.Analyzers/xlf/Resources.de.xlf | 15 + .../MSTest.Analyzers/xlf/Resources.es.xlf | 15 + .../MSTest.Analyzers/xlf/Resources.fr.xlf | 17 +- .../MSTest.Analyzers/xlf/Resources.it.xlf | 17 +- .../MSTest.Analyzers/xlf/Resources.ja.xlf | 23 +- .../MSTest.Analyzers/xlf/Resources.ko.xlf | 29 +- .../MSTest.Analyzers/xlf/Resources.pl.xlf | 17 +- .../MSTest.Analyzers/xlf/Resources.pt-BR.xlf | 17 +- .../MSTest.Analyzers/xlf/Resources.ru.xlf | 17 +- .../MSTest.Analyzers/xlf/Resources.tr.xlf | 17 +- .../xlf/Resources.zh-Hans.xlf | 17 +- .../xlf/Resources.zh-Hant.xlf | 17 +- ...ouldContainSingleStatementAnalyzerTests.cs | 605 ++++++++++++++++++ .../MSTest.Analyzers.UnitTests.csproj | 4 +- .../VisualBasicCodeFixVerifier`2+Test.cs | 33 + .../Verifiers/VisualBasicCodeFixVerifier`2.cs | 64 ++ 23 files changed, 1233 insertions(+), 165 deletions(-) create mode 100644 src/Analyzers/MSTest.Analyzers/AssertThrowsShouldContainSingleStatementAnalyzer.cs create mode 100644 test/UnitTests/MSTest.Analyzers.UnitTests/AssertThrowsShouldContainSingleStatementAnalyzerTests.cs create mode 100644 test/UnitTests/MSTest.Analyzers.UnitTests/Verifiers/VisualBasicCodeFixVerifier`2+Test.cs create mode 100644 test/UnitTests/MSTest.Analyzers.UnitTests/Verifiers/VisualBasicCodeFixVerifier`2.cs diff --git a/Directory.Packages.props b/Directory.Packages.props index 674c59ac55..9d6d463190 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -62,6 +62,10 @@ + + + + diff --git a/src/Analyzers/MSTest.Analyzers/AnalyzerReleases.Unshipped.md b/src/Analyzers/MSTest.Analyzers/AnalyzerReleases.Unshipped.md index f2b7fad657..967b851f18 100644 --- a/src/Analyzers/MSTest.Analyzers/AnalyzerReleases.Unshipped.md +++ b/src/Analyzers/MSTest.Analyzers/AnalyzerReleases.Unshipped.md @@ -1,2 +1,8 @@ ; Unshipped analyzer release ; https://github.com/dotnet/roslyn-analyzers/blob/main/src/Microsoft.CodeAnalysis.Analyzers/ReleaseTrackingAnalyzers.Help.md + +### New Rules + +Rule ID | Category | Severity | Notes +--------|----------|----------|------- +MSTEST0051 | Usage | Info | AssertThrowsShouldContainSingleStatementAnalyzer, [Documentation](https://learn.microsoft.com/dotnet/core/testing/mstest-analyzers/mstest0051) diff --git a/src/Analyzers/MSTest.Analyzers/AssertThrowsShouldContainSingleStatementAnalyzer.cs b/src/Analyzers/MSTest.Analyzers/AssertThrowsShouldContainSingleStatementAnalyzer.cs new file mode 100644 index 0000000000..ef41149c65 --- /dev/null +++ b/src/Analyzers/MSTest.Analyzers/AssertThrowsShouldContainSingleStatementAnalyzer.cs @@ -0,0 +1,122 @@ +// 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.Immutable; + +using Analyzer.Utilities.Extensions; + +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Diagnostics; +using Microsoft.CodeAnalysis.Operations; + +using MSTest.Analyzers.Helpers; +using MSTest.Analyzers.RoslynAnalyzerHelpers; + +namespace MSTest.Analyzers; + +/// +/// MSTEST0051: Assert.Throws should contain only a single statement/expression. +/// +[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] +public sealed class AssertThrowsShouldContainSingleStatementAnalyzer : DiagnosticAnalyzer +{ + private static readonly LocalizableResourceString Title = new(nameof(Resources.AssertThrowsShouldContainSingleStatementTitle), Resources.ResourceManager, typeof(Resources)); + private static readonly LocalizableResourceString MessageFormat = new(nameof(Resources.AssertThrowsShouldContainSingleStatementMessageFormat), Resources.ResourceManager, typeof(Resources)); + private static readonly LocalizableResourceString Description = new(nameof(Resources.AssertThrowsShouldContainSingleStatementDescription), Resources.ResourceManager, typeof(Resources)); + + internal static readonly DiagnosticDescriptor Rule = DiagnosticDescriptorHelper.Create( + DiagnosticIds.AssertThrowsShouldContainSingleStatementRuleId, + Title, + MessageFormat, + Description, + Category.Usage, + DiagnosticSeverity.Info, + isEnabledByDefault: true); + + /// + public override ImmutableArray SupportedDiagnostics { get; } + = ImmutableArray.Create(Rule); + + /// + public override void Initialize(AnalysisContext context) + { + context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); + context.EnableConcurrentExecution(); + + context.RegisterCompilationStartAction(context => + { + if (!context.Compilation.TryGetOrCreateTypeByMetadataName(WellKnownTypeNames.MicrosoftVisualStudioTestToolsUnitTestingAssert, out INamedTypeSymbol? assertTypeSymbol)) + { + return; + } + + context.RegisterOperationAction(context => AnalyzeInvocationOperation(context, assertTypeSymbol), OperationKind.Invocation); + }); + } + + private static void AnalyzeInvocationOperation(OperationAnalysisContext context, INamedTypeSymbol assertTypeSymbol) + { + var operation = (IInvocationOperation)context.Operation; + IMethodSymbol targetMethod = operation.TargetMethod; + + if (!SymbolEqualityComparer.Default.Equals(targetMethod.ContainingType, assertTypeSymbol) || + !targetMethod.Name.StartsWith("Throws", StringComparison.Ordinal)) + { + return; + } + + // Find the action parameter (lambda expression) - it's typically the first parameter + foreach (IArgumentOperation argument in operation.Arguments) + { + if (argument.Parameter?.Ordinal == 0) + { + AnalyzeActionArgument(context, argument.Value.WalkDownConversion(), operation); + break; + } + } + } + + private static void AnalyzeActionArgument(OperationAnalysisContext context, IOperation argumentValueOperation, IInvocationOperation invocationOperation) + { + if (argumentValueOperation is not IDelegateCreationOperation delegateCreation || + delegateCreation.Target is not IAnonymousFunctionOperation lambdaOperation || + lambdaOperation.Body is not IBlockOperation blockOperation) + { + return; + } + + // Flag if there are multiple meaningful statements + if (CountStatements(blockOperation) > 1) + { + context.ReportDiagnostic(invocationOperation.CreateDiagnostic(Rule)); + } + } + + private static int CountStatements(IBlockOperation blockOperation) + { + int statementCount = 0; + foreach (IOperation operation in blockOperation.Operations) + { + // Skip implicit return/labeled operations. + // Implicit returns don't represent user code. + // Implicit labeled operations seem to be created for lambdas only under VB. But we don't do a language check. + // TODO: Should we bail-out for any implicit operation? + if (operation is IReturnOperation or ILabeledOperation && operation.IsImplicit) + { + continue; + } + + // Skip empty statements + if (operation is IEmptyOperation) + { + continue; + } + + // If we have a nested block operation, we add the count of the statements within it. Otherwise, + // we increment by one. + statementCount += operation is IBlockOperation nestedBlock ? CountStatements(nestedBlock) : 1; + } + + return statementCount; + } +} diff --git a/src/Analyzers/MSTest.Analyzers/Helpers/DiagnosticIds.cs b/src/Analyzers/MSTest.Analyzers/Helpers/DiagnosticIds.cs index 5b31df82e2..fd6aac276f 100644 --- a/src/Analyzers/MSTest.Analyzers/Helpers/DiagnosticIds.cs +++ b/src/Analyzers/MSTest.Analyzers/Helpers/DiagnosticIds.cs @@ -55,4 +55,5 @@ internal static class DiagnosticIds public const string TestContextPropertyUsageRuleId = "MSTEST0048"; public const string FlowTestContextCancellationTokenRuleId = "MSTEST0049"; public const string GlobalTestFixtureShouldBeValidRuleId = "MSTEST0050"; + public const string AssertThrowsShouldContainSingleStatementRuleId = "MSTEST0051"; } diff --git a/src/Analyzers/MSTest.Analyzers/Resources.Designer.cs b/src/Analyzers/MSTest.Analyzers/Resources.Designer.cs index d81903f9ed..e011d0724d 100644 --- a/src/Analyzers/MSTest.Analyzers/Resources.Designer.cs +++ b/src/Analyzers/MSTest.Analyzers/Resources.Designer.cs @@ -10,8 +10,8 @@ namespace MSTest.Analyzers { using System; - - + + /// /// A strongly-typed resource class, for looking up localized strings, etc. /// @@ -23,15 +23,15 @@ namespace MSTest.Analyzers { [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { - + private static global::System.Resources.ResourceManager resourceMan; - + private static global::System.Globalization.CultureInfo resourceCulture; - + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } - + /// /// Returns the cached ResourceManager instance used by this class. /// @@ -45,7 +45,7 @@ internal Resources() { return resourceMan; } } - + /// /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. @@ -59,7 +59,7 @@ internal Resources() { resourceCulture = value; } } - + /// /// Looks up a localized string similar to Methods marked with '[AssemblyCleanup]' should follow the following layout to be valid: ///-it can't be declared on a generic class @@ -78,7 +78,7 @@ internal static string AssemblyCleanupShouldBeValidDescription { return ResourceManager.GetString("AssemblyCleanupShouldBeValidDescription", resourceCulture); } } - + /// /// Looks up a localized string similar to AssemblyCleanup method '{0}' signature is invalid. /// @@ -87,7 +87,7 @@ internal static string AssemblyCleanupShouldBeValidMessageFormat { return ResourceManager.GetString("AssemblyCleanupShouldBeValidMessageFormat", resourceCulture); } } - + /// /// Looks up a localized string similar to AssemblyCleanup methods should have valid layout. /// @@ -96,7 +96,7 @@ internal static string AssemblyCleanupShouldBeValidTitle { return ResourceManager.GetString("AssemblyCleanupShouldBeValidTitle", resourceCulture); } } - + /// /// Looks up a localized string similar to Methods marked with '[AssemblyInitialize]' should follow the following layout to be valid: ///-it can't be declared on a generic class @@ -116,7 +116,7 @@ internal static string AssemblyInitializeShouldBeValidDescription { return ResourceManager.GetString("AssemblyInitializeShouldBeValidDescription", resourceCulture); } } - + /// /// Looks up a localized string similar to AssemblyInitialize method '{0}' signature is invalid. /// @@ -125,7 +125,7 @@ internal static string AssemblyInitializeShouldBeValidMessageFormat { return ResourceManager.GetString("AssemblyInitializeShouldBeValidMessageFormat", resourceCulture); } } - + /// /// Looks up a localized string similar to AssemblyInitialize methods should have valid layout. /// @@ -134,7 +134,7 @@ internal static string AssemblyInitializeShouldBeValidTitle { return ResourceManager.GetString("AssemblyInitializeShouldBeValidTitle", resourceCulture); } } - + /// /// Looks up a localized string similar to Prefer adding an additional assertion that checks for null. /// @@ -143,7 +143,7 @@ internal static string AssertionArgsShouldAvoidConditionalAccessMessageFormat { return ResourceManager.GetString("AssertionArgsShouldAvoidConditionalAccessMessageFormat", resourceCulture); } } - + /// /// Looks up a localized string similar to Avoid conditional access in assertions. /// @@ -152,7 +152,7 @@ internal static string AssertionArgsShouldAvoidConditionalAccessTitle { return ResourceManager.GetString("AssertionArgsShouldAvoidConditionalAccessTitle", resourceCulture); } } - + /// /// Looks up a localized string similar to 'Assert.AreEqual', 'Assert.AreNotEqual', 'Assert.AreSame' and 'Assert.AreNotSame' expects the expected value to be passed first and the actual value to be passed as second argument.. /// @@ -161,7 +161,7 @@ internal static string AssertionArgsShouldBePassedInCorrectOrderDescription { return ResourceManager.GetString("AssertionArgsShouldBePassedInCorrectOrderDescription", resourceCulture); } } - + /// /// Looks up a localized string similar to Assertion arguments should be passed in the correct order. 'actual' and 'expected'/'notExpected' arguments have been swapped.. /// @@ -170,7 +170,7 @@ internal static string AssertionArgsShouldBePassedInCorrectOrderMessageFormat { return ResourceManager.GetString("AssertionArgsShouldBePassedInCorrectOrderMessageFormat", resourceCulture); } } - + /// /// Looks up a localized string similar to Assertion arguments should be passed in the correct order. /// @@ -179,7 +179,7 @@ internal static string AssertionArgsShouldBePassedInCorrectOrderTitle { return ResourceManager.GetString("AssertionArgsShouldBePassedInCorrectOrderTitle", resourceCulture); } } - + /// /// Looks up a localized string similar to Use 'Assert.AreEqual'/'Assert.AreNotEqual' instead of 'Assert.AreSame'/'Assert.AreNotSame' when comparing value types. Passing a value type to 'Assert.AreSame'/'Assert.AreNotSame' will be boxed (creating a new object). Because 'Assert.AreSame'/'Assert.AreNotSame' does the comparison by reference, 'Assert.AreSame' will fail when boxing happens, and 'Assert.AreNotSame' will always pass.. /// @@ -188,7 +188,7 @@ internal static string AvoidAssertAreSameWithValueTypesDescription { return ResourceManager.GetString("AvoidAssertAreSameWithValueTypesDescription", resourceCulture); } } - + /// /// Looks up a localized string similar to Use '{0}' instead of '{1}' when comparing value types. /// @@ -197,7 +197,7 @@ internal static string AvoidAssertAreSameWithValueTypesMessageFormat { return ResourceManager.GetString("AvoidAssertAreSameWithValueTypesMessageFormat", resourceCulture); } } - + /// /// Looks up a localized string similar to Don't use 'Assert.AreSame' or 'Assert.AreNotSame' with value types. /// @@ -206,7 +206,7 @@ internal static string AvoidAssertAreSameWithValueTypesTitle { return ResourceManager.GetString("AvoidAssertAreSameWithValueTypesTitle", resourceCulture); } } - + /// /// Looks up a localized string similar to Prefer 'Assert.ThrowsExactly' or 'Assert.ThrowsExactlyAsync' over '[ExpectedException]' as it ensures that only the expected call throws the expected exception. The assert APIs also provide more flexibility and allow you to assert extra properties of the exception.. /// @@ -215,7 +215,7 @@ internal static string AvoidExpectedExceptionAttributeDescription { return ResourceManager.GetString("AvoidExpectedExceptionAttributeDescription", resourceCulture); } } - + /// /// Looks up a localized string similar to Prefer 'Assert.ThrowsExactly/ThrowsExactlyAsync' over '[ExpectedException]'. /// @@ -224,7 +224,7 @@ internal static string AvoidExpectedExceptionAttributeMessageFormat { return ResourceManager.GetString("AvoidExpectedExceptionAttributeMessageFormat", resourceCulture); } } - + /// /// Looks up a localized string similar to Avoid '[ExpectedException]'. /// @@ -233,7 +233,7 @@ internal static string AvoidExpectedExceptionAttributeTitle { return ResourceManager.GetString("AvoidExpectedExceptionAttributeTitle", resourceCulture); } } - + /// /// Looks up a localized string similar to Do not assert inside 'async void' methods, local functions, or lambdas. Exceptions that are thrown in this context will be unhandled exceptions. When using VSTest under .NET Framework, they will be silently swallowed. When using Microsoft.Testing.Platform or VSTest under modern .NET, they may crash the process.. /// @@ -242,7 +242,7 @@ internal static string AvoidUsingAssertsInAsyncVoidContextDescription { return ResourceManager.GetString("AvoidUsingAssertsInAsyncVoidContextDescription", resourceCulture); } } - + /// /// Looks up a localized string similar to Do not assert inside 'async void' methods, local functions, or lambdas because they may not fail the test. /// @@ -251,7 +251,7 @@ internal static string AvoidUsingAssertsInAsyncVoidContextMessageFormat { return ResourceManager.GetString("AvoidUsingAssertsInAsyncVoidContextMessageFormat", resourceCulture); } } - + /// /// Looks up a localized string similar to Do not assert inside 'async void' contexts. /// @@ -260,7 +260,7 @@ internal static string AvoidUsingAssertsInAsyncVoidContextTitle { return ResourceManager.GetString("AvoidUsingAssertsInAsyncVoidContextTitle", resourceCulture); } } - + /// /// Looks up a localized string similar to Methods marked with '[ClassCleanup]' should follow the following layout to be valid: ///-it can't be declared on a generic class without the 'InheritanceBehavior' mode is set @@ -278,7 +278,7 @@ internal static string ClassCleanupShouldBeValidDescription { return ResourceManager.GetString("ClassCleanupShouldBeValidDescription", resourceCulture); } } - + /// /// Looks up a localized string similar to ClassCleanup method '{0}' signature is invalid. /// @@ -287,7 +287,7 @@ internal static string ClassCleanupShouldBeValidMessageFormat { return ResourceManager.GetString("ClassCleanupShouldBeValidMessageFormat", resourceCulture); } } - + /// /// Looks up a localized string similar to ClassCleanup methods should have valid layout. /// @@ -296,7 +296,7 @@ internal static string ClassCleanupShouldBeValidTitle { return ResourceManager.GetString("ClassCleanupShouldBeValidTitle", resourceCulture); } } - + /// /// Looks up a localized string similar to Methods marked with '[ClassInitialize]' should follow the following layout to be valid: ///-it can't be declared on a generic class without the 'InheritanceBehavior' mode is set @@ -314,7 +314,7 @@ internal static string ClassInitializeShouldBeValidDescription { return ResourceManager.GetString("ClassInitializeShouldBeValidDescription", resourceCulture); } } - + /// /// Looks up a localized string similar to ClassInitialize method '{0}' signature is invalid. /// @@ -323,7 +323,7 @@ internal static string ClassInitializeShouldBeValidMessageFormat { return ResourceManager.GetString("ClassInitializeShouldBeValidMessageFormat", resourceCulture); } } - + /// /// Looks up a localized string similar to ClassInitialize methods should have valid layout. /// @@ -332,7 +332,7 @@ internal static string ClassInitializeShouldBeValidTitle { return ResourceManager.GetString("ClassInitializeShouldBeValidTitle", resourceCulture); } } - + /// /// Looks up a localized string similar to DataRow entry should have the following layout to be valid: ///- should only be set on a test method; @@ -344,7 +344,7 @@ internal static string DataRowShouldBeValidDescription { return ResourceManager.GetString("DataRowShouldBeValidDescription", resourceCulture); } } - + /// /// Looks up a localized string similar to DataRow argument count should match method parameter count (constructor arguments: {0}, method parameters: {1}). /// @@ -353,7 +353,7 @@ internal static string DataRowShouldBeValidMessageFormat_ArgumentCountMismatch { return ResourceManager.GetString("DataRowShouldBeValidMessageFormat_ArgumentCountMismatch", resourceCulture); } } - + /// /// Looks up a localized string similar to DataRow argument types do not match method parameter types. {0}. /// @@ -362,7 +362,7 @@ internal static string DataRowShouldBeValidMessageFormat_ArgumentTypeMismatch { return ResourceManager.GetString("DataRowShouldBeValidMessageFormat_ArgumentTypeMismatch", resourceCulture); } } - + /// /// Looks up a localized string similar to Found two conflicting types for generic parameter '{0}'. The conflicting types are '{1}' and '{2}'.. /// @@ -371,7 +371,7 @@ internal static string DataRowShouldBeValidMessageFormat_GenericTypeArgumentConf return ResourceManager.GetString("DataRowShouldBeValidMessageFormat_GenericTypeArgumentConflictingTypes", resourceCulture); } } - + /// /// Looks up a localized string similar to The type of the generic parameter '{0}' could not be inferred.. /// @@ -380,7 +380,7 @@ internal static string DataRowShouldBeValidMessageFormat_GenericTypeArgumentNotR return ResourceManager.GetString("DataRowShouldBeValidMessageFormat_GenericTypeArgumentNotResolved", resourceCulture); } } - + /// /// Looks up a localized string similar to DataRow should only be set on a test method. /// @@ -389,7 +389,7 @@ internal static string DataRowShouldBeValidMessageFormat_OnTestMethod { return ResourceManager.GetString("DataRowShouldBeValidMessageFormat_OnTestMethod", resourceCulture); } } - + /// /// Looks up a localized string similar to Parameter '{0}' expects type '{1}', but the provided value has type '{2}'. /// @@ -398,7 +398,7 @@ internal static string DataRowShouldBeValidMessageFormat_ParameterMismatch { return ResourceManager.GetString("DataRowShouldBeValidMessageFormat_ParameterMismatch", resourceCulture); } } - + /// /// Looks up a localized string similar to DataRow should be valid. /// @@ -407,7 +407,7 @@ internal static string DataRowShouldBeValidTitle { return ResourceManager.GetString("DataRowShouldBeValidTitle", resourceCulture); } } - + /// /// Looks up a localized string similar to Do not negate boolean assertions, instead use the opposite assertion. /// @@ -416,7 +416,7 @@ internal static string DoNotNegateBooleanAssertionMessageFormat { return ResourceManager.GetString("DoNotNegateBooleanAssertionMessageFormat", resourceCulture); } } - + /// /// Looks up a localized string similar to Do not negate boolean assertions. /// @@ -425,7 +425,7 @@ internal static string DoNotNegateBooleanAssertionTitle { return ResourceManager.GetString("DoNotNegateBooleanAssertionTitle", resourceCulture); } } - + /// /// Looks up a localized string similar to Do not store TestContext in a static member. /// @@ -434,7 +434,7 @@ internal static string DoNotStoreStaticTestContextAnalyzerMessageFormat { return ResourceManager.GetString("DoNotStoreStaticTestContextAnalyzerMessageFormat", resourceCulture); } } - + /// /// Looks up a localized string similar to Do not store TestContext in a static member. /// @@ -443,7 +443,7 @@ internal static string DoNotStoreStaticTestContextAnalyzerTitle { return ResourceManager.GetString("DoNotStoreStaticTestContextAnalyzerTitle", resourceCulture); } } - + /// /// Looks up a localized string similar to Shadowing test members could cause testing issues (such as NRE).. /// @@ -452,7 +452,7 @@ internal static string DoNotUseShadowingDescription { return ResourceManager.GetString("DoNotUseShadowingDescription", resourceCulture); } } - + /// /// Looks up a localized string similar to Member '{0}' already exists in the base class. /// @@ -461,7 +461,7 @@ internal static string DoNotUseShadowingMessageFormat { return ResourceManager.GetString("DoNotUseShadowingMessageFormat", resourceCulture); } } - + /// /// Looks up a localized string similar to Do not use shadowing. /// @@ -470,7 +470,7 @@ internal static string DoNotUseShadowingTitle { return ResourceManager.GetString("DoNotUseShadowingTitle", resourceCulture); } } - + /// /// Looks up a localized string similar to 'System.ComponentModel.DescriptionAttribute' has no effect in the context of tests and you likely wanted to use 'Microsoft.VisualStudio.TestTools.UnitTesting.DescriptionAttribute' instead.. /// @@ -479,7 +479,7 @@ internal static string DoNotUseSystemDescriptionAttributeDescription { return ResourceManager.GetString("DoNotUseSystemDescriptionAttributeDescription", resourceCulture); } } - + /// /// Looks up a localized string similar to Did you mean to be using 'Microsoft.VisualStudio.TestTools.UnitTesting.DescriptionAttribute'?. /// @@ -488,7 +488,7 @@ internal static string DoNotUseSystemDescriptionAttributeMessageFormat { return ResourceManager.GetString("DoNotUseSystemDescriptionAttributeMessageFormat", resourceCulture); } } - + /// /// Looks up a localized string similar to 'System.ComponentModel.DescriptionAttribute' has no effect on test methods. /// @@ -497,7 +497,7 @@ internal static string DoNotUseSystemDescriptionAttributeTitle { return ResourceManager.GetString("DoNotUseSystemDescriptionAttributeTitle", resourceCulture); } } - + /// /// Looks up a localized string similar to Do not duplicate 'DataRow' attributes. This is usually a copy/paste error. The attribute indices are '{0}' and '{1}'.. /// @@ -506,7 +506,7 @@ internal static string DuplicateDataRowMessageFormat { return ResourceManager.GetString("DuplicateDataRowMessageFormat", resourceCulture); } } - + /// /// Looks up a localized string similar to Avoid duplicated 'DataRow' entries. /// @@ -515,7 +515,7 @@ internal static string DuplicateDataRowTitle { return ResourceManager.GetString("DuplicateDataRowTitle", resourceCulture); } } - + /// /// Looks up a localized string similar to 'DynamicData' entry should have the following layout to be valid: ///- should only be set on a test method; @@ -527,7 +527,7 @@ internal static string DynamicDataShouldBeValidDescription { return ResourceManager.GetString("DynamicDataShouldBeValidDescription", resourceCulture); } } - + /// /// Looks up a localized string similar to '[DynamicData]' data member '{0}.{1}' signature is invalid. /// @@ -536,7 +536,7 @@ internal static string DynamicDataShouldBeValidMessageFormat_DataMemberSignature return ResourceManager.GetString("DynamicDataShouldBeValidMessageFormat_DataMemberSignature", resourceCulture); } } - + /// /// Looks up a localized string similar to '[DynamicData]' display name method '{0}.{1}' signature is invalid. /// @@ -545,7 +545,7 @@ internal static string DynamicDataShouldBeValidMessageFormat_DisplayMethodSignat return ResourceManager.GetString("DynamicDataShouldBeValidMessageFormat_DisplayMethodSignature", resourceCulture); } } - + /// /// Looks up a localized string similar to '[DynamicData]' member '{0}.{1}' should be a method. /// @@ -554,7 +554,7 @@ internal static string DynamicDataShouldBeValidMessageFormat_MemberMethod { return ResourceManager.GetString("DynamicDataShouldBeValidMessageFormat_MemberMethod", resourceCulture); } } - + /// /// Looks up a localized string similar to '[DynamicData]' member '{0}.{1}' cannot be found. /// @@ -563,7 +563,7 @@ internal static string DynamicDataShouldBeValidMessageFormat_MemberNotFound { return ResourceManager.GetString("DynamicDataShouldBeValidMessageFormat_MemberNotFound", resourceCulture); } } - + /// /// Looks up a localized string similar to '[DynamicData]' referenced member '{0}.{1}' should return 'IEnumerable<object[]>', 'IEnumerable<Tuple>` or 'IEnumerable<ValueTuple>'. /// @@ -572,7 +572,7 @@ internal static string DynamicDataShouldBeValidMessageFormat_MemberType { return ResourceManager.GetString("DynamicDataShouldBeValidMessageFormat_MemberType", resourceCulture); } } - + /// /// Looks up a localized string similar to '[DynamicData]' should only be set on a test method. /// @@ -581,7 +581,7 @@ internal static string DynamicDataShouldBeValidMessageFormat_OnTestMethod { return ResourceManager.GetString("DynamicDataShouldBeValidMessageFormat_OnTestMethod", resourceCulture); } } - + /// /// Looks up a localized string similar to '[DynamicData]' member '{0}.{1}' is a method so you should use 'DynamicDataSourceType.AutoDetect' or 'DynamicDataSourceType.Method' (auto detect is the default when not specified explicitly, and is recommended). /// @@ -590,7 +590,7 @@ internal static string DynamicDataShouldBeValidMessageFormat_SourceTypeMethod { return ResourceManager.GetString("DynamicDataShouldBeValidMessageFormat_SourceTypeMethod", resourceCulture); } } - + /// /// Looks up a localized string similar to '[DynamicData]' member '{0}.{1}' is not a property nor a method. Only properties and methods are supported.. /// @@ -599,7 +599,7 @@ internal static string DynamicDataShouldBeValidMessageFormat_SourceTypeNotProper return ResourceManager.GetString("DynamicDataShouldBeValidMessageFormat_SourceTypeNotPropertyOrMethod", resourceCulture); } } - + /// /// Looks up a localized string similar to '[DynamicData]' member '{0}.{1}' is a property so you should use 'DynamicDataSourceType.AutoDetect' or 'DynamicDataSourceType.Property' (auto detect is the default when not specified explicitly, and is recommended). /// @@ -608,7 +608,7 @@ internal static string DynamicDataShouldBeValidMessageFormat_SourceTypeProperty return ResourceManager.GetString("DynamicDataShouldBeValidMessageFormat_SourceTypeProperty", resourceCulture); } } - + /// /// Looks up a localized string similar to '[DynamicData]' member '{0}.{1}' is found more than once. /// @@ -617,7 +617,7 @@ internal static string DynamicDataShouldBeValidMessageFormat_TooManyMembers { return ResourceManager.GetString("DynamicDataShouldBeValidMessageFormat_TooManyMembers", resourceCulture); } } - + /// /// Looks up a localized string similar to DynamicData should be valid. /// @@ -626,7 +626,7 @@ internal static string DynamicDataShouldBeValidTitle { return ResourceManager.GetString("DynamicDataShouldBeValidTitle", resourceCulture); } } - + /// /// Looks up a localized string similar to When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationTokenSource.Token to enable cooperative cancellation and respect test timeouts.. /// @@ -635,7 +635,7 @@ internal static string FlowTestContextCancellationTokenDescription { return ResourceManager.GetString("FlowTestContextCancellationTokenDescription", resourceCulture); } } - + /// /// Looks up a localized string similar to Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationTokenSource.Token'. /// @@ -644,7 +644,7 @@ internal static string FlowTestContextCancellationTokenMessageFormat { return ResourceManager.GetString("FlowTestContextCancellationTokenMessageFormat", resourceCulture); } } - + /// /// Looks up a localized string similar to Flow TestContext.CancellationToken to async operations. /// @@ -653,7 +653,7 @@ internal static string FlowTestContextCancellationTokenTitle { return ResourceManager.GetString("FlowTestContextCancellationTokenTitle", resourceCulture); } } - + /// /// Looks up a localized string similar to Methods marked with '[GlobalTestInitialize]' or '[GlobalTestCleanup]' should follow the following layout to be valid: ///-it can't be declared on a generic class @@ -672,7 +672,7 @@ internal static string GlobalTestFixtureShouldBeValidDescription { return ResourceManager.GetString("GlobalTestFixtureShouldBeValidDescription", resourceCulture); } } - + /// /// Looks up a localized string similar to Global test fixture method '{0}' signature is invalid. /// @@ -681,7 +681,7 @@ internal static string GlobalTestFixtureShouldBeValidMessageFormat { return ResourceManager.GetString("GlobalTestFixtureShouldBeValidMessageFormat", resourceCulture); } } - + /// /// Looks up a localized string similar to GlobalTestInitialize and GlobalTestCleanup methods should have valid layout. /// @@ -690,7 +690,7 @@ internal static string GlobalTestFixtureShouldBeValidTitle { return ResourceManager.GetString("GlobalTestFixtureShouldBeValidTitle", resourceCulture); } } - + /// /// Looks up a localized string similar to Use 'Assert.Fail' instead of an always-failing 'Assert.{0}' assert. /// @@ -699,7 +699,7 @@ internal static string PreferAssertFailOverAlwaysFalseConditionsMessageFormat { return ResourceManager.GetString("PreferAssertFailOverAlwaysFalseConditionsMessageFormat", resourceCulture); } } - + /// /// Looks up a localized string similar to Use 'Assert.Fail' instead of an always-failing assert. /// @@ -708,7 +708,7 @@ internal static string PreferAssertFailOverAlwaysFalseConditionsTitle { return ResourceManager.GetString("PreferAssertFailOverAlwaysFalseConditionsTitle", resourceCulture); } } - + /// /// Looks up a localized string similar to Prefer constructors over TestInitialize methods. /// @@ -717,7 +717,7 @@ internal static string PreferConstructorOverTestInitializeMessageFormat { return ResourceManager.GetString("PreferConstructorOverTestInitializeMessageFormat", resourceCulture); } } - + /// /// Looks up a localized string similar to Prefer constructors over TestInitialize methods. /// @@ -726,7 +726,7 @@ internal static string PreferConstructorOverTestInitializeTitle { return ResourceManager.GetString("PreferConstructorOverTestInitializeTitle", resourceCulture); } } - + /// /// Looks up a localized string similar to Prefer 'Dispose' over TestCleanup methods. /// @@ -735,7 +735,7 @@ internal static string PreferDisposeOverTestCleanupMessageFormat { return ResourceManager.GetString("PreferDisposeOverTestCleanupMessageFormat", resourceCulture); } } - + /// /// Looks up a localized string similar to Prefer 'Dispose' over TestCleanup methods. /// @@ -744,7 +744,7 @@ internal static string PreferDisposeOverTestCleanupTitle { return ResourceManager.GetString("PreferDisposeOverTestCleanupTitle", resourceCulture); } } - + /// /// Looks up a localized string similar to Prefer TestCleanup over 'Dispose' methods. /// @@ -753,7 +753,7 @@ internal static string PreferTestCleanupOverDisposeMessageFormat { return ResourceManager.GetString("PreferTestCleanupOverDisposeMessageFormat", resourceCulture); } } - + /// /// Looks up a localized string similar to Prefer TestCleanup over 'Dispose' methods. /// @@ -762,7 +762,7 @@ internal static string PreferTestCleanupOverDisposeTitle { return ResourceManager.GetString("PreferTestCleanupOverDisposeTitle", resourceCulture); } } - + /// /// Looks up a localized string similar to Prefer TestInitialize methods over constructors. /// @@ -771,7 +771,7 @@ internal static string PreferTestInitializeOverConstructorMessageFormat { return ResourceManager.GetString("PreferTestInitializeOverConstructorMessageFormat", resourceCulture); } } - + /// /// Looks up a localized string similar to Prefer TestInitialize methods over constructors. /// @@ -780,7 +780,7 @@ internal static string PreferTestInitializeOverConstructorTitle { return ResourceManager.GetString("PreferTestInitializeOverConstructorTitle", resourceCulture); } } - + /// /// Looks up a localized string similar to 'DataTestMethodAttribute' is obsolete and provides no additional functionality over 'TestMethodAttribute'. Use 'TestMethodAttribute' for all test methods, including parameterized tests.. /// @@ -789,7 +789,7 @@ internal static string PreferTestMethodOverDataTestMethodAnalyzerDescription { return ResourceManager.GetString("PreferTestMethodOverDataTestMethodAnalyzerDescription", resourceCulture); } } - + /// /// Looks up a localized string similar to 'DataTestMethod' is obsolete. Use 'TestMethod' instead.. /// @@ -798,7 +798,7 @@ internal static string PreferTestMethodOverDataTestMethodAnalyzerMessageFormat { return ResourceManager.GetString("PreferTestMethodOverDataTestMethodAnalyzerMessageFormat", resourceCulture); } } - + /// /// Looks up a localized string similar to Prefer 'TestMethod' over 'DataTestMethod'. /// @@ -807,7 +807,7 @@ internal static string PreferTestMethodOverDataTestMethodAnalyzerTitle { return ResourceManager.GetString("PreferTestMethodOverDataTestMethodAnalyzerTitle", resourceCulture); } } - + /// /// Looks up a localized string similar to Public methods should be test methods (marked with `[TestMethod]`).. /// @@ -816,7 +816,7 @@ internal static string PublicMethodShouldBeTestMethodAnalyzerDescription { return ResourceManager.GetString("PublicMethodShouldBeTestMethodAnalyzerDescription", resourceCulture); } } - + /// /// Looks up a localized string similar to Public method '{0}' should be a test method. /// @@ -825,7 +825,7 @@ internal static string PublicMethodShouldBeTestMethodAnalyzerFormat { return ResourceManager.GetString("PublicMethodShouldBeTestMethodAnalyzerFormat", resourceCulture); } } - + /// /// Looks up a localized string similar to Public methods should be test methods. /// @@ -834,7 +834,7 @@ internal static string PublicMethodShouldBeTestMethodAnalyzerTitle { return ResourceManager.GetString("PublicMethodShouldBeTestMethodAnalyzerTitle", resourceCulture); } } - + /// /// Looks up a localized string similar to It's considered a good practice to have only test classes marked public in a test project.. /// @@ -843,7 +843,7 @@ internal static string PublicTypeShouldBeTestClassDescription { return ResourceManager.GetString("PublicTypeShouldBeTestClassDescription", resourceCulture); } } - + /// /// Looks up a localized string similar to Public type '{0}' should be marked with '[TestClass]' or changed to 'internal'. /// @@ -852,7 +852,7 @@ internal static string PublicTypeShouldBeTestClassMessageFormat { return ResourceManager.GetString("PublicTypeShouldBeTestClassMessageFormat", resourceCulture); } } - + /// /// Looks up a localized string similar to Public types should be test classes. /// @@ -861,7 +861,7 @@ internal static string PublicTypeShouldBeTestClassTitle { return ResourceManager.GetString("PublicTypeShouldBeTestClassTitle", resourceCulture); } } - + /// /// Looks up a localized string similar to Review or remove the assertion as its condition is known to be always true. /// @@ -870,7 +870,7 @@ internal static string ReviewAlwaysTrueAssertConditionAnalyzerMessageFormat { return ResourceManager.GetString("ReviewAlwaysTrueAssertConditionAnalyzerMessageFormat", resourceCulture); } } - + /// /// Looks up a localized string similar to Assertion condition is always true. /// @@ -879,7 +879,7 @@ internal static string ReviewAlwaysTrueAssertConditionAnalyzerTitle { return ResourceManager.GetString("ReviewAlwaysTrueAssertConditionAnalyzerTitle", resourceCulture); } } - + /// /// Looks up a localized string similar to Use 'Assert.{0}' instead of 'StringAssert.{1}'. /// @@ -888,7 +888,7 @@ internal static string StringAssertToAssertMessageFormat { return ResourceManager.GetString("StringAssertToAssertMessageFormat", resourceCulture); } } - + /// /// Looks up a localized string similar to Use 'Assert' instead of 'StringAssert'. /// @@ -897,7 +897,7 @@ internal static string StringAssertToAssertTitle { return ResourceManager.GetString("StringAssertToAssertTitle", resourceCulture); } } - + /// /// Looks up a localized string similar to Test classes, classes marked with the '[TestClass]' attribute, should respect the following layout to be considered valid by MSTest: ///- it should be 'public' (or 'internal' if '[assembly: DiscoverInternals]' attribute is set) @@ -909,7 +909,7 @@ internal static string TestClassShouldBeValidDescription { return ResourceManager.GetString("TestClassShouldBeValidDescription", resourceCulture); } } - + /// /// Looks up a localized string similar to Test class '{0}' should be valid. /// @@ -918,7 +918,7 @@ internal static string TestClassShouldBeValidMessageFormat { return ResourceManager.GetString("TestClassShouldBeValidMessageFormat", resourceCulture); } } - + /// /// Looks up a localized string similar to Test classes should have valid layout. /// @@ -927,7 +927,7 @@ internal static string TestClassShouldBeValidTitle { return ResourceManager.GetString("TestClassShouldBeValidTitle", resourceCulture); } } - + /// /// Looks up a localized string similar to Test class should have at least one test method or be 'static' with method(s) marked by '[AssemblyInitialize]' and/or '[AssemblyCleanup]'.. /// @@ -936,7 +936,7 @@ internal static string TestClassShouldHaveTestMethodDescription { return ResourceManager.GetString("TestClassShouldHaveTestMethodDescription", resourceCulture); } } - + /// /// Looks up a localized string similar to Test class '{0}' should have at least one test method or be 'static' with method(s) marked by '[AssemblyInitialize]' and/or '[AssemblyCleanup]'. /// @@ -945,7 +945,7 @@ internal static string TestClassShouldHaveTestMethodMessageFormat { return ResourceManager.GetString("TestClassShouldHaveTestMethodMessageFormat", resourceCulture); } } - + /// /// Looks up a localized string similar to Test class should have test method. /// @@ -954,7 +954,7 @@ internal static string TestClassShouldHaveTestMethodTitle { return ResourceManager.GetString("TestClassShouldHaveTestMethodTitle", resourceCulture); } } - + /// /// Looks up a localized string similar to Methods marked with '[TestCleanup]' should follow the following layout to be valid: ///-it should be 'public' @@ -975,7 +975,7 @@ internal static string TestCleanupShouldBeValidDescription { return ResourceManager.GetString("TestCleanupShouldBeValidDescription", resourceCulture); } } - + /// /// Looks up a localized string similar to TestCleanup method '{0}' signature is invalid. /// @@ -984,7 +984,7 @@ internal static string TestCleanupShouldBeValidMessageFormat { return ResourceManager.GetString("TestCleanupShouldBeValidMessageFormat", resourceCulture); } } - + /// /// Looks up a localized string similar to TestCleanup method should have valid layout. /// @@ -993,7 +993,7 @@ internal static string TestCleanupShouldBeValidTitle { return ResourceManager.GetString("TestCleanupShouldBeValidTitle", resourceCulture); } } - + /// /// Looks up a localized string similar to Some TestContext properties are only available during test execution and cannot be accessed in assembly initialize, class initialize, class cleanup, or assembly cleanup methods.. /// @@ -1002,7 +1002,7 @@ internal static string TestContextPropertyUsageDescription { return ResourceManager.GetString("TestContextPropertyUsageDescription", resourceCulture); } } - + /// /// Looks up a localized string similar to TestContext property '{0}' cannot be accessed in '{1}' method. /// @@ -1011,7 +1011,7 @@ internal static string TestContextPropertyUsageMessageFormat { return ResourceManager.GetString("TestContextPropertyUsageMessageFormat", resourceCulture); } } - + /// /// Looks up a localized string similar to TestContext property cannot be accessed in this context. /// @@ -1020,7 +1020,7 @@ internal static string TestContextPropertyUsageTitle { return ResourceManager.GetString("TestContextPropertyUsageTitle", resourceCulture); } } - + /// /// Looks up a localized string similar to 'TestContext' should be a non-static field or property assigned in constructor or for a property set by MSTest, it should follow the layout: ///- it should be 'public' regardless of whether '[assembly: DiscoverInternals]' attribute is set or not. @@ -1032,7 +1032,7 @@ internal static string TestContextShouldBeValidDescription { return ResourceManager.GetString("TestContextShouldBeValidDescription", resourceCulture); } } - + /// /// Looks up a localized string similar to Property 'TestContext' should be valid. /// @@ -1041,7 +1041,7 @@ internal static string TestContextShouldBeValidMessageFormat { return ResourceManager.GetString("TestContextShouldBeValidMessageFormat", resourceCulture); } } - + /// /// Looks up a localized string similar to Test context property should have valid layout. /// @@ -1050,7 +1050,7 @@ internal static string TestContextShouldBeValidTitle { return ResourceManager.GetString("TestContextShouldBeValidTitle", resourceCulture); } } - + /// /// Looks up a localized string similar to Methods marked with '[TestInitialize]' should follow the following layout to be valid: ///-it should be 'public' @@ -1071,7 +1071,7 @@ internal static string TestInitializeShouldBeValidDescription { return ResourceManager.GetString("TestInitializeShouldBeValidDescription", resourceCulture); } } - + /// /// Looks up a localized string similar to TestInitialize method '{0}' signature is invalid. /// @@ -1080,7 +1080,7 @@ internal static string TestInitializeShouldBeValidMessageFormat { return ResourceManager.GetString("TestInitializeShouldBeValidMessageFormat", resourceCulture); } } - + /// /// Looks up a localized string similar to TestInitialize method should have valid layout. /// @@ -1089,7 +1089,7 @@ internal static string TestInitializeShouldBeValidTitle { return ResourceManager.GetString("TestInitializeShouldBeValidTitle", resourceCulture); } } - + /// /// Looks up a localized string similar to Test methods, methods marked with the '[TestMethod]' attribute, should respect the following layout to be considered valid by MSTest: ///- it should be 'public' (or 'internal' if '[assembly: DiscoverInternals]' attribute is set) @@ -1105,7 +1105,7 @@ internal static string TestMethodShouldBeValidDescription { return ResourceManager.GetString("TestMethodShouldBeValidDescription", resourceCulture); } } - + /// /// Looks up a localized string similar to Test method '{0}' signature is invalid. /// @@ -1114,7 +1114,7 @@ internal static string TestMethodShouldBeValidMessageFormat { return ResourceManager.GetString("TestMethodShouldBeValidMessageFormat", resourceCulture); } } - + /// /// Looks up a localized string similar to Test methods should have valid layout. /// @@ -1123,7 +1123,7 @@ internal static string TestMethodShouldBeValidTitle { return ResourceManager.GetString("TestMethodShouldBeValidTitle", resourceCulture); } } - + /// /// Looks up a localized string similar to Test methods should not be ignored (marked with '[Ignore]').. /// @@ -1132,7 +1132,7 @@ internal static string TestMethodShouldNotBeIgnoredAnalyzerDescription { return ResourceManager.GetString("TestMethodShouldNotBeIgnoredAnalyzerDescription", resourceCulture); } } - + /// /// Looks up a localized string similar to Test method '{0}' should not be ignored. /// @@ -1141,7 +1141,7 @@ internal static string TestMethodShouldNotBeIgnoredAnalyzerFormat { return ResourceManager.GetString("TestMethodShouldNotBeIgnoredAnalyzerFormat", resourceCulture); } } - + /// /// Looks up a localized string similar to Test method should not be ignored. /// @@ -1150,7 +1150,7 @@ internal static string TestMethodShouldNotBeIgnoredAnalyzerTitle { return ResourceManager.GetString("TestMethodShouldNotBeIgnoredAnalyzerTitle", resourceCulture); } } - + /// /// Looks up a localized string similar to Type containing '[TestMethod]' should be marked with '[TestClass]', otherwise the test method will be silently ignored.. /// @@ -1159,7 +1159,7 @@ internal static string TypeContainingTestMethodShouldBeATestClassDescription { return ResourceManager.GetString("TypeContainingTestMethodShouldBeATestClassDescription", resourceCulture); } } - + /// /// Looks up a localized string similar to Type '{0}' contains test methods and should be marked with '[TestClass]'. /// @@ -1168,7 +1168,7 @@ internal static string TypeContainingTestMethodShouldBeATestClassMessageFormat { return ResourceManager.GetString("TypeContainingTestMethodShouldBeATestClassMessageFormat", resourceCulture); } } - + /// /// Looks up a localized string similar to Type containing '[TestMethod]' should be marked with '[TestClass]'. /// @@ -1177,7 +1177,7 @@ internal static string TypeContainingTestMethodShouldBeATestClassTitle { return ResourceManager.GetString("TypeContainingTestMethodShouldBeATestClassTitle", resourceCulture); } } - + /// /// Looks up a localized string similar to TestContext parameter is required by MSTest for AssemblyInitialize and ClassInitialize methods. /// @@ -1186,7 +1186,7 @@ internal static string UnusedParameterSuppressorJustification { return ResourceManager.GetString("UnusedParameterSuppressorJustification", resourceCulture); } } - + /// /// Looks up a localized string similar to Asynchronous test fixture methods do not require the 'Async' suffix. /// @@ -1195,7 +1195,7 @@ internal static string UseAsyncSuffixTestFixtureMethodSuppressorJustification { return ResourceManager.GetString("UseAsyncSuffixTestFixtureMethodSuppressorJustification", resourceCulture); } } - + /// /// Looks up a localized string similar to Asynchronous test methods do not require the 'Async' suffix. /// @@ -1204,7 +1204,7 @@ internal static string UseAsyncSuffixTestMethodSuppressorJustification { return ResourceManager.GetString("UseAsyncSuffixTestMethodSuppressorJustification", resourceCulture); } } - + /// /// Looks up a localized string similar to [{0}] can only be set on methods marked with [TestMethod]. /// @@ -1213,7 +1213,7 @@ internal static string UseAttributeOnTestMethodAnalyzerMessageFormat { return ResourceManager.GetString("UseAttributeOnTestMethodAnalyzerMessageFormat", resourceCulture); } } - + /// /// Looks up a localized string similar to [{0}] can only be set on methods marked with [TestMethod]. /// @@ -1222,7 +1222,7 @@ internal static string UseAttributeOnTestMethodAnalyzerTitle { return ResourceManager.GetString("UseAttributeOnTestMethodAnalyzerTitle", resourceCulture); } } - + /// /// Looks up a localized string similar to Without using 'ClassCleanupBehavior.EndOfClass', the '[ClassCleanup]' will by default be run at the end of the assembly and not at the end of the class.. /// @@ -1231,7 +1231,7 @@ internal static string UseClassCleanupBehaviorEndOfClassDescription { return ResourceManager.GetString("UseClassCleanupBehaviorEndOfClassDescription", resourceCulture); } } - + /// /// Looks up a localized string similar to Use 'ClassCleanupBehavior.EndOfClass' with the '[ClassCleanup]'. /// @@ -1240,7 +1240,7 @@ internal static string UseClassCleanupBehaviorEndOfClassMessageFormat { return ResourceManager.GetString("UseClassCleanupBehaviorEndOfClassMessageFormat", resourceCulture); } } - + /// /// Looks up a localized string similar to Use 'ClassCleanupBehavior.EndOfClass' with the '[ClassCleanup]'. /// @@ -1249,7 +1249,7 @@ internal static string UseClassCleanupBehaviorEndOfClassTitle { return ResourceManager.GetString("UseClassCleanupBehaviorEndOfClassTitle", resourceCulture); } } - + /// /// Looks up a localized string similar to The attribute '{0}' which derives from 'ConditionBaseAttribute' should be used only on classes marked with `TestClassAttribute`. /// @@ -1258,7 +1258,7 @@ internal static string UseConditionBaseWithTestClassMessageFormat { return ResourceManager.GetString("UseConditionBaseWithTestClassMessageFormat", resourceCulture); } } - + /// /// Looks up a localized string similar to Use 'ConditionBaseAttribute' on test classes. /// @@ -1267,7 +1267,7 @@ internal static string UseConditionBaseWithTestClassTitle { return ResourceManager.GetString("UseConditionBaseWithTestClassTitle", resourceCulture); } } - + /// /// Looks up a localized string similar to Using '[Timeout]' without explicitly setting 'CooperativeCancellation = true' is discouraged. In a future version, cooperative cancellation will become the default behavior. Set 'CooperativeCancellation = true' to opt into the recommended behavior and avoid breaking changes.. /// @@ -1276,7 +1276,7 @@ internal static string UseCooperativeCancellationForTimeoutDescription { return ResourceManager.GetString("UseCooperativeCancellationForTimeoutDescription", resourceCulture); } } - + /// /// Looks up a localized string similar to Use 'CooperativeCancellation = true' with '[Timeout]' to enable cooperative cancellation behavior. /// @@ -1285,7 +1285,7 @@ internal static string UseCooperativeCancellationForTimeoutMessageFormat { return ResourceManager.GetString("UseCooperativeCancellationForTimeoutMessageFormat", resourceCulture); } } - + /// /// Looks up a localized string similar to Use 'CooperativeCancellation = true' with '[Timeout]'. /// @@ -1294,7 +1294,7 @@ internal static string UseCooperativeCancellationForTimeoutTitle { return ResourceManager.GetString("UseCooperativeCancellationForTimeoutTitle", resourceCulture); } } - + /// /// Looks up a localized string similar to '[DeploymentItem]' can be specified only on test class or test method. /// @@ -1303,7 +1303,7 @@ internal static string UseDeploymentItemWithTestMethodOrTestClassMessageFormat { return ResourceManager.GetString("UseDeploymentItemWithTestMethodOrTestClassMessageFormat", resourceCulture); } } - + /// /// Looks up a localized string similar to '[DeploymentItem]' can be specified only on test class or test method. /// @@ -1312,7 +1312,7 @@ internal static string UseDeploymentItemWithTestMethodOrTestClassTitle { return ResourceManager.GetString("UseDeploymentItemWithTestMethodOrTestClassTitle", resourceCulture); } } - + /// /// Looks up a localized string similar to Use 'Assert.ThrowsExactly' instead of 'Assert.ThrowsException'. /// @@ -1321,7 +1321,7 @@ internal static string UseNewerAssertThrowsMessageFormat { return ResourceManager.GetString("UseNewerAssertThrowsMessageFormat", resourceCulture); } } - + /// /// Looks up a localized string similar to Use newer methods to assert exceptions. /// @@ -1330,7 +1330,7 @@ internal static string UseNewerAssertThrowsTitle { return ResourceManager.GetString("UseNewerAssertThrowsTitle", resourceCulture); } } - + /// /// Looks up a localized string similar to By default, MSTest runs tests within the same assembly sequentially, which can lead to severe performance limitations. It is recommended to enable assembly attribute '[Parallelize]' to run tests in parallel, or if the assembly is known to not be parallelizable, to use explicitly the assembly level attribute '[DoNotParallelize]'.. /// @@ -1339,7 +1339,7 @@ internal static string UseParallelizeAttributeAnalyzerDescription { return ResourceManager.GetString("UseParallelizeAttributeAnalyzerDescription", resourceCulture); } } - + /// /// Looks up a localized string similar to Explicitly enable or disable tests parallelization. /// @@ -1348,7 +1348,7 @@ internal static string UseParallelizeAttributeAnalyzerMessageFormat { return ResourceManager.GetString("UseParallelizeAttributeAnalyzerMessageFormat", resourceCulture); } } - + /// /// Looks up a localized string similar to Explicitly enable or disable tests parallelization. /// @@ -1357,7 +1357,7 @@ internal static string UseParallelizeAttributeAnalyzerTitle { return ResourceManager.GetString("UseParallelizeAttributeAnalyzerTitle", resourceCulture); } } - + /// /// Looks up a localized string similar to Use 'Assert.{0}' instead of 'Assert.{1}'. /// @@ -1366,7 +1366,7 @@ internal static string UseProperAssertMethodsMessageFormat { return ResourceManager.GetString("UseProperAssertMethodsMessageFormat", resourceCulture); } } - + /// /// Looks up a localized string similar to Use proper 'Assert' methods. /// @@ -1375,7 +1375,7 @@ internal static string UseProperAssertMethodsTitle { return ResourceManager.GetString("UseProperAssertMethodsTitle", resourceCulture); } } - + /// /// Looks up a localized string similar to An attribute that derives from 'RetryBaseAttribute' can be specified only on a test method. /// @@ -1384,7 +1384,7 @@ internal static string UseRetryWithTestMethodMessageFormat { return ResourceManager.GetString("UseRetryWithTestMethodMessageFormat", resourceCulture); } } - + /// /// Looks up a localized string similar to Use retry attribute on test method. /// @@ -1393,5 +1393,32 @@ internal static string UseRetryWithTestMethodTitle { return ResourceManager.GetString("UseRetryWithTestMethodTitle", resourceCulture); } } + + /// + /// Looks up a localized string similar to Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws. + /// + internal static string AssertThrowsShouldContainSingleStatementDescription { + get { + return ResourceManager.GetString("AssertThrowsShouldContainSingleStatementDescription", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Assert.Throws should contain only a single statement/expression. + /// + internal static string AssertThrowsShouldContainSingleStatementMessageFormat { + get { + return ResourceManager.GetString("AssertThrowsShouldContainSingleStatementMessageFormat", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Assert.Throws should contain only a single statement/expression. + /// + internal static string AssertThrowsShouldContainSingleStatementTitle { + get { + return ResourceManager.GetString("AssertThrowsShouldContainSingleStatementTitle", resourceCulture); + } + } } } diff --git a/src/Analyzers/MSTest.Analyzers/Resources.resx b/src/Analyzers/MSTest.Analyzers/Resources.resx index 45445b2d82..b909feb184 100644 --- a/src/Analyzers/MSTest.Analyzers/Resources.resx +++ b/src/Analyzers/MSTest.Analyzers/Resources.resx @@ -633,6 +633,15 @@ The type declaring these methods should also respect the following rules: When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationTokenSource.Token to enable cooperative cancellation and respect test timeouts. + + Assert.Throws should contain only a single statement/expression + + + Assert.Throws should contain only a single statement/expression + + + Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws. + GlobalTestInitialize and GlobalTestCleanup methods should have valid layout diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf index e80dfe879f..184dd976cb 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf @@ -944,6 +944,21 @@ Typ deklarující tyto metody by měl také respektovat následující pravidla: Některé vlastnosti TestContext jsou k dispozici pouze během provádění testu a nelze k nim přistupovat v metodách inicializace sestavení, inicializace třídy, vyčištění třídy nebo vyčištění sestavení. + + Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws. + Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws. + + + + Assert.Throws should contain only a single statement/expression + Assert.Throws should contain only a single statement/expression + + + + Assert.Throws should contain only a single statement/expression + Assert.Throws should contain only a single statement/expression + + \ No newline at end of file diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf index 5ca054556d..37c51282ed 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf @@ -945,6 +945,21 @@ Der Typ, der diese Methoden deklariert, sollte auch die folgenden Regeln beachte Einige TestContext-Eigenschaften sind nur während der Testausführung verfügbar und können nicht in Assemblyinitialisierungs-, Klasseninitialisierungs-, Klassenbereinigungs- oder Assemblybereinigungsmethoden aufgerufen werden. + + Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws. + Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws. + + + + Assert.Throws should contain only a single statement/expression + Assert.Throws should contain only a single statement/expression + + + + Assert.Throws should contain only a single statement/expression + Assert.Throws should contain only a single statement/expression + + \ No newline at end of file diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf index 7f56748641..f860c98191 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf @@ -944,6 +944,21 @@ El tipo que declara estos métodos también debe respetar las reglas siguientes: Algunas propiedades de TestContext solo están disponibles durante la ejecución de la prueba y no se puede acceder a ellas en los métodos assembly initialize, class initialize, class cleanup o assembly cleanup. + + Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws. + Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws. + + + + Assert.Throws should contain only a single statement/expression + Assert.Throws should contain only a single statement/expression + + + + Assert.Throws should contain only a single statement/expression + Assert.Throws should contain only a single statement/expression + + \ No newline at end of file diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf index d9296f52a6..77b5c88911 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf @@ -92,6 +92,21 @@ Le type doit être une classe La méthode AssemblyInitialize doit avoir une disposition valide + + Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws. + Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws. + + + + Assert.Throws should contain only a single statement/expression + Assert.Throws should contain only a single statement/expression + + + + Assert.Throws should contain only a single statement/expression + Assert.Throws should contain only a single statement/expression + + Prefer adding an additional assertion that checks for null Préférer l’ajout d’une assertion supplémentaire qui recherche la valeur null @@ -946,4 +961,4 @@ Le type doit être une classe - \ No newline at end of file + diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf index 9f587e84bb..4cfc1be033 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf @@ -92,6 +92,21 @@ Anche il tipo che dichiara questi metodi deve rispettare le regole seguenti: Il metodo AssemblyInitialize deve avere un layout valido + + Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws. + Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws. + + + + Assert.Throws should contain only a single statement/expression + Assert.Throws should contain only a single statement/expression + + + + Assert.Throws should contain only a single statement/expression + Assert.Throws should contain only a single statement/expression + + Prefer adding an additional assertion that checks for null Preferire l'aggiunta di un'ulteriore asserzione che controlli la presenza di valori null @@ -946,4 +961,4 @@ Anche il tipo che dichiara questi metodi deve rispettare le regole seguenti: - \ No newline at end of file + diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf index f3572dc873..699df11940 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf @@ -64,7 +64,7 @@ The type declaring these methods should also respect the following rules: -The class shouldn't be 'static' -The class should be marked with '[TestClass]' (or a derived attribute) -the class should not be generic. - '[AssemblyInitialize]' でマークされたメソッドを有効にするには、次のレイアウトに従う必要があります: + '[AssemblyInitialize]' でマークされたメソッドを有効にするには、次のレイアウトに従う必要があります: - ジェネリック クラスで宣言することはできません - 'public' である必要があります - 'static' である必要があります @@ -92,6 +92,21 @@ The type declaring these methods should also respect the following rules: AssemblyInitialize メソッドには有効なレイアウトが必要です + + Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws. + Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws. + + + + Assert.Throws should contain only a single statement/expression + Assert.Throws should contain only a single statement/expression + + + + Assert.Throws should contain only a single statement/expression + Assert.Throws should contain only a single statement/expression + + Prefer adding an additional assertion that checks for null 追加のアサーションによる null チェックを推奨する @@ -684,7 +699,7 @@ The type declaring these methods should also respect the following rules: -The class should be 'public' or 'internal' (if the test project is using the '[DiscoverInternals]' attribute) -The class shouldn't be 'static' -If the class is 'sealed', it should be marked with '[TestClass]' (or a derived attribute). - '[TestCleanup]' でマークされたメソッドを有効にするには、次のレイアウトに従う必要があります: + '[TestCleanup]' でマークされたメソッドを有効にするには、次のレイアウトに従う必要があります: - 'public' である必要があります - 'abstract' にすることはできません - 'async void' にすることはできません @@ -743,7 +758,7 @@ The type declaring these methods should also respect the following rules: -The class should be 'public' or 'internal' (if the test project is using the '[DiscoverInternals]' attribute) -The class shouldn't be 'static' -If the class is 'sealed', it should be marked with '[TestClass]' (or a derived attribute). - '[TestInitialize]' でマークされたメソッドを有効にするには、次のレイアウトに従う必要があります: + '[TestInitialize]' でマークされたメソッドを有効にするには、次のレイアウトに従う必要があります: - 'public' である必要があります - 'abstract' にすることはできません - 'async void' にすることはできません @@ -946,4 +961,4 @@ The type declaring these methods should also respect the following rules: - \ No newline at end of file + diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf index e088c8f658..ff7ca2c36d 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf @@ -21,7 +21,7 @@ The type declaring these methods should also respect the following rules: -the class should not be generic. '[AssemblyCleanup]'으로 표시된 메서드가 유효하려면 다음 레이아웃을 따라야 합니다. - 제네릭 클래스에서 선언할 수 없습니다. -- 'public'이어야 합니다. +- 'public'이어야 합니다. - 'static'이어야 합니다. - 'async void'가 아니어야 합니다. - 특수 메서드(종료자, 연산자...)가 아니어야 합니다. @@ -66,7 +66,7 @@ The type declaring these methods should also respect the following rules: -the class should not be generic. '[AssemblyInitialize]'로 표시된 메서드가 유효하려면 다음 레이아웃을 따라야 합니다. -제네릭 클래스에서 선언할 수 없습니다. -- 'public'이어야 합니다. +- 'public'이어야 합니다. - 'static'이어야 합니다. - 'async void'가 아니어야 합니다. - 특수 메서드(종료자, 연산자...)가 아니어야 합니다. @@ -92,6 +92,21 @@ The type declaring these methods should also respect the following rules: AssemblyInitialize 메서드에는 유효한 레이아웃이 있어야 합니다. + + Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws. + Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws. + + + + Assert.Throws should contain only a single statement/expression + Assert.Throws should contain only a single statement/expression + + + + Assert.Throws should contain only a single statement/expression + Assert.Throws should contain only a single statement/expression + + Prefer adding an additional assertion that checks for null null을 확인하는 추가 어설션을 추가하는 것이 좋습니다. @@ -183,7 +198,7 @@ The type declaring these methods should also respect the following rules: -the class should not be generic. '[ClassCleanup]'으로 표시된 메서드가 유효하려면 다음 레이아웃을 따라야 합니다. - 'InheritanceBehavior' 모드가 설정되지 않은 제네릭 클래스에서 선언할 수 없습니다. -- 'public'이어야 합니다. +- 'public'이어야 합니다. - 'static'이어야 합니다. - 'async void'가 아니어야 합니다. - 특수 메서드(종료자, 연산자...)가 아니어야 합니다. @@ -232,7 +247,7 @@ The type declaring these methods should also respect the following rules: -the class should not be generic. '[ClassInitialize]'로 표시된 메서드가 유효하려면 다음 레이아웃을 따라야 합니다. -'InheritanceBehavior' 모드가 설정되지 않은 제네릭 클래스에서 선언할 수 없습니다. -- 'public'이어야 합니다. +- 'public'이어야 합니다. - 'static'이어야 합니다. - 'async void'가 아니어야 합니다. - 특수 메서드(종료자, 연산자...)가 아니어야 합니다. @@ -685,7 +700,7 @@ The type declaring these methods should also respect the following rules: -The class shouldn't be 'static' -If the class is 'sealed', it should be marked with '[TestClass]' (or a derived attribute). '[TestCleanup]'으로 표시된 메서드가 유효하려면 다음 레이아웃을 따라야 합니다. -- 'public'이어야 합니다. +- 'public'이어야 합니다. - 'abstract'가 아니어야 합니다. - 'async void'가 아니어야 합니다. - 'static'이 아니어야 합니다. @@ -744,7 +759,7 @@ The type declaring these methods should also respect the following rules: -The class shouldn't be 'static' -If the class is 'sealed', it should be marked with '[TestClass]' (or a derived attribute). '[TestInitialize]'로 표시된 메서드가 유효하려면 다음 레이아웃을 따라야 합니다. -- 'public'이어야 합니다. +- 'public'이어야 합니다. - 'abstract'가 아니어야 합니다. - 'async void'가 아니어야 합니다. - 'static'이 아니어야 합니다. @@ -946,4 +961,4 @@ The type declaring these methods should also respect the following rules: - \ No newline at end of file + diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf index de09b7c71d..4d51a484ab 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf @@ -92,6 +92,21 @@ Typ deklarujący te metody powinien również przestrzegać następujących regu Metody AssemblyInitialize powinny mieć prawidłowy układ + + Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws. + Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws. + + + + Assert.Throws should contain only a single statement/expression + Assert.Throws should contain only a single statement/expression + + + + Assert.Throws should contain only a single statement/expression + Assert.Throws should contain only a single statement/expression + + Prefer adding an additional assertion that checks for null Preferuj dodawanie dodatkowej asercji, która sprawdza pod kątem wartości null @@ -946,4 +961,4 @@ Typ deklarujący te metody powinien również przestrzegać następujących regu - \ No newline at end of file + diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf index eea0cceb35..a56d8f07ae 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf @@ -92,6 +92,21 @@ O tipo que declara esses métodos também deve respeitar as seguintes regras: Os métodos AssemblyInitialize devem ter um layout válido + + Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws. + Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws. + + + + Assert.Throws should contain only a single statement/expression + Assert.Throws should contain only a single statement/expression + + + + Assert.Throws should contain only a single statement/expression + Assert.Throws should contain only a single statement/expression + + Prefer adding an additional assertion that checks for null Preferir adicionar uma declaração adicional que verifica se existe um nulo @@ -946,4 +961,4 @@ O tipo que declara esses métodos também deve respeitar as seguintes regras: - \ No newline at end of file + diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf index ef026326fb..0cb531a102 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf @@ -95,6 +95,21 @@ The type declaring these methods should also respect the following rules: Методы AssemblyInitialize должны использовать допустимый макет + + Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws. + Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws. + + + + Assert.Throws should contain only a single statement/expression + Assert.Throws should contain only a single statement/expression + + + + Assert.Throws should contain only a single statement/expression + Assert.Throws should contain only a single statement/expression + + Prefer adding an additional assertion that checks for null Предпочитайте добавление дополнительного утверждения, проверяющего наличие значения NULL @@ -958,4 +973,4 @@ The type declaring these methods should also respect the following rules: - \ No newline at end of file + diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf index 4f8789a5ae..6861b7064b 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf @@ -92,6 +92,21 @@ Bu yöntemleri bildiren tipin ayrıca aşağıdaki kurallara uyması gerekir: AssemblyInitialize yöntemleri geçerli bir düzene sahip olmalıdır + + Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws. + Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws. + + + + Assert.Throws should contain only a single statement/expression + Assert.Throws should contain only a single statement/expression + + + + Assert.Throws should contain only a single statement/expression + Assert.Throws should contain only a single statement/expression + + Prefer adding an additional assertion that checks for null Null değerini denetlerken ek bir onaylama eklemeyi tercih et @@ -948,4 +963,4 @@ Bu yöntemleri bildiren tipin ayrıca aşağıdaki kurallara uyması gerekir: - \ No newline at end of file + diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf index fce3905e91..944fc36c56 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf @@ -92,6 +92,21 @@ The type declaring these methods should also respect the following rules: AssemblyInitialize 方法应具有有效的布局 + + Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws. + Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws. + + + + Assert.Throws should contain only a single statement/expression + Assert.Throws should contain only a single statement/expression + + + + Assert.Throws should contain only a single statement/expression + Assert.Throws should contain only a single statement/expression + + Prefer adding an additional assertion that checks for null 首选添加检查 null 的其他断言 @@ -946,4 +961,4 @@ The type declaring these methods should also respect the following rules: - \ No newline at end of file + diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf index 992bf1f44a..5778ecc55c 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf @@ -92,6 +92,21 @@ The type declaring these methods should also respect the following rules: AssemblyInitialize 方法應該具有有效的配置 + + Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws. + Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws. + + + + Assert.Throws should contain only a single statement/expression + Assert.Throws should contain only a single statement/expression + + + + Assert.Throws should contain only a single statement/expression + Assert.Throws should contain only a single statement/expression + + Prefer adding an additional assertion that checks for null 偏好新增檢查 Null 的其他判斷提示 @@ -946,4 +961,4 @@ The type declaring these methods should also respect the following rules: - \ No newline at end of file + diff --git a/test/UnitTests/MSTest.Analyzers.UnitTests/AssertThrowsShouldContainSingleStatementAnalyzerTests.cs b/test/UnitTests/MSTest.Analyzers.UnitTests/AssertThrowsShouldContainSingleStatementAnalyzerTests.cs new file mode 100644 index 0000000000..26c4c0754b --- /dev/null +++ b/test/UnitTests/MSTest.Analyzers.UnitTests/AssertThrowsShouldContainSingleStatementAnalyzerTests.cs @@ -0,0 +1,605 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using VerifyCS = MSTest.Analyzers.Test.CSharpCodeFixVerifier< + MSTest.Analyzers.AssertThrowsShouldContainSingleStatementAnalyzer, + Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>; + +using VerifyVB = MSTest.Analyzers.Test.VisualBasicCodeFixVerifier< + MSTest.Analyzers.AssertThrowsShouldContainSingleStatementAnalyzer, + Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>; + +namespace MSTest.Analyzers.Test; + +[TestClass] +public sealed class AssertThrowsShouldContainSingleStatementAnalyzerTests +{ + [TestMethod] + public async Task WhenAssertThrowsContainsMultipleStatements_CSharp_Diagnostic() + { + string code = """ + using System; + using System.Threading.Tasks; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + // Multiple statements in Assert.Throws - should be flagged + [|Assert.Throws(() => + { + Console.WriteLine("First"); + Console.WriteLine("Second"); + })|]; + + // Multiple statements in Assert.Throws, wrapped in extra block syntax - should be flagged + [|Assert.Throws(() => + { + { + { + Console.WriteLine("First"); + } + { + Console.WriteLine("Second"); + } + } + })|]; + + // Multiple statements in Assert.ThrowsExactly - should be flagged + [|Assert.ThrowsExactly(() => + { + Console.WriteLine("First"); + Console.WriteLine("Second"); + })|]; + } + + [TestMethod] + public async Task MyAsyncTestMethod() + { + // Multiple statements in Assert.ThrowsAsync - should be flagged + [|Assert.ThrowsAsync(() => + { + Console.WriteLine("First"); + return Task.CompletedTask; + })|]; + + // Multiple statements in Assert.ThrowsExactlyAsync - should be flagged + [|Assert.ThrowsExactlyAsync(() => + { + Console.WriteLine("First"); + return Task.CompletedTask; + })|]; + } + } + """; + + await VerifyCS.VerifyAnalyzerAsync(code); + } + + [TestMethod] + public async Task WhenAssertThrowsContainsMultipleStatements_VB_Diagnostic() + { + string code = """ + Imports System + Imports System.Threading.Tasks + Imports Microsoft.VisualStudio.TestTools.UnitTesting + + + Public Class MyTestClass + + Public Sub MyTestMethod() + ' Multiple statements in Assert.Throws - should be flagged + [|Assert.Throws(Of Exception)(Sub() + Console.WriteLine("First") + Console.WriteLine("Second") + End Sub)|] + + ' Multiple statements in Assert.ThrowsExactly - should be flagged + [|Assert.ThrowsExactly(Of Exception)(Sub() + Console.WriteLine("First") + Console.WriteLine("Second") + End Sub)|] + End Sub + + + Public Async Function MyAsyncTestMethod() As Task + ' Multiple statements in Assert.ThrowsAsync - should be flagged + [|Assert.ThrowsAsync(Of Exception)(Function() + Console.WriteLine("First") + Return Task.CompletedTask + End Function)|] + + ' Multiple statements in Assert.ThrowsExactlyAsync - should be flagged + [|Assert.ThrowsExactlyAsync(Of Exception)(Function() + Console.WriteLine("First") + Return Task.CompletedTask + End Function)|] + End Function + End Class + """; + + await VerifyVB.VerifyAnalyzerAsync(code); + } + + [TestMethod] + public async Task WhenAssertThrowsContainsMultipleStatementsWithVariableDeclarations_CSharp_Diagnostic() + { + string code = """ + using System; + using System.Threading.Tasks; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + // Multiple statements including variable declarations - should be flagged + [|Assert.Throws(() => + { + var value = 42; + Console.WriteLine(value); + DoSomething(); + })|]; + + // Multiple statements with ThrowsExactly - should be flagged + [|Assert.ThrowsExactly(() => + { + var value = 42; + Console.WriteLine(value); + DoSomething(); + })|]; + } + + [TestMethod] + public async Task MyAsyncTestMethod() + { + // Multiple statements with ThrowsAsync - should be flagged + [|Assert.ThrowsAsync(() => + { + var value = 42; + Console.WriteLine(value); + return Task.CompletedTask; + })|]; + + // Multiple statements with ThrowsExactlyAsync - should be flagged + [|Assert.ThrowsExactlyAsync(() => + { + var value = 42; + Console.WriteLine(value); + return Task.CompletedTask; + })|]; + } + + private static void DoSomething() => throw new Exception(); + } + """; + + await VerifyCS.VerifyAnalyzerAsync(code); + } + + [TestMethod] + public async Task WhenAssertThrowsContainsMultipleStatementsWithVariableDeclarations_VB_Diagnostic() + { + string code = """ + Imports System + Imports System.Threading.Tasks + Imports Microsoft.VisualStudio.TestTools.UnitTesting + + + Public Class MyTestClass + + Public Sub MyTestMethod() + ' Multiple statements including variable declarations - should be flagged + [|Assert.Throws(Of Exception)(Sub() + Dim value As Integer = 42 + Console.WriteLine(value) + DoSomething() + End Sub)|] + + ' Multiple statements with ThrowsExactly - should be flagged + [|Assert.ThrowsExactly(Of Exception)(Sub() + Dim value As Integer = 42 + Console.WriteLine(value) + DoSomething() + End Sub)|] + End Sub + + + Public Async Function MyAsyncTestMethod() As Task + ' Multiple statements with ThrowsAsync - should be flagged + [|Assert.ThrowsAsync(Of Exception)(Function() + Dim value As Integer = 42 + Console.WriteLine(value) + Return Task.CompletedTask + End Function)|] + + ' Multiple statements with ThrowsExactlyAsync - should be flagged + [|Assert.ThrowsExactlyAsync(Of Exception)(Function() + Dim value As Integer = 42 + Console.WriteLine(value) + Return Task.CompletedTask + End Function)|] + End Function + + Private Shared Sub DoSomething() + Throw New Exception() + End Sub + End Class + """; + + await VerifyVB.VerifyAnalyzerAsync(code); + } + + [TestMethod] + public async Task WhenAssertThrowsContainsSingleStatement_CSharp_NoDiagnostic() + { + string code = """ + using System; + using System.Threading.Tasks; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + // Single statement - should NOT be flagged + Assert.Throws(() => Console.WriteLine("Only one")); + + // Single expression - should NOT be flagged + Assert.Throws(() => DoSomething()); + + // Single statement in block - should NOT be flagged + Assert.Throws(() => + { + DoSomething(); + }); + + // Single statement with ThrowsExactly - should NOT be flagged + Assert.ThrowsExactly(() => DoSomething()); + } + + [TestMethod] + public async Task MyAsyncTestMethod() + { + // Single async statement - should NOT be flagged + await Assert.ThrowsAsync(() => Task.CompletedTask); + + // Single async statement in block - should NOT be flagged + await Assert.ThrowsAsync(() => + { + return Task.CompletedTask; + }); + + // Single async statement with ThrowsExactlyAsync - should NOT be flagged + await Assert.ThrowsExactlyAsync(() => Task.CompletedTask); + } + + private static void DoSomething() => throw new Exception(); + } + """; + + await VerifyCS.VerifyAnalyzerAsync(code); + } + + [TestMethod] + public async Task WhenAssertThrowsContainsSingleStatement_VB_NoDiagnostic() + { + string code = """ + Imports System + Imports System.Threading.Tasks + Imports Microsoft.VisualStudio.TestTools.UnitTesting + + + Public Class MyTestClass + + Public Sub MyTestMethod() + ' Single statement - should NOT be flagged + Assert.Throws(Of Exception)(Sub() Console.WriteLine("Only one")) + + ' Single expression - should NOT be flagged + Assert.Throws(Of Exception)(Sub() DoSomething()) + + ' Single statement in block - should NOT be flagged + Assert.Throws(Of Exception)(Sub() + DoSomething() + End Sub) + + ' Single statement with ThrowsExactly - should NOT be flagged + Assert.ThrowsExactly(Of Exception)(Sub() DoSomething()) + End Sub + + + Public Async Function MyAsyncTestMethod() As Task + ' Single async statement - should NOT be flagged + Await Assert.ThrowsAsync(Of Exception)(Function() Task.CompletedTask) + + ' Single async statement in block - should NOT be flagged + Await Assert.ThrowsAsync(Of Exception)(Function() + Return Task.CompletedTask + End Function) + + ' Single async statement with ThrowsExactlyAsync - should NOT be flagged + Await Assert.ThrowsExactlyAsync(Of Exception)(Function() Task.CompletedTask) + End Function + + Private Shared Sub DoSomething() + Throw New Exception() + End Sub + End Class + """; + + await VerifyVB.VerifyAnalyzerAsync(code); + } + + [TestMethod] + public async Task WhenUsingOtherAssertMethods_CSharp_NoDiagnostic() + { + string code = """ + using System; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + // Other Assert methods should not be flagged even with multiple statements + Assert.IsTrue(true); + Assert.AreEqual(1, 1); + Assert.IsNotNull("test"); + + // Non-Assert.Throws methods should not be analyzed + var action = new Action(() => + { + Console.WriteLine("First"); + Console.WriteLine("Second"); + }); + action(); + } + } + """; + + await VerifyCS.VerifyAnalyzerAsync(code); + } + + [TestMethod] + public async Task WhenUsingOtherAssertMethods_VB_NoDiagnostic() + { + string code = """ + Imports System + Imports Microsoft.VisualStudio.TestTools.UnitTesting + + + Public Class MyTestClass + + Public Sub MyTestMethod() + ' Other Assert methods should not be flagged even with multiple statements + Assert.IsTrue(true) + Assert.AreEqual(1, 1) + Assert.IsNotNull("test") + + ' Non-Assert.Throws methods should not be analyzed + Dim action As new Action(Sub() + Console.WriteLine("First") + Console.WriteLine("Second") + End Sub) + action() + End Sub + End Class + """; + + await VerifyVB.VerifyAnalyzerAsync(code); + } + + [TestMethod] + public async Task WhenAssertThrowsHasMessageParameter_CSharp_StillAnalyzes() + { + string code = """ + using System; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + // Multiple statements with message parameter - should be flagged + [|Assert.Throws(() => + { + Console.WriteLine("First"); + Console.WriteLine("Second"); + }, "Custom message")|]; + + // Single statement with message parameter - should NOT be flagged + Assert.Throws(() => DoSomething(), "Custom message"); + } + + private static void DoSomething() => throw new Exception(); + } + """; + + await VerifyCS.VerifyAnalyzerAsync(code); + } + + [TestMethod] + public async Task WhenAssertThrowsHasMessageParameter_VB_StillAnalyzes() + { + string code = """ + Imports System + Imports Microsoft.VisualStudio.TestTools.UnitTesting + + + Public Class MyTestClass + + Public Sub MyTestMethod() + ' Multiple statements with message parameter - should be flagged + [|Assert.Throws(Of Exception)(Sub() + Console.WriteLine("First") + Console.WriteLine("Second") + End Sub, "Custom message")|] + + ' Single statement with message parameter - should NOT be flagged + Assert.Throws(Of Exception)(Sub() DoSomething(), "Custom message") + End Sub + + Private Shared Sub DoSomething() + Throw New Exception() + End Sub + End Class + """; + + await VerifyVB.VerifyAnalyzerAsync(code); + } + + [TestMethod] + public async Task WhenAssertThrowsWithExpressionBody_CSharp_NoDiagnostic() + { + string code = """ + using System; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + // Expression-bodied lambda - should NOT be flagged + Assert.Throws(() => DoSomething()); + Assert.ThrowsExactly(() => DoSomething()); + + // Expression-bodied with method chain - should NOT be flagged + Assert.Throws(() => "test".ToUpper().ToLower()); + } + + private static void DoSomething() => throw new Exception(); + } + """; + + await VerifyCS.VerifyAnalyzerAsync(code); + } + + [TestMethod] + public async Task WhenAssertThrowsWithExpressionBody_VB_NoDiagnostic() + { + string code = """ + Imports System + Imports Microsoft.VisualStudio.TestTools.UnitTesting + + + Public Class MyTestClass + + Public Sub MyTestMethod() + ' Expression-bodied lambda - should NOT be flagged + Assert.Throws(Of Exception)(Sub() DoSomething()) + Assert.ThrowsExactly(Of Exception)(Sub() DoSomething()) + + ' Expression-bodied with method chain - should NOT be flagged + Assert.Throws(Of Exception)(Function() "test".ToUpper().ToLower()) + End Sub + + Private Shared Sub DoSomething() + Throw New Exception() + End Sub + End Class + """; + + await VerifyVB.VerifyAnalyzerAsync(code); + } + + [TestMethod] + public async Task WhenAssertThrowsWithEmptyStatements_CSharp_NoDiagnostic() + { + string code = """ + using System; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + // Single statement with empty statements - should NOT be flagged + Assert.Throws(() => + { + DoSomething(); + ; // empty statement + }); + } + + private static void DoSomething() => throw new Exception(); + } + """; + + await VerifyCS.VerifyAnalyzerAsync(code); + } + + [TestMethod] + public async Task WhenAssertThrowsWithMultipleNonEmptyStatements_CSharp_Diagnostic() + { + string code = """ + using System; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + // Multiple non-empty statements - should be flagged + [|Assert.Throws(() => + { + DoSomething(); + DoSomething(); + ; // empty statement + })|]; + } + + private static void DoSomething() => throw new Exception(); + } + """; + + await VerifyCS.VerifyAnalyzerAsync(code); + } + + [TestMethod] + public async Task WhenAssertThrowsContainsMultipleStatementsOnSameLine_CSharp_Diagnostic() + { + string code = """ + using System; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + // Multiple statements on same line - should be flagged (shows we count statements, not lines) + [|Assert.Throws(() => { DoSomething(); DoSomething(); })|]; + + // Multiple statements on same line in block - should be flagged + [|Assert.Throws(() => + { + DoSomething(); DoSomething(); + })|]; + } + + private static void DoSomething() => throw new Exception(); + } + """; + + await VerifyCS.VerifyAnalyzerAsync(code); + } +} diff --git a/test/UnitTests/MSTest.Analyzers.UnitTests/MSTest.Analyzers.UnitTests.csproj b/test/UnitTests/MSTest.Analyzers.UnitTests/MSTest.Analyzers.UnitTests.csproj index 1bf57106ad..0f5fe782b9 100644 --- a/test/UnitTests/MSTest.Analyzers.UnitTests/MSTest.Analyzers.UnitTests.csproj +++ b/test/UnitTests/MSTest.Analyzers.UnitTests/MSTest.Analyzers.UnitTests.csproj @@ -24,7 +24,9 @@ - + + + diff --git a/test/UnitTests/MSTest.Analyzers.UnitTests/Verifiers/VisualBasicCodeFixVerifier`2+Test.cs b/test/UnitTests/MSTest.Analyzers.UnitTests/Verifiers/VisualBasicCodeFixVerifier`2+Test.cs new file mode 100644 index 0000000000..28715f1f30 --- /dev/null +++ b/test/UnitTests/MSTest.Analyzers.UnitTests/Verifiers/VisualBasicCodeFixVerifier`2+Test.cs @@ -0,0 +1,33 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CodeFixes; +using Microsoft.CodeAnalysis.Diagnostics; +using Microsoft.CodeAnalysis.Testing; +using Microsoft.CodeAnalysis.VisualBasic.Testing; + +using TestContext = Microsoft.VisualStudio.TestTools.UnitTesting.TestContext; + +namespace MSTest.Analyzers.Test; + +public static partial class VisualBasicCodeFixVerifier + where TAnalyzer : DiagnosticAnalyzer, new() + where TCodeFix : CodeFixProvider, new() +{ + public class Test : VisualBasicCodeFixTest + { + public Test() + { +#if NET462 + ReferenceAssemblies = ReferenceAssemblies.NetFramework.Net462.Default; + TestState.AdditionalReferences.Add(MetadataReference.CreateFromFile(typeof(ValueTask<>).Assembly.Location)); + TestState.AdditionalReferences.Add(MetadataReference.CreateFromFile(typeof(IAsyncDisposable).Assembly.Location)); +#else + ReferenceAssemblies = ReferenceAssemblies.Net.Net60; +#endif + TestState.AdditionalReferences.Add(MetadataReference.CreateFromFile(typeof(ParallelizeAttribute).Assembly.Location)); + TestState.AdditionalReferences.Add(MetadataReference.CreateFromFile(typeof(TestContext).Assembly.Location)); + } + } +} diff --git a/test/UnitTests/MSTest.Analyzers.UnitTests/Verifiers/VisualBasicCodeFixVerifier`2.cs b/test/UnitTests/MSTest.Analyzers.UnitTests/Verifiers/VisualBasicCodeFixVerifier`2.cs new file mode 100644 index 0000000000..430eada725 --- /dev/null +++ b/test/UnitTests/MSTest.Analyzers.UnitTests/Verifiers/VisualBasicCodeFixVerifier`2.cs @@ -0,0 +1,64 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CodeFixes; +using Microsoft.CodeAnalysis.Diagnostics; +using Microsoft.CodeAnalysis.Testing; +using Microsoft.CodeAnalysis.VisualBasic.Testing; + +namespace MSTest.Analyzers.Test; + +public static partial class VisualBasicCodeFixVerifier + where TAnalyzer : DiagnosticAnalyzer, new() + where TCodeFix : CodeFixProvider, new() +{ + /// + public static DiagnosticResult Diagnostic() + => VisualBasicCodeFixVerifier.Diagnostic(); + + /// + public static DiagnosticResult DiagnosticIgnoringAdditionalLocations() + => VisualBasicCodeFixVerifier.Diagnostic().WithOptions(DiagnosticOptions.IgnoreAdditionalLocations); + + /// + public static DiagnosticResult Diagnostic(string diagnosticId) + => VisualBasicCodeFixVerifier.Diagnostic(diagnosticId); + + /// + public static DiagnosticResult Diagnostic(DiagnosticDescriptor descriptor) + => VisualBasicCodeFixVerifier.Diagnostic(descriptor); + + /// + public static async Task VerifyAnalyzerAsync([StringSyntax("VB-test")] string source, params DiagnosticResult[] expected) + { + var test = new Test + { + TestCode = source, + }; + + test.ExpectedDiagnostics.AddRange(expected); + await test.RunAsync(CancellationToken.None); + } + + /// + public static async Task VerifyCodeFixAsync([StringSyntax("VB-test")] string source, [StringSyntax("VB-test")] string fixedSource) + => await VerifyCodeFixAsync(source, DiagnosticResult.EmptyDiagnosticResults, fixedSource); + + /// + public static async Task VerifyCodeFixAsync([StringSyntax("VB-test")] string source, DiagnosticResult expected, [StringSyntax("VB-test")] string fixedSource) + => await VerifyCodeFixAsync(source, [expected], fixedSource); + + /// + public static async Task VerifyCodeFixAsync([StringSyntax("VB-test")] string source, DiagnosticResult[] expected, [StringSyntax("VB-test")] string fixedSource) + { + var test = new Test + { + TestCode = source, + FixedCode = fixedSource, + }; + + test.ExpectedDiagnostics.AddRange(expected); + await test.RunAsync(CancellationToken.None); + } +} From 050f3f80d9192ac0930919af53c8c501180c3262 Mon Sep 17 00:00:00 2001 From: dotnet bot Date: Wed, 30 Jul 2025 04:08:09 -0700 Subject: [PATCH 332/541] Localized file check-in by OneLocBuild Task: Build definition ID 1218: Build ID 2761219 --- .../MSTest.Analyzers/xlf/Resources.fr.xlf | 32 +++++++------- .../MSTest.Analyzers/xlf/Resources.it.xlf | 32 +++++++------- .../MSTest.Analyzers/xlf/Resources.ja.xlf | 38 ++++++++-------- .../MSTest.Analyzers/xlf/Resources.ko.xlf | 44 +++++++++---------- .../MSTest.Analyzers/xlf/Resources.pl.xlf | 32 +++++++------- .../MSTest.Analyzers/xlf/Resources.pt-BR.xlf | 32 +++++++------- .../MSTest.Analyzers/xlf/Resources.ru.xlf | 32 +++++++------- .../MSTest.Analyzers/xlf/Resources.tr.xlf | 32 +++++++------- .../xlf/Resources.zh-Hans.xlf | 32 +++++++------- .../xlf/Resources.zh-Hant.xlf | 32 +++++++------- 10 files changed, 169 insertions(+), 169 deletions(-) diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf index 77b5c88911..723d8019fc 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf @@ -92,21 +92,6 @@ Le type doit être une classe La méthode AssemblyInitialize doit avoir une disposition valide - - Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws. - Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws. - - - - Assert.Throws should contain only a single statement/expression - Assert.Throws should contain only a single statement/expression - - - - Assert.Throws should contain only a single statement/expression - Assert.Throws should contain only a single statement/expression - - Prefer adding an additional assertion that checks for null Préférer l’ajout d’une assertion supplémentaire qui recherche la valeur null @@ -959,6 +944,21 @@ Le type doit être une classe Certaines propriétés TestContext sont disponibles uniquement pendant l’exécution du test et ne sont pas accessibles dans les méthodes d’initialisation d’assembly, d’initialisation de classe, de nettoyage de classe ou de nettoyage d’assembly. + + Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws. + Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws. + + + + Assert.Throws should contain only a single statement/expression + Assert.Throws should contain only a single statement/expression + + + + Assert.Throws should contain only a single statement/expression + Assert.Throws should contain only a single statement/expression + + - + \ No newline at end of file diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf index 4cfc1be033..59e6bb89da 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf @@ -92,21 +92,6 @@ Anche il tipo che dichiara questi metodi deve rispettare le regole seguenti: Il metodo AssemblyInitialize deve avere un layout valido - - Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws. - Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws. - - - - Assert.Throws should contain only a single statement/expression - Assert.Throws should contain only a single statement/expression - - - - Assert.Throws should contain only a single statement/expression - Assert.Throws should contain only a single statement/expression - - Prefer adding an additional assertion that checks for null Preferire l'aggiunta di un'ulteriore asserzione che controlli la presenza di valori null @@ -959,6 +944,21 @@ Anche il tipo che dichiara questi metodi deve rispettare le regole seguenti: Alcune proprietà TestContext sono disponibili solo durante l'esecuzione dei test e non è possibile accedervi nei metodi di inizializzazione degli assembly, inizializzazione delle classi, pulizia delle classi o pulizia degli assembly. + + Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws. + Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws. + + + + Assert.Throws should contain only a single statement/expression + Assert.Throws should contain only a single statement/expression + + + + Assert.Throws should contain only a single statement/expression + Assert.Throws should contain only a single statement/expression + + - + \ No newline at end of file diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf index 699df11940..6d4efeccfe 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf @@ -64,7 +64,7 @@ The type declaring these methods should also respect the following rules: -The class shouldn't be 'static' -The class should be marked with '[TestClass]' (or a derived attribute) -the class should not be generic. - '[AssemblyInitialize]' でマークされたメソッドを有効にするには、次のレイアウトに従う必要があります: + '[AssemblyInitialize]' でマークされたメソッドを有効にするには、次のレイアウトに従う必要があります: - ジェネリック クラスで宣言することはできません - 'public' である必要があります - 'static' である必要があります @@ -92,21 +92,6 @@ The type declaring these methods should also respect the following rules: AssemblyInitialize メソッドには有効なレイアウトが必要です - - Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws. - Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws. - - - - Assert.Throws should contain only a single statement/expression - Assert.Throws should contain only a single statement/expression - - - - Assert.Throws should contain only a single statement/expression - Assert.Throws should contain only a single statement/expression - - Prefer adding an additional assertion that checks for null 追加のアサーションによる null チェックを推奨する @@ -699,7 +684,7 @@ The type declaring these methods should also respect the following rules: -The class should be 'public' or 'internal' (if the test project is using the '[DiscoverInternals]' attribute) -The class shouldn't be 'static' -If the class is 'sealed', it should be marked with '[TestClass]' (or a derived attribute). - '[TestCleanup]' でマークされたメソッドを有効にするには、次のレイアウトに従う必要があります: + '[TestCleanup]' でマークされたメソッドを有効にするには、次のレイアウトに従う必要があります: - 'public' である必要があります - 'abstract' にすることはできません - 'async void' にすることはできません @@ -758,7 +743,7 @@ The type declaring these methods should also respect the following rules: -The class should be 'public' or 'internal' (if the test project is using the '[DiscoverInternals]' attribute) -The class shouldn't be 'static' -If the class is 'sealed', it should be marked with '[TestClass]' (or a derived attribute). - '[TestInitialize]' でマークされたメソッドを有効にするには、次のレイアウトに従う必要があります: + '[TestInitialize]' でマークされたメソッドを有効にするには、次のレイアウトに従う必要があります: - 'public' である必要があります - 'abstract' にすることはできません - 'async void' にすることはできません @@ -959,6 +944,21 @@ The type declaring these methods should also respect the following rules: TestContext プロパティの一部はテストの実行中にのみ使用でき、assenbly initialize、class initialize、class cleanup、または assembly cleanup メソッドではアクセスできません。 + + Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws. + Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws. + + + + Assert.Throws should contain only a single statement/expression + Assert.Throws should contain only a single statement/expression + + + + Assert.Throws should contain only a single statement/expression + Assert.Throws should contain only a single statement/expression + + - + \ No newline at end of file diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf index ff7ca2c36d..59a35da614 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf @@ -21,7 +21,7 @@ The type declaring these methods should also respect the following rules: -the class should not be generic. '[AssemblyCleanup]'으로 표시된 메서드가 유효하려면 다음 레이아웃을 따라야 합니다. - 제네릭 클래스에서 선언할 수 없습니다. -- 'public'이어야 합니다. +- 'public'이어야 합니다. - 'static'이어야 합니다. - 'async void'가 아니어야 합니다. - 특수 메서드(종료자, 연산자...)가 아니어야 합니다. @@ -66,7 +66,7 @@ The type declaring these methods should also respect the following rules: -the class should not be generic. '[AssemblyInitialize]'로 표시된 메서드가 유효하려면 다음 레이아웃을 따라야 합니다. -제네릭 클래스에서 선언할 수 없습니다. -- 'public'이어야 합니다. +- 'public'이어야 합니다. - 'static'이어야 합니다. - 'async void'가 아니어야 합니다. - 특수 메서드(종료자, 연산자...)가 아니어야 합니다. @@ -92,21 +92,6 @@ The type declaring these methods should also respect the following rules: AssemblyInitialize 메서드에는 유효한 레이아웃이 있어야 합니다. - - Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws. - Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws. - - - - Assert.Throws should contain only a single statement/expression - Assert.Throws should contain only a single statement/expression - - - - Assert.Throws should contain only a single statement/expression - Assert.Throws should contain only a single statement/expression - - Prefer adding an additional assertion that checks for null null을 확인하는 추가 어설션을 추가하는 것이 좋습니다. @@ -198,7 +183,7 @@ The type declaring these methods should also respect the following rules: -the class should not be generic. '[ClassCleanup]'으로 표시된 메서드가 유효하려면 다음 레이아웃을 따라야 합니다. - 'InheritanceBehavior' 모드가 설정되지 않은 제네릭 클래스에서 선언할 수 없습니다. -- 'public'이어야 합니다. +- 'public'이어야 합니다. - 'static'이어야 합니다. - 'async void'가 아니어야 합니다. - 특수 메서드(종료자, 연산자...)가 아니어야 합니다. @@ -247,7 +232,7 @@ The type declaring these methods should also respect the following rules: -the class should not be generic. '[ClassInitialize]'로 표시된 메서드가 유효하려면 다음 레이아웃을 따라야 합니다. -'InheritanceBehavior' 모드가 설정되지 않은 제네릭 클래스에서 선언할 수 없습니다. -- 'public'이어야 합니다. +- 'public'이어야 합니다. - 'static'이어야 합니다. - 'async void'가 아니어야 합니다. - 특수 메서드(종료자, 연산자...)가 아니어야 합니다. @@ -700,7 +685,7 @@ The type declaring these methods should also respect the following rules: -The class shouldn't be 'static' -If the class is 'sealed', it should be marked with '[TestClass]' (or a derived attribute). '[TestCleanup]'으로 표시된 메서드가 유효하려면 다음 레이아웃을 따라야 합니다. -- 'public'이어야 합니다. +- 'public'이어야 합니다. - 'abstract'가 아니어야 합니다. - 'async void'가 아니어야 합니다. - 'static'이 아니어야 합니다. @@ -759,7 +744,7 @@ The type declaring these methods should also respect the following rules: -The class shouldn't be 'static' -If the class is 'sealed', it should be marked with '[TestClass]' (or a derived attribute). '[TestInitialize]'로 표시된 메서드가 유효하려면 다음 레이아웃을 따라야 합니다. -- 'public'이어야 합니다. +- 'public'이어야 합니다. - 'abstract'가 아니어야 합니다. - 'async void'가 아니어야 합니다. - 'static'이 아니어야 합니다. @@ -959,6 +944,21 @@ The type declaring these methods should also respect the following rules: 일부 TestContext 속성은 테스트 실행 중에만 사용할 수 있으며, 어셈블리 초기화, 클래스 초기화, 클래스 정리 또는 어셈블리 정리 메서드에서는 액세스할 수 없습니다. + + Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws. + Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws. + + + + Assert.Throws should contain only a single statement/expression + Assert.Throws should contain only a single statement/expression + + + + Assert.Throws should contain only a single statement/expression + Assert.Throws should contain only a single statement/expression + + - + \ No newline at end of file diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf index 4d51a484ab..667dc0e6ce 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf @@ -92,21 +92,6 @@ Typ deklarujący te metody powinien również przestrzegać następujących regu Metody AssemblyInitialize powinny mieć prawidłowy układ - - Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws. - Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws. - - - - Assert.Throws should contain only a single statement/expression - Assert.Throws should contain only a single statement/expression - - - - Assert.Throws should contain only a single statement/expression - Assert.Throws should contain only a single statement/expression - - Prefer adding an additional assertion that checks for null Preferuj dodawanie dodatkowej asercji, która sprawdza pod kątem wartości null @@ -959,6 +944,21 @@ Typ deklarujący te metody powinien również przestrzegać następujących regu Niektóre właściwości TestContext są dostępne tylko podczas wykonywania testu i nie można uzyskać do nich dostępu w metodach inicjowania, inicjowania klasy, oczyszczania klasy ani oczyszczania zestawów. + + Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws. + Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws. + + + + Assert.Throws should contain only a single statement/expression + Assert.Throws should contain only a single statement/expression + + + + Assert.Throws should contain only a single statement/expression + Assert.Throws should contain only a single statement/expression + + - + \ No newline at end of file diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf index a56d8f07ae..82748b03c4 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf @@ -92,21 +92,6 @@ O tipo que declara esses métodos também deve respeitar as seguintes regras: Os métodos AssemblyInitialize devem ter um layout válido - - Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws. - Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws. - - - - Assert.Throws should contain only a single statement/expression - Assert.Throws should contain only a single statement/expression - - - - Assert.Throws should contain only a single statement/expression - Assert.Throws should contain only a single statement/expression - - Prefer adding an additional assertion that checks for null Preferir adicionar uma declaração adicional que verifica se existe um nulo @@ -959,6 +944,21 @@ O tipo que declara esses métodos também deve respeitar as seguintes regras: Algumas propriedades TestContext só estão disponíveis durante a execução do teste e não podem ser acessadas em métodos de inicialização de assembly, inicialização de classe, limpeza de classe ou limpeza de assembly. + + Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws. + Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws. + + + + Assert.Throws should contain only a single statement/expression + Assert.Throws should contain only a single statement/expression + + + + Assert.Throws should contain only a single statement/expression + Assert.Throws should contain only a single statement/expression + + - + \ No newline at end of file diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf index 0cb531a102..dde5f7cda7 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf @@ -95,21 +95,6 @@ The type declaring these methods should also respect the following rules: Методы AssemblyInitialize должны использовать допустимый макет - - Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws. - Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws. - - - - Assert.Throws should contain only a single statement/expression - Assert.Throws should contain only a single statement/expression - - - - Assert.Throws should contain only a single statement/expression - Assert.Throws should contain only a single statement/expression - - Prefer adding an additional assertion that checks for null Предпочитайте добавление дополнительного утверждения, проверяющего наличие значения NULL @@ -971,6 +956,21 @@ The type declaring these methods should also respect the following rules: Некоторые свойства TestContext доступны только во время выполнения теста и недоступны в методах инициализации сборки, инициализации класса, очистки класса или очистки сборки. + + Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws. + Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws. + + + + Assert.Throws should contain only a single statement/expression + Assert.Throws should contain only a single statement/expression + + + + Assert.Throws should contain only a single statement/expression + Assert.Throws should contain only a single statement/expression + + - + \ No newline at end of file diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf index 6861b7064b..85dcb105c5 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf @@ -92,21 +92,6 @@ Bu yöntemleri bildiren tipin ayrıca aşağıdaki kurallara uyması gerekir: AssemblyInitialize yöntemleri geçerli bir düzene sahip olmalıdır - - Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws. - Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws. - - - - Assert.Throws should contain only a single statement/expression - Assert.Throws should contain only a single statement/expression - - - - Assert.Throws should contain only a single statement/expression - Assert.Throws should contain only a single statement/expression - - Prefer adding an additional assertion that checks for null Null değerini denetlerken ek bir onaylama eklemeyi tercih et @@ -961,6 +946,21 @@ Bu yöntemleri bildiren tipin ayrıca aşağıdaki kurallara uyması gerekir: Bazı TestContext özellikleri yalnızca test yürütmesi sırasında kullanılabilir ve derleme başlatma, sınıf başlatma, sınıf temizleme veya derleme temizleme yöntemlerinde erişilemez. + + Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws. + Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws. + + + + Assert.Throws should contain only a single statement/expression + Assert.Throws should contain only a single statement/expression + + + + Assert.Throws should contain only a single statement/expression + Assert.Throws should contain only a single statement/expression + + - + \ No newline at end of file diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf index 944fc36c56..9301ffbaf1 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf @@ -92,21 +92,6 @@ The type declaring these methods should also respect the following rules: AssemblyInitialize 方法应具有有效的布局 - - Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws. - Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws. - - - - Assert.Throws should contain only a single statement/expression - Assert.Throws should contain only a single statement/expression - - - - Assert.Throws should contain only a single statement/expression - Assert.Throws should contain only a single statement/expression - - Prefer adding an additional assertion that checks for null 首选添加检查 null 的其他断言 @@ -959,6 +944,21 @@ The type declaring these methods should also respect the following rules: 一些 TestContext 属性仅在测试执行期间可用,并且无法在程序集初始化、类初始化、类清理或程序集清理方法中访问。 + + Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws. + Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws. + + + + Assert.Throws should contain only a single statement/expression + Assert.Throws should contain only a single statement/expression + + + + Assert.Throws should contain only a single statement/expression + Assert.Throws should contain only a single statement/expression + + - + \ No newline at end of file diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf index 5778ecc55c..6d927ef60c 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf @@ -92,21 +92,6 @@ The type declaring these methods should also respect the following rules: AssemblyInitialize 方法應該具有有效的配置 - - Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws. - Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws. - - - - Assert.Throws should contain only a single statement/expression - Assert.Throws should contain only a single statement/expression - - - - Assert.Throws should contain only a single statement/expression - Assert.Throws should contain only a single statement/expression - - Prefer adding an additional assertion that checks for null 偏好新增檢查 Null 的其他判斷提示 @@ -959,6 +944,21 @@ The type declaring these methods should also respect the following rules: 某些 TestContext 屬性僅在測試執行期間可供使用,無法在組件初始化、類別初始化、類別清理或組件清理方法中存取。 + + Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws. + Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws. + + + + Assert.Throws should contain only a single statement/expression + Assert.Throws should contain only a single statement/expression + + + + Assert.Throws should contain only a single statement/expression + Assert.Throws should contain only a single statement/expression + + - + \ No newline at end of file From 4c428c0d0b72c650cabd8c7eaa2dc31dfcb7c709 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Wed, 30 Jul 2025 13:37:44 +0200 Subject: [PATCH 333/541] Bump dependencies (#6243) --- Directory.Packages.props | 11 +++++------ .../DesktopTestSourceHostTests.cs | 2 +- .../ReflectionUtilityTests.cs | 2 +- .../Generators/DataRowAttributeGenerationTests.cs | 2 +- .../Generators/DynamicDataAttributeTests.cs | 2 +- .../Generators/IgnoreAttributeGenerationTests.cs | 2 +- .../Generators/StaticMethodGenerationTests.cs | 2 +- .../Generators/TestNodesGeneratorTests.cs | 2 +- .../Helpers/ConstantsTests.cs | 2 +- .../Helpers/GeneratorCompilationResultHelpers.cs | 2 +- .../Helpers/SourceCodeAssertionExtensions.cs | 2 +- .../Helpers/SourceCodeAssertions.cs | 6 +++--- .../TestUtilities/GeneratorTester.cs | 2 +- .../Assertions/AssertTests.Contains.cs | 2 +- .../Assertions/AssertTests.IComparableTests.cs | 2 +- .../Assertions/AssertTests.IsInRange.cs | 2 +- .../Attributes/CIConditionAttributeTests.cs | 2 +- 17 files changed, 23 insertions(+), 24 deletions(-) diff --git a/Directory.Packages.props b/Directory.Packages.props index 9d6d463190..784d1ceb9b 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -16,7 +16,7 @@ 17.11.4 3.11.0 4.10.0 - 3.11.0-beta1.25173.3 + 4.14.0 $(MicrosoftCodeAnalysisPublicApiAnalyzersVersion) 6.2.14 @@ -33,7 +33,7 @@ - + @@ -57,7 +57,7 @@ - + @@ -76,10 +76,9 @@ - - + - + diff --git a/test/IntegrationTests/PlatformServices.Desktop.IntegrationTests/DesktopTestSourceHostTests.cs b/test/IntegrationTests/PlatformServices.Desktop.IntegrationTests/DesktopTestSourceHostTests.cs index 793d570a5a..036e595186 100644 --- a/test/IntegrationTests/PlatformServices.Desktop.IntegrationTests/DesktopTestSourceHostTests.cs +++ b/test/IntegrationTests/PlatformServices.Desktop.IntegrationTests/DesktopTestSourceHostTests.cs @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. -using FluentAssertions; +using AwesomeAssertions; using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Utilities; diff --git a/test/IntegrationTests/PlatformServices.Desktop.IntegrationTests/ReflectionUtilityTests.cs b/test/IntegrationTests/PlatformServices.Desktop.IntegrationTests/ReflectionUtilityTests.cs index bad20b6f9d..135c8f072f 100644 --- a/test/IntegrationTests/PlatformServices.Desktop.IntegrationTests/ReflectionUtilityTests.cs +++ b/test/IntegrationTests/PlatformServices.Desktop.IntegrationTests/ReflectionUtilityTests.cs @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. -using FluentAssertions; +using AwesomeAssertions; using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Utilities; diff --git a/test/UnitTests/MSTest.SourceGeneration.UnitTests/Generators/DataRowAttributeGenerationTests.cs b/test/UnitTests/MSTest.SourceGeneration.UnitTests/Generators/DataRowAttributeGenerationTests.cs index 905e697241..e98484efb2 100644 --- a/test/UnitTests/MSTest.SourceGeneration.UnitTests/Generators/DataRowAttributeGenerationTests.cs +++ b/test/UnitTests/MSTest.SourceGeneration.UnitTests/Generators/DataRowAttributeGenerationTests.cs @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. -using FluentAssertions; +using AwesomeAssertions; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Text; diff --git a/test/UnitTests/MSTest.SourceGeneration.UnitTests/Generators/DynamicDataAttributeTests.cs b/test/UnitTests/MSTest.SourceGeneration.UnitTests/Generators/DynamicDataAttributeTests.cs index 21c0def72c..e53515cd66 100644 --- a/test/UnitTests/MSTest.SourceGeneration.UnitTests/Generators/DynamicDataAttributeTests.cs +++ b/test/UnitTests/MSTest.SourceGeneration.UnitTests/Generators/DynamicDataAttributeTests.cs @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. -using FluentAssertions; +using AwesomeAssertions; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Text; diff --git a/test/UnitTests/MSTest.SourceGeneration.UnitTests/Generators/IgnoreAttributeGenerationTests.cs b/test/UnitTests/MSTest.SourceGeneration.UnitTests/Generators/IgnoreAttributeGenerationTests.cs index 402f796376..e80811eaba 100644 --- a/test/UnitTests/MSTest.SourceGeneration.UnitTests/Generators/IgnoreAttributeGenerationTests.cs +++ b/test/UnitTests/MSTest.SourceGeneration.UnitTests/Generators/IgnoreAttributeGenerationTests.cs @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. -using FluentAssertions; +using AwesomeAssertions; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Text; diff --git a/test/UnitTests/MSTest.SourceGeneration.UnitTests/Generators/StaticMethodGenerationTests.cs b/test/UnitTests/MSTest.SourceGeneration.UnitTests/Generators/StaticMethodGenerationTests.cs index d536926a30..aa801b8bfd 100644 --- a/test/UnitTests/MSTest.SourceGeneration.UnitTests/Generators/StaticMethodGenerationTests.cs +++ b/test/UnitTests/MSTest.SourceGeneration.UnitTests/Generators/StaticMethodGenerationTests.cs @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. -using FluentAssertions; +using AwesomeAssertions; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Text; diff --git a/test/UnitTests/MSTest.SourceGeneration.UnitTests/Generators/TestNodesGeneratorTests.cs b/test/UnitTests/MSTest.SourceGeneration.UnitTests/Generators/TestNodesGeneratorTests.cs index c528c601ba..a66808826e 100644 --- a/test/UnitTests/MSTest.SourceGeneration.UnitTests/Generators/TestNodesGeneratorTests.cs +++ b/test/UnitTests/MSTest.SourceGeneration.UnitTests/Generators/TestNodesGeneratorTests.cs @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. -using FluentAssertions; +using AwesomeAssertions; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Text; diff --git a/test/UnitTests/MSTest.SourceGeneration.UnitTests/Helpers/ConstantsTests.cs b/test/UnitTests/MSTest.SourceGeneration.UnitTests/Helpers/ConstantsTests.cs index a579ec298c..1944f5b664 100644 --- a/test/UnitTests/MSTest.SourceGeneration.UnitTests/Helpers/ConstantsTests.cs +++ b/test/UnitTests/MSTest.SourceGeneration.UnitTests/Helpers/ConstantsTests.cs @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. -using FluentAssertions; +using AwesomeAssertions; namespace Microsoft.Testing.Framework.SourceGeneration.UnitTests; diff --git a/test/UnitTests/MSTest.SourceGeneration.UnitTests/Helpers/GeneratorCompilationResultHelpers.cs b/test/UnitTests/MSTest.SourceGeneration.UnitTests/Helpers/GeneratorCompilationResultHelpers.cs index 6bd800f900..e9c4db7ff9 100644 --- a/test/UnitTests/MSTest.SourceGeneration.UnitTests/Helpers/GeneratorCompilationResultHelpers.cs +++ b/test/UnitTests/MSTest.SourceGeneration.UnitTests/Helpers/GeneratorCompilationResultHelpers.cs @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. -using FluentAssertions; +using AwesomeAssertions; using Microsoft.CodeAnalysis; using Microsoft.Testing.Framework.SourceGeneration.UnitTests.Helpers; diff --git a/test/UnitTests/MSTest.SourceGeneration.UnitTests/Helpers/SourceCodeAssertionExtensions.cs b/test/UnitTests/MSTest.SourceGeneration.UnitTests/Helpers/SourceCodeAssertionExtensions.cs index 0c9e28aae2..e2c6014a6b 100644 --- a/test/UnitTests/MSTest.SourceGeneration.UnitTests/Helpers/SourceCodeAssertionExtensions.cs +++ b/test/UnitTests/MSTest.SourceGeneration.UnitTests/Helpers/SourceCodeAssertionExtensions.cs @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. -using FluentAssertions.Execution; +using AwesomeAssertions.Execution; using Microsoft.CodeAnalysis.Text; diff --git a/test/UnitTests/MSTest.SourceGeneration.UnitTests/Helpers/SourceCodeAssertions.cs b/test/UnitTests/MSTest.SourceGeneration.UnitTests/Helpers/SourceCodeAssertions.cs index 369801c195..6d24195427 100644 --- a/test/UnitTests/MSTest.SourceGeneration.UnitTests/Helpers/SourceCodeAssertions.cs +++ b/test/UnitTests/MSTest.SourceGeneration.UnitTests/Helpers/SourceCodeAssertions.cs @@ -1,9 +1,9 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. -using FluentAssertions; -using FluentAssertions.Execution; -using FluentAssertions.Primitives; +using AwesomeAssertions; +using AwesomeAssertions.Execution; +using AwesomeAssertions.Primitives; namespace Microsoft.Testing.Framework.SourceGeneration.UnitTests.Helpers; diff --git a/test/UnitTests/MSTest.SourceGeneration.UnitTests/TestUtilities/GeneratorTester.cs b/test/UnitTests/MSTest.SourceGeneration.UnitTests/TestUtilities/GeneratorTester.cs index 1bbd56f15a..28dd385e13 100644 --- a/test/UnitTests/MSTest.SourceGeneration.UnitTests/TestUtilities/GeneratorTester.cs +++ b/test/UnitTests/MSTest.SourceGeneration.UnitTests/TestUtilities/GeneratorTester.cs @@ -3,7 +3,7 @@ using System.Collections.Immutable; -using FluentAssertions; +using AwesomeAssertions; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; diff --git a/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.Contains.cs b/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.Contains.cs index ea9da826ea..b751807d44 100644 --- a/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.Contains.cs +++ b/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.Contains.cs @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. -using FluentAssertions; +using AwesomeAssertions; using TestFramework.ForTestingMSTest; diff --git a/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.IComparableTests.cs b/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.IComparableTests.cs index 33267fd00f..4b17cb9ae4 100644 --- a/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.IComparableTests.cs +++ b/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.IComparableTests.cs @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. -using FluentAssertions; +using AwesomeAssertions; using TestFramework.ForTestingMSTest; diff --git a/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.IsInRange.cs b/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.IsInRange.cs index 016b02a799..c3aef44bc3 100644 --- a/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.IsInRange.cs +++ b/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.IsInRange.cs @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. -using FluentAssertions; +using AwesomeAssertions; using TestFramework.ForTestingMSTest; diff --git a/test/UnitTests/TestFramework.UnitTests/Attributes/CIConditionAttributeTests.cs b/test/UnitTests/TestFramework.UnitTests/Attributes/CIConditionAttributeTests.cs index 701a1f4ca7..1a0b6687d5 100644 --- a/test/UnitTests/TestFramework.UnitTests/Attributes/CIConditionAttributeTests.cs +++ b/test/UnitTests/TestFramework.UnitTests/Attributes/CIConditionAttributeTests.cs @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. -using FluentAssertions; +using AwesomeAssertions; using Moq; From 95aa658728658407e9887d0aee9afdf4c4fbe54f Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Wed, 30 Jul 2025 16:04:15 +0200 Subject: [PATCH 334/541] Fix race in TestContextImplementation (#6249) --- .../Services/TestContextImplementation.cs | 39 ++++++++++++++----- .../TestContextImplementationTests.cs | 18 +++++++++ 2 files changed, 48 insertions(+), 9 deletions(-) diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Services/TestContextImplementation.cs b/src/Adapter/MSTestAdapter.PlatformServices/Services/TestContextImplementation.cs index b2d0ab97d1..2dcb6d291c 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Services/TestContextImplementation.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Services/TestContextImplementation.cs @@ -27,6 +27,27 @@ namespace Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; #endif public class TestContextImplementation : TestContext, ITestContext, IDisposable { + internal sealed class SynchronizedStringBuilder + { + private readonly StringBuilder _builder = new(); + + [MethodImpl(MethodImplOptions.Synchronized)] + internal void Append(char value) + => _builder.Append(value); + + [MethodImpl(MethodImplOptions.Synchronized)] + internal void Append(string? value) + => _builder.Append(value); + + [MethodImpl(MethodImplOptions.Synchronized)] + internal void Append(char[] buffer, int index, int count) + => _builder.Append(buffer, index, count); + + [MethodImpl(MethodImplOptions.Synchronized)] + public override string ToString() + => _builder.ToString(); + } + private static readonly AsyncLocal CurrentTestContextAsyncLocal = new(); /// @@ -45,9 +66,9 @@ public class TestContextImplementation : TestContext, ITestContext, IDisposable private readonly IMessageLogger? _messageLogger; private readonly CancellationTokenRegistration? _cancellationTokenRegistration; - private StringBuilder? _stdOutStringBuilder; - private StringBuilder? _stdErrStringBuilder; - private StringBuilder? _traceStringBuilder; + private SynchronizedStringBuilder? _stdOutStringBuilder; + private SynchronizedStringBuilder? _stdErrStringBuilder; + private SynchronizedStringBuilder? _traceStringBuilder; private StringBuilder? _testContextMessageStringBuilder; private bool _isDisposed; @@ -394,21 +415,21 @@ internal void WriteTrace(char value) internal void WriteTrace(string? value) => GetTraceStringBuilder().Append(value); - private StringBuilder GetOutStringBuilder() + private SynchronizedStringBuilder GetOutStringBuilder() { - _ = _stdOutStringBuilder ?? Interlocked.CompareExchange(ref _stdOutStringBuilder, new StringBuilder(), null)!; + _ = _stdOutStringBuilder ?? Interlocked.CompareExchange(ref _stdOutStringBuilder, new SynchronizedStringBuilder(), null)!; return _stdOutStringBuilder; } - private StringBuilder GetErrStringBuilder() + private SynchronizedStringBuilder GetErrStringBuilder() { - _ = _stdErrStringBuilder ?? Interlocked.CompareExchange(ref _stdErrStringBuilder, new StringBuilder(), null)!; + _ = _stdErrStringBuilder ?? Interlocked.CompareExchange(ref _stdErrStringBuilder, new SynchronizedStringBuilder(), null)!; return _stdErrStringBuilder; } - private StringBuilder GetTraceStringBuilder() + private SynchronizedStringBuilder GetTraceStringBuilder() { - _ = _traceStringBuilder ?? Interlocked.CompareExchange(ref _traceStringBuilder, new StringBuilder(), null)!; + _ = _traceStringBuilder ?? Interlocked.CompareExchange(ref _traceStringBuilder, new SynchronizedStringBuilder(), null)!; return _traceStringBuilder; } diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/TestContextImplementationTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/TestContextImplementationTests.cs index 92d5588978..dc49451d72 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/TestContextImplementationTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/TestContextImplementationTests.cs @@ -407,4 +407,22 @@ public void DisplayMessageShouldForwardToIMessageLogger() messageLoggerMock.Verify(x => x.SendMessage(TestMessageLevel.Warning, "WarningMessage"), Times.Once); messageLoggerMock.Verify(x => x.SendMessage(TestMessageLevel.Error, "ErrorMessage"), Times.Once); } + + public void WritesFromBackgroundThreadShouldNotThrow() + { + var testContextImplementation = new TestContextImplementation(_testMethod.Object, _properties, new Mock().Object, testRunCancellationToken: null); + var t = new Thread(() => + { + for (int i = 0; i < 100; i++) + { + testContextImplementation.WriteConsoleOut(new string('a', 1000000)); + testContextImplementation.WriteConsoleErr(new string('b', 1000000)); + } + }); + + t.Start(); + _ = testContextImplementation.GetOut(); + _ = testContextImplementation.GetErr(); + t.Join(); + } } From 9f49e7a264ea799ff1adfdbe79cc45eefdc89cee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Wed, 30 Jul 2025 18:09:32 +0200 Subject: [PATCH 335/541] Make azdo extension stable (#6252) --- src/Package/MSTest.Sdk/Sdk/Runner/ClassicEngine.targets | 7 +++++++ .../Microsoft.Testing.Extensions.AzureDevOpsReport.csproj | 5 ----- .../MSTest.Acceptance.IntegrationTests/SdkTests.cs | 7 ++++++- 3 files changed, 13 insertions(+), 6 deletions(-) diff --git a/src/Package/MSTest.Sdk/Sdk/Runner/ClassicEngine.targets b/src/Package/MSTest.Sdk/Sdk/Runner/ClassicEngine.targets index 7f0480c71f..8ff884ae40 100644 --- a/src/Package/MSTest.Sdk/Sdk/Runner/ClassicEngine.targets +++ b/src/Package/MSTest.Sdk/Sdk/Runner/ClassicEngine.targets @@ -34,6 +34,10 @@ true $(MicrosoftTestingExtensionsCommonVersion) + + true + $(MicrosoftTestingExtensionsCommonVersion) + true $(MicrosoftTestingExtensionsFakesVersion) @@ -86,6 +90,9 @@ + diff --git a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Microsoft.Testing.Extensions.AzureDevOpsReport.csproj b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Microsoft.Testing.Extensions.AzureDevOpsReport.csproj index cf9962e410..eaf0d46fd9 100644 --- a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Microsoft.Testing.Extensions.AzureDevOpsReport.csproj +++ b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Microsoft.Testing.Extensions.AzureDevOpsReport.csproj @@ -2,11 +2,6 @@ netstandard2.0;$(MicrosoftTestingTargetFrameworks) - - - 1.0.0 - alpha - true diff --git a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/SdkTests.cs b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/SdkTests.cs index 2a2ceeb800..67a16ff3a1 100644 --- a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/SdkTests.cs +++ b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/SdkTests.cs @@ -177,6 +177,11 @@ public async Task RunTests_With_CentralPackageManagement_Standalone(string multi "true", "--hangdump", "--crashdump"); + + yield return new(buildConfig.MultiTfm, buildConfig.BuildConfiguration, + "true", + "--report-azdo", + "--crashdump"); } } @@ -223,7 +228,7 @@ public async Task RunTests_With_MSTestRunner_Standalone_EnableAll_Extensions(str foreach (string tfm in multiTfm.Split(";")) { var testHost = TestHost.LocateFrom(testAsset.TargetAssetPath, AssetName, tfm, buildConfiguration: buildConfiguration); - TestHostResult testHostResult = await testHost.ExecuteAsync(command: "--coverage --retry-failed-tests 3 --report-trx --crashdump --hangdump"); + TestHostResult testHostResult = await testHost.ExecuteAsync(command: "--coverage --retry-failed-tests 3 --report-trx --crashdump --hangdump --report-azdo"); testHostResult.AssertOutputContainsSummary(0, 1, 0); } } From e8e32f8bffcb4cd9d9e6c86e52423b3ab7652f9e Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Thu, 31 Jul 2025 04:32:42 +0000 Subject: [PATCH 336/541] [main] Update dependencies from devdiv/DevDiv/vs-code-coverage (#6255) [main] Update dependencies from devdiv/DevDiv/vs-code-coverage --- eng/Version.Details.xml | 4 ++-- eng/Versions.props | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index 5361e90ac3..096284cf8b 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -13,9 +13,9 @@ https://github.com/dotnet/arcade 8df06d38fb9183c3fdff5077b670eb35f0cb3f31 - + https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage - 23601926c69466349912ac82a09b791098af451c + f6f6f1d48de353f64e428115a9624dc4c73dd13b https://github.com/microsoft/testfx diff --git a/eng/Versions.props b/eng/Versions.props index 51e79ad8be..edd1086a54 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -8,7 +8,7 @@ 10.0.0-beta.25379.3 - 18.0.0-preview.25379.1 + 18.0.0-preview.25380.2 3.11.0-preview.25379.21 1.9.0-preview.25379.21 From 929bdf5ee23cb50e9fe9647181b392b0f7faa5f4 Mon Sep 17 00:00:00 2001 From: dotnet bot Date: Wed, 30 Jul 2025 21:48:14 -0700 Subject: [PATCH 337/541] Localized file check-in by OneLocBuild Task: Build definition ID 1218: Build ID 2761755 --- .../MSTest.Analyzers/xlf/Resources.cs.xlf | 34 +++++++++---------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf index 184dd976cb..aab0b81907 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf @@ -464,32 +464,32 @@ The type declaring these methods should also respect the following rules: -The class shouldn't be 'static' -The class should be marked with '[TestClass]' (or a derived attribute) -the class should not be generic. - Methods marked with '[GlobalTestInitialize]' or '[GlobalTestCleanup]' should follow the following layout to be valid: --it can't be declared on a generic class --it should be 'public' --it should be 'static' --it should not be 'async void' --it should not be a special method (finalizer, operator...). --it should not be generic --it should take one parameter of type 'TestContext' --return type should be 'void', 'Task' or 'ValueTask' + Aby byly metody s označením [GlobalTestInitialize] nebo [GlobalTestCleanup] platné, musí se řídit následujícím rozložením: +– Nesmí být deklarované pro obecnou třídu. +– Musí být „public“. +– Musí být „static“. +– Nesmí být „async void“. +– Nesmí být speciální metodou („finalizer“, „operator“...). +– Nesmí být obecné. +– Musí mít jeden parametr typu TestContext. +– Návratový typ musí být „void“, „Task“ nebo „ValueTask“. -The type declaring these methods should also respect the following rules: --The type should be a class --The class should be 'public' --The class shouldn't be 'static' --The class should be marked with '[TestClass]' (or a derived attribute) --the class should not be generic. +Typ deklarující tyto metody by měl také respektovat následující pravidla: +– Typ by měl být třída. +– Třída by měla být „public“. +– Třída by neměla být „static“. +– Třída by měla být označena atributem [TestClass] (nebo odvozeným atributem). +– Třída by neměla být obecná. Global test fixture method '{0}' signature is invalid - Global test fixture method '{0}' signature is invalid + Podpis metody globálního testovacího přípravku {0} je neplatný. GlobalTestInitialize and GlobalTestCleanup methods should have valid layout - GlobalTestInitialize and GlobalTestCleanup methods should have valid layout + Metody GlobalTestInitialize a GlobalTestCleanup by měly mít platné rozložení. From ad51e7e08a585529971575c0b147772c838c2afa Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Thu, 31 Jul 2025 08:17:41 +0200 Subject: [PATCH 338/541] [main] Update dependencies from microsoft/testfx (#6256) Co-authored-by: dotnet-maestro[bot] --- eng/Version.Details.xml | 8 ++++---- eng/Versions.props | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index 096284cf8b..0edc34f6de 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -17,13 +17,13 @@ https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage f6f6f1d48de353f64e428115a9624dc4c73dd13b - + https://github.com/microsoft/testfx - f822bb9cfb379c5d49b6a138504bea8f0093ca7b + 9f49e7a264ea799ff1adfdbe79cc45eefdc89cee - + https://github.com/microsoft/testfx - f822bb9cfb379c5d49b6a138504bea8f0093ca7b + 9f49e7a264ea799ff1adfdbe79cc45eefdc89cee diff --git a/eng/Versions.props b/eng/Versions.props index edd1086a54..e496124367 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -10,7 +10,7 @@ 10.0.0-beta.25379.3 18.0.0-preview.25380.2 - 3.11.0-preview.25379.21 - 1.9.0-preview.25379.21 + 3.11.0-preview.25380.15 + 1.9.0-preview.25380.15 From 22ed24bd95d8d8d96c97057e4c1551d422a372f7 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Thu, 31 Jul 2025 09:45:58 +0200 Subject: [PATCH 339/541] Cleanup test/Directory.Build.targets (#6258) --- test/Directory.Build.targets | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/test/Directory.Build.targets b/test/Directory.Build.targets index 8d8896cb3d..b8089a73ab 100644 --- a/test/Directory.Build.targets +++ b/test/Directory.Build.targets @@ -4,7 +4,6 @@ - true false false $(PlatformTarget) @@ -59,8 +58,7 @@ - + From aaa561e10ae83650f1f3d8ec9f68e31737101c6a Mon Sep 17 00:00:00 2001 From: Copilot <198982749+Copilot@users.noreply.github.com> Date: Thu, 31 Jul 2025 08:25:52 +0000 Subject: [PATCH 340/541] Fix codefix of analyzer for flowing cancellation token (#6239) Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: Evangelink <11340282+Evangelink@users.noreply.github.com> Co-authored-by: Youssef1313 --- .../FlowTestContextCancellationTokenFixer.cs | 204 ++++++++++++++-- ...lowTestContextCancellationTokenAnalyzer.cs | 36 +-- ...stContextCancellationTokenAnalyzerTests.cs | 217 +++++++++++++++++- 3 files changed, 424 insertions(+), 33 deletions(-) diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/FlowTestContextCancellationTokenFixer.cs b/src/Analyzers/MSTest.Analyzers.CodeFixes/FlowTestContextCancellationTokenFixer.cs index 0941d05e6c..83ec8e124d 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/FlowTestContextCancellationTokenFixer.cs +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/FlowTestContextCancellationTokenFixer.cs @@ -16,6 +16,8 @@ using MSTest.Analyzers.Helpers; +using Polyfills; + namespace MSTest.Analyzers; /// @@ -31,8 +33,8 @@ public sealed class FlowTestContextCancellationTokenFixer : CodeFixProvider /// public override FixAllProvider GetFixAllProvider() - // See https://github.com/dotnet/roslyn/blob/main/docs/analyzers/FixAllProvider.md for more information on Fix All Providers - => WellKnownFixAllProviders.BatchFixer; + // Use custom FixAllProvider to handle adding TestContext property when needed + => FlowTestContextCancellationTokenFixAllProvider.Instance; /// public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) @@ -49,37 +51,213 @@ public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) } diagnostic.Properties.TryGetValue(FlowTestContextCancellationTokenAnalyzer.TestContextMemberNamePropertyKey, out string? testContextMemberName); + diagnostic.Properties.TryGetValue(nameof(FlowTestContextCancellationTokenAnalyzer.TestContextState), out string? testContextState); // Register a code action that will invoke the fix context.RegisterCodeFix( CodeAction.Create( title: CodeFixResources.PassCancellationTokenFix, - createChangedDocument: c => AddCancellationTokenParameterAsync(context.Document, invocationExpression, testContextMemberName, c), - equivalenceKey: "AddTestContextCancellationToken"), + createChangedDocument: async c => + { + DocumentEditor editor = await DocumentEditor.CreateAsync(context.Document, context.CancellationToken).ConfigureAwait(false); + return ApplyFix(editor, invocationExpression, testContextMemberName, testContextState, adjustedSymbols: null, c); + }, + equivalenceKey: nameof(FlowTestContextCancellationTokenFixer)), diagnostic); } - private static async Task AddCancellationTokenParameterAsync( - Document document, + internal static Document ApplyFix( + DocumentEditor editor, InvocationExpressionSyntax invocationExpression, string? testContextMemberName, + string? testContextState, + HashSet? adjustedSymbols, CancellationToken cancellationToken) { - DocumentEditor editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false); + if (testContextState == nameof(FlowTestContextCancellationTokenAnalyzer.TestContextState.CouldBeInScopeAsProperty)) + { + Debug.Assert(testContextMemberName is null, "TestContext member name should be null when state is CouldBeInScopeAsProperty"); + AddCancellationTokenArgument(editor, invocationExpression, "TestContext"); + TypeDeclarationSyntax? containingTypeDeclaration = invocationExpression.FirstAncestorOrSelf(); + if (containingTypeDeclaration is not null) + { + // adjustedSymbols is null meaning we are only applying a single fix (in that case we add the property). + // If we are in fix all, we then verify if a previous fix has already added the property. + // We only add the property if it wasn't added by a previous fix. + // NOTE: We don't expect GetDeclaredSymbol to return null, but if it did (e.g, error scenario), we add the property. + if (adjustedSymbols is null || + editor.SemanticModel.GetDeclaredSymbol(containingTypeDeclaration, cancellationToken) is not { } symbol || + adjustedSymbols.Add(symbol)) + { + editor.ReplaceNode(containingTypeDeclaration, (containingTypeDeclaration, _) => AddTestContextProperty((TypeDeclarationSyntax)containingTypeDeclaration)); + } + } + } + else if (testContextState == nameof(FlowTestContextCancellationTokenAnalyzer.TestContextState.CouldBeInScopeAsParameter)) + { + Debug.Assert(testContextMemberName is null, "TestContext member name should be null when state is CouldBeInScopeAsParameter"); + AddCancellationTokenArgument(editor, invocationExpression, "testContext"); + MethodDeclarationSyntax? containingMethodDeclaration = invocationExpression.FirstAncestorOrSelf(); + + if (containingMethodDeclaration is not null) + { + // adjustedSymbols is null meaning we are only applying a single fix (in that case we add the parameter). + // If we are in fix all, we then verify if a previous fix has already added the parameter. + // We only add the parameter if it wasn't added by a previous fix. + // NOTE: We don't expect GetDeclaredSymbol to return null, but if it did (e.g, error scenario), we add the property. + if (adjustedSymbols is null || + editor.SemanticModel.GetDeclaredSymbol(containingMethodDeclaration, cancellationToken) is not { } symbol || + adjustedSymbols.Add(symbol)) + { + editor.ReplaceNode(containingMethodDeclaration, (containingMethodDeclaration, _) => AddTestContextParameterToMethod((MethodDeclarationSyntax)containingMethodDeclaration)); + } + } + } + else + { + Guard.NotNull(testContextMemberName); + AddCancellationTokenArgument(editor, invocationExpression, testContextMemberName); + } + + return editor.GetChangedDocument(); + } + + internal static void AddCancellationTokenArgument( + DocumentEditor editor, + InvocationExpressionSyntax invocationExpression, + string testContextMemberName) + { + // Find the containing method to determine the context + MethodDeclarationSyntax? containingMethod = invocationExpression.FirstAncestorOrSelf(); // Create the TestContext.CancellationTokenSource.Token expression MemberAccessExpressionSyntax testContextExpression = SyntaxFactory.MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, SyntaxFactory.MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, - SyntaxFactory.IdentifierName(testContextMemberName ?? "testContext"), + SyntaxFactory.IdentifierName(testContextMemberName), SyntaxFactory.IdentifierName("CancellationTokenSource")), SyntaxFactory.IdentifierName("Token")); - ArgumentListSyntax currentArguments = invocationExpression.ArgumentList; - SeparatedSyntaxList newArguments = currentArguments.Arguments.Add(SyntaxFactory.Argument(testContextExpression)); - InvocationExpressionSyntax newInvocation = invocationExpression.WithArgumentList(currentArguments.WithArguments(newArguments)); - editor.ReplaceNode(invocationExpression, newInvocation); - return editor.GetChangedDocument(); + editor.ReplaceNode(invocationExpression, (node, _) => + { + var invocationExpression = (InvocationExpressionSyntax)node; + ArgumentListSyntax currentArguments = invocationExpression.ArgumentList; + SeparatedSyntaxList newArguments = currentArguments.Arguments.Add(SyntaxFactory.Argument(testContextExpression)); + return invocationExpression.WithArgumentList(currentArguments.WithArguments(newArguments)); + }); + } + + internal static MethodDeclarationSyntax AddTestContextParameterToMethod(MethodDeclarationSyntax method) + { + // Create TestContext parameter + ParameterSyntax testContextParameter = SyntaxFactory.Parameter(SyntaxFactory.Identifier("testContext")) + .WithType(SyntaxFactory.IdentifierName("TestContext")); + + // Add the parameter to the method + SeparatedSyntaxList updatedParameterList = method.ParameterList.Parameters.Count == 0 + ? SyntaxFactory.SingletonSeparatedList(testContextParameter) + : method.ParameterList.Parameters.Add(testContextParameter); + + return method.WithParameterList(method.ParameterList.WithParameters(updatedParameterList)); + } + + internal static TypeDeclarationSyntax AddTestContextProperty(TypeDeclarationSyntax typeDeclaration) + { + PropertyDeclarationSyntax testContextProperty = SyntaxFactory.PropertyDeclaration( + SyntaxFactory.IdentifierName("TestContext"), + "TestContext") + .WithModifiers(SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.PublicKeyword))) + .WithAccessorList(SyntaxFactory.AccessorList( + SyntaxFactory.List(new[] + { + SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration) + .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)), + SyntaxFactory.AccessorDeclaration(SyntaxKind.SetAccessorDeclaration) + .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)), + }))); + + return typeDeclaration.AddMembers(testContextProperty); + } +} + +/// +/// Custom FixAllProvider for that can add TestContext property when needed. +/// This ensures that when multiple fixes are applied to the same class, the TestContext property is added only once. +/// +internal sealed class FlowTestContextCancellationTokenFixAllProvider : FixAllProvider +{ + public static readonly FlowTestContextCancellationTokenFixAllProvider Instance = new(); + + private FlowTestContextCancellationTokenFixAllProvider() + { + } + + public override Task GetFixAsync(FixAllContext fixAllContext) + => Task.FromResult(new FixAllCodeAction(fixAllContext)); + + private sealed class FixAllCodeAction : CodeAction + { + private readonly FixAllContext _fixAllContext; + + public FixAllCodeAction(FixAllContext fixAllContext) + => _fixAllContext = fixAllContext; + + public override string Title => CodeFixResources.PassCancellationTokenFix; + + public override string? EquivalenceKey => nameof(FlowTestContextCancellationTokenFixer); + + protected override async Task GetChangedSolutionAsync(CancellationToken cancellationToken) + { + FixAllContext fixAllContext = _fixAllContext; + var editor = new SolutionEditor(fixAllContext.Solution); + var fixedSymbols = new HashSet(SymbolEqualityComparer.Default); + + if (fixAllContext.Scope == FixAllScope.Document) + { + DocumentEditor documentEditor = await editor.GetDocumentEditorAsync(fixAllContext.Document!.Id, cancellationToken).ConfigureAwait(false); + foreach (Diagnostic diagnostic in await fixAllContext.GetDocumentDiagnosticsAsync(fixAllContext.Document!).ConfigureAwait(false)) + { + FixOneDiagnostic(documentEditor, diagnostic, fixedSymbols, cancellationToken); + } + } + else if (fixAllContext.Scope == FixAllScope.Project) + { + await FixAllInProjectAsync(fixAllContext, fixAllContext.Project, editor, fixedSymbols, cancellationToken).ConfigureAwait(false); + } + else if (fixAllContext.Scope == FixAllScope.Solution) + { + foreach (Project project in fixAllContext.Solution.Projects) + { + await FixAllInProjectAsync(fixAllContext, project, editor, fixedSymbols, cancellationToken).ConfigureAwait(false); + } + } + + return editor.GetChangedSolution(); + } + + private static async Task FixAllInProjectAsync(FixAllContext fixAllContext, Project project, SolutionEditor editor, HashSet fixedSymbols, CancellationToken cancellationToken) + { + foreach (Diagnostic diagnostic in await fixAllContext.GetAllDiagnosticsAsync(project).ConfigureAwait(false)) + { + DocumentId documentId = editor.OriginalSolution.GetDocumentId(diagnostic.Location.SourceTree)!; + DocumentEditor documentEditor = await editor.GetDocumentEditorAsync(documentId, cancellationToken).ConfigureAwait(false); + FixOneDiagnostic(documentEditor, diagnostic, fixedSymbols, cancellationToken); + } + } + + private static void FixOneDiagnostic(DocumentEditor documentEditor, Diagnostic diagnostic, HashSet fixedSymbols, CancellationToken cancellationToken) + { + SyntaxNode node = documentEditor.OriginalRoot.FindNode(diagnostic.Location.SourceSpan, getInnermostNodeForTie: true); + if (node is not InvocationExpressionSyntax invocationExpression) + { + return; + } + + diagnostic.Properties.TryGetValue(FlowTestContextCancellationTokenAnalyzer.TestContextMemberNamePropertyKey, out string? testContextMemberName); + diagnostic.Properties.TryGetValue(nameof(FlowTestContextCancellationTokenAnalyzer.TestContextState), out string? testContextState); + + FlowTestContextCancellationTokenFixer.ApplyFix(documentEditor, invocationExpression, testContextMemberName, testContextState, fixedSymbols, cancellationToken); + } } } diff --git a/src/Analyzers/MSTest.Analyzers/FlowTestContextCancellationTokenAnalyzer.cs b/src/Analyzers/MSTest.Analyzers/FlowTestContextCancellationTokenAnalyzer.cs index cf38e10478..19eb3b5cde 100644 --- a/src/Analyzers/MSTest.Analyzers/FlowTestContextCancellationTokenAnalyzer.cs +++ b/src/Analyzers/MSTest.Analyzers/FlowTestContextCancellationTokenAnalyzer.cs @@ -74,7 +74,7 @@ private static void AnalyzeInvocation( IMethodSymbol method = invocationOperation.TargetMethod; // Check if we're in a context where a TestContext is already available or could be made available. - if (!HasOrCouldHaveTestContextInScope(context.ContainingSymbol, testContextSymbol, classCleanupAttributeSymbol, assemblyCleanupAttributeSymbol, testMethodAttributeSymbol, out string? testContextMemberNameInScope)) + if (!HasOrCouldHaveTestContextInScope(context.ContainingSymbol, testContextSymbol, classCleanupAttributeSymbol, assemblyCleanupAttributeSymbol, testMethodAttributeSymbol, out string? testContextMemberNameInScope, out TestContextState? testContextState)) { return; } @@ -93,13 +93,7 @@ private static void AnalyzeInvocation( invocationOperation.Arguments.FirstOrDefault(arg => SymbolEqualityComparer.Default.Equals(arg.Parameter, cancellationTokenParameter))?.ArgumentKind != ArgumentKind.Explicit) { // The called method has an optional CancellationToken parameter, but it was not explicitly provided. - ImmutableDictionary properties = ImmutableDictionary.Empty; - if (testContextMemberNameInScope is not null) - { - properties = properties.Add(TestContextMemberNamePropertyKey, testContextMemberNameInScope); - } - - context.ReportDiagnostic(invocationOperation.Syntax.CreateDiagnostic(FlowTestContextCancellationTokenRule, properties: GetPropertiesBag(testContextMemberNameInScope))); + context.ReportDiagnostic(invocationOperation.Syntax.CreateDiagnostic(FlowTestContextCancellationTokenRule, properties: GetPropertiesBag(testContextMemberNameInScope, testContextState))); return; } @@ -108,16 +102,15 @@ private static void AnalyzeInvocation( if (cancellationTokenParameter is null && HasOverloadWithCancellationToken(method, cancellationTokenSymbol)) { - context.ReportDiagnostic(invocationOperation.Syntax.CreateDiagnostic(FlowTestContextCancellationTokenRule, properties: GetPropertiesBag(testContextMemberNameInScope))); + context.ReportDiagnostic(invocationOperation.Syntax.CreateDiagnostic(FlowTestContextCancellationTokenRule, properties: GetPropertiesBag(testContextMemberNameInScope, testContextState))); } - static ImmutableDictionary GetPropertiesBag(string? testContextMemberNameInScope) + static ImmutableDictionary GetPropertiesBag(string? testContextMemberNameInScope, TestContextState? testContextState) { ImmutableDictionary properties = ImmutableDictionary.Empty; - if (testContextMemberNameInScope is not null) - { - properties = properties.Add(TestContextMemberNamePropertyKey, testContextMemberNameInScope); - } + properties = testContextMemberNameInScope is not null + ? properties.Add(TestContextMemberNamePropertyKey, testContextMemberNameInScope) + : properties.Add(nameof(TestContextState), testContextState.ToString()); return properties; } @@ -151,9 +144,11 @@ private static bool HasOrCouldHaveTestContextInScope( INamedTypeSymbol classCleanupAttributeSymbol, INamedTypeSymbol assemblyCleanupAttributeSymbol, INamedTypeSymbol testMethodAttributeSymbol, - out string? testContextMemberNameInScope) + out string? testContextMemberNameInScope, + [NotNullWhen(true)] out TestContextState? testContextState) { testContextMemberNameInScope = null; + testContextState = null; if (containingSymbol is not IMethodSymbol method) { @@ -164,6 +159,7 @@ private static bool HasOrCouldHaveTestContextInScope( if (method.Parameters.FirstOrDefault(p => testContextSymbol.Equals(p.Type, SymbolEqualityComparer.Default)) is { } testContextParameter) { testContextMemberNameInScope = testContextParameter.Name; + testContextState = TestContextState.InScope; return true; } @@ -178,6 +174,7 @@ private static bool HasOrCouldHaveTestContextInScope( testContextMemberNameInScope = testContextMember.Name.StartsWith('<') && testContextMember.Name.EndsWith(">P", StringComparison.Ordinal) ? testContextMember.Name.Substring(1, testContextMember.Name.Length - 3) : testContextMember.Name; + testContextState = TestContextState.InScope; return true; } @@ -191,11 +188,13 @@ private static bool HasOrCouldHaveTestContextInScope( (classCleanupAttributeSymbol.Equals(attribute.AttributeClass, SymbolEqualityComparer.Default) || assemblyCleanupAttributeSymbol.Equals(attribute.AttributeClass, SymbolEqualityComparer.Default))) { + testContextState = TestContextState.CouldBeInScopeAsParameter; return true; } if (attribute.AttributeClass?.Inherits(testMethodAttributeSymbol) == true) { + testContextState = TestContextState.CouldBeInScopeAsProperty; return true; } } @@ -228,4 +227,11 @@ private static bool IsCompatibleOverloadWithCancellationToken(IMethodSymbol orig IParameterSymbol lastParam = candidateParams[candidateParams.Length - 1]; return SymbolEqualityComparer.Default.Equals(lastParam.Type, cancellationTokenSymbol); } + + internal enum TestContextState + { + InScope, + CouldBeInScopeAsParameter, + CouldBeInScopeAsProperty, + } } diff --git a/test/UnitTests/MSTest.Analyzers.UnitTests/FlowTestContextCancellationTokenAnalyzerTests.cs b/test/UnitTests/MSTest.Analyzers.UnitTests/FlowTestContextCancellationTokenAnalyzerTests.cs index 95022f5cb7..9ba0988c3a 100644 --- a/test/UnitTests/MSTest.Analyzers.UnitTests/FlowTestContextCancellationTokenAnalyzerTests.cs +++ b/test/UnitTests/MSTest.Analyzers.UnitTests/FlowTestContextCancellationTokenAnalyzerTests.cs @@ -296,11 +296,11 @@ public class MyTestClass public static async Task ClassCleanup() { await [|Task.Delay(1000)|]; + await [|Task.Delay(1000)|]; } } """; - // Codefix doesn't yet handle the addition of TestContext parameter. string fixedCode = """ using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Threading; @@ -310,9 +310,10 @@ public static async Task ClassCleanup() public class MyTestClass { [ClassCleanup] - public static async Task ClassCleanup() + public static async Task ClassCleanup(TestContext testContext) { - await Task.Delay(1000, {|CS0103:testContext|}.CancellationTokenSource.Token); + await Task.Delay(1000, testContext.CancellationTokenSource.Token); + await Task.Delay(1000, testContext.CancellationTokenSource.Token); } } """; @@ -343,6 +344,7 @@ public async Task Test1() public async Task Test2(int _) { await [|Task.Delay(1000)|]; + await [|Task.Delay(1000)|]; } } """; @@ -358,7 +360,7 @@ public class MyTestClass [TestMethod] public async Task Test1() { - await Task.Delay(1000, {|CS0103:testContext|}.CancellationTokenSource.Token); + await Task.Delay(1000, TestContext.CancellationTokenSource.Token); } [TestMethod] @@ -366,8 +368,11 @@ public async Task Test1() [DataRow(1)] public async Task Test2(int _) { - await Task.Delay(1000, {|CS0103:testContext|}.CancellationTokenSource.Token); + await Task.Delay(1000, TestContext.CancellationTokenSource.Token); + await Task.Delay(1000, TestContext.CancellationTokenSource.Token); } + + public TestContext TestContext { get; set; } } """; @@ -531,4 +536,206 @@ public async Task MyTestMethod() await VerifyCS.VerifyCodeFixAsync(code, fixedCode); } + + [TestMethod] + public async Task WhenMultipleFixesInSameClassWithoutTestContext_ShouldAddPropertyOnce() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + using System.Threading; + using System.Threading.Tasks; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public async Task Test1() + { + await [|Task.Delay(1000)|]; + await [|Task.Delay(2000)|]; + } + + [TestMethod] + public async Task Test2() + { + await [|Task.Delay(3000)|]; + } + } + """; + + string fixedCode = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + using System.Threading; + using System.Threading.Tasks; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public async Task Test1() + { + await Task.Delay(1000, TestContext.CancellationTokenSource.Token); + await Task.Delay(2000, TestContext.CancellationTokenSource.Token); + } + + [TestMethod] + public async Task Test2() + { + await Task.Delay(3000, TestContext.CancellationTokenSource.Token); + } + + public TestContext TestContext { get; set; } + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, fixedCode); + } + + [TestMethod] + public async Task WhenMultipleFixesInSameClassMultiplePartialsWithoutTestContext_ShouldAddPropertyOnce() + { + var test = new VerifyCS.Test + { + TestState = + { + Sources = + { + """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + using System.Threading; + using System.Threading.Tasks; + + [TestClass] + public partial class MyTestClass + { + [TestMethod] + public async Task Test1() + { + await [|Task.Delay(1000)|]; + await [|Task.Delay(2000)|]; + } + + [TestMethod] + public async Task Test2() + { + await [|Task.Delay(3000)|]; + } + } + """, + """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + using System.Threading; + using System.Threading.Tasks; + + public partial class MyTestClass + { + [TestMethod] + public async Task Test3() + { + await [|Task.Delay(1000)|]; + await [|Task.Delay(2000)|]; + } + + [TestMethod] + public async Task Test4() + { + await [|Task.Delay(3000)|]; + } + } + """, + }, + }, + FixedState = + { + Sources = + { + """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + using System.Threading; + using System.Threading.Tasks; + + [TestClass] + public partial class MyTestClass + { + [TestMethod] + public async Task Test1() + { + await Task.Delay(1000, TestContext.CancellationTokenSource.Token); + await Task.Delay(2000, TestContext.CancellationTokenSource.Token); + } + + [TestMethod] + public async Task Test2() + { + await Task.Delay(3000, TestContext.CancellationTokenSource.Token); + } + + public TestContext TestContext { get; set; } + } + """, + """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + using System.Threading; + using System.Threading.Tasks; + + public partial class MyTestClass + { + [TestMethod] + public async Task Test3() + { + await Task.Delay(1000, TestContext.CancellationTokenSource.Token); + await Task.Delay(2000, TestContext.CancellationTokenSource.Token); + } + + [TestMethod] + public async Task Test4() + { + await Task.Delay(3000, TestContext.CancellationTokenSource.Token); + } + } + """, + }, + }, + }; + + await test.RunAsync(); + } + + [TestMethod] + public async Task WhenInAssemblyCleanupWithoutTestContextParameter_Diagnostic() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + using System.Threading; + using System.Threading.Tasks; + + [TestClass] + public class MyTestClass + { + [AssemblyCleanup] + public static async Task AssemblyCleanup() + { + await [|Task.Delay(1000)|]; + } + } + """; + + string fixedCode = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + using System.Threading; + using System.Threading.Tasks; + + [TestClass] + public class MyTestClass + { + [AssemblyCleanup] + public static async Task AssemblyCleanup(TestContext testContext) + { + await Task.Delay(1000, testContext.CancellationTokenSource.Token); + } + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, fixedCode); + } } From 98cd588ac627b5152f54148e609911cc79cdac14 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Thu, 31 Jul 2025 11:50:30 +0200 Subject: [PATCH 341/541] Cleanup test/Directory.Build.targets (#6262) --- test/Directory.Build.targets | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Directory.Build.targets b/test/Directory.Build.targets index b8089a73ab..83503ee774 100644 --- a/test/Directory.Build.targets +++ b/test/Directory.Build.targets @@ -3,7 +3,7 @@ - + false false $(PlatformTarget) From 428ddf892ffae7e5511389b84e97b1f9b1822dbe Mon Sep 17 00:00:00 2001 From: Copilot <198982749+Copilot@users.noreply.github.com> Date: Thu, 31 Jul 2025 12:43:59 +0200 Subject: [PATCH 342/541] Add field support to DynamicDataAttribute (#6203) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: Evangelink <11340282+Evangelink@users.noreply.github.com> Co-authored-by: Amaury Levé --- .../DynamicDataShouldBeValidAnalyzer.cs | 15 +- .../MSTest.Analyzers/Resources.Designer.cs | 18 +++ src/Analyzers/MSTest.Analyzers/Resources.resx | 6 + .../MSTest.Analyzers/xlf/Resources.cs.xlf | 10 ++ .../MSTest.Analyzers/xlf/Resources.de.xlf | 10 ++ .../MSTest.Analyzers/xlf/Resources.es.xlf | 10 ++ .../MSTest.Analyzers/xlf/Resources.fr.xlf | 10 ++ .../MSTest.Analyzers/xlf/Resources.it.xlf | 10 ++ .../MSTest.Analyzers/xlf/Resources.ja.xlf | 10 ++ .../MSTest.Analyzers/xlf/Resources.ko.xlf | 10 ++ .../MSTest.Analyzers/xlf/Resources.pl.xlf | 10 ++ .../MSTest.Analyzers/xlf/Resources.pt-BR.xlf | 10 ++ .../MSTest.Analyzers/xlf/Resources.ru.xlf | 10 ++ .../MSTest.Analyzers/xlf/Resources.tr.xlf | 10 ++ .../xlf/Resources.zh-Hans.xlf | 10 ++ .../xlf/Resources.zh-Hant.xlf | 10 ++ .../DynamicDataTestMethodArgumentsInfo.cs | 16 +- .../DataSource/DynamicDataAttribute.cs | 29 ++-- .../DataSource/DynamicDataOperations.cs | 44 +++++ .../PublicAPI/PublicAPI.Unshipped.txt | 1 + .../Resources/FrameworkMessages.Designer.cs | 11 +- .../Resources/FrameworkMessages.resx | 5 +- .../Resources/xlf/FrameworkMessages.cs.xlf | 9 +- .../Resources/xlf/FrameworkMessages.de.xlf | 9 +- .../Resources/xlf/FrameworkMessages.es.xlf | 9 +- .../Resources/xlf/FrameworkMessages.fr.xlf | 9 +- .../Resources/xlf/FrameworkMessages.it.xlf | 9 +- .../Resources/xlf/FrameworkMessages.ja.xlf | 9 +- .../Resources/xlf/FrameworkMessages.ko.xlf | 9 +- .../Resources/xlf/FrameworkMessages.pl.xlf | 9 +- .../Resources/xlf/FrameworkMessages.pt-BR.xlf | 9 +- .../Resources/xlf/FrameworkMessages.ru.xlf | 9 +- .../Resources/xlf/FrameworkMessages.tr.xlf | 9 +- .../xlf/FrameworkMessages.zh-Hans.xlf | 9 +- .../xlf/FrameworkMessages.zh-Hant.xlf | 9 +- .../Parameterized tests/DynamicDataTests.cs | 84 +++++----- .../Parameterized tests/DynamicDataTests.cs | 6 +- .../DynamicDataTests.cs | 17 ++ .../DynamicDataShouldBeValidAnalyzerTests.cs | 152 ++++++++++++++++-- .../Attributes/DynamicDataAttributeTests.cs | 95 +++++++++++ 40 files changed, 640 insertions(+), 106 deletions(-) diff --git a/src/Analyzers/MSTest.Analyzers/DynamicDataShouldBeValidAnalyzer.cs b/src/Analyzers/MSTest.Analyzers/DynamicDataShouldBeValidAnalyzer.cs index 2a91cf33eb..3c3d1a3e1e 100644 --- a/src/Analyzers/MSTest.Analyzers/DynamicDataShouldBeValidAnalyzer.cs +++ b/src/Analyzers/MSTest.Analyzers/DynamicDataShouldBeValidAnalyzer.cs @@ -21,6 +21,7 @@ public sealed class DynamicDataShouldBeValidAnalyzer : DiagnosticAnalyzer private const int DynamicDataSourceTypeProperty = 0; private const int DynamicDataSourceTypeMethod = 1; private const int DynamicDataSourceTypeAutoDetect = 2; + private const int DynamicDataSourceTypeField = 3; private static readonly LocalizableResourceString Title = new(nameof(Resources.DynamicDataShouldBeValidTitle), Resources.ResourceManager, typeof(Resources)); private static readonly LocalizableResourceString Description = new(nameof(Resources.DynamicDataShouldBeValidDescription), Resources.ResourceManager, typeof(Resources)); @@ -47,8 +48,11 @@ public sealed class DynamicDataShouldBeValidAnalyzer : DiagnosticAnalyzer internal static readonly DiagnosticDescriptor SourceTypeMethodRule = NotTestMethodRule .WithMessage(new(nameof(Resources.DynamicDataShouldBeValidMessageFormat_SourceTypeMethod), Resources.ResourceManager, typeof(Resources))); + internal static readonly DiagnosticDescriptor SourceTypeFieldRule = NotTestMethodRule + .WithMessage(new(nameof(Resources.DynamicDataShouldBeValidMessageFormat_SourceTypeField), Resources.ResourceManager, typeof(Resources))); + internal static readonly DiagnosticDescriptor SourceTypeNotPropertyOrMethodRule = NotTestMethodRule - .WithMessage(new(nameof(Resources.DynamicDataShouldBeValidMessageFormat_SourceTypeNotPropertyOrMethod), Resources.ResourceManager, typeof(Resources))); + .WithMessage(new(nameof(Resources.DynamicDataShouldBeValidMessageFormat_SourceTypeNotPropertyMethodOrField), Resources.ResourceManager, typeof(Resources))); internal static readonly DiagnosticDescriptor MemberMethodRule = NotTestMethodRule .WithMessage(new(nameof(Resources.DynamicDataShouldBeValidMessageFormat_MemberMethod), Resources.ResourceManager, typeof(Resources))); @@ -256,6 +260,15 @@ private static void AnalyzeDataSource(SymbolAnalysisContext context, AttributeDa return; } + break; + case SymbolKind.Field: + // If the member is a field and the data source type is not set to field or auto detect, report a diagnostic. + if (dataSourceType is not (DynamicDataSourceTypeField or DynamicDataSourceTypeAutoDetect)) + { + context.ReportDiagnostic(attributeSyntax.CreateDiagnostic(SourceTypeFieldRule, declaringType.Name, memberName)); + return; + } + break; default: context.ReportDiagnostic(attributeSyntax.CreateDiagnostic(SourceTypeNotPropertyOrMethodRule, declaringType.Name, memberName)); diff --git a/src/Analyzers/MSTest.Analyzers/Resources.Designer.cs b/src/Analyzers/MSTest.Analyzers/Resources.Designer.cs index e011d0724d..2fbc596ab7 100644 --- a/src/Analyzers/MSTest.Analyzers/Resources.Designer.cs +++ b/src/Analyzers/MSTest.Analyzers/Resources.Designer.cs @@ -591,6 +591,15 @@ internal static string DynamicDataShouldBeValidMessageFormat_SourceTypeMethod { } } + /// + /// Looks up a localized string similar to '[DynamicData]' member '{0}.{1}' is a field so you should use 'DynamicDataSourceType.AutoDetect' or 'DynamicDataSourceType.Field' (auto detect is the default when not specified explicitly, and is recommended). + /// + internal static string DynamicDataShouldBeValidMessageFormat_SourceTypeField { + get { + return ResourceManager.GetString("DynamicDataShouldBeValidMessageFormat_SourceTypeField", resourceCulture); + } + } + /// /// Looks up a localized string similar to '[DynamicData]' member '{0}.{1}' is not a property nor a method. Only properties and methods are supported.. /// @@ -600,6 +609,15 @@ internal static string DynamicDataShouldBeValidMessageFormat_SourceTypeNotProper } } + /// + /// Looks up a localized string similar to '[DynamicData]' member '{0}.{1}' is not a property, method, or field. Only properties, methods, and fields are supported.. + /// + internal static string DynamicDataShouldBeValidMessageFormat_SourceTypeNotPropertyMethodOrField { + get { + return ResourceManager.GetString("DynamicDataShouldBeValidMessageFormat_SourceTypeNotPropertyMethodOrField", resourceCulture); + } + } + /// /// Looks up a localized string similar to '[DynamicData]' member '{0}.{1}' is a property so you should use 'DynamicDataSourceType.AutoDetect' or 'DynamicDataSourceType.Property' (auto detect is the default when not specified explicitly, and is recommended). /// diff --git a/src/Analyzers/MSTest.Analyzers/Resources.resx b/src/Analyzers/MSTest.Analyzers/Resources.resx index b909feb184..79517906d0 100644 --- a/src/Analyzers/MSTest.Analyzers/Resources.resx +++ b/src/Analyzers/MSTest.Analyzers/Resources.resx @@ -510,6 +510,9 @@ The type declaring these methods should also respect the following rules: '[DynamicData]' member '{0}.{1}' is a method so you should use 'DynamicDataSourceType.AutoDetect' or 'DynamicDataSourceType.Method' (auto detect is the default when not specified explicitly, and is recommended) + + '[DynamicData]' member '{0}.{1}' is a field so you should use 'DynamicDataSourceType.AutoDetect' or 'DynamicDataSourceType.Field' (auto detect is the default when not specified explicitly, and is recommended) + '[DynamicData]' display name method '{0}.{1}' signature is invalid @@ -555,6 +558,9 @@ The type declaring these methods should also respect the following rules: '[DynamicData]' member '{0}.{1}' is not a property nor a method. Only properties and methods are supported. + + '[DynamicData]' member '{0}.{1}' is not a property, method, or field. Only properties, methods, and fields are supported. + Use newer methods to assert exceptions diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf index aab0b81907..243e52b284 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf @@ -407,11 +407,21 @@ Typ deklarující tyto metody by měl také respektovat následující pravidla: Položka [DynamicData] by měla být nastavená jenom u testovací metody. + + '[DynamicData]' member '{0}.{1}' is a field so you should use 'DynamicDataSourceType.AutoDetect' or 'DynamicDataSourceType.Field' (auto detect is the default when not specified explicitly, and is recommended) + '[DynamicData]' member '{0}.{1}' is a field so you should use 'DynamicDataSourceType.AutoDetect' or 'DynamicDataSourceType.Field' (auto detect is the default when not specified explicitly, and is recommended) + + '[DynamicData]' member '{0}.{1}' is a method so you should use 'DynamicDataSourceType.AutoDetect' or 'DynamicDataSourceType.Method' (auto detect is the default when not specified explicitly, and is recommended) '[DynamicData]' člen {0}.{1} je metoda, takže byste měli použít DynamicDataSourceType.AutoDetect nebo DynamicDataSourceType.Method (automatické zjišťování je výchozí, pokud není explicitně zadáno, a doporučuje se) + + '[DynamicData]' member '{0}.{1}' is not a property, method, or field. Only properties, methods, and fields are supported. + '[DynamicData]' member '{0}.{1}' is not a property, method, or field. Only properties, methods, and fields are supported. + + '[DynamicData]' member '{0}.{1}' is not a property nor a method. Only properties and methods are supported. '[DynamicData]' člen {0}.{1} není vlastnost ani metoda. Jsou podporovány pouze vlastnosti a metody. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf index 37c51282ed..bd9c5800fb 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf @@ -408,11 +408,21 @@ Der Typ, der diese Methoden deklariert, sollte auch die folgenden Regeln beachte "[DynamicData]" sollte nur für eine Testmethode festgelegt werden. + + '[DynamicData]' member '{0}.{1}' is a field so you should use 'DynamicDataSourceType.AutoDetect' or 'DynamicDataSourceType.Field' (auto detect is the default when not specified explicitly, and is recommended) + '[DynamicData]' member '{0}.{1}' is a field so you should use 'DynamicDataSourceType.AutoDetect' or 'DynamicDataSourceType.Field' (auto detect is the default when not specified explicitly, and is recommended) + + '[DynamicData]' member '{0}.{1}' is a method so you should use 'DynamicDataSourceType.AutoDetect' or 'DynamicDataSourceType.Method' (auto detect is the default when not specified explicitly, and is recommended) '[DynamicData]' Member "{0}.{1}" ist eine Methode, daher sollten Sie "DynamicDataSourceType.AutoDetect" oder "DynamicDataSourceType.Method" verwenden (die automatische Erkennung ist der Standardwert, wenn sie nicht explizit angegeben wird und empfohlen wird). + + '[DynamicData]' member '{0}.{1}' is not a property, method, or field. Only properties, methods, and fields are supported. + '[DynamicData]' member '{0}.{1}' is not a property, method, or field. Only properties, methods, and fields are supported. + + '[DynamicData]' member '{0}.{1}' is not a property nor a method. Only properties and methods are supported. '[DynamicData]' Member "{0}.{1}" ist weder eine Eigenschaft noch eine Methode. Nur Eigenschaften und Methoden werden unterstützt. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf index f860c98191..f128a53eaa 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf @@ -407,11 +407,21 @@ El tipo que declara estos métodos también debe respetar las reglas siguientes: '[DynamicData]' solo debe establecerse en un método de prueba + + '[DynamicData]' member '{0}.{1}' is a field so you should use 'DynamicDataSourceType.AutoDetect' or 'DynamicDataSourceType.Field' (auto detect is the default when not specified explicitly, and is recommended) + '[DynamicData]' member '{0}.{1}' is a field so you should use 'DynamicDataSourceType.AutoDetect' or 'DynamicDataSourceType.Field' (auto detect is the default when not specified explicitly, and is recommended) + + '[DynamicData]' member '{0}.{1}' is a method so you should use 'DynamicDataSourceType.AutoDetect' or 'DynamicDataSourceType.Method' (auto detect is the default when not specified explicitly, and is recommended) '[DynamicData]' miembro '{0}.{1}' es un método, por lo que debe usar 'DynamicDataSourceType.AutoDetect' o 'DynamicDataSourceType.Method' (la detección automática es el valor predeterminado cuando no se especifica explícitamente y se recomienda) + + '[DynamicData]' member '{0}.{1}' is not a property, method, or field. Only properties, methods, and fields are supported. + '[DynamicData]' member '{0}.{1}' is not a property, method, or field. Only properties, methods, and fields are supported. + + '[DynamicData]' member '{0}.{1}' is not a property nor a method. Only properties and methods are supported. '[DynamicData]' miembro '{0}.{1}' no es una propiedad ni un método. Solo se admiten propiedades y métodos. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf index 723d8019fc..ac3e3d031f 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf @@ -407,11 +407,21 @@ Le type doit être une classe '[DynamicData]' ne doit être défini que sur une méthode de test + + '[DynamicData]' member '{0}.{1}' is a field so you should use 'DynamicDataSourceType.AutoDetect' or 'DynamicDataSourceType.Field' (auto detect is the default when not specified explicitly, and is recommended) + '[DynamicData]' member '{0}.{1}' is a field so you should use 'DynamicDataSourceType.AutoDetect' or 'DynamicDataSourceType.Field' (auto detect is the default when not specified explicitly, and is recommended) + + '[DynamicData]' member '{0}.{1}' is a method so you should use 'DynamicDataSourceType.AutoDetect' or 'DynamicDataSourceType.Method' (auto detect is the default when not specified explicitly, and is recommended) '[DynamicData]' membre ' {0}.{1}' est une méthode, vous devez donc utiliser 'DynamicDataSourceType.AutoDetect' ou 'DynamicDataSourceType.Method' (la détection automatique est la valeur par défaut quand elle n’est pas spécifiée explicitement et est recommandée) + + '[DynamicData]' member '{0}.{1}' is not a property, method, or field. Only properties, methods, and fields are supported. + '[DynamicData]' member '{0}.{1}' is not a property, method, or field. Only properties, methods, and fields are supported. + + '[DynamicData]' member '{0}.{1}' is not a property nor a method. Only properties and methods are supported. '[DynamicData]' membre '{0}.{1}' n’est ni une propriété ni une méthode. Seules les propriétés et les méthodes sont prises en charge. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf index 59e6bb89da..585b39973a 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf @@ -407,11 +407,21 @@ Anche il tipo che dichiara questi metodi deve rispettare le regole seguenti: '[DynamicData]' deve essere impostato solo su un metodo di test + + '[DynamicData]' member '{0}.{1}' is a field so you should use 'DynamicDataSourceType.AutoDetect' or 'DynamicDataSourceType.Field' (auto detect is the default when not specified explicitly, and is recommended) + '[DynamicData]' member '{0}.{1}' is a field so you should use 'DynamicDataSourceType.AutoDetect' or 'DynamicDataSourceType.Field' (auto detect is the default when not specified explicitly, and is recommended) + + '[DynamicData]' member '{0}.{1}' is a method so you should use 'DynamicDataSourceType.AutoDetect' or 'DynamicDataSourceType.Method' (auto detect is the default when not specified explicitly, and is recommended) '[DynamicData]' membro '{0}.{1}' è un metodo, quindi è consigliabile usare 'DynamicDataSourceType.AutoDetect' o 'DynamicDataSourceType.Method'. Il rilevamento automatico è l'impostazione predefinita quando non è specificata in modo esplicito ed è consigliabile + + '[DynamicData]' member '{0}.{1}' is not a property, method, or field. Only properties, methods, and fields are supported. + '[DynamicData]' member '{0}.{1}' is not a property, method, or field. Only properties, methods, and fields are supported. + + '[DynamicData]' member '{0}.{1}' is not a property nor a method. Only properties and methods are supported. '[DynamicData]' membro '{0}.{1}' non è una proprietà né un metodo. Sono supportati solo metodi e proprietà. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf index 6d4efeccfe..ae7471f9e6 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf @@ -407,11 +407,21 @@ The type declaring these methods should also respect the following rules: '[DynamicData]' はテスト メソッドでのみ設定する必要があります + + '[DynamicData]' member '{0}.{1}' is a field so you should use 'DynamicDataSourceType.AutoDetect' or 'DynamicDataSourceType.Field' (auto detect is the default when not specified explicitly, and is recommended) + '[DynamicData]' member '{0}.{1}' is a field so you should use 'DynamicDataSourceType.AutoDetect' or 'DynamicDataSourceType.Field' (auto detect is the default when not specified explicitly, and is recommended) + + '[DynamicData]' member '{0}.{1}' is a method so you should use 'DynamicDataSourceType.AutoDetect' or 'DynamicDataSourceType.Method' (auto detect is the default when not specified explicitly, and is recommended) '[DynamicData]' メンバー '{0}.{1}' はメソッドであるため、'DynamicDataSourceType.AutoDetect' または 'DynamicDataSourceType.Method' を使用する必要があります (自動検出は明示的に指定されていない場合の既定値であり、推奨されます) + + '[DynamicData]' member '{0}.{1}' is not a property, method, or field. Only properties, methods, and fields are supported. + '[DynamicData]' member '{0}.{1}' is not a property, method, or field. Only properties, methods, and fields are supported. + + '[DynamicData]' member '{0}.{1}' is not a property nor a method. Only properties and methods are supported. メンバー '{0}.{1}' '[DynamicData]' プロパティでもメソッドでもありません。プロパティとメソッドのみがサポートされています。 diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf index 59a35da614..9d22ce3a8d 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf @@ -407,11 +407,21 @@ The type declaring these methods should also respect the following rules: '[DynamicData]'는 테스트 메서드에서만 설정해야 합니다. + + '[DynamicData]' member '{0}.{1}' is a field so you should use 'DynamicDataSourceType.AutoDetect' or 'DynamicDataSourceType.Field' (auto detect is the default when not specified explicitly, and is recommended) + '[DynamicData]' member '{0}.{1}' is a field so you should use 'DynamicDataSourceType.AutoDetect' or 'DynamicDataSourceType.Field' (auto detect is the default when not specified explicitly, and is recommended) + + '[DynamicData]' member '{0}.{1}' is a method so you should use 'DynamicDataSourceType.AutoDetect' or 'DynamicDataSourceType.Method' (auto detect is the default when not specified explicitly, and is recommended) '[DynamicData]' 멤버 '{0}.{1}'은(는) 'DynamicDataSourceType.AutoDetect' 또는 'DynamicDataSourceType.Method'를 사용해야 하는 메서드입니다.(명시적으로 지정하지 않은 경우 자동 검색이 기본값이며 권장) + + '[DynamicData]' member '{0}.{1}' is not a property, method, or field. Only properties, methods, and fields are supported. + '[DynamicData]' member '{0}.{1}' is not a property, method, or field. Only properties, methods, and fields are supported. + + '[DynamicData]' member '{0}.{1}' is not a property nor a method. Only properties and methods are supported. '[DynamicData]' 멤버 '{0}.{1}'은(는) 속성이나 메서드가 아닙니다. 속성 및 메서드만 지원됩니다. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf index 667dc0e6ce..3f5492237d 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf @@ -407,11 +407,21 @@ Typ deklarujący te metody powinien również przestrzegać następujących regu „[DynamicData]” należy ustawić tylko dla metody testowej + + '[DynamicData]' member '{0}.{1}' is a field so you should use 'DynamicDataSourceType.AutoDetect' or 'DynamicDataSourceType.Field' (auto detect is the default when not specified explicitly, and is recommended) + '[DynamicData]' member '{0}.{1}' is a field so you should use 'DynamicDataSourceType.AutoDetect' or 'DynamicDataSourceType.Field' (auto detect is the default when not specified explicitly, and is recommended) + + '[DynamicData]' member '{0}.{1}' is a method so you should use 'DynamicDataSourceType.AutoDetect' or 'DynamicDataSourceType.Method' (auto detect is the default when not specified explicitly, and is recommended) '[DynamicData]' składowej "{0}.{1}" jest metodą, dlatego należy użyć elementu "DynamicDataSourceType.AutoDetect" lub "DynamicDataSourceType.Method" (autowykrywanie jest domyślne, gdy nie zostało jawnie określone i jest zalecane) + + '[DynamicData]' member '{0}.{1}' is not a property, method, or field. Only properties, methods, and fields are supported. + '[DynamicData]' member '{0}.{1}' is not a property, method, or field. Only properties, methods, and fields are supported. + + '[DynamicData]' member '{0}.{1}' is not a property nor a method. Only properties and methods are supported. składowa '[DynamicData]' "{0}.{1}" nie jest właściwością ani metodą. Obsługiwane są tylko właściwości i metody. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf index 82748b03c4..67886effc7 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf @@ -407,11 +407,21 @@ O tipo que declara esses métodos também deve respeitar as seguintes regras: "[DynamicData]" só deve ser definido em um método de teste + + '[DynamicData]' member '{0}.{1}' is a field so you should use 'DynamicDataSourceType.AutoDetect' or 'DynamicDataSourceType.Field' (auto detect is the default when not specified explicitly, and is recommended) + '[DynamicData]' member '{0}.{1}' is a field so you should use 'DynamicDataSourceType.AutoDetect' or 'DynamicDataSourceType.Field' (auto detect is the default when not specified explicitly, and is recommended) + + '[DynamicData]' member '{0}.{1}' is a method so you should use 'DynamicDataSourceType.AutoDetect' or 'DynamicDataSourceType.Method' (auto detect is the default when not specified explicitly, and is recommended) '[DynamicData]' membro '{0}.{1}' é um método, portanto, você deve usar 'DynamicDataSourceType.AutoDetect' ou 'DynamicDataSourceType.Method' (detectar automaticamente é o padrão quando não especificado explicitamente e é recomendado) + + '[DynamicData]' member '{0}.{1}' is not a property, method, or field. Only properties, methods, and fields are supported. + '[DynamicData]' member '{0}.{1}' is not a property, method, or field. Only properties, methods, and fields are supported. + + '[DynamicData]' member '{0}.{1}' is not a property nor a method. Only properties and methods are supported. '[DynamicData]' membro '{0}.{1}' não é uma propriedade nem um método. Somente propriedades e métodos têm suporte. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf index dde5f7cda7..3f3354dd43 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf @@ -413,11 +413,21 @@ The type declaring these methods should also respect the following rules: "[DynamicData]" следует задавать только для метода теста + + '[DynamicData]' member '{0}.{1}' is a field so you should use 'DynamicDataSourceType.AutoDetect' or 'DynamicDataSourceType.Field' (auto detect is the default when not specified explicitly, and is recommended) + '[DynamicData]' member '{0}.{1}' is a field so you should use 'DynamicDataSourceType.AutoDetect' or 'DynamicDataSourceType.Field' (auto detect is the default when not specified explicitly, and is recommended) + + '[DynamicData]' member '{0}.{1}' is a method so you should use 'DynamicDataSourceType.AutoDetect' or 'DynamicDataSourceType.Method' (auto detect is the default when not specified explicitly, and is recommended) '[DynamicData]' "{0}.{1}" является методом, поэтому следует использовать "DynamicDataSourceType.AutoDetect" или "DynamicDataSourceType.Method" (автообнаружение используется по умолчанию, если не указано явно, и рекомендуется) + + '[DynamicData]' member '{0}.{1}' is not a property, method, or field. Only properties, methods, and fields are supported. + '[DynamicData]' member '{0}.{1}' is not a property, method, or field. Only properties, methods, and fields are supported. + + '[DynamicData]' member '{0}.{1}' is not a property nor a method. Only properties and methods are supported. '[DynamicData]' "{0}.{1}" не является свойством или методом. Поддерживаются только свойства и методы. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf index 85dcb105c5..f3a853182b 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf @@ -407,11 +407,21 @@ Bu yöntemleri bildiren tipin ayrıca aşağıdaki kurallara uyması gerekir: '[DynamicData]' yalnızca bir test yönteminde ayarlanmalıdır + + '[DynamicData]' member '{0}.{1}' is a field so you should use 'DynamicDataSourceType.AutoDetect' or 'DynamicDataSourceType.Field' (auto detect is the default when not specified explicitly, and is recommended) + '[DynamicData]' member '{0}.{1}' is a field so you should use 'DynamicDataSourceType.AutoDetect' or 'DynamicDataSourceType.Field' (auto detect is the default when not specified explicitly, and is recommended) + + '[DynamicData]' member '{0}.{1}' is a method so you should use 'DynamicDataSourceType.AutoDetect' or 'DynamicDataSourceType.Method' (auto detect is the default when not specified explicitly, and is recommended) '[DynamicData]' üyesi '{0}.{1}' bir metot olduğundan 'DynamicDataSourceType.AutoDetect' veya 'DynamicDataSourceType.Method' kullanmalısınız (otomatik algılama açıkça belirtilmediğinden varsayılandır ve önerilir) + + '[DynamicData]' member '{0}.{1}' is not a property, method, or field. Only properties, methods, and fields are supported. + '[DynamicData]' member '{0}.{1}' is not a property, method, or field. Only properties, methods, and fields are supported. + + '[DynamicData]' member '{0}.{1}' is not a property nor a method. Only properties and methods are supported. '[DynamicData]' '{0}.{1}' üyesi bir özellik veya yöntem değil. Yalnızca özellikler ve yöntemler desteklenir. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf index 9301ffbaf1..45f0e177b3 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf @@ -407,11 +407,21 @@ The type declaring these methods should also respect the following rules: 应仅对测试方法设置 "[DynamicData]" + + '[DynamicData]' member '{0}.{1}' is a field so you should use 'DynamicDataSourceType.AutoDetect' or 'DynamicDataSourceType.Field' (auto detect is the default when not specified explicitly, and is recommended) + '[DynamicData]' member '{0}.{1}' is a field so you should use 'DynamicDataSourceType.AutoDetect' or 'DynamicDataSourceType.Field' (auto detect is the default when not specified explicitly, and is recommended) + + '[DynamicData]' member '{0}.{1}' is a method so you should use 'DynamicDataSourceType.AutoDetect' or 'DynamicDataSourceType.Method' (auto detect is the default when not specified explicitly, and is recommended) '[DynamicData]' 成员 “{0}.{1}” 是一个方法,因此应使用 “DynamicDataSourceType.AutoDetect” 或 “DynamicDataSourceType.Method”,(未显式指定时,自动检测为默认值,建议) + + '[DynamicData]' member '{0}.{1}' is not a property, method, or field. Only properties, methods, and fields are supported. + '[DynamicData]' member '{0}.{1}' is not a property, method, or field. Only properties, methods, and fields are supported. + + '[DynamicData]' member '{0}.{1}' is not a property nor a method. Only properties and methods are supported. '[DynamicData]' 成员 “{0}.{1}” 既不是属性也不是方法。仅支持属性和方法。 diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf index 6d927ef60c..7136911d17 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf @@ -407,11 +407,21 @@ The type declaring these methods should also respect the following rules: [DynamicData]' 只能在測試方法上設定 + + '[DynamicData]' member '{0}.{1}' is a field so you should use 'DynamicDataSourceType.AutoDetect' or 'DynamicDataSourceType.Field' (auto detect is the default when not specified explicitly, and is recommended) + '[DynamicData]' member '{0}.{1}' is a field so you should use 'DynamicDataSourceType.AutoDetect' or 'DynamicDataSourceType.Field' (auto detect is the default when not specified explicitly, and is recommended) + + '[DynamicData]' member '{0}.{1}' is a method so you should use 'DynamicDataSourceType.AutoDetect' or 'DynamicDataSourceType.Method' (auto detect is the default when not specified explicitly, and is recommended) '[DynamicData]' 成員 '{0}.{1}' 是方法,因此您應該使用 'DynamicDataSourceType.AutoDetect' 或 'DynamicDataSourceType.Method' (未明確指定時,自動偵測是預設值,建議) + + '[DynamicData]' member '{0}.{1}' is not a property, method, or field. Only properties, methods, and fields are supported. + '[DynamicData]' member '{0}.{1}' is not a property, method, or field. Only properties, methods, and fields are supported. + + '[DynamicData]' member '{0}.{1}' is not a property nor a method. Only properties and methods are supported. '[DynamicData]' 成員 『{0}.{1}』 不是屬性也不是方法。只支援屬性和方法。 diff --git a/src/Analyzers/MSTest.SourceGeneration/ObjectModels/DynamicDataTestMethodArgumentsInfo.cs b/src/Analyzers/MSTest.SourceGeneration/ObjectModels/DynamicDataTestMethodArgumentsInfo.cs index 1f520350ae..0d08f672a8 100644 --- a/src/Analyzers/MSTest.SourceGeneration/ObjectModels/DynamicDataTestMethodArgumentsInfo.cs +++ b/src/Analyzers/MSTest.SourceGeneration/ObjectModels/DynamicDataTestMethodArgumentsInfo.cs @@ -19,6 +19,7 @@ internal sealed class DynamicDataTestMethodArgumentsInfo : ITestMethodArgumentsI private const int DynamicDataSourceTypeProperty = 0; private const int DynamicDataSourceTypeMethod = 1; private const int DynamicDataSourceTypeAutoDetect = 2; + private const int DynamicDataSourceTypeField = 3; internal const string TestArgumentsEntryTypeName = "MSTF::InternalUnsafeTestArgumentsEntry"; internal const string DynamicDataNameProviderTypeName = "MSTF::DynamicDataNameProvider"; @@ -94,6 +95,7 @@ private DynamicDataTestMethodArgumentsInfo(string memberName, string memberFullT { DynamicDataSourceTypeProperty => SymbolKind.Property, DynamicDataSourceTypeMethod => SymbolKind.Method, + DynamicDataSourceTypeField => SymbolKind.Field, DynamicDataSourceTypeAutoDetect => null, _ => throw ApplicationStateGuard.Unreachable(), }; @@ -102,33 +104,31 @@ private DynamicDataTestMethodArgumentsInfo(string memberName, string memberFullT private static DynamicDataTestMethodArgumentsInfo? TryBuildFromDynamicData(INamedTypeSymbol memberTypeSymbol, string memberName, SymbolKind? symbolKind, WellKnownTypes wellKnownTypes, IMethodSymbol testMethodSymbol) { - // Dynamic data only support Properties and Methods, but not fields. + // Dynamic data supports Properties, Methods, and Fields. // null is also possible and means "AutoDetect" - if (symbolKind is not (SymbolKind.Property or SymbolKind.Method or null)) + if (symbolKind is not (SymbolKind.Property or SymbolKind.Method or SymbolKind.Field or null)) { return null; } ISymbol? firstMatchingMember = memberTypeSymbol.GetAllMembers(memberName) .SelectMany(x => x) - // DynamicData does not have option to not specify the kind of member we are looking for at the moment. - // But the code below can easily handle searching for all kinds of supported members, and only - // take the kind into consideration when needed. If a ctor is added to DynamicData, or if we can tell if - // user specified the value explicitly or if it was taken from the default value, then `symbolKind` can be made nullable - // and only filtered below. + // DynamicData supports properties, methods, and fields. // .Where(s => s.IsStatic && (s.Kind is SymbolKind.Field or SymbolKind.Property or SymbolKind.Method)) // .Where(s => symbolKind == null || s.Kind == symbolKind) - .Where(s => s.IsStatic && (s.Kind == symbolKind || (symbolKind is null && s.Kind is SymbolKind.Property or SymbolKind.Method))) + .Where(s => s.IsStatic && (s.Kind == symbolKind || (symbolKind is null && s.Kind is SymbolKind.Property or SymbolKind.Method or SymbolKind.Field))) .Select(s => s switch { IPropertySymbol propertySymbol => (ISymbol)propertySymbol, IMethodSymbol methodSymbol => methodSymbol, + IFieldSymbol fieldSymbol => fieldSymbol, _ => throw ApplicationStateGuard.Unreachable(), }) .OrderBy(tuple => tuple.Kind switch { SymbolKind.Property => 1, SymbolKind.Method => 2, + SymbolKind.Field => 3, _ => throw ApplicationStateGuard.Unreachable(), }) .FirstOrDefault(); diff --git a/src/TestFramework/TestFramework/Attributes/DataSource/DynamicDataAttribute.cs b/src/TestFramework/TestFramework/Attributes/DataSource/DynamicDataAttribute.cs index 6768a2195b..a05d089798 100644 --- a/src/TestFramework/TestFramework/Attributes/DataSource/DynamicDataAttribute.cs +++ b/src/TestFramework/TestFramework/Attributes/DataSource/DynamicDataAttribute.cs @@ -8,7 +8,7 @@ namespace Microsoft.VisualStudio.TestTools.UnitTesting; /// -/// Enum to specify whether the data is stored as property or in method. +/// Enum to specify whether the data is stored as property, in method, or in field. /// public enum DynamicDataSourceType { @@ -26,6 +26,11 @@ public enum DynamicDataSourceType /// The data source type is auto-detected. /// AutoDetect = 2, + + /// + /// Data is declared as field. + /// + Field = 3, } /// @@ -43,10 +48,10 @@ public sealed class DynamicDataAttribute : Attribute, ITestDataSource, ITestData /// Initializes a new instance of the class. /// /// - /// The name of method or property having test data. + /// The name of method, property, or field having test data. /// /// - /// Specifies whether the data is stored as property or in method. + /// Specifies whether the data is stored as property, in method, or in field. /// [EditorBrowsable(EditorBrowsableState.Never)] public DynamicDataAttribute(string dynamicDataSourceName, DynamicDataSourceType dynamicDataSourceType) @@ -59,7 +64,7 @@ public DynamicDataAttribute(string dynamicDataSourceName, DynamicDataSourceType /// Initializes a new instance of the class. /// /// - /// The name of method or property having test data. + /// The name of method, property, or field having test data. /// public DynamicDataAttribute(string dynamicDataSourceName) { @@ -71,7 +76,7 @@ public DynamicDataAttribute(string dynamicDataSourceName) /// Initializes a new instance of the class. /// /// - /// The name of method or property having test data. + /// The name of method, property, or field having test data. /// /// /// Arguments to be passed to method referred to by . @@ -88,14 +93,14 @@ public DynamicDataAttribute(string dynamicDataSourceName, params object?[] dynam /// from test method's class. /// /// - /// The name of method or property having test data. + /// The name of method, property, or field having test data. /// /// - /// The declaring type of property or method having data. Useful in cases when declaring type is present in a class different from + /// The declaring type of property, method, or field having data. Useful in cases when declaring type is present in a class different from /// test method's class. If null, declaring type defaults to test method's class type. /// /// - /// Specifies whether the data is stored as property or in method. + /// Specifies whether the data is stored as property, in method, or in field. /// [EditorBrowsable(EditorBrowsableState.Never)] public DynamicDataAttribute(string dynamicDataSourceName, Type dynamicDataDeclaringType, DynamicDataSourceType dynamicDataSourceType) @@ -106,10 +111,10 @@ public DynamicDataAttribute(string dynamicDataSourceName, Type dynamicDataDeclar /// from test method's class. /// /// - /// The name of method or property having test data. + /// The name of method, property, or field having test data. /// /// - /// The declaring type of property or method having data. Useful in cases when declaring type is present in a class different from + /// The declaring type of property, method, or field having data. Useful in cases when declaring type is present in a class different from /// test method's class. If null, declaring type defaults to test method's class type. /// public DynamicDataAttribute(string dynamicDataSourceName, Type dynamicDataDeclaringType) @@ -120,10 +125,10 @@ public DynamicDataAttribute(string dynamicDataSourceName, Type dynamicDataDeclar /// from test method's class. /// /// - /// The name of method or property having test data. + /// The name of method, property, or field having test data. /// /// - /// The declaring type of property or method having data. Useful in cases when declaring type is present in a class different from + /// The declaring type of property, method, or field having data. Useful in cases when declaring type is present in a class different from /// test method's class. If null, declaring type defaults to test method's class type. /// /// diff --git a/src/TestFramework/TestFramework/Attributes/DataSource/DynamicDataOperations.cs b/src/TestFramework/TestFramework/Attributes/DataSource/DynamicDataOperations.cs index 8a654af412..b3990377c7 100644 --- a/src/TestFramework/TestFramework/Attributes/DataSource/DynamicDataOperations.cs +++ b/src/TestFramework/TestFramework/Attributes/DataSource/DynamicDataOperations.cs @@ -27,6 +27,10 @@ public static IEnumerable GetData(Type? dynamicDataDeclaringType, Dyna { obj = GetDataFromMethod(dynamicDataMethodInfo, dynamicDataSourceArguments); } + else if (GetFieldConsideringInheritance(dynamicDataDeclaringType, dynamicDataSourceName) is { } dynamicDataFieldInfo) + { + obj = GetDataFromField(dynamicDataFieldInfo); + } else { throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, FrameworkMessages.DynamicDataSourceShouldExistAndBeValid, dynamicDataSourceName, dynamicDataDeclaringType.FullName)); @@ -47,6 +51,13 @@ public static IEnumerable GetData(Type? dynamicDataDeclaringType, Dyna obj = GetDataFromMethod(method, dynamicDataSourceArguments); break; + + case DynamicDataSourceType.Field: + FieldInfo field = GetFieldConsideringInheritance(dynamicDataDeclaringType, dynamicDataSourceName) + ?? throw new ArgumentNullException($"{DynamicDataSourceType.Field} {dynamicDataSourceName}"); + + obj = GetDataFromField(field); + break; } if (obj == null) @@ -101,6 +112,21 @@ public static IEnumerable GetData(Type? dynamicDataDeclaringType, Dyna return method.Invoke(null, arguments.Length == 0 ? null : arguments); } + private static object? GetDataFromField(FieldInfo field) + { + if (!field.IsStatic) + { + throw new NotSupportedException( + string.Format( + CultureInfo.InvariantCulture, + FrameworkMessages.DynamicDataInvalidFieldLayout, + field.DeclaringType?.FullName is { } typeFullName ? $"{typeFullName}.{field.Name}" : field.Name)); + } + + // Note: the field is static. + return field.GetValue(null); + } + private static object? GetDataFromProperty(PropertyInfo property) { if (property.GetGetMethod(true) is not { IsStatic: true }) @@ -140,6 +166,24 @@ private static bool TryGetData(object dataSource, [NotNullWhen(true)] out IEnume return false; } + private static FieldInfo? GetFieldConsideringInheritance(Type type, string fieldName) + { + // NOTE: Don't use GetRuntimeField. It considers inheritance only for instance fields. + Type? currentType = type; + while (currentType is not null) + { + FieldInfo? field = currentType.GetField(fieldName, DeclaredOnlyLookup); + if (field is not null) + { + return field; + } + + currentType = currentType.BaseType; + } + + return null; + } + private static PropertyInfo? GetPropertyConsideringInheritance(Type type, string propertyName) { // NOTE: Don't use GetRuntimeProperty. It considers inheritance only for instance properties. diff --git a/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Unshipped.txt b/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Unshipped.txt index 7dc5c58110..880fc26f4b 100644 --- a/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Unshipped.txt +++ b/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Unshipped.txt @@ -1 +1,2 @@ #nullable enable +Microsoft.VisualStudio.TestTools.UnitTesting.DynamicDataSourceType.Field = 3 -> Microsoft.VisualStudio.TestTools.UnitTesting.DynamicDataSourceType diff --git a/src/TestFramework/TestFramework/Resources/FrameworkMessages.Designer.cs b/src/TestFramework/TestFramework/Resources/FrameworkMessages.Designer.cs index 6f6bd8b572..698a07f64f 100644 --- a/src/TestFramework/TestFramework/Resources/FrameworkMessages.Designer.cs +++ b/src/TestFramework/TestFramework/Resources/FrameworkMessages.Designer.cs @@ -421,7 +421,16 @@ internal static string DynamicDataInvalidPropertyLayout { } /// - /// Looks up a localized string similar to The dynamic data source '{0}' in type '{1}' should exist and be a property or a method.. + /// Looks up a localized string similar to Dynamic data field '{0}' should be static.. + /// + internal static string DynamicDataInvalidFieldLayout { + get { + return ResourceManager.GetString("DynamicDataInvalidFieldLayout", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The dynamic data source '{0}' in type '{1}' should exist and be a property, a method, or a field.. /// internal static string DynamicDataSourceShouldExistAndBeValid { get { diff --git a/src/TestFramework/TestFramework/Resources/FrameworkMessages.resx b/src/TestFramework/TestFramework/Resources/FrameworkMessages.resx index 2fbf6e32e0..d52e623343 100644 --- a/src/TestFramework/TestFramework/Resources/FrameworkMessages.resx +++ b/src/TestFramework/TestFramework/Resources/FrameworkMessages.resx @@ -274,8 +274,11 @@ Actual: {2} Dynamic data property '{0}' should be static and have a getter. + + Dynamic data field '{0}' should be static. + - The dynamic data source '{0}' in type '{1}' should exist and be a property or a method. + The dynamic data source '{0}' in type '{1}' should exist and be a property, a method, or a field. Expected collection of size {1}. Actual: {2}. {0} diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.cs.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.cs.xlf index c5e59f0e0c..5f4461b69a 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.cs.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.cs.xlf @@ -127,6 +127,11 @@ Řetězec „{0}“ začíná řetězcem „{1}“. {2} + + Dynamic data field '{0}' should be static. + Dynamic data field '{0}' should be static. + + Dynamic data method '{0}' should be static, non-generic, and cannot have 'params' parameter. Dynamická datová metoda {0} by měla být statická a neobecná a nemůže mít parametr params. @@ -138,8 +143,8 @@ - The dynamic data source '{0}' in type '{1}' should exist and be a property or a method. - Dynamický zdroj dat '{0}' v typu '{1}' by měl existovat a být vlastností nebo metodou. + The dynamic data source '{0}' in type '{1}' should exist and be a property, a method, or a field. + Dynamický zdroj dat '{0}' v typu '{1}' by měl existovat a být vlastností nebo metodou. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.de.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.de.xlf index 9a44a844f2..97c5d578c9 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.de.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.de.xlf @@ -127,6 +127,11 @@ Die Zeichenfolge „{0}“ beginnt mit der Zeichenfolge „{1}“. {2} + + Dynamic data field '{0}' should be static. + Dynamic data field '{0}' should be static. + + Dynamic data method '{0}' should be static, non-generic, and cannot have 'params' parameter. Die dynamische Datenmethode „{0}“ muss statisch, nicht generisch sein und darf keinen Parameter „params“ enthalten. @@ -138,8 +143,8 @@ - The dynamic data source '{0}' in type '{1}' should exist and be a property or a method. - Die dynamische Datenquelle '{0}' im Typ '{1}' muss vorhanden sein und eine Eigenschaft oder Methode sein. + The dynamic data source '{0}' in type '{1}' should exist and be a property, a method, or a field. + Die dynamische Datenquelle '{0}' im Typ '{1}' muss vorhanden sein und eine Eigenschaft oder Methode sein. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.es.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.es.xlf index 9a157e3763..26a2384533 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.es.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.es.xlf @@ -127,6 +127,11 @@ La cadena "{0}" comienza con la cadena "{1}". {2} + + Dynamic data field '{0}' should be static. + Dynamic data field '{0}' should be static. + + Dynamic data method '{0}' should be static, non-generic, and cannot have 'params' parameter. El método de datos dinámicos '{0}' debe ser estático, no genérico y no puede tener un parámetro 'params'. @@ -138,8 +143,8 @@ - The dynamic data source '{0}' in type '{1}' should exist and be a property or a method. - El origen de datos dinámico '{0}' en el tipo '{1}' debe existir y ser una propiedad o un método. + The dynamic data source '{0}' in type '{1}' should exist and be a property, a method, or a field. + El origen de datos dinámico '{0}' en el tipo '{1}' debe existir y ser una propiedad o un método. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.fr.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.fr.xlf index 29f3fb510f..8f9232c016 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.fr.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.fr.xlf @@ -127,6 +127,11 @@ La chaîne '{0}' commence par la chaîne '{1}'. {2} + + Dynamic data field '{0}' should be static. + Dynamic data field '{0}' should be static. + + Dynamic data method '{0}' should be static, non-generic, and cannot have 'params' parameter. La méthode de données dynamiques « {0} » doit être statique, non générique et ne peut pas avoir le paramètre « params ». @@ -138,8 +143,8 @@ - The dynamic data source '{0}' in type '{1}' should exist and be a property or a method. - La source de données dynamique '{0}' dans le type '{1}' doit exister et être une propriété ou une méthode. + The dynamic data source '{0}' in type '{1}' should exist and be a property, a method, or a field. + La source de données dynamique '{0}' dans le type '{1}' doit exister et être une propriété ou une méthode. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.it.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.it.xlf index bf538f0172..a18ec4d81c 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.it.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.it.xlf @@ -127,6 +127,11 @@ La stringa '{0}' inizia con la stringa '{1}'. {2} + + Dynamic data field '{0}' should be static. + Dynamic data field '{0}' should be static. + + Dynamic data method '{0}' should be static, non-generic, and cannot have 'params' parameter. Il metodo dei dati dinamici '{0}' deve essere statico, non generico e non può includere un parametro 'params'. @@ -138,8 +143,8 @@ - The dynamic data source '{0}' in type '{1}' should exist and be a property or a method. - L'origine dati dinamica '{0}' nel tipo '{1}' deve esistere ed essere una proprietà o un metodo. + The dynamic data source '{0}' in type '{1}' should exist and be a property, a method, or a field. + L'origine dati dinamica '{0}' nel tipo '{1}' deve esistere ed essere una proprietà o un metodo. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ja.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ja.xlf index b23c0df7bb..dcf06007fa 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ja.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ja.xlf @@ -127,6 +127,11 @@ 文字列 '{0}' は文字列 '{1}' で始まります。 {2} + + Dynamic data field '{0}' should be static. + Dynamic data field '{0}' should be static. + + Dynamic data method '{0}' should be static, non-generic, and cannot have 'params' parameter. 動的データ メソッド '{0}' は、静的で、非ジェネリックである必要があり、'params' パラメーターを持つことはできません。 @@ -138,8 +143,8 @@ - The dynamic data source '{0}' in type '{1}' should exist and be a property or a method. - 型 '{1}' の動的データ ソース '{0}' は、プロパティまたはメソッドである必要があります。 + The dynamic data source '{0}' in type '{1}' should exist and be a property, a method, or a field. + 型 '{1}' の動的データ ソース '{0}' は、プロパティまたはメソッドである必要があります。 diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ko.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ko.xlf index 19b6b3453e..99e50cbf7a 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ko.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ko.xlf @@ -127,6 +127,11 @@ 문자열 '{0}'은 문자열 '{1}'(으)로 시작합니다. {2} + + Dynamic data field '{0}' should be static. + Dynamic data field '{0}' should be static. + + Dynamic data method '{0}' should be static, non-generic, and cannot have 'params' parameter. 동적 데이터 메서드 '{0}'은(는) 정적이고 제네릭이 아니어야 하며 'params' 매개 변수를 사용할 수 없습니다. @@ -138,8 +143,8 @@ - The dynamic data source '{0}' in type '{1}' should exist and be a property or a method. - '{1}' 형식의 동적 데이터 원본 '{0}' 존재하며 속성 또는 메서드여야 합니다. + The dynamic data source '{0}' in type '{1}' should exist and be a property, a method, or a field. + '{1}' 형식의 동적 데이터 원본 '{0}' 존재하며 속성 또는 메서드여야 합니다. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pl.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pl.xlf index 3482be7955..23ce865435 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pl.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pl.xlf @@ -127,6 +127,11 @@ Ciąg „{0}” rozpoczyna się od ciągu „{1}”. {2} + + Dynamic data field '{0}' should be static. + Dynamic data field '{0}' should be static. + + Dynamic data method '{0}' should be static, non-generic, and cannot have 'params' parameter. Metoda danych dynamicznych „{0}” powinna być statyczna, niestandardowa i nie może mieć parametru „params”. @@ -138,8 +143,8 @@ - The dynamic data source '{0}' in type '{1}' should exist and be a property or a method. - Dynamiczne źródło danych '{0}' w typie '{1}' powinno istnieć i być właściwością lub metodą. + The dynamic data source '{0}' in type '{1}' should exist and be a property, a method, or a field. + Dynamiczne źródło danych '{0}' w typie '{1}' powinno istnieć i być właściwością lub metodą. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf index 78710455a7..69a56397d2 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf @@ -127,6 +127,11 @@ A cadeia de caracteres “{0}” começa com a cadeia de caracteres “{1}”. {2} + + Dynamic data field '{0}' should be static. + Dynamic data field '{0}' should be static. + + Dynamic data method '{0}' should be static, non-generic, and cannot have 'params' parameter. O método de dados dinâmicos '{0}' deve ser estático, não genérico e não pode ter um parâmetro 'params'. @@ -138,8 +143,8 @@ - The dynamic data source '{0}' in type '{1}' should exist and be a property or a method. - A fonte de dados dinâmica '{0}' no tipo '{1}' deve existir e ser uma propriedade ou um método. + The dynamic data source '{0}' in type '{1}' should exist and be a property, a method, or a field. + A fonte de dados dinâmica '{0}' no tipo '{1}' deve existir e ser uma propriedade ou um método. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ru.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ru.xlf index 00f8b5968b..879f4405eb 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ru.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ru.xlf @@ -127,6 +127,11 @@ Строка "{0}" начинается со строки "{1}". {2} + + Dynamic data field '{0}' should be static. + Dynamic data field '{0}' should be static. + + Dynamic data method '{0}' should be static, non-generic, and cannot have 'params' parameter. Метод динамических данных "{0}" должен быть статическим, неуниверсальным и не может иметь содержать параметр params. @@ -138,8 +143,8 @@ - The dynamic data source '{0}' in type '{1}' should exist and be a property or a method. - Динамический источник '{0}' в типе '{1}' должен существовать и быть свойством или методом. + The dynamic data source '{0}' in type '{1}' should exist and be a property, a method, or a field. + Динамический источник '{0}' в типе '{1}' должен существовать и быть свойством или методом. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.tr.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.tr.xlf index db8f3f9bc8..aad55d0eee 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.tr.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.tr.xlf @@ -127,6 +127,11 @@ '{0}' dizesi '{1}' dizesi ile başlıyor. {2} + + Dynamic data field '{0}' should be static. + Dynamic data field '{0}' should be static. + + Dynamic data method '{0}' should be static, non-generic, and cannot have 'params' parameter. Dinamik veri yöntemi ‘{0}’ statik, genel olmayan ve ‘params’ parametresine sahip olamaz. @@ -138,8 +143,8 @@ - The dynamic data source '{0}' in type '{1}' should exist and be a property or a method. - Dinamik veri kaynağı '{0}' türdeki '{1}' bir özellik veya yöntem olmalıdır. + The dynamic data source '{0}' in type '{1}' should exist and be a property, a method, or a field. + Dinamik veri kaynağı '{0}' türdeki '{1}' bir özellik veya yöntem olmalıdır. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf index fa0014b034..e88535a20b 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf @@ -127,6 +127,11 @@ 字符串 '{0}' 以字符串 '{1}' 开头。{2} + + Dynamic data field '{0}' should be static. + Dynamic data field '{0}' should be static. + + Dynamic data method '{0}' should be static, non-generic, and cannot have 'params' parameter. 动态数据方法 ‘{0}’ 应为静态、非泛型,并且不能具有 ‘params’ 参数。 @@ -138,8 +143,8 @@ - The dynamic data source '{0}' in type '{1}' should exist and be a property or a method. - 类型 '{1}' 中的动态数据源 '{0}' 应存在,并且应为属性或方法。 + The dynamic data source '{0}' in type '{1}' should exist and be a property, a method, or a field. + 类型 '{1}' 中的动态数据源 '{0}' 应存在,并且应为属性或方法。 diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf index e4688b69d9..03ac80f0c3 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf @@ -127,6 +127,11 @@ 字串 '{0}' 以字串 '{1}' 開頭。{2} + + Dynamic data field '{0}' should be static. + Dynamic data field '{0}' should be static. + + Dynamic data method '{0}' should be static, non-generic, and cannot have 'params' parameter. 動態資料方法 '{0}' 應該是靜態、非一般,而且不能有 'params' 參數。 @@ -138,8 +143,8 @@ - The dynamic data source '{0}' in type '{1}' should exist and be a property or a method. - 類型 '{1}' 中的動態數據源 '{0}' 應該存在,而且必須是屬性或方法。 + The dynamic data source '{0}' in type '{1}' should exist and be a property, a method, or a field. + 類型 '{1}' 中的動態數據源 '{0}' 應該存在,而且必須是屬性或方法。 diff --git a/test/IntegrationTests/MSTest.IntegrationTests/Parameterized tests/DynamicDataTests.cs b/test/IntegrationTests/MSTest.IntegrationTests/Parameterized tests/DynamicDataTests.cs index 0cdf9e25c4..9e3a97c8fe 100644 --- a/test/IntegrationTests/MSTest.IntegrationTests/Parameterized tests/DynamicDataTests.cs +++ b/test/IntegrationTests/MSTest.IntegrationTests/Parameterized tests/DynamicDataTests.cs @@ -28,60 +28,64 @@ public async Task ExecuteDynamicDataTests() // Assert VerifyE2E.TestsPassed( testResults, - "DynamicDataTest_SourceProperty (\"John;Doe\",LibProjectReferencedByDataSourceTest.User)", + "DynamicDataTest_SourcePropertyAutoShadowingBase (\"Jane;Doe\",LibProjectReferencedByDataSourceTest.User)", + "DynamicDataTest_SourcePropertyOtherType (\"John;Doe\",LibProjectReferencedByDataSourceTest.User)", + "DynamicDataTest_SourceMethodOtherType (\"Jane;Doe\",LibProjectReferencedByDataSourceTest.User)", + "DynamicDataTest_SourceMethodAutoShadowingBase (\"Jane;Doe\",LibProjectReferencedByDataSourceTest.User)", + "UserDynamicDataTestMethod DynamicDataTest_SourceProperty_CustomDisplayNameOtherType with 2 parameters", + "DynamicDataTest_SourceMethodFromBase (\"John;Doe\",LibProjectReferencedByDataSourceTest.User)", + "DynamicDataTestWithTestCategory (\"John;Doe\",LibProjectReferencedByDataSourceTest.User)", "DynamicDataTest_SourcePropertyFromBase (\"John;Doe\",LibProjectReferencedByDataSourceTest.User)", - "DynamicDataTest_SourcePropertyShadowingBase (\"John;Doe\",LibProjectReferencedByDataSourceTest.User)", + "Custom DynamicDataTestMethod DynamicDataTest_SourceMethodOtherType_CustomDisplayName with 2 parameters", + "MethodWithOverload (1,\"0\")", + "DynamicDataTest_SourceFieldAutoDetect (\"test\",4)", + "Custom DynamicDataTestMethod DynamicDataTest_SourceProperty_CustomDisplayName with 2 parameters", "DynamicDataTest_SourcePropertyAuto (\"John;Doe\",LibProjectReferencedByDataSourceTest.User)", + "UserDynamicDataTestMethod DynamicDataTest_SourceProperty_CustomDisplayNameOtherType with 2 parameters", + "DynamicDataTest_SimpleCollection (2)", + "DynamicDataTest_SimpleCollection (4)", + "UserDynamicDataTestMethod DynamicDataTest_SourceMethodOtherType_CustomDisplayNameOtherType with 2 parameters", + "DynamicDataTest_SourceMethodAutoShadowingBase (\"John;Doe\",LibProjectReferencedByDataSourceTest.User)", "DynamicDataTest_SourcePropertyAutoFromBase (\"John;Doe\",LibProjectReferencedByDataSourceTest.User)", + "DynamicDataTest_SourceMethodAuto (\"John;Doe\",LibProjectReferencedByDataSourceTest.User)", + "DynamicDataTest_SourceMethodAutoFromBase (\"John;Doe\",LibProjectReferencedByDataSourceTest.User)", + "Custom DynamicDataTestMethod DynamicDataTest_SourceProperty_CustomDisplayName with 2 parameters", + "DynamicDataTest_SourceMethod (\"Jane;Doe\",LibProjectReferencedByDataSourceTest.User)", + "DynamicDataTest_SourcePropertyFromBase (\"Jane;Doe\",LibProjectReferencedByDataSourceTest.User)", + "DynamicDataTest_SourceMethodAuto (\"Jane;Doe\",LibProjectReferencedByDataSourceTest.User)", + "DynamicDataTestWithTestCategory (\"Jane;Doe\",LibProjectReferencedByDataSourceTest.User)", + "UserDynamicDataTestMethod DynamicDataTest_SourcePropertyOtherType_CustomDisplayNameOtherType with 2 parameters", "DynamicDataTest_SourcePropertyAutoShadowingBase (\"John;Doe\",LibProjectReferencedByDataSourceTest.User)", + "DynamicDataTest_SourceFieldExplicit (\"field\",5)", + "DynamicDataTest_SourceProperty (\"Jane;Doe\",LibProjectReferencedByDataSourceTest.User)", + "MethodWithOverload (\"2\",1)", "Custom DynamicDataTestMethod DynamicDataTest_SourcePropertyOtherType_CustomDisplayName with 2 parameters", - "Custom DynamicDataTestMethod DynamicDataTest_SourceMethodOtherType_CustomDisplayName with 2 parameters", - "UserDynamicDataTestMethod DynamicDataTest_SourcePropertyOtherType_CustomDisplayNameOtherType with 2 parameters", - "Custom DynamicDataTestMethod DynamicDataTest_SourceMethod_CustomDisplayName with 2 parameters", - "UserDynamicDataTestMethod DynamicDataTest_SourceMethodOtherType_CustomDisplayNameOtherType with 2 parameters", - "DynamicDataTest_SourceMethod (\"Jane;Doe\",LibProjectReferencedByDataSourceTest.User)", "DynamicDataTest_SourceMethodFromBase (\"Jane;Doe\",LibProjectReferencedByDataSourceTest.User)", + "DynamicDataTest_SourcePropertyAuto (\"Jane;Doe\",LibProjectReferencedByDataSourceTest.User)", + "DynamicDataTest_SourceMethodOtherType (\"John;Doe\",LibProjectReferencedByDataSourceTest.User)", + "DynamicDataTest_SourcePropertyShadowingBase (\"John;Doe\",LibProjectReferencedByDataSourceTest.User)", + "UserDynamicDataTestMethod DynamicDataTest_SourceMethod_CustomDisplayNameOtherType with 2 parameters", + "Custom DynamicDataTestMethod DynamicDataTest_SourceMethod_CustomDisplayName with 2 parameters", "DynamicDataTest_SourceMethodShadowingBase (\"Jane;Doe\",LibProjectReferencedByDataSourceTest.User)", - "DynamicDataTest_SourceMethodAuto (\"Jane;Doe\",LibProjectReferencedByDataSourceTest.User)", - "DynamicDataTest_SourceMethodAutoFromBase (\"Jane;Doe\",LibProjectReferencedByDataSourceTest.User)", - "DynamicDataTest_SourceMethodAutoShadowingBase (\"Jane;Doe\",LibProjectReferencedByDataSourceTest.User)", - "UserDynamicDataTestMethod DynamicDataTest_SourcePropertyOtherType_CustomDisplayNameOtherType with 2 parameters", "StackOverflowException_Example (DataSourceTestProject.DynamicDataTests+ExampleTestCase)", - "Custom DynamicDataTestMethod DynamicDataTest_SourceProperty_CustomDisplayName with 2 parameters", - "UserDynamicDataTestMethod DynamicDataTest_SourceMethod_CustomDisplayNameOtherType with 2 parameters", - "DynamicDataTest_SourceMethodOtherType (\"John;Doe\",LibProjectReferencedByDataSourceTest.User)", - "DynamicDataTest_SourceMethodOtherType (\"Jane;Doe\",LibProjectReferencedByDataSourceTest.User)", - "Custom DynamicDataTestMethod DynamicDataTest_SourceProperty_CustomDisplayName with 2 parameters", "UserDynamicDataTestMethod DynamicDataTest_SourceMethod_CustomDisplayNameOtherType with 2 parameters", - "Custom DynamicDataTestMethod DynamicDataTest_SourceMethodOtherType_CustomDisplayName with 2 parameters", - "DynamicDataTest_SourcePropertyOtherType (\"John;Doe\",LibProjectReferencedByDataSourceTest.User)", - "DynamicDataTestWithTestCategory (\"Jane;Doe\",LibProjectReferencedByDataSourceTest.User)", - "DynamicDataTestWithTestCategory (\"John;Doe\",LibProjectReferencedByDataSourceTest.User)", - "UserDynamicDataTestMethod DynamicDataTest_SourceProperty_CustomDisplayNameOtherType with 2 parameters", - "UserDynamicDataTestMethod DynamicDataTest_SourceProperty_CustomDisplayNameOtherType with 2 parameters", - "DynamicDataTest_SourceMethod (\"John;Doe\",LibProjectReferencedByDataSourceTest.User)", - "DynamicDataTest_SourceMethodFromBase (\"John;Doe\",LibProjectReferencedByDataSourceTest.User)", - "DynamicDataTest_SourceMethodShadowingBase (\"John;Doe\",LibProjectReferencedByDataSourceTest.User)", - "DynamicDataTest_SourceMethodAuto (\"John;Doe\",LibProjectReferencedByDataSourceTest.User)", - "DynamicDataTest_SourceMethodAutoFromBase (\"John;Doe\",LibProjectReferencedByDataSourceTest.User)", - "DynamicDataTest_SourceMethodAutoShadowingBase (\"John;Doe\",LibProjectReferencedByDataSourceTest.User)", - "Custom DynamicDataTestMethod DynamicDataTest_SourcePropertyOtherType_CustomDisplayName with 2 parameters", - "UserDynamicDataTestMethod DynamicDataTest_SourceMethodOtherType_CustomDisplayNameOtherType with 2 parameters", - "DynamicDataTest_SourceProperty (\"Jane;Doe\",LibProjectReferencedByDataSourceTest.User)", - "DynamicDataTest_SourcePropertyFromBase (\"Jane;Doe\",LibProjectReferencedByDataSourceTest.User)", + "MethodWithOverload (\"1\",1)", "DynamicDataTest_SourcePropertyShadowingBase (\"Jane;Doe\",LibProjectReferencedByDataSourceTest.User)", - "DynamicDataTest_SourcePropertyAuto (\"Jane;Doe\",LibProjectReferencedByDataSourceTest.User)", + "DynamicDataTest_SourceProperty (\"John;Doe\",LibProjectReferencedByDataSourceTest.User)", "DynamicDataTest_SourcePropertyAutoFromBase (\"Jane;Doe\",LibProjectReferencedByDataSourceTest.User)", - "DynamicDataTest_SourcePropertyAutoShadowingBase (\"Jane;Doe\",LibProjectReferencedByDataSourceTest.User)", - "DynamicDataTest_SourcePropertyOtherType (\"Jane;Doe\",LibProjectReferencedByDataSourceTest.User)", + "DynamicDataTest_SourceFieldExplicit (\"test\",4)", "Custom DynamicDataTestMethod DynamicDataTest_SourceMethod_CustomDisplayName with 2 parameters", - "MethodWithOverload (\"1\",1)", - "MethodWithOverload (\"2\",1)", - "MethodWithOverload (1,\"0\")", + "Custom DynamicDataTestMethod DynamicDataTest_SourceMethodOtherType_CustomDisplayName with 2 parameters", + "DynamicDataTest_SourceFieldAutoDetect (\"field\",5)", + "DynamicDataTest_SourcePropertyOtherType (\"Jane;Doe\",LibProjectReferencedByDataSourceTest.User)", + "UserDynamicDataTestMethod DynamicDataTest_SourceMethodOtherType_CustomDisplayNameOtherType with 2 parameters", + "Custom DynamicDataTestMethod DynamicDataTest_SourcePropertyOtherType_CustomDisplayName with 2 parameters", + "DynamicDataTest_SourceMethodAutoFromBase (\"Jane;Doe\",LibProjectReferencedByDataSourceTest.User)", "MethodWithOverload (2,\"2\")", + "DynamicDataTest_SourceMethodShadowingBase (\"John;Doe\",LibProjectReferencedByDataSourceTest.User)", + "DynamicDataTest_SourceMethod (\"John;Doe\",LibProjectReferencedByDataSourceTest.User)", "DynamicDataTest_SimpleCollection (0)", - "DynamicDataTest_SimpleCollection (2)", - "DynamicDataTest_SimpleCollection (4)"); + "UserDynamicDataTestMethod DynamicDataTest_SourcePropertyOtherType_CustomDisplayNameOtherType with 2 parameters"); VerifyE2E.FailedTestCount(testResults, 0); } diff --git a/test/IntegrationTests/MSTest.VstestConsoleWrapper.IntegrationTests/Parameterized tests/DynamicDataTests.cs b/test/IntegrationTests/MSTest.VstestConsoleWrapper.IntegrationTests/Parameterized tests/DynamicDataTests.cs index b0e6dd89f8..bcd2386251 100644 --- a/test/IntegrationTests/MSTest.VstestConsoleWrapper.IntegrationTests/Parameterized tests/DynamicDataTests.cs +++ b/test/IntegrationTests/MSTest.VstestConsoleWrapper.IntegrationTests/Parameterized tests/DynamicDataTests.cs @@ -73,7 +73,11 @@ public void ExecuteDynamicDataTests() "MethodWithOverload (2,\"2\")", "DynamicDataTest_SimpleCollection (0)", "DynamicDataTest_SimpleCollection (2)", - "DynamicDataTest_SimpleCollection (4)"); + "DynamicDataTest_SimpleCollection (4)", + "DynamicDataTest_SourceFieldExplicit (\"field\",5)", + "DynamicDataTest_SourceFieldExplicit (\"test\",4)", + "DynamicDataTest_SourceFieldAutoDetect (\"field\",5)", + "DynamicDataTest_SourceFieldAutoDetect (\"test\",4)"); ValidateFailedTestsCount(0); } diff --git a/test/IntegrationTests/TestAssets/DynamicDataTestProject/DynamicDataTests.cs b/test/IntegrationTests/TestAssets/DynamicDataTestProject/DynamicDataTests.cs index 5e0149815c..27ebbf8590 100644 --- a/test/IntegrationTests/TestAssets/DynamicDataTestProject/DynamicDataTests.cs +++ b/test/IntegrationTests/TestAssets/DynamicDataTestProject/DynamicDataTests.cs @@ -272,4 +272,21 @@ private static IEnumerable SimpleCollection yield return 4; } } + + // Test field support - static field for dynamic data + private static readonly IEnumerable FieldTestData = new[] + { + ["field", 5], + new object[] { "test", 4 }, + }; + + [DataTestMethod] + [DynamicData(nameof(FieldTestData), DynamicDataSourceType.Field)] + public void DynamicDataTest_SourceFieldExplicit(string text, int expectedLength) + => Assert.AreEqual(expectedLength, text.Length); + + [DataTestMethod] + [DynamicData(nameof(FieldTestData))] // AutoDetect should find the field + public void DynamicDataTest_SourceFieldAutoDetect(string text, int expectedLength) + => Assert.AreEqual(expectedLength, text.Length); } diff --git a/test/UnitTests/MSTest.Analyzers.UnitTests/DynamicDataShouldBeValidAnalyzerTests.cs b/test/UnitTests/MSTest.Analyzers.UnitTests/DynamicDataShouldBeValidAnalyzerTests.cs index 75d851eb83..f4f236ae00 100644 --- a/test/UnitTests/MSTest.Analyzers.UnitTests/DynamicDataShouldBeValidAnalyzerTests.cs +++ b/test/UnitTests/MSTest.Analyzers.UnitTests/DynamicDataShouldBeValidAnalyzerTests.cs @@ -908,18 +908,6 @@ public void TestMethod16(object[] o) { } - [{|#10:DynamicData(nameof(DataField), DynamicDataSourceType.AutoDetect)|}] - [TestMethod] - public void TestMethod17(object[] o) - { - } - - [{|#11:DynamicData(nameof(DataField))|}] - [TestMethod] - public void TestMethod18(object[] o) - { - } - public static IEnumerable Data => new List(); public static IEnumerable GetData() => new List(); public static IEnumerable DataField = new List(); @@ -942,10 +930,142 @@ await VerifyCS.VerifyAnalyzerAsync( VerifyCS.Diagnostic(DynamicDataShouldBeValidAnalyzer.SourceTypePropertyRule).WithLocation(5).WithArguments("SomeClass", "SomeData"), VerifyCS.Diagnostic(DynamicDataShouldBeValidAnalyzer.SourceTypePropertyRule).WithLocation(6).WithArguments("MyTestClass", "Data"), VerifyCS.Diagnostic(DynamicDataShouldBeValidAnalyzer.SourceTypePropertyRule).WithLocation(7).WithArguments("SomeClass", "SomeData"), - VerifyCS.Diagnostic(DynamicDataShouldBeValidAnalyzer.SourceTypeNotPropertyOrMethodRule).WithLocation(8).WithArguments("MyTestClass", "DataField"), - VerifyCS.Diagnostic(DynamicDataShouldBeValidAnalyzer.SourceTypeNotPropertyOrMethodRule).WithLocation(9).WithArguments("MyTestClass", "DataField"), - VerifyCS.Diagnostic(DynamicDataShouldBeValidAnalyzer.SourceTypeNotPropertyOrMethodRule).WithLocation(10).WithArguments("MyTestClass", "DataField"), - VerifyCS.Diagnostic(DynamicDataShouldBeValidAnalyzer.SourceTypeNotPropertyOrMethodRule).WithLocation(11).WithArguments("MyTestClass", "DataField")); + VerifyCS.Diagnostic(DynamicDataShouldBeValidAnalyzer.SourceTypeFieldRule).WithLocation(8).WithArguments("MyTestClass", "DataField"), + VerifyCS.Diagnostic(DynamicDataShouldBeValidAnalyzer.SourceTypeFieldRule).WithLocation(9).WithArguments("MyTestClass", "DataField")); + } + + [TestMethod] + public async Task WhenDataIsField_NoDiagnostic() + { + string code = """ + using System.Collections.Generic; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [DynamicData("DataField")] + [TestMethod] + public void TestMethod1Auto(object[] o) + { + } + + [DynamicData("DataField", DynamicDataSourceType.Field)] + [TestMethod] + public void TestMethod1Field(object[] o) + { + } + + [DynamicData("SomeDataField", typeof(SomeClass))] + [TestMethod] + public void TestMethod2Auto(object[] o) + { + } + + [DynamicData("SomeDataField", typeof(SomeClass), DynamicDataSourceType.Field)] + [TestMethod] + public void TestMethod2Field(object[] o) + { + } + + [DynamicData(dynamicDataSourceName: "DataField")] + [TestMethod] + public void TestMethod3Auto(object[] o) + { + } + + [DynamicData(dynamicDataDeclaringType: typeof(SomeClass), dynamicDataSourceName: "SomeDataField")] + [TestMethod] + public void TestMethod4Auto(object[] o) + { + } + + [DynamicData(dynamicDataDeclaringType: typeof(SomeClass), dynamicDataSourceName: "SomeDataField", dynamicDataSourceType: DynamicDataSourceType.Field)] + [TestMethod] + public void TestMethod4Field(object[] o) + { + } + + public static IEnumerable DataField = new[] + { + new object[] { 1, 2 }, + new object[] { 3, 4 } + }; + } + + public class SomeClass + { + public static IEnumerable SomeDataField = new[] + { + new object[] { 1, 2 }, + new object[] { 3, 4 } + }; + } + """; + + await VerifyCS.VerifyAnalyzerAsync(code); + } + + [TestMethod] + public async Task WhenFieldMemberKindIsMixedUp_Diagnostic() + { + string code = """ + using System.Collections.Generic; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [{|#0:DynamicData("DataField", DynamicDataSourceType.Property)|}] + [TestMethod] + public void TestMethod1(object[] o) + { + } + + [{|#1:DynamicData("DataField", DynamicDataSourceType.Method)|}] + [TestMethod] + public void TestMethod2(object[] o) + { + } + + [{|#2:DynamicData("Data", DynamicDataSourceType.Field)|}] + [TestMethod] + public void TestMethod3(object[] o) + { + } + + [{|#3:DynamicData("GetData", DynamicDataSourceType.Field)|}] + [TestMethod] + public void TestMethod4(object[] o) + { + } + + public static IEnumerable Data => new[] + { + new object[] { 1, 2 }, + new object[] { 3, 4 } + }; + + public static IEnumerable GetData() => new[] + { + new object[] { 1, 2 }, + new object[] { 3, 4 } + }; + + public static IEnumerable DataField = new[] + { + new object[] { 1, 2 }, + new object[] { 3, 4 } + }; + } + """; + + await VerifyCS.VerifyAnalyzerAsync( + code, + VerifyCS.Diagnostic(DynamicDataShouldBeValidAnalyzer.SourceTypeFieldRule).WithLocation(0).WithArguments("MyTestClass", "DataField"), + VerifyCS.Diagnostic(DynamicDataShouldBeValidAnalyzer.SourceTypeFieldRule).WithLocation(1).WithArguments("MyTestClass", "DataField"), + VerifyCS.Diagnostic(DynamicDataShouldBeValidAnalyzer.SourceTypePropertyRule).WithLocation(2).WithArguments("MyTestClass", "Data"), + VerifyCS.Diagnostic(DynamicDataShouldBeValidAnalyzer.SourceTypeMethodRule).WithLocation(3).WithArguments("MyTestClass", "GetData")); } [TestMethod] diff --git a/test/UnitTests/TestFramework.UnitTests/Attributes/DynamicDataAttributeTests.cs b/test/UnitTests/TestFramework.UnitTests/Attributes/DynamicDataAttributeTests.cs index 93630f184b..97a6020d0e 100644 --- a/test/UnitTests/TestFramework.UnitTests/Attributes/DynamicDataAttributeTests.cs +++ b/test/UnitTests/TestFramework.UnitTests/Attributes/DynamicDataAttributeTests.cs @@ -261,10 +261,72 @@ public void DynamicDataSource_WithValueTupleWithTupleSyntax_Works() dynamicDataAttribute.GetData(testMethodInfo); } + public void GetDataShouldReadDataFromField() + { + MethodInfo methodInfo = _dummyTestClass.GetType().GetTypeInfo().GetDeclaredMethod("TestMethod1")!; + _dynamicDataAttribute = new DynamicDataAttribute("ReusableTestDataField", DynamicDataSourceType.Field); + IEnumerable data = _dynamicDataAttribute.GetData(methodInfo); + Verify(data is not null); + Verify(data.ToList().Count == 2); + } + + public void GetDataShouldReadDataFromFieldInDifferentClass() + { + MethodInfo methodInfo = _dummyTestClass.GetType().GetTypeInfo().GetDeclaredMethod("TestMethod1")!; + _dynamicDataAttribute = new DynamicDataAttribute("ReusableTestDataField2", typeof(DummyTestClass2), DynamicDataSourceType.Field); + IEnumerable data = _dynamicDataAttribute.GetData(methodInfo); + Verify(data is not null); + Verify(data.ToList().Count == 2); + } + + public void GetDataShouldReadDataFromFieldInAutoDetectMode() + { + MethodInfo methodInfo = _dummyTestClass.GetType().GetTypeInfo().GetDeclaredMethod("TestMethod1")!; + _dynamicDataAttribute = new DynamicDataAttribute("ReusableTestDataField"); + IEnumerable data = _dynamicDataAttribute.GetData(methodInfo); + Verify(data is not null); + Verify(data.ToList().Count == 2); + } + + public void GetDataShouldThrowExceptionIfFieldReturnsNull() => + VerifyThrows(() => + { + MethodInfo methodInfo = _dummyTestClass.GetType().GetTypeInfo().GetDeclaredMethod("TestMethod1")!; + _dynamicDataAttribute = new DynamicDataAttribute("NullField", typeof(DummyTestClass), DynamicDataSourceType.Field); + _dynamicDataAttribute.GetData(methodInfo); + }); + + public void GetDataShouldNotThrowExceptionIfFieldReturnsEmpty() + { + MethodInfo methodInfo = _dummyTestClass.GetType().GetTypeInfo().GetDeclaredMethod("TestMethod1")!; + _dynamicDataAttribute = new DynamicDataAttribute("EmptyField", typeof(DummyTestClass), DynamicDataSourceType.Field); + IEnumerable data = _dynamicDataAttribute.GetData(methodInfo); + // The callers in AssemblyEnumerator and TestMethodRunner are responsible + // for throwing an exception if data is empty and ConsiderEmptyDataSourceAsInconclusive is false. + Verify(!data.Any()); + } + + public void GetDataShouldThrowExceptionIfFieldDoesNotReturnCorrectType() => + VerifyThrows(() => + { + MethodInfo methodInfo = _dummyTestClass.GetType().GetTypeInfo().GetDeclaredMethod("TestMethod1")!; + _dynamicDataAttribute = new DynamicDataAttribute("WrongDataTypeField", typeof(DummyTestClass), DynamicDataSourceType.Field); + _dynamicDataAttribute.GetData(methodInfo); + }); + + public void GetDataShouldThrowExceptionIfFieldIsNotStatic() => + VerifyThrows(() => + { + MethodInfo methodInfo = _dummyTestClass.GetType().GetTypeInfo().GetDeclaredMethod("TestMethod1")!; + _dynamicDataAttribute = new DynamicDataAttribute("NonStaticField", typeof(DummyTestClass), DynamicDataSourceType.Field); + _dynamicDataAttribute.GetData(methodInfo); + }); + /// /// The dummy test class. /// [TestClass] + [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:Fields should be private", Justification = "Test use case")] internal class DummyTestClass { /// @@ -288,6 +350,32 @@ internal class DummyTestClass /// public static string WrongDataTypeProperty => "Dummy"; + /// + /// The reusable test data field. + /// + public static IEnumerable ReusableTestDataField = [[1, 2, 3], [4, 5, 6]]; + + /// + /// The null test data field. + /// + public static IEnumerable NullField = null!; + + /// + /// The empty test data field. + /// + public static IEnumerable EmptyField = []; + + /// + /// The wrong test data field i.e. Field returning something other than + /// expected data type of . + /// + public static string WrongDataTypeField = "Dummy"; + + /// + /// Non-static field that should cause an error. + /// + public IEnumerable NonStaticField = [[1, 2, 3]]; + /// /// The reusable test data method. /// @@ -438,6 +526,8 @@ public void DataRowTestMethod() private static string GetDynamicDataDisplayNamePrivate(MethodInfo methodInfo, object[] data) => throw new InvalidOperationException(); } + [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:Fields should be private", Justification = "For testing the use case")] + [SuppressMessage("Usage", "CA2211:Non-constant fields should not be visible", Justification = "For testing the use case")] public class DummyTestClass2 { /// @@ -453,6 +543,11 @@ public class DummyTestClass2 /// public static IEnumerable ReusableTestDataMethod2() => [[1, 2, 3], [4, 5, 6]]; + /// + /// The reusable test data field. + /// + public static IEnumerable ReusableTestDataField2 = [[1, 2, 3], [4, 5, 6]]; + /// /// The custom display name method. /// From 0b1db146329349f3fa2a5d395ae94e5d17ce8231 Mon Sep 17 00:00:00 2001 From: dotnet bot Date: Thu, 31 Jul 2025 04:02:41 -0700 Subject: [PATCH 343/541] Localized file check-in by OneLocBuild Task: Build definition ID 1218: Build ID 2761913 --- .../TestFramework/Resources/xlf/FrameworkMessages.cs.xlf | 2 +- .../TestFramework/Resources/xlf/FrameworkMessages.de.xlf | 2 +- .../TestFramework/Resources/xlf/FrameworkMessages.es.xlf | 2 +- .../TestFramework/Resources/xlf/FrameworkMessages.fr.xlf | 2 +- .../TestFramework/Resources/xlf/FrameworkMessages.it.xlf | 2 +- .../TestFramework/Resources/xlf/FrameworkMessages.ja.xlf | 2 +- .../TestFramework/Resources/xlf/FrameworkMessages.ko.xlf | 2 +- .../TestFramework/Resources/xlf/FrameworkMessages.pl.xlf | 2 +- .../TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf | 2 +- .../TestFramework/Resources/xlf/FrameworkMessages.ru.xlf | 2 +- .../TestFramework/Resources/xlf/FrameworkMessages.tr.xlf | 2 +- .../TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf | 2 +- .../TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf | 2 +- 13 files changed, 13 insertions(+), 13 deletions(-) diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.cs.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.cs.xlf index 5f4461b69a..bd9ab254e9 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.cs.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.cs.xlf @@ -144,7 +144,7 @@ The dynamic data source '{0}' in type '{1}' should exist and be a property, a method, or a field. - Dynamický zdroj dat '{0}' v typu '{1}' by měl existovat a být vlastností nebo metodou. + The dynamic data source '{0}' in type '{1}' should exist and be a property, a method, or a field. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.de.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.de.xlf index 97c5d578c9..c2cac59253 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.de.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.de.xlf @@ -144,7 +144,7 @@ The dynamic data source '{0}' in type '{1}' should exist and be a property, a method, or a field. - Die dynamische Datenquelle '{0}' im Typ '{1}' muss vorhanden sein und eine Eigenschaft oder Methode sein. + The dynamic data source '{0}' in type '{1}' should exist and be a property, a method, or a field. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.es.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.es.xlf index 26a2384533..0df98f32df 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.es.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.es.xlf @@ -144,7 +144,7 @@ The dynamic data source '{0}' in type '{1}' should exist and be a property, a method, or a field. - El origen de datos dinámico '{0}' en el tipo '{1}' debe existir y ser una propiedad o un método. + The dynamic data source '{0}' in type '{1}' should exist and be a property, a method, or a field. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.fr.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.fr.xlf index 8f9232c016..0709bd08e2 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.fr.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.fr.xlf @@ -144,7 +144,7 @@ The dynamic data source '{0}' in type '{1}' should exist and be a property, a method, or a field. - La source de données dynamique '{0}' dans le type '{1}' doit exister et être une propriété ou une méthode. + The dynamic data source '{0}' in type '{1}' should exist and be a property, a method, or a field. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.it.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.it.xlf index a18ec4d81c..0f9f091b46 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.it.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.it.xlf @@ -144,7 +144,7 @@ The dynamic data source '{0}' in type '{1}' should exist and be a property, a method, or a field. - L'origine dati dinamica '{0}' nel tipo '{1}' deve esistere ed essere una proprietà o un metodo. + The dynamic data source '{0}' in type '{1}' should exist and be a property, a method, or a field. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ja.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ja.xlf index dcf06007fa..f01e9d6e10 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ja.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ja.xlf @@ -144,7 +144,7 @@ The dynamic data source '{0}' in type '{1}' should exist and be a property, a method, or a field. - 型 '{1}' の動的データ ソース '{0}' は、プロパティまたはメソッドである必要があります。 + The dynamic data source '{0}' in type '{1}' should exist and be a property, a method, or a field. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ko.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ko.xlf index 99e50cbf7a..c215074879 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ko.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ko.xlf @@ -144,7 +144,7 @@ The dynamic data source '{0}' in type '{1}' should exist and be a property, a method, or a field. - '{1}' 형식의 동적 데이터 원본 '{0}' 존재하며 속성 또는 메서드여야 합니다. + The dynamic data source '{0}' in type '{1}' should exist and be a property, a method, or a field. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pl.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pl.xlf index 23ce865435..ba23236751 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pl.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pl.xlf @@ -144,7 +144,7 @@ The dynamic data source '{0}' in type '{1}' should exist and be a property, a method, or a field. - Dynamiczne źródło danych '{0}' w typie '{1}' powinno istnieć i być właściwością lub metodą. + The dynamic data source '{0}' in type '{1}' should exist and be a property, a method, or a field. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf index 69a56397d2..c23f2d592c 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf @@ -144,7 +144,7 @@ The dynamic data source '{0}' in type '{1}' should exist and be a property, a method, or a field. - A fonte de dados dinâmica '{0}' no tipo '{1}' deve existir e ser uma propriedade ou um método. + The dynamic data source '{0}' in type '{1}' should exist and be a property, a method, or a field. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ru.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ru.xlf index 879f4405eb..7922657c22 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ru.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ru.xlf @@ -144,7 +144,7 @@ The dynamic data source '{0}' in type '{1}' should exist and be a property, a method, or a field. - Динамический источник '{0}' в типе '{1}' должен существовать и быть свойством или методом. + The dynamic data source '{0}' in type '{1}' should exist and be a property, a method, or a field. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.tr.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.tr.xlf index aad55d0eee..8948617376 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.tr.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.tr.xlf @@ -144,7 +144,7 @@ The dynamic data source '{0}' in type '{1}' should exist and be a property, a method, or a field. - Dinamik veri kaynağı '{0}' türdeki '{1}' bir özellik veya yöntem olmalıdır. + The dynamic data source '{0}' in type '{1}' should exist and be a property, a method, or a field. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf index e88535a20b..4f8f4ba639 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf @@ -144,7 +144,7 @@ The dynamic data source '{0}' in type '{1}' should exist and be a property, a method, or a field. - 类型 '{1}' 中的动态数据源 '{0}' 应存在,并且应为属性或方法。 + The dynamic data source '{0}' in type '{1}' should exist and be a property, a method, or a field. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf index 03ac80f0c3..8b0c772e2d 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf @@ -144,7 +144,7 @@ The dynamic data source '{0}' in type '{1}' should exist and be a property, a method, or a field. - 類型 '{1}' 中的動態數據源 '{0}' 應該存在,而且必須是屬性或方法。 + The dynamic data source '{0}' in type '{1}' should exist and be a property, a method, or a field. From f548433961344ee1629c5b04c35d99efc9fdd860 Mon Sep 17 00:00:00 2001 From: Copilot <198982749+Copilot@users.noreply.github.com> Date: Thu, 31 Jul 2025 17:45:57 +0200 Subject: [PATCH 344/541] Add analyzer for DynamicDataSourceType usage (MSTEST0052) (#6261) Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: Evangelink <11340282+Evangelink@users.noreply.github.com> Co-authored-by: Youssef1313 --- ...AvoidExplicitDynamicDataSourceTypeFixer.cs | 83 ++++ .../CodeFixResources.Designer.cs | 9 + .../CodeFixResources.resx | 3 + .../xlf/CodeFixResources.cs.xlf | 5 + .../xlf/CodeFixResources.de.xlf | 5 + .../xlf/CodeFixResources.es.xlf | 5 + .../xlf/CodeFixResources.fr.xlf | 5 + .../xlf/CodeFixResources.it.xlf | 5 + .../xlf/CodeFixResources.ja.xlf | 5 + .../xlf/CodeFixResources.ko.xlf | 5 + .../xlf/CodeFixResources.pl.xlf | 5 + .../xlf/CodeFixResources.pt-BR.xlf | 5 + .../xlf/CodeFixResources.ru.xlf | 5 + .../xlf/CodeFixResources.tr.xlf | 5 + .../xlf/CodeFixResources.zh-Hans.xlf | 5 + .../xlf/CodeFixResources.zh-Hant.xlf | 5 + .../AnalyzerReleases.Unshipped.md | 1 + ...idExplicitDynamicDataSourceTypeAnalyzer.cs | 75 ++++ .../MSTest.Analyzers/Helpers/DiagnosticIds.cs | 1 + .../MSTest.Analyzers/Resources.Designer.cs | 384 +++++++++--------- src/Analyzers/MSTest.Analyzers/Resources.resx | 6 + .../MSTest.Analyzers/xlf/Resources.cs.xlf | 10 + .../MSTest.Analyzers/xlf/Resources.de.xlf | 10 + .../MSTest.Analyzers/xlf/Resources.es.xlf | 10 + .../MSTest.Analyzers/xlf/Resources.fr.xlf | 10 + .../MSTest.Analyzers/xlf/Resources.it.xlf | 10 + .../MSTest.Analyzers/xlf/Resources.ja.xlf | 10 + .../MSTest.Analyzers/xlf/Resources.ko.xlf | 10 + .../MSTest.Analyzers/xlf/Resources.pl.xlf | 10 + .../MSTest.Analyzers/xlf/Resources.pt-BR.xlf | 10 + .../MSTest.Analyzers/xlf/Resources.ru.xlf | 10 + .../MSTest.Analyzers/xlf/Resources.tr.xlf | 10 + .../xlf/Resources.zh-Hans.xlf | 10 + .../xlf/Resources.zh-Hant.xlf | 10 + ...AvoidExplicitDynamicDataSourceTypeTests.cs | 266 ++++++++++++ 35 files changed, 840 insertions(+), 183 deletions(-) create mode 100644 src/Analyzers/MSTest.Analyzers.CodeFixes/AvoidExplicitDynamicDataSourceTypeFixer.cs create mode 100644 src/Analyzers/MSTest.Analyzers/AvoidExplicitDynamicDataSourceTypeAnalyzer.cs create mode 100644 test/UnitTests/MSTest.Analyzers.UnitTests/AvoidExplicitDynamicDataSourceTypeTests.cs diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/AvoidExplicitDynamicDataSourceTypeFixer.cs b/src/Analyzers/MSTest.Analyzers.CodeFixes/AvoidExplicitDynamicDataSourceTypeFixer.cs new file mode 100644 index 0000000000..9811d55ce5 --- /dev/null +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/AvoidExplicitDynamicDataSourceTypeFixer.cs @@ -0,0 +1,83 @@ +// 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.Immutable; +using System.Composition; + +using Analyzer.Utilities; +using Analyzer.Utilities.Extensions; + +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CodeActions; +using Microsoft.CodeAnalysis.CodeFixes; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Editing; +using Microsoft.CodeAnalysis.Text; + +using MSTest.Analyzers.Helpers; + +namespace MSTest.Analyzers; + +/// +/// Code fixer for . +/// +[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(AvoidExplicitDynamicDataSourceTypeFixer))] +[Shared] +public sealed class AvoidExplicitDynamicDataSourceTypeFixer : CodeFixProvider +{ + /// + public sealed override ImmutableArray FixableDiagnosticIds { get; } + = ImmutableArray.Create(DiagnosticIds.AvoidExplicitDynamicDataSourceTypeRuleId); + + /// + public override FixAllProvider GetFixAllProvider() + // See https://github.com/dotnet/roslyn/blob/main/docs/analyzers/FixAllProvider.md for more information on Fix All Providers + => WellKnownFixAllProviders.BatchFixer; + + /// + public override async Task RegisterCodeFixesAsync(CodeFixContext context) + { + SyntaxNode root = await context.Document.GetRequiredSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); + Diagnostic diagnostic = context.Diagnostics[0]; + TextSpan diagnosticSpan = diagnostic.Location.SourceSpan; + + if (root.FindNode(diagnosticSpan) is not AttributeSyntax attributeSyntax || + attributeSyntax.ArgumentList is not AttributeArgumentListSyntax argumentList) + { + return; + } + + context.RegisterCodeFix( + CodeAction.Create( + CodeFixResources.RemoveDynamicDataSourceTypeFix, + ct => RemoveDynamicDataSourceTypeAsync(context.Document, argumentList, ct), + nameof(AvoidExplicitDynamicDataSourceTypeFixer)), + context.Diagnostics); + } + + private static async Task RemoveDynamicDataSourceTypeAsync(Document document, AttributeArgumentListSyntax argumentList, CancellationToken cancellationToken) + { + cancellationToken.ThrowIfCancellationRequested(); + + DocumentEditor editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false); + SemanticModel semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); + + if (!semanticModel.Compilation.TryGetOrCreateTypeByMetadataName(WellKnownTypeNames.MicrosoftVisualStudioTestToolsUnitTestingDynamicDataSourceType, out INamedTypeSymbol? dynamicDataSourceTypeSymbol)) + { + return document; + } + + foreach (AttributeArgumentSyntax argument in argumentList.Arguments) + { + Microsoft.CodeAnalysis.TypeInfo typeInfo = semanticModel.GetTypeInfo(argument.Expression, cancellationToken); + if (SymbolEqualityComparer.Default.Equals(typeInfo.Type, dynamicDataSourceTypeSymbol)) + { + editor.ReplaceNode(argumentList, argumentList.WithArguments(argumentList.Arguments.Remove(argument))); + break; + } + } + + return editor.GetChangedDocument(); + } +} diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/CodeFixResources.Designer.cs b/src/Analyzers/MSTest.Analyzers.CodeFixes/CodeFixResources.Designer.cs index 39751da4c0..0ffb6ab9dc 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/CodeFixResources.Designer.cs +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/CodeFixResources.Designer.cs @@ -284,5 +284,14 @@ internal static string UseProperAssertMethodsFix { return ResourceManager.GetString("UseProperAssertMethodsFix", resourceCulture); } } + + /// + /// Looks up a localized string similar to Remove 'DynamicDataSourceType' parameter to use default 'AutoDetect'. + /// + internal static string RemoveDynamicDataSourceTypeFix { + get { + return ResourceManager.GetString("RemoveDynamicDataSourceTypeFix", resourceCulture); + } + } } } diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/CodeFixResources.resx b/src/Analyzers/MSTest.Analyzers.CodeFixes/CodeFixResources.resx index 5c5033b0df..be5663f1eb 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/CodeFixResources.resx +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/CodeFixResources.resx @@ -192,4 +192,7 @@ Pass 'TestContext.CancellationTokenSource.Token' argument to method call + + Remove 'DynamicDataSourceType' parameter to use default 'AutoDetect' + \ No newline at end of file diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.cs.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.cs.xlf index 7c85a47db8..f37ac67ed8 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.cs.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.cs.xlf @@ -52,6 +52,11 @@ Předejte argument TestContext.CancellationTokenSource.Token volání metody. + + Remove 'DynamicDataSourceType' parameter to use default 'AutoDetect' + Remove 'DynamicDataSourceType' parameter to use default 'AutoDetect' + + Replace 'DataTestMethod' with 'TestMethod' Nahradit DataTestMethod hodnotou TestMethod diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.de.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.de.xlf index 16776cafc7..5547c7b016 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.de.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.de.xlf @@ -52,6 +52,11 @@ Argument „TestContext.CancellationTokenSource.Token“ an den Methodenaufruf übergeben + + Remove 'DynamicDataSourceType' parameter to use default 'AutoDetect' + Remove 'DynamicDataSourceType' parameter to use default 'AutoDetect' + + Replace 'DataTestMethod' with 'TestMethod' „DataTestMethod“ durch „TestMethod“ ersetzen diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.es.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.es.xlf index 5fe2aeef20..cb6b8436f2 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.es.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.es.xlf @@ -52,6 +52,11 @@ Pasa el argumento 'TestContext.CancellationTokenSource.Token' a la llamada de método + + Remove 'DynamicDataSourceType' parameter to use default 'AutoDetect' + Remove 'DynamicDataSourceType' parameter to use default 'AutoDetect' + + Replace 'DataTestMethod' with 'TestMethod' Reemplazar "DataTestMethod" por "TestMethod" diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.fr.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.fr.xlf index 821c7fe651..9a67381860 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.fr.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.fr.xlf @@ -52,6 +52,11 @@ Passer l’argument « TestContext.CancellationTokenSource.Token » à l’appel de méthode + + Remove 'DynamicDataSourceType' parameter to use default 'AutoDetect' + Remove 'DynamicDataSourceType' parameter to use default 'AutoDetect' + + Replace 'DataTestMethod' with 'TestMethod' Remplacer « DataTestMethod » par « TestMethod » diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.it.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.it.xlf index 31788d3248..0dafc34936 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.it.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.it.xlf @@ -52,6 +52,11 @@ Passare l'argomento 'TestContext.CancellationTokenSource.Token' alla chiamata al metodo + + Remove 'DynamicDataSourceType' parameter to use default 'AutoDetect' + Remove 'DynamicDataSourceType' parameter to use default 'AutoDetect' + + Replace 'DataTestMethod' with 'TestMethod' Sostituisci 'DataTestMethod' con 'TestMethod' diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ja.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ja.xlf index 94549b537e..9924ecd9af 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ja.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ja.xlf @@ -52,6 +52,11 @@ 'TestContext.CancellationTokenSource.Token' 引数をメソッド呼び出しに渡す + + Remove 'DynamicDataSourceType' parameter to use default 'AutoDetect' + Remove 'DynamicDataSourceType' parameter to use default 'AutoDetect' + + Replace 'DataTestMethod' with 'TestMethod' 'DataTestMethod' を 'TestMethod' に置き換えます diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ko.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ko.xlf index 1d3b2b6c7d..cedcce1149 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ko.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ko.xlf @@ -52,6 +52,11 @@ 메서드 호출에 'TestContext.CancellationTokenSource.Token' 인수 전달 + + Remove 'DynamicDataSourceType' parameter to use default 'AutoDetect' + Remove 'DynamicDataSourceType' parameter to use default 'AutoDetect' + + Replace 'DataTestMethod' with 'TestMethod' 'DataTestMethod'를 'TestMethod'로 바꾸기 diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pl.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pl.xlf index 310742cd01..3caa21908b 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pl.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pl.xlf @@ -52,6 +52,11 @@ Przekaż argument „TestContext.CancellationTokenSource.Token” do wywołania metody + + Remove 'DynamicDataSourceType' parameter to use default 'AutoDetect' + Remove 'DynamicDataSourceType' parameter to use default 'AutoDetect' + + Replace 'DataTestMethod' with 'TestMethod' Zastąp element „DataTestMethod” elementem „TestMethod” diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pt-BR.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pt-BR.xlf index bd3d1f3de9..471b1602e5 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pt-BR.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pt-BR.xlf @@ -52,6 +52,11 @@ Passe o argumento 'TestContext.CancellationTokenSource.Token' para a chamada do método + + Remove 'DynamicDataSourceType' parameter to use default 'AutoDetect' + Remove 'DynamicDataSourceType' parameter to use default 'AutoDetect' + + Replace 'DataTestMethod' with 'TestMethod' Substitua 'DataTestMethod' por 'TestMethod' diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ru.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ru.xlf index e39f5f059c..0cb8bcef77 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ru.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ru.xlf @@ -52,6 +52,11 @@ Передайте аргумент "TestContext.CancellationTokenSource.Token" вызов метода + + Remove 'DynamicDataSourceType' parameter to use default 'AutoDetect' + Remove 'DynamicDataSourceType' parameter to use default 'AutoDetect' + + Replace 'DataTestMethod' with 'TestMethod' Заменить "DataTestMethod" на "TestMethod" diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.tr.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.tr.xlf index 1d0141b71c..9b1c7acf17 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.tr.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.tr.xlf @@ -52,6 +52,11 @@ ‘TestContext.CancellationTokenSource.Token’ bağımsız değişkeni metot çağrısına geçirin + + Remove 'DynamicDataSourceType' parameter to use default 'AutoDetect' + Remove 'DynamicDataSourceType' parameter to use default 'AutoDetect' + + Replace 'DataTestMethod' with 'TestMethod' 'DataTestMethod' yöntemini 'TestMethod' ile değiştirin diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hans.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hans.xlf index 271951cb89..ec07f7bfe2 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hans.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hans.xlf @@ -52,6 +52,11 @@ 将 'TestContext.CancellationTokenSource.Token' 参数传递给方法调用 + + Remove 'DynamicDataSourceType' parameter to use default 'AutoDetect' + Remove 'DynamicDataSourceType' parameter to use default 'AutoDetect' + + Replace 'DataTestMethod' with 'TestMethod' 将 'DataTestMethod' 替换为 'TestMethod' diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hant.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hant.xlf index d490fcbef8..0fe18848ae 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hant.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hant.xlf @@ -52,6 +52,11 @@ 將 'TestContext.CancellationTokenSource.Token' 引數傳遞給方法呼叫 + + Remove 'DynamicDataSourceType' parameter to use default 'AutoDetect' + Remove 'DynamicDataSourceType' parameter to use default 'AutoDetect' + + Replace 'DataTestMethod' with 'TestMethod' 將 'DataTestMethod' 取代為 'TestMethod' diff --git a/src/Analyzers/MSTest.Analyzers/AnalyzerReleases.Unshipped.md b/src/Analyzers/MSTest.Analyzers/AnalyzerReleases.Unshipped.md index 967b851f18..f68f3db8ab 100644 --- a/src/Analyzers/MSTest.Analyzers/AnalyzerReleases.Unshipped.md +++ b/src/Analyzers/MSTest.Analyzers/AnalyzerReleases.Unshipped.md @@ -6,3 +6,4 @@ Rule ID | Category | Severity | Notes --------|----------|----------|------- MSTEST0051 | Usage | Info | AssertThrowsShouldContainSingleStatementAnalyzer, [Documentation](https://learn.microsoft.com/dotnet/core/testing/mstest-analyzers/mstest0051) +MSTEST0052 | Usage | Warning | PreferDynamicDataSourceTypeAutoDetectAnalyzer, [Documentation](https://learn.microsoft.com/dotnet/core/testing/mstest-analyzers/mstest0052) diff --git a/src/Analyzers/MSTest.Analyzers/AvoidExplicitDynamicDataSourceTypeAnalyzer.cs b/src/Analyzers/MSTest.Analyzers/AvoidExplicitDynamicDataSourceTypeAnalyzer.cs new file mode 100644 index 0000000000..43aad409d3 --- /dev/null +++ b/src/Analyzers/MSTest.Analyzers/AvoidExplicitDynamicDataSourceTypeAnalyzer.cs @@ -0,0 +1,75 @@ +// 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.Immutable; + +using Analyzer.Utilities.Extensions; + +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Diagnostics; + +using MSTest.Analyzers.Helpers; + +namespace MSTest.Analyzers; + +/// +/// MSTEST0052: . +/// +[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] +public sealed class AvoidExplicitDynamicDataSourceTypeAnalyzer : DiagnosticAnalyzer +{ + private static readonly LocalizableResourceString Title = new(nameof(Resources.AvoidExplicitDynamicDataSourceTypeTitle), Resources.ResourceManager, typeof(Resources)); + private static readonly LocalizableResourceString MessageFormat = new(nameof(Resources.AvoidExplicitDynamicDataSourceTypeMessageFormat), Resources.ResourceManager, typeof(Resources)); + + internal static readonly DiagnosticDescriptor PreferAutoDetectRule = DiagnosticDescriptorHelper.Create( + DiagnosticIds.AvoidExplicitDynamicDataSourceTypeRuleId, + Title, + MessageFormat, + null, + Category.Usage, + DiagnosticSeverity.Warning, + isEnabledByDefault: true); + + /// + public override ImmutableArray SupportedDiagnostics { get; } = ImmutableArray.Create(PreferAutoDetectRule); + + /// + public override void Initialize(AnalysisContext context) + { + context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); + context.EnableConcurrentExecution(); + + context.RegisterCompilationStartAction(context => + { + if (context.Compilation.TryGetOrCreateTypeByMetadataName(WellKnownTypeNames.MicrosoftVisualStudioTestToolsUnitTestingDynamicDataAttribute, out INamedTypeSymbol? dynamicDataAttributeSymbol) + && context.Compilation.TryGetOrCreateTypeByMetadataName(WellKnownTypeNames.MicrosoftVisualStudioTestToolsUnitTestingDynamicDataSourceType, out INamedTypeSymbol? dynamicDataSourceTypeSymbol)) + { + context.RegisterSymbolAction( + context => AnalyzeSymbol(context, dynamicDataAttributeSymbol, dynamicDataSourceTypeSymbol), + SymbolKind.Method); + } + }); + } + + private static void AnalyzeSymbol(SymbolAnalysisContext context, INamedTypeSymbol dynamicDataAttributeSymbol, INamedTypeSymbol dynamicDataSourceTypeSymbol) + { + var methodSymbol = (IMethodSymbol)context.Symbol; + + foreach (AttributeData methodAttribute in methodSymbol.GetAttributes()) + { + if (SymbolEqualityComparer.Default.Equals(methodAttribute.AttributeClass, dynamicDataAttributeSymbol)) + { + AnalyzeAttribute(context, methodAttribute, dynamicDataSourceTypeSymbol); + } + } + } + + private static void AnalyzeAttribute(SymbolAnalysisContext context, AttributeData attributeData, INamedTypeSymbol dynamicDataSourceTypeSymbol) + { + if (attributeData.ApplicationSyntaxReference?.GetSyntax(context.CancellationToken) is { } syntax && + attributeData.AttributeConstructor?.Parameters.Any(p => dynamicDataSourceTypeSymbol.Equals(p.Type, SymbolEqualityComparer.Default)) == true) + { + context.ReportDiagnostic(syntax.CreateDiagnostic(PreferAutoDetectRule)); + } + } +} diff --git a/src/Analyzers/MSTest.Analyzers/Helpers/DiagnosticIds.cs b/src/Analyzers/MSTest.Analyzers/Helpers/DiagnosticIds.cs index fd6aac276f..0b2cbe6f9e 100644 --- a/src/Analyzers/MSTest.Analyzers/Helpers/DiagnosticIds.cs +++ b/src/Analyzers/MSTest.Analyzers/Helpers/DiagnosticIds.cs @@ -56,4 +56,5 @@ internal static class DiagnosticIds public const string FlowTestContextCancellationTokenRuleId = "MSTEST0049"; public const string GlobalTestFixtureShouldBeValidRuleId = "MSTEST0050"; public const string AssertThrowsShouldContainSingleStatementRuleId = "MSTEST0051"; + public const string AvoidExplicitDynamicDataSourceTypeRuleId = "MSTEST0052"; } diff --git a/src/Analyzers/MSTest.Analyzers/Resources.Designer.cs b/src/Analyzers/MSTest.Analyzers/Resources.Designer.cs index 2fbc596ab7..682130ac4a 100644 --- a/src/Analyzers/MSTest.Analyzers/Resources.Designer.cs +++ b/src/Analyzers/MSTest.Analyzers/Resources.Designer.cs @@ -10,8 +10,8 @@ namespace MSTest.Analyzers { using System; - - + + /// /// A strongly-typed resource class, for looking up localized strings, etc. /// @@ -23,15 +23,15 @@ namespace MSTest.Analyzers { [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { - + private static global::System.Resources.ResourceManager resourceMan; - + private static global::System.Globalization.CultureInfo resourceCulture; - + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } - + /// /// Returns the cached ResourceManager instance used by this class. /// @@ -45,7 +45,7 @@ internal Resources() { return resourceMan; } } - + /// /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. @@ -59,7 +59,7 @@ internal Resources() { resourceCulture = value; } } - + /// /// Looks up a localized string similar to Methods marked with '[AssemblyCleanup]' should follow the following layout to be valid: ///-it can't be declared on a generic class @@ -78,7 +78,7 @@ internal static string AssemblyCleanupShouldBeValidDescription { return ResourceManager.GetString("AssemblyCleanupShouldBeValidDescription", resourceCulture); } } - + /// /// Looks up a localized string similar to AssemblyCleanup method '{0}' signature is invalid. /// @@ -87,7 +87,7 @@ internal static string AssemblyCleanupShouldBeValidMessageFormat { return ResourceManager.GetString("AssemblyCleanupShouldBeValidMessageFormat", resourceCulture); } } - + /// /// Looks up a localized string similar to AssemblyCleanup methods should have valid layout. /// @@ -96,7 +96,7 @@ internal static string AssemblyCleanupShouldBeValidTitle { return ResourceManager.GetString("AssemblyCleanupShouldBeValidTitle", resourceCulture); } } - + /// /// Looks up a localized string similar to Methods marked with '[AssemblyInitialize]' should follow the following layout to be valid: ///-it can't be declared on a generic class @@ -116,7 +116,7 @@ internal static string AssemblyInitializeShouldBeValidDescription { return ResourceManager.GetString("AssemblyInitializeShouldBeValidDescription", resourceCulture); } } - + /// /// Looks up a localized string similar to AssemblyInitialize method '{0}' signature is invalid. /// @@ -125,7 +125,7 @@ internal static string AssemblyInitializeShouldBeValidMessageFormat { return ResourceManager.GetString("AssemblyInitializeShouldBeValidMessageFormat", resourceCulture); } } - + /// /// Looks up a localized string similar to AssemblyInitialize methods should have valid layout. /// @@ -134,7 +134,7 @@ internal static string AssemblyInitializeShouldBeValidTitle { return ResourceManager.GetString("AssemblyInitializeShouldBeValidTitle", resourceCulture); } } - + /// /// Looks up a localized string similar to Prefer adding an additional assertion that checks for null. /// @@ -143,7 +143,7 @@ internal static string AssertionArgsShouldAvoidConditionalAccessMessageFormat { return ResourceManager.GetString("AssertionArgsShouldAvoidConditionalAccessMessageFormat", resourceCulture); } } - + /// /// Looks up a localized string similar to Avoid conditional access in assertions. /// @@ -152,7 +152,7 @@ internal static string AssertionArgsShouldAvoidConditionalAccessTitle { return ResourceManager.GetString("AssertionArgsShouldAvoidConditionalAccessTitle", resourceCulture); } } - + /// /// Looks up a localized string similar to 'Assert.AreEqual', 'Assert.AreNotEqual', 'Assert.AreSame' and 'Assert.AreNotSame' expects the expected value to be passed first and the actual value to be passed as second argument.. /// @@ -161,7 +161,7 @@ internal static string AssertionArgsShouldBePassedInCorrectOrderDescription { return ResourceManager.GetString("AssertionArgsShouldBePassedInCorrectOrderDescription", resourceCulture); } } - + /// /// Looks up a localized string similar to Assertion arguments should be passed in the correct order. 'actual' and 'expected'/'notExpected' arguments have been swapped.. /// @@ -170,7 +170,7 @@ internal static string AssertionArgsShouldBePassedInCorrectOrderMessageFormat { return ResourceManager.GetString("AssertionArgsShouldBePassedInCorrectOrderMessageFormat", resourceCulture); } } - + /// /// Looks up a localized string similar to Assertion arguments should be passed in the correct order. /// @@ -179,7 +179,34 @@ internal static string AssertionArgsShouldBePassedInCorrectOrderTitle { return ResourceManager.GetString("AssertionArgsShouldBePassedInCorrectOrderTitle", resourceCulture); } } - + + /// + /// Looks up a localized string similar to Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws.. + /// + internal static string AssertThrowsShouldContainSingleStatementDescription { + get { + return ResourceManager.GetString("AssertThrowsShouldContainSingleStatementDescription", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Assert.Throws should contain only a single statement/expression. + /// + internal static string AssertThrowsShouldContainSingleStatementMessageFormat { + get { + return ResourceManager.GetString("AssertThrowsShouldContainSingleStatementMessageFormat", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Assert.Throws should contain only a single statement/expression. + /// + internal static string AssertThrowsShouldContainSingleStatementTitle { + get { + return ResourceManager.GetString("AssertThrowsShouldContainSingleStatementTitle", resourceCulture); + } + } + /// /// Looks up a localized string similar to Use 'Assert.AreEqual'/'Assert.AreNotEqual' instead of 'Assert.AreSame'/'Assert.AreNotSame' when comparing value types. Passing a value type to 'Assert.AreSame'/'Assert.AreNotSame' will be boxed (creating a new object). Because 'Assert.AreSame'/'Assert.AreNotSame' does the comparison by reference, 'Assert.AreSame' will fail when boxing happens, and 'Assert.AreNotSame' will always pass.. /// @@ -188,7 +215,7 @@ internal static string AvoidAssertAreSameWithValueTypesDescription { return ResourceManager.GetString("AvoidAssertAreSameWithValueTypesDescription", resourceCulture); } } - + /// /// Looks up a localized string similar to Use '{0}' instead of '{1}' when comparing value types. /// @@ -197,7 +224,7 @@ internal static string AvoidAssertAreSameWithValueTypesMessageFormat { return ResourceManager.GetString("AvoidAssertAreSameWithValueTypesMessageFormat", resourceCulture); } } - + /// /// Looks up a localized string similar to Don't use 'Assert.AreSame' or 'Assert.AreNotSame' with value types. /// @@ -206,7 +233,7 @@ internal static string AvoidAssertAreSameWithValueTypesTitle { return ResourceManager.GetString("AvoidAssertAreSameWithValueTypesTitle", resourceCulture); } } - + /// /// Looks up a localized string similar to Prefer 'Assert.ThrowsExactly' or 'Assert.ThrowsExactlyAsync' over '[ExpectedException]' as it ensures that only the expected call throws the expected exception. The assert APIs also provide more flexibility and allow you to assert extra properties of the exception.. /// @@ -215,7 +242,7 @@ internal static string AvoidExpectedExceptionAttributeDescription { return ResourceManager.GetString("AvoidExpectedExceptionAttributeDescription", resourceCulture); } } - + /// /// Looks up a localized string similar to Prefer 'Assert.ThrowsExactly/ThrowsExactlyAsync' over '[ExpectedException]'. /// @@ -224,7 +251,7 @@ internal static string AvoidExpectedExceptionAttributeMessageFormat { return ResourceManager.GetString("AvoidExpectedExceptionAttributeMessageFormat", resourceCulture); } } - + /// /// Looks up a localized string similar to Avoid '[ExpectedException]'. /// @@ -233,7 +260,25 @@ internal static string AvoidExpectedExceptionAttributeTitle { return ResourceManager.GetString("AvoidExpectedExceptionAttributeTitle", resourceCulture); } } - + + /// + /// Looks up a localized string similar to Remove the 'DynamicDataSourceType' argument to use the default auto detect behavior. + /// + internal static string AvoidExplicitDynamicDataSourceTypeMessageFormat { + get { + return ResourceManager.GetString("AvoidExplicitDynamicDataSourceTypeMessageFormat", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Avoid passing an explicit 'DynamicDataSourceType' and use the default auto detect behavior. + /// + internal static string AvoidExplicitDynamicDataSourceTypeTitle { + get { + return ResourceManager.GetString("AvoidExplicitDynamicDataSourceTypeTitle", resourceCulture); + } + } + /// /// Looks up a localized string similar to Do not assert inside 'async void' methods, local functions, or lambdas. Exceptions that are thrown in this context will be unhandled exceptions. When using VSTest under .NET Framework, they will be silently swallowed. When using Microsoft.Testing.Platform or VSTest under modern .NET, they may crash the process.. /// @@ -242,7 +287,7 @@ internal static string AvoidUsingAssertsInAsyncVoidContextDescription { return ResourceManager.GetString("AvoidUsingAssertsInAsyncVoidContextDescription", resourceCulture); } } - + /// /// Looks up a localized string similar to Do not assert inside 'async void' methods, local functions, or lambdas because they may not fail the test. /// @@ -251,7 +296,7 @@ internal static string AvoidUsingAssertsInAsyncVoidContextMessageFormat { return ResourceManager.GetString("AvoidUsingAssertsInAsyncVoidContextMessageFormat", resourceCulture); } } - + /// /// Looks up a localized string similar to Do not assert inside 'async void' contexts. /// @@ -260,7 +305,7 @@ internal static string AvoidUsingAssertsInAsyncVoidContextTitle { return ResourceManager.GetString("AvoidUsingAssertsInAsyncVoidContextTitle", resourceCulture); } } - + /// /// Looks up a localized string similar to Methods marked with '[ClassCleanup]' should follow the following layout to be valid: ///-it can't be declared on a generic class without the 'InheritanceBehavior' mode is set @@ -278,7 +323,7 @@ internal static string ClassCleanupShouldBeValidDescription { return ResourceManager.GetString("ClassCleanupShouldBeValidDescription", resourceCulture); } } - + /// /// Looks up a localized string similar to ClassCleanup method '{0}' signature is invalid. /// @@ -287,7 +332,7 @@ internal static string ClassCleanupShouldBeValidMessageFormat { return ResourceManager.GetString("ClassCleanupShouldBeValidMessageFormat", resourceCulture); } } - + /// /// Looks up a localized string similar to ClassCleanup methods should have valid layout. /// @@ -296,7 +341,7 @@ internal static string ClassCleanupShouldBeValidTitle { return ResourceManager.GetString("ClassCleanupShouldBeValidTitle", resourceCulture); } } - + /// /// Looks up a localized string similar to Methods marked with '[ClassInitialize]' should follow the following layout to be valid: ///-it can't be declared on a generic class without the 'InheritanceBehavior' mode is set @@ -314,7 +359,7 @@ internal static string ClassInitializeShouldBeValidDescription { return ResourceManager.GetString("ClassInitializeShouldBeValidDescription", resourceCulture); } } - + /// /// Looks up a localized string similar to ClassInitialize method '{0}' signature is invalid. /// @@ -323,7 +368,7 @@ internal static string ClassInitializeShouldBeValidMessageFormat { return ResourceManager.GetString("ClassInitializeShouldBeValidMessageFormat", resourceCulture); } } - + /// /// Looks up a localized string similar to ClassInitialize methods should have valid layout. /// @@ -332,7 +377,7 @@ internal static string ClassInitializeShouldBeValidTitle { return ResourceManager.GetString("ClassInitializeShouldBeValidTitle", resourceCulture); } } - + /// /// Looks up a localized string similar to DataRow entry should have the following layout to be valid: ///- should only be set on a test method; @@ -344,7 +389,7 @@ internal static string DataRowShouldBeValidDescription { return ResourceManager.GetString("DataRowShouldBeValidDescription", resourceCulture); } } - + /// /// Looks up a localized string similar to DataRow argument count should match method parameter count (constructor arguments: {0}, method parameters: {1}). /// @@ -353,7 +398,7 @@ internal static string DataRowShouldBeValidMessageFormat_ArgumentCountMismatch { return ResourceManager.GetString("DataRowShouldBeValidMessageFormat_ArgumentCountMismatch", resourceCulture); } } - + /// /// Looks up a localized string similar to DataRow argument types do not match method parameter types. {0}. /// @@ -362,7 +407,7 @@ internal static string DataRowShouldBeValidMessageFormat_ArgumentTypeMismatch { return ResourceManager.GetString("DataRowShouldBeValidMessageFormat_ArgumentTypeMismatch", resourceCulture); } } - + /// /// Looks up a localized string similar to Found two conflicting types for generic parameter '{0}'. The conflicting types are '{1}' and '{2}'.. /// @@ -371,7 +416,7 @@ internal static string DataRowShouldBeValidMessageFormat_GenericTypeArgumentConf return ResourceManager.GetString("DataRowShouldBeValidMessageFormat_GenericTypeArgumentConflictingTypes", resourceCulture); } } - + /// /// Looks up a localized string similar to The type of the generic parameter '{0}' could not be inferred.. /// @@ -380,7 +425,7 @@ internal static string DataRowShouldBeValidMessageFormat_GenericTypeArgumentNotR return ResourceManager.GetString("DataRowShouldBeValidMessageFormat_GenericTypeArgumentNotResolved", resourceCulture); } } - + /// /// Looks up a localized string similar to DataRow should only be set on a test method. /// @@ -389,7 +434,7 @@ internal static string DataRowShouldBeValidMessageFormat_OnTestMethod { return ResourceManager.GetString("DataRowShouldBeValidMessageFormat_OnTestMethod", resourceCulture); } } - + /// /// Looks up a localized string similar to Parameter '{0}' expects type '{1}', but the provided value has type '{2}'. /// @@ -398,7 +443,7 @@ internal static string DataRowShouldBeValidMessageFormat_ParameterMismatch { return ResourceManager.GetString("DataRowShouldBeValidMessageFormat_ParameterMismatch", resourceCulture); } } - + /// /// Looks up a localized string similar to DataRow should be valid. /// @@ -407,7 +452,7 @@ internal static string DataRowShouldBeValidTitle { return ResourceManager.GetString("DataRowShouldBeValidTitle", resourceCulture); } } - + /// /// Looks up a localized string similar to Do not negate boolean assertions, instead use the opposite assertion. /// @@ -416,7 +461,7 @@ internal static string DoNotNegateBooleanAssertionMessageFormat { return ResourceManager.GetString("DoNotNegateBooleanAssertionMessageFormat", resourceCulture); } } - + /// /// Looks up a localized string similar to Do not negate boolean assertions. /// @@ -425,7 +470,7 @@ internal static string DoNotNegateBooleanAssertionTitle { return ResourceManager.GetString("DoNotNegateBooleanAssertionTitle", resourceCulture); } } - + /// /// Looks up a localized string similar to Do not store TestContext in a static member. /// @@ -434,7 +479,7 @@ internal static string DoNotStoreStaticTestContextAnalyzerMessageFormat { return ResourceManager.GetString("DoNotStoreStaticTestContextAnalyzerMessageFormat", resourceCulture); } } - + /// /// Looks up a localized string similar to Do not store TestContext in a static member. /// @@ -443,7 +488,7 @@ internal static string DoNotStoreStaticTestContextAnalyzerTitle { return ResourceManager.GetString("DoNotStoreStaticTestContextAnalyzerTitle", resourceCulture); } } - + /// /// Looks up a localized string similar to Shadowing test members could cause testing issues (such as NRE).. /// @@ -452,7 +497,7 @@ internal static string DoNotUseShadowingDescription { return ResourceManager.GetString("DoNotUseShadowingDescription", resourceCulture); } } - + /// /// Looks up a localized string similar to Member '{0}' already exists in the base class. /// @@ -461,7 +506,7 @@ internal static string DoNotUseShadowingMessageFormat { return ResourceManager.GetString("DoNotUseShadowingMessageFormat", resourceCulture); } } - + /// /// Looks up a localized string similar to Do not use shadowing. /// @@ -470,7 +515,7 @@ internal static string DoNotUseShadowingTitle { return ResourceManager.GetString("DoNotUseShadowingTitle", resourceCulture); } } - + /// /// Looks up a localized string similar to 'System.ComponentModel.DescriptionAttribute' has no effect in the context of tests and you likely wanted to use 'Microsoft.VisualStudio.TestTools.UnitTesting.DescriptionAttribute' instead.. /// @@ -479,7 +524,7 @@ internal static string DoNotUseSystemDescriptionAttributeDescription { return ResourceManager.GetString("DoNotUseSystemDescriptionAttributeDescription", resourceCulture); } } - + /// /// Looks up a localized string similar to Did you mean to be using 'Microsoft.VisualStudio.TestTools.UnitTesting.DescriptionAttribute'?. /// @@ -488,7 +533,7 @@ internal static string DoNotUseSystemDescriptionAttributeMessageFormat { return ResourceManager.GetString("DoNotUseSystemDescriptionAttributeMessageFormat", resourceCulture); } } - + /// /// Looks up a localized string similar to 'System.ComponentModel.DescriptionAttribute' has no effect on test methods. /// @@ -497,7 +542,7 @@ internal static string DoNotUseSystemDescriptionAttributeTitle { return ResourceManager.GetString("DoNotUseSystemDescriptionAttributeTitle", resourceCulture); } } - + /// /// Looks up a localized string similar to Do not duplicate 'DataRow' attributes. This is usually a copy/paste error. The attribute indices are '{0}' and '{1}'.. /// @@ -506,7 +551,7 @@ internal static string DuplicateDataRowMessageFormat { return ResourceManager.GetString("DuplicateDataRowMessageFormat", resourceCulture); } } - + /// /// Looks up a localized string similar to Avoid duplicated 'DataRow' entries. /// @@ -515,7 +560,7 @@ internal static string DuplicateDataRowTitle { return ResourceManager.GetString("DuplicateDataRowTitle", resourceCulture); } } - + /// /// Looks up a localized string similar to 'DynamicData' entry should have the following layout to be valid: ///- should only be set on a test method; @@ -527,7 +572,7 @@ internal static string DynamicDataShouldBeValidDescription { return ResourceManager.GetString("DynamicDataShouldBeValidDescription", resourceCulture); } } - + /// /// Looks up a localized string similar to '[DynamicData]' data member '{0}.{1}' signature is invalid. /// @@ -536,7 +581,7 @@ internal static string DynamicDataShouldBeValidMessageFormat_DataMemberSignature return ResourceManager.GetString("DynamicDataShouldBeValidMessageFormat_DataMemberSignature", resourceCulture); } } - + /// /// Looks up a localized string similar to '[DynamicData]' display name method '{0}.{1}' signature is invalid. /// @@ -545,7 +590,7 @@ internal static string DynamicDataShouldBeValidMessageFormat_DisplayMethodSignat return ResourceManager.GetString("DynamicDataShouldBeValidMessageFormat_DisplayMethodSignature", resourceCulture); } } - + /// /// Looks up a localized string similar to '[DynamicData]' member '{0}.{1}' should be a method. /// @@ -554,7 +599,7 @@ internal static string DynamicDataShouldBeValidMessageFormat_MemberMethod { return ResourceManager.GetString("DynamicDataShouldBeValidMessageFormat_MemberMethod", resourceCulture); } } - + /// /// Looks up a localized string similar to '[DynamicData]' member '{0}.{1}' cannot be found. /// @@ -563,7 +608,7 @@ internal static string DynamicDataShouldBeValidMessageFormat_MemberNotFound { return ResourceManager.GetString("DynamicDataShouldBeValidMessageFormat_MemberNotFound", resourceCulture); } } - + /// /// Looks up a localized string similar to '[DynamicData]' referenced member '{0}.{1}' should return 'IEnumerable<object[]>', 'IEnumerable<Tuple>` or 'IEnumerable<ValueTuple>'. /// @@ -572,7 +617,7 @@ internal static string DynamicDataShouldBeValidMessageFormat_MemberType { return ResourceManager.GetString("DynamicDataShouldBeValidMessageFormat_MemberType", resourceCulture); } } - + /// /// Looks up a localized string similar to '[DynamicData]' should only be set on a test method. /// @@ -581,16 +626,7 @@ internal static string DynamicDataShouldBeValidMessageFormat_OnTestMethod { return ResourceManager.GetString("DynamicDataShouldBeValidMessageFormat_OnTestMethod", resourceCulture); } } - - /// - /// Looks up a localized string similar to '[DynamicData]' member '{0}.{1}' is a method so you should use 'DynamicDataSourceType.AutoDetect' or 'DynamicDataSourceType.Method' (auto detect is the default when not specified explicitly, and is recommended). - /// - internal static string DynamicDataShouldBeValidMessageFormat_SourceTypeMethod { - get { - return ResourceManager.GetString("DynamicDataShouldBeValidMessageFormat_SourceTypeMethod", resourceCulture); - } - } - + /// /// Looks up a localized string similar to '[DynamicData]' member '{0}.{1}' is a field so you should use 'DynamicDataSourceType.AutoDetect' or 'DynamicDataSourceType.Field' (auto detect is the default when not specified explicitly, and is recommended). /// @@ -601,14 +637,14 @@ internal static string DynamicDataShouldBeValidMessageFormat_SourceTypeField { } /// - /// Looks up a localized string similar to '[DynamicData]' member '{0}.{1}' is not a property nor a method. Only properties and methods are supported.. + /// Looks up a localized string similar to '[DynamicData]' member '{0}.{1}' is a method so you should use 'DynamicDataSourceType.AutoDetect' or 'DynamicDataSourceType.Method' (auto detect is the default when not specified explicitly, and is recommended). /// - internal static string DynamicDataShouldBeValidMessageFormat_SourceTypeNotPropertyOrMethod { + internal static string DynamicDataShouldBeValidMessageFormat_SourceTypeMethod { get { - return ResourceManager.GetString("DynamicDataShouldBeValidMessageFormat_SourceTypeNotPropertyOrMethod", resourceCulture); + return ResourceManager.GetString("DynamicDataShouldBeValidMessageFormat_SourceTypeMethod", resourceCulture); } } - + /// /// Looks up a localized string similar to '[DynamicData]' member '{0}.{1}' is not a property, method, or field. Only properties, methods, and fields are supported.. /// @@ -618,6 +654,15 @@ internal static string DynamicDataShouldBeValidMessageFormat_SourceTypeNotProper } } + /// + /// Looks up a localized string similar to '[DynamicData]' member '{0}.{1}' is not a property nor a method. Only properties and methods are supported.. + /// + internal static string DynamicDataShouldBeValidMessageFormat_SourceTypeNotPropertyOrMethod { + get { + return ResourceManager.GetString("DynamicDataShouldBeValidMessageFormat_SourceTypeNotPropertyOrMethod", resourceCulture); + } + } + /// /// Looks up a localized string similar to '[DynamicData]' member '{0}.{1}' is a property so you should use 'DynamicDataSourceType.AutoDetect' or 'DynamicDataSourceType.Property' (auto detect is the default when not specified explicitly, and is recommended). /// @@ -626,7 +671,7 @@ internal static string DynamicDataShouldBeValidMessageFormat_SourceTypeProperty return ResourceManager.GetString("DynamicDataShouldBeValidMessageFormat_SourceTypeProperty", resourceCulture); } } - + /// /// Looks up a localized string similar to '[DynamicData]' member '{0}.{1}' is found more than once. /// @@ -635,7 +680,7 @@ internal static string DynamicDataShouldBeValidMessageFormat_TooManyMembers { return ResourceManager.GetString("DynamicDataShouldBeValidMessageFormat_TooManyMembers", resourceCulture); } } - + /// /// Looks up a localized string similar to DynamicData should be valid. /// @@ -644,7 +689,7 @@ internal static string DynamicDataShouldBeValidTitle { return ResourceManager.GetString("DynamicDataShouldBeValidTitle", resourceCulture); } } - + /// /// Looks up a localized string similar to When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationTokenSource.Token to enable cooperative cancellation and respect test timeouts.. /// @@ -653,7 +698,7 @@ internal static string FlowTestContextCancellationTokenDescription { return ResourceManager.GetString("FlowTestContextCancellationTokenDescription", resourceCulture); } } - + /// /// Looks up a localized string similar to Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationTokenSource.Token'. /// @@ -662,7 +707,7 @@ internal static string FlowTestContextCancellationTokenMessageFormat { return ResourceManager.GetString("FlowTestContextCancellationTokenMessageFormat", resourceCulture); } } - + /// /// Looks up a localized string similar to Flow TestContext.CancellationToken to async operations. /// @@ -671,7 +716,7 @@ internal static string FlowTestContextCancellationTokenTitle { return ResourceManager.GetString("FlowTestContextCancellationTokenTitle", resourceCulture); } } - + /// /// Looks up a localized string similar to Methods marked with '[GlobalTestInitialize]' or '[GlobalTestCleanup]' should follow the following layout to be valid: ///-it can't be declared on a generic class @@ -690,7 +735,7 @@ internal static string GlobalTestFixtureShouldBeValidDescription { return ResourceManager.GetString("GlobalTestFixtureShouldBeValidDescription", resourceCulture); } } - + /// /// Looks up a localized string similar to Global test fixture method '{0}' signature is invalid. /// @@ -699,7 +744,7 @@ internal static string GlobalTestFixtureShouldBeValidMessageFormat { return ResourceManager.GetString("GlobalTestFixtureShouldBeValidMessageFormat", resourceCulture); } } - + /// /// Looks up a localized string similar to GlobalTestInitialize and GlobalTestCleanup methods should have valid layout. /// @@ -708,7 +753,7 @@ internal static string GlobalTestFixtureShouldBeValidTitle { return ResourceManager.GetString("GlobalTestFixtureShouldBeValidTitle", resourceCulture); } } - + /// /// Looks up a localized string similar to Use 'Assert.Fail' instead of an always-failing 'Assert.{0}' assert. /// @@ -717,7 +762,7 @@ internal static string PreferAssertFailOverAlwaysFalseConditionsMessageFormat { return ResourceManager.GetString("PreferAssertFailOverAlwaysFalseConditionsMessageFormat", resourceCulture); } } - + /// /// Looks up a localized string similar to Use 'Assert.Fail' instead of an always-failing assert. /// @@ -726,7 +771,7 @@ internal static string PreferAssertFailOverAlwaysFalseConditionsTitle { return ResourceManager.GetString("PreferAssertFailOverAlwaysFalseConditionsTitle", resourceCulture); } } - + /// /// Looks up a localized string similar to Prefer constructors over TestInitialize methods. /// @@ -735,7 +780,7 @@ internal static string PreferConstructorOverTestInitializeMessageFormat { return ResourceManager.GetString("PreferConstructorOverTestInitializeMessageFormat", resourceCulture); } } - + /// /// Looks up a localized string similar to Prefer constructors over TestInitialize methods. /// @@ -744,7 +789,7 @@ internal static string PreferConstructorOverTestInitializeTitle { return ResourceManager.GetString("PreferConstructorOverTestInitializeTitle", resourceCulture); } } - + /// /// Looks up a localized string similar to Prefer 'Dispose' over TestCleanup methods. /// @@ -753,7 +798,7 @@ internal static string PreferDisposeOverTestCleanupMessageFormat { return ResourceManager.GetString("PreferDisposeOverTestCleanupMessageFormat", resourceCulture); } } - + /// /// Looks up a localized string similar to Prefer 'Dispose' over TestCleanup methods. /// @@ -762,7 +807,7 @@ internal static string PreferDisposeOverTestCleanupTitle { return ResourceManager.GetString("PreferDisposeOverTestCleanupTitle", resourceCulture); } } - + /// /// Looks up a localized string similar to Prefer TestCleanup over 'Dispose' methods. /// @@ -771,7 +816,7 @@ internal static string PreferTestCleanupOverDisposeMessageFormat { return ResourceManager.GetString("PreferTestCleanupOverDisposeMessageFormat", resourceCulture); } } - + /// /// Looks up a localized string similar to Prefer TestCleanup over 'Dispose' methods. /// @@ -780,7 +825,7 @@ internal static string PreferTestCleanupOverDisposeTitle { return ResourceManager.GetString("PreferTestCleanupOverDisposeTitle", resourceCulture); } } - + /// /// Looks up a localized string similar to Prefer TestInitialize methods over constructors. /// @@ -789,7 +834,7 @@ internal static string PreferTestInitializeOverConstructorMessageFormat { return ResourceManager.GetString("PreferTestInitializeOverConstructorMessageFormat", resourceCulture); } } - + /// /// Looks up a localized string similar to Prefer TestInitialize methods over constructors. /// @@ -798,7 +843,7 @@ internal static string PreferTestInitializeOverConstructorTitle { return ResourceManager.GetString("PreferTestInitializeOverConstructorTitle", resourceCulture); } } - + /// /// Looks up a localized string similar to 'DataTestMethodAttribute' is obsolete and provides no additional functionality over 'TestMethodAttribute'. Use 'TestMethodAttribute' for all test methods, including parameterized tests.. /// @@ -807,7 +852,7 @@ internal static string PreferTestMethodOverDataTestMethodAnalyzerDescription { return ResourceManager.GetString("PreferTestMethodOverDataTestMethodAnalyzerDescription", resourceCulture); } } - + /// /// Looks up a localized string similar to 'DataTestMethod' is obsolete. Use 'TestMethod' instead.. /// @@ -816,7 +861,7 @@ internal static string PreferTestMethodOverDataTestMethodAnalyzerMessageFormat { return ResourceManager.GetString("PreferTestMethodOverDataTestMethodAnalyzerMessageFormat", resourceCulture); } } - + /// /// Looks up a localized string similar to Prefer 'TestMethod' over 'DataTestMethod'. /// @@ -825,7 +870,7 @@ internal static string PreferTestMethodOverDataTestMethodAnalyzerTitle { return ResourceManager.GetString("PreferTestMethodOverDataTestMethodAnalyzerTitle", resourceCulture); } } - + /// /// Looks up a localized string similar to Public methods should be test methods (marked with `[TestMethod]`).. /// @@ -834,7 +879,7 @@ internal static string PublicMethodShouldBeTestMethodAnalyzerDescription { return ResourceManager.GetString("PublicMethodShouldBeTestMethodAnalyzerDescription", resourceCulture); } } - + /// /// Looks up a localized string similar to Public method '{0}' should be a test method. /// @@ -843,7 +888,7 @@ internal static string PublicMethodShouldBeTestMethodAnalyzerFormat { return ResourceManager.GetString("PublicMethodShouldBeTestMethodAnalyzerFormat", resourceCulture); } } - + /// /// Looks up a localized string similar to Public methods should be test methods. /// @@ -852,7 +897,7 @@ internal static string PublicMethodShouldBeTestMethodAnalyzerTitle { return ResourceManager.GetString("PublicMethodShouldBeTestMethodAnalyzerTitle", resourceCulture); } } - + /// /// Looks up a localized string similar to It's considered a good practice to have only test classes marked public in a test project.. /// @@ -861,7 +906,7 @@ internal static string PublicTypeShouldBeTestClassDescription { return ResourceManager.GetString("PublicTypeShouldBeTestClassDescription", resourceCulture); } } - + /// /// Looks up a localized string similar to Public type '{0}' should be marked with '[TestClass]' or changed to 'internal'. /// @@ -870,7 +915,7 @@ internal static string PublicTypeShouldBeTestClassMessageFormat { return ResourceManager.GetString("PublicTypeShouldBeTestClassMessageFormat", resourceCulture); } } - + /// /// Looks up a localized string similar to Public types should be test classes. /// @@ -879,7 +924,7 @@ internal static string PublicTypeShouldBeTestClassTitle { return ResourceManager.GetString("PublicTypeShouldBeTestClassTitle", resourceCulture); } } - + /// /// Looks up a localized string similar to Review or remove the assertion as its condition is known to be always true. /// @@ -888,7 +933,7 @@ internal static string ReviewAlwaysTrueAssertConditionAnalyzerMessageFormat { return ResourceManager.GetString("ReviewAlwaysTrueAssertConditionAnalyzerMessageFormat", resourceCulture); } } - + /// /// Looks up a localized string similar to Assertion condition is always true. /// @@ -897,7 +942,7 @@ internal static string ReviewAlwaysTrueAssertConditionAnalyzerTitle { return ResourceManager.GetString("ReviewAlwaysTrueAssertConditionAnalyzerTitle", resourceCulture); } } - + /// /// Looks up a localized string similar to Use 'Assert.{0}' instead of 'StringAssert.{1}'. /// @@ -906,7 +951,7 @@ internal static string StringAssertToAssertMessageFormat { return ResourceManager.GetString("StringAssertToAssertMessageFormat", resourceCulture); } } - + /// /// Looks up a localized string similar to Use 'Assert' instead of 'StringAssert'. /// @@ -915,7 +960,7 @@ internal static string StringAssertToAssertTitle { return ResourceManager.GetString("StringAssertToAssertTitle", resourceCulture); } } - + /// /// Looks up a localized string similar to Test classes, classes marked with the '[TestClass]' attribute, should respect the following layout to be considered valid by MSTest: ///- it should be 'public' (or 'internal' if '[assembly: DiscoverInternals]' attribute is set) @@ -927,7 +972,7 @@ internal static string TestClassShouldBeValidDescription { return ResourceManager.GetString("TestClassShouldBeValidDescription", resourceCulture); } } - + /// /// Looks up a localized string similar to Test class '{0}' should be valid. /// @@ -936,7 +981,7 @@ internal static string TestClassShouldBeValidMessageFormat { return ResourceManager.GetString("TestClassShouldBeValidMessageFormat", resourceCulture); } } - + /// /// Looks up a localized string similar to Test classes should have valid layout. /// @@ -945,7 +990,7 @@ internal static string TestClassShouldBeValidTitle { return ResourceManager.GetString("TestClassShouldBeValidTitle", resourceCulture); } } - + /// /// Looks up a localized string similar to Test class should have at least one test method or be 'static' with method(s) marked by '[AssemblyInitialize]' and/or '[AssemblyCleanup]'.. /// @@ -954,7 +999,7 @@ internal static string TestClassShouldHaveTestMethodDescription { return ResourceManager.GetString("TestClassShouldHaveTestMethodDescription", resourceCulture); } } - + /// /// Looks up a localized string similar to Test class '{0}' should have at least one test method or be 'static' with method(s) marked by '[AssemblyInitialize]' and/or '[AssemblyCleanup]'. /// @@ -963,7 +1008,7 @@ internal static string TestClassShouldHaveTestMethodMessageFormat { return ResourceManager.GetString("TestClassShouldHaveTestMethodMessageFormat", resourceCulture); } } - + /// /// Looks up a localized string similar to Test class should have test method. /// @@ -972,7 +1017,7 @@ internal static string TestClassShouldHaveTestMethodTitle { return ResourceManager.GetString("TestClassShouldHaveTestMethodTitle", resourceCulture); } } - + /// /// Looks up a localized string similar to Methods marked with '[TestCleanup]' should follow the following layout to be valid: ///-it should be 'public' @@ -993,7 +1038,7 @@ internal static string TestCleanupShouldBeValidDescription { return ResourceManager.GetString("TestCleanupShouldBeValidDescription", resourceCulture); } } - + /// /// Looks up a localized string similar to TestCleanup method '{0}' signature is invalid. /// @@ -1002,7 +1047,7 @@ internal static string TestCleanupShouldBeValidMessageFormat { return ResourceManager.GetString("TestCleanupShouldBeValidMessageFormat", resourceCulture); } } - + /// /// Looks up a localized string similar to TestCleanup method should have valid layout. /// @@ -1011,7 +1056,7 @@ internal static string TestCleanupShouldBeValidTitle { return ResourceManager.GetString("TestCleanupShouldBeValidTitle", resourceCulture); } } - + /// /// Looks up a localized string similar to Some TestContext properties are only available during test execution and cannot be accessed in assembly initialize, class initialize, class cleanup, or assembly cleanup methods.. /// @@ -1020,7 +1065,7 @@ internal static string TestContextPropertyUsageDescription { return ResourceManager.GetString("TestContextPropertyUsageDescription", resourceCulture); } } - + /// /// Looks up a localized string similar to TestContext property '{0}' cannot be accessed in '{1}' method. /// @@ -1029,7 +1074,7 @@ internal static string TestContextPropertyUsageMessageFormat { return ResourceManager.GetString("TestContextPropertyUsageMessageFormat", resourceCulture); } } - + /// /// Looks up a localized string similar to TestContext property cannot be accessed in this context. /// @@ -1038,7 +1083,7 @@ internal static string TestContextPropertyUsageTitle { return ResourceManager.GetString("TestContextPropertyUsageTitle", resourceCulture); } } - + /// /// Looks up a localized string similar to 'TestContext' should be a non-static field or property assigned in constructor or for a property set by MSTest, it should follow the layout: ///- it should be 'public' regardless of whether '[assembly: DiscoverInternals]' attribute is set or not. @@ -1050,7 +1095,7 @@ internal static string TestContextShouldBeValidDescription { return ResourceManager.GetString("TestContextShouldBeValidDescription", resourceCulture); } } - + /// /// Looks up a localized string similar to Property 'TestContext' should be valid. /// @@ -1059,7 +1104,7 @@ internal static string TestContextShouldBeValidMessageFormat { return ResourceManager.GetString("TestContextShouldBeValidMessageFormat", resourceCulture); } } - + /// /// Looks up a localized string similar to Test context property should have valid layout. /// @@ -1068,7 +1113,7 @@ internal static string TestContextShouldBeValidTitle { return ResourceManager.GetString("TestContextShouldBeValidTitle", resourceCulture); } } - + /// /// Looks up a localized string similar to Methods marked with '[TestInitialize]' should follow the following layout to be valid: ///-it should be 'public' @@ -1089,7 +1134,7 @@ internal static string TestInitializeShouldBeValidDescription { return ResourceManager.GetString("TestInitializeShouldBeValidDescription", resourceCulture); } } - + /// /// Looks up a localized string similar to TestInitialize method '{0}' signature is invalid. /// @@ -1098,7 +1143,7 @@ internal static string TestInitializeShouldBeValidMessageFormat { return ResourceManager.GetString("TestInitializeShouldBeValidMessageFormat", resourceCulture); } } - + /// /// Looks up a localized string similar to TestInitialize method should have valid layout. /// @@ -1107,7 +1152,7 @@ internal static string TestInitializeShouldBeValidTitle { return ResourceManager.GetString("TestInitializeShouldBeValidTitle", resourceCulture); } } - + /// /// Looks up a localized string similar to Test methods, methods marked with the '[TestMethod]' attribute, should respect the following layout to be considered valid by MSTest: ///- it should be 'public' (or 'internal' if '[assembly: DiscoverInternals]' attribute is set) @@ -1123,7 +1168,7 @@ internal static string TestMethodShouldBeValidDescription { return ResourceManager.GetString("TestMethodShouldBeValidDescription", resourceCulture); } } - + /// /// Looks up a localized string similar to Test method '{0}' signature is invalid. /// @@ -1132,7 +1177,7 @@ internal static string TestMethodShouldBeValidMessageFormat { return ResourceManager.GetString("TestMethodShouldBeValidMessageFormat", resourceCulture); } } - + /// /// Looks up a localized string similar to Test methods should have valid layout. /// @@ -1141,7 +1186,7 @@ internal static string TestMethodShouldBeValidTitle { return ResourceManager.GetString("TestMethodShouldBeValidTitle", resourceCulture); } } - + /// /// Looks up a localized string similar to Test methods should not be ignored (marked with '[Ignore]').. /// @@ -1150,7 +1195,7 @@ internal static string TestMethodShouldNotBeIgnoredAnalyzerDescription { return ResourceManager.GetString("TestMethodShouldNotBeIgnoredAnalyzerDescription", resourceCulture); } } - + /// /// Looks up a localized string similar to Test method '{0}' should not be ignored. /// @@ -1159,7 +1204,7 @@ internal static string TestMethodShouldNotBeIgnoredAnalyzerFormat { return ResourceManager.GetString("TestMethodShouldNotBeIgnoredAnalyzerFormat", resourceCulture); } } - + /// /// Looks up a localized string similar to Test method should not be ignored. /// @@ -1168,7 +1213,7 @@ internal static string TestMethodShouldNotBeIgnoredAnalyzerTitle { return ResourceManager.GetString("TestMethodShouldNotBeIgnoredAnalyzerTitle", resourceCulture); } } - + /// /// Looks up a localized string similar to Type containing '[TestMethod]' should be marked with '[TestClass]', otherwise the test method will be silently ignored.. /// @@ -1177,7 +1222,7 @@ internal static string TypeContainingTestMethodShouldBeATestClassDescription { return ResourceManager.GetString("TypeContainingTestMethodShouldBeATestClassDescription", resourceCulture); } } - + /// /// Looks up a localized string similar to Type '{0}' contains test methods and should be marked with '[TestClass]'. /// @@ -1186,7 +1231,7 @@ internal static string TypeContainingTestMethodShouldBeATestClassMessageFormat { return ResourceManager.GetString("TypeContainingTestMethodShouldBeATestClassMessageFormat", resourceCulture); } } - + /// /// Looks up a localized string similar to Type containing '[TestMethod]' should be marked with '[TestClass]'. /// @@ -1195,7 +1240,7 @@ internal static string TypeContainingTestMethodShouldBeATestClassTitle { return ResourceManager.GetString("TypeContainingTestMethodShouldBeATestClassTitle", resourceCulture); } } - + /// /// Looks up a localized string similar to TestContext parameter is required by MSTest for AssemblyInitialize and ClassInitialize methods. /// @@ -1204,7 +1249,7 @@ internal static string UnusedParameterSuppressorJustification { return ResourceManager.GetString("UnusedParameterSuppressorJustification", resourceCulture); } } - + /// /// Looks up a localized string similar to Asynchronous test fixture methods do not require the 'Async' suffix. /// @@ -1213,7 +1258,7 @@ internal static string UseAsyncSuffixTestFixtureMethodSuppressorJustification { return ResourceManager.GetString("UseAsyncSuffixTestFixtureMethodSuppressorJustification", resourceCulture); } } - + /// /// Looks up a localized string similar to Asynchronous test methods do not require the 'Async' suffix. /// @@ -1222,7 +1267,7 @@ internal static string UseAsyncSuffixTestMethodSuppressorJustification { return ResourceManager.GetString("UseAsyncSuffixTestMethodSuppressorJustification", resourceCulture); } } - + /// /// Looks up a localized string similar to [{0}] can only be set on methods marked with [TestMethod]. /// @@ -1231,7 +1276,7 @@ internal static string UseAttributeOnTestMethodAnalyzerMessageFormat { return ResourceManager.GetString("UseAttributeOnTestMethodAnalyzerMessageFormat", resourceCulture); } } - + /// /// Looks up a localized string similar to [{0}] can only be set on methods marked with [TestMethod]. /// @@ -1240,7 +1285,7 @@ internal static string UseAttributeOnTestMethodAnalyzerTitle { return ResourceManager.GetString("UseAttributeOnTestMethodAnalyzerTitle", resourceCulture); } } - + /// /// Looks up a localized string similar to Without using 'ClassCleanupBehavior.EndOfClass', the '[ClassCleanup]' will by default be run at the end of the assembly and not at the end of the class.. /// @@ -1249,7 +1294,7 @@ internal static string UseClassCleanupBehaviorEndOfClassDescription { return ResourceManager.GetString("UseClassCleanupBehaviorEndOfClassDescription", resourceCulture); } } - + /// /// Looks up a localized string similar to Use 'ClassCleanupBehavior.EndOfClass' with the '[ClassCleanup]'. /// @@ -1258,7 +1303,7 @@ internal static string UseClassCleanupBehaviorEndOfClassMessageFormat { return ResourceManager.GetString("UseClassCleanupBehaviorEndOfClassMessageFormat", resourceCulture); } } - + /// /// Looks up a localized string similar to Use 'ClassCleanupBehavior.EndOfClass' with the '[ClassCleanup]'. /// @@ -1267,7 +1312,7 @@ internal static string UseClassCleanupBehaviorEndOfClassTitle { return ResourceManager.GetString("UseClassCleanupBehaviorEndOfClassTitle", resourceCulture); } } - + /// /// Looks up a localized string similar to The attribute '{0}' which derives from 'ConditionBaseAttribute' should be used only on classes marked with `TestClassAttribute`. /// @@ -1276,7 +1321,7 @@ internal static string UseConditionBaseWithTestClassMessageFormat { return ResourceManager.GetString("UseConditionBaseWithTestClassMessageFormat", resourceCulture); } } - + /// /// Looks up a localized string similar to Use 'ConditionBaseAttribute' on test classes. /// @@ -1285,7 +1330,7 @@ internal static string UseConditionBaseWithTestClassTitle { return ResourceManager.GetString("UseConditionBaseWithTestClassTitle", resourceCulture); } } - + /// /// Looks up a localized string similar to Using '[Timeout]' without explicitly setting 'CooperativeCancellation = true' is discouraged. In a future version, cooperative cancellation will become the default behavior. Set 'CooperativeCancellation = true' to opt into the recommended behavior and avoid breaking changes.. /// @@ -1294,7 +1339,7 @@ internal static string UseCooperativeCancellationForTimeoutDescription { return ResourceManager.GetString("UseCooperativeCancellationForTimeoutDescription", resourceCulture); } } - + /// /// Looks up a localized string similar to Use 'CooperativeCancellation = true' with '[Timeout]' to enable cooperative cancellation behavior. /// @@ -1303,7 +1348,7 @@ internal static string UseCooperativeCancellationForTimeoutMessageFormat { return ResourceManager.GetString("UseCooperativeCancellationForTimeoutMessageFormat", resourceCulture); } } - + /// /// Looks up a localized string similar to Use 'CooperativeCancellation = true' with '[Timeout]'. /// @@ -1312,7 +1357,7 @@ internal static string UseCooperativeCancellationForTimeoutTitle { return ResourceManager.GetString("UseCooperativeCancellationForTimeoutTitle", resourceCulture); } } - + /// /// Looks up a localized string similar to '[DeploymentItem]' can be specified only on test class or test method. /// @@ -1321,7 +1366,7 @@ internal static string UseDeploymentItemWithTestMethodOrTestClassMessageFormat { return ResourceManager.GetString("UseDeploymentItemWithTestMethodOrTestClassMessageFormat", resourceCulture); } } - + /// /// Looks up a localized string similar to '[DeploymentItem]' can be specified only on test class or test method. /// @@ -1330,7 +1375,7 @@ internal static string UseDeploymentItemWithTestMethodOrTestClassTitle { return ResourceManager.GetString("UseDeploymentItemWithTestMethodOrTestClassTitle", resourceCulture); } } - + /// /// Looks up a localized string similar to Use 'Assert.ThrowsExactly' instead of 'Assert.ThrowsException'. /// @@ -1339,7 +1384,7 @@ internal static string UseNewerAssertThrowsMessageFormat { return ResourceManager.GetString("UseNewerAssertThrowsMessageFormat", resourceCulture); } } - + /// /// Looks up a localized string similar to Use newer methods to assert exceptions. /// @@ -1348,7 +1393,7 @@ internal static string UseNewerAssertThrowsTitle { return ResourceManager.GetString("UseNewerAssertThrowsTitle", resourceCulture); } } - + /// /// Looks up a localized string similar to By default, MSTest runs tests within the same assembly sequentially, which can lead to severe performance limitations. It is recommended to enable assembly attribute '[Parallelize]' to run tests in parallel, or if the assembly is known to not be parallelizable, to use explicitly the assembly level attribute '[DoNotParallelize]'.. /// @@ -1357,7 +1402,7 @@ internal static string UseParallelizeAttributeAnalyzerDescription { return ResourceManager.GetString("UseParallelizeAttributeAnalyzerDescription", resourceCulture); } } - + /// /// Looks up a localized string similar to Explicitly enable or disable tests parallelization. /// @@ -1366,7 +1411,7 @@ internal static string UseParallelizeAttributeAnalyzerMessageFormat { return ResourceManager.GetString("UseParallelizeAttributeAnalyzerMessageFormat", resourceCulture); } } - + /// /// Looks up a localized string similar to Explicitly enable or disable tests parallelization. /// @@ -1375,7 +1420,7 @@ internal static string UseParallelizeAttributeAnalyzerTitle { return ResourceManager.GetString("UseParallelizeAttributeAnalyzerTitle", resourceCulture); } } - + /// /// Looks up a localized string similar to Use 'Assert.{0}' instead of 'Assert.{1}'. /// @@ -1384,7 +1429,7 @@ internal static string UseProperAssertMethodsMessageFormat { return ResourceManager.GetString("UseProperAssertMethodsMessageFormat", resourceCulture); } } - + /// /// Looks up a localized string similar to Use proper 'Assert' methods. /// @@ -1393,7 +1438,7 @@ internal static string UseProperAssertMethodsTitle { return ResourceManager.GetString("UseProperAssertMethodsTitle", resourceCulture); } } - + /// /// Looks up a localized string similar to An attribute that derives from 'RetryBaseAttribute' can be specified only on a test method. /// @@ -1402,7 +1447,7 @@ internal static string UseRetryWithTestMethodMessageFormat { return ResourceManager.GetString("UseRetryWithTestMethodMessageFormat", resourceCulture); } } - + /// /// Looks up a localized string similar to Use retry attribute on test method. /// @@ -1411,32 +1456,5 @@ internal static string UseRetryWithTestMethodTitle { return ResourceManager.GetString("UseRetryWithTestMethodTitle", resourceCulture); } } - - /// - /// Looks up a localized string similar to Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws. - /// - internal static string AssertThrowsShouldContainSingleStatementDescription { - get { - return ResourceManager.GetString("AssertThrowsShouldContainSingleStatementDescription", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Assert.Throws should contain only a single statement/expression. - /// - internal static string AssertThrowsShouldContainSingleStatementMessageFormat { - get { - return ResourceManager.GetString("AssertThrowsShouldContainSingleStatementMessageFormat", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Assert.Throws should contain only a single statement/expression. - /// - internal static string AssertThrowsShouldContainSingleStatementTitle { - get { - return ResourceManager.GetString("AssertThrowsShouldContainSingleStatementTitle", resourceCulture); - } - } } } diff --git a/src/Analyzers/MSTest.Analyzers/Resources.resx b/src/Analyzers/MSTest.Analyzers/Resources.resx index 79517906d0..4cb1c3b193 100644 --- a/src/Analyzers/MSTest.Analyzers/Resources.resx +++ b/src/Analyzers/MSTest.Analyzers/Resources.resx @@ -672,4 +672,10 @@ The type declaring these methods should also respect the following rules: -The class should be marked with '[TestClass]' (or a derived attribute) -the class should not be generic. + + Avoid passing an explicit 'DynamicDataSourceType' and use the default auto detect behavior + + + Remove the 'DynamicDataSourceType' argument to use the default auto detect behavior + diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf index 243e52b284..e891585a90 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf @@ -147,6 +147,16 @@ Typ deklarující tyto metody by měl také respektovat následující pravidla: Vyhněte se [ExpectedException] + + Remove the 'DynamicDataSourceType' argument to use the default auto detect behavior + Remove the 'DynamicDataSourceType' argument to use the default auto detect behavior + + + + Avoid passing an explicit 'DynamicDataSourceType' and use the default auto detect behavior + Avoid passing an explicit 'DynamicDataSourceType' and use the default auto detect behavior + + Do not assert inside 'async void' methods, local functions, or lambdas. Exceptions that are thrown in this context will be unhandled exceptions. When using VSTest under .NET Framework, they will be silently swallowed. When using Microsoft.Testing.Platform or VSTest under modern .NET, they may crash the process. Nepoužívejte výraz uvnitř metod async void, místních funkcí nebo výrazů lambda. Výjimky vyvolané v tomto kontextu budou neošetřené výjimky. Když používáte VSTest v .NET Framework, budou se bezobslužně používat. Když používáte Microsoft.Testing.Platform nebo VSTest v moderním rozhraní .NET, může dojít k chybovému ukončení procesu. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf index bd9c5800fb..73605a1c41 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf @@ -147,6 +147,16 @@ Der Typ, der diese Methoden deklariert, sollte auch die folgenden Regeln beachte „[ExpectedException]“ vermeiden + + Remove the 'DynamicDataSourceType' argument to use the default auto detect behavior + Remove the 'DynamicDataSourceType' argument to use the default auto detect behavior + + + + Avoid passing an explicit 'DynamicDataSourceType' and use the default auto detect behavior + Avoid passing an explicit 'DynamicDataSourceType' and use the default auto detect behavior + + Do not assert inside 'async void' methods, local functions, or lambdas. Exceptions that are thrown in this context will be unhandled exceptions. When using VSTest under .NET Framework, they will be silently swallowed. When using Microsoft.Testing.Platform or VSTest under modern .NET, they may crash the process. Nicht innerhalb von "async void"-Methoden, lokalen Funktionen oder Lambdafunktionen bestätigen. Ausnahmen, die in diesem Kontext ausgelöst werden, werden nicht behandelt. Bei Verwendung von VSTest unter .NET Framework werden diese im Hintergrund verschlungen. Wenn Sie Microsoft.Testing.Platform oder VSTest unter modernem .NET verwenden, kann der Prozess abgestürzt werden. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf index f128a53eaa..e2705d9d8f 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf @@ -147,6 +147,16 @@ El tipo que declara estos métodos también debe respetar las reglas siguientes: Evitar '[ExpectedException]' + + Remove the 'DynamicDataSourceType' argument to use the default auto detect behavior + Remove the 'DynamicDataSourceType' argument to use the default auto detect behavior + + + + Avoid passing an explicit 'DynamicDataSourceType' and use the default auto detect behavior + Avoid passing an explicit 'DynamicDataSourceType' and use the default auto detect behavior + + Do not assert inside 'async void' methods, local functions, or lambdas. Exceptions that are thrown in this context will be unhandled exceptions. When using VSTest under .NET Framework, they will be silently swallowed. When using Microsoft.Testing.Platform or VSTest under modern .NET, they may crash the process. No realice ninguna aserción dentro de métodos 'async void', funciones locales o expresiones lambda. Las excepciones que se inicien en este contexto serán excepciones no controladas. Al usar VSTest en .NET Framework, se ingerirán silenciosamente. Cuando se usa Microsoft.Testing.Platform o VSTest en .NET moderno, es posible que se bloquee el proceso. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf index ac3e3d031f..27c9a4cb31 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf @@ -147,6 +147,16 @@ Le type doit être une classe Éviter « [ExpectedException] » + + Remove the 'DynamicDataSourceType' argument to use the default auto detect behavior + Remove the 'DynamicDataSourceType' argument to use the default auto detect behavior + + + + Avoid passing an explicit 'DynamicDataSourceType' and use the default auto detect behavior + Avoid passing an explicit 'DynamicDataSourceType' and use the default auto detect behavior + + Do not assert inside 'async void' methods, local functions, or lambdas. Exceptions that are thrown in this context will be unhandled exceptions. When using VSTest under .NET Framework, they will be silently swallowed. When using Microsoft.Testing.Platform or VSTest under modern .NET, they may crash the process. N’effectuez pas d’assertion dans les méthodes 'async void', les fonctions locales ou les expressions lambda. Les exceptions levées dans ce contexte seront des exceptions non gérées. Lors de l’utilisation de VSTest sous .NET Framework, ils sont silencieusement coupés. Quand vous utilisez Microsoft.Testing.Platform ou VSTest sous .NET moderne, ils peuvent bloquer le processus. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf index 585b39973a..f4c6ebc874 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf @@ -147,6 +147,16 @@ Anche il tipo che dichiara questi metodi deve rispettare le regole seguenti: Evita '[ExpectedException]' + + Remove the 'DynamicDataSourceType' argument to use the default auto detect behavior + Remove the 'DynamicDataSourceType' argument to use the default auto detect behavior + + + + Avoid passing an explicit 'DynamicDataSourceType' and use the default auto detect behavior + Avoid passing an explicit 'DynamicDataSourceType' and use the default auto detect behavior + + Do not assert inside 'async void' methods, local functions, or lambdas. Exceptions that are thrown in this context will be unhandled exceptions. When using VSTest under .NET Framework, they will be silently swallowed. When using Microsoft.Testing.Platform or VSTest under modern .NET, they may crash the process. Non dichiarare all'interno di metodi 'async void', funzioni locali o espressioni lambda. Le eccezioni generate in questo contesto saranno eccezioni non gestite. Quando si usa VSTest in .NET Framework, verranno eliminati automaticamente. Quando si usa Microsoft.Testing.Platform o VSTest nella versione moderna di .NET, è possibile che il processo venga arrestato in modo anomalo. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf index ae7471f9e6..90a47991c0 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf @@ -147,6 +147,16 @@ The type declaring these methods should also respect the following rules: '[ExpectedException]' を回避する + + Remove the 'DynamicDataSourceType' argument to use the default auto detect behavior + Remove the 'DynamicDataSourceType' argument to use the default auto detect behavior + + + + Avoid passing an explicit 'DynamicDataSourceType' and use the default auto detect behavior + Avoid passing an explicit 'DynamicDataSourceType' and use the default auto detect behavior + + Do not assert inside 'async void' methods, local functions, or lambdas. Exceptions that are thrown in this context will be unhandled exceptions. When using VSTest under .NET Framework, they will be silently swallowed. When using Microsoft.Testing.Platform or VSTest under modern .NET, they may crash the process. 'async void' メソッド、ローカル関数、またはラムダ内ではアサートしないでください。このコンテキストでスローされる例外は、ハンドルされない例外になります。.NET Frameworkで VSTest を使用すると、警告なしに飲み込まれるようになります。最新の .NET で Microsoft.Testing.Platform または VSTest を使用すると、プロセスがクラッシュする可能性があります。 diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf index 9d22ce3a8d..002b455ed8 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf @@ -147,6 +147,16 @@ The type declaring these methods should also respect the following rules: '[ExpectedException]' 사용 지양 + + Remove the 'DynamicDataSourceType' argument to use the default auto detect behavior + Remove the 'DynamicDataSourceType' argument to use the default auto detect behavior + + + + Avoid passing an explicit 'DynamicDataSourceType' and use the default auto detect behavior + Avoid passing an explicit 'DynamicDataSourceType' and use the default auto detect behavior + + Do not assert inside 'async void' methods, local functions, or lambdas. Exceptions that are thrown in this context will be unhandled exceptions. When using VSTest under .NET Framework, they will be silently swallowed. When using Microsoft.Testing.Platform or VSTest under modern .NET, they may crash the process. 'async void' 메서드, 로컬 함수 또는 람다 내에서 어설션하지 마십시오. 이 컨텍스트에서 throw된 예외는 처리되지 않은 예외가 됩니다. .NET Framework 아래에서 VSTest를 사용하면 자동으로 무시됩니다. 최신 .NET에서 Microsoft.Testing.Platform 또는 VSTest를 사용하는 경우 프로세스가 중단될 수 있습니다. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf index 3f5492237d..511014e7a8 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf @@ -147,6 +147,16 @@ Typ deklarujący te metody powinien również przestrzegać następujących regu Unikaj elementu „[ExpectedException]” + + Remove the 'DynamicDataSourceType' argument to use the default auto detect behavior + Remove the 'DynamicDataSourceType' argument to use the default auto detect behavior + + + + Avoid passing an explicit 'DynamicDataSourceType' and use the default auto detect behavior + Avoid passing an explicit 'DynamicDataSourceType' and use the default auto detect behavior + + Do not assert inside 'async void' methods, local functions, or lambdas. Exceptions that are thrown in this context will be unhandled exceptions. When using VSTest under .NET Framework, they will be silently swallowed. When using Microsoft.Testing.Platform or VSTest under modern .NET, they may crash the process. Nie potwierdzaj wewnątrz metod "async void", funkcji lokalnych ani lambda. Wyjątki, które są zgłaszane w tym kontekście, będą nieobsługiwanymi wyjątkami. W przypadku korzystania z narzędzia VSTest w .NET Framework będą one dyskretnie ściszone. W przypadku korzystania z elementu Microsoft.Testing.Platform lub VSTest w nowoczesnych programach .NET mogą one spowodować awarię procesu. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf index 67886effc7..53c6356d12 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf @@ -147,6 +147,16 @@ O tipo que declara esses métodos também deve respeitar as seguintes regras: Evitar '[ExpectedException]' + + Remove the 'DynamicDataSourceType' argument to use the default auto detect behavior + Remove the 'DynamicDataSourceType' argument to use the default auto detect behavior + + + + Avoid passing an explicit 'DynamicDataSourceType' and use the default auto detect behavior + Avoid passing an explicit 'DynamicDataSourceType' and use the default auto detect behavior + + Do not assert inside 'async void' methods, local functions, or lambdas. Exceptions that are thrown in this context will be unhandled exceptions. When using VSTest under .NET Framework, they will be silently swallowed. When using Microsoft.Testing.Platform or VSTest under modern .NET, they may crash the process. Não asserção dentro de métodos 'async void', funções locais ou lambdas. Exceções lançadas neste contexto serão exceções sem tratamento. Ao usar VSTest sob .NET Framework, eles serão silenciosamente ignoradas. Ao usar Microsoft.Testing.Platform ou VSTest em .NET moderno, o processo pode falhar. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf index 3f3354dd43..e182e64a4f 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf @@ -150,6 +150,16 @@ The type declaring these methods should also respect the following rules: Избегать "[ExpectedException]" + + Remove the 'DynamicDataSourceType' argument to use the default auto detect behavior + Remove the 'DynamicDataSourceType' argument to use the default auto detect behavior + + + + Avoid passing an explicit 'DynamicDataSourceType' and use the default auto detect behavior + Avoid passing an explicit 'DynamicDataSourceType' and use the default auto detect behavior + + Do not assert inside 'async void' methods, local functions, or lambdas. Exceptions that are thrown in this context will be unhandled exceptions. When using VSTest under .NET Framework, they will be silently swallowed. When using Microsoft.Testing.Platform or VSTest under modern .NET, they may crash the process. Не подтверяйте внутри методов async void, локальных функций или лямбда-выражений. Исключения, вызванные в этом контексте, будут необработанные исключения. При использовании VSTest платформа .NET Framework, они будут пропущены без уведомления. При использовании Microsoft.Testing.Platform или VSTest в современной версии .NET они могут привести к сбою процесса. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf index f3a853182b..14e6a30d81 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf @@ -147,6 +147,16 @@ Bu yöntemleri bildiren tipin ayrıca aşağıdaki kurallara uyması gerekir: '[ExpectedException]' kullanmayın + + Remove the 'DynamicDataSourceType' argument to use the default auto detect behavior + Remove the 'DynamicDataSourceType' argument to use the default auto detect behavior + + + + Avoid passing an explicit 'DynamicDataSourceType' and use the default auto detect behavior + Avoid passing an explicit 'DynamicDataSourceType' and use the default auto detect behavior + + Do not assert inside 'async void' methods, local functions, or lambdas. Exceptions that are thrown in this context will be unhandled exceptions. When using VSTest under .NET Framework, they will be silently swallowed. When using Microsoft.Testing.Platform or VSTest under modern .NET, they may crash the process. 'async void' metotları, yerel işlevler veya lambdalar içinde onaylamayın. Bu bağlamda oluşturulan özel durumlar işlenmeyen özel durumlar olacak. VsTest'i .NET Framework, sessizce kırılır. Modern .NET altında Microsoft.Testing.Platform veya VSTest kullanırken işlemi kilitler. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf index 45f0e177b3..f80fea53ae 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf @@ -147,6 +147,16 @@ The type declaring these methods should also respect the following rules: 避免 "[ExpectedException]" + + Remove the 'DynamicDataSourceType' argument to use the default auto detect behavior + Remove the 'DynamicDataSourceType' argument to use the default auto detect behavior + + + + Avoid passing an explicit 'DynamicDataSourceType' and use the default auto detect behavior + Avoid passing an explicit 'DynamicDataSourceType' and use the default auto detect behavior + + Do not assert inside 'async void' methods, local functions, or lambdas. Exceptions that are thrown in this context will be unhandled exceptions. When using VSTest under .NET Framework, they will be silently swallowed. When using Microsoft.Testing.Platform or VSTest under modern .NET, they may crash the process. 不要在 “async void” 方法、本地函数或 lambdas 内断言。在此上下文中引发的异常将是未经处理的异常。在.NET Framework下使用 VSTest 时,将无提示地接受这些测试。在现代 .NET 下使用 Microsoft.Testing.Platform 或 VSTest 时,它们可能会导致进程崩溃。 diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf index 7136911d17..a566285c1b 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf @@ -147,6 +147,16 @@ The type declaring these methods should also respect the following rules: 避免 '[ExpectedException]' + + Remove the 'DynamicDataSourceType' argument to use the default auto detect behavior + Remove the 'DynamicDataSourceType' argument to use the default auto detect behavior + + + + Avoid passing an explicit 'DynamicDataSourceType' and use the default auto detect behavior + Avoid passing an explicit 'DynamicDataSourceType' and use the default auto detect behavior + + Do not assert inside 'async void' methods, local functions, or lambdas. Exceptions that are thrown in this context will be unhandled exceptions. When using VSTest under .NET Framework, they will be silently swallowed. When using Microsoft.Testing.Platform or VSTest under modern .NET, they may crash the process. 不要在 'async void' 方法、本機函數或 lambdas 內判斷提示。在此內容中擲回的例外狀況將會是未處理的例外狀況。在 .NET Framework 下使用 VSTest 時,會以無訊息方式接受。在現代 .NET 下使用 Microsoft.Testing.Platform 或 VSTest 時,可能會損毀進程。 diff --git a/test/UnitTests/MSTest.Analyzers.UnitTests/AvoidExplicitDynamicDataSourceTypeTests.cs b/test/UnitTests/MSTest.Analyzers.UnitTests/AvoidExplicitDynamicDataSourceTypeTests.cs new file mode 100644 index 0000000000..3e109a390e --- /dev/null +++ b/test/UnitTests/MSTest.Analyzers.UnitTests/AvoidExplicitDynamicDataSourceTypeTests.cs @@ -0,0 +1,266 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using VerifyCS = MSTest.Analyzers.Test.CSharpCodeFixVerifier< + MSTest.Analyzers.AvoidExplicitDynamicDataSourceTypeAnalyzer, + MSTest.Analyzers.AvoidExplicitDynamicDataSourceTypeFixer>; + +namespace MSTest.Analyzers.Test; + +[TestClass] +public sealed class AvoidExplicitDynamicDataSourceTypeTests +{ + [TestMethod] + public async Task WhenDynamicDataUsesAutoDetectImplicitly_NoDiagnostic() + { + string code = """ + using System.Collections.Generic; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [DynamicData("Data")] + [TestMethod] + public void TestMethod1(object[] o) { } + + + [DynamicData("Data", typeof(MyTestClass))] + [TestMethod] + public void TestMethod2(object[] o) { } + + static IEnumerable Data => new[] { new object[] { 1 } }; + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, code); + } + + [TestMethod] + public async Task WhenDynamicDataUsesAutoDetectExplicitly_Diagnostic() + { + string code = """ + using System.Collections.Generic; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [[|DynamicData("Data", DynamicDataSourceType.AutoDetect)|]] + [TestMethod] + public void TestMethod1(object[] o) { } + + [[|DynamicData("Data", typeof(MyTestClass), DynamicDataSourceType.AutoDetect)|]] + [TestMethod] + public void TestMethod2(object[] o) { } + + static IEnumerable Data => new[] { new object[] { 1 } }; + } + """; + + string fixedCode = """ + using System.Collections.Generic; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [DynamicData("Data")] + [TestMethod] + public void TestMethod1(object[] o) { } + + [DynamicData("Data", typeof(MyTestClass))] + [TestMethod] + public void TestMethod2(object[] o) { } + + static IEnumerable Data => new[] { new object[] { 1 } }; + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, fixedCode); + } + + [TestMethod] + public async Task WhenDynamicDataUsesProperty_ReportsDiagnostic() + { + string code = """ + using System.Collections.Generic; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [[|DynamicData("Data", DynamicDataSourceType.Property)|]] + [TestMethod] + public void TestMethod1(object[] o) { } + + static IEnumerable Data => new[] { new object[] { 1 } }; + } + """; + + string fixedCode = """ + using System.Collections.Generic; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [DynamicData("Data")] + [TestMethod] + public void TestMethod1(object[] o) { } + + static IEnumerable Data => new[] { new object[] { 1 } }; + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, fixedCode); + } + + [TestMethod] + public async Task WhenDynamicDataUsesMethod_ReportsDiagnostic() + { + string code = """ + using System.Collections.Generic; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [[|DynamicData("GetData", DynamicDataSourceType.Method)|]] + [TestMethod] + public void TestMethod1(object[] o) { } + + static IEnumerable GetData() => new[] { new object[] { 1 } }; + } + """; + + string fixedCode = """ + using System.Collections.Generic; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [DynamicData("GetData")] + [TestMethod] + public void TestMethod1(object[] o) { } + + static IEnumerable GetData() => new[] { new object[] { 1 } }; + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, fixedCode); + } + + [TestMethod] + public async Task WhenDynamicDataUsesPropertyWithDeclaringType_ReportsDiagnostic() + { + string code = """ + using System.Collections.Generic; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [[|DynamicData("Data", typeof(MyTestClass), DynamicDataSourceType.Property)|]] + [TestMethod] + public void TestMethod1(object[] o) { } + + static IEnumerable Data => new[] { new object[] { 1 } }; + } + """; + + string fixedCode = """ + using System.Collections.Generic; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [DynamicData("Data", typeof(MyTestClass))] + [TestMethod] + public void TestMethod1(object[] o) { } + + static IEnumerable Data => new[] { new object[] { 1 } }; + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, fixedCode); + } + + [TestMethod] + public async Task WhenDynamicDataUsesMethodWithDeclaringType_ReportsDiagnostic() + { + string code = """ + using System.Collections.Generic; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [[|DynamicData("GetData", typeof(MyTestClass), DynamicDataSourceType.Method)|]] + [TestMethod] + public void TestMethod1(object[] o) { } + + static IEnumerable GetData() => new[] { new object[] { 1 } }; + } + """; + + string fixedCode = """ + using System.Collections.Generic; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [DynamicData("GetData", typeof(MyTestClass))] + [TestMethod] + public void TestMethod1(object[] o) { } + + static IEnumerable GetData() => new[] { new object[] { 1 } }; + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, fixedCode); + } + + [TestMethod] + public async Task WhenMultipleDynamicDataAttributesWithExplicitTypes_ReportsMultipleDiagnostics() + { + string code = """ + using System.Collections.Generic; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [[|DynamicData("Data", DynamicDataSourceType.Property)|]] + [[|DynamicData("GetData", DynamicDataSourceType.Method)|]] + [TestMethod] + public void TestMethod1(object[] o) { } + + static IEnumerable Data => new[] { new object[] { 1 } }; + static IEnumerable GetData() => new[] { new object[] { 2 } }; + } + """; + + string fixedCode = """ + using System.Collections.Generic; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [DynamicData("Data")] + [DynamicData("GetData")] + [TestMethod] + public void TestMethod1(object[] o) { } + + static IEnumerable Data => new[] { new object[] { 1 } }; + static IEnumerable GetData() => new[] { new object[] { 2 } }; + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, fixedCode); + } +} From 28cfa094717054b70f01a1da28b0b8b17dabc6e3 Mon Sep 17 00:00:00 2001 From: dotnet bot Date: Thu, 31 Jul 2025 09:03:26 -0700 Subject: [PATCH 345/541] Localized file check-in by OneLocBuild Task: Build definition ID 1218: Build ID 2762056 --- .../xlf/CodeFixResources.cs.xlf | 5 +++++ .../xlf/CodeFixResources.de.xlf | 5 +++++ .../xlf/CodeFixResources.es.xlf | 5 +++++ .../xlf/CodeFixResources.fr.xlf | 5 +++++ .../xlf/CodeFixResources.it.xlf | 5 +++++ .../xlf/CodeFixResources.ja.xlf | 5 +++++ .../xlf/CodeFixResources.ko.xlf | 5 +++++ .../xlf/CodeFixResources.pl.xlf | 5 +++++ .../xlf/CodeFixResources.pt-BR.xlf | 5 +++++ .../xlf/CodeFixResources.ru.xlf | 5 +++++ .../xlf/CodeFixResources.tr.xlf | 5 +++++ .../xlf/CodeFixResources.zh-Hans.xlf | 5 +++++ .../xlf/CodeFixResources.zh-Hant.xlf | 5 +++++ src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf | 10 ++++++++++ src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf | 10 ++++++++++ src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf | 10 ++++++++++ src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf | 10 ++++++++++ src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf | 10 ++++++++++ src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf | 10 ++++++++++ src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf | 10 ++++++++++ src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf | 10 ++++++++++ src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf | 10 ++++++++++ src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf | 10 ++++++++++ src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf | 10 ++++++++++ .../MSTest.Analyzers/xlf/Resources.zh-Hans.xlf | 10 ++++++++++ .../MSTest.Analyzers/xlf/Resources.zh-Hant.xlf | 10 ++++++++++ 26 files changed, 195 insertions(+) diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.cs.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.cs.xlf index 7c85a47db8..f37ac67ed8 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.cs.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.cs.xlf @@ -52,6 +52,11 @@ Předejte argument TestContext.CancellationTokenSource.Token volání metody. + + Remove 'DynamicDataSourceType' parameter to use default 'AutoDetect' + Remove 'DynamicDataSourceType' parameter to use default 'AutoDetect' + + Replace 'DataTestMethod' with 'TestMethod' Nahradit DataTestMethod hodnotou TestMethod diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.de.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.de.xlf index 16776cafc7..5547c7b016 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.de.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.de.xlf @@ -52,6 +52,11 @@ Argument „TestContext.CancellationTokenSource.Token“ an den Methodenaufruf übergeben + + Remove 'DynamicDataSourceType' parameter to use default 'AutoDetect' + Remove 'DynamicDataSourceType' parameter to use default 'AutoDetect' + + Replace 'DataTestMethod' with 'TestMethod' „DataTestMethod“ durch „TestMethod“ ersetzen diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.es.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.es.xlf index 5fe2aeef20..cb6b8436f2 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.es.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.es.xlf @@ -52,6 +52,11 @@ Pasa el argumento 'TestContext.CancellationTokenSource.Token' a la llamada de método + + Remove 'DynamicDataSourceType' parameter to use default 'AutoDetect' + Remove 'DynamicDataSourceType' parameter to use default 'AutoDetect' + + Replace 'DataTestMethod' with 'TestMethod' Reemplazar "DataTestMethod" por "TestMethod" diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.fr.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.fr.xlf index 821c7fe651..9a67381860 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.fr.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.fr.xlf @@ -52,6 +52,11 @@ Passer l’argument « TestContext.CancellationTokenSource.Token » à l’appel de méthode + + Remove 'DynamicDataSourceType' parameter to use default 'AutoDetect' + Remove 'DynamicDataSourceType' parameter to use default 'AutoDetect' + + Replace 'DataTestMethod' with 'TestMethod' Remplacer « DataTestMethod » par « TestMethod » diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.it.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.it.xlf index 31788d3248..0dafc34936 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.it.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.it.xlf @@ -52,6 +52,11 @@ Passare l'argomento 'TestContext.CancellationTokenSource.Token' alla chiamata al metodo + + Remove 'DynamicDataSourceType' parameter to use default 'AutoDetect' + Remove 'DynamicDataSourceType' parameter to use default 'AutoDetect' + + Replace 'DataTestMethod' with 'TestMethod' Sostituisci 'DataTestMethod' con 'TestMethod' diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ja.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ja.xlf index 94549b537e..9924ecd9af 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ja.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ja.xlf @@ -52,6 +52,11 @@ 'TestContext.CancellationTokenSource.Token' 引数をメソッド呼び出しに渡す + + Remove 'DynamicDataSourceType' parameter to use default 'AutoDetect' + Remove 'DynamicDataSourceType' parameter to use default 'AutoDetect' + + Replace 'DataTestMethod' with 'TestMethod' 'DataTestMethod' を 'TestMethod' に置き換えます diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ko.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ko.xlf index 1d3b2b6c7d..cedcce1149 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ko.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ko.xlf @@ -52,6 +52,11 @@ 메서드 호출에 'TestContext.CancellationTokenSource.Token' 인수 전달 + + Remove 'DynamicDataSourceType' parameter to use default 'AutoDetect' + Remove 'DynamicDataSourceType' parameter to use default 'AutoDetect' + + Replace 'DataTestMethod' with 'TestMethod' 'DataTestMethod'를 'TestMethod'로 바꾸기 diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pl.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pl.xlf index 310742cd01..3caa21908b 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pl.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pl.xlf @@ -52,6 +52,11 @@ Przekaż argument „TestContext.CancellationTokenSource.Token” do wywołania metody + + Remove 'DynamicDataSourceType' parameter to use default 'AutoDetect' + Remove 'DynamicDataSourceType' parameter to use default 'AutoDetect' + + Replace 'DataTestMethod' with 'TestMethod' Zastąp element „DataTestMethod” elementem „TestMethod” diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pt-BR.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pt-BR.xlf index bd3d1f3de9..471b1602e5 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pt-BR.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pt-BR.xlf @@ -52,6 +52,11 @@ Passe o argumento 'TestContext.CancellationTokenSource.Token' para a chamada do método + + Remove 'DynamicDataSourceType' parameter to use default 'AutoDetect' + Remove 'DynamicDataSourceType' parameter to use default 'AutoDetect' + + Replace 'DataTestMethod' with 'TestMethod' Substitua 'DataTestMethod' por 'TestMethod' diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ru.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ru.xlf index e39f5f059c..0cb8bcef77 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ru.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ru.xlf @@ -52,6 +52,11 @@ Передайте аргумент "TestContext.CancellationTokenSource.Token" вызов метода + + Remove 'DynamicDataSourceType' parameter to use default 'AutoDetect' + Remove 'DynamicDataSourceType' parameter to use default 'AutoDetect' + + Replace 'DataTestMethod' with 'TestMethod' Заменить "DataTestMethod" на "TestMethod" diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.tr.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.tr.xlf index 1d0141b71c..9b1c7acf17 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.tr.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.tr.xlf @@ -52,6 +52,11 @@ ‘TestContext.CancellationTokenSource.Token’ bağımsız değişkeni metot çağrısına geçirin + + Remove 'DynamicDataSourceType' parameter to use default 'AutoDetect' + Remove 'DynamicDataSourceType' parameter to use default 'AutoDetect' + + Replace 'DataTestMethod' with 'TestMethod' 'DataTestMethod' yöntemini 'TestMethod' ile değiştirin diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hans.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hans.xlf index 271951cb89..ec07f7bfe2 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hans.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hans.xlf @@ -52,6 +52,11 @@ 将 'TestContext.CancellationTokenSource.Token' 参数传递给方法调用 + + Remove 'DynamicDataSourceType' parameter to use default 'AutoDetect' + Remove 'DynamicDataSourceType' parameter to use default 'AutoDetect' + + Replace 'DataTestMethod' with 'TestMethod' 将 'DataTestMethod' 替换为 'TestMethod' diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hant.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hant.xlf index d490fcbef8..0fe18848ae 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hant.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hant.xlf @@ -52,6 +52,11 @@ 將 'TestContext.CancellationTokenSource.Token' 引數傳遞給方法呼叫 + + Remove 'DynamicDataSourceType' parameter to use default 'AutoDetect' + Remove 'DynamicDataSourceType' parameter to use default 'AutoDetect' + + Replace 'DataTestMethod' with 'TestMethod' 將 'DataTestMethod' 取代為 'TestMethod' diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf index 243e52b284..e891585a90 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf @@ -147,6 +147,16 @@ Typ deklarující tyto metody by měl také respektovat následující pravidla: Vyhněte se [ExpectedException] + + Remove the 'DynamicDataSourceType' argument to use the default auto detect behavior + Remove the 'DynamicDataSourceType' argument to use the default auto detect behavior + + + + Avoid passing an explicit 'DynamicDataSourceType' and use the default auto detect behavior + Avoid passing an explicit 'DynamicDataSourceType' and use the default auto detect behavior + + Do not assert inside 'async void' methods, local functions, or lambdas. Exceptions that are thrown in this context will be unhandled exceptions. When using VSTest under .NET Framework, they will be silently swallowed. When using Microsoft.Testing.Platform or VSTest under modern .NET, they may crash the process. Nepoužívejte výraz uvnitř metod async void, místních funkcí nebo výrazů lambda. Výjimky vyvolané v tomto kontextu budou neošetřené výjimky. Když používáte VSTest v .NET Framework, budou se bezobslužně používat. Když používáte Microsoft.Testing.Platform nebo VSTest v moderním rozhraní .NET, může dojít k chybovému ukončení procesu. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf index bd9c5800fb..73605a1c41 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf @@ -147,6 +147,16 @@ Der Typ, der diese Methoden deklariert, sollte auch die folgenden Regeln beachte „[ExpectedException]“ vermeiden + + Remove the 'DynamicDataSourceType' argument to use the default auto detect behavior + Remove the 'DynamicDataSourceType' argument to use the default auto detect behavior + + + + Avoid passing an explicit 'DynamicDataSourceType' and use the default auto detect behavior + Avoid passing an explicit 'DynamicDataSourceType' and use the default auto detect behavior + + Do not assert inside 'async void' methods, local functions, or lambdas. Exceptions that are thrown in this context will be unhandled exceptions. When using VSTest under .NET Framework, they will be silently swallowed. When using Microsoft.Testing.Platform or VSTest under modern .NET, they may crash the process. Nicht innerhalb von "async void"-Methoden, lokalen Funktionen oder Lambdafunktionen bestätigen. Ausnahmen, die in diesem Kontext ausgelöst werden, werden nicht behandelt. Bei Verwendung von VSTest unter .NET Framework werden diese im Hintergrund verschlungen. Wenn Sie Microsoft.Testing.Platform oder VSTest unter modernem .NET verwenden, kann der Prozess abgestürzt werden. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf index f128a53eaa..e2705d9d8f 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf @@ -147,6 +147,16 @@ El tipo que declara estos métodos también debe respetar las reglas siguientes: Evitar '[ExpectedException]' + + Remove the 'DynamicDataSourceType' argument to use the default auto detect behavior + Remove the 'DynamicDataSourceType' argument to use the default auto detect behavior + + + + Avoid passing an explicit 'DynamicDataSourceType' and use the default auto detect behavior + Avoid passing an explicit 'DynamicDataSourceType' and use the default auto detect behavior + + Do not assert inside 'async void' methods, local functions, or lambdas. Exceptions that are thrown in this context will be unhandled exceptions. When using VSTest under .NET Framework, they will be silently swallowed. When using Microsoft.Testing.Platform or VSTest under modern .NET, they may crash the process. No realice ninguna aserción dentro de métodos 'async void', funciones locales o expresiones lambda. Las excepciones que se inicien en este contexto serán excepciones no controladas. Al usar VSTest en .NET Framework, se ingerirán silenciosamente. Cuando se usa Microsoft.Testing.Platform o VSTest en .NET moderno, es posible que se bloquee el proceso. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf index ac3e3d031f..27c9a4cb31 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf @@ -147,6 +147,16 @@ Le type doit être une classe Éviter « [ExpectedException] » + + Remove the 'DynamicDataSourceType' argument to use the default auto detect behavior + Remove the 'DynamicDataSourceType' argument to use the default auto detect behavior + + + + Avoid passing an explicit 'DynamicDataSourceType' and use the default auto detect behavior + Avoid passing an explicit 'DynamicDataSourceType' and use the default auto detect behavior + + Do not assert inside 'async void' methods, local functions, or lambdas. Exceptions that are thrown in this context will be unhandled exceptions. When using VSTest under .NET Framework, they will be silently swallowed. When using Microsoft.Testing.Platform or VSTest under modern .NET, they may crash the process. N’effectuez pas d’assertion dans les méthodes 'async void', les fonctions locales ou les expressions lambda. Les exceptions levées dans ce contexte seront des exceptions non gérées. Lors de l’utilisation de VSTest sous .NET Framework, ils sont silencieusement coupés. Quand vous utilisez Microsoft.Testing.Platform ou VSTest sous .NET moderne, ils peuvent bloquer le processus. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf index 585b39973a..f4c6ebc874 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf @@ -147,6 +147,16 @@ Anche il tipo che dichiara questi metodi deve rispettare le regole seguenti: Evita '[ExpectedException]' + + Remove the 'DynamicDataSourceType' argument to use the default auto detect behavior + Remove the 'DynamicDataSourceType' argument to use the default auto detect behavior + + + + Avoid passing an explicit 'DynamicDataSourceType' and use the default auto detect behavior + Avoid passing an explicit 'DynamicDataSourceType' and use the default auto detect behavior + + Do not assert inside 'async void' methods, local functions, or lambdas. Exceptions that are thrown in this context will be unhandled exceptions. When using VSTest under .NET Framework, they will be silently swallowed. When using Microsoft.Testing.Platform or VSTest under modern .NET, they may crash the process. Non dichiarare all'interno di metodi 'async void', funzioni locali o espressioni lambda. Le eccezioni generate in questo contesto saranno eccezioni non gestite. Quando si usa VSTest in .NET Framework, verranno eliminati automaticamente. Quando si usa Microsoft.Testing.Platform o VSTest nella versione moderna di .NET, è possibile che il processo venga arrestato in modo anomalo. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf index ae7471f9e6..90a47991c0 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf @@ -147,6 +147,16 @@ The type declaring these methods should also respect the following rules: '[ExpectedException]' を回避する + + Remove the 'DynamicDataSourceType' argument to use the default auto detect behavior + Remove the 'DynamicDataSourceType' argument to use the default auto detect behavior + + + + Avoid passing an explicit 'DynamicDataSourceType' and use the default auto detect behavior + Avoid passing an explicit 'DynamicDataSourceType' and use the default auto detect behavior + + Do not assert inside 'async void' methods, local functions, or lambdas. Exceptions that are thrown in this context will be unhandled exceptions. When using VSTest under .NET Framework, they will be silently swallowed. When using Microsoft.Testing.Platform or VSTest under modern .NET, they may crash the process. 'async void' メソッド、ローカル関数、またはラムダ内ではアサートしないでください。このコンテキストでスローされる例外は、ハンドルされない例外になります。.NET Frameworkで VSTest を使用すると、警告なしに飲み込まれるようになります。最新の .NET で Microsoft.Testing.Platform または VSTest を使用すると、プロセスがクラッシュする可能性があります。 diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf index 9d22ce3a8d..002b455ed8 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf @@ -147,6 +147,16 @@ The type declaring these methods should also respect the following rules: '[ExpectedException]' 사용 지양 + + Remove the 'DynamicDataSourceType' argument to use the default auto detect behavior + Remove the 'DynamicDataSourceType' argument to use the default auto detect behavior + + + + Avoid passing an explicit 'DynamicDataSourceType' and use the default auto detect behavior + Avoid passing an explicit 'DynamicDataSourceType' and use the default auto detect behavior + + Do not assert inside 'async void' methods, local functions, or lambdas. Exceptions that are thrown in this context will be unhandled exceptions. When using VSTest under .NET Framework, they will be silently swallowed. When using Microsoft.Testing.Platform or VSTest under modern .NET, they may crash the process. 'async void' 메서드, 로컬 함수 또는 람다 내에서 어설션하지 마십시오. 이 컨텍스트에서 throw된 예외는 처리되지 않은 예외가 됩니다. .NET Framework 아래에서 VSTest를 사용하면 자동으로 무시됩니다. 최신 .NET에서 Microsoft.Testing.Platform 또는 VSTest를 사용하는 경우 프로세스가 중단될 수 있습니다. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf index 3f5492237d..511014e7a8 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf @@ -147,6 +147,16 @@ Typ deklarujący te metody powinien również przestrzegać następujących regu Unikaj elementu „[ExpectedException]” + + Remove the 'DynamicDataSourceType' argument to use the default auto detect behavior + Remove the 'DynamicDataSourceType' argument to use the default auto detect behavior + + + + Avoid passing an explicit 'DynamicDataSourceType' and use the default auto detect behavior + Avoid passing an explicit 'DynamicDataSourceType' and use the default auto detect behavior + + Do not assert inside 'async void' methods, local functions, or lambdas. Exceptions that are thrown in this context will be unhandled exceptions. When using VSTest under .NET Framework, they will be silently swallowed. When using Microsoft.Testing.Platform or VSTest under modern .NET, they may crash the process. Nie potwierdzaj wewnątrz metod "async void", funkcji lokalnych ani lambda. Wyjątki, które są zgłaszane w tym kontekście, będą nieobsługiwanymi wyjątkami. W przypadku korzystania z narzędzia VSTest w .NET Framework będą one dyskretnie ściszone. W przypadku korzystania z elementu Microsoft.Testing.Platform lub VSTest w nowoczesnych programach .NET mogą one spowodować awarię procesu. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf index 67886effc7..53c6356d12 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf @@ -147,6 +147,16 @@ O tipo que declara esses métodos também deve respeitar as seguintes regras: Evitar '[ExpectedException]' + + Remove the 'DynamicDataSourceType' argument to use the default auto detect behavior + Remove the 'DynamicDataSourceType' argument to use the default auto detect behavior + + + + Avoid passing an explicit 'DynamicDataSourceType' and use the default auto detect behavior + Avoid passing an explicit 'DynamicDataSourceType' and use the default auto detect behavior + + Do not assert inside 'async void' methods, local functions, or lambdas. Exceptions that are thrown in this context will be unhandled exceptions. When using VSTest under .NET Framework, they will be silently swallowed. When using Microsoft.Testing.Platform or VSTest under modern .NET, they may crash the process. Não asserção dentro de métodos 'async void', funções locais ou lambdas. Exceções lançadas neste contexto serão exceções sem tratamento. Ao usar VSTest sob .NET Framework, eles serão silenciosamente ignoradas. Ao usar Microsoft.Testing.Platform ou VSTest em .NET moderno, o processo pode falhar. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf index 3f3354dd43..e182e64a4f 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf @@ -150,6 +150,16 @@ The type declaring these methods should also respect the following rules: Избегать "[ExpectedException]" + + Remove the 'DynamicDataSourceType' argument to use the default auto detect behavior + Remove the 'DynamicDataSourceType' argument to use the default auto detect behavior + + + + Avoid passing an explicit 'DynamicDataSourceType' and use the default auto detect behavior + Avoid passing an explicit 'DynamicDataSourceType' and use the default auto detect behavior + + Do not assert inside 'async void' methods, local functions, or lambdas. Exceptions that are thrown in this context will be unhandled exceptions. When using VSTest under .NET Framework, they will be silently swallowed. When using Microsoft.Testing.Platform or VSTest under modern .NET, they may crash the process. Не подтверяйте внутри методов async void, локальных функций или лямбда-выражений. Исключения, вызванные в этом контексте, будут необработанные исключения. При использовании VSTest платформа .NET Framework, они будут пропущены без уведомления. При использовании Microsoft.Testing.Platform или VSTest в современной версии .NET они могут привести к сбою процесса. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf index f3a853182b..14e6a30d81 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf @@ -147,6 +147,16 @@ Bu yöntemleri bildiren tipin ayrıca aşağıdaki kurallara uyması gerekir: '[ExpectedException]' kullanmayın + + Remove the 'DynamicDataSourceType' argument to use the default auto detect behavior + Remove the 'DynamicDataSourceType' argument to use the default auto detect behavior + + + + Avoid passing an explicit 'DynamicDataSourceType' and use the default auto detect behavior + Avoid passing an explicit 'DynamicDataSourceType' and use the default auto detect behavior + + Do not assert inside 'async void' methods, local functions, or lambdas. Exceptions that are thrown in this context will be unhandled exceptions. When using VSTest under .NET Framework, they will be silently swallowed. When using Microsoft.Testing.Platform or VSTest under modern .NET, they may crash the process. 'async void' metotları, yerel işlevler veya lambdalar içinde onaylamayın. Bu bağlamda oluşturulan özel durumlar işlenmeyen özel durumlar olacak. VsTest'i .NET Framework, sessizce kırılır. Modern .NET altında Microsoft.Testing.Platform veya VSTest kullanırken işlemi kilitler. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf index 45f0e177b3..f80fea53ae 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf @@ -147,6 +147,16 @@ The type declaring these methods should also respect the following rules: 避免 "[ExpectedException]" + + Remove the 'DynamicDataSourceType' argument to use the default auto detect behavior + Remove the 'DynamicDataSourceType' argument to use the default auto detect behavior + + + + Avoid passing an explicit 'DynamicDataSourceType' and use the default auto detect behavior + Avoid passing an explicit 'DynamicDataSourceType' and use the default auto detect behavior + + Do not assert inside 'async void' methods, local functions, or lambdas. Exceptions that are thrown in this context will be unhandled exceptions. When using VSTest under .NET Framework, they will be silently swallowed. When using Microsoft.Testing.Platform or VSTest under modern .NET, they may crash the process. 不要在 “async void” 方法、本地函数或 lambdas 内断言。在此上下文中引发的异常将是未经处理的异常。在.NET Framework下使用 VSTest 时,将无提示地接受这些测试。在现代 .NET 下使用 Microsoft.Testing.Platform 或 VSTest 时,它们可能会导致进程崩溃。 diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf index 7136911d17..a566285c1b 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf @@ -147,6 +147,16 @@ The type declaring these methods should also respect the following rules: 避免 '[ExpectedException]' + + Remove the 'DynamicDataSourceType' argument to use the default auto detect behavior + Remove the 'DynamicDataSourceType' argument to use the default auto detect behavior + + + + Avoid passing an explicit 'DynamicDataSourceType' and use the default auto detect behavior + Avoid passing an explicit 'DynamicDataSourceType' and use the default auto detect behavior + + Do not assert inside 'async void' methods, local functions, or lambdas. Exceptions that are thrown in this context will be unhandled exceptions. When using VSTest under .NET Framework, they will be silently swallowed. When using Microsoft.Testing.Platform or VSTest under modern .NET, they may crash the process. 不要在 'async void' 方法、本機函數或 lambdas 內判斷提示。在此內容中擲回的例外狀況將會是未處理的例外狀況。在 .NET Framework 下使用 VSTest 時,會以無訊息方式接受。在現代 .NET 下使用 Microsoft.Testing.Platform 或 VSTest 時,可能會損毀進程。 From d1f0c3d9a10670d9c18cabb512b635e457284522 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Thu, 31 Jul 2025 22:23:42 +0200 Subject: [PATCH 346/541] Use Arcade's resx generation (#6266) --- Directory.Build.props | 4 + Directory.Build.targets | 7 + .../VSTestAdapter/MSTestExecutor.cs | 1 + .../Discovery/AssemblyEnumeratorWrapper.cs | 1 - .../Discovery/TestMethodValidator.cs | 1 - .../Discovery/TypeValidator.cs | 1 - .../Execution/ExceptionHelper.cs | 1 - .../Execution/TypeCache.cs | 1 - .../Extensions/MethodInfoExtensions.cs | 1 - .../Helpers/MSTestDiscovererHelpers.cs | 1 - .../Helpers/ReflectHelper.cs | 1 - .../Helpers/RunSettingsUtilities.cs | 1 - .../Helpers/TestRunParameters.cs | 1 - .../MSTestAdapter.PlatformServices.csproj | 15 +- .../MSTestSettings.cs | 2 + .../Resources/Resource.Designer.cs | 1105 ------------- .../RunConfigurationSettings.cs | 1 - .../CodeFixResources.Designer.cs | 297 ---- .../MSTest.Analyzers.CodeFixes.csproj | 5 - .../MSTest.Analyzers/MSTest.Analyzers.csproj | 5 - .../MSTest.Analyzers/Resources.Designer.cs | 1460 ----------------- ...esting.Extensions.AzureDevOpsReport.csproj | 4 - ...rosoft.Testing.Extensions.CrashDump.csproj | 4 - ...crosoft.Testing.Extensions.HangDump.csproj | 4 - ...rosoft.Testing.Extensions.HotReload.csproj | 15 - .../Resources/ExtensionResources.Designer.cs | 90 - ...icrosoft.Testing.Extensions.MSBuild.csproj | 4 - .../Microsoft.Testing.Extensions.Retry.csproj | 15 - .../Resources/ExtensionResources.Designer.cs | 284 ---- ...rosoft.Testing.Extensions.Telemetry.csproj | 4 - ...rosoft.Testing.Extensions.TrxReport.csproj | 4 - ...oft.Testing.Extensions.VSTestBridge.csproj | 4 - .../Microsoft.Testing.Platform.MSBuild.csproj | 4 - .../Microsoft.Testing.Platform.csproj | 4 - .../FrameworkExtensionsMessages.Designer.cs | 81 - .../TestFramework.Extensions.csproj | 15 +- .../Resources/FrameworkMessages.Designer.cs | 748 --------- .../TestFramework/TestFramework.csproj | 15 +- .../Deployment/DeploymentItemTests.cs | 2 +- .../Discovery/AssemblyEnumeratorTests.cs | 2 +- .../AssemblyEnumeratorWrapperTests.cs | 2 +- .../Discovery/TypeValidatorTests.cs | 2 +- .../Execution/TestMethodInfoTests.cs | 1 + .../Execution/TestMethodRunnerTests.cs | 1 + .../Extensions/ExceptionExtensionsTests.cs | 2 +- .../Extensions/MethodInfoExtensionsTests.cs | 2 +- .../MSTestSettingsTests.cs | 2 +- .../TestContextImplementationTests.cs | 1 + .../Utilities/DeploymentUtilityTests.cs | 2 +- .../ns13DeploymentItemUtilityTests.cs | 2 +- .../Attributes/DynamicDataAttributeTests.cs | 2 + 51 files changed, 31 insertions(+), 4203 deletions(-) delete mode 100644 src/Adapter/MSTestAdapter.PlatformServices/Resources/Resource.Designer.cs delete mode 100644 src/Analyzers/MSTest.Analyzers.CodeFixes/CodeFixResources.Designer.cs delete mode 100644 src/Analyzers/MSTest.Analyzers/Resources.Designer.cs delete mode 100644 src/Platform/Microsoft.Testing.Extensions.HotReload/Resources/ExtensionResources.Designer.cs delete mode 100644 src/Platform/Microsoft.Testing.Extensions.Retry/Resources/ExtensionResources.Designer.cs delete mode 100644 src/TestFramework/TestFramework.Extensions/Resources/FrameworkExtensionsMessages.Designer.cs delete mode 100644 src/TestFramework/TestFramework/Resources/FrameworkMessages.Designer.cs diff --git a/Directory.Build.props b/Directory.Build.props index 2f31b2c195..52438c9dd4 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -5,6 +5,10 @@ true + + + + false diff --git a/Directory.Build.targets b/Directory.Build.targets index 5b18285eb1..f509b732e7 100644 --- a/Directory.Build.targets +++ b/Directory.Build.targets @@ -1,5 +1,12 @@ + + + + + + + diff --git a/src/Adapter/MSTest.TestAdapter/VSTestAdapter/MSTestExecutor.cs b/src/Adapter/MSTest.TestAdapter/VSTestAdapter/MSTestExecutor.cs index 82b316d549..7f041e0559 100644 --- a/src/Adapter/MSTest.TestAdapter/VSTestAdapter/MSTestExecutor.cs +++ b/src/Adapter/MSTest.TestAdapter/VSTestAdapter/MSTestExecutor.cs @@ -4,6 +4,7 @@ using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution; using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Interface; +using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Resources; using Microsoft.VisualStudio.TestPlatform.ObjectModel; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging; diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Discovery/AssemblyEnumeratorWrapper.cs b/src/Adapter/MSTestAdapter.PlatformServices/Discovery/AssemblyEnumeratorWrapper.cs index 5bb2e65b9a..5633389cbd 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Discovery/AssemblyEnumeratorWrapper.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Discovery/AssemblyEnumeratorWrapper.cs @@ -2,7 +2,6 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel; -using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter; using Microsoft.VisualStudio.TestTools.UnitTesting; diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Discovery/TestMethodValidator.cs b/src/Adapter/MSTestAdapter.PlatformServices/Discovery/TestMethodValidator.cs index 846a92dd72..04ca9f18ba 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Discovery/TestMethodValidator.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Discovery/TestMethodValidator.cs @@ -3,7 +3,6 @@ using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Extensions; using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Helpers; -using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Discovery; diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Discovery/TypeValidator.cs b/src/Adapter/MSTestAdapter.PlatformServices/Discovery/TypeValidator.cs index 5589955516..b82623ca7c 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Discovery/TypeValidator.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Discovery/TypeValidator.cs @@ -2,7 +2,6 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Helpers; -using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Discovery; diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Execution/ExceptionHelper.cs b/src/Adapter/MSTestAdapter.PlatformServices/Execution/ExceptionHelper.cs index 8e774940c0..1da2014846 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Execution/ExceptionHelper.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Execution/ExceptionHelper.cs @@ -2,7 +2,6 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel; -using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution; diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Execution/TypeCache.cs b/src/Adapter/MSTestAdapter.PlatformServices/Execution/TypeCache.cs index 3ac9676a1e..e775efc7c6 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Execution/TypeCache.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Execution/TypeCache.cs @@ -8,7 +8,6 @@ using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Extensions; using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Helpers; using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel; -using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Interface; using Microsoft.VisualStudio.TestTools.UnitTesting; diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Extensions/MethodInfoExtensions.cs b/src/Adapter/MSTestAdapter.PlatformServices/Extensions/MethodInfoExtensions.cs index 46fb6e6d53..3511b19253 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Extensions/MethodInfoExtensions.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Extensions/MethodInfoExtensions.cs @@ -4,7 +4,6 @@ using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Helpers; using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel; using Microsoft.VisualStudio.TestPlatform.MSTestAdapter; -using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Extensions; using Microsoft.VisualStudio.TestTools.UnitTesting; diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Helpers/MSTestDiscovererHelpers.cs b/src/Adapter/MSTestAdapter.PlatformServices/Helpers/MSTestDiscovererHelpers.cs index 1a5b5ef336..3b76323e58 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Helpers/MSTestDiscovererHelpers.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Helpers/MSTestDiscovererHelpers.cs @@ -2,7 +2,6 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel; -using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Interface; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging; diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Helpers/ReflectHelper.cs b/src/Adapter/MSTestAdapter.PlatformServices/Helpers/ReflectHelper.cs index c671899b5a..be1a1a8fe4 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Helpers/ReflectHelper.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Helpers/ReflectHelper.cs @@ -3,7 +3,6 @@ using System.Security; -using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; using Microsoft.VisualStudio.TestPlatform.ObjectModel; using Microsoft.VisualStudio.TestTools.UnitTesting; diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Helpers/RunSettingsUtilities.cs b/src/Adapter/MSTestAdapter.PlatformServices/Helpers/RunSettingsUtilities.cs index fa73447efd..e4a457b0cc 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Helpers/RunSettingsUtilities.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Helpers/RunSettingsUtilities.cs @@ -1,7 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. -using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; using Microsoft.VisualStudio.TestPlatform.ObjectModel; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Utilities; using Microsoft.VisualStudio.TestTools.UnitTesting; diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Helpers/TestRunParameters.cs b/src/Adapter/MSTestAdapter.PlatformServices/Helpers/TestRunParameters.cs index 8cd4b81655..9a324be172 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Helpers/TestRunParameters.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Helpers/TestRunParameters.cs @@ -1,7 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. -using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; using Microsoft.VisualStudio.TestPlatform.ObjectModel; namespace Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Helpers; diff --git a/src/Adapter/MSTestAdapter.PlatformServices/MSTestAdapter.PlatformServices.csproj b/src/Adapter/MSTestAdapter.PlatformServices/MSTestAdapter.PlatformServices.csproj index e3a37a6b2d..5b5c5d1758 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/MSTestAdapter.PlatformServices.csproj +++ b/src/Adapter/MSTestAdapter.PlatformServices/MSTestAdapter.PlatformServices.csproj @@ -61,22 +61,9 @@ - - - True - True - Resource.resx - - - ResXFileCodeGenerator - Resource.Designer.cs - Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices - Designer - - - + diff --git a/src/Adapter/MSTestAdapter.PlatformServices/MSTestSettings.cs b/src/Adapter/MSTestAdapter.PlatformServices/MSTestSettings.cs index 54f8c20c6e..1637d7f3f0 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/MSTestSettings.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/MSTestSettings.cs @@ -2,7 +2,9 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel; +#if !WINDOWS_UWP using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; +#endif using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Interface; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging; diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/Resource.Designer.cs b/src/Adapter/MSTestAdapter.PlatformServices/Resources/Resource.Designer.cs deleted file mode 100644 index b934d1b01d..0000000000 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/Resource.Designer.cs +++ /dev/null @@ -1,1105 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:4.0.30319.42000 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices { - using System; - - - /// - /// A strongly-typed resource class, for looking up localized strings, etc. - /// - // This class was auto-generated by the StronglyTypedResourceBuilder - // class via a tool like ResGen or Visual Studio. - // To add or remove a member, edit your .ResX file then rerun ResGen - // with the /str option, or rebuild your VS project. - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - internal class Resource { - - private static global::System.Resources.ResourceManager resourceMan; - - private static global::System.Globalization.CultureInfo resourceCulture; - - [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - internal Resource() { - } - - /// - /// Returns the cached ResourceManager instance used by this class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Resources.ResourceManager ResourceManager { - get { - if (object.ReferenceEquals(resourceMan, null)) { - global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Resources.Reso" + - "urce", typeof(Resource).Assembly); - resourceMan = temp; - } - return resourceMan; - } - } - - /// - /// Overrides the current thread's CurrentUICulture property for all - /// resource lookups using this strongly typed resource class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Globalization.CultureInfo Culture { - get { - return resourceCulture; - } - set { - resourceCulture = value; - } - } - - /// - /// Looks up a localized string similar to Assembly cleanup method '{0}.{1}' timed out after {2}ms. - /// - internal static string AssemblyCleanupTimedOut { - get { - return ResourceManager.GetString("AssemblyCleanupTimedOut", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Assembly cleanup method '{0}.{1}' was canceled. - /// - internal static string AssemblyCleanupWasCancelled { - get { - return ResourceManager.GetString("AssemblyCleanupWasCancelled", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Assembly initialize method '{0}.{1}' timed out after {2}ms. - /// - internal static string AssemblyInitializeTimedOut { - get { - return ResourceManager.GetString("AssemblyInitializeTimedOut", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Assembly initialize method '{0}.{1}' was canceled. - /// - internal static string AssemblyInitializeWasCancelled { - get { - return ResourceManager.GetString("AssemblyInitializeWasCancelled", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to MSTestAdapterV2. - /// - internal static string AttachmentSetDisplayName { - get { - return ResourceManager.GetString("AttachmentSetDisplayName", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Exception occurred while enumerating IDataSource attribute on "{0}.{1}": {2}. - /// - internal static string CannotEnumerateIDataSourceAttribute { - get { - return ResourceManager.GetString("CannotEnumerateIDataSourceAttribute", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Exception occurred while expanding IDataSource rows from attribute on "{0}.{1}": {2}. - /// - internal static string CannotExpandIDataSourceAttribute { - get { - return ResourceManager.GetString("CannotExpandIDataSourceAttribute", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Data on index {0} for "{1}" cannot be serialized. All data provided through "IDataSource" should be serializable. If you need to test non-serializable data sources, please make sure you add "TestDataSourceDiscovery" attribute on your test assembly and set the discovery option to "DuringExecution".. - /// - internal static string CannotExpandIDataSourceAttribute_CannotSerialize { - get { - return ResourceManager.GetString("CannotExpandIDataSourceAttribute_CannotSerialize", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Display name "{2}" on indexes {0} and {1} are duplicate. Display names should be unique.. - /// - internal static string CannotExpandIDataSourceAttribute_DuplicateDisplayName { - get { - return ResourceManager.GetString("CannotExpandIDataSourceAttribute_DuplicateDisplayName", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Could not find file '{0}'.. - /// - internal static string CannotFindFile { - get { - return ResourceManager.GetString("CannotFindFile", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Cannot run test method '{0}.{1}': Test data doesn't match method parameters. Either the count or types are different. - ///Test expected {2} parameter(s), with types '{3}', - ///but received {4} argument(s), with types '{5}'.. - /// - internal static string CannotRunTestArgumentsMismatchError { - get { - return ResourceManager.GetString("CannotRunTestArgumentsMismatchError", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Cannot run test method '{0}.{1}': Method has parameters, but does not define any test source. Use '[DataRow]', '[DynamicData]', or a custom 'ITestDataSource' data source to provide test data.. - /// - internal static string CannotRunTestMethodNoDataError { - get { - return ResourceManager.GetString("CannotRunTestMethodNoDataError", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Class cleanup method '{0}.{1}' timed out after {2}ms. - /// - internal static string ClassCleanupTimedOut { - get { - return ResourceManager.GetString("ClassCleanupTimedOut", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Class cleanup method '{0}.{1}' was canceled. - /// - internal static string ClassCleanupWasCancelled { - get { - return ResourceManager.GetString("ClassCleanupWasCancelled", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Class initialize method '{0}.{1}' timed out after {2}ms. - /// - internal static string ClassInitializeTimedOut { - get { - return ResourceManager.GetString("ClassInitializeTimedOut", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Class initialize method '{0}.{1}' was canceled. - /// - internal static string ClassInitializeWasCancelled { - get { - return ResourceManager.GetString("ClassInitializeWasCancelled", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The parameter should not be null or empty.. - /// - internal static string Common_CannotBeNullOrEmpty { - get { - return ResourceManager.GetString("Common_CannotBeNullOrEmpty", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to MSTestAdapter failed to discover tests in class '{0}' of assembly '{1}' because {2}.. - /// - internal static string CouldNotInspectTypeDuringDiscovery { - get { - return ResourceManager.GetString("CouldNotInspectTypeDuringDiscovery", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to {0} (Data Row {1}). - /// - internal static string DataDrivenResultDisplayName { - get { - return ResourceManager.GetString("DataDrivenResultDisplayName", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Debug Trace:. - /// - internal static string DebugTraceBanner { - get { - return ResourceManager.GetString("DebugTraceBanner", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Test Run deployment issue: Bad deployment item: '{0}': output directory '{1}' specifies the item to be deployed outside deployment root directory which is not allowed.. - /// - internal static string DeploymentErrorBadDeploymentItem { - get { - return ResourceManager.GetString("DeploymentErrorBadDeploymentItem", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Test Run deployment issue: Failed to access output directory '{1}' specified by deployment item '{0}', the item will not be deployed: {2}: {3}. - /// - internal static string DeploymentErrorFailedToAccesOutputDirectory { - get { - return ResourceManager.GetString("DeploymentErrorFailedToAccesOutputDirectory", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Test Run deployment issue: Failed to access the file '{0}': {1}: {2}. - /// - internal static string DeploymentErrorFailedToAccessFile { - get { - return ResourceManager.GetString("DeploymentErrorFailedToAccessFile", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Test Run deployment issue: Failed to copy file '{0}' to '{1}': {2}: {3}. - /// - internal static string DeploymentErrorFailedToCopyWithOverwrite { - get { - return ResourceManager.GetString("DeploymentErrorFailedToCopyWithOverwrite", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Test Run deployment issue: Failed to deploy dependencies for test storage '{0}': {1}. - /// - internal static string DeploymentErrorFailedToDeployDependencies { - get { - return ResourceManager.GetString("DeploymentErrorFailedToDeployDependencies", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Test Run deployment issue: Failed to get the file for {0}: {1}: {2}. - /// - internal static string DeploymentErrorFailedToGetFileForDeploymentItem { - get { - return ResourceManager.GetString("DeploymentErrorFailedToGetFileForDeploymentItem", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Test Run deployment issue: an error occurred while getting satellite assemblies for {0}: {1}: {2}. - /// - internal static string DeploymentErrorGettingSatellite { - get { - return ResourceManager.GetString("DeploymentErrorGettingSatellite", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to deployment item '{0}'. - /// - internal static string DeploymentItem { - get { - return ResourceManager.GetString("DeploymentItem", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Invalid deployment item: the specified path '{0}' or output directory '{1}' contains illegal characters.. - /// - internal static string DeploymentItemContainsInvalidCharacters { - get { - return ResourceManager.GetString("DeploymentItemContainsInvalidCharacters", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Invalid deployment item: the output directory cannot be null.. - /// - internal static string DeploymentItemOutputDirectoryCannotBeNull { - get { - return ResourceManager.GetString("DeploymentItemOutputDirectoryCannotBeNull", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Invalid deployment item: the specified output directory '{0}' is not relative.. - /// - internal static string DeploymentItemOutputDirectoryMustBeRelative { - get { - return ResourceManager.GetString("DeploymentItemOutputDirectoryMustBeRelative", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Invalid deployment item: the path must contain at least one character.. - /// - internal static string DeploymentItemPathCannotBeNullOrEmpty { - get { - return ResourceManager.GetString("DeploymentItemPathCannotBeNullOrEmpty", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to deployment item '{0}' (output directory '{1}'). - /// - internal static string DeploymentItemWithOutputDirectory { - get { - return ResourceManager.GetString("DeploymentItemWithOutputDirectory", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to [MSTest][Discovery][{0}] {1}. - /// - internal static string DiscoveryWarning { - get { - return ResourceManager.GetString("DiscoveryWarning", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Both '.runsettings' and '.testconfig.json' files have been detected. Please select only one of these test configuration files.. - /// - internal static string DuplicateConfigurationError { - get { - return ResourceManager.GetString("DuplicateConfigurationError", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to {0}: {1}. - /// - internal static string EnumeratorLoadTypeErrorFormat { - get { - return ResourceManager.GetString("EnumeratorLoadTypeErrorFormat", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to "{0}": (Failed to get exception description due to an exception of type "{1}".. - /// - internal static string ExceptionOccuredWhileGettingTheExceptionDescription { - get { - return ResourceManager.GetString("ExceptionOccuredWhileGettingTheExceptionDescription", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Exceptions thrown:. - /// - internal static string ExceptionsThrown { - get { - return ResourceManager.GetString("ExceptionsThrown", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Test '{0}' was canceled. - /// - internal static string Execution_Test_Cancelled { - get { - return ResourceManager.GetString("Execution_Test_Cancelled", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Test '{0}' timed out after {1}ms. - /// - internal static string Execution_Test_Timeout { - get { - return ResourceManager.GetString("Execution_Test_Timeout", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Getting custom attributes for type {0} threw exception (will ignore and use the reflection way): {1}. - /// - internal static string FailedToGetCustomAttribute { - get { - return ResourceManager.GetString("FailedToGetCustomAttribute", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The type of the generic parameter '{0}' could not be inferred.. - /// - internal static string GenericParameterCantBeInferred { - get { - return ResourceManager.GetString("GenericParameterCantBeInferred", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The generic test method '{0}' doesn't have arguments, so the generic parameter cannot be inferred.. - /// - internal static string GenericParameterCantBeInferredBecauseNoArguments { - get { - return ResourceManager.GetString("GenericParameterCantBeInferredBecauseNoArguments", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Found two conflicting types for generic parameter '{0}'. The conflicting types are '{1}' and '{2}'.. - /// - internal static string GenericParameterConflict { - get { - return ResourceManager.GetString("GenericParameterConflict", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}.. - /// - internal static string InvalidClassCleanupLifecycleValue { - get { - return ResourceManager.GetString("InvalidClassCleanupLifecycleValue", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}.. - /// - internal static string InvalidParallelScopeValue { - get { - return ResourceManager.GetString("InvalidParallelScopeValue", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer.. - /// - internal static string InvalidParallelWorkersValue { - get { - return ResourceManager.GetString("InvalidParallelWorkersValue", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Invalid settings '{0}'. Unexpected XmlAttribute: '{1}'.. - /// - internal static string InvalidSettingsXmlAttribute { - get { - return ResourceManager.GetString("InvalidSettingsXmlAttribute", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to MSTestAdapter encountered an unexpected element '{0}' in its settings '{1}'. Remove this element and try again.. - /// - internal static string InvalidSettingsXmlElement { - get { - return ResourceManager.GetString("InvalidSettingsXmlElement", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Invalid settings '{0}'. Unexpected XmlElement: '{1}'.. - /// - internal static string InvalidSettingsXmlElement1 { - get { - return ResourceManager.GetString("InvalidSettingsXmlElement1", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Invalid value '{0}' for runsettings entry '{1}', setting will be ignored.. - /// - internal static string InvalidValue { - get { - return ResourceManager.GetString("InvalidValue", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Invalid value '{0}' for runsettings entry '{1}', setting will be ignored.. - /// - internal static string InvalidValue1 { - get { - return ResourceManager.GetString("InvalidValue1", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Warning : A testsettings file or a vsmdi file is not supported with the MSTest V2 Adapter.. - /// - internal static string LegacyScenariosNotSupportedWarning { - get { - return ResourceManager.GetString("LegacyScenariosNotSupportedWarning", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Test Run deployment issue: The assembly or module '{0}' was not found. Reason: {1}. - /// - internal static string MissingDeploymentDependency { - get { - return ResourceManager.GetString("MissingDeploymentDependency", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Test Run deployment issue: The assembly or module '{0}' was not found.. - /// - internal static string MissingDeploymentDependencyWithoutReason { - get { - return ResourceManager.GetString("MissingDeploymentDependencyWithoutReason", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to An older version of MSTestV2 package is loaded in assembly, test discovery might fail to discover all data tests if they depend on `.runsettings` file.. - /// - internal static string OlderTFMVersionFound { - get { - return ResourceManager.GetString("OlderTFMVersionFound", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Running tests in any of the provided sources is not supported for the selected platform. - /// - internal static string SourcesNotSupported { - get { - return ResourceManager.GetString("SourcesNotSupported", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Runsettings entry '<ExecutionApartmentState>STA</ExecutionApartmentState>' is not supported on non-Windows OSes.. - /// - internal static string STAIsOnlySupportedOnWindowsWarning { - get { - return ResourceManager.GetString("STAIsOnlySupportedOnWindowsWarning", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Failed to discover tests from assembly {0}. Reason:{1}. - /// - internal static string TestAssembly_AssemblyDiscoveryFailure { - get { - return ResourceManager.GetString("TestAssembly_AssemblyDiscoveryFailure", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to File does not exist: {0}. - /// - internal static string TestAssembly_FileDoesNotExist { - get { - return ResourceManager.GetString("TestAssembly_FileDoesNotExist", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Test cleanup method '{0}.{1}' timed out after {2}ms. - /// - internal static string TestCleanupTimedOut { - get { - return ResourceManager.GetString("TestCleanupTimedOut", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Test cleanup method '{0}.{1}' was canceled. - /// - internal static string TestCleanupWasCancelled { - get { - return ResourceManager.GetString("TestCleanupWasCancelled", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to TestContext cannot be Null.. - /// - internal static string TestContextIsNull { - get { - return ResourceManager.GetString("TestContextIsNull", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to TestContext Messages:. - /// - internal static string TestContextMessageBanner { - get { - return ResourceManager.GetString("TestContextMessageBanner", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Test initialize method '{0}.{1}' timed out after {2}ms. - /// - internal static string TestInitializeTimedOut { - get { - return ResourceManager.GetString("TestInitializeTimedOut", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Test initialize method '{0}.{1}' was canceled. - /// - internal static string TestInitializeWasCancelled { - get { - return ResourceManager.GetString("TestInitializeWasCancelled", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Test method {0} was not found.. - /// - internal static string TestNotFound { - get { - return ResourceManager.GetString("TestNotFound", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}). - /// - internal static string TestParallelizationBanner { - get { - return ResourceManager.GetString("TestParallelizationBanner", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to {0}_{1} {2}. - /// - internal static string TestRunName { - get { - return ResourceManager.GetString("TestRunName", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Unable to load types from the test source '{0}'. Some or all of the tests in this source may not be discovered. - ///Error: {1}. - /// - internal static string TypeLoadFailed { - get { - return ResourceManager.GetString("TypeLoadFailed", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Assembly Cleanup method {0}.{1} failed. Error Message: {2}. StackTrace: {3}. - /// - internal static string UTA_AssemblyCleanupMethodWasUnsuccesful { - get { - return ResourceManager.GetString("UTA_AssemblyCleanupMethodWasUnsuccesful", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Assembly Initialization method {0}.{1} threw exception. {2}: {3}. Aborting test execution.. - /// - internal static string UTA_AssemblyInitMethodThrows { - get { - return ResourceManager.GetString("UTA_AssemblyInitMethodThrows", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Class Cleanup method {0}.{1} failed. Error Message: {2}. Stack Trace: {3}. - /// - internal static string UTA_ClassCleanupMethodWasUnsuccesful { - get { - return ResourceManager.GetString("UTA_ClassCleanupMethodWasUnsuccesful", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Class Initialization method {0}.{1} threw exception. {2}: {3}.. - /// - internal static string UTA_ClassInitMethodThrows { - get { - return ResourceManager.GetString("UTA_ClassInitMethodThrows", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'.. - /// - internal static string UTA_ClassOrAssemblyCleanupMethodHasWrongSignature { - get { - return ResourceManager.GetString("UTA_ClassOrAssemblyCleanupMethodHasWrongSignature", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Method {0}.{1} has wrong signature. The method must be static, public, does not return a value and should take a single parameter of type TestContext. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'.. - /// - internal static string UTA_ClassOrAssemblyInitializeMethodHasWrongSignature { - get { - return ResourceManager.GetString("UTA_ClassOrAssemblyInitializeMethodHasWrongSignature", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to TestCleanup method {0}.{1} threw exception. {2}.. - /// - internal static string UTA_CleanupMethodThrows { - get { - return ResourceManager.GetString("UTA_CleanupMethodThrows", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Error calling Test Cleanup method for test class {0}: {1}. - /// - internal static string UTA_CleanupMethodThrowsGeneralError { - get { - return ResourceManager.GetString("UTA_CleanupMethodThrowsGeneralError", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to TestCleanup Stack Trace. - /// - internal static string UTA_CleanupStackTrace { - get { - return ResourceManager.GetString("UTA_CleanupStackTrace", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Data source '{0}' cannot be found in the test configuration settings. - /// - internal static string UTA_DataSourceConfigurationSectionMissing { - get { - return ResourceManager.GetString("UTA_DataSourceConfigurationSectionMissing", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to --- End of inner exception stack trace ---. - /// - internal static string UTA_EndOfInnerExceptionTrace { - get { - return ResourceManager.GetString("UTA_EndOfInnerExceptionTrace", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The unit test adapter failed to connect to the data source or to read the data. For more information on troubleshooting this error, see "Troubleshooting Data-Driven Unit Tests" (http://go.microsoft.com/fwlink/?LinkId=62412) in the MSDN Library. Error details: {0}. - /// - internal static string UTA_ErrorDataConnectionFailed { - get { - return ResourceManager.GetString("UTA_ErrorDataConnectionFailed", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to UTA007: Method {1} defined in class {0} does not have correct signature. Test method marked with the [TestMethod] attribute must be non-static, public, return-type as void and should not take any parameter. Example: public void Test.Class1.Test(). Additionally, if you are using async-await in test method then return-type must be 'Task' or 'ValueTask'. Example: public async Task Test.Class1.Test2(). - /// - internal static string UTA_ErrorIncorrectTestMethodSignature { - get { - return ResourceManager.GetString("UTA_ErrorIncorrectTestMethodSignature", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to UTA031: class {0} does not have valid TestContext property. TestContext must be of type TestContext, must be non-static, and must be public. For example: public TestContext TestContext.. - /// - internal static string UTA_ErrorInValidTestContextSignature { - get { - return ResourceManager.GetString("UTA_ErrorInValidTestContextSignature", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to UTA054: {0}.{1} has invalid Timeout attribute. The timeout must be an integer value greater than 0.. - /// - internal static string UTA_ErrorInvalidTimeout { - get { - return ResourceManager.GetString("UTA_ErrorInvalidTimeout", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to UTA014: {0}: Cannot define more than one method with the AssemblyCleanup attribute inside an assembly.. - /// - internal static string UTA_ErrorMultiAssemblyClean { - get { - return ResourceManager.GetString("UTA_ErrorMultiAssemblyClean", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to UTA013: {0}: Cannot define more than one method with the AssemblyInitialize attribute inside an assembly.. - /// - internal static string UTA_ErrorMultiAssemblyInit { - get { - return ResourceManager.GetString("UTA_ErrorMultiAssemblyInit", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to UTA026: {0}: Cannot define more than one method with the ClassCleanup attribute inside a class.. - /// - internal static string UTA_ErrorMultiClassClean { - get { - return ResourceManager.GetString("UTA_ErrorMultiClassClean", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to UTA025: {0}: Cannot define more than one method with the ClassInitialize attribute inside a class.. - /// - internal static string UTA_ErrorMultiClassInit { - get { - return ResourceManager.GetString("UTA_ErrorMultiClassInit", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to UTA024: {0}: Cannot define more than one method with the TestCleanup attribute.. - /// - internal static string UTA_ErrorMultiClean { - get { - return ResourceManager.GetString("UTA_ErrorMultiClean", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to UTA018: {0}: Cannot define more than one method with the TestInitialize attribute.. - /// - internal static string UTA_ErrorMultiInit { - get { - return ResourceManager.GetString("UTA_ErrorMultiInit", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to UTA001: TestClass attribute defined on non-public class {0}. - /// - internal static string UTA_ErrorNonPublicTestClass { - get { - return ResourceManager.GetString("UTA_ErrorNonPublicTestClass", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to UTA023: {0}: Cannot define predefined property {2} on method {1}.. - /// - internal static string UTA_ErrorPredefinedTestProperty { - get { - return ResourceManager.GetString("UTA_ErrorPredefinedTestProperty", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to TestClass attribute defined on generic non-abstract class {0}. - /// - internal static string UTA_ErrorTestClassIsGenericNonAbstract { - get { - return ResourceManager.GetString("UTA_ErrorTestClassIsGenericNonAbstract", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to UTA021: {0}: Null or empty custom property defined on method {1}. The custom property must have a valid name.. - /// - internal static string UTA_ErrorTestPropertyNullOrEmpty { - get { - return ResourceManager.GetString("UTA_ErrorTestPropertyNullOrEmpty", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to An unhandled exception was thrown by the 'Execute' method. Please report this error to the author of the attribute '{0}'. - ///{1}. - /// - internal static string UTA_ExecuteThrewException { - get { - return ResourceManager.GetString("UTA_ExecuteThrewException", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The ExpectedException attribute defined on test method {0}.{1} threw an exception during construction. - ///{2}. - /// - internal static string UTA_ExpectedExceptionAttributeConstructionException { - get { - return ResourceManager.GetString("UTA_ExpectedExceptionAttributeConstructionException", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Failed to obtain the exception thrown by test method {0}.{1}.. - /// - internal static string UTA_FailedToGetTestMethodException { - get { - return ResourceManager.GetString("UTA_FailedToGetTestMethodException", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Initialization method {0}.{1} threw exception. {2}.. - /// - internal static string UTA_InitMethodThrows { - get { - return ResourceManager.GetString("UTA_InitMethodThrows", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Unable to create instance of class {0}. Error: {1}.. - /// - internal static string UTA_InstanceCreationError { - get { - return ResourceManager.GetString("UTA_InstanceCreationError", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Method {0}.{1} does not exist.. - /// - internal static string UTA_MethodDoesNotExists { - get { - return ResourceManager.GetString("UTA_MethodDoesNotExists", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The test method '{0}.{1}' has multiple attributes derived from '{2}' defined on it. Only one such attribute is allowed.. - /// - internal static string UTA_MultipleAttributesOnTestMethod { - get { - return ResourceManager.GetString("UTA_MultipleAttributesOnTestMethod", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Error in executing test. No result returned by extension. If using extension of TestMethodAttribute then please contact vendor.. - /// - internal static string UTA_NoTestResult { - get { - return ResourceManager.GetString("UTA_NoTestResult", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Cannot find a valid constructor for test class '{0}'. Valid constructors are 'public' and either parameterless or with one parameter of type 'TestContext'.. - /// - internal static string UTA_NoValidConstructor { - get { - return ResourceManager.GetString("UTA_NoValidConstructor", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Unable to find property {0}.TestContext. Error:{1}.. - /// - internal static string UTA_TestContextLoadError { - get { - return ResourceManager.GetString("UTA_TestContextLoadError", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Unable to set TestContext property for the class {0}. Error: {1}.. - /// - internal static string UTA_TestContextSetError { - get { - return ResourceManager.GetString("UTA_TestContextSetError", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The {0}.TestContext has incorrect type.. - /// - internal static string UTA_TestContextTypeMismatchLoadError { - get { - return ResourceManager.GetString("UTA_TestContextTypeMismatchLoadError", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Method {0}.{1} has wrong signature. The method must be non-static, public, does not return a value and should not take any parameter. Additionally, if you are using async-await in method then return-type must be 'Task' or 'ValueTask'.. - /// - internal static string UTA_TestInitializeAndCleanupMethodHasWrongSignature { - get { - return ResourceManager.GetString("UTA_TestInitializeAndCleanupMethodHasWrongSignature", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Test method {0}.{1} threw exception: - ///{2}. - /// - internal static string UTA_TestMethodThrows { - get { - return ResourceManager.GetString("UTA_TestMethodThrows", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Unable to get type {0}. Error: {1}.. - /// - internal static string UTA_TypeLoadError { - get { - return ResourceManager.GetString("UTA_TypeLoadError", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The called code threw an exception that was caught, but the exception value was null. - /// - internal static string UTA_UserCodeThrewNullValueException { - get { - return ResourceManager.GetString("UTA_UserCodeThrewNullValueException", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to {0} For UWP projects, if you are using UI objects in test consider using [UITestMethod] attribute instead of [TestMethod] to execute test in UI thread.. - /// - internal static string UTA_WrongThread { - get { - return ResourceManager.GetString("UTA_WrongThread", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to (Failed to get the message for an exception of type {0} due to an exception.). - /// - internal static string UTF_FailedToGetExceptionMessage { - get { - return ResourceManager.GetString("UTF_FailedToGetExceptionMessage", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 'MSTest.TestAdapter' and 'MSTest.TestFramework' must have the same version. Found 'MSTest.TestAdapter' version '{0}' and 'MSTest.TestFramework' version '{1}'.. - /// - internal static string VersionMismatchBetweenAdapterAndFramework { - get { - return ResourceManager.GetString("VersionMismatchBetweenAdapterAndFramework", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Wrong number of objects for permutation. Should be greater than zero.. - /// - internal static string WrongNumberOfObjects { - get { - return ResourceManager.GetString("WrongNumberOfObjects", resourceCulture); - } - } - } -} diff --git a/src/Adapter/MSTestAdapter.PlatformServices/RunConfigurationSettings.cs b/src/Adapter/MSTestAdapter.PlatformServices/RunConfigurationSettings.cs index 41b1ad7058..915bca4761 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/RunConfigurationSettings.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/RunConfigurationSettings.cs @@ -2,7 +2,6 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. #if !WINDOWS_UWP -using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Interface; #endif diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/CodeFixResources.Designer.cs b/src/Analyzers/MSTest.Analyzers.CodeFixes/CodeFixResources.Designer.cs deleted file mode 100644 index 0ffb6ab9dc..0000000000 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/CodeFixResources.Designer.cs +++ /dev/null @@ -1,297 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:4.0.30319.42000 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace MSTest.Analyzers { - using System; - - - /// - /// A strongly-typed resource class, for looking up localized strings, etc. - /// - // This class was auto-generated by the StronglyTypedResourceBuilder - // class via a tool like ResGen or Visual Studio. - // To add or remove a member, edit your .ResX file then rerun ResGen - // with the /str option, or rebuild your VS project. - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - internal class CodeFixResources { - - private static global::System.Resources.ResourceManager resourceMan; - - private static global::System.Globalization.CultureInfo resourceCulture; - - [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - internal CodeFixResources() { - } - - /// - /// Returns the cached ResourceManager instance used by this class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Resources.ResourceManager ResourceManager { - get { - if (object.ReferenceEquals(resourceMan, null)) { - global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("MSTest.Analyzers.CodeFixResources", typeof(CodeFixResources).Assembly); - resourceMan = temp; - } - return resourceMan; - } - } - - /// - /// Overrides the current thread's CurrentUICulture property for all - /// resource lookups using this strongly typed resource class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Globalization.CultureInfo Culture { - get { - return resourceCulture; - } - set { - resourceCulture = value; - } - } - - /// - /// Looks up a localized string similar to Add '[TestClass]'. - /// - internal static string AddTestClassFix { - get { - return ResourceManager.GetString("AddTestClassFix", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Add '[TestMethod]'. - /// - internal static string AddTestMethodAttributeFix { - get { - return ResourceManager.GetString("AddTestMethodAttributeFix", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Fix signature. - /// - internal static string AssemblyInitializeShouldBeValidCodeFix { - get { - return ResourceManager.GetString("AssemblyInitializeShouldBeValidCodeFix", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Move conditional access in assertion to separate 'Assert.IsNotNull' check. - /// - internal static string AssertionArgsShouldAvoidConditionalAccessFix { - get { - return ResourceManager.GetString("AssertionArgsShouldAvoidConditionalAccessFix", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Use '{0}'. - /// - internal static string AvoidAssertAreSameWithValueTypesFix { - get { - return ResourceManager.GetString("AvoidAssertAreSameWithValueTypesFix", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Change method accessibility to 'private'. - /// - internal static string ChangeMethodAccessibilityToPrivateFix { - get { - return ResourceManager.GetString("ChangeMethodAccessibilityToPrivateFix", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Change to 'class' and add '[TestClass]'. - /// - internal static string ChangeStructToClassAndAddTestClassFix { - get { - return ResourceManager.GetString("ChangeStructToClassAndAddTestClassFix", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Fix actual/expected arguments order. - /// - internal static string FixAssertionArgsOrder { - get { - return ResourceManager.GetString("FixAssertionArgsOrder", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Fix signature. - /// - internal static string FixSignatureCodeFix { - get { - return ResourceManager.GetString("FixSignatureCodeFix", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Pass 'TestContext.CancellationTokenSource.Token' argument to method call. - /// - internal static string PassCancellationTokenFix { - get { - return ResourceManager.GetString("PassCancellationTokenFix", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Replace 'DataTestMethod' with 'TestMethod'. - /// - internal static string ReplaceDataTestMethodWithTestMethodTitle { - get { - return ResourceManager.GetString("ReplaceDataTestMethodWithTestMethodTitle", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Replace TestInitialize method with constructor. - /// - internal static string ReplaceWithConstructorFix { - get { - return ResourceManager.GetString("ReplaceWithConstructorFix", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Replace TestCleanup with Dispose method. - /// - internal static string ReplaceWithDisposeFix { - get { - return ResourceManager.GetString("ReplaceWithDisposeFix", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Replace the assertion with 'Assert.Fail()'. - /// - internal static string ReplaceWithFailAssertionFix { - get { - return ResourceManager.GetString("ReplaceWithFailAssertionFix", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Replace 'Dispose' with a TestCleanup method. - /// - internal static string ReplaceWithTestCleanuFix { - get { - return ResourceManager.GetString("ReplaceWithTestCleanuFix", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Replace constructor with TestInitialize method. - /// - internal static string ReplaceWithTestInitializeFix { - get { - return ResourceManager.GetString("ReplaceWithTestInitializeFix", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Use 'Assert.{0}' instead of 'StringAssert'. - /// - internal static string StringAssertToAssertTitle { - get { - return ResourceManager.GetString("StringAssertToAssertTitle", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Fix test class signature. - /// - internal static string TestClassShouldBeValidFix { - get { - return ResourceManager.GetString("TestClassShouldBeValidFix", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Fix test context. - /// - internal static string TestContextShouldBeValidFix { - get { - return ResourceManager.GetString("TestContextShouldBeValidFix", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Fix test method signature. - /// - internal static string TestMethodShouldBeValidFix { - get { - return ResourceManager.GetString("TestMethodShouldBeValidFix", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Use 'Assert.ThrowsException<T>' instead of '[ExpectedException]' attribute. - /// - internal static string UseAssertThrowsExceptionOnLastStatementFix { - get { - return ResourceManager.GetString("UseAssertThrowsExceptionOnLastStatementFix", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Add '[TestMethod]'. - /// - internal static string UseAttributeOnTestMethodFix { - get { - return ResourceManager.GetString("UseAttributeOnTestMethodFix", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Use 'CooperativeCancellation = true'. - /// - internal static string UseCooperativeCancellationForTimeoutFix { - get { - return ResourceManager.GetString("UseCooperativeCancellationForTimeoutFix", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Use '{0}'. - /// - internal static string UseNewerAssertThrows { - get { - return ResourceManager.GetString("UseNewerAssertThrows", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Use '{0}'. - /// - internal static string UseProperAssertMethodsFix { - get { - return ResourceManager.GetString("UseProperAssertMethodsFix", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Remove 'DynamicDataSourceType' parameter to use default 'AutoDetect'. - /// - internal static string RemoveDynamicDataSourceTypeFix { - get { - return ResourceManager.GetString("RemoveDynamicDataSourceTypeFix", resourceCulture); - } - } - } -} diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/MSTest.Analyzers.CodeFixes.csproj b/src/Analyzers/MSTest.Analyzers.CodeFixes/MSTest.Analyzers.CodeFixes.csproj index 90c2706c8f..525d079c19 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/MSTest.Analyzers.CodeFixes.csproj +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/MSTest.Analyzers.CodeFixes.csproj @@ -14,9 +14,4 @@ - - - - - diff --git a/src/Analyzers/MSTest.Analyzers/MSTest.Analyzers.csproj b/src/Analyzers/MSTest.Analyzers/MSTest.Analyzers.csproj index 217d171183..cc4ad8f545 100644 --- a/src/Analyzers/MSTest.Analyzers/MSTest.Analyzers.csproj +++ b/src/Analyzers/MSTest.Analyzers/MSTest.Analyzers.csproj @@ -24,9 +24,4 @@ - - - - - diff --git a/src/Analyzers/MSTest.Analyzers/Resources.Designer.cs b/src/Analyzers/MSTest.Analyzers/Resources.Designer.cs deleted file mode 100644 index 682130ac4a..0000000000 --- a/src/Analyzers/MSTest.Analyzers/Resources.Designer.cs +++ /dev/null @@ -1,1460 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:4.0.30319.42000 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace MSTest.Analyzers { - using System; - - - /// - /// A strongly-typed resource class, for looking up localized strings, etc. - /// - // This class was auto-generated by the StronglyTypedResourceBuilder - // class via a tool like ResGen or Visual Studio. - // To add or remove a member, edit your .ResX file then rerun ResGen - // with the /str option, or rebuild your VS project. - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "18.0.0.0")] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - internal class Resources { - - private static global::System.Resources.ResourceManager resourceMan; - - private static global::System.Globalization.CultureInfo resourceCulture; - - [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - internal Resources() { - } - - /// - /// Returns the cached ResourceManager instance used by this class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Resources.ResourceManager ResourceManager { - get { - if (object.ReferenceEquals(resourceMan, null)) { - global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("MSTest.Analyzers.Resources", typeof(Resources).Assembly); - resourceMan = temp; - } - return resourceMan; - } - } - - /// - /// Overrides the current thread's CurrentUICulture property for all - /// resource lookups using this strongly typed resource class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Globalization.CultureInfo Culture { - get { - return resourceCulture; - } - set { - resourceCulture = value; - } - } - - /// - /// Looks up a localized string similar to Methods marked with '[AssemblyCleanup]' should follow the following layout to be valid: - ///-it can't be declared on a generic class - ///-it should be 'public' - ///-it should be 'static' - ///-it should not be 'async void' - ///-it should not be a special method (finalizer, operator...). - ///-it should not be generic - ///-it should either not take any parameter, or take a single parameter of type 'TestContext' - ///-return type should be 'void', 'Task' or 'ValueTask' - /// - ///The type declaring these methods should also respect the followi [rest of string was truncated]";. - /// - internal static string AssemblyCleanupShouldBeValidDescription { - get { - return ResourceManager.GetString("AssemblyCleanupShouldBeValidDescription", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to AssemblyCleanup method '{0}' signature is invalid. - /// - internal static string AssemblyCleanupShouldBeValidMessageFormat { - get { - return ResourceManager.GetString("AssemblyCleanupShouldBeValidMessageFormat", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to AssemblyCleanup methods should have valid layout. - /// - internal static string AssemblyCleanupShouldBeValidTitle { - get { - return ResourceManager.GetString("AssemblyCleanupShouldBeValidTitle", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Methods marked with '[AssemblyInitialize]' should follow the following layout to be valid: - ///-it can't be declared on a generic class - ///-it should be 'public' - ///-it should be 'static' - ///-it should not be 'async void' - ///-it should not be a special method (finalizer, operator...). - ///-it should not be generic - ///-it should take one parameter of type 'TestContext' - ///-return type should be 'void', 'Task' or 'ValueTask' - /// - ///The type declaring these methods should also respect the following rules: - ///-The type should be a cla [rest of string was truncated]";. - /// - internal static string AssemblyInitializeShouldBeValidDescription { - get { - return ResourceManager.GetString("AssemblyInitializeShouldBeValidDescription", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to AssemblyInitialize method '{0}' signature is invalid. - /// - internal static string AssemblyInitializeShouldBeValidMessageFormat { - get { - return ResourceManager.GetString("AssemblyInitializeShouldBeValidMessageFormat", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to AssemblyInitialize methods should have valid layout. - /// - internal static string AssemblyInitializeShouldBeValidTitle { - get { - return ResourceManager.GetString("AssemblyInitializeShouldBeValidTitle", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Prefer adding an additional assertion that checks for null. - /// - internal static string AssertionArgsShouldAvoidConditionalAccessMessageFormat { - get { - return ResourceManager.GetString("AssertionArgsShouldAvoidConditionalAccessMessageFormat", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Avoid conditional access in assertions. - /// - internal static string AssertionArgsShouldAvoidConditionalAccessTitle { - get { - return ResourceManager.GetString("AssertionArgsShouldAvoidConditionalAccessTitle", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 'Assert.AreEqual', 'Assert.AreNotEqual', 'Assert.AreSame' and 'Assert.AreNotSame' expects the expected value to be passed first and the actual value to be passed as second argument.. - /// - internal static string AssertionArgsShouldBePassedInCorrectOrderDescription { - get { - return ResourceManager.GetString("AssertionArgsShouldBePassedInCorrectOrderDescription", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Assertion arguments should be passed in the correct order. 'actual' and 'expected'/'notExpected' arguments have been swapped.. - /// - internal static string AssertionArgsShouldBePassedInCorrectOrderMessageFormat { - get { - return ResourceManager.GetString("AssertionArgsShouldBePassedInCorrectOrderMessageFormat", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Assertion arguments should be passed in the correct order. - /// - internal static string AssertionArgsShouldBePassedInCorrectOrderTitle { - get { - return ResourceManager.GetString("AssertionArgsShouldBePassedInCorrectOrderTitle", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws.. - /// - internal static string AssertThrowsShouldContainSingleStatementDescription { - get { - return ResourceManager.GetString("AssertThrowsShouldContainSingleStatementDescription", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Assert.Throws should contain only a single statement/expression. - /// - internal static string AssertThrowsShouldContainSingleStatementMessageFormat { - get { - return ResourceManager.GetString("AssertThrowsShouldContainSingleStatementMessageFormat", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Assert.Throws should contain only a single statement/expression. - /// - internal static string AssertThrowsShouldContainSingleStatementTitle { - get { - return ResourceManager.GetString("AssertThrowsShouldContainSingleStatementTitle", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Use 'Assert.AreEqual'/'Assert.AreNotEqual' instead of 'Assert.AreSame'/'Assert.AreNotSame' when comparing value types. Passing a value type to 'Assert.AreSame'/'Assert.AreNotSame' will be boxed (creating a new object). Because 'Assert.AreSame'/'Assert.AreNotSame' does the comparison by reference, 'Assert.AreSame' will fail when boxing happens, and 'Assert.AreNotSame' will always pass.. - /// - internal static string AvoidAssertAreSameWithValueTypesDescription { - get { - return ResourceManager.GetString("AvoidAssertAreSameWithValueTypesDescription", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Use '{0}' instead of '{1}' when comparing value types. - /// - internal static string AvoidAssertAreSameWithValueTypesMessageFormat { - get { - return ResourceManager.GetString("AvoidAssertAreSameWithValueTypesMessageFormat", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Don't use 'Assert.AreSame' or 'Assert.AreNotSame' with value types. - /// - internal static string AvoidAssertAreSameWithValueTypesTitle { - get { - return ResourceManager.GetString("AvoidAssertAreSameWithValueTypesTitle", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Prefer 'Assert.ThrowsExactly' or 'Assert.ThrowsExactlyAsync' over '[ExpectedException]' as it ensures that only the expected call throws the expected exception. The assert APIs also provide more flexibility and allow you to assert extra properties of the exception.. - /// - internal static string AvoidExpectedExceptionAttributeDescription { - get { - return ResourceManager.GetString("AvoidExpectedExceptionAttributeDescription", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Prefer 'Assert.ThrowsExactly/ThrowsExactlyAsync' over '[ExpectedException]'. - /// - internal static string AvoidExpectedExceptionAttributeMessageFormat { - get { - return ResourceManager.GetString("AvoidExpectedExceptionAttributeMessageFormat", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Avoid '[ExpectedException]'. - /// - internal static string AvoidExpectedExceptionAttributeTitle { - get { - return ResourceManager.GetString("AvoidExpectedExceptionAttributeTitle", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Remove the 'DynamicDataSourceType' argument to use the default auto detect behavior. - /// - internal static string AvoidExplicitDynamicDataSourceTypeMessageFormat { - get { - return ResourceManager.GetString("AvoidExplicitDynamicDataSourceTypeMessageFormat", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Avoid passing an explicit 'DynamicDataSourceType' and use the default auto detect behavior. - /// - internal static string AvoidExplicitDynamicDataSourceTypeTitle { - get { - return ResourceManager.GetString("AvoidExplicitDynamicDataSourceTypeTitle", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Do not assert inside 'async void' methods, local functions, or lambdas. Exceptions that are thrown in this context will be unhandled exceptions. When using VSTest under .NET Framework, they will be silently swallowed. When using Microsoft.Testing.Platform or VSTest under modern .NET, they may crash the process.. - /// - internal static string AvoidUsingAssertsInAsyncVoidContextDescription { - get { - return ResourceManager.GetString("AvoidUsingAssertsInAsyncVoidContextDescription", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Do not assert inside 'async void' methods, local functions, or lambdas because they may not fail the test. - /// - internal static string AvoidUsingAssertsInAsyncVoidContextMessageFormat { - get { - return ResourceManager.GetString("AvoidUsingAssertsInAsyncVoidContextMessageFormat", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Do not assert inside 'async void' contexts. - /// - internal static string AvoidUsingAssertsInAsyncVoidContextTitle { - get { - return ResourceManager.GetString("AvoidUsingAssertsInAsyncVoidContextTitle", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Methods marked with '[ClassCleanup]' should follow the following layout to be valid: - ///-it can't be declared on a generic class without the 'InheritanceBehavior' mode is set - ///-it should be 'public' - ///-it should be 'static' - ///-it should not be 'async void' - ///-it should not be a special method (finalizer, operator...). - ///-it should not be generic - ///-it should either not take any parameter, or take a single parameter of type 'TestContext' - ///-return type should be 'void', 'Task' or 'ValueTask' - ///-'InheritanceBehavior.B [rest of string was truncated]";. - /// - internal static string ClassCleanupShouldBeValidDescription { - get { - return ResourceManager.GetString("ClassCleanupShouldBeValidDescription", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to ClassCleanup method '{0}' signature is invalid. - /// - internal static string ClassCleanupShouldBeValidMessageFormat { - get { - return ResourceManager.GetString("ClassCleanupShouldBeValidMessageFormat", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to ClassCleanup methods should have valid layout. - /// - internal static string ClassCleanupShouldBeValidTitle { - get { - return ResourceManager.GetString("ClassCleanupShouldBeValidTitle", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Methods marked with '[ClassInitialize]' should follow the following layout to be valid: - ///-it can't be declared on a generic class without the 'InheritanceBehavior' mode is set - ///-it should be 'public' - ///-it should be 'static' - ///-it should not be 'async void' - ///-it should not be a special method (finalizer, operator...). - ///-it should not be generic - ///-it should take one parameter of type 'TestContext' - ///-return type should be 'void', 'Task' or 'ValueTask' - ///-'InheritanceBehavior.BeforeEachDerivedClass' attribute par [rest of string was truncated]";. - /// - internal static string ClassInitializeShouldBeValidDescription { - get { - return ResourceManager.GetString("ClassInitializeShouldBeValidDescription", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to ClassInitialize method '{0}' signature is invalid. - /// - internal static string ClassInitializeShouldBeValidMessageFormat { - get { - return ResourceManager.GetString("ClassInitializeShouldBeValidMessageFormat", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to ClassInitialize methods should have valid layout. - /// - internal static string ClassInitializeShouldBeValidTitle { - get { - return ResourceManager.GetString("ClassInitializeShouldBeValidTitle", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to DataRow entry should have the following layout to be valid: - ///- should only be set on a test method; - ///- argument count should match method argument count; - ///- argument type should match method argument type.. - /// - internal static string DataRowShouldBeValidDescription { - get { - return ResourceManager.GetString("DataRowShouldBeValidDescription", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to DataRow argument count should match method parameter count (constructor arguments: {0}, method parameters: {1}). - /// - internal static string DataRowShouldBeValidMessageFormat_ArgumentCountMismatch { - get { - return ResourceManager.GetString("DataRowShouldBeValidMessageFormat_ArgumentCountMismatch", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to DataRow argument types do not match method parameter types. {0}. - /// - internal static string DataRowShouldBeValidMessageFormat_ArgumentTypeMismatch { - get { - return ResourceManager.GetString("DataRowShouldBeValidMessageFormat_ArgumentTypeMismatch", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Found two conflicting types for generic parameter '{0}'. The conflicting types are '{1}' and '{2}'.. - /// - internal static string DataRowShouldBeValidMessageFormat_GenericTypeArgumentConflictingTypes { - get { - return ResourceManager.GetString("DataRowShouldBeValidMessageFormat_GenericTypeArgumentConflictingTypes", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The type of the generic parameter '{0}' could not be inferred.. - /// - internal static string DataRowShouldBeValidMessageFormat_GenericTypeArgumentNotResolved { - get { - return ResourceManager.GetString("DataRowShouldBeValidMessageFormat_GenericTypeArgumentNotResolved", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to DataRow should only be set on a test method. - /// - internal static string DataRowShouldBeValidMessageFormat_OnTestMethod { - get { - return ResourceManager.GetString("DataRowShouldBeValidMessageFormat_OnTestMethod", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Parameter '{0}' expects type '{1}', but the provided value has type '{2}'. - /// - internal static string DataRowShouldBeValidMessageFormat_ParameterMismatch { - get { - return ResourceManager.GetString("DataRowShouldBeValidMessageFormat_ParameterMismatch", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to DataRow should be valid. - /// - internal static string DataRowShouldBeValidTitle { - get { - return ResourceManager.GetString("DataRowShouldBeValidTitle", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Do not negate boolean assertions, instead use the opposite assertion. - /// - internal static string DoNotNegateBooleanAssertionMessageFormat { - get { - return ResourceManager.GetString("DoNotNegateBooleanAssertionMessageFormat", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Do not negate boolean assertions. - /// - internal static string DoNotNegateBooleanAssertionTitle { - get { - return ResourceManager.GetString("DoNotNegateBooleanAssertionTitle", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Do not store TestContext in a static member. - /// - internal static string DoNotStoreStaticTestContextAnalyzerMessageFormat { - get { - return ResourceManager.GetString("DoNotStoreStaticTestContextAnalyzerMessageFormat", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Do not store TestContext in a static member. - /// - internal static string DoNotStoreStaticTestContextAnalyzerTitle { - get { - return ResourceManager.GetString("DoNotStoreStaticTestContextAnalyzerTitle", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Shadowing test members could cause testing issues (such as NRE).. - /// - internal static string DoNotUseShadowingDescription { - get { - return ResourceManager.GetString("DoNotUseShadowingDescription", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Member '{0}' already exists in the base class. - /// - internal static string DoNotUseShadowingMessageFormat { - get { - return ResourceManager.GetString("DoNotUseShadowingMessageFormat", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Do not use shadowing. - /// - internal static string DoNotUseShadowingTitle { - get { - return ResourceManager.GetString("DoNotUseShadowingTitle", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 'System.ComponentModel.DescriptionAttribute' has no effect in the context of tests and you likely wanted to use 'Microsoft.VisualStudio.TestTools.UnitTesting.DescriptionAttribute' instead.. - /// - internal static string DoNotUseSystemDescriptionAttributeDescription { - get { - return ResourceManager.GetString("DoNotUseSystemDescriptionAttributeDescription", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Did you mean to be using 'Microsoft.VisualStudio.TestTools.UnitTesting.DescriptionAttribute'?. - /// - internal static string DoNotUseSystemDescriptionAttributeMessageFormat { - get { - return ResourceManager.GetString("DoNotUseSystemDescriptionAttributeMessageFormat", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 'System.ComponentModel.DescriptionAttribute' has no effect on test methods. - /// - internal static string DoNotUseSystemDescriptionAttributeTitle { - get { - return ResourceManager.GetString("DoNotUseSystemDescriptionAttributeTitle", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Do not duplicate 'DataRow' attributes. This is usually a copy/paste error. The attribute indices are '{0}' and '{1}'.. - /// - internal static string DuplicateDataRowMessageFormat { - get { - return ResourceManager.GetString("DuplicateDataRowMessageFormat", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Avoid duplicated 'DataRow' entries. - /// - internal static string DuplicateDataRowTitle { - get { - return ResourceManager.GetString("DuplicateDataRowTitle", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 'DynamicData' entry should have the following layout to be valid: - ///- should only be set on a test method; - ///- member should be defined on the type specified; - ///- member should be a method if DynamicDataSourceType.Method is specified or a property otherwise.. - /// - internal static string DynamicDataShouldBeValidDescription { - get { - return ResourceManager.GetString("DynamicDataShouldBeValidDescription", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to '[DynamicData]' data member '{0}.{1}' signature is invalid. - /// - internal static string DynamicDataShouldBeValidMessageFormat_DataMemberSignature { - get { - return ResourceManager.GetString("DynamicDataShouldBeValidMessageFormat_DataMemberSignature", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to '[DynamicData]' display name method '{0}.{1}' signature is invalid. - /// - internal static string DynamicDataShouldBeValidMessageFormat_DisplayMethodSignature { - get { - return ResourceManager.GetString("DynamicDataShouldBeValidMessageFormat_DisplayMethodSignature", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to '[DynamicData]' member '{0}.{1}' should be a method. - /// - internal static string DynamicDataShouldBeValidMessageFormat_MemberMethod { - get { - return ResourceManager.GetString("DynamicDataShouldBeValidMessageFormat_MemberMethod", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to '[DynamicData]' member '{0}.{1}' cannot be found. - /// - internal static string DynamicDataShouldBeValidMessageFormat_MemberNotFound { - get { - return ResourceManager.GetString("DynamicDataShouldBeValidMessageFormat_MemberNotFound", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to '[DynamicData]' referenced member '{0}.{1}' should return 'IEnumerable<object[]>', 'IEnumerable<Tuple>` or 'IEnumerable<ValueTuple>'. - /// - internal static string DynamicDataShouldBeValidMessageFormat_MemberType { - get { - return ResourceManager.GetString("DynamicDataShouldBeValidMessageFormat_MemberType", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to '[DynamicData]' should only be set on a test method. - /// - internal static string DynamicDataShouldBeValidMessageFormat_OnTestMethod { - get { - return ResourceManager.GetString("DynamicDataShouldBeValidMessageFormat_OnTestMethod", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to '[DynamicData]' member '{0}.{1}' is a field so you should use 'DynamicDataSourceType.AutoDetect' or 'DynamicDataSourceType.Field' (auto detect is the default when not specified explicitly, and is recommended). - /// - internal static string DynamicDataShouldBeValidMessageFormat_SourceTypeField { - get { - return ResourceManager.GetString("DynamicDataShouldBeValidMessageFormat_SourceTypeField", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to '[DynamicData]' member '{0}.{1}' is a method so you should use 'DynamicDataSourceType.AutoDetect' or 'DynamicDataSourceType.Method' (auto detect is the default when not specified explicitly, and is recommended). - /// - internal static string DynamicDataShouldBeValidMessageFormat_SourceTypeMethod { - get { - return ResourceManager.GetString("DynamicDataShouldBeValidMessageFormat_SourceTypeMethod", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to '[DynamicData]' member '{0}.{1}' is not a property, method, or field. Only properties, methods, and fields are supported.. - /// - internal static string DynamicDataShouldBeValidMessageFormat_SourceTypeNotPropertyMethodOrField { - get { - return ResourceManager.GetString("DynamicDataShouldBeValidMessageFormat_SourceTypeNotPropertyMethodOrField", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to '[DynamicData]' member '{0}.{1}' is not a property nor a method. Only properties and methods are supported.. - /// - internal static string DynamicDataShouldBeValidMessageFormat_SourceTypeNotPropertyOrMethod { - get { - return ResourceManager.GetString("DynamicDataShouldBeValidMessageFormat_SourceTypeNotPropertyOrMethod", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to '[DynamicData]' member '{0}.{1}' is a property so you should use 'DynamicDataSourceType.AutoDetect' or 'DynamicDataSourceType.Property' (auto detect is the default when not specified explicitly, and is recommended). - /// - internal static string DynamicDataShouldBeValidMessageFormat_SourceTypeProperty { - get { - return ResourceManager.GetString("DynamicDataShouldBeValidMessageFormat_SourceTypeProperty", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to '[DynamicData]' member '{0}.{1}' is found more than once. - /// - internal static string DynamicDataShouldBeValidMessageFormat_TooManyMembers { - get { - return ResourceManager.GetString("DynamicDataShouldBeValidMessageFormat_TooManyMembers", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to DynamicData should be valid. - /// - internal static string DynamicDataShouldBeValidTitle { - get { - return ResourceManager.GetString("DynamicDataShouldBeValidTitle", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationTokenSource.Token to enable cooperative cancellation and respect test timeouts.. - /// - internal static string FlowTestContextCancellationTokenDescription { - get { - return ResourceManager.GetString("FlowTestContextCancellationTokenDescription", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationTokenSource.Token'. - /// - internal static string FlowTestContextCancellationTokenMessageFormat { - get { - return ResourceManager.GetString("FlowTestContextCancellationTokenMessageFormat", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Flow TestContext.CancellationToken to async operations. - /// - internal static string FlowTestContextCancellationTokenTitle { - get { - return ResourceManager.GetString("FlowTestContextCancellationTokenTitle", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Methods marked with '[GlobalTestInitialize]' or '[GlobalTestCleanup]' should follow the following layout to be valid: - ///-it can't be declared on a generic class - ///-it should be 'public' - ///-it should be 'static' - ///-it should not be 'async void' - ///-it should not be a special method (finalizer, operator...). - ///-it should not be generic - ///-it should take one parameter of type 'TestContext' - ///-return type should be 'void', 'Task' or 'ValueTask' - /// - ///The type declaring these methods should also respect the following rules: [rest of string was truncated]";. - /// - internal static string GlobalTestFixtureShouldBeValidDescription { - get { - return ResourceManager.GetString("GlobalTestFixtureShouldBeValidDescription", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Global test fixture method '{0}' signature is invalid. - /// - internal static string GlobalTestFixtureShouldBeValidMessageFormat { - get { - return ResourceManager.GetString("GlobalTestFixtureShouldBeValidMessageFormat", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to GlobalTestInitialize and GlobalTestCleanup methods should have valid layout. - /// - internal static string GlobalTestFixtureShouldBeValidTitle { - get { - return ResourceManager.GetString("GlobalTestFixtureShouldBeValidTitle", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Use 'Assert.Fail' instead of an always-failing 'Assert.{0}' assert. - /// - internal static string PreferAssertFailOverAlwaysFalseConditionsMessageFormat { - get { - return ResourceManager.GetString("PreferAssertFailOverAlwaysFalseConditionsMessageFormat", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Use 'Assert.Fail' instead of an always-failing assert. - /// - internal static string PreferAssertFailOverAlwaysFalseConditionsTitle { - get { - return ResourceManager.GetString("PreferAssertFailOverAlwaysFalseConditionsTitle", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Prefer constructors over TestInitialize methods. - /// - internal static string PreferConstructorOverTestInitializeMessageFormat { - get { - return ResourceManager.GetString("PreferConstructorOverTestInitializeMessageFormat", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Prefer constructors over TestInitialize methods. - /// - internal static string PreferConstructorOverTestInitializeTitle { - get { - return ResourceManager.GetString("PreferConstructorOverTestInitializeTitle", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Prefer 'Dispose' over TestCleanup methods. - /// - internal static string PreferDisposeOverTestCleanupMessageFormat { - get { - return ResourceManager.GetString("PreferDisposeOverTestCleanupMessageFormat", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Prefer 'Dispose' over TestCleanup methods. - /// - internal static string PreferDisposeOverTestCleanupTitle { - get { - return ResourceManager.GetString("PreferDisposeOverTestCleanupTitle", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Prefer TestCleanup over 'Dispose' methods. - /// - internal static string PreferTestCleanupOverDisposeMessageFormat { - get { - return ResourceManager.GetString("PreferTestCleanupOverDisposeMessageFormat", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Prefer TestCleanup over 'Dispose' methods. - /// - internal static string PreferTestCleanupOverDisposeTitle { - get { - return ResourceManager.GetString("PreferTestCleanupOverDisposeTitle", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Prefer TestInitialize methods over constructors. - /// - internal static string PreferTestInitializeOverConstructorMessageFormat { - get { - return ResourceManager.GetString("PreferTestInitializeOverConstructorMessageFormat", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Prefer TestInitialize methods over constructors. - /// - internal static string PreferTestInitializeOverConstructorTitle { - get { - return ResourceManager.GetString("PreferTestInitializeOverConstructorTitle", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 'DataTestMethodAttribute' is obsolete and provides no additional functionality over 'TestMethodAttribute'. Use 'TestMethodAttribute' for all test methods, including parameterized tests.. - /// - internal static string PreferTestMethodOverDataTestMethodAnalyzerDescription { - get { - return ResourceManager.GetString("PreferTestMethodOverDataTestMethodAnalyzerDescription", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 'DataTestMethod' is obsolete. Use 'TestMethod' instead.. - /// - internal static string PreferTestMethodOverDataTestMethodAnalyzerMessageFormat { - get { - return ResourceManager.GetString("PreferTestMethodOverDataTestMethodAnalyzerMessageFormat", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Prefer 'TestMethod' over 'DataTestMethod'. - /// - internal static string PreferTestMethodOverDataTestMethodAnalyzerTitle { - get { - return ResourceManager.GetString("PreferTestMethodOverDataTestMethodAnalyzerTitle", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Public methods should be test methods (marked with `[TestMethod]`).. - /// - internal static string PublicMethodShouldBeTestMethodAnalyzerDescription { - get { - return ResourceManager.GetString("PublicMethodShouldBeTestMethodAnalyzerDescription", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Public method '{0}' should be a test method. - /// - internal static string PublicMethodShouldBeTestMethodAnalyzerFormat { - get { - return ResourceManager.GetString("PublicMethodShouldBeTestMethodAnalyzerFormat", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Public methods should be test methods. - /// - internal static string PublicMethodShouldBeTestMethodAnalyzerTitle { - get { - return ResourceManager.GetString("PublicMethodShouldBeTestMethodAnalyzerTitle", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to It's considered a good practice to have only test classes marked public in a test project.. - /// - internal static string PublicTypeShouldBeTestClassDescription { - get { - return ResourceManager.GetString("PublicTypeShouldBeTestClassDescription", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Public type '{0}' should be marked with '[TestClass]' or changed to 'internal'. - /// - internal static string PublicTypeShouldBeTestClassMessageFormat { - get { - return ResourceManager.GetString("PublicTypeShouldBeTestClassMessageFormat", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Public types should be test classes. - /// - internal static string PublicTypeShouldBeTestClassTitle { - get { - return ResourceManager.GetString("PublicTypeShouldBeTestClassTitle", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Review or remove the assertion as its condition is known to be always true. - /// - internal static string ReviewAlwaysTrueAssertConditionAnalyzerMessageFormat { - get { - return ResourceManager.GetString("ReviewAlwaysTrueAssertConditionAnalyzerMessageFormat", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Assertion condition is always true. - /// - internal static string ReviewAlwaysTrueAssertConditionAnalyzerTitle { - get { - return ResourceManager.GetString("ReviewAlwaysTrueAssertConditionAnalyzerTitle", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Use 'Assert.{0}' instead of 'StringAssert.{1}'. - /// - internal static string StringAssertToAssertMessageFormat { - get { - return ResourceManager.GetString("StringAssertToAssertMessageFormat", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Use 'Assert' instead of 'StringAssert'. - /// - internal static string StringAssertToAssertTitle { - get { - return ResourceManager.GetString("StringAssertToAssertTitle", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Test classes, classes marked with the '[TestClass]' attribute, should respect the following layout to be considered valid by MSTest: - ///- it should be 'public' (or 'internal' if '[assembly: DiscoverInternals]' attribute is set) - ///- it should not be 'static' (except if it contains only 'AssemblyInitialize' and/or 'AssemblyCleanup' methods) - ///- it should not be generic.. - /// - internal static string TestClassShouldBeValidDescription { - get { - return ResourceManager.GetString("TestClassShouldBeValidDescription", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Test class '{0}' should be valid. - /// - internal static string TestClassShouldBeValidMessageFormat { - get { - return ResourceManager.GetString("TestClassShouldBeValidMessageFormat", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Test classes should have valid layout. - /// - internal static string TestClassShouldBeValidTitle { - get { - return ResourceManager.GetString("TestClassShouldBeValidTitle", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Test class should have at least one test method or be 'static' with method(s) marked by '[AssemblyInitialize]' and/or '[AssemblyCleanup]'.. - /// - internal static string TestClassShouldHaveTestMethodDescription { - get { - return ResourceManager.GetString("TestClassShouldHaveTestMethodDescription", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Test class '{0}' should have at least one test method or be 'static' with method(s) marked by '[AssemblyInitialize]' and/or '[AssemblyCleanup]'. - /// - internal static string TestClassShouldHaveTestMethodMessageFormat { - get { - return ResourceManager.GetString("TestClassShouldHaveTestMethodMessageFormat", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Test class should have test method. - /// - internal static string TestClassShouldHaveTestMethodTitle { - get { - return ResourceManager.GetString("TestClassShouldHaveTestMethodTitle", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Methods marked with '[TestCleanup]' should follow the following layout to be valid: - ///-it should be 'public' - ///-it should not be 'abstract' - ///-it should not be 'async void' - ///-it should not be 'static' - ///-it should not be a special method (finalizer, operator...). - ///-it should not be generic - ///-it should not take any parameter - ///-return type should be 'void', 'Task' or 'ValueTask' - /// - ///The type declaring these methods should also respect the following rules: - ///-The type should be a class - ///-The class should be 'public' [rest of string was truncated]";. - /// - internal static string TestCleanupShouldBeValidDescription { - get { - return ResourceManager.GetString("TestCleanupShouldBeValidDescription", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to TestCleanup method '{0}' signature is invalid. - /// - internal static string TestCleanupShouldBeValidMessageFormat { - get { - return ResourceManager.GetString("TestCleanupShouldBeValidMessageFormat", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to TestCleanup method should have valid layout. - /// - internal static string TestCleanupShouldBeValidTitle { - get { - return ResourceManager.GetString("TestCleanupShouldBeValidTitle", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Some TestContext properties are only available during test execution and cannot be accessed in assembly initialize, class initialize, class cleanup, or assembly cleanup methods.. - /// - internal static string TestContextPropertyUsageDescription { - get { - return ResourceManager.GetString("TestContextPropertyUsageDescription", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to TestContext property '{0}' cannot be accessed in '{1}' method. - /// - internal static string TestContextPropertyUsageMessageFormat { - get { - return ResourceManager.GetString("TestContextPropertyUsageMessageFormat", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to TestContext property cannot be accessed in this context. - /// - internal static string TestContextPropertyUsageTitle { - get { - return ResourceManager.GetString("TestContextPropertyUsageTitle", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 'TestContext' should be a non-static field or property assigned in constructor or for a property set by MSTest, it should follow the layout: - ///- it should be 'public' regardless of whether '[assembly: DiscoverInternals]' attribute is set or not. - ///- it should not be 'static' - ///- it should have a setter.. - /// - internal static string TestContextShouldBeValidDescription { - get { - return ResourceManager.GetString("TestContextShouldBeValidDescription", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Property 'TestContext' should be valid. - /// - internal static string TestContextShouldBeValidMessageFormat { - get { - return ResourceManager.GetString("TestContextShouldBeValidMessageFormat", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Test context property should have valid layout. - /// - internal static string TestContextShouldBeValidTitle { - get { - return ResourceManager.GetString("TestContextShouldBeValidTitle", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Methods marked with '[TestInitialize]' should follow the following layout to be valid: - ///-it should be 'public' - ///-it should not be 'abstract' - ///-it should not be 'async void' - ///-it should not be 'static' - ///-it should not be a special method (finalizer, operator...). - ///-it should not be generic - ///-it should not take any parameter - ///-return type should be 'void', 'Task' or 'ValueTask' - /// - ///The type declaring these methods should also respect the following rules: - ///-The type should be a class - ///-The class should be 'publ [rest of string was truncated]";. - /// - internal static string TestInitializeShouldBeValidDescription { - get { - return ResourceManager.GetString("TestInitializeShouldBeValidDescription", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to TestInitialize method '{0}' signature is invalid. - /// - internal static string TestInitializeShouldBeValidMessageFormat { - get { - return ResourceManager.GetString("TestInitializeShouldBeValidMessageFormat", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to TestInitialize method should have valid layout. - /// - internal static string TestInitializeShouldBeValidTitle { - get { - return ResourceManager.GetString("TestInitializeShouldBeValidTitle", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Test methods, methods marked with the '[TestMethod]' attribute, should respect the following layout to be considered valid by MSTest: - ///- it should be 'public' (or 'internal' if '[assembly: DiscoverInternals]' attribute is set) - ///- it should not be 'static' - ///- it should may be generic as long as type parameters can be inferred and argument types are compatible - ///- it should not be 'abstract' - ///- return type should be 'void', 'Task' or 'ValueTask' - ///- it should not be 'async void' - ///- it should not be a special me [rest of string was truncated]";. - /// - internal static string TestMethodShouldBeValidDescription { - get { - return ResourceManager.GetString("TestMethodShouldBeValidDescription", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Test method '{0}' signature is invalid. - /// - internal static string TestMethodShouldBeValidMessageFormat { - get { - return ResourceManager.GetString("TestMethodShouldBeValidMessageFormat", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Test methods should have valid layout. - /// - internal static string TestMethodShouldBeValidTitle { - get { - return ResourceManager.GetString("TestMethodShouldBeValidTitle", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Test methods should not be ignored (marked with '[Ignore]').. - /// - internal static string TestMethodShouldNotBeIgnoredAnalyzerDescription { - get { - return ResourceManager.GetString("TestMethodShouldNotBeIgnoredAnalyzerDescription", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Test method '{0}' should not be ignored. - /// - internal static string TestMethodShouldNotBeIgnoredAnalyzerFormat { - get { - return ResourceManager.GetString("TestMethodShouldNotBeIgnoredAnalyzerFormat", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Test method should not be ignored. - /// - internal static string TestMethodShouldNotBeIgnoredAnalyzerTitle { - get { - return ResourceManager.GetString("TestMethodShouldNotBeIgnoredAnalyzerTitle", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Type containing '[TestMethod]' should be marked with '[TestClass]', otherwise the test method will be silently ignored.. - /// - internal static string TypeContainingTestMethodShouldBeATestClassDescription { - get { - return ResourceManager.GetString("TypeContainingTestMethodShouldBeATestClassDescription", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Type '{0}' contains test methods and should be marked with '[TestClass]'. - /// - internal static string TypeContainingTestMethodShouldBeATestClassMessageFormat { - get { - return ResourceManager.GetString("TypeContainingTestMethodShouldBeATestClassMessageFormat", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Type containing '[TestMethod]' should be marked with '[TestClass]'. - /// - internal static string TypeContainingTestMethodShouldBeATestClassTitle { - get { - return ResourceManager.GetString("TypeContainingTestMethodShouldBeATestClassTitle", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to TestContext parameter is required by MSTest for AssemblyInitialize and ClassInitialize methods. - /// - internal static string UnusedParameterSuppressorJustification { - get { - return ResourceManager.GetString("UnusedParameterSuppressorJustification", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Asynchronous test fixture methods do not require the 'Async' suffix. - /// - internal static string UseAsyncSuffixTestFixtureMethodSuppressorJustification { - get { - return ResourceManager.GetString("UseAsyncSuffixTestFixtureMethodSuppressorJustification", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Asynchronous test methods do not require the 'Async' suffix. - /// - internal static string UseAsyncSuffixTestMethodSuppressorJustification { - get { - return ResourceManager.GetString("UseAsyncSuffixTestMethodSuppressorJustification", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to [{0}] can only be set on methods marked with [TestMethod]. - /// - internal static string UseAttributeOnTestMethodAnalyzerMessageFormat { - get { - return ResourceManager.GetString("UseAttributeOnTestMethodAnalyzerMessageFormat", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to [{0}] can only be set on methods marked with [TestMethod]. - /// - internal static string UseAttributeOnTestMethodAnalyzerTitle { - get { - return ResourceManager.GetString("UseAttributeOnTestMethodAnalyzerTitle", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Without using 'ClassCleanupBehavior.EndOfClass', the '[ClassCleanup]' will by default be run at the end of the assembly and not at the end of the class.. - /// - internal static string UseClassCleanupBehaviorEndOfClassDescription { - get { - return ResourceManager.GetString("UseClassCleanupBehaviorEndOfClassDescription", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Use 'ClassCleanupBehavior.EndOfClass' with the '[ClassCleanup]'. - /// - internal static string UseClassCleanupBehaviorEndOfClassMessageFormat { - get { - return ResourceManager.GetString("UseClassCleanupBehaviorEndOfClassMessageFormat", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Use 'ClassCleanupBehavior.EndOfClass' with the '[ClassCleanup]'. - /// - internal static string UseClassCleanupBehaviorEndOfClassTitle { - get { - return ResourceManager.GetString("UseClassCleanupBehaviorEndOfClassTitle", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The attribute '{0}' which derives from 'ConditionBaseAttribute' should be used only on classes marked with `TestClassAttribute`. - /// - internal static string UseConditionBaseWithTestClassMessageFormat { - get { - return ResourceManager.GetString("UseConditionBaseWithTestClassMessageFormat", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Use 'ConditionBaseAttribute' on test classes. - /// - internal static string UseConditionBaseWithTestClassTitle { - get { - return ResourceManager.GetString("UseConditionBaseWithTestClassTitle", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Using '[Timeout]' without explicitly setting 'CooperativeCancellation = true' is discouraged. In a future version, cooperative cancellation will become the default behavior. Set 'CooperativeCancellation = true' to opt into the recommended behavior and avoid breaking changes.. - /// - internal static string UseCooperativeCancellationForTimeoutDescription { - get { - return ResourceManager.GetString("UseCooperativeCancellationForTimeoutDescription", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Use 'CooperativeCancellation = true' with '[Timeout]' to enable cooperative cancellation behavior. - /// - internal static string UseCooperativeCancellationForTimeoutMessageFormat { - get { - return ResourceManager.GetString("UseCooperativeCancellationForTimeoutMessageFormat", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Use 'CooperativeCancellation = true' with '[Timeout]'. - /// - internal static string UseCooperativeCancellationForTimeoutTitle { - get { - return ResourceManager.GetString("UseCooperativeCancellationForTimeoutTitle", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to '[DeploymentItem]' can be specified only on test class or test method. - /// - internal static string UseDeploymentItemWithTestMethodOrTestClassMessageFormat { - get { - return ResourceManager.GetString("UseDeploymentItemWithTestMethodOrTestClassMessageFormat", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to '[DeploymentItem]' can be specified only on test class or test method. - /// - internal static string UseDeploymentItemWithTestMethodOrTestClassTitle { - get { - return ResourceManager.GetString("UseDeploymentItemWithTestMethodOrTestClassTitle", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Use 'Assert.ThrowsExactly' instead of 'Assert.ThrowsException'. - /// - internal static string UseNewerAssertThrowsMessageFormat { - get { - return ResourceManager.GetString("UseNewerAssertThrowsMessageFormat", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Use newer methods to assert exceptions. - /// - internal static string UseNewerAssertThrowsTitle { - get { - return ResourceManager.GetString("UseNewerAssertThrowsTitle", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to By default, MSTest runs tests within the same assembly sequentially, which can lead to severe performance limitations. It is recommended to enable assembly attribute '[Parallelize]' to run tests in parallel, or if the assembly is known to not be parallelizable, to use explicitly the assembly level attribute '[DoNotParallelize]'.. - /// - internal static string UseParallelizeAttributeAnalyzerDescription { - get { - return ResourceManager.GetString("UseParallelizeAttributeAnalyzerDescription", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Explicitly enable or disable tests parallelization. - /// - internal static string UseParallelizeAttributeAnalyzerMessageFormat { - get { - return ResourceManager.GetString("UseParallelizeAttributeAnalyzerMessageFormat", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Explicitly enable or disable tests parallelization. - /// - internal static string UseParallelizeAttributeAnalyzerTitle { - get { - return ResourceManager.GetString("UseParallelizeAttributeAnalyzerTitle", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Use 'Assert.{0}' instead of 'Assert.{1}'. - /// - internal static string UseProperAssertMethodsMessageFormat { - get { - return ResourceManager.GetString("UseProperAssertMethodsMessageFormat", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Use proper 'Assert' methods. - /// - internal static string UseProperAssertMethodsTitle { - get { - return ResourceManager.GetString("UseProperAssertMethodsTitle", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to An attribute that derives from 'RetryBaseAttribute' can be specified only on a test method. - /// - internal static string UseRetryWithTestMethodMessageFormat { - get { - return ResourceManager.GetString("UseRetryWithTestMethodMessageFormat", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Use retry attribute on test method. - /// - internal static string UseRetryWithTestMethodTitle { - get { - return ResourceManager.GetString("UseRetryWithTestMethodTitle", resourceCulture); - } - } - } -} diff --git a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Microsoft.Testing.Extensions.AzureDevOpsReport.csproj b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Microsoft.Testing.Extensions.AzureDevOpsReport.csproj index eaf0d46fd9..02e9d786da 100644 --- a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Microsoft.Testing.Extensions.AzureDevOpsReport.csproj +++ b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Microsoft.Testing.Extensions.AzureDevOpsReport.csproj @@ -42,10 +42,6 @@ This package extends Microsoft Testing Platform to provide a Azure DevOps report - - - - diff --git a/src/Platform/Microsoft.Testing.Extensions.CrashDump/Microsoft.Testing.Extensions.CrashDump.csproj b/src/Platform/Microsoft.Testing.Extensions.CrashDump/Microsoft.Testing.Extensions.CrashDump.csproj index 6d7d59466d..b6f17f7577 100644 --- a/src/Platform/Microsoft.Testing.Extensions.CrashDump/Microsoft.Testing.Extensions.CrashDump.csproj +++ b/src/Platform/Microsoft.Testing.Extensions.CrashDump/Microsoft.Testing.Extensions.CrashDump.csproj @@ -46,8 +46,4 @@ This package extends Microsoft Testing Platform to provide a crash dump function - - - - diff --git a/src/Platform/Microsoft.Testing.Extensions.HangDump/Microsoft.Testing.Extensions.HangDump.csproj b/src/Platform/Microsoft.Testing.Extensions.HangDump/Microsoft.Testing.Extensions.HangDump.csproj index d115d99e12..a7766d483a 100644 --- a/src/Platform/Microsoft.Testing.Extensions.HangDump/Microsoft.Testing.Extensions.HangDump.csproj +++ b/src/Platform/Microsoft.Testing.Extensions.HangDump/Microsoft.Testing.Extensions.HangDump.csproj @@ -43,10 +43,6 @@ This package extends Microsoft Testing Platform to provide an implementation of - - - - diff --git a/src/Platform/Microsoft.Testing.Extensions.HotReload/Microsoft.Testing.Extensions.HotReload.csproj b/src/Platform/Microsoft.Testing.Extensions.HotReload/Microsoft.Testing.Extensions.HotReload.csproj index a7e8e9b6f7..91dad273e7 100644 --- a/src/Platform/Microsoft.Testing.Extensions.HotReload/Microsoft.Testing.Extensions.HotReload.csproj +++ b/src/Platform/Microsoft.Testing.Extensions.HotReload/Microsoft.Testing.Extensions.HotReload.csproj @@ -43,19 +43,4 @@ This package extends Microsoft Testing Platform to provide Hot Reload support.]] - - - True - True - ExtensionResources.resx - - - - - - ResXFileCodeGenerator - ExtensionResources.Designer.cs - - - \ No newline at end of file diff --git a/src/Platform/Microsoft.Testing.Extensions.HotReload/Resources/ExtensionResources.Designer.cs b/src/Platform/Microsoft.Testing.Extensions.HotReload/Resources/ExtensionResources.Designer.cs deleted file mode 100644 index 4e6bc289c6..0000000000 --- a/src/Platform/Microsoft.Testing.Extensions.HotReload/Resources/ExtensionResources.Designer.cs +++ /dev/null @@ -1,90 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:4.0.30319.42000 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace Microsoft.Testing.Extensions.Hosting.Resources { - using System; - - - /// - /// A strongly-typed resource class, for looking up localized strings, etc. - /// - // This class was auto-generated by the StronglyTypedResourceBuilder - // class via a tool like ResGen or Visual Studio. - // To add or remove a member, edit your .ResX file then rerun ResGen - // with the /str option, or rebuild your VS project. - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - internal class ExtensionResources { - - private static global::System.Resources.ResourceManager resourceMan; - - private static global::System.Globalization.CultureInfo resourceCulture; - - [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - internal ExtensionResources() { - } - - /// - /// Returns the cached ResourceManager instance used by this class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Resources.ResourceManager ResourceManager { - get { - if (object.ReferenceEquals(resourceMan, null)) { - global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Microsoft.Testing.Extensions.Hosting.Resources.ExtensionResources", typeof(ExtensionResources).Assembly); - resourceMan = temp; - } - return resourceMan; - } - } - - /// - /// Overrides the current thread's CurrentUICulture property for all - /// resource lookups using this strongly typed resource class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Globalization.CultureInfo Culture { - get { - return resourceCulture; - } - set { - resourceCulture = value; - } - } - - /// - /// Looks up a localized string similar to Hot reload is only supported on .NET 6.0 or greater. - /// - internal static string HotReloadHandlerUnsupportedFrameworkErrorMessage { - get { - return ResourceManager.GetString("HotReloadHandlerUnsupportedFrameworkErrorMessage", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Hot reload test session completed. - /// - internal static string HotReloadSessionCompleted { - get { - return ResourceManager.GetString("HotReloadSessionCompleted", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Hot reload test session started. - /// - internal static string HotReloadSessionStarted { - get { - return ResourceManager.GetString("HotReloadSessionStarted", resourceCulture); - } - } - } -} diff --git a/src/Platform/Microsoft.Testing.Extensions.MSBuild/Microsoft.Testing.Extensions.MSBuild.csproj b/src/Platform/Microsoft.Testing.Extensions.MSBuild/Microsoft.Testing.Extensions.MSBuild.csproj index b830523061..33a50cbf53 100644 --- a/src/Platform/Microsoft.Testing.Extensions.MSBuild/Microsoft.Testing.Extensions.MSBuild.csproj +++ b/src/Platform/Microsoft.Testing.Extensions.MSBuild/Microsoft.Testing.Extensions.MSBuild.csproj @@ -19,8 +19,4 @@ - - - - diff --git a/src/Platform/Microsoft.Testing.Extensions.Retry/Microsoft.Testing.Extensions.Retry.csproj b/src/Platform/Microsoft.Testing.Extensions.Retry/Microsoft.Testing.Extensions.Retry.csproj index 9af602da35..017a33f007 100644 --- a/src/Platform/Microsoft.Testing.Extensions.Retry/Microsoft.Testing.Extensions.Retry.csproj +++ b/src/Platform/Microsoft.Testing.Extensions.Retry/Microsoft.Testing.Extensions.Retry.csproj @@ -43,21 +43,6 @@ This package extends Microsoft Testing Platform to provide a retry policy system - - - True - True - ExtensionResources.resx - - - - - - ResXFileCodeGenerator - ExtensionResources.Designer.cs - - - diff --git a/src/Platform/Microsoft.Testing.Extensions.Retry/Resources/ExtensionResources.Designer.cs b/src/Platform/Microsoft.Testing.Extensions.Retry/Resources/ExtensionResources.Designer.cs deleted file mode 100644 index 79b07ef2dc..0000000000 --- a/src/Platform/Microsoft.Testing.Extensions.Retry/Resources/ExtensionResources.Designer.cs +++ /dev/null @@ -1,284 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:4.0.30319.42000 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace Microsoft.Testing.Extensions.Policy.Resources { - using System; - - - /// - /// A strongly-typed resource class, for looking up localized strings, etc. - /// - // This class was auto-generated by the StronglyTypedResourceBuilder - // class via a tool like ResGen or Visual Studio. - // To add or remove a member, edit your .ResX file then rerun ResGen - // with the /str option, or rebuild your VS project. - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - internal class ExtensionResources { - - private static global::System.Resources.ResourceManager resourceMan; - - private static global::System.Globalization.CultureInfo resourceCulture; - - [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - internal ExtensionResources() { - } - - /// - /// Returns the cached ResourceManager instance used by this class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Resources.ResourceManager ResourceManager { - get { - if (object.ReferenceEquals(resourceMan, null)) { - global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Microsoft.Testing.Extensions.Policy.Resources.ExtensionResources", typeof(ExtensionResources).Assembly); - resourceMan = temp; - } - return resourceMan; - } - } - - /// - /// Overrides the current thread's CurrentUICulture property for all - /// resource lookups using this strongly typed resource class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Globalization.CultureInfo Culture { - get { - return resourceCulture; - } - set { - resourceCulture = value; - } - } - - /// - /// Looks up a localized string similar to Failed to create retries directory due to collisions in '{0}' despite re-trying.. - /// - internal static string FailedToCreateRetryDirectoryBecauseOfCollision { - get { - return ResourceManager.GetString("FailedToCreateRetryDirectoryBecauseOfCollision", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Failure threshold policy is enabled, failed tests will not be restarted.. - /// - internal static string FailureThresholdPolicy { - get { - return ResourceManager.GetString("FailureThresholdPolicy", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Maximum failed tests threshold is {0} and {1} tests failed. - /// - internal static string FailureThresholdPolicyMaxCount { - get { - return ResourceManager.GetString("FailureThresholdPolicyMaxCount", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Percentage failed threshold is {0}% and {1}% tests failed ({2}/{3}). - /// - internal static string FailureThresholdPolicyMaxPercentage { - get { - return ResourceManager.GetString("FailureThresholdPolicyMaxPercentage", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to - ///===================== - ///Moving last attempt asset files to the default result directory - ///===================== - ///. - /// - internal static string MoveFiles { - get { - return ResourceManager.GetString("MoveFiles", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Moving file '{0}' to '{1}'. - /// - internal static string MovingFileToLocation { - get { - return ResourceManager.GetString("MovingFileToLocation", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Failed to start process '{0}'. - /// - internal static string RetryFailedTestsCannotStartProcessErrorMessage { - get { - return ResourceManager.GetString("RetryFailedTestsCannotStartProcessErrorMessage", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Retry failed tests feature allows to restart test execution upon failure.. - /// - internal static string RetryFailedTestsExtensionDescription { - get { - return ResourceManager.GetString("RetryFailedTestsExtensionDescription", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Retry failed tests. - /// - internal static string RetryFailedTestsExtensionDisplayName { - get { - return ResourceManager.GetString("RetryFailedTestsExtensionDisplayName", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Retry failed tests only works with builders of type 'Microsoft.Testing.Platform.Builder.TestApplicationBuilder'. - /// - internal static string RetryFailedTestsInvalidTestApplicationBuilderErrorMessage { - get { - return ResourceManager.GetString("RetryFailedTestsInvalidTestApplicationBuilderErrorMessage", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Disable retry mechanism if the percentage of failed tests is greater than the specified value. - /// - internal static string RetryFailedTestsMaxPercentageOptionDescription { - get { - return ResourceManager.GetString("RetryFailedTestsMaxPercentageOptionDescription", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Disable retry mechanism if the number of failed tests is greater than the specified value. - /// - internal static string RetryFailedTestsMaxTestsOptionDescription { - get { - return ResourceManager.GetString("RetryFailedTestsMaxTestsOptionDescription", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Retry failed tests feature is not supported in hot reload mode. - /// - internal static string RetryFailedTestsNotSupportedInHotReloadErrorMessage { - get { - return ResourceManager.GetString("RetryFailedTestsNotSupportedInHotReloadErrorMessage", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Retry failed tests feature is not supported in server mode. - /// - internal static string RetryFailedTestsNotSupportedInServerModeErrorMessage { - get { - return ResourceManager.GetString("RetryFailedTestsNotSupportedInServerModeErrorMessage", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Enable retry failed tests. - /// - internal static string RetryFailedTestsOptionDescription { - get { - return ResourceManager.GetString("RetryFailedTestsOptionDescription", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Option '{0}' requires option '{1}' to be specified. - /// - internal static string RetryFailedTestsOptionIsMissingErrorMessage { - get { - return ResourceManager.GetString("RetryFailedTestsOptionIsMissingErrorMessage", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Option '{0}' expects a single integer argument. - /// - internal static string RetryFailedTestsOptionSingleIntegerArgumentErrorMessage { - get { - return ResourceManager.GetString("RetryFailedTestsOptionSingleIntegerArgumentErrorMessage", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Options '{0}' and '{1}' cannot be used together. - /// - internal static string RetryFailedTestsPercentageAndCountCannotBeMixedErrorMessage { - get { - return ResourceManager.GetString("RetryFailedTestsPercentageAndCountCannotBeMixedErrorMessage", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Test host process exited before the retry service could connect to it. Exit code: {0}. - /// - internal static string TestHostProcessExitedBeforeRetryCouldConnect { - get { - return ResourceManager.GetString("TestHostProcessExitedBeforeRetryCouldConnect", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to - ///===================== - ///Tests suite completed successfully in {0} attempts - ///=====================. - /// - internal static string TestSuiteCompletedSuccessfully { - get { - return ResourceManager.GetString("TestSuiteCompletedSuccessfully", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to - ///===================== - ///Tests suite failed, total failed tests: {0}, exit code: {1}, attempt: {2}/{3} - ///===================== - ///. - /// - internal static string TestSuiteFailed { - get { - return ResourceManager.GetString("TestSuiteFailed", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to - ///===================== - ///Tests suite failed in all {0} attempts - ///=====================. - /// - internal static string TestSuiteFailedInAllAttempts { - get { - return ResourceManager.GetString("TestSuiteFailedInAllAttempts", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Test suite failed with and exit code different that 2 (failed tests). Failure related to an unexpected condition. Exit code '{0}'. - /// - internal static string TestSuiteFailedWithWrongExitCode { - get { - return ResourceManager.GetString("TestSuiteFailedWithWrongExitCode", resourceCulture); - } - } - } -} diff --git a/src/Platform/Microsoft.Testing.Extensions.Telemetry/Microsoft.Testing.Extensions.Telemetry.csproj b/src/Platform/Microsoft.Testing.Extensions.Telemetry/Microsoft.Testing.Extensions.Telemetry.csproj index 7eca355606..5ff94339a8 100644 --- a/src/Platform/Microsoft.Testing.Extensions.Telemetry/Microsoft.Testing.Extensions.Telemetry.csproj +++ b/src/Platform/Microsoft.Testing.Extensions.Telemetry/Microsoft.Testing.Extensions.Telemetry.csproj @@ -48,10 +48,6 @@ This package provides telemetry for the platform.]]> - - - - diff --git a/src/Platform/Microsoft.Testing.Extensions.TrxReport/Microsoft.Testing.Extensions.TrxReport.csproj b/src/Platform/Microsoft.Testing.Extensions.TrxReport/Microsoft.Testing.Extensions.TrxReport.csproj index 0cfd477f7f..5aa0333965 100644 --- a/src/Platform/Microsoft.Testing.Extensions.TrxReport/Microsoft.Testing.Extensions.TrxReport.csproj +++ b/src/Platform/Microsoft.Testing.Extensions.TrxReport/Microsoft.Testing.Extensions.TrxReport.csproj @@ -54,10 +54,6 @@ This package extends Microsoft Testing Platform to provide TRX test reports.]]> - - - - diff --git a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/Microsoft.Testing.Extensions.VSTestBridge.csproj b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/Microsoft.Testing.Extensions.VSTestBridge.csproj index fd51a85275..cf8668354d 100644 --- a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/Microsoft.Testing.Extensions.VSTestBridge.csproj +++ b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/Microsoft.Testing.Extensions.VSTestBridge.csproj @@ -36,10 +36,6 @@ This package provides a bridge integration for test adapters wanting to target b - - - - diff --git a/src/Platform/Microsoft.Testing.Platform.MSBuild/Microsoft.Testing.Platform.MSBuild.csproj b/src/Platform/Microsoft.Testing.Platform.MSBuild/Microsoft.Testing.Platform.MSBuild.csproj index 57274bc055..619611adb6 100644 --- a/src/Platform/Microsoft.Testing.Platform.MSBuild/Microsoft.Testing.Platform.MSBuild.csproj +++ b/src/Platform/Microsoft.Testing.Platform.MSBuild/Microsoft.Testing.Platform.MSBuild.csproj @@ -58,10 +58,6 @@ This package provides MSBuild integration of the platform, its extensions and co - - - - diff --git a/src/Platform/Microsoft.Testing.Platform/Microsoft.Testing.Platform.csproj b/src/Platform/Microsoft.Testing.Platform/Microsoft.Testing.Platform.csproj index c77b8f1fb9..0e41d8bb55 100644 --- a/src/Platform/Microsoft.Testing.Platform/Microsoft.Testing.Platform.csproj +++ b/src/Platform/Microsoft.Testing.Platform/Microsoft.Testing.Platform.csproj @@ -74,10 +74,6 @@ This package provides the core platform and the .NET implementation of the proto - - - - diff --git a/src/TestFramework/TestFramework.Extensions/Resources/FrameworkExtensionsMessages.Designer.cs b/src/TestFramework/TestFramework.Extensions/Resources/FrameworkExtensionsMessages.Designer.cs deleted file mode 100644 index 8591c426b3..0000000000 --- a/src/TestFramework/TestFramework.Extensions/Resources/FrameworkExtensionsMessages.Designer.cs +++ /dev/null @@ -1,81 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:4.0.30319.42000 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace Microsoft.VisualStudio.TestTools.UnitTesting { - using System; - - - /// - /// A strongly-typed resource class, for looking up localized strings, etc. - /// - // This class was auto-generated by the StronglyTypedResourceBuilder - // class via a tool like ResGen or Visual Studio. - // To add or remove a member, edit your .ResX file then rerun ResGen - // with the /str option, or rebuild your VS project. - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - internal class FrameworkExtensionsMessages { - - private static global::System.Resources.ResourceManager resourceMan; - - private static global::System.Globalization.CultureInfo resourceCulture; - - [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - internal FrameworkExtensionsMessages() { - } - - /// - /// Returns the cached ResourceManager instance used by this class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Resources.ResourceManager ResourceManager { - get { - if (object.ReferenceEquals(resourceMan, null)) { - global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Microsoft.VisualStudio.TestTools.UnitTesting.Resources.FrameworkExtensionsMessages", typeof(FrameworkExtensionsMessages).Assembly); - resourceMan = temp; - } - return resourceMan; - } - } - - /// - /// Overrides the current thread's CurrentUICulture property for all - /// resource lookups using this strongly typed resource class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Globalization.CultureInfo Culture { - get { - return resourceCulture; - } - set { - resourceCulture = value; - } - } - - /// - /// Looks up a localized string similar to Type '{0}' is not assignable to '{1}'.. - /// - internal static string ArgumentXMustDeriveFromClassY { - get { - return ResourceManager.GetString("ArgumentXMustDeriveFromClassY", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to UITestMethodAttribute.DispatcherQueue should not be null. To use UITestMethodAttribute within a WinUI Desktop App, remember to set the static UITestMethodAttribute.DispatcherQueue during the test initialization.. - /// - internal static string AsyncUITestMethodWithNoDispatcherQueue { - get { - return ResourceManager.GetString("AsyncUITestMethodWithNoDispatcherQueue", resourceCulture); - } - } - } -} diff --git a/src/TestFramework/TestFramework.Extensions/TestFramework.Extensions.csproj b/src/TestFramework/TestFramework.Extensions/TestFramework.Extensions.csproj index 3a751c24b1..67cdf269a5 100644 --- a/src/TestFramework/TestFramework.Extensions/TestFramework.Extensions.csproj +++ b/src/TestFramework/TestFramework.Extensions/TestFramework.Extensions.csproj @@ -88,6 +88,7 @@ + @@ -96,20 +97,6 @@ - - - True - True - FrameworkExtensionsMessages.resx - - - ResXFileCodeGenerator - FrameworkExtensionsMessages.Designer.cs - Microsoft.VisualStudio.TestTools.UnitTesting - Designer - - - diff --git a/src/TestFramework/TestFramework/Resources/FrameworkMessages.Designer.cs b/src/TestFramework/TestFramework/Resources/FrameworkMessages.Designer.cs deleted file mode 100644 index 698a07f64f..0000000000 --- a/src/TestFramework/TestFramework/Resources/FrameworkMessages.Designer.cs +++ /dev/null @@ -1,748 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:4.0.30319.42000 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace Microsoft.VisualStudio.TestTools.UnitTesting { - using System; - - - /// - /// A strongly-typed resource class, for looking up localized strings, etc. - /// - // This class was auto-generated by the StronglyTypedResourceBuilder - // class via a tool like ResGen or Visual Studio. - // To add or remove a member, edit your .ResX file then rerun ResGen - // with the /str option, or rebuild your VS project. - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - internal class FrameworkMessages { - - private static global::System.Resources.ResourceManager resourceMan; - - private static global::System.Globalization.CultureInfo resourceCulture; - - [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - internal FrameworkMessages() { - } - - /// - /// Returns the cached ResourceManager instance used by this class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Resources.ResourceManager ResourceManager { - get { - if (object.ReferenceEquals(resourceMan, null)) { - global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Microsoft.VisualStudio.TestTools.UnitTesting.Resources.FrameworkMessages", typeof(FrameworkMessages).Assembly); - resourceMan = temp; - } - return resourceMan; - } - } - - /// - /// Overrides the current thread's CurrentUICulture property for all - /// resource lookups using this strongly typed resource class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Globalization.CultureInfo Culture { - get { - return resourceCulture; - } - set { - resourceCulture = value; - } - } - - /// - /// Looks up a localized string similar to Access string has invalid syntax.. - /// - internal static string AccessStringInvalidSyntax { - get { - return ResourceManager.GetString("AccessStringInvalidSyntax", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The expected collection contains {1} occurrence(s) of <{2}>. The actual collection contains {3} occurrence(s). {0}. - /// - internal static string ActualHasMismatchedElements { - get { - return ResourceManager.GetString("ActualHasMismatchedElements", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Duplicate item found:<{1}>. {0}. - /// - internal static string AllItemsAreUniqueFailMsg { - get { - return ResourceManager.GetString("AllItemsAreUniqueFailMsg", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Expected:<{1}>. Case is different for actual value:<{2}>. {0}. - /// - internal static string AreEqualCaseFailMsg { - get { - return ResourceManager.GetString("AreEqualCaseFailMsg", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Expected a difference no greater than <{3}> between expected value <{1}> and actual value <{2}>. {0}. - /// - internal static string AreEqualDeltaFailMsg { - get { - return ResourceManager.GetString("AreEqualDeltaFailMsg", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Expected:<{1} ({2})>. Actual:<{3} ({4})>. {0}. - /// - internal static string AreEqualDifferentTypesFailMsg { - get { - return ResourceManager.GetString("AreEqualDifferentTypesFailMsg", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Expected:<{1}>. Actual:<{2}>. {0}. - /// - internal static string AreEqualFailMsg { - get { - return ResourceManager.GetString("AreEqualFailMsg", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Expected a difference greater than <{3}> between expected value <{1}> and actual value <{2}>. {0}. - /// - internal static string AreNotEqualDeltaFailMsg { - get { - return ResourceManager.GetString("AreNotEqualDeltaFailMsg", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Expected any value except:<{1}>. Actual:<{2}>. {0}. - /// - internal static string AreNotEqualFailMsg { - get { - return ResourceManager.GetString("AreNotEqualFailMsg", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Do not pass value types to AreSame(). Values converted to Object will never be the same. Consider using AreEqual(). {0}. - /// - internal static string AreSameGivenValues { - get { - return ResourceManager.GetString("AreSameGivenValues", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to {0} failed. {1}. - /// - internal static string AssertionFailed { - get { - return ResourceManager.GetString("AssertionFailed", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Both collections are empty. {0}. - /// - internal static string BothCollectionsEmpty { - get { - return ResourceManager.GetString("BothCollectionsEmpty", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Both collection contain same elements.. - /// - internal static string BothCollectionsSameElements { - get { - return ResourceManager.GetString("BothCollectionsSameElements", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Both collection references point to the same collection object. {0}. - /// - internal static string BothCollectionsSameReference { - get { - return ResourceManager.GetString("BothCollectionsSameReference", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Both collections contain the same elements. {0}. - /// - internal static string BothSameElements { - get { - return ResourceManager.GetString("BothSameElements", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to {0}. {1}. - /// - internal static string CollectionEqualReason { - get { - return ResourceManager.GetString("CollectionEqualReason", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to (null). - /// - internal static string Common_NullInMessages { - get { - return ResourceManager.GetString("Common_NullInMessages", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to (object). - /// - internal static string Common_ObjectString { - get { - return ResourceManager.GetString("Common_ObjectString", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to String '{0}' does not contain string '{1}'. {2}.. - /// - internal static string ContainsFail { - get { - return ResourceManager.GetString("ContainsFail", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Expected collection to contain the specified item. {0}. - /// - internal static string ContainsItemFailMsg { - get { - return ResourceManager.GetString("ContainsItemFailMsg", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Expected at least one item to match the predicate. {0}. - /// - internal static string ContainsPredicateFailMsg { - get { - return ResourceManager.GetString("ContainsPredicateFailMsg", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Expected collection to contain exactly one element but found {1} element(s). {0}. - /// - internal static string ContainsSingleFailMsg { - get { - return ResourceManager.GetString("ContainsSingleFailMsg", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Expected exactly one item to match the predicate but found {1} item(s). {0}. - /// - internal static string ContainsSingleMatchFailMsg { - get { - return ResourceManager.GetString("ContainsSingleMatchFailMsg", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to {0} ({1}). - /// - internal static string DataDrivenResultDisplayName { - get { - return ResourceManager.GetString("DataDrivenResultDisplayName", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to String '{0}' does contain string '{1}'. {2}.. - /// - internal static string DoesNotContainFail { - get { - return ResourceManager.GetString("DoesNotContainFail", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Expected collection to not contain the specified item. {0}. - /// - internal static string DoesNotContainItemFailMsg { - get { - return ResourceManager.GetString("DoesNotContainItemFailMsg", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Expected no items to match the predicate. {0}. - /// - internal static string DoesNotContainPredicateFailMsg { - get { - return ResourceManager.GetString("DoesNotContainPredicateFailMsg", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to String '{0}' ends with string '{1}'. {2}. - /// - internal static string DoesNotEndWithFail { - get { - return ResourceManager.GetString("DoesNotEndWithFail", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to String '{0}' starts with string '{1}'. {2}. - /// - internal static string DoesNotStartWithFail { - get { - return ResourceManager.GetString("DoesNotStartWithFail", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Assert.Equals should not be used for Assertions. Please use Assert.AreEqual & overloads instead.. - /// - internal static string DoNotUseAssertEquals { - get { - return ResourceManager.GetString("DoNotUseAssertEquals", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Assert.ReferenceEquals should not be used for Assertions. Please use Assert.AreSame & overloads instead.. - /// - internal static string DoNotUseAssertReferenceEquals { - get { - return ResourceManager.GetString("DoNotUseAssertReferenceEquals", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to CollectionAssert.Equals should not be used for Assertions. Please use CollectionAssert.AreEqual & overloads instead.. - /// - internal static string DoNotUseCollectionAssertEquals { - get { - return ResourceManager.GetString("DoNotUseCollectionAssertEquals", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to CollectionAssert.ReferenceEquals should not be used for Assertions. Please use CollectionAssert methods or Assert.AreSame & overloads instead.. - /// - internal static string DoNotUseCollectionAssertReferenceEquals { - get { - return ResourceManager.GetString("DoNotUseCollectionAssertReferenceEquals", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to StringAssert.Equals should not be used for Assertions. Please use StringAssert methods or Assert.AreEqual & overloads instead.. - /// - internal static string DoNotUseStringAssertEquals { - get { - return ResourceManager.GetString("DoNotUseStringAssertEquals", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to StringAssert.ReferenceEquals should not be used for Assertions. Please use StringAssert methods or Assert.AreSame & overloads instead.. - /// - internal static string DoNotUseStringAssertReferenceEquals { - get { - return ResourceManager.GetString("DoNotUseStringAssertReferenceEquals", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Method {0} must match the expected signature: public static {1} {0}({2}).. - /// - internal static string DynamicDataDisplayName { - get { - return ResourceManager.GetString("DynamicDataDisplayName", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Property or method {0} on {1} returns empty IEnumerable<object[]>.. - /// - internal static string DynamicDataIEnumerableEmpty { - get { - return ResourceManager.GetString("DynamicDataIEnumerableEmpty", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Property or method {0} on {1} return type is not assignable to 'IEnumerable'.. - /// - internal static string DynamicDataIEnumerableNull { - get { - return ResourceManager.GetString("DynamicDataIEnumerableNull", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Dynamic data method '{0}' should be static, non-generic, and cannot have 'params' parameter.. - /// - internal static string DynamicDataInvalidMethodLayout { - get { - return ResourceManager.GetString("DynamicDataInvalidMethodLayout", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Dynamic data property '{0}' should be static and have a getter.. - /// - internal static string DynamicDataInvalidPropertyLayout { - get { - return ResourceManager.GetString("DynamicDataInvalidPropertyLayout", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Dynamic data field '{0}' should be static.. - /// - internal static string DynamicDataInvalidFieldLayout { - get { - return ResourceManager.GetString("DynamicDataInvalidFieldLayout", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The dynamic data source '{0}' in type '{1}' should exist and be a property, a method, or a field.. - /// - internal static string DynamicDataSourceShouldExistAndBeValid { - get { - return ResourceManager.GetString("DynamicDataSourceShouldExistAndBeValid", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Value returned by property or method {0} shouldn't be null.. - /// - internal static string DynamicDataValueNull { - get { - return ResourceManager.GetString("DynamicDataValueNull", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The number of elements in the collections do not match. Expected:<{1}>. Actual:<{2}>.{0}. - /// - internal static string ElementNumbersDontMatch { - get { - return ResourceManager.GetString("ElementNumbersDontMatch", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Element at index {0} do not match. - ///Expected: {1} - ///Actual: {2}. - /// - internal static string ElementsAtIndexDontMatch { - get { - return ResourceManager.GetString("ElementsAtIndexDontMatch", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Element at index {1} is not of expected type. Expected type:<{2}>. Actual type:<{3}>.{0}. - /// - internal static string ElementTypesAtIndexDontMatch { - get { - return ResourceManager.GetString("ElementTypesAtIndexDontMatch", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to String '{0}' does not end with string '{1}'. {2}. - /// - internal static string EndsWithFail { - get { - return ResourceManager.GetString("EndsWithFail", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Expected collection of size {1}. Actual: {2}. {0}. - /// - internal static string HasCountFailMsg { - get { - return ResourceManager.GetString("HasCountFailMsg", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Invalid GitHub ticket URL. - /// - internal static string InvalidGitHubUrl { - get { - return ResourceManager.GetString("InvalidGitHubUrl", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The property {0} has type {1}; expected type {2}.. - /// - internal static string InvalidPropertyType { - get { - return ResourceManager.GetString("InvalidPropertyType", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Actual value <{2}> is not greater than expected value <{1}>. {0}. - /// - internal static string IsGreaterThanFailMsg { - get { - return ResourceManager.GetString("IsGreaterThanFailMsg", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Actual value <{2}> is not greater than or equal to expected value <{1}>. {0}. - /// - internal static string IsGreaterThanOrEqualToFailMsg { - get { - return ResourceManager.GetString("IsGreaterThanOrEqualToFailMsg", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Value '{0}' is not within the expected range [{1}, {2}]. {3}. - /// - internal static string IsInRangeFail { - get { - return ResourceManager.GetString("IsInRangeFail", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to {0} Expected type:<{1}>. Actual type:<{2}>.. - /// - internal static string IsInstanceOfFailMsg { - get { - return ResourceManager.GetString("IsInstanceOfFailMsg", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Actual value <{2}> is not less than expected value <{1}>. {0}. - /// - internal static string IsLessThanFailMsg { - get { - return ResourceManager.GetString("IsLessThanFailMsg", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Actual value <{2}> is not less than or equal to expected value <{1}>. {0}. - /// - internal static string IsLessThanOrEqualToFailMsg { - get { - return ResourceManager.GetString("IsLessThanOrEqualToFailMsg", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to String '{0}' does not match pattern '{1}'. {2}. - /// - internal static string IsMatchFail { - get { - return ResourceManager.GetString("IsMatchFail", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Expected value <{1}> to be negative. {0}. - /// - internal static string IsNegativeFailMsg { - get { - return ResourceManager.GetString("IsNegativeFailMsg", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Expected collection to contain any item but it is empty. {0}. - /// - internal static string IsNotEmptyFailMsg { - get { - return ResourceManager.GetString("IsNotEmptyFailMsg", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Wrong Type:<{1}>. Actual type:<{2}>. {0}. - /// - internal static string IsNotInstanceOfFailMsg { - get { - return ResourceManager.GetString("IsNotInstanceOfFailMsg", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to String '{0}' matches pattern '{1}'. {2}. - /// - internal static string IsNotMatchFail { - get { - return ResourceManager.GetString("IsNotMatchFail", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Expected value <{1}> to be positive. {0}. - /// - internal static string IsPositiveFailMsg { - get { - return ResourceManager.GetString("IsPositiveFailMsg", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Expected exception type:<{1}> but no exception was thrown. {0}. - /// - internal static string NoExceptionThrown { - get { - return ResourceManager.GetString("NoExceptionThrown", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The parameter '{0}' is invalid. The value cannot be null. {1}.. - /// - internal static string NullParameterToAssert { - get { - return ResourceManager.GetString("NullParameterToAssert", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Different number of elements.. - /// - internal static string NumberOfElementsDiff { - get { - return ResourceManager.GetString("NumberOfElementsDiff", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to - /// The constructor with the specified signature could not be found. You might need to regenerate your private accessor, - /// or the member may be private and defined on a base class. If the latter is true, you need to pass the type - /// that defines the member into PrivateObject's constructor. - /// . - /// - internal static string PrivateAccessorConstructorNotFound { - get { - return ResourceManager.GetString("PrivateAccessorConstructorNotFound", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to - /// The member specified ({0}) could not be found. You might need to regenerate your private accessor, - /// or the member may be private and defined on a base class. If the latter is true, you need to pass the type - /// that defines the member into PrivateObject's constructor. - /// . - /// - internal static string PrivateAccessorMemberNotFound { - get { - return ResourceManager.GetString("PrivateAccessorMemberNotFound", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to String '{0}' does not start with string '{1}'. {2}. - /// - internal static string StartsWithFail { - get { - return ResourceManager.GetString("StartsWithFail", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The expected exception type must be System.Exception or a type derived from System.Exception.. - /// - internal static string UTF_ExpectedExceptionTypeMustDeriveFromException { - get { - return ResourceManager.GetString("UTF_ExpectedExceptionTypeMustDeriveFromException", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to (Failed to get the message for an exception of type {0} due to an exception.). - /// - internal static string UTF_FailedToGetExceptionMessage { - get { - return ResourceManager.GetString("UTF_FailedToGetExceptionMessage", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Test method did not throw expected exception {0}. {1}. - /// - internal static string UTF_TestMethodNoException { - get { - return ResourceManager.GetString("UTF_TestMethodNoException", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Test method did not throw an exception. An exception was expected by attribute {0} defined on the test method.. - /// - internal static string UTF_TestMethodNoExceptionDefault { - get { - return ResourceManager.GetString("UTF_TestMethodNoExceptionDefault", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Test method threw exception {0}, but exception {1} was expected. Exception message: {2}. - /// - internal static string UTF_TestMethodWrongException { - get { - return ResourceManager.GetString("UTF_TestMethodWrongException", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Test method threw exception {0}, but exception {1} or a type derived from it was expected. Exception message: {2}. - /// - internal static string UTF_TestMethodWrongExceptionDerivedAllowed { - get { - return ResourceManager.GetString("UTF_TestMethodWrongExceptionDerivedAllowed", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Expected exception type:<{1}>. Actual exception type:<{2}>. {0}. - /// - internal static string WrongExceptionThrown { - get { - return ResourceManager.GetString("WrongExceptionThrown", resourceCulture); - } - } - } -} diff --git a/src/TestFramework/TestFramework/TestFramework.csproj b/src/TestFramework/TestFramework/TestFramework.csproj index 265bc3d974..d1c919233b 100644 --- a/src/TestFramework/TestFramework/TestFramework.csproj +++ b/src/TestFramework/TestFramework/TestFramework.csproj @@ -43,22 +43,9 @@ - - - True - True - FrameworkMessages.resx - - - ResXFileCodeGenerator - FrameworkMessages.Designer.cs - Microsoft.VisualStudio.TestTools.UnitTesting - Designer - - - + diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Deployment/DeploymentItemTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Deployment/DeploymentItemTests.cs index 34b48cb028..4eb8834a36 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Deployment/DeploymentItemTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Deployment/DeploymentItemTests.cs @@ -1,8 +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 Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Deployment; +using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Resources; using TestFramework.ForTestingMSTest; diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Discovery/AssemblyEnumeratorTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Discovery/AssemblyEnumeratorTests.cs index bb874f4757..86b380a3f5 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Discovery/AssemblyEnumeratorTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Discovery/AssemblyEnumeratorTests.cs @@ -7,7 +7,7 @@ using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Discovery; using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Helpers; using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel; -using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; +using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Resources; using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.TestableImplementations; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging; diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Discovery/AssemblyEnumeratorWrapperTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Discovery/AssemblyEnumeratorWrapperTests.cs index 4276e16d93..32a73cdba7 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Discovery/AssemblyEnumeratorWrapperTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Discovery/AssemblyEnumeratorWrapperTests.cs @@ -3,7 +3,7 @@ using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter; using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Discovery; -using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; +using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Resources; using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.TestableImplementations; using Moq; diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Discovery/TypeValidatorTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Discovery/TypeValidatorTests.cs index 7916f355c1..7745cdc0cc 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Discovery/TypeValidatorTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Discovery/TypeValidatorTests.cs @@ -3,7 +3,7 @@ using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Discovery; using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Helpers; -using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; +using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Resources; using Moq; diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestMethodInfoTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestMethodInfoTests.cs index a6f7dea1cc..73f68819ac 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestMethodInfoTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestMethodInfoTests.cs @@ -6,6 +6,7 @@ using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel; using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Interface; +using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Resources; using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.TestableImplementations; using Moq; diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestMethodRunnerTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestMethodRunnerTests.cs index a6a3817026..2b2c91a3d9 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestMethodRunnerTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestMethodRunnerTests.cs @@ -8,6 +8,7 @@ using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Interface; using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.TestableImplementations; +using Microsoft.VisualStudio.TestTools.UnitTesting.Resources; using Moq; diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Extensions/ExceptionExtensionsTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Extensions/ExceptionExtensionsTests.cs index ec2af07cf3..bf28034646 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Extensions/ExceptionExtensionsTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Extensions/ExceptionExtensionsTests.cs @@ -2,8 +2,8 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel; -using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Extensions; +using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Resources; using TestFramework.ForTestingMSTest; diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Extensions/MethodInfoExtensionsTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Extensions/MethodInfoExtensionsTests.cs index 3341676ab3..d330dc42e8 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Extensions/MethodInfoExtensionsTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Extensions/MethodInfoExtensionsTests.cs @@ -3,8 +3,8 @@ using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Extensions; using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel; -using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Extensions; +using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Resources; using TestFramework.ForTestingMSTest; diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/MSTestSettingsTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/MSTestSettingsTests.cs index af31738440..8ddac24611 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/MSTestSettingsTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/MSTestSettingsTests.cs @@ -3,8 +3,8 @@ using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter; using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel; -using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Interface; +using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Resources; using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.TestableImplementations; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging; diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/TestContextImplementationTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/TestContextImplementationTests.cs index dc49451d72..5c457cf39e 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/TestContextImplementationTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/TestContextImplementationTests.cs @@ -7,6 +7,7 @@ #endif using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; +using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Resources; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging; using Moq; diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Utilities/DeploymentUtilityTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Utilities/DeploymentUtilityTests.cs index 928a13ca44..3ca5bd35f4 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Utilities/DeploymentUtilityTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Utilities/DeploymentUtilityTests.cs @@ -1,8 +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 Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Deployment; +using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Resources; using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Utilities; using Microsoft.VisualStudio.TestPlatform.ObjectModel; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter; diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Utilities/ns13DeploymentItemUtilityTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Utilities/ns13DeploymentItemUtilityTests.cs index 0cdb0d537d..539c42f503 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Utilities/ns13DeploymentItemUtilityTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Utilities/ns13DeploymentItemUtilityTests.cs @@ -1,8 +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 Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Deployment; +using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Resources; using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Utilities; using Microsoft.VisualStudio.TestPlatform.ObjectModel; diff --git a/test/UnitTests/TestFramework.UnitTests/Attributes/DynamicDataAttributeTests.cs b/test/UnitTests/TestFramework.UnitTests/Attributes/DynamicDataAttributeTests.cs index 97a6020d0e..4354e252b4 100644 --- a/test/UnitTests/TestFramework.UnitTests/Attributes/DynamicDataAttributeTests.cs +++ b/test/UnitTests/TestFramework.UnitTests/Attributes/DynamicDataAttributeTests.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 Microsoft.VisualStudio.TestTools.UnitTesting.Resources; + using TestFramework.ForTestingMSTest; namespace Microsoft.VisualStudio.TestPlatform.TestFramework.UnitTests.Attributes; From 5d4f9500884e94c11c31a912f7455083ae509402 Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Fri, 1 Aug 2025 08:46:01 +0200 Subject: [PATCH 347/541] [main] Update dependencies from devdiv/DevDiv/vs-code-coverage (#6273) Co-authored-by: dotnet-maestro[bot] --- eng/Version.Details.xml | 4 ++-- eng/Versions.props | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index 0edc34f6de..6ea3f5e2ee 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -13,9 +13,9 @@ https://github.com/dotnet/arcade 8df06d38fb9183c3fdff5077b670eb35f0cb3f31 - + https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage - f6f6f1d48de353f64e428115a9624dc4c73dd13b + c424a64350b804d827578adb55e00a0749731a51 https://github.com/microsoft/testfx diff --git a/eng/Versions.props b/eng/Versions.props index e496124367..07d92a6155 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -8,7 +8,7 @@ 10.0.0-beta.25379.3 - 18.0.0-preview.25380.2 + 18.0.0-preview.25381.1 3.11.0-preview.25380.15 1.9.0-preview.25380.15 From 97b9d602094920828c6fc87025c8437bcc92f27e Mon Sep 17 00:00:00 2001 From: dotnet bot Date: Fri, 1 Aug 2025 00:01:51 -0700 Subject: [PATCH 348/541] Localized file check-in by OneLocBuild Task: Build definition ID 1218: Build ID 2762527 --- src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf | 6 +++--- src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf | 6 +++--- src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf | 6 +++--- src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf | 6 +++--- src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf | 6 +++--- 5 files changed, 15 insertions(+), 15 deletions(-) diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf index 73605a1c41..6242e90714 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf @@ -967,17 +967,17 @@ Der Typ, der diese Methoden deklariert, sollte auch die folgenden Regeln beachte Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws. - Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws. + Assert.Throws-Methoden dürfen nur eine einzelne Anweisung oder einen einzelnen Ausdruck enthalten. Mehrere Anweisungen können irreführend sein: Wenn die erste Anweisung eine Ausnahme auslöst, werden nachfolgende Anweisungen nie ausgeführt; wenn sie keine Ausnahme auslöst, sollte sie nach außerhalb von Assert.Throws verschoben werden. Assert.Throws should contain only a single statement/expression - Assert.Throws should contain only a single statement/expression + Assert.Throws darf nur eine einzelne Anweisung/einen einzelnen Ausdruck enthalten Assert.Throws should contain only a single statement/expression - Assert.Throws should contain only a single statement/expression + Assert.Throws darf nur eine einzelne Anweisung/einen einzelnen Ausdruck enthalten diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf index f4c6ebc874..5e2d061ae8 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf @@ -966,17 +966,17 @@ Anche il tipo che dichiara questi metodi deve rispettare le regole seguenti: Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws. - Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws. + I metodi Assert.Throws devono contenere solo una singola istruzione o espressione. Istruzioni multiple possono essere fuorvianti: se la prima istruzione genera, le istruzioni successive non vengono mai eseguite; se non genera, è necessario spostarla all'esterno di Assert.Throws. Assert.Throws should contain only a single statement/expression - Assert.Throws should contain only a single statement/expression + Assert.Throws deve contenere solo una singola istruzione/espressione Assert.Throws should contain only a single statement/expression - Assert.Throws should contain only a single statement/expression + Assert.Throws deve contenere solo una singola istruzione/espressione diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf index 53c6356d12..afde6025b5 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf @@ -966,17 +966,17 @@ O tipo que declara esses métodos também deve respeitar as seguintes regras: Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws. - Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws. + Os métodos Assert.Throws devem conter apenas uma única declaração ou expressão. Várias declarações podem ser enganosas: se a primeira declaração for lançada, as declarações subsequentes nunca serão executadas; se não lançar, ela deverá ser movida para fora do Assert.Throws. Assert.Throws should contain only a single statement/expression - Assert.Throws should contain only a single statement/expression + Assert.Throws deve conter apenas uma única declaração/expressão Assert.Throws should contain only a single statement/expression - Assert.Throws should contain only a single statement/expression + Assert.Throws deve conter apenas uma única declaração/expressão diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf index e182e64a4f..3c611b0d65 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf @@ -978,17 +978,17 @@ The type declaring these methods should also respect the following rules: Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws. - Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws. + Методы Assert.Throws должны содержать только одну инструкцию или выражение. Несколько инструкций могут вводить в заблуждение: если первое выражение вызывает исключение, последующие инструкции не выполняются; если исключение не возникает, его следует вынести за пределы Assert.Throws. Assert.Throws should contain only a single statement/expression - Assert.Throws should contain only a single statement/expression + Assert.Throws должен содержать только одну инструкцию/выражение Assert.Throws should contain only a single statement/expression - Assert.Throws should contain only a single statement/expression + Assert.Throws должен содержать только одну инструкцию/выражение diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf index a566285c1b..3278b76988 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf @@ -966,17 +966,17 @@ The type declaring these methods should also respect the following rules: Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws. - Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws. + Assert.Throws 方法應該只包含單一陳述式或運算式。多個陳述式可能會產生誤導 - 如果擲出第一個陳述式,後續陳述式永遠不會執行; 如果未擲回,則應該移到 Assert.Throws 之外。 Assert.Throws should contain only a single statement/expression - Assert.Throws should contain only a single statement/expression + Assert.Throws 應該只包含單一陳述式/運算式 Assert.Throws should contain only a single statement/expression - Assert.Throws should contain only a single statement/expression + Assert.Throws 應該只包含單一陳述式/運算式 From 799da019f3ce9d03fdc785e24cf90abcd15df200 Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Fri, 1 Aug 2025 07:59:58 +0000 Subject: [PATCH 349/541] [main] Update dependencies from microsoft/testfx (#6274) Co-authored-by: dotnet-maestro[bot] Co-authored-by: Youssef1313 --- eng/Version.Details.xml | 8 ++++---- eng/Versions.props | 4 ++-- .../DotnetTestCliTests.cs | 2 +- .../MSBuildRunnerTests.cs | 2 +- .../RunnerTests.cs | 8 ++++---- .../RunsettingsTests.cs | 2 +- .../SdkTests.cs | 16 ++++++++-------- .../MSTest.Engine.UnitTests/DynamicDataTests.cs | 8 ++++---- 8 files changed, 25 insertions(+), 25 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index 6ea3f5e2ee..dd36e09b53 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -17,13 +17,13 @@ https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage c424a64350b804d827578adb55e00a0749731a51 - + https://github.com/microsoft/testfx - 9f49e7a264ea799ff1adfdbe79cc45eefdc89cee + f548433961344ee1629c5b04c35d99efc9fdd860 - + https://github.com/microsoft/testfx - 9f49e7a264ea799ff1adfdbe79cc45eefdc89cee + f548433961344ee1629c5b04c35d99efc9fdd860 diff --git a/eng/Versions.props b/eng/Versions.props index 07d92a6155..d6ac1e08e4 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -10,7 +10,7 @@ 10.0.0-beta.25379.3 18.0.0-preview.25381.1 - 3.11.0-preview.25380.15 - 1.9.0-preview.25380.15 + 3.11.0-preview.25381.6 + 1.9.0-preview.25381.6 diff --git a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/DotnetTestCliTests.cs b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/DotnetTestCliTests.cs index 866bd1ed8f..a0c1192fed 100644 --- a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/DotnetTestCliTests.cs +++ b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/DotnetTestCliTests.cs @@ -12,7 +12,7 @@ public class DotnetTestCliTests : AcceptanceTestBase private const string AssetName = "MSTestProject"; [TestMethod] - [DynamicData(nameof(GetBuildMatrixTfmBuildConfiguration), typeof(AcceptanceTestBase), DynamicDataSourceType.Method)] + [DynamicData(nameof(GetBuildMatrixTfmBuildConfiguration), typeof(AcceptanceTestBase))] public async Task DotnetTest_Should_Execute_Tests(string tfm, BuildConfiguration buildConfiguration) { using TestAsset generator = await TestAsset.GenerateAssetAsync( diff --git a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/MSBuildRunnerTests.cs b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/MSBuildRunnerTests.cs index e826266a0b..a65f29602d 100644 --- a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/MSBuildRunnerTests.cs +++ b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/MSBuildRunnerTests.cs @@ -28,7 +28,7 @@ public class MSBuildRunnerTests : AcceptanceTestBase } [TestMethod] - [DynamicData(nameof(GetBuildMatrix), DynamicDataSourceType.Method)] + [DynamicData(nameof(GetBuildMatrix))] public async Task MSBuildTestTarget_SingleAndMultiTfm_Should_Run_Solution_Tests(string singleTfmOrMultiTfm, BuildConfiguration buildConfiguration, bool isMultiTfm, string command) { // Get the template project diff --git a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/RunnerTests.cs b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/RunnerTests.cs index f33fa0eb98..977aa8e1ce 100644 --- a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/RunnerTests.cs +++ b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/RunnerTests.cs @@ -15,7 +15,7 @@ public class RunnerTests : AcceptanceTestBase private const string AssetName = "MSTestProject"; [TestMethod] - [DynamicData(nameof(GetBuildMatrixTfmBuildVerbConfiguration), typeof(AcceptanceTestBase), DynamicDataSourceType.Method)] + [DynamicData(nameof(GetBuildMatrixTfmBuildVerbConfiguration), typeof(AcceptanceTestBase))] public async SystemTask EnableMSTestRunner_True_Will_Run_Standalone(string tfm, BuildConfiguration buildConfiguration, Verb verb) { using TestAsset generator = await TestAsset.GenerateAssetAsync( @@ -44,7 +44,7 @@ public async SystemTask EnableMSTestRunner_True_Will_Run_Standalone(string tfm, } [TestMethod] - [DynamicData(nameof(GetBuildMatrixTfmBuildVerbConfiguration), typeof(AcceptanceTestBase), DynamicDataSourceType.Method)] + [DynamicData(nameof(GetBuildMatrixTfmBuildVerbConfiguration), typeof(AcceptanceTestBase))] public async SystemTask EnableMSTestRunner_True_WithCustomEntryPoint_Will_Run_Standalone(string tfm, BuildConfiguration buildConfiguration, Verb verb) { using TestAsset generator = await TestAsset.GenerateAssetAsync( @@ -78,7 +78,7 @@ await DotnetCli.RunAsync( } [TestMethod] - [DynamicData(nameof(GetBuildMatrixTfmBuildVerbConfiguration), typeof(AcceptanceTestBase), DynamicDataSourceType.Method)] + [DynamicData(nameof(GetBuildMatrixTfmBuildVerbConfiguration), typeof(AcceptanceTestBase))] public async SystemTask EnableMSTestRunner_False_Will_Run_Empty_Program_EntryPoint_From_Tpv2_SDK(string tfm, BuildConfiguration buildConfiguration, Verb verb) { using TestAsset generator = await TestAsset.GenerateAssetAsync( @@ -109,7 +109,7 @@ public async SystemTask EnableMSTestRunner_False_Will_Run_Empty_Program_EntryPoi } [TestMethod] - [DynamicData(nameof(GetBuildMatrixTfmBuildVerbConfiguration), typeof(AcceptanceTestBase), DynamicDataSourceType.Method)] + [DynamicData(nameof(GetBuildMatrixTfmBuildVerbConfiguration), typeof(AcceptanceTestBase))] public async SystemTask EnableMSTestRunner_False_Wont_Flow_TestingPlatformServer_Capability(string tfm, BuildConfiguration buildConfiguration, Verb verb) { using TestAsset generator = await TestAsset.GenerateAssetAsync( diff --git a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/RunsettingsTests.cs b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/RunsettingsTests.cs index 9944f0d74f..c2e213c7e7 100644 --- a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/RunsettingsTests.cs +++ b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/RunsettingsTests.cs @@ -54,7 +54,7 @@ public async Task UnsupportedRunSettingsEntriesAreFlagged(string tfm) } [TestMethod] - [DynamicData(nameof(LocalizationTestCases), DynamicDataSourceType.Method)] + [DynamicData(nameof(LocalizationTestCases))] public async Task UnsupportedRunSettingsEntriesAreFlagged_Localization(string? testingPlatformUILanguage, string? dotnetCLILanguage, string? vsLang, string? expectedLocale) { var testHost = TestHost.LocateFrom(AssetFixture.ProjectPath, TestAssetFixture.ProjectName, TargetFrameworks.NetCurrent); diff --git a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/SdkTests.cs b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/SdkTests.cs index 67a16ff3a1..6f1c5462ca 100644 --- a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/SdkTests.cs +++ b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/SdkTests.cs @@ -54,7 +54,7 @@ public void TestMethod1() """; [TestMethod] - [DynamicData(nameof(GetBuildMatrixMultiTfmFoldedBuildConfiguration), typeof(AcceptanceTestBase), DynamicDataSourceType.Method)] + [DynamicData(nameof(GetBuildMatrixMultiTfmFoldedBuildConfiguration), typeof(AcceptanceTestBase))] public async Task RunTests_With_VSTest(string multiTfm, BuildConfiguration buildConfiguration) { using TestAsset testAsset = await TestAsset.GenerateAssetAsync( @@ -81,7 +81,7 @@ public async Task RunTests_With_VSTest(string multiTfm, BuildConfiguration build } [TestMethod] - [DynamicData(nameof(GetBuildMatrixMultiTfmFoldedBuildConfiguration), typeof(AcceptanceTestBase), DynamicDataSourceType.Method)] + [DynamicData(nameof(GetBuildMatrixMultiTfmFoldedBuildConfiguration), typeof(AcceptanceTestBase))] public async Task RunTests_With_MSTestRunner_DotnetTest(string multiTfm, BuildConfiguration buildConfiguration) { using TestAsset testAsset = await TestAsset.GenerateAssetAsync( @@ -108,7 +108,7 @@ public async Task RunTests_With_MSTestRunner_DotnetTest(string multiTfm, BuildCo } [TestMethod] - [DynamicData(nameof(GetBuildMatrixMultiTfmFoldedBuildConfiguration), typeof(AcceptanceTestBase), DynamicDataSourceType.Method)] + [DynamicData(nameof(GetBuildMatrixMultiTfmFoldedBuildConfiguration), typeof(AcceptanceTestBase))] public async Task RunTests_With_MSTestRunner_Standalone(string multiTfm, BuildConfiguration buildConfiguration) { using TestAsset testAsset = await TestAsset.GenerateAssetAsync( @@ -129,7 +129,7 @@ public async Task RunTests_With_MSTestRunner_Standalone(string multiTfm, BuildCo } [TestMethod] - [DynamicData(nameof(GetBuildMatrixMultiTfmFoldedBuildConfiguration), typeof(AcceptanceTestBase), DynamicDataSourceType.Method)] + [DynamicData(nameof(GetBuildMatrixMultiTfmFoldedBuildConfiguration), typeof(AcceptanceTestBase))] public async Task RunTests_With_CentralPackageManagement_Standalone(string multiTfm, BuildConfiguration buildConfiguration) { using TestAsset testAsset = await TestAsset.GenerateAssetAsync( @@ -186,7 +186,7 @@ public async Task RunTests_With_CentralPackageManagement_Standalone(string multi } [TestMethod] - [DynamicData(nameof(RunTests_With_MSTestRunner_Standalone_Plus_Extensions_Data), DynamicDataSourceType.Method)] + [DynamicData(nameof(RunTests_With_MSTestRunner_Standalone_Plus_Extensions_Data))] public async Task RunTests_With_MSTestRunner_Standalone_Selectively_Enabled_Extensions(string multiTfm, BuildConfiguration buildConfiguration, string msbuildExtensionEnableFragment, string enableCommandLineArg, @@ -213,7 +213,7 @@ public async Task RunTests_With_MSTestRunner_Standalone_Selectively_Enabled_Exte } [TestMethod] - [DynamicData(nameof(GetBuildMatrixMultiTfmFoldedBuildConfiguration), typeof(AcceptanceTestBase), DynamicDataSourceType.Method)] + [DynamicData(nameof(GetBuildMatrixMultiTfmFoldedBuildConfiguration), typeof(AcceptanceTestBase))] public async Task RunTests_With_MSTestRunner_Standalone_EnableAll_Extensions(string multiTfm, BuildConfiguration buildConfiguration) { using TestAsset testAsset = await TestAsset.GenerateAssetAsync( @@ -243,7 +243,7 @@ public async Task RunTests_With_MSTestRunner_Standalone_EnableAll_Extensions(str } [TestMethod] - [DynamicData(nameof(RunTests_With_MSTestRunner_Standalone_Default_Extensions_Data), DynamicDataSourceType.Method)] + [DynamicData(nameof(RunTests_With_MSTestRunner_Standalone_Default_Extensions_Data))] public async Task RunTests_With_MSTestRunner_Standalone_Enable_Default_Extensions(string multiTfm, BuildConfiguration buildConfiguration, bool enableDefaultExtensions) { using TestAsset testAsset = await TestAsset.GenerateAssetAsync( @@ -271,7 +271,7 @@ public async Task RunTests_With_MSTestRunner_Standalone_Enable_Default_Extension } [TestMethod] - [DynamicData(nameof(GetBuildMatrixMultiTfmFoldedBuildConfiguration), typeof(AcceptanceTestBase), DynamicDataSourceType.Method)] + [DynamicData(nameof(GetBuildMatrixMultiTfmFoldedBuildConfiguration), typeof(AcceptanceTestBase))] public async Task Invalid_TestingProfile_Name_Should_Fail(string multiTfm, BuildConfiguration buildConfiguration) { using TestAsset testAsset = await TestAsset.GenerateAssetAsync( diff --git a/test/UnitTests/MSTest.Engine.UnitTests/DynamicDataTests.cs b/test/UnitTests/MSTest.Engine.UnitTests/DynamicDataTests.cs index 1fa1ce4990..7c4ba68622 100644 --- a/test/UnitTests/MSTest.Engine.UnitTests/DynamicDataTests.cs +++ b/test/UnitTests/MSTest.Engine.UnitTests/DynamicDataTests.cs @@ -21,7 +21,7 @@ public static IEnumerable IntDataProperty public void DynamicDataWithIntProperty(int expected, int actualPlus1) => Assert.AreEqual(expected, actualPlus1 - 1); - [DynamicData(nameof(IntDataProperty), DynamicDataSourceType.Property)] + [DynamicData(nameof(IntDataProperty))] [TestMethod] public void DynamicDataWithIntPropertyAndExplicitSourceType(int expected, int actualPlus1) => Assert.AreEqual(expected, actualPlus1 - 1); @@ -31,7 +31,7 @@ public void DynamicDataWithIntPropertyAndExplicitSourceType(int expected, int ac public void DynamicDataWithIntMethod(int expected, int actualPlus1) => Assert.AreEqual(expected, actualPlus1 - 1); - [DynamicData(nameof(IntDataMethod), DynamicDataSourceType.Method)] + [DynamicData(nameof(IntDataMethod))] [TestMethod] public void DynamicDataWithIntMethodAndExplicitSourceType(int expected, int actualPlus1) => Assert.AreEqual(expected, actualPlus1 - 1); @@ -48,7 +48,7 @@ public static IEnumerable IntDataMethod() public void DynamicDataWithIntPropertyOnSeparateClass(int expected, int actualPlus2) => Assert.AreEqual(expected, actualPlus2 - 2); - [DynamicData(nameof(IntDataMethod), typeof(DataClass), DynamicDataSourceType.Method)] + [DynamicData(nameof(IntDataMethod), typeof(DataClass))] [TestMethod] public void DynamicDataWithIntMethodOnSeparateClass(int expected, int actualPlus2) => Assert.AreEqual(expected, actualPlus2 - 2); @@ -66,7 +66,7 @@ public static IEnumerable UserDataProperty [new User("Marco"), new User("Pavel")] ]; - [DynamicData(nameof(UserDataMethod), DynamicDataSourceType.Method)] + [DynamicData(nameof(UserDataMethod))] [TestMethod] public void DynamicDataWithUserMethod(User _, User _2) { From 4c60f8cd36af08999470984f86a80663e2379c17 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Fri, 1 Aug 2025 12:52:32 +0200 Subject: [PATCH 350/541] Don't return null types from AssemblyEnumerator when ReflectionTypeLoadException is encountered (#6276) --- .../Discovery/AssemblyEnumerator.cs | 10 ++++----- .../Execution/TypeCache.cs | 21 ++++++++++++------- .../TestDiscoveryWarningsTests.cs | 2 +- .../Discovery/AssemblyEnumeratorTests.cs | 2 +- 4 files changed, 20 insertions(+), 15 deletions(-) diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Discovery/AssemblyEnumerator.cs b/src/Adapter/MSTestAdapter.PlatformServices/Discovery/AssemblyEnumerator.cs index 7ea3298836..c11031c378 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Discovery/AssemblyEnumerator.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Discovery/AssemblyEnumerator.cs @@ -106,11 +106,6 @@ internal AssemblyEnumerationResult EnumerateAssembly(string assemblyFileName) foreach (Type type in types) { - if (type == null) - { - continue; - } - List testsInType = DiscoverTestsInType(assemblyFileName, type, warnings, discoverInternals, dataSourcesUnfoldingStrategy, testIdGenerationStrategy, fixturesTests); tests.AddRange(testsInType); @@ -150,7 +145,10 @@ internal static Type[] GetTypes(Assembly assembly, string assemblyFileName, ICol } } - return ex.Types!; + // We already logged a warning or error. + // So don't return types that failed to load. + // The intent of the catch is to gracefully run the types that we could load. + return ex.Types is null ? [] : [.. ex.Types.Where(t => t is not null)!]; } } diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Execution/TypeCache.cs b/src/Adapter/MSTestAdapter.PlatformServices/Execution/TypeCache.cs index e775efc7c6..b6ff25d055 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Execution/TypeCache.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Execution/TypeCache.cs @@ -421,18 +421,25 @@ private TestAssemblyInfo GetAssemblyInfo(Assembly assembly) assemblyInfo.AssemblyCleanupMethodTimeoutMilliseconds = @this.TryGetTimeoutInfo(methodInfo, FixtureKind.AssemblyCleanup); } - if (methodInfo is { IsPublic: true, IsStatic: true, IsGenericMethod: false, DeclaringType.IsGenericType: false, DeclaringType.IsPublic: true } && - methodInfo.GetParameters() is { } parameters && parameters.Length == 1 && parameters[0].ParameterType == typeof(TestContext) && - methodInfo.IsValidReturnType()) + bool isGlobalTestInitialize = @this._reflectionHelper.IsAttributeDefined(methodInfo, inherit: true); + bool isGlobalTestCleanup = @this._reflectionHelper.IsAttributeDefined(methodInfo, inherit: true); + + if (isGlobalTestInitialize || isGlobalTestCleanup) { - bool isGlobalTestInitialize = @this._reflectionHelper.IsAttributeDefined(methodInfo, inherit: true); - bool isGlobalTestCleanup = @this._reflectionHelper.IsAttributeDefined(methodInfo, inherit: true); - if (isGlobalTestInitialize) + // Only try to validate the method if it already has the needed attribute. + // This avoids potential type load exceptions when the return type cannot be resolved. + // NOTE: Users tend to load assemblies in AssemblyInitialize after finishing the discovery. + // We want to avoid loading types early as much as we can. + bool isValid = methodInfo is { IsSpecialName: false, IsPublic: true, IsStatic: true, IsGenericMethod: false, DeclaringType.IsGenericType: false, DeclaringType.IsPublic: true } && + methodInfo.GetParameters() is { } parameters && parameters.Length == 1 && parameters[0].ParameterType == typeof(TestContext) && + methodInfo.IsValidReturnType(); + + if (isValid && isGlobalTestInitialize) { assemblyInfo.GlobalTestInitializations.Add((methodInfo, @this.TryGetTimeoutInfo(methodInfo, FixtureKind.TestInitialize))); } - if (isGlobalTestCleanup) + if (isValid && isGlobalTestCleanup) { assemblyInfo.GlobalTestCleanups.Add((methodInfo, @this.TryGetTimeoutInfo(methodInfo, FixtureKind.TestCleanup))); } diff --git a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/TestDiscoveryWarningsTests.cs b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/TestDiscoveryWarningsTests.cs index 73fe85121c..2ba0913283 100644 --- a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/TestDiscoveryWarningsTests.cs +++ b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/TestDiscoveryWarningsTests.cs @@ -35,7 +35,7 @@ public async Task DiscoverTests_ShowsWarningsForTestsThatFailedToDiscover(string TestHostResult testHostResult = await testHost.ExecuteAsync("--list-tests"); - testHostResult.AssertExitCodeIsNot(ExitCodes.Success); + testHostResult.AssertExitCodeIs(ExitCodes.Success); testHostResult.AssertOutputContains("System.IO.FileNotFoundException: Could not load file or assembly 'TestDiscoveryWarningsBaseClass"); } diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Discovery/AssemblyEnumeratorTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Discovery/AssemblyEnumeratorTests.cs index 86b380a3f5..6e72cae9df 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Discovery/AssemblyEnumeratorTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Discovery/AssemblyEnumeratorTests.cs @@ -120,7 +120,7 @@ public void GetTypesShouldReturnReflectionTypeLoadExceptionTypesOnException() Type[] types = AssemblyEnumerator.GetTypes(mockAssembly.Object, string.Empty, _warnings); Verify(types is not null); - Verify(reflectedTypes.Equals(types)); + Verify(reflectedTypes.SequenceEqual(types)); } public void GetTypesShouldLogWarningsWhenReflectionFailsWithLoaderExceptions() From 600770acd9a218f443c83eff9ebe6aff16b9761b Mon Sep 17 00:00:00 2001 From: dotnet bot Date: Fri, 1 Aug 2025 04:08:21 -0700 Subject: [PATCH 351/541] Localized file check-in by OneLocBuild Task: Build definition ID 1218: Build ID 2762622 --- src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf | 6 +++--- src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf | 6 +++--- src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf | 10 +++++----- src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf | 4 ++-- .../MSTest.Analyzers/xlf/Resources.zh-Hans.xlf | 4 ++-- 5 files changed, 15 insertions(+), 15 deletions(-) diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf index e2705d9d8f..9220288210 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf @@ -966,17 +966,17 @@ El tipo que declara estos métodos también debe respetar las reglas siguientes: Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws. - Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws. + Los métodos Assert.Throws solo deben contener una sola instrucción o expresión. Varias instrucciones pueden ser engañosas: si se lanza la primera instrucción, las instrucciones posteriores nunca se ejecutan; si no se lanza, se debe mover fuera de Assert.Throws. Assert.Throws should contain only a single statement/expression - Assert.Throws should contain only a single statement/expression + Assert.Throws debe contener solo una única instrucción o expresión Assert.Throws should contain only a single statement/expression - Assert.Throws should contain only a single statement/expression + Assert.Throws debe contener solo una única instrucción o expresión diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf index 27c9a4cb31..40319aee2a 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf @@ -966,17 +966,17 @@ Le type doit être une classe Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws. - Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws. + Les méthodes Assert.Throws ne doivent contenir qu’une seule instruction ou expression. Plusieurs instructions peuvent prêter à confusion : si la première instruction lève une exception, les instructions suivantes ne sont jamais exécutées ; si elle ne lève pas d'exception, elle doit être déplacée en dehors de Assert.Throws. Assert.Throws should contain only a single statement/expression - Assert.Throws should contain only a single statement/expression + Assert.Throws ne doit contenir qu’une seule instruction Assert.Throws should contain only a single statement/expression - Assert.Throws should contain only a single statement/expression + Assert.Throws ne doit contenir qu’une seule instruction diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf index 90a47991c0..bff683bf94 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf @@ -419,7 +419,7 @@ The type declaring these methods should also respect the following rules: '[DynamicData]' member '{0}.{1}' is a field so you should use 'DynamicDataSourceType.AutoDetect' or 'DynamicDataSourceType.Field' (auto detect is the default when not specified explicitly, and is recommended) - '[DynamicData]' member '{0}.{1}' is a field so you should use 'DynamicDataSourceType.AutoDetect' or 'DynamicDataSourceType.Field' (auto detect is the default when not specified explicitly, and is recommended) + '[DynamicData]' のメンバー '{0}.{1}' はフィールドであるため、'DynamicDataSourceType.AutoDetect' または 'DynamicDataSourceType.Field' を使用する必要があります (明示的に指定しない場合は既定で自動検出され、これが推奨されます) @@ -429,7 +429,7 @@ The type declaring these methods should also respect the following rules: '[DynamicData]' member '{0}.{1}' is not a property, method, or field. Only properties, methods, and fields are supported. - '[DynamicData]' member '{0}.{1}' is not a property, method, or field. Only properties, methods, and fields are supported. + '[DynamicData]' のメンバー '{0}.{1}' は、プロパティ、メソッド、フィールドではありません。サポートされているのは、プロパティ、メソッド、フィールドのみです。 @@ -966,17 +966,17 @@ The type declaring these methods should also respect the following rules: Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws. - Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws. + Assert.Throws メソッドには 1 つのステートメントまたは式のみを含める必要があります。複数のステートメントは誤解を招く可能性があります。最初のステートメントがスローされた場合、後続のステートメントは実行されません。スローされない場合は、Assert.Throws の外部に移動する必要があります。 Assert.Throws should contain only a single statement/expression - Assert.Throws should contain only a single statement/expression + Assert.Throws には 1 つのステートメントまたは式のみを含める必要があります Assert.Throws should contain only a single statement/expression - Assert.Throws should contain only a single statement/expression + Assert.Throws には 1 つのステートメントまたは式のみを含める必要があります diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf index 002b455ed8..90f2cfbac5 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf @@ -419,7 +419,7 @@ The type declaring these methods should also respect the following rules: '[DynamicData]' member '{0}.{1}' is a field so you should use 'DynamicDataSourceType.AutoDetect' or 'DynamicDataSourceType.Field' (auto detect is the default when not specified explicitly, and is recommended) - '[DynamicData]' member '{0}.{1}' is a field so you should use 'DynamicDataSourceType.AutoDetect' or 'DynamicDataSourceType.Field' (auto detect is the default when not specified explicitly, and is recommended) + '[DynamicData]' 구성원 '{0}.{1}'은(는) 필드이므로 'DynamicDataSourceType.AutoDetect' 또는 'DynamicDataSourceType.Field'를 사용해야 합니다(명시적으로 지정하지 않은 경우 자동 검색이 기본값이며 권장됨). @@ -429,7 +429,7 @@ The type declaring these methods should also respect the following rules: '[DynamicData]' member '{0}.{1}' is not a property, method, or field. Only properties, methods, and fields are supported. - '[DynamicData]' member '{0}.{1}' is not a property, method, or field. Only properties, methods, and fields are supported. + '[DynamicData]' 구성원 '{0}.{1}'은(는) 속성, 메서드 또는 필드가 아닙니다. 속성, 메서드 및 필드만 지원됩니다. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf index f80fea53ae..68dac3ed37 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf @@ -419,7 +419,7 @@ The type declaring these methods should also respect the following rules: '[DynamicData]' member '{0}.{1}' is a field so you should use 'DynamicDataSourceType.AutoDetect' or 'DynamicDataSourceType.Field' (auto detect is the default when not specified explicitly, and is recommended) - '[DynamicData]' member '{0}.{1}' is a field so you should use 'DynamicDataSourceType.AutoDetect' or 'DynamicDataSourceType.Field' (auto detect is the default when not specified explicitly, and is recommended) + "[DynamicData]" 成员“{0}.{1}”是字段,因此应使用 "DynamicDataSourceType.AutoDetect" 或 "DynamicDataSourceType.Field" (未显式指定时,默认为自动检测,建议使用此设置) @@ -429,7 +429,7 @@ The type declaring these methods should also respect the following rules: '[DynamicData]' member '{0}.{1}' is not a property, method, or field. Only properties, methods, and fields are supported. - '[DynamicData]' member '{0}.{1}' is not a property, method, or field. Only properties, methods, and fields are supported. + "[DynamicData]" 成员“{0}.{1}”不是属性、方法或字段。仅支持属性、方法和字段。 From efc3457dc1c25ff32b9a682eb15f2d5de30b1aa0 Mon Sep 17 00:00:00 2001 From: dotnet bot Date: Fri, 1 Aug 2025 04:12:45 -0700 Subject: [PATCH 352/541] Localized file check-in by OneLocBuild Task: Build definition ID 1218: Build ID 2762622 --- .../TestFramework/Resources/xlf/FrameworkMessages.ja.xlf | 4 ++-- .../TestFramework/Resources/xlf/FrameworkMessages.ko.xlf | 4 ++-- .../TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ja.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ja.xlf index f01e9d6e10..2fe1bb318f 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ja.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ja.xlf @@ -129,7 +129,7 @@ Dynamic data field '{0}' should be static. - Dynamic data field '{0}' should be static. + 動的データ フィールド '{0}' は静的である必要があります。 @@ -144,7 +144,7 @@ The dynamic data source '{0}' in type '{1}' should exist and be a property, a method, or a field. - The dynamic data source '{0}' in type '{1}' should exist and be a property, a method, or a field. + 型 '{1}' の動的データ ソース '{0}' が、プロパティ、メソッド、またはフィールドとして存在している必要があります。 diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ko.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ko.xlf index c215074879..664eecc5b0 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ko.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ko.xlf @@ -129,7 +129,7 @@ Dynamic data field '{0}' should be static. - Dynamic data field '{0}' should be static. + 동적 데이터 필드 '{0}'은(는) 정적이어야 합니다. @@ -144,7 +144,7 @@ The dynamic data source '{0}' in type '{1}' should exist and be a property, a method, or a field. - The dynamic data source '{0}' in type '{1}' should exist and be a property, a method, or a field. + 형식 '{1}'의 동적 데이터 원본 '{0}'은(는) 속성, 메서드 또는 필드로 존재해야 합니다. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf index 4f8f4ba639..73117c0eb8 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf @@ -129,7 +129,7 @@ Dynamic data field '{0}' should be static. - Dynamic data field '{0}' should be static. + 动态数据字段“{0}”应该是静态的。 @@ -144,7 +144,7 @@ The dynamic data source '{0}' in type '{1}' should exist and be a property, a method, or a field. - The dynamic data source '{0}' in type '{1}' should exist and be a property, a method, or a field. + 类型“{1}”中的动态数据源“{0}”应该存在,并且应为属性、方法或字段。 From 9be2b5589c1adde04a72ee7860712da943af2c26 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Jare=C5=A1?= Date: Fri, 1 Aug 2025 14:16:02 +0200 Subject: [PATCH 353/541] Update copilot-instructions.md (#6280) --- .github/copilot-instructions.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index 0ca019af93..8910537ae2 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -34,3 +34,9 @@ Anytime you add a new localization resource, you MUST: - Tests for MTP and MSTest analyzers MUST use MSTest. - Unit tests for MSTest MUST use the internal test framework defined in [`TestFramework.ForTestingMSTest`](../test/Utilities/TestFramework.ForTestingMSTest). - All assertions must be written using FluentAssertions style of assertion. + +## Pull Request guidelines + +- Let other developers discuss their comments to your PRs, unless something sounds like a direct order to you, don't do changes. +- Do the changes when you are specifically tagged or mentioned as copilot. +- If you are unsure comment with the temperature and sentiment of the comment, so we know how to efficiently address you as a member of the team rather than having to tag you. From e85342442c74718bdf0183812aecb411ea27aa4d Mon Sep 17 00:00:00 2001 From: Copilot <198982749+Copilot@users.noreply.github.com> Date: Fri, 1 Aug 2025 14:24:06 +0000 Subject: [PATCH 354/541] Enhance Assert.AreEqual string comparison to show first difference with index and context (#6163) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: Evangelink <11340282+Evangelink@users.noreply.github.com> Co-authored-by: Amaury Levé --- Build.cmd | 0 .../Execution/TestMethodRunner.cs | 1 - .../Execution/UnitTestRunner.cs | 1 - .../Extensions/MethodInfoExtensions.cs | 1 - .../Assertions/Assert.AreEqual.cs | 247 +++++++++++++++++- .../TestFramework/Internal/Class1.cs | 8 + .../Resources/FrameworkMessages.resx | 18 ++ .../Resources/xlf/FrameworkMessages.cs.xlf | 31 +++ .../Resources/xlf/FrameworkMessages.de.xlf | 31 +++ .../Resources/xlf/FrameworkMessages.es.xlf | 31 +++ .../Resources/xlf/FrameworkMessages.fr.xlf | 31 +++ .../Resources/xlf/FrameworkMessages.it.xlf | 31 +++ .../Resources/xlf/FrameworkMessages.ja.xlf | 31 +++ .../Resources/xlf/FrameworkMessages.ko.xlf | 31 +++ .../Resources/xlf/FrameworkMessages.pl.xlf | 31 +++ .../Resources/xlf/FrameworkMessages.pt-BR.xlf | 31 +++ .../Resources/xlf/FrameworkMessages.ru.xlf | 31 +++ .../Resources/xlf/FrameworkMessages.tr.xlf | 31 +++ .../xlf/FrameworkMessages.zh-Hans.xlf | 31 +++ .../xlf/FrameworkMessages.zh-Hant.xlf | 31 +++ .../Assertions/AssertTests.AreEqualTests.cs | 215 +++++++++++++++ 21 files changed, 877 insertions(+), 17 deletions(-) mode change 100644 => 100755 Build.cmd create mode 100644 src/TestFramework/TestFramework/Internal/Class1.cs diff --git a/Build.cmd b/Build.cmd old mode 100644 new mode 100755 diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestMethodRunner.cs b/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestMethodRunner.cs index 443e2443c7..de0d83bb16 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestMethodRunner.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestMethodRunner.cs @@ -5,7 +5,6 @@ using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Helpers; using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel; -using Microsoft.VisualStudio.TestPlatform.MSTestAdapter; using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Extensions; using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Interface; diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Execution/UnitTestRunner.cs b/src/Adapter/MSTestAdapter.PlatformServices/Execution/UnitTestRunner.cs index 0afe682950..0934c7792a 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Execution/UnitTestRunner.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Execution/UnitTestRunner.cs @@ -6,7 +6,6 @@ using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Extensions; using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Helpers; using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel; -using Microsoft.VisualStudio.TestPlatform.MSTestAdapter; using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Extensions; using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Interface; diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Extensions/MethodInfoExtensions.cs b/src/Adapter/MSTestAdapter.PlatformServices/Extensions/MethodInfoExtensions.cs index 3511b19253..a3b2d99372 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Extensions/MethodInfoExtensions.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Extensions/MethodInfoExtensions.cs @@ -3,7 +3,6 @@ using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Helpers; using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel; -using Microsoft.VisualStudio.TestPlatform.MSTestAdapter; using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Extensions; using Microsoft.VisualStudio.TestTools.UnitTesting; diff --git a/src/TestFramework/TestFramework/Assertions/Assert.AreEqual.cs b/src/TestFramework/TestFramework/Assertions/Assert.AreEqual.cs index 930ddb4504..637039dd8e 100644 --- a/src/TestFramework/TestFramework/Assertions/Assert.AreEqual.cs +++ b/src/TestFramework/TestFramework/Assertions/Assert.AreEqual.cs @@ -694,6 +694,104 @@ private static bool AreEqualFailing(decimal expected, decimal actual, decimal de private static bool AreEqualFailing(long expected, long actual, long delta) => Math.Abs(expected - actual) > delta; + private static string FormatStringComparisonMessage(string? expected, string? actual, string userMessage) + { + // Handle null cases + if (expected is null && actual is null) + { + return string.Format( + CultureInfo.CurrentCulture, + FrameworkMessages.AreEqualFailMsg, + userMessage, + ReplaceNulls(expected), + ReplaceNulls(actual)); + } + + if (expected is null || actual is null) + { + return string.Format( + CultureInfo.CurrentCulture, + FrameworkMessages.AreEqualFailMsg, + userMessage, + ReplaceNulls(expected), + ReplaceNulls(actual)); + } + + // Find the first difference + int diffIndex = FindFirstStringDifference(expected, actual); + + if (diffIndex == -1) + { + // Strings are equal - should not happen in practice, we call this method only when they are not equal. + ApplicationStateGuard.Unreachable(); + } + + // Format the enhanced string comparison message + return FormatStringDifferenceMessage(expected, actual, diffIndex, userMessage); + } + + private static int FindFirstStringDifference(string expected, string actual) + { + int minLength = Math.Min(expected.Length, actual.Length); + + for (int i = 0; i < minLength; i++) + { + if (expected[i] != actual[i]) + { + return i; + } + } + + // If we reach here, one string is a prefix of the other + return expected.Length != actual.Length ? minLength : -1; + } + + private static string FormatStringDifferenceMessage(string expected, string actual, int diffIndex, string userMessage) + { + string lengthInfo = expected.Length == actual.Length + ? string.Format(CultureInfo.CurrentCulture, FrameworkMessages.AreEqualStringDiffLengthBothMsg, expected.Length, diffIndex) + : string.Format(CultureInfo.CurrentCulture, FrameworkMessages.AreEqualStringDiffLengthDifferentMsg, expected.Length, actual.Length); + + // Create contextual preview around the difference + const int contextLength = 41; // Show up to 20 characters of context on each side + Tuple tuple = StringPreviewHelper.CreateStringPreviews(expected, actual, diffIndex, contextLength); + string expectedPreview = tuple.Item1; + string actualPreview = tuple.Item2; + int caretPosition = tuple.Item3; + + // Get localized prefixes + string expectedPrefix = FrameworkMessages.AreEqualStringDiffExpectedPrefix; + string actualPrefix = FrameworkMessages.AreEqualStringDiffActualPrefix; + + // Calculate the maximum prefix length to align the caret properly + int maxPrefixLength = Math.Max(expectedPrefix.Length, actualPrefix.Length); + + // Pad shorter prefix to match the longer one for proper alignment + string paddedExpectedPrefix = expectedPrefix.PadRight(maxPrefixLength); + string paddedActualPrefix = actualPrefix.PadRight(maxPrefixLength); + + // Build the formatted lines with proper alignment + string expectedLine = paddedExpectedPrefix + $"\"{expectedPreview}\""; + string actualLine = paddedActualPrefix + $"\"{actualPreview}\""; + + // The caret should align under the difference in the string content + // For localized prefixes with different lengths, we need to account for the longer prefix + // to ensure proper alignment. But the caret position is relative to the string content. + int adjustedCaretPosition = maxPrefixLength + 1 + caretPosition; // +1 for the opening quote + + // Format user message properly - add leading space if not empty, otherwise no extra formatting + string formattedUserMessage = string.IsNullOrEmpty(userMessage) ? string.Empty : $" {userMessage}"; + + return string.Format( + CultureInfo.CurrentCulture, + FrameworkMessages.AreEqualStringDiffFailMsg, + lengthInfo, + formattedUserMessage, + expectedLine, + actualLine, + new string('-', adjustedCaretPosition) + "^"); + } + [DoesNotReturn] private static void ThrowAssertAreEqualFailed(object? expected, object? actual, string userMessage) { @@ -706,12 +804,14 @@ private static void ThrowAssertAreEqualFailed(object? expected, object? actual, expected.GetType().FullName, ReplaceNulls(actual), actual.GetType().FullName) - : string.Format( - CultureInfo.CurrentCulture, - FrameworkMessages.AreEqualFailMsg, - userMessage, - ReplaceNulls(expected), - ReplaceNulls(actual)); + : expected is string expectedString && actual is string actualString + ? FormatStringComparisonMessage(expectedString, actualString, userMessage) + : string.Format( + CultureInfo.CurrentCulture, + FrameworkMessages.AreEqualFailMsg, + userMessage, + ReplaceNulls(expected), + ReplaceNulls(actual)); ThrowAssertFailed("Assert.AreEqual", finalMessage); } @@ -732,20 +832,23 @@ private static void ThrowAssertAreEqualFailed(T expected, T actual, T delta, [DoesNotReturn] private static void ThrowAssertAreEqualFailed(string? expected, string? actual, bool ignoreCase, CultureInfo culture, string userMessage) { + string finalMessage; + // If the user requested to match case, and the difference between expected/actual is casing only, then we use a different message. - string finalMessage = !ignoreCase && CompareInternal(expected, actual, ignoreCase: true, culture) == 0 - ? string.Format( + if (!ignoreCase && CompareInternal(expected, actual, ignoreCase: true, culture) == 0) + { + finalMessage = string.Format( CultureInfo.CurrentCulture, FrameworkMessages.AreEqualCaseFailMsg, userMessage, ReplaceNulls(expected), - ReplaceNulls(actual)) - : string.Format( - CultureInfo.CurrentCulture, - FrameworkMessages.AreEqualFailMsg, - userMessage, - ReplaceNulls(expected), ReplaceNulls(actual)); + } + else + { + // Use enhanced string comparison for string-specific failures + finalMessage = FormatStringComparisonMessage(expected, actual, userMessage); + } ThrowAssertFailed("Assert.AreEqual", finalMessage); } @@ -2118,3 +2221,119 @@ private static void ThrowAssertAreNotEqualFailed(object? notExpected, object? ac ThrowAssertFailed("Assert.AreNotEqual", finalMessage); } } + +internal static class StringPreviewHelper +{ + public static Tuple CreateStringPreviews(string expected, string actual, int diffIndex, int fullPreviewLength) + { + int ellipsisLength = 3; // Length of the ellipsis "..." + + if (fullPreviewLength % 2 == 0) + { + // Being odd makes it easier to calculate the context length, and center the marker, this is not user customizable. + throw new ArgumentException($"{nameof(fullPreviewLength)} must be odd, but it was even."); + } + + // This is arbitrary number that is 2 times the size of the ellipsis, + // plus 3 chars to make it easier to check the tests are correct when part of string is masked. + // Preview length is not user customizable, just makes it harder to break the tests, and avoids few ifs we would need to write otherwise. + if (fullPreviewLength < 9) + { + throw new ArgumentException($"{nameof(fullPreviewLength)} cannot be shorter than 9."); + } + + // In case we want to instead count runes or text elements we can change it just here. + int expectedLength = expected.Length; + int actualLength = actual.Length; + + if (diffIndex < 0 || diffIndex > Math.Min(expectedLength, actualLength)) // Not -1 here because the difference can be right after the end of the shorter string. + { + throw new ArgumentOutOfRangeException(nameof(diffIndex), "diffIndex must be within the bounds of both strings."); + } + + int contextLength = (fullPreviewLength - 1) / 2; + + // Diff index must point into the string, the start of the strings will always be shortened the same amount, + // because otherwise the diff would happen at the beginning of the string. + // So we just care about how far we are from the end of the string, so we can show the maximum amount of info to the user + // when diff is really close to the end. + string shorterString = expectedLength < actualLength ? expected : actual; + string longerString = expectedLength < actualLength ? actual : expected; + bool expectedIsShorter = expectedLength < actualLength; + + int shorterStringLength = shorterString.Length; + int longerStringLength = longerString.Length; + + // End marker will point to the end of the shorter string, but the end of the longer string will be replaced by ... + // make sure we don't point at the dots. To do this we need to make sure the strings are cut at the beginning, rather than preferring the maximum context shown. + bool markerPointsAtEllipsis = longerStringLength - shorterStringLength > ellipsisLength && shorterStringLength - diffIndex < ellipsisLength; + int ellipsisSpaceOrZero = markerPointsAtEllipsis ? ellipsisLength + 2 : 0; + + // Find the end of the string that we will show, either then end of the shorter string, or the end of the preview window. + // Then calculate the start of the preview from that. This makes sure that if diff is close end of the string we show as much as we can. + int start = Math.Min(diffIndex + contextLength, shorterStringLength) - fullPreviewLength + ellipsisSpaceOrZero; + + // If the string is shorter than the preview, start cutting from 0, otherwise start cutting from the calculated start. + int cutStart = Math.Max(0, start); + // From here we need to handle longer and shorter string separately, because one of the can be shorter, + // and we want to show the maximum we can that fits in thew preview window. + int cutEndShort = Math.Min(cutStart + fullPreviewLength, shorterStringLength); + int cutEndLong = Math.Min(cutStart + fullPreviewLength, longerStringLength); + + string shorterStringPreview = shorterString.Substring(cutStart, cutEndShort - cutStart); + string longerStringPreview = longerString.Substring(cutStart, cutEndLong - cutStart); + + // We cut something from the start of the string, so we need to add ellipsis there. + // We know if one string is cut then both must be cut, otherwise the diff would be at the beginning of the string. + if (cutStart > 0) + { + shorterStringPreview = EllipsisStart(shorterStringPreview); + longerStringPreview = EllipsisStart(longerStringPreview); + } + + // We cut something from the end of the string, so we need to add ellipsis there. + // We don't know if both strings are cut, so we need to check them separately. + if (cutEndShort < shorterStringLength) + { + shorterStringPreview = EllipsisEnd(shorterStringPreview); + } + + // We cut something from the end of the string, so we need to add ellipsis there. + if (cutEndLong < longerStringLength) + { + longerStringPreview = EllipsisEnd(longerStringPreview); + } + + string escapedShorterStringPreview = MakeControlCharactersVisible(shorterStringPreview); + string escapedLongerStringPreview = MakeControlCharactersVisible(longerStringPreview); + + return new Tuple( + expectedIsShorter ? escapedShorterStringPreview : escapedLongerStringPreview, + expectedIsShorter ? escapedLongerStringPreview : escapedShorterStringPreview, + diffIndex - cutStart); + } + + private static string EllipsisEnd(string text) + => $"{text.Substring(0, text.Length - 3)}..."; + + private static string EllipsisStart(string text) + => $"...{text.Substring(3)}"; + + private static string MakeControlCharactersVisible(string text) + { + var stringBuilder = new StringBuilder(text.Length); + foreach (char ch in text) + { + if (char.IsControl(ch)) + { + stringBuilder.Append((char)(0x2400 + ch)); + } + else + { + stringBuilder.Append(ch); + } + } + + return stringBuilder.ToString(); + } +} diff --git a/src/TestFramework/TestFramework/Internal/Class1.cs b/src/TestFramework/TestFramework/Internal/Class1.cs new file mode 100644 index 0000000000..b879e79499 --- /dev/null +++ b/src/TestFramework/TestFramework/Internal/Class1.cs @@ -0,0 +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. + +internal static class ApplicationStateGuard +{ + public static UnreachableException Unreachable([CallerFilePath] string? path = null, [CallerLineNumber] int line = 0) + => new($"This program location is thought to be unreachable. File='{path}' Line={line}"); +} diff --git a/src/TestFramework/TestFramework/Resources/FrameworkMessages.resx b/src/TestFramework/TestFramework/Resources/FrameworkMessages.resx index d52e623343..6a559ed4a7 100644 --- a/src/TestFramework/TestFramework/Resources/FrameworkMessages.resx +++ b/src/TestFramework/TestFramework/Resources/FrameworkMessages.resx @@ -138,6 +138,24 @@ Expected:<{1} ({2})>. Actual:<{3} ({4})>. {0} + + {0}{1} +{2} +{3} +{4} + + + Expected: + + + But was: + + + String lengths are both {0} but differ at index {1}. + + + Expected string length {0} but was {1}. + Expected any value except:<{1}>. Actual:<{2}>. {0} diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.cs.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.cs.xlf index bd9ab254e9..07a88dd5c4 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.cs.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.cs.xlf @@ -37,6 +37,37 @@ Očekáváno:<{1} ({2})>. Aktuálně:<{3} ({4})>. {0} + + {0}{1} +{2} +{3} +{4} + {0}{1} +{2} +{3} +{4} + + + + Expected: + Očekáváno: + + + + But was: + Ale bylo: + + + + String lengths are both {0} but differ at index {1}. + String lengths are both {0} but differ at index {1}. + + + + Expected string length {0} but was {1}. + Expected string length {0} but was {1}. + + Expected any value except:<{1}>. Actual:<{2}>. {0} Nebyla očekávána žádná hodnota kromě:<{1}>. Aktuálně:<{2}>. {0} diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.de.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.de.xlf index c2cac59253..7700ea600e 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.de.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.de.xlf @@ -37,6 +37,37 @@ Erwartet:<{1} ({2})>. Tatsächlich:<{3} ({4})>. {0} + + {0}{1} +{2} +{3} +{4} + {0}{1} +{2} +{3} +{4} + + + + Expected: + Erwartet: + + + + But was: + Aber war: + + + + String lengths are both {0} but differ at index {1}. + String lengths are both {0} but differ at index {1}. + + + + Expected string length {0} but was {1}. + Expected string length {0} but was {1}. + + Expected any value except:<{1}>. Actual:<{2}>. {0} Es wurde ein beliebiger Wert erwartet außer:<{1}>. Tatsächlich:<{2}>. {0} diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.es.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.es.xlf index 0df98f32df..b5599da4b5 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.es.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.es.xlf @@ -37,6 +37,37 @@ Se esperaba:<{1} ({2})>, pero es:<{3} ({4})>. {0} + + {0}{1} +{2} +{3} +{4} + {0}{1} +{2} +{3} +{4} + + + + Expected: + Esperado: + + + + But was: + Pero fue: + + + + String lengths are both {0} but differ at index {1}. + String lengths are both {0} but differ at index {1}. + + + + Expected string length {0} but was {1}. + Expected string length {0} but was {1}. + + Expected any value except:<{1}>. Actual:<{2}>. {0} Se esperaba cualquier valor excepto <{1}>, pero es <{2}>. {0} diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.fr.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.fr.xlf index 0709bd08e2..57ccd98815 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.fr.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.fr.xlf @@ -37,6 +37,37 @@ Attendu : <{1} ({2})>, Réel : <{3} ({4})>. {0} + + {0}{1} +{2} +{3} +{4} + {0}{1} +{2} +{3} +{4} + + + + Expected: + Attendu : + + + + But was: + Mais était : + + + + String lengths are both {0} but differ at index {1}. + String lengths are both {0} but differ at index {1}. + + + + Expected string length {0} but was {1}. + Expected string length {0} but was {1}. + + Expected any value except:<{1}>. Actual:<{2}>. {0} Toute valeur attendue sauf :<{1}>. Réel :<{2}>. {0} diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.it.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.it.xlf index 0f9f091b46..7a051c0fbe 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.it.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.it.xlf @@ -37,6 +37,37 @@ Previsto:<{1} ({2})>. Effettivo:<{3} ({4})>. {0} + + {0}{1} +{2} +{3} +{4} + {0}{1} +{2} +{3} +{4} + + + + Expected: + Previsto: + + + + But was: + Ma era: + + + + String lengths are both {0} but differ at index {1}. + String lengths are both {0} but differ at index {1}. + + + + Expected string length {0} but was {1}. + Expected string length {0} but was {1}. + + Expected any value except:<{1}>. Actual:<{2}>. {0} Previsto qualsiasi valore tranne:<{1}>. Effettivo:<{2}>. {0} diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ja.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ja.xlf index 2fe1bb318f..a0940d414c 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ja.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ja.xlf @@ -37,6 +37,37 @@ <{1} ({2})> が必要ですが、<{3} ({4})> が指定されました。{0} + + {0}{1} +{2} +{3} +{4} + {0}{1} +{2} +{3} +{4} + + + + Expected: + 期待値: + + + + But was: + しかし実際: + + + + String lengths are both {0} but differ at index {1}. + String lengths are both {0} but differ at index {1}. + + + + Expected string length {0} but was {1}. + Expected string length {0} but was {1}. + + Expected any value except:<{1}>. Actual:<{2}>. {0} <{1}> 以外の任意の値が必要ですが、<{2}> が指定されています。{0} diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ko.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ko.xlf index 664eecc5b0..2f621daf6a 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ko.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ko.xlf @@ -37,6 +37,37 @@ 예상 값: <{1} ({2})>. 실제 값: <{3} ({4})>. {0} + + {0}{1} +{2} +{3} +{4} + {0}{1} +{2} +{3} +{4} + + + + Expected: + 기대값: + + + + But was: + 하지만 실제: + + + + String lengths are both {0} but differ at index {1}. + String lengths are both {0} but differ at index {1}. + + + + Expected string length {0} but was {1}. + Expected string length {0} but was {1}. + + Expected any value except:<{1}>. Actual:<{2}>. {0} 예상 값: <{1}>을(를) 제외한 모든 값. 실제 값: <{2}>. {0} diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pl.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pl.xlf index ba23236751..a63517f7f1 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pl.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pl.xlf @@ -37,6 +37,37 @@ Oczekiwana:<{1} ({2})>. Rzeczywista:<{3} ({4})>. {0} + + {0}{1} +{2} +{3} +{4} + {0}{1} +{2} +{3} +{4} + + + + Expected: + Oczekiwano: + + + + But was: + Ale było: + + + + String lengths are both {0} but differ at index {1}. + String lengths are both {0} but differ at index {1}. + + + + Expected string length {0} but was {1}. + Expected string length {0} but was {1}. + + Expected any value except:<{1}>. Actual:<{2}>. {0} Oczekiwano dowolnej wartości za wyjątkiem:<{1}>. Rzeczywista:<{2}>. {0} diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf index c23f2d592c..51321e6921 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf @@ -37,6 +37,37 @@ Esperado:<{1} ({2})>. Real:<{3} ({4})>. {0} + + {0}{1} +{2} +{3} +{4} + {0}{1} +{2} +{3} +{4} + + + + Expected: + Esperado: + + + + But was: + Mas foi: + + + + String lengths are both {0} but differ at index {1}. + String lengths are both {0} but differ at index {1}. + + + + Expected string length {0} but was {1}. + Expected string length {0} but was {1}. + + Expected any value except:<{1}>. Actual:<{2}>. {0} Esperado qualquer valor exceto:<{1}>. Real:<{2}>. {0} diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ru.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ru.xlf index 7922657c22..7c3799c139 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ru.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ru.xlf @@ -37,6 +37,37 @@ Ожидается: <{1} ({2})>. Фактически: <{3} ({4})>. {0} + + {0}{1} +{2} +{3} +{4} + {0}{1} +{2} +{3} +{4} + + + + Expected: + Ожидалось: + + + + But was: + Но было: + + + + String lengths are both {0} but differ at index {1}. + String lengths are both {0} but differ at index {1}. + + + + Expected string length {0} but was {1}. + Expected string length {0} but was {1}. + + Expected any value except:<{1}>. Actual:<{2}>. {0} Ожидается любое значение, кроме: <{1}>. Фактически: <{2}>. {0} diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.tr.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.tr.xlf index 8948617376..b53ad9db79 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.tr.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.tr.xlf @@ -37,6 +37,37 @@ Beklenen:<{1} ({2})>. Gerçek:<{3} ({4})>. {0} + + {0}{1} +{2} +{3} +{4} + {0}{1} +{2} +{3} +{4} + + + + Expected: + Beklenen: + + + + But was: + Ama idi: + + + + String lengths are both {0} but differ at index {1}. + String lengths are both {0} but differ at index {1}. + + + + Expected string length {0} but was {1}. + Expected string length {0} but was {1}. + + Expected any value except:<{1}>. Actual:<{2}>. {0} Şunun dışında bir değer bekleniyor:<{1}>. Gerçek:<{2}>. {0} diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf index 73117c0eb8..7ed9157255 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf @@ -37,6 +37,37 @@ 应为: <{1} ({2})>,实际为: <{3} ({4})>。{0} + + {0}{1} +{2} +{3} +{4} + {0}{1} +{2} +{3} +{4} + + + + Expected: + 期望值: + + + + But was: + 但实际为: + + + + String lengths are both {0} but differ at index {1}. + String lengths are both {0} but differ at index {1}. + + + + Expected string length {0} but was {1}. + Expected string length {0} but was {1}. + + Expected any value except:<{1}>. Actual:<{2}>. {0} 应为: <{1}> 以外的任意值,实际为: <{2}>。{0} diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf index 8b0c772e2d..8fe191624c 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf @@ -37,6 +37,37 @@ 預期: <{1} ({2})>。實際: <{3} ({4})>。{0} + + {0}{1} +{2} +{3} +{4} + {0}{1} +{2} +{3} +{4} + + + + Expected: + 預期值: + + + + But was: + 但實際為: + + + + String lengths are both {0} but differ at index {1}. + String lengths are both {0} but differ at index {1}. + + + + Expected string length {0} but was {1}. + Expected string length {0} but was {1}. + + Expected any value except:<{1}>. Actual:<{2}>. {0} 預期任何值 (<{1}> 除外)。實際: <{2}>。{0} diff --git a/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.AreEqualTests.cs b/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.AreEqualTests.cs index 3815be857a..805c9bc53d 100644 --- a/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.AreEqualTests.cs +++ b/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.AreEqualTests.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 AwesomeAssertions; + using TestFramework.ForTestingMSTest; namespace Microsoft.VisualStudio.TestPlatform.TestFramework.UnitTests; @@ -1140,4 +1142,217 @@ public bool Equals(A? other) public override int GetHashCode() => Id.GetHashCode() + 1234; } + + public void AreEqualStringDifferenceAtBeginning() + { + Exception ex = VerifyThrows(() => Assert.AreEqual("baaa", "aaaa")); + ex.Message.Should().Be(""" + Assert.AreEqual failed. String lengths are both 4 but differ at index 0. + Expected: "baaa" + But was: "aaaa" + -----------^ + """); + } + + public void AreEqualStringDifferenceAtEnd() + { + Exception ex = VerifyThrows(() => Assert.AreEqual("aaaa", "aaab")); + ex.Message.Should().Be(""" + Assert.AreEqual failed. String lengths are both 4 but differ at index 3. + Expected: "aaaa" + But was: "aaab" + --------------^ + """); + } + + public void AreEqualStringWithSpecialCharactersShouldEscape() + { + Exception ex = VerifyThrows(() => Assert.AreEqual("aa\ta", "aa a")); + ex.Message.Should().Be(""" + Assert.AreEqual failed. String lengths are both 4 but differ at index 2. + Expected: "aa␉a" + But was: "aa a" + -------------^ + """); + } + + public void AreEqualLongStringsShouldTruncateAndShowContext() + { + string expected = new string('a', 100) + "b" + new string('c', 100); + string actual = new string('a', 100) + "d" + new string('c', 100); + + Exception ex = VerifyThrows(() => Assert.AreEqual(expected, actual)); + ex.Message.Should().Be(""" + Assert.AreEqual failed. String lengths are both 201 but differ at index 100. + Expected: "...aaaaaaaaaaaaaaaaaabcccccccccccccccc..." + But was: "...aaaaaaaaaaaaaaaaaadcccccccccccccccc..." + --------------------------------^ + """); + } + + public void AreEqualStringWithCultureShouldUseEnhancedMessage() + { + Exception ex = VerifyThrows(() => Assert.AreEqual("aaaa", "aaab", false, CultureInfo.InvariantCulture)); + ex.Message.Should().Be(""" + Assert.AreEqual failed. String lengths are both 4 but differ at index 3. + Expected: "aaaa" + But was: "aaab" + --------------^ + """); + } + + public void AreEqualStringWithDifferentLength() + { + Exception ex = VerifyThrows(() => Assert.AreEqual("aaaa", "aaa")); + ex.Message.Should().Be(""" + Assert.AreEqual failed. Expected string length 4 but was 3. + Expected: "aaaa" + But was: "aaa" + --------------^ + """); + } + + public void AreEqualShorterExpectedString() + { + Exception ex = VerifyThrows(() => Assert.AreEqual("aaa", "aaab")); + ex.Message.Should().Be(""" + Assert.AreEqual failed. Expected string length 3 but was 4. + Expected: "aaa" + But was: "aaab" + --------------^ + """); + } + + public void AreEqualStringWithUserMessage() + { + Exception ex = VerifyThrows(() => Assert.AreEqual("aaaa", "aaab", "My custom message")); + ex.Message.Should().Be(""" + Assert.AreEqual failed. String lengths are both 4 but differ at index 3. My custom message + Expected: "aaaa" + But was: "aaab" + --------------^ + """); + } + + public void AreEqualStringWithEmojis() + { + Exception ex = VerifyThrows(() => Assert.AreEqual("🥰", "aaab")); + ex.Message.Should().Be(""" + Assert.AreEqual failed. Expected string length 2 but was 4. + Expected: "🥰" + But was: "aaab" + -----------^ + """); + } + + public void CreateStringPreviews_DiffPointsToCorrectPlaceInNonShortenedString() + { + int preview = 9; + int length = 1; + int diffIndex = 0; + string stringPreview = FormatStringPreview(StringPreviewHelper.CreateStringPreviews(DigitString(length, diffIndex), DigitString(length, diffIndex), diffIndex, preview)); + stringPreview.Should().Be(""" + "X" + "X" + _^ + """); + } + + public void CreateStringPreviews_DiffPointsToCorrectPlaceInShortenedStringWithEndCut() + { + int preview = 9; + int length = preview + 10; + int diffIndex = 0; + string stringPreview = FormatStringPreview(StringPreviewHelper.CreateStringPreviews(DigitString(length, diffIndex), DigitString(length, diffIndex), diffIndex, preview)); + stringPreview.Should().Be(""" + "X12345..." + "X12345..." + _^ + """); + } + + public void CreateStringPreviews_DiffPointsToCorrectPlaceInShortenedStringWithStartCut() + { + int preview = 9; + int length = 10; + int diffIndex = 9; + string stringPreview = FormatStringPreview(StringPreviewHelper.CreateStringPreviews(DigitString(length, diffIndex), DigitString(length, diffIndex), diffIndex: diffIndex, preview)); + stringPreview.Should().Be(""" + "...45678X" + "...45678X" + _________^ + """); + } + + public void CreateStringPreviews_ShowWholeStringWhenDifferenceIsAtTheEndAndJustOneStringDoesNotFit() + { + int preview = 21; + int length = 50; + int diffIndex = 16; + string stringPreview = FormatStringPreview(StringPreviewHelper.CreateStringPreviews(DigitString(preview, diffIndex), DigitString(length, diffIndex), diffIndex: diffIndex, preview)); + stringPreview.Should().Be(""" + "0123456789012345X7890" + "0123456789012345X7..." + _________________^ + """); + } + + public void CreateStringPreviews_MakeSureWeDontPointToEndEllipsis() + { + // We will mask last 3 chars of the string, so we need to make sure that the diff index is not pointing to the end ellipsis. + int preview = 25; + int length = 50; + int diffIndex = 24; + + string stringPreview = FormatStringPreview(StringPreviewHelper.CreateStringPreviews(DigitString(preview, diffIndex), DigitString(length, diffIndex), diffIndex: diffIndex, preview)); + stringPreview.Should().Be(""" + "...8901234567890123X" + "...8901234567890123X56..." + ____________________^ + """); + } + + public void CreateStringPreviews_DiffPointsAfterLastCharacterWhenStringsAreAllTheSameCharactersUntilTheEndOfTheShorterOne() + { + int preview = 9; + int diffIndex = 3; + string stringPreview = FormatStringPreview(StringPreviewHelper.CreateStringPreviews("aaa", "aaaX", diffIndex, preview)); + stringPreview.Should().Be(""" + "aaa" + "aaaX" + ____^ + """); + } + + private string FormatStringPreview(Tuple tuple) + => $""" + "{tuple.Item1}" + "{tuple.Item2}" + {new string('_', tuple.Item3 + 1)}{'^'} + """; + + private static string DigitString(int length, int diffIndex) + { + const string digits = "0123456789"; + if (length <= 0) + { + return string.Empty; + } + + var result = new StringBuilder(length); + for (int i = 0; i < length; i++) + { + if (i == diffIndex) + { + // Use 'X' to indicate a difference should be at this index. + // To make it easier to see where the arrow should point, even though both strings are the same (we provide the diff index externally). + result.Append('X'); + continue; + } + + result.Append(digits[i % digits.Length]); + } + + return result.ToString(); + } } From 1109a5e2ed2562759db66a9501d3914ebbae5971 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Fri, 1 Aug 2025 16:31:18 +0200 Subject: [PATCH 355/541] Cleanup TerminalTestReporter (#6281) --- .../Terminal/TerminalTestReporter.cs | 160 +++++++----------- 1 file changed, 64 insertions(+), 96 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporter.cs b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporter.cs index 576117e89e..962ae0f881 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporter.cs +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporter.cs @@ -548,64 +548,68 @@ private static void FormatStandardAndErrorOutput(ITerminal terminal, string? sta private void AppendAssemblyLinkTargetFrameworkAndArchitecture(ITerminal terminal) { terminal.AppendLink(_assembly, lineNumber: null); - if (_targetFramework != null || _architecture != null) + if (_targetFramework == null && _architecture == null) { - terminal.Append(" ("); - if (_targetFramework != null) - { - terminal.Append(_targetFramework); - terminal.Append('|'); - } + return; + } - if (_architecture != null) - { - terminal.Append(_architecture); - } + terminal.Append(" ("); + if (_targetFramework != null) + { + terminal.Append(_targetFramework); + terminal.Append('|'); + } - terminal.Append(')'); + if (_architecture != null) + { + terminal.Append(_architecture); } + + terminal.Append(')'); } internal /* for testing */ static void AppendStackFrame(ITerminal terminal, string stackTraceLine) { terminal.Append(DoubleIndentation); Match match = StackTraceHelper.GetFrameRegex().Match(stackTraceLine); - if (match.Success) + if (!match.Success) { - bool weHaveFilePathAndCodeLine = !RoslynString.IsNullOrWhiteSpace(match.Groups["code"].Value); - terminal.Append(PlatformResources.StackFrameAt); - terminal.Append(' '); - - if (weHaveFilePathAndCodeLine) - { - terminal.Append(match.Groups["code"].Value); - } - else - { - terminal.Append(match.Groups["code1"].Value); - } + terminal.AppendLine(stackTraceLine); + return; + } - if (weHaveFilePathAndCodeLine) - { - terminal.Append(' '); - terminal.Append(PlatformResources.StackFrameIn); - terminal.Append(' '); - if (!RoslynString.IsNullOrWhiteSpace(match.Groups["file"].Value)) - { - int line = int.TryParse(match.Groups["line"].Value, out int value) ? value : 0; - terminal.AppendLink(match.Groups["file"].Value, line); + bool weHaveFilePathAndCodeLine = !RoslynString.IsNullOrWhiteSpace(match.Groups["code"].Value); + terminal.Append(PlatformResources.StackFrameAt); + terminal.Append(' '); - // AppendLink finishes by resetting color - terminal.SetColor(TerminalColor.DarkGray); - } - } + if (weHaveFilePathAndCodeLine) + { + terminal.Append(match.Groups["code"].Value); + } + else + { + terminal.Append(match.Groups["code1"].Value); + } + if (!weHaveFilePathAndCodeLine) + { terminal.AppendLine(); + return; } - else + + terminal.Append(' '); + terminal.Append(PlatformResources.StackFrameIn); + terminal.Append(' '); + if (!RoslynString.IsNullOrWhiteSpace(match.Groups["file"].Value)) { - terminal.AppendLine(stackTraceLine); + int line = int.TryParse(match.Groups["line"].Value, out int value) ? value : 0; + terminal.AppendLink(match.Groups["file"].Value, line); + + // AppendLink finishes by resetting color + terminal.SetColor(TerminalColor.DarkGray); } + + terminal.AppendLine(); } private static void AppendIndentedLine(ITerminal terminal, string? message, string indent) @@ -690,30 +694,30 @@ internal void WriteErrorMessage(string text, int? padding) { TestProgressState asm = GetOrAddAssemblyRun(); asm.AddError(text); - - _terminalWithProgress.WriteToTerminal(terminal => - { - terminal.SetColor(TerminalColor.DarkRed); - if (padding == null) - { - terminal.AppendLine(text); - } - else - { - AppendIndentedLine(terminal, text, new string(' ', padding.Value)); - } - - terminal.ResetColor(); - }); + WriteMessage(text, TerminalColor.DarkRed, padding); } internal void WriteWarningMessage(string text, int? padding) { TestProgressState asm = GetOrAddAssemblyRun(); asm.AddWarning(text); - _terminalWithProgress.WriteToTerminal(terminal => + WriteMessage(text, TerminalColor.DarkYellow, padding); + } + + internal void WriteErrorMessage(Exception exception) + => WriteErrorMessage(exception.ToString(), padding: null); + + public void WriteMessage(string text, SystemConsoleColor? color = null, int? padding = null) + => WriteMessage(text, color is not null ? ToTerminalColor(color.ConsoleColor) : null, padding); + + private void WriteMessage(string text, TerminalColor? color = null, int? padding = null) + => _terminalWithProgress.WriteToTerminal(terminal => { - terminal.SetColor(TerminalColor.DarkYellow); + if (color.HasValue) + { + terminal.SetColor(color.Value); + } + if (padding == null) { terminal.AppendLine(text); @@ -723,47 +727,11 @@ internal void WriteWarningMessage(string text, int? padding) AppendIndentedLine(terminal, text, new string(' ', padding.Value)); } - terminal.ResetColor(); - }); - } - - internal void WriteErrorMessage(Exception exception) - => WriteErrorMessage(exception.ToString(), padding: null); - - public void WriteMessage(string text, SystemConsoleColor? color = null, int? padding = null) - { - if (color != null) - { - _terminalWithProgress.WriteToTerminal(terminal => + if (color.HasValue) { - terminal.SetColor(ToTerminalColor(color.ConsoleColor)); - if (padding == null) - { - terminal.AppendLine(text); - } - else - { - AppendIndentedLine(terminal, text, new string(' ', padding.Value)); - } - terminal.ResetColor(); - }); - } - else - { - _terminalWithProgress.WriteToTerminal(terminal => - { - if (padding == null) - { - terminal.AppendLine(text); - } - else - { - AppendIndentedLine(terminal, text, new string(' ', padding.Value)); - } - }); - } - } + } + }); internal void TestDiscovered(string displayName) { From 2e14be58f664bc089fa4fff668b2efe4da5b9b00 Mon Sep 17 00:00:00 2001 From: dotnet bot Date: Fri, 1 Aug 2025 07:47:19 -0700 Subject: [PATCH 356/541] Localized file check-in by OneLocBuild Task: Build definition ID 1218: Build ID 2762728 --- .../TestFramework/Resources/xlf/FrameworkMessages.cs.xlf | 4 ++-- .../TestFramework/Resources/xlf/FrameworkMessages.de.xlf | 4 ++-- .../TestFramework/Resources/xlf/FrameworkMessages.es.xlf | 4 ++-- .../TestFramework/Resources/xlf/FrameworkMessages.fr.xlf | 4 ++-- .../TestFramework/Resources/xlf/FrameworkMessages.it.xlf | 4 ++-- .../TestFramework/Resources/xlf/FrameworkMessages.ja.xlf | 4 ++-- .../TestFramework/Resources/xlf/FrameworkMessages.ko.xlf | 4 ++-- .../TestFramework/Resources/xlf/FrameworkMessages.pl.xlf | 4 ++-- .../TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf | 4 ++-- .../TestFramework/Resources/xlf/FrameworkMessages.ru.xlf | 4 ++-- .../TestFramework/Resources/xlf/FrameworkMessages.tr.xlf | 4 ++-- .../TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf | 4 ++-- .../TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf | 4 ++-- 13 files changed, 26 insertions(+), 26 deletions(-) diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.cs.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.cs.xlf index 07a88dd5c4..c867ba8382 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.cs.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.cs.xlf @@ -50,12 +50,12 @@ Expected: - Očekáváno: + Expected: But was: - Ale bylo: + But was: diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.de.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.de.xlf index 7700ea600e..db937864b7 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.de.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.de.xlf @@ -50,12 +50,12 @@ Expected: - Erwartet: + Expected: But was: - Aber war: + But was: diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.es.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.es.xlf index b5599da4b5..90ac7471ca 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.es.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.es.xlf @@ -50,12 +50,12 @@ Expected: - Esperado: + Expected: But was: - Pero fue: + But was: diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.fr.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.fr.xlf index 57ccd98815..3396253ee0 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.fr.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.fr.xlf @@ -50,12 +50,12 @@ Expected: - Attendu : + Expected: But was: - Mais était : + But was: diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.it.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.it.xlf index 7a051c0fbe..8e0692c475 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.it.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.it.xlf @@ -50,12 +50,12 @@ Expected: - Previsto: + Expected: But was: - Ma era: + But was: diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ja.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ja.xlf index a0940d414c..68a712abf5 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ja.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ja.xlf @@ -50,12 +50,12 @@ Expected: - 期待値: + Expected: But was: - しかし実際: + But was: diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ko.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ko.xlf index 2f621daf6a..0b922f5552 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ko.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ko.xlf @@ -50,12 +50,12 @@ Expected: - 기대값: + Expected: But was: - 하지만 실제: + But was: diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pl.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pl.xlf index a63517f7f1..8a71710586 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pl.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pl.xlf @@ -50,12 +50,12 @@ Expected: - Oczekiwano: + Expected: But was: - Ale było: + But was: diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf index 51321e6921..44d643f9fc 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf @@ -50,12 +50,12 @@ Expected: - Esperado: + Expected: But was: - Mas foi: + But was: diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ru.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ru.xlf index 7c3799c139..0cd0510ef8 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ru.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ru.xlf @@ -50,12 +50,12 @@ Expected: - Ожидалось: + Expected: But was: - Но было: + But was: diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.tr.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.tr.xlf index b53ad9db79..9b5076beb9 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.tr.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.tr.xlf @@ -50,12 +50,12 @@ Expected: - Beklenen: + Expected: But was: - Ama idi: + But was: diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf index 7ed9157255..79a0ed8b34 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf @@ -50,12 +50,12 @@ Expected: - 期望值: + Expected: But was: - 但实际为: + But was: diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf index 8fe191624c..7fdc693b19 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf @@ -50,12 +50,12 @@ Expected: - 預期值: + Expected: But was: - 但實際為: + But was: From 6df1da328808574104e4d375154200b9c2219a4c Mon Sep 17 00:00:00 2001 From: dotnet bot Date: Fri, 1 Aug 2025 07:53:12 -0700 Subject: [PATCH 357/541] Localized file check-in by OneLocBuild Task: Build definition ID 1218: Build ID 2762730 --- .../TestFramework/Resources/xlf/FrameworkMessages.cs.xlf | 4 ++-- .../TestFramework/Resources/xlf/FrameworkMessages.de.xlf | 4 ++-- .../TestFramework/Resources/xlf/FrameworkMessages.es.xlf | 4 ++-- .../TestFramework/Resources/xlf/FrameworkMessages.fr.xlf | 4 ++-- .../TestFramework/Resources/xlf/FrameworkMessages.it.xlf | 4 ++-- .../TestFramework/Resources/xlf/FrameworkMessages.ja.xlf | 4 ++-- .../TestFramework/Resources/xlf/FrameworkMessages.ko.xlf | 4 ++-- .../TestFramework/Resources/xlf/FrameworkMessages.pl.xlf | 4 ++-- .../TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf | 4 ++-- .../TestFramework/Resources/xlf/FrameworkMessages.ru.xlf | 4 ++-- .../TestFramework/Resources/xlf/FrameworkMessages.tr.xlf | 4 ++-- .../TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf | 4 ++-- .../TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf | 4 ++-- 13 files changed, 26 insertions(+), 26 deletions(-) diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.cs.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.cs.xlf index 07a88dd5c4..c867ba8382 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.cs.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.cs.xlf @@ -50,12 +50,12 @@ Expected: - Očekáváno: + Expected: But was: - Ale bylo: + But was: diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.de.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.de.xlf index 7700ea600e..db937864b7 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.de.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.de.xlf @@ -50,12 +50,12 @@ Expected: - Erwartet: + Expected: But was: - Aber war: + But was: diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.es.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.es.xlf index b5599da4b5..90ac7471ca 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.es.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.es.xlf @@ -50,12 +50,12 @@ Expected: - Esperado: + Expected: But was: - Pero fue: + But was: diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.fr.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.fr.xlf index 57ccd98815..3396253ee0 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.fr.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.fr.xlf @@ -50,12 +50,12 @@ Expected: - Attendu : + Expected: But was: - Mais était : + But was: diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.it.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.it.xlf index 7a051c0fbe..8e0692c475 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.it.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.it.xlf @@ -50,12 +50,12 @@ Expected: - Previsto: + Expected: But was: - Ma era: + But was: diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ja.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ja.xlf index a0940d414c..68a712abf5 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ja.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ja.xlf @@ -50,12 +50,12 @@ Expected: - 期待値: + Expected: But was: - しかし実際: + But was: diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ko.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ko.xlf index 2f621daf6a..0b922f5552 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ko.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ko.xlf @@ -50,12 +50,12 @@ Expected: - 기대값: + Expected: But was: - 하지만 실제: + But was: diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pl.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pl.xlf index a63517f7f1..8a71710586 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pl.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pl.xlf @@ -50,12 +50,12 @@ Expected: - Oczekiwano: + Expected: But was: - Ale było: + But was: diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf index 51321e6921..44d643f9fc 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf @@ -50,12 +50,12 @@ Expected: - Esperado: + Expected: But was: - Mas foi: + But was: diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ru.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ru.xlf index 7c3799c139..0cd0510ef8 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ru.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ru.xlf @@ -50,12 +50,12 @@ Expected: - Ожидалось: + Expected: But was: - Но было: + But was: diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.tr.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.tr.xlf index b53ad9db79..9b5076beb9 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.tr.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.tr.xlf @@ -50,12 +50,12 @@ Expected: - Beklenen: + Expected: But was: - Ama idi: + But was: diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf index 7ed9157255..79a0ed8b34 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf @@ -50,12 +50,12 @@ Expected: - 期望值: + Expected: But was: - 但实际为: + But was: diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf index 8fe191624c..7fdc693b19 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf @@ -50,12 +50,12 @@ Expected: - 預期值: + Expected: But was: - 但實際為: + But was: From 0afe5b71af1862a57503f43a51e5e1604cf3f63d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Fri, 1 Aug 2025 17:41:59 +0200 Subject: [PATCH 358/541] Fix terminal reporter when architecture is null (#6284) --- .../OutputDevice/Terminal/TerminalTestReporter.cs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporter.cs b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporter.cs index 962ae0f881..960e47d3ca 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporter.cs +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporter.cs @@ -557,7 +557,10 @@ private void AppendAssemblyLinkTargetFrameworkAndArchitecture(ITerminal terminal if (_targetFramework != null) { terminal.Append(_targetFramework); - terminal.Append('|'); + if (_architecture != null) + { + terminal.Append('|'); + } } if (_architecture != null) From 84963178b98e79c9fc1f83e6656869fb1df53518 Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Sat, 2 Aug 2025 03:02:57 +0000 Subject: [PATCH 359/541] [main] Update dependencies from devdiv/DevDiv/vs-code-coverage, dotnet/arcade (#6287) [main] Update dependencies from devdiv/DevDiv/vs-code-coverage, dotnet/arcade --- eng/Version.Details.xml | 16 ++++++++-------- eng/Versions.props | 4 ++-- global.json | 2 +- 3 files changed, 11 insertions(+), 11 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index dd36e09b53..825bc8edcb 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -1,21 +1,21 @@ - + https://github.com/dotnet/arcade - 8df06d38fb9183c3fdff5077b670eb35f0cb3f31 + 40693ae2ee51e447f6ca96d07bc1ba779dcb9b9c - + https://github.com/dotnet/arcade - 8df06d38fb9183c3fdff5077b670eb35f0cb3f31 + 40693ae2ee51e447f6ca96d07bc1ba779dcb9b9c - + https://github.com/dotnet/arcade - 8df06d38fb9183c3fdff5077b670eb35f0cb3f31 + 40693ae2ee51e447f6ca96d07bc1ba779dcb9b9c - + https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage - c424a64350b804d827578adb55e00a0749731a51 + 3897080c69443cb675380bb3ac72cb9881dd5c87 https://github.com/microsoft/testfx diff --git a/eng/Versions.props b/eng/Versions.props index d6ac1e08e4..23e09d240e 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -7,8 +7,8 @@ preview - 10.0.0-beta.25379.3 - 18.0.0-preview.25381.1 + 10.0.0-beta.25401.2 + 18.0.0-preview.25401.1 3.11.0-preview.25381.6 1.9.0-preview.25381.6 diff --git a/global.json b/global.json index 988d17a92a..9482dcb124 100644 --- a/global.json +++ b/global.json @@ -33,7 +33,7 @@ "rollForward": "latestFeature" }, "msbuild-sdks": { - "Microsoft.DotNet.Arcade.Sdk": "10.0.0-beta.25379.3", + "Microsoft.DotNet.Arcade.Sdk": "10.0.0-beta.25401.2", "MSBuild.Sdk.Extras": "3.0.44" } } From 614f8faf027f6746d051ba08d7a68ec46edb4614 Mon Sep 17 00:00:00 2001 From: dotnet bot Date: Fri, 1 Aug 2025 20:21:46 -0700 Subject: [PATCH 360/541] Localized file check-in by OneLocBuild Task: Build definition ID 1218: Build ID 2763105 --- src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf | 6 +++--- src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf | 4 ++-- src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf | 4 ++-- src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf | 4 ++-- src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf | 4 ++-- src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf | 6 +++--- src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf | 10 +++++----- src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf | 4 ++-- src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf | 4 ++-- src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf | 10 +++++----- .../MSTest.Analyzers/xlf/Resources.zh-Hans.xlf | 6 +++--- .../MSTest.Analyzers/xlf/Resources.zh-Hant.xlf | 4 ++-- 12 files changed, 33 insertions(+), 33 deletions(-) diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf index e891585a90..596c767c56 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf @@ -966,17 +966,17 @@ Typ deklarující tyto metody by měl také respektovat následující pravidla: Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws. - Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws. + Metody Assert.Throws by měly obsahovat pouze jeden příkaz nebo výraz. Více příkazů může být zavádějící – pokud se vyvolá první příkaz, následující příkazy se nikdy neprovedou. Pokud se nevyvolá, měl by se přesunout mimo Assert.Throws. Assert.Throws should contain only a single statement/expression - Assert.Throws should contain only a single statement/expression + Parametr Assert.Throws by měl obsahovat jenom jeden příkaz nebo výraz Assert.Throws should contain only a single statement/expression - Assert.Throws should contain only a single statement/expression + Parametr Assert.Throws by měl obsahovat jenom jeden příkaz nebo výraz diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf index 6242e90714..26d28ceb9b 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf @@ -420,7 +420,7 @@ Der Typ, der diese Methoden deklariert, sollte auch die folgenden Regeln beachte '[DynamicData]' member '{0}.{1}' is a field so you should use 'DynamicDataSourceType.AutoDetect' or 'DynamicDataSourceType.Field' (auto detect is the default when not specified explicitly, and is recommended) - '[DynamicData]' member '{0}.{1}' is a field so you should use 'DynamicDataSourceType.AutoDetect' or 'DynamicDataSourceType.Field' (auto detect is the default when not specified explicitly, and is recommended) + '[DynamicData]' Mitglied '{0}.{1}' ist ein Feld, daher sollten Sie 'DynamicDataSourceType.AutoDetect' oder 'DynamicDataSourceType.Field' verwenden (die automatische Erkennung ist der Standardwert, wenn sie nicht explizit angegeben wird und wird empfohlen). @@ -430,7 +430,7 @@ Der Typ, der diese Methoden deklariert, sollte auch die folgenden Regeln beachte '[DynamicData]' member '{0}.{1}' is not a property, method, or field. Only properties, methods, and fields are supported. - '[DynamicData]' member '{0}.{1}' is not a property, method, or field. Only properties, methods, and fields are supported. + '[DynamicData]' Mitglied '{0}.{1}' ist keine Eigenschaft, Methode oder kein Feld. Nur Eigenschaften, Methoden und Felder werden unterstützt. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf index 9220288210..24a066f204 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf @@ -419,7 +419,7 @@ El tipo que declara estos métodos también debe respetar las reglas siguientes: '[DynamicData]' member '{0}.{1}' is a field so you should use 'DynamicDataSourceType.AutoDetect' or 'DynamicDataSourceType.Field' (auto detect is the default when not specified explicitly, and is recommended) - '[DynamicData]' member '{0}.{1}' is a field so you should use 'DynamicDataSourceType.AutoDetect' or 'DynamicDataSourceType.Field' (auto detect is the default when not specified explicitly, and is recommended) + El miembro '{0}.{1}' de '[DynamicData]' es un campo, por lo que debe usar 'DynamicDataSourceType.AutoDetect' o 'DynamicDataSourceType.Field' (la detección automática es el valor predeterminado cuando no se especifica explícitamente y se recomienda) @@ -429,7 +429,7 @@ El tipo que declara estos métodos también debe respetar las reglas siguientes: '[DynamicData]' member '{0}.{1}' is not a property, method, or field. Only properties, methods, and fields are supported. - '[DynamicData]' member '{0}.{1}' is not a property, method, or field. Only properties, methods, and fields are supported. + El miembro '{0}.{1}' de '[DynamicData]' no es una propiedad, un método o un campo. Solo se admiten propiedades, métodos y campos. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf index 40319aee2a..909fce01ba 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf @@ -419,7 +419,7 @@ Le type doit être une classe '[DynamicData]' member '{0}.{1}' is a field so you should use 'DynamicDataSourceType.AutoDetect' or 'DynamicDataSourceType.Field' (auto detect is the default when not specified explicitly, and is recommended) - '[DynamicData]' member '{0}.{1}' is a field so you should use 'DynamicDataSourceType.AutoDetect' or 'DynamicDataSourceType.Field' (auto detect is the default when not specified explicitly, and is recommended) + Le membre « [DynamicData] » « {0}.{1} » est un champ, vous devez donc utiliser « DynamicDataSourceType.AutoDetect » ou « DynamicDataSourceType.Field » (la détection automatique est la valeur par défaut lorsqu’elle n’est pas spécifiée explicitement et est recommandée) @@ -429,7 +429,7 @@ Le type doit être une classe '[DynamicData]' member '{0}.{1}' is not a property, method, or field. Only properties, methods, and fields are supported. - '[DynamicData]' member '{0}.{1}' is not a property, method, or field. Only properties, methods, and fields are supported. + Le membre « [Données dynamiques] » « {0}.{1} » n’est pas une propriété, une méthode ou un champ. Seules les propriétés, les méthodes et les champs sont pris en charge. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf index 5e2d061ae8..705406fedd 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf @@ -419,7 +419,7 @@ Anche il tipo che dichiara questi metodi deve rispettare le regole seguenti: '[DynamicData]' member '{0}.{1}' is a field so you should use 'DynamicDataSourceType.AutoDetect' or 'DynamicDataSourceType.Field' (auto detect is the default when not specified explicitly, and is recommended) - '[DynamicData]' member '{0}.{1}' is a field so you should use 'DynamicDataSourceType.AutoDetect' or 'DynamicDataSourceType.Field' (auto detect is the default when not specified explicitly, and is recommended) + Il membro di '[DynamicData]' '{0}.{1}' è un campo, quindi è necessario usare 'DynamicDataSourceType.AutoDetect' o 'DynamicDataSourceType.Field' (il rilevamento automatico è l'impostazione predefinita quando non è specificato esplicitamente ed è l'opzione consigliata) @@ -429,7 +429,7 @@ Anche il tipo che dichiara questi metodi deve rispettare le regole seguenti: '[DynamicData]' member '{0}.{1}' is not a property, method, or field. Only properties, methods, and fields are supported. - '[DynamicData]' member '{0}.{1}' is not a property, method, or field. Only properties, methods, and fields are supported. + Il membro di '[DynamicData]' '{0}.{1}' non è una proprietà, un metodo o un campo. Sono supportati solo le proprietà, i metodi e i campi. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf index 90f2cfbac5..7f188bc8c8 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf @@ -966,17 +966,17 @@ The type declaring these methods should also respect the following rules: Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws. - Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws. + Assert.Throws 메서드는 단일 문 또는 식만 포함해야 합니다. 여러 문이 있을 경우 혼란을 줄 수 있습니다. 첫 번째 문이 예외를 발생시키면 후속 문은 실행되지 않으며, 예외가 발생하지 않는 경우에는 Assert.Throws 외부로 이동해야 합니다. Assert.Throws should contain only a single statement/expression - Assert.Throws should contain only a single statement/expression + Assert.Throws는 단일 문/식만 포함해야 합니다. Assert.Throws should contain only a single statement/expression - Assert.Throws should contain only a single statement/expression + Assert.Throws는 단일 문/식만 포함해야 합니다. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf index 511014e7a8..4ec67dfe46 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf @@ -419,7 +419,7 @@ Typ deklarujący te metody powinien również przestrzegać następujących regu '[DynamicData]' member '{0}.{1}' is a field so you should use 'DynamicDataSourceType.AutoDetect' or 'DynamicDataSourceType.Field' (auto detect is the default when not specified explicitly, and is recommended) - '[DynamicData]' member '{0}.{1}' is a field so you should use 'DynamicDataSourceType.AutoDetect' or 'DynamicDataSourceType.Field' (auto detect is the default when not specified explicitly, and is recommended) + Składowa „[DynamicData]” „{0}.{1}” jest polem, dlatego należy użyć elementu „DynamicDataSourceType.AutoDetect” lub „DynamicDataSourceType.Field” (wykrywanie automatyczne jest ustawieniem domyślnym, gdy nie zostanie jawnie określone i jest zalecane) @@ -429,7 +429,7 @@ Typ deklarujący te metody powinien również przestrzegać następujących regu '[DynamicData]' member '{0}.{1}' is not a property, method, or field. Only properties, methods, and fields are supported. - '[DynamicData]' member '{0}.{1}' is not a property, method, or field. Only properties, methods, and fields are supported. + Składowa „[DynamicData]” „{0}.{1}” nie jest właściwością, metodą ani polem. Obsługiwane są tylko właściwości, metody i pola. @@ -966,17 +966,17 @@ Typ deklarujący te metody powinien również przestrzegać następujących regu Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws. - Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws. + Metody Assert.Throws powinny zawierać tylko jedną instrukcję lub wyrażenie. Wiele instrukcji może być mylących – jeśli pierwsza instrukcja zgłosi wyjątek, kolejne instrukcje nigdy nie zostaną wykonane; jeśli nie zgłosi wyjątku, powinna zostać przeniesiona poza Assert.Throws. Assert.Throws should contain only a single statement/expression - Assert.Throws should contain only a single statement/expression + Element Assert.Throws powinien zawierać tylko jedną instrukcję/wyrażenie Assert.Throws should contain only a single statement/expression - Assert.Throws should contain only a single statement/expression + Element Assert.Throws powinien zawierać tylko jedną instrukcję/wyrażenie diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf index afde6025b5..2d170cd8eb 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf @@ -419,7 +419,7 @@ O tipo que declara esses métodos também deve respeitar as seguintes regras: '[DynamicData]' member '{0}.{1}' is a field so you should use 'DynamicDataSourceType.AutoDetect' or 'DynamicDataSourceType.Field' (auto detect is the default when not specified explicitly, and is recommended) - '[DynamicData]' member '{0}.{1}' is a field so you should use 'DynamicDataSourceType.AutoDetect' or 'DynamicDataSourceType.Field' (auto detect is the default when not specified explicitly, and is recommended) + O membro "[DynamicData]" "{0}.{1}" é um campo — portanto, você deve usar "DynamicDataSourceType.AutoDetect" ou "DynamicDataSourceType.Field" (detectar automaticamente é o padrão quando não especificado explicitamente, e é recomendado) @@ -429,7 +429,7 @@ O tipo que declara esses métodos também deve respeitar as seguintes regras: '[DynamicData]' member '{0}.{1}' is not a property, method, or field. Only properties, methods, and fields are supported. - '[DynamicData]' member '{0}.{1}' is not a property, method, or field. Only properties, methods, and fields are supported. + O membro "[DynamicData]" "{0}.{1}" não é uma propriedade, método ou campo. Somente propriedades, métodos e campos têm suporte. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf index 3c611b0d65..ace33e5ecc 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf @@ -425,7 +425,7 @@ The type declaring these methods should also respect the following rules: '[DynamicData]' member '{0}.{1}' is a field so you should use 'DynamicDataSourceType.AutoDetect' or 'DynamicDataSourceType.Field' (auto detect is the default when not specified explicitly, and is recommended) - '[DynamicData]' member '{0}.{1}' is a field so you should use 'DynamicDataSourceType.AutoDetect' or 'DynamicDataSourceType.Field' (auto detect is the default when not specified explicitly, and is recommended) + Элемент "[DynamicData]" "{0}.{1}" является полем, поэтому следует использовать "DynamicDataSourceType.AutoDetect" или "DynamicDataSourceType.Field" (автообнаружение используется по умолчанию, если не указано явно, и является рекомендуемым) @@ -435,7 +435,7 @@ The type declaring these methods should also respect the following rules: '[DynamicData]' member '{0}.{1}' is not a property, method, or field. Only properties, methods, and fields are supported. - '[DynamicData]' member '{0}.{1}' is not a property, method, or field. Only properties, methods, and fields are supported. + Элемент "[DynamicData]" "{0}.{1}" не является свойством, методом или полем. Поддерживаются только свойства, методы и поля. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf index 14e6a30d81..d67273a437 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf @@ -419,7 +419,7 @@ Bu yöntemleri bildiren tipin ayrıca aşağıdaki kurallara uyması gerekir: '[DynamicData]' member '{0}.{1}' is a field so you should use 'DynamicDataSourceType.AutoDetect' or 'DynamicDataSourceType.Field' (auto detect is the default when not specified explicitly, and is recommended) - '[DynamicData]' member '{0}.{1}' is a field so you should use 'DynamicDataSourceType.AutoDetect' or 'DynamicDataSourceType.Field' (auto detect is the default when not specified explicitly, and is recommended) + ‘[DynamicData]’ üyesi ‘{0}.{1}’, bir alandır, bu nedenle ‘DynamicDataSourceType.AutoDetect’ veya ‘DynamicDataSourceType.Field’ kullanmalısınız (otomatik algılama, açıkça belirtilmediğinde varsayılan ayardır ve önerilir) @@ -429,7 +429,7 @@ Bu yöntemleri bildiren tipin ayrıca aşağıdaki kurallara uyması gerekir: '[DynamicData]' member '{0}.{1}' is not a property, method, or field. Only properties, methods, and fields are supported. - '[DynamicData]' member '{0}.{1}' is not a property, method, or field. Only properties, methods, and fields are supported. + ‘[DynamicData]’ üyesi ‘{0}.{1}’, bir özellik, yöntem veya alan değildir. Yalnızca özellikler, yöntemler ve alanlar desteklenir. @@ -968,17 +968,17 @@ Bu yöntemleri bildiren tipin ayrıca aşağıdaki kurallara uyması gerekir: Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws. - Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws. + Assert.Throws yöntemleri yalnızca tek bir deyim veya ifade içermelidir. Birden fazla deyim yanıltıcı olabilir; eğer ilk deyim bir sonuç oluşturursa, sonraki deyimler asla çalıştırılmaz; eğer sonuç oluşturmazsa, bu deyim Assert.Throws dışına alınmalıdır. Assert.Throws should contain only a single statement/expression - Assert.Throws should contain only a single statement/expression + Assert.Throws yalnızca tek bir deyim/ifade içermelidir. Assert.Throws should contain only a single statement/expression - Assert.Throws should contain only a single statement/expression + Assert.Throws yalnızca tek bir deyim/ifade içermelidir. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf index 68dac3ed37..04e7e3e394 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf @@ -966,17 +966,17 @@ The type declaring these methods should also respect the following rules: Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws. - Assert.Throws methods should contain only a single statement or expression. Multiple statements can be misleading - if the first statement throws, subsequent statements are never executed; if it doesn't throw, it should be moved outside the Assert.Throws. + Assert.Throws 方法应只包含单个语句或表达式。多个语句可能会产生误导性 - 如果第一个语句引发,则永远不会执行后续语句;如果不引发,则应将其移到 Assert.Throws 外部。 Assert.Throws should contain only a single statement/expression - Assert.Throws should contain only a single statement/expression + Assert.Throws 应仅包含单个语句/表达式 Assert.Throws should contain only a single statement/expression - Assert.Throws should contain only a single statement/expression + Assert.Throws 应仅包含单个语句/表达式 diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf index 3278b76988..2f19c2e8f7 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf @@ -419,7 +419,7 @@ The type declaring these methods should also respect the following rules: '[DynamicData]' member '{0}.{1}' is a field so you should use 'DynamicDataSourceType.AutoDetect' or 'DynamicDataSourceType.Field' (auto detect is the default when not specified explicitly, and is recommended) - '[DynamicData]' member '{0}.{1}' is a field so you should use 'DynamicDataSourceType.AutoDetect' or 'DynamicDataSourceType.Field' (auto detect is the default when not specified explicitly, and is recommended) + '[DynamicData]' 成員 '{0}.{1}' 是欄位,因此您應該使用 'DynamicDataSourceType.AutoDetect' 或 'DynamicDataSourceType.Field' (未明確指定時,自動偵測為預設值,建議使用) @@ -429,7 +429,7 @@ The type declaring these methods should also respect the following rules: '[DynamicData]' member '{0}.{1}' is not a property, method, or field. Only properties, methods, and fields are supported. - '[DynamicData]' member '{0}.{1}' is not a property, method, or field. Only properties, methods, and fields are supported. + '[DynamicData]' 成員 '{0}.{1}' 不是屬性、方法或欄位。僅支援屬性、方法和欄位。 From 8c2a2becede67aa8307a9fa8ef797f393796208b Mon Sep 17 00:00:00 2001 From: dotnet bot Date: Fri, 1 Aug 2025 20:26:02 -0700 Subject: [PATCH 361/541] Localized file check-in by OneLocBuild Task: Build definition ID 1218: Build ID 2763105 --- .../TestFramework/Resources/xlf/FrameworkMessages.cs.xlf | 4 ++-- .../TestFramework/Resources/xlf/FrameworkMessages.de.xlf | 4 ++-- .../TestFramework/Resources/xlf/FrameworkMessages.es.xlf | 4 ++-- .../TestFramework/Resources/xlf/FrameworkMessages.fr.xlf | 4 ++-- .../TestFramework/Resources/xlf/FrameworkMessages.it.xlf | 4 ++-- .../TestFramework/Resources/xlf/FrameworkMessages.pl.xlf | 4 ++-- .../TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf | 4 ++-- .../TestFramework/Resources/xlf/FrameworkMessages.ru.xlf | 4 ++-- .../TestFramework/Resources/xlf/FrameworkMessages.tr.xlf | 4 ++-- .../TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf | 4 ++-- 10 files changed, 20 insertions(+), 20 deletions(-) diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.cs.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.cs.xlf index c867ba8382..1af7cdedd7 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.cs.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.cs.xlf @@ -160,7 +160,7 @@ Dynamic data field '{0}' should be static. - Dynamic data field '{0}' should be static. + Dynamické datové pole {0} by mělo být statické. @@ -175,7 +175,7 @@ The dynamic data source '{0}' in type '{1}' should exist and be a property, a method, or a field. - The dynamic data source '{0}' in type '{1}' should exist and be a property, a method, or a field. + Dynamický zdroj dat {0} v typu {1} by měl existovat a měla by to být vlastnost, metoda nebo pole. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.de.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.de.xlf index db937864b7..ecfa565f11 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.de.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.de.xlf @@ -160,7 +160,7 @@ Dynamic data field '{0}' should be static. - Dynamic data field '{0}' should be static. + Das dynamische Datenfeld „{0}“ sollte statisch sein. @@ -175,7 +175,7 @@ The dynamic data source '{0}' in type '{1}' should exist and be a property, a method, or a field. - The dynamic data source '{0}' in type '{1}' should exist and be a property, a method, or a field. + Die dynamische Datenquelle „{0}“ vom Typ „{1}“ sollte vorhanden sein und eine Eigenschaft, eine Methode oder ein Feld darstellen. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.es.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.es.xlf index 90ac7471ca..a9e1cf08cf 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.es.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.es.xlf @@ -160,7 +160,7 @@ Dynamic data field '{0}' should be static. - Dynamic data field '{0}' should be static. + El campo de datos dinámico '{0}' debe ser estático. @@ -175,7 +175,7 @@ The dynamic data source '{0}' in type '{1}' should exist and be a property, a method, or a field. - The dynamic data source '{0}' in type '{1}' should exist and be a property, a method, or a field. + El origen de datos dinámico '{0}' del tipo '{1}' debe existir y ser una propiedad, un método o un campo. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.fr.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.fr.xlf index 3396253ee0..04eef1a70e 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.fr.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.fr.xlf @@ -160,7 +160,7 @@ Dynamic data field '{0}' should be static. - Dynamic data field '{0}' should be static. + Le champ de données dynamiques « {0} » doit être statique. @@ -175,7 +175,7 @@ The dynamic data source '{0}' in type '{1}' should exist and be a property, a method, or a field. - The dynamic data source '{0}' in type '{1}' should exist and be a property, a method, or a field. + La source de données dynamique « {0} » du type « {1} » doit exister et être une propriété, une méthode ou un champ. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.it.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.it.xlf index 8e0692c475..41c19c6e41 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.it.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.it.xlf @@ -160,7 +160,7 @@ Dynamic data field '{0}' should be static. - Dynamic data field '{0}' should be static. + Il campo dati dinamico '{0}' deve essere statico. @@ -175,7 +175,7 @@ The dynamic data source '{0}' in type '{1}' should exist and be a property, a method, or a field. - The dynamic data source '{0}' in type '{1}' should exist and be a property, a method, or a field. + L'origine dati dinamica '{0}' nel tipo '{1}' deve esistere ed essere una proprietà, un metodo o un campo. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pl.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pl.xlf index 8a71710586..239e2540f5 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pl.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pl.xlf @@ -160,7 +160,7 @@ Dynamic data field '{0}' should be static. - Dynamic data field '{0}' should be static. + Dynamiczne pole danych „{0}” powinno być statyczne. @@ -175,7 +175,7 @@ The dynamic data source '{0}' in type '{1}' should exist and be a property, a method, or a field. - The dynamic data source '{0}' in type '{1}' should exist and be a property, a method, or a field. + Dynamiczne źródło danych „{0}” w typie „{1}” powinno istnieć i być właściwością, metodą lub polem. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf index 44d643f9fc..a45be57fc2 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf @@ -160,7 +160,7 @@ Dynamic data field '{0}' should be static. - Dynamic data field '{0}' should be static. + O campo de dados dinâmicos '{0}' deve ser estático. @@ -175,7 +175,7 @@ The dynamic data source '{0}' in type '{1}' should exist and be a property, a method, or a field. - The dynamic data source '{0}' in type '{1}' should exist and be a property, a method, or a field. + A fonte de dados dinâmica '{0}' do tipo '{1}' deve existir e ser uma propriedade, um método ou um campo. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ru.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ru.xlf index 0cd0510ef8..f50b305b65 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ru.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ru.xlf @@ -160,7 +160,7 @@ Dynamic data field '{0}' should be static. - Dynamic data field '{0}' should be static. + Поле динамических данных "{0}" должно быть статическим. @@ -175,7 +175,7 @@ The dynamic data source '{0}' in type '{1}' should exist and be a property, a method, or a field. - The dynamic data source '{0}' in type '{1}' should exist and be a property, a method, or a field. + Динамический источник данных "{0}" в типе "{1}" должен существовать и быть свойством, методом или полем. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.tr.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.tr.xlf index 9b5076beb9..30c58a310d 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.tr.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.tr.xlf @@ -160,7 +160,7 @@ Dynamic data field '{0}' should be static. - Dynamic data field '{0}' should be static. + Dinamik veri alanı ‘{0}’ statik olmalıdır. @@ -175,7 +175,7 @@ The dynamic data source '{0}' in type '{1}' should exist and be a property, a method, or a field. - The dynamic data source '{0}' in type '{1}' should exist and be a property, a method, or a field. + ‘{1}’ türündeki dinamik veri kaynağı ‘{0}’ mevcut olmalı ve bir özellik, yöntem veya alan olmalıdır. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf index 7fdc693b19..7d6a4ba72e 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf @@ -160,7 +160,7 @@ Dynamic data field '{0}' should be static. - Dynamic data field '{0}' should be static. + 動態資料欄位 '{0}' 應該為靜態。 @@ -175,7 +175,7 @@ The dynamic data source '{0}' in type '{1}' should exist and be a property, a method, or a field. - The dynamic data source '{0}' in type '{1}' should exist and be a property, a method, or a field. + 類型 '{1}' 中的動態資料來源 '{0}' 應該存在,並且必須是屬性、方法或欄位。 From a309c8fc8b7cf2a0bc7e411ac5506b0d2ce93d5a Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Sat, 2 Aug 2025 07:41:31 +0200 Subject: [PATCH 362/541] [main] Update dependencies from microsoft/testfx (#6288) Co-authored-by: dotnet-maestro[bot] --- eng/Version.Details.xml | 8 ++++---- eng/Versions.props | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index 825bc8edcb..64f6880a42 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -17,13 +17,13 @@ https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage 3897080c69443cb675380bb3ac72cb9881dd5c87 - + https://github.com/microsoft/testfx - f548433961344ee1629c5b04c35d99efc9fdd860 + 0afe5b71af1862a57503f43a51e5e1604cf3f63d - + https://github.com/microsoft/testfx - f548433961344ee1629c5b04c35d99efc9fdd860 + 0afe5b71af1862a57503f43a51e5e1604cf3f63d diff --git a/eng/Versions.props b/eng/Versions.props index 23e09d240e..94d0c663c7 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -10,7 +10,7 @@ 10.0.0-beta.25401.2 18.0.0-preview.25401.1 - 3.11.0-preview.25381.6 - 1.9.0-preview.25381.6 + 3.11.0-preview.25401.10 + 1.9.0-preview.25401.10 From 8ce2d7dfd54799d183dae1135431d3a7d8f297dc Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Mon, 4 Aug 2025 06:49:31 +0200 Subject: [PATCH 363/541] [main] Update dependencies from microsoft/testfx (#6291) Co-authored-by: dotnet-maestro[bot] --- eng/Version.Details.xml | 8 ++++---- eng/Versions.props | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index 64f6880a42..af2965a2dd 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -17,13 +17,13 @@ https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage 3897080c69443cb675380bb3ac72cb9881dd5c87 - + https://github.com/microsoft/testfx - 0afe5b71af1862a57503f43a51e5e1604cf3f63d + a309c8fc8b7cf2a0bc7e411ac5506b0d2ce93d5a - + https://github.com/microsoft/testfx - 0afe5b71af1862a57503f43a51e5e1604cf3f63d + a309c8fc8b7cf2a0bc7e411ac5506b0d2ce93d5a diff --git a/eng/Versions.props b/eng/Versions.props index 94d0c663c7..a6a63f73d9 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -10,7 +10,7 @@ 10.0.0-beta.25401.2 18.0.0-preview.25401.1 - 3.11.0-preview.25401.10 - 1.9.0-preview.25401.10 + 3.11.0-preview.25401.13 + 1.9.0-preview.25401.13 From 4e5dd2540b99f1bad71b49a65636a7dc8d125c15 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Mon, 4 Aug 2025 10:49:10 +0200 Subject: [PATCH 364/541] Update vs version in global.json (#6296) --- global.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/global.json b/global.json index 9482dcb124..552650a9d8 100644 --- a/global.json +++ b/global.json @@ -19,7 +19,7 @@ ] }, "vs": { - "version": "17.8.0" + "version": "17.14.10" } }, "sdk": { From aed6f05343768fcdce5333519e0f97c302f31a8a Mon Sep 17 00:00:00 2001 From: Copilot <198982749+Copilot@users.noreply.github.com> Date: Mon, 4 Aug 2025 14:56:26 +0200 Subject: [PATCH 365/541] Fix ApplicationStateGuard filename - rename Class1.cs to ApplicationStateGuard.cs (#6298) Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: nohwnd <5735905+nohwnd@users.noreply.github.com> Co-authored-by: Youssef1313 <31348972+Youssef1313@users.noreply.github.com> Co-authored-by: Youssef Victor --- .../Internal/{Class1.cs => ApplicationStateGuard.cs} | 2 ++ 1 file changed, 2 insertions(+) rename src/TestFramework/TestFramework/Internal/{Class1.cs => ApplicationStateGuard.cs} (88%) diff --git a/src/TestFramework/TestFramework/Internal/Class1.cs b/src/TestFramework/TestFramework/Internal/ApplicationStateGuard.cs similarity index 88% rename from src/TestFramework/TestFramework/Internal/Class1.cs rename to src/TestFramework/TestFramework/Internal/ApplicationStateGuard.cs index b879e79499..bfa64b6765 100644 --- a/src/TestFramework/TestFramework/Internal/Class1.cs +++ b/src/TestFramework/TestFramework/Internal/ApplicationStateGuard.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. +namespace Microsoft.VisualStudio.TestTools.UnitTesting; + internal static class ApplicationStateGuard { public static UnreachableException Unreachable([CallerFilePath] string? path = null, [CallerLineNumber] int line = 0) From f3ec4dde6ee95396a53012dad96885827b7f932b Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Mon, 4 Aug 2025 16:25:20 +0200 Subject: [PATCH 366/541] Fix analyzer false positives for collection asserts (#6300) --- .../UseProperAssertMethodsAnalyzer.cs | 43 ++++++------ .../UseProperAssertMethodsAnalyzerTests.cs | 68 +++++++++++++++++++ 2 files changed, 92 insertions(+), 19 deletions(-) diff --git a/src/Analyzers/MSTest.Analyzers/UseProperAssertMethodsAnalyzer.cs b/src/Analyzers/MSTest.Analyzers/UseProperAssertMethodsAnalyzer.cs index 7b49b0bc40..2d51ae27da 100644 --- a/src/Analyzers/MSTest.Analyzers/UseProperAssertMethodsAnalyzer.cs +++ b/src/Analyzers/MSTest.Analyzers/UseProperAssertMethodsAnalyzer.cs @@ -219,11 +219,13 @@ public override void Initialize(AnalysisContext context) return; } - context.RegisterOperationAction(context => AnalyzeInvocationOperation(context, assertTypeSymbol), OperationKind.Invocation); + INamedTypeSymbol objectTypeSymbol = context.Compilation.GetSpecialType(SpecialType.System_Object); + + context.RegisterOperationAction(context => AnalyzeInvocationOperation(context, assertTypeSymbol, objectTypeSymbol), OperationKind.Invocation); }); } - private static void AnalyzeInvocationOperation(OperationAnalysisContext context, INamedTypeSymbol assertTypeSymbol) + private static void AnalyzeInvocationOperation(OperationAnalysisContext context, INamedTypeSymbol assertTypeSymbol, INamedTypeSymbol objectTypeSymbol) { var operation = (IInvocationOperation)context.Operation; IMethodSymbol targetMethod = operation.TargetMethod; @@ -240,19 +242,19 @@ private static void AnalyzeInvocationOperation(OperationAnalysisContext context, switch (targetMethod.Name) { case "IsTrue": - AnalyzeIsTrueOrIsFalseInvocation(context, firstArgument, isTrueInvocation: true); + AnalyzeIsTrueOrIsFalseInvocation(context, firstArgument, isTrueInvocation: true, objectTypeSymbol); break; case "IsFalse": - AnalyzeIsTrueOrIsFalseInvocation(context, firstArgument, isTrueInvocation: false); + AnalyzeIsTrueOrIsFalseInvocation(context, firstArgument, isTrueInvocation: false, objectTypeSymbol); break; case "AreEqual": - AnalyzeAreEqualOrAreNotEqualInvocation(context, firstArgument, isAreEqualInvocation: true); + AnalyzeAreEqualOrAreNotEqualInvocation(context, firstArgument, isAreEqualInvocation: true, objectTypeSymbol); break; case "AreNotEqual": - AnalyzeAreEqualOrAreNotEqualInvocation(context, firstArgument, isAreEqualInvocation: false); + AnalyzeAreEqualOrAreNotEqualInvocation(context, firstArgument, isAreEqualInvocation: false, objectTypeSymbol); break; } } @@ -429,6 +431,7 @@ private static StringMethodCheckStatus RecognizeStringMethodCheck( private static CollectionCheckStatus RecognizeCollectionMethodCheck( IOperation operation, + INamedTypeSymbol objectTypeSymbol, out SyntaxNode? collectionExpression, out SyntaxNode? itemExpression) { @@ -439,10 +442,7 @@ private static CollectionCheckStatus RecognizeCollectionMethodCheck( // Check for Collection.Contains(item) if (methodName == "Contains" && invocation.Arguments.Length == 1) { - // Ensure it's a collection type (implements IEnumerable) - ITypeSymbol? receiverType = invocation.Instance?.Type; - if (receiverType is not null && - IsCollectionType(receiverType)) + if (IsBCLCollectionType(invocation.TargetMethod.ContainingType, objectTypeSymbol)) { collectionExpression = invocation.Instance?.Syntax; itemExpression = invocation.Arguments[0].Value.Syntax; @@ -456,11 +456,14 @@ private static CollectionCheckStatus RecognizeCollectionMethodCheck( return CollectionCheckStatus.Unknown; } - private static bool IsCollectionType(ITypeSymbol type) - // Check if the type implements IEnumerable (but is not string) + private static bool IsBCLCollectionType(ITypeSymbol type, INamedTypeSymbol objectTypeSymbol) + // Check if the type implements IEnumerable (but is not string) + // Note: Assert.Contains/IsEmpty/HasCount for collections accept IEnumerable, but not IEnumerable. => type.SpecialType != SpecialType.System_String && type.AllInterfaces.Any(i => - i.SpecialType == SpecialType.System_Collections_IEnumerable || - (i.OriginalDefinition?.SpecialType == SpecialType.System_Collections_Generic_IEnumerable_T)); + i.OriginalDefinition.SpecialType == SpecialType.System_Collections_Generic_IEnumerable_T) && + // object is coming from BCL and it's expected to always have a public key. + type.ContainingAssembly.Identity.HasPublicKey == objectTypeSymbol.ContainingAssembly.Identity.HasPublicKey && + type.ContainingAssembly.Identity.PublicKey.SequenceEqual(objectTypeSymbol.ContainingAssembly.Identity.PublicKey); private static ComparisonCheckStatus RecognizeComparisonCheck( IOperation operation, @@ -488,7 +491,7 @@ private static ComparisonCheckStatus RecognizeComparisonCheck( return ComparisonCheckStatus.Unknown; } - private static void AnalyzeIsTrueOrIsFalseInvocation(OperationAnalysisContext context, IOperation conditionArgument, bool isTrueInvocation) + private static void AnalyzeIsTrueOrIsFalseInvocation(OperationAnalysisContext context, IOperation conditionArgument, bool isTrueInvocation, INamedTypeSymbol objectTypeSymbol) { RoslynDebug.Assert(context.Operation is IInvocationOperation, "Expected IInvocationOperation."); @@ -575,7 +578,7 @@ private static void AnalyzeIsTrueOrIsFalseInvocation(OperationAnalysisContext co } // Check for collection method patterns: myCollection.Contains(...) - CollectionCheckStatus collectionMethodStatus = RecognizeCollectionMethodCheck(conditionArgument, out SyntaxNode? collectionExpr, out SyntaxNode? itemExpr); + CollectionCheckStatus collectionMethodStatus = RecognizeCollectionMethodCheck(conditionArgument, objectTypeSymbol, out SyntaxNode? collectionExpr, out SyntaxNode? itemExpr); if (collectionMethodStatus != CollectionCheckStatus.Unknown) { if (collectionMethodStatus == CollectionCheckStatus.Contains) @@ -705,7 +708,7 @@ private static void AnalyzeIsTrueOrIsFalseInvocation(OperationAnalysisContext co } } - private static void AnalyzeAreEqualOrAreNotEqualInvocation(OperationAnalysisContext context, IOperation expectedArgument, bool isAreEqualInvocation) + private static void AnalyzeAreEqualOrAreNotEqualInvocation(OperationAnalysisContext context, IOperation expectedArgument, bool isAreEqualInvocation, INamedTypeSymbol objectTypeSymbol) { // Check for collection count patterns: collection.Count/Length == 0 or collection.Count/Length == X if (isAreEqualInvocation) @@ -716,6 +719,7 @@ private static void AnalyzeAreEqualOrAreNotEqualInvocation(OperationAnalysisCont CountCheckStatus countStatus = RecognizeCountCheck( expectedArgument, actualArgumentValue, + objectTypeSymbol, out SyntaxNode? collectionExpr, out _, out _); @@ -822,6 +826,7 @@ actualArgumentValue.Type is { } actualType && private static CountCheckStatus RecognizeCountCheck( IOperation expectedArgument, IOperation actualArgument, + INamedTypeSymbol objectTypeSymbol, out SyntaxNode? collectionExpression, out SyntaxNode? countExpression, out int countValue) @@ -833,7 +838,7 @@ expectedArgument.ConstantValue.Value is int expectedValue && actualArgument is IPropertyReferenceOperation propertyRef && propertyRef.Property.Name is "Count" or "Length" && propertyRef.Instance?.Type is not null && - IsCollectionType(propertyRef.Instance.Type)) + IsBCLCollectionType(propertyRef.Property.ContainingType, objectTypeSymbol)) { collectionExpression = propertyRef.Instance.Syntax; countExpression = propertyRef.Syntax; @@ -848,7 +853,7 @@ actualArgument.ConstantValue.Value is int actualValue && expectedArgument is IPropertyReferenceOperation propertyRef2 && propertyRef2.Property.Name is "Count" or "Length" && propertyRef2.Instance?.Type is not null && - IsCollectionType(propertyRef2.Instance.Type)) + IsBCLCollectionType(propertyRef2.Property.ContainingType, objectTypeSymbol)) { collectionExpression = propertyRef2.Instance.Syntax; countExpression = propertyRef2.Syntax; diff --git a/test/UnitTests/MSTest.Analyzers.UnitTests/UseProperAssertMethodsAnalyzerTests.cs b/test/UnitTests/MSTest.Analyzers.UnitTests/UseProperAssertMethodsAnalyzerTests.cs index 53e6281640..e2809bc1a9 100644 --- a/test/UnitTests/MSTest.Analyzers.UnitTests/UseProperAssertMethodsAnalyzerTests.cs +++ b/test/UnitTests/MSTest.Analyzers.UnitTests/UseProperAssertMethodsAnalyzerTests.cs @@ -2091,5 +2091,73 @@ await VerifyCS.VerifyCodeFixAsync( fixedCode); } + [TestMethod] + public async Task WhenAssertAreEqualWithCollectionCountUsingCustomCollection() + { + string code = """ + using System; + using System.Collections; + using System.Collections.Generic; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + internal sealed class MyCustomCollection : IEnumerable + { + public IEnumerator GetEnumerator() + { + throw new NotImplementedException(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + throw new NotImplementedException(); + } + + public int Count => 5; + } + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + var x = new MyCustomCollection(); + Assert.AreEqual(4, x.Count); + } + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, code); + } + + [TestMethod] + public async Task WhenAssertAreEqualWithCollectionCountUsingNonGenericCollection() + { + string code = """ + using System; + using System.Collections; + using System.Collections.Generic; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + var x = new Hashtable(); + Assert.AreEqual(4, x.Count); + // error CS0411: The type arguments for method 'Assert.HasCount(int, IEnumerable)' cannot be inferred from the usage. Try specifying the type arguments explicitly. + // When we add a non-generic IEnumerable overload, this test will fail because CS0411 is no longer reported. + // In that case, the analyzer should start reporting a diagnostic for the AreEqual call above. + // The codefix should suggest to switch to HasCount. + // Tracking issue https://github.com/microsoft/testfx/issues/6184. + Assert.{|CS0411:HasCount|}(4, x); + } + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, code); + } #endregion } From 0eeb7e3b17cbda840e2ea43228e0d60147cbe605 Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Tue, 5 Aug 2025 03:35:53 +0000 Subject: [PATCH 367/541] [main] Update dependencies from devdiv/DevDiv/vs-code-coverage (#6304) [main] Update dependencies from devdiv/DevDiv/vs-code-coverage --- eng/Version.Details.xml | 4 ++-- eng/Versions.props | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index af2965a2dd..2340306d32 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -13,9 +13,9 @@ https://github.com/dotnet/arcade 40693ae2ee51e447f6ca96d07bc1ba779dcb9b9c - + https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage - 3897080c69443cb675380bb3ac72cb9881dd5c87 + e653c22dca7a7603b0045551f8d370552eabfd92 https://github.com/microsoft/testfx diff --git a/eng/Versions.props b/eng/Versions.props index a6a63f73d9..60b2ba681c 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -8,7 +8,7 @@ 10.0.0-beta.25401.2 - 18.0.0-preview.25401.1 + 18.0.0-preview.25404.2 3.11.0-preview.25401.13 1.9.0-preview.25401.13 From 93c09d677b554cd9cb80fbb0bbac308253f22ac7 Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Tue, 5 Aug 2025 07:16:06 +0200 Subject: [PATCH 368/541] [main] Update dependencies from microsoft/testfx (#6305) Co-authored-by: dotnet-maestro[bot] --- eng/Version.Details.xml | 8 ++++---- eng/Versions.props | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index 2340306d32..ad24ce66b1 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -17,13 +17,13 @@ https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage e653c22dca7a7603b0045551f8d370552eabfd92 - + https://github.com/microsoft/testfx - a309c8fc8b7cf2a0bc7e411ac5506b0d2ce93d5a + f3ec4dde6ee95396a53012dad96885827b7f932b - + https://github.com/microsoft/testfx - a309c8fc8b7cf2a0bc7e411ac5506b0d2ce93d5a + f3ec4dde6ee95396a53012dad96885827b7f932b diff --git a/eng/Versions.props b/eng/Versions.props index 60b2ba681c..93adf7fa32 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -10,7 +10,7 @@ 10.0.0-beta.25401.2 18.0.0-preview.25404.2 - 3.11.0-preview.25401.13 - 1.9.0-preview.25401.13 + 3.11.0-preview.25404.3 + 1.9.0-preview.25404.3 From 07d36fd9a7959c757a9f0dade43667bdec159944 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Tue, 5 Aug 2025 19:34:09 +0200 Subject: [PATCH 369/541] Post-release changes for 3.10.1 (#6308) --- docs/Changelog-Platform.md | 20 ++++++++++++++++++++ docs/Changelog.md | 22 ++++++++++++++++++++++ samples/public/Directory.Build.props | 6 +++--- samples/public/global.json | 2 +- 4 files changed, 46 insertions(+), 4 deletions(-) diff --git a/docs/Changelog-Platform.md b/docs/Changelog-Platform.md index 91fcfbfa1b..c5fbe74f15 100644 --- a/docs/Changelog-Platform.md +++ b/docs/Changelog-Platform.md @@ -4,6 +4,26 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) +## [1.8.1] - 2025-08-05 + +See full log [of v3.10.0...v3.10.1](https://github.com/microsoft/testfx/compare/v3.10.0...v3.10.1) + +* No change, released to keep version aligned with MSTest. + +### Artifacts + +* Microsoft.Testing.Platform: [1.8.1](https://www.nuget.org/packages/Microsoft.Testing.Platform/1.8.1) +* Microsoft.Testing.Platform.MSBuild: [1.8.1](https://www.nuget.org/packages/Microsoft.Testing.Platform.MSBuild/1.8.1) +* Microsoft.Testing.Extensions.CrashDump: [1.8.1](https://www.nuget.org/packages/Microsoft.Testing.Extensions.CrashDump/1.8.1) +* Microsoft.Testing.Extensions.HangDump: [1.8.1](https://www.nuget.org/packages/Microsoft.Testing.Extensions.HangDump/1.8.1) +* Microsoft.Testing.Extensions.HotReload: [1.8.1](https://www.nuget.org/packages/Microsoft.Testing.Extensions.HotReload/1.8.1) +* Microsoft.Testing.Extensions.Retry: [1.8.1](https://www.nuget.org/packages/Microsoft.Testing.Extensions.Retry/1.8.1) +* Microsoft.Testing.Extensions.Telemetry: [1.8.1](https://www.nuget.org/packages/Microsoft.Testing.Extensions.Telemetry/1.8.1) +* Microsoft.Testing.Extensions.TrxReport: [1.8.1](https://www.nuget.org/packages/Microsoft.Testing.Extensions.TrxReport/1.8.1) +* Microsoft.Testing.Extensions.TrxReport.Abstractions: [1.8.1](https://www.nuget.org/packages/Microsoft.Testing.Extensions.TrxReport.Abstractions/1.8.1) +* Microsoft.Testing.Extensions.VSTestBridge: [1.8.1](https://www.nuget.org/packages/Microsoft.Testing.Extensions.VSTestBridge/1.8.1) +* Microsoft.Testing.Extensions.AzureDevOpsReport [1.0.0-alpha.25405.1](https://www.nuget.org/packages/Microsoft.Testing.Extensions.AzureDevOpsReport/1.0.0-alpha.25405.1) + ## [1.8.0] - 2025-07-29 See full log [of v3.9.3...v3.10.0](https://github.com/microsoft/testfx/compare/v3.9.3...v3.10.0) diff --git a/docs/Changelog.md b/docs/Changelog.md index 07b7757c2f..e183bbf85a 100644 --- a/docs/Changelog.md +++ b/docs/Changelog.md @@ -4,6 +4,28 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) +## [3.10.1] - 2025-08-05 + +See full log [of v3.10.0...v3.10.1](https://github.com/microsoft/testfx/compare/v3.10.0...v3.10.1) + +### Fixed + +* Add compat overload for GetPipeName by @Youssef1313 in [#6227](https://github.com/microsoft/testfx/pull/6227) +* Fix race in TestContextImplementation by @Youssef1313 in [#6249](https://github.com/microsoft/testfx/pull/6249) +* Fix codefix of analyzer for flowing cancellation token by @Copilot in [#6239](https://github.com/microsoft/testfx/pull/6239) +* Don't return null types from AssemblyEnumerator when ReflectionTypeLoadException is encountered by @Youssef1313 in [#6276](https://github.com/microsoft/testfx/pull/6276) +* Fix analyzer false positives for collection asserts by @Youssef1313 in [#6300](https://github.com/microsoft/testfx/pull/6300) + +### Artifacts + +* MSTest: [3.10.1](https://www.nuget.org/packages/MSTest/3.10.1) +* MSTest.TestFramework: [3.10.1](https://www.nuget.org/packages/MSTest.TestFramework/3.10.1) +* MSTest.TestAdapter: [3.10.1](https://www.nuget.org/packages/MSTest.TestAdapter/3.10.1) +* MSTest.Analyzers: [3.10.1](https://www.nuget.org/packages/MSTest.Analyzers/3.10.1) +* MSTest.Sdk: [3.10.1](https://www.nuget.org/packages/MSTest.Sdk/3.10.1) +* MSTest.SourceGeneration: [1.0.0-alpha.25405.1](https://www.nuget.org/packages/MSTest.SourceGeneration/1.0.0-alpha.25405.1) +* MSTest.Engine: [1.0.0-alpha.25405.1](https://www.nuget.org/packages/MSTest.Engine/1.0.0-alpha.25405.1) + ## [3.10.0] - 2025-07-29 See full log [of v3.9.3...v3.10.0](https://github.com/microsoft/testfx/compare/v3.9.3...v3.10.0) diff --git a/samples/public/Directory.Build.props b/samples/public/Directory.Build.props index 83c8a8c552..20019790aa 100644 --- a/samples/public/Directory.Build.props +++ b/samples/public/Directory.Build.props @@ -3,10 +3,10 @@ 9.4.0 17.14.2 - 3.10.0 - 1.0.0-alpha.25379.8 + 3.10.1 + 1.0.0-alpha.25405.1 1.54.0 - 1.8.0 + 1.8.1 17.13.0 false $(NoWarn);SA0001;EnableGenerateDocumentationFile diff --git a/samples/public/global.json b/samples/public/global.json index ede0260933..17e37be137 100644 --- a/samples/public/global.json +++ b/samples/public/global.json @@ -1,5 +1,5 @@ { "msbuild-sdks": { - "MSTest.Sdk": "3.10.0" + "MSTest.Sdk": "3.10.1" } } From 3cfe56055760c171e260b1d96f5d93d03d87d781 Mon Sep 17 00:00:00 2001 From: dotnet bot Date: Tue, 5 Aug 2025 10:49:05 -0700 Subject: [PATCH 370/541] Localized file check-in by OneLocBuild Task: Build definition ID 1218: Build ID 2765378 --- .../xlf/CodeFixResources.cs.xlf | 2 +- .../xlf/CodeFixResources.de.xlf | 2 +- .../xlf/CodeFixResources.es.xlf | 2 +- .../xlf/CodeFixResources.fr.xlf | 2 +- .../xlf/CodeFixResources.it.xlf | 2 +- .../xlf/CodeFixResources.ja.xlf | 2 +- .../xlf/CodeFixResources.ko.xlf | 2 +- .../xlf/CodeFixResources.pl.xlf | 2 +- .../xlf/CodeFixResources.pt-BR.xlf | 2 +- .../xlf/CodeFixResources.ru.xlf | 2 +- .../xlf/CodeFixResources.tr.xlf | 2 +- .../xlf/CodeFixResources.zh-Hans.xlf | 2 +- .../xlf/CodeFixResources.zh-Hant.xlf | 2 +- src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf | 8 ++++---- src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf | 4 ++-- src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf | 4 ++-- src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf | 4 ++-- src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf | 4 ++-- src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf | 4 ++-- src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf | 4 ++-- src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf | 4 ++-- src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf | 4 ++-- src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf | 4 ++-- src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf | 4 ++-- src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf | 4 ++-- src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf | 4 ++-- 26 files changed, 41 insertions(+), 41 deletions(-) diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.cs.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.cs.xlf index f37ac67ed8..6c49aec94f 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.cs.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.cs.xlf @@ -54,7 +54,7 @@ Remove 'DynamicDataSourceType' parameter to use default 'AutoDetect' - Remove 'DynamicDataSourceType' parameter to use default 'AutoDetect' + Pokud chcete použít výchozí AutoDetect, odeberte parametr DynamicDataSourceType. diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.de.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.de.xlf index 5547c7b016..3873329568 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.de.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.de.xlf @@ -54,7 +54,7 @@ Remove 'DynamicDataSourceType' parameter to use default 'AutoDetect' - Remove 'DynamicDataSourceType' parameter to use default 'AutoDetect' + Entfernen Sie den Parameter „DynamicDataSourceType“, um die Standardeinstellung „AutoDetect“ zu verwenden. diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.es.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.es.xlf index cb6b8436f2..35fd8a4a02 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.es.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.es.xlf @@ -54,7 +54,7 @@ Remove 'DynamicDataSourceType' parameter to use default 'AutoDetect' - Remove 'DynamicDataSourceType' parameter to use default 'AutoDetect' + Elimine el parámetro 'DynamicDataSourceType' para utilizar el valor predeterminado 'AutoDetect' diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.fr.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.fr.xlf index 9a67381860..a5cf0cf2bf 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.fr.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.fr.xlf @@ -54,7 +54,7 @@ Remove 'DynamicDataSourceType' parameter to use default 'AutoDetect' - Remove 'DynamicDataSourceType' parameter to use default 'AutoDetect' + Pour utiliser la valeur par défaut « AutoDetect », supprimez le paramètre « DynamicDataSourceType » diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.it.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.it.xlf index 0dafc34936..f31da6ce1f 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.it.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.it.xlf @@ -54,7 +54,7 @@ Remove 'DynamicDataSourceType' parameter to use default 'AutoDetect' - Remove 'DynamicDataSourceType' parameter to use default 'AutoDetect' + Rimuovi il parametro ''DynamicDataSourceType'' per utilizzare il valore predefinito ''AutoDetect'' diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ja.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ja.xlf index 9924ecd9af..c767a0d5de 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ja.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ja.xlf @@ -54,7 +54,7 @@ Remove 'DynamicDataSourceType' parameter to use default 'AutoDetect' - Remove 'DynamicDataSourceType' parameter to use default 'AutoDetect' + 'DynamicDataSourceType' パラメーターを削除して、既定の 'AutoDetect' を使用します diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ko.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ko.xlf index cedcce1149..c61eb3cf53 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ko.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ko.xlf @@ -54,7 +54,7 @@ Remove 'DynamicDataSourceType' parameter to use default 'AutoDetect' - Remove 'DynamicDataSourceType' parameter to use default 'AutoDetect' + 기본 'AutoDetect'를 사용하려면 'DynamicDataSourceType' 매개 변수를 제거합니다. diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pl.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pl.xlf index 3caa21908b..8679a32ddc 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pl.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pl.xlf @@ -54,7 +54,7 @@ Remove 'DynamicDataSourceType' parameter to use default 'AutoDetect' - Remove 'DynamicDataSourceType' parameter to use default 'AutoDetect' + Usuń parametr „DynamicDataSourceType”, aby użyć domyślnego elementu „AutoDetect” diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pt-BR.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pt-BR.xlf index 471b1602e5..d905b23073 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pt-BR.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pt-BR.xlf @@ -54,7 +54,7 @@ Remove 'DynamicDataSourceType' parameter to use default 'AutoDetect' - Remove 'DynamicDataSourceType' parameter to use default 'AutoDetect' + Remover o parâmetro "DynamicDataSourceType" para usar o padrão "AutoDetect" diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ru.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ru.xlf index 0cb8bcef77..e9309b69c1 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ru.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ru.xlf @@ -54,7 +54,7 @@ Remove 'DynamicDataSourceType' parameter to use default 'AutoDetect' - Remove 'DynamicDataSourceType' parameter to use default 'AutoDetect' + Удалите параметр "DynamicDataSourceType", чтобы использовать значение по умолчанию "AutoDetect" diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.tr.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.tr.xlf index 9b1c7acf17..3d7c8d0257 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.tr.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.tr.xlf @@ -54,7 +54,7 @@ Remove 'DynamicDataSourceType' parameter to use default 'AutoDetect' - Remove 'DynamicDataSourceType' parameter to use default 'AutoDetect' + Varsayılan ‘AutoDetect’ değerini kullanmak için ‘DynamicDataSourceType’ parametresini kaldırın diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hans.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hans.xlf index ec07f7bfe2..e77f1cb076 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hans.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hans.xlf @@ -54,7 +54,7 @@ Remove 'DynamicDataSourceType' parameter to use default 'AutoDetect' - Remove 'DynamicDataSourceType' parameter to use default 'AutoDetect' + 移除 ‘DynamicDataSourceType’ 参数以使用默认的 ‘AutoDetect’ diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hant.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hant.xlf index 0fe18848ae..032eb8be4c 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hant.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hant.xlf @@ -54,7 +54,7 @@ Remove 'DynamicDataSourceType' parameter to use default 'AutoDetect' - Remove 'DynamicDataSourceType' parameter to use default 'AutoDetect' + 移除 'DynamicDataSourceType' 參數,以使用預設的 'AutoDetect' diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf index 596c767c56..757d1d378c 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf @@ -149,12 +149,12 @@ Typ deklarující tyto metody by měl také respektovat následující pravidla: Remove the 'DynamicDataSourceType' argument to use the default auto detect behavior - Remove the 'DynamicDataSourceType' argument to use the default auto detect behavior + Pokud chcete použít výchozí chování automatického zjišťování, odeberte argument DynamicDataSourceType. Avoid passing an explicit 'DynamicDataSourceType' and use the default auto detect behavior - Avoid passing an explicit 'DynamicDataSourceType' and use the default auto detect behavior + Vyhněte se předávání explicitního typu DynamicDataSourceType a použijte výchozí chování automatického zjišťování. @@ -419,7 +419,7 @@ Typ deklarující tyto metody by měl také respektovat následující pravidla: '[DynamicData]' member '{0}.{1}' is a field so you should use 'DynamicDataSourceType.AutoDetect' or 'DynamicDataSourceType.Field' (auto detect is the default when not specified explicitly, and is recommended) - '[DynamicData]' member '{0}.{1}' is a field so you should use 'DynamicDataSourceType.AutoDetect' or 'DynamicDataSourceType.Field' (auto detect is the default when not specified explicitly, and is recommended) + Člen [DynamicData] {0}.{1} je pole, měli byste použít DynamicDataSourceType.AutoDetect nebo DynamicDataSourceType.Field (výchozí nastavení je automatické rozpoznávání, pokud není zadané explicitně, a je doporučeno). @@ -429,7 +429,7 @@ Typ deklarující tyto metody by měl také respektovat následující pravidla: '[DynamicData]' member '{0}.{1}' is not a property, method, or field. Only properties, methods, and fields are supported. - '[DynamicData]' member '{0}.{1}' is not a property, method, or field. Only properties, methods, and fields are supported. + Člen [DynamicData] {0}.{1} není vlastnost, metoda ani pole. Podporují se jen vlastnosti, metody a pole. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf index 26d28ceb9b..6743426439 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf @@ -149,12 +149,12 @@ Der Typ, der diese Methoden deklariert, sollte auch die folgenden Regeln beachte Remove the 'DynamicDataSourceType' argument to use the default auto detect behavior - Remove the 'DynamicDataSourceType' argument to use the default auto detect behavior + Entfernen Sie das Argument „DynamicDataSourceType“, um das standardmäßige automatische Erkennungsverhalten zu verwenden. Avoid passing an explicit 'DynamicDataSourceType' and use the default auto detect behavior - Avoid passing an explicit 'DynamicDataSourceType' and use the default auto detect behavior + Vermeiden Sie die explizite Übergabe von „DynamicDataSourceType” und verwenden Sie das standardmäßige automatische Erkennungsverhalten. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf index 24a066f204..352e39a299 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf @@ -149,12 +149,12 @@ El tipo que declara estos métodos también debe respetar las reglas siguientes: Remove the 'DynamicDataSourceType' argument to use the default auto detect behavior - Remove the 'DynamicDataSourceType' argument to use the default auto detect behavior + Elimine el argumento 'DynamicDataSourceType' para utilizar el comportamiento de detección automática predeterminado Avoid passing an explicit 'DynamicDataSourceType' and use the default auto detect behavior - Avoid passing an explicit 'DynamicDataSourceType' and use the default auto detect behavior + Evite pasar un 'DynamicDataSourceType' explícito y utilice el comportamiento de detección automática predeterminado diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf index 909fce01ba..e39e5e5d39 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf @@ -149,12 +149,12 @@ Le type doit être une classe Remove the 'DynamicDataSourceType' argument to use the default auto detect behavior - Remove the 'DynamicDataSourceType' argument to use the default auto detect behavior + Supprimez l’argument « DynamicDataSourceType » pour utiliser le comportement de détection automatique par défaut Avoid passing an explicit 'DynamicDataSourceType' and use the default auto detect behavior - Avoid passing an explicit 'DynamicDataSourceType' and use the default auto detect behavior + Évitez de passer un type « DynamicDataSourceType » explicite et utilisez le comportement de détection automatique par défaut diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf index 705406fedd..c06853d2c8 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf @@ -149,12 +149,12 @@ Anche il tipo che dichiara questi metodi deve rispettare le regole seguenti: Remove the 'DynamicDataSourceType' argument to use the default auto detect behavior - Remove the 'DynamicDataSourceType' argument to use the default auto detect behavior + Rimuovere l'argomento 'DynamicDataSourceType' per utilizzare il comportamento di rilevamento automatico predefinito Avoid passing an explicit 'DynamicDataSourceType' and use the default auto detect behavior - Avoid passing an explicit 'DynamicDataSourceType' and use the default auto detect behavior + Evitare di passare l'argomento 'DynamicDataSourceType' in modo esplicito e utilizzare il comportamento di rilevamento automatico predefinito diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf index bff683bf94..d389192ede 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf @@ -149,12 +149,12 @@ The type declaring these methods should also respect the following rules: Remove the 'DynamicDataSourceType' argument to use the default auto detect behavior - Remove the 'DynamicDataSourceType' argument to use the default auto detect behavior + 既定の自動検出動作を使用するには、'DynamicDataSourceType' 引数を削除してください Avoid passing an explicit 'DynamicDataSourceType' and use the default auto detect behavior - Avoid passing an explicit 'DynamicDataSourceType' and use the default auto detect behavior + 明示的な 'DynamicDataSourceType' を渡さず、既定の自動検出動作を使用してください diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf index 7f188bc8c8..fc7a972260 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf @@ -149,12 +149,12 @@ The type declaring these methods should also respect the following rules: Remove the 'DynamicDataSourceType' argument to use the default auto detect behavior - Remove the 'DynamicDataSourceType' argument to use the default auto detect behavior + 기본 자동 검색 동작을 사용하려면 'DynamicDataSourceType' 인수를 제거합니다. Avoid passing an explicit 'DynamicDataSourceType' and use the default auto detect behavior - Avoid passing an explicit 'DynamicDataSourceType' and use the default auto detect behavior + 명시적 'DynamicDataSourceType'을 전달하지 말고 기본 자동 검색 동작을 사용합니다. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf index 4ec67dfe46..8e9a9d5a89 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf @@ -149,12 +149,12 @@ Typ deklarujący te metody powinien również przestrzegać następujących regu Remove the 'DynamicDataSourceType' argument to use the default auto detect behavior - Remove the 'DynamicDataSourceType' argument to use the default auto detect behavior + Usuń argument „DynamicDataSourceType”, aby użyć domyślnego zachowania wykrywania automatycznego Avoid passing an explicit 'DynamicDataSourceType' and use the default auto detect behavior - Avoid passing an explicit 'DynamicDataSourceType' and use the default auto detect behavior + Unikaj przekazywania jawnego elementu „DynamicDataSourceType” i użyj domyślnego zachowania wykrywania automatycznego diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf index 2d170cd8eb..9cd4ae78f7 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf @@ -149,12 +149,12 @@ O tipo que declara esses métodos também deve respeitar as seguintes regras: Remove the 'DynamicDataSourceType' argument to use the default auto detect behavior - Remove the 'DynamicDataSourceType' argument to use the default auto detect behavior + Remova o argumento "DynamicDataSourceType" para usar o comportamento de detecção automática padrão Avoid passing an explicit 'DynamicDataSourceType' and use the default auto detect behavior - Avoid passing an explicit 'DynamicDataSourceType' and use the default auto detect behavior + Evitar passar um "DynamicDataSourceType" explícito e usar o comportamento de detecção automática padrão diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf index ace33e5ecc..3f957ef057 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf @@ -152,12 +152,12 @@ The type declaring these methods should also respect the following rules: Remove the 'DynamicDataSourceType' argument to use the default auto detect behavior - Remove the 'DynamicDataSourceType' argument to use the default auto detect behavior + Удалите аргумент DynamicDataSourceType, чтобы использовать поведение автоматического обнаружения по умолчанию Avoid passing an explicit 'DynamicDataSourceType' and use the default auto detect behavior - Avoid passing an explicit 'DynamicDataSourceType' and use the default auto detect behavior + Избегайте передачи явного DynamicDataSourceType и используйте поведение автоматического обнаружения по умолчанию diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf index d67273a437..6dece6197c 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf @@ -149,12 +149,12 @@ Bu yöntemleri bildiren tipin ayrıca aşağıdaki kurallara uyması gerekir: Remove the 'DynamicDataSourceType' argument to use the default auto detect behavior - Remove the 'DynamicDataSourceType' argument to use the default auto detect behavior + Varsayılan otomatik algılama davranışını kullanmak için ‘DynamicDataSourceType’ bağımsız değişkenini kaldırın Avoid passing an explicit 'DynamicDataSourceType' and use the default auto detect behavior - Avoid passing an explicit 'DynamicDataSourceType' and use the default auto detect behavior + Açık bir ‘DynamicDataSourceType’ geçirmeyin ve varsayılan otomatik algılama davranışını kullanın diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf index 04e7e3e394..00008832d0 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf @@ -149,12 +149,12 @@ The type declaring these methods should also respect the following rules: Remove the 'DynamicDataSourceType' argument to use the default auto detect behavior - Remove the 'DynamicDataSourceType' argument to use the default auto detect behavior + 移除 "DynamicDataSourceType" 参数以使用默认的自动检测行为 Avoid passing an explicit 'DynamicDataSourceType' and use the default auto detect behavior - Avoid passing an explicit 'DynamicDataSourceType' and use the default auto detect behavior + 避免传递显式 "DynamicDataSourceType" 并使用默认的自动检测行为 diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf index 2f19c2e8f7..3d64a914d8 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf @@ -149,12 +149,12 @@ The type declaring these methods should also respect the following rules: Remove the 'DynamicDataSourceType' argument to use the default auto detect behavior - Remove the 'DynamicDataSourceType' argument to use the default auto detect behavior + 移除 'DynamicDataSourceType' 引數,以使用預設的自動偵測行為 Avoid passing an explicit 'DynamicDataSourceType' and use the default auto detect behavior - Avoid passing an explicit 'DynamicDataSourceType' and use the default auto detect behavior + 避免傳遞明確的 'DynamicDataSourceType',並使用預設的自動偵測行為 From 8ea682d01e02b187ac17808b2af2b73e2ba348cb Mon Sep 17 00:00:00 2001 From: dotnet bot Date: Tue, 5 Aug 2025 10:53:38 -0700 Subject: [PATCH 371/541] Localized file check-in by OneLocBuild Task: Build definition ID 1218: Build ID 2765378 --- .../Resources/xlf/FrameworkMessages.cs.xlf | 10 +++++----- .../Resources/xlf/FrameworkMessages.de.xlf | 10 +++++----- .../Resources/xlf/FrameworkMessages.es.xlf | 10 +++++----- .../Resources/xlf/FrameworkMessages.fr.xlf | 10 +++++----- .../Resources/xlf/FrameworkMessages.it.xlf | 10 +++++----- .../Resources/xlf/FrameworkMessages.ja.xlf | 10 +++++----- .../Resources/xlf/FrameworkMessages.ko.xlf | 10 +++++----- .../Resources/xlf/FrameworkMessages.pl.xlf | 10 +++++----- .../Resources/xlf/FrameworkMessages.pt-BR.xlf | 10 +++++----- .../Resources/xlf/FrameworkMessages.ru.xlf | 10 +++++----- .../Resources/xlf/FrameworkMessages.tr.xlf | 10 +++++----- .../Resources/xlf/FrameworkMessages.zh-Hans.xlf | 10 +++++----- .../Resources/xlf/FrameworkMessages.zh-Hant.xlf | 10 +++++----- 13 files changed, 65 insertions(+), 65 deletions(-) diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.cs.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.cs.xlf index 1af7cdedd7..eb42733783 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.cs.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.cs.xlf @@ -42,7 +42,7 @@ {2} {3} {4} - {0}{1} + {0}{1} {2} {3} {4} @@ -50,22 +50,22 @@ Expected: - Expected: + Očekáváno: But was: - But was: + Ale bylo: String lengths are both {0} but differ at index {1}. - String lengths are both {0} but differ at index {1}. + Délky obou řetězců jsou {0}, ale liší se na indexu {1}. Expected string length {0} but was {1}. - Expected string length {0} but was {1}. + Očekávaná délka řetězce je {0}, ale byla {1}. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.de.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.de.xlf index ecfa565f11..54f6b8bb30 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.de.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.de.xlf @@ -42,7 +42,7 @@ {2} {3} {4} - {0}{1} + {0}{1} {2} {3} {4} @@ -50,22 +50,22 @@ Expected: - Expected: + Erwartet: But was: - But was: + War aber: String lengths are both {0} but differ at index {1}. - String lengths are both {0} but differ at index {1}. + Die Zeichenfolgenlängen sind beide {0}, unterscheiden sich jedoch bei Index {1}. Expected string length {0} but was {1}. - Expected string length {0} but was {1}. + Die erwartete Länge der Zeichenfolge ist {0}, war aber {1}. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.es.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.es.xlf index a9e1cf08cf..db1e3c240c 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.es.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.es.xlf @@ -42,7 +42,7 @@ {2} {3} {4} - {0}{1} + {0}{1} {2} {3} {4} @@ -50,22 +50,22 @@ Expected: - Expected: + Se esperaba: But was: - But was: + Pero fue: String lengths are both {0} but differ at index {1}. - String lengths are both {0} but differ at index {1}. + Las longitudes de las cadenas son {0} pero difieren en el índice {1}. Expected string length {0} but was {1}. - Expected string length {0} but was {1}. + Se esperaba una longitud de cadena {0} pero fue {1}. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.fr.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.fr.xlf index 04eef1a70e..e6b7647f69 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.fr.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.fr.xlf @@ -42,7 +42,7 @@ {2} {3} {4} - {0}{1} + {0}{1} {2} {3} {4} @@ -50,22 +50,22 @@ Expected: - Expected: + Attendu : But was: - But was: + Mais c'était : String lengths are both {0} but differ at index {1}. - String lengths are both {0} but differ at index {1}. + Les longueurs de chaîne sont toutes les deux {0} mais diffèrent à l’index {1}. Expected string length {0} but was {1}. - Expected string length {0} but was {1}. + La longueur de chaîne attendue {0} mais était {1}. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.it.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.it.xlf index 41c19c6e41..11ce79e9eb 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.it.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.it.xlf @@ -42,7 +42,7 @@ {2} {3} {4} - {0}{1} + {0}{1} {2} {3} {4} @@ -50,22 +50,22 @@ Expected: - Expected: + Previsto: But was: - But was: + Ma era: String lengths are both {0} but differ at index {1}. - String lengths are both {0} but differ at index {1}. + Le lunghezze delle stringhe sono entrambe {0} ma differiscono all'indice {1}. Expected string length {0} but was {1}. - Expected string length {0} but was {1}. + La lunghezza della stringa prevista è {0} ma era {1}. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ja.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ja.xlf index 68a712abf5..95eccb1dc7 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ja.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ja.xlf @@ -42,7 +42,7 @@ {2} {3} {4} - {0}{1} + {0}{1} {2} {3} {4} @@ -50,22 +50,22 @@ Expected: - Expected: + 期待値: But was: - But was: + しかし、次でした: String lengths are both {0} but differ at index {1}. - String lengths are both {0} but differ at index {1}. + 文字列の長さは両方とも {0} ですが、インデックス {1} で異なります。 Expected string length {0} but was {1}. - Expected string length {0} but was {1}. + 期待される文字列の長さは {0} ですが、実際は {1} でした。 diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ko.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ko.xlf index 0b922f5552..677e3d8784 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ko.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ko.xlf @@ -42,7 +42,7 @@ {2} {3} {4} - {0}{1} + {0}{1} {2} {3} {4} @@ -50,22 +50,22 @@ Expected: - Expected: + 예상: But was: - But was: + 그러나 다음과 같습니다. String lengths are both {0} but differ at index {1}. - String lengths are both {0} but differ at index {1}. + 문자열 길이는 둘 다 {0} 이지만 인덱스 {1}에서 다릅니다. Expected string length {0} but was {1}. - Expected string length {0} but was {1}. + 문자열 길이 {0}(을)를 예상했지만 {1}입니다. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pl.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pl.xlf index 239e2540f5..b75c6f30a3 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pl.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pl.xlf @@ -42,7 +42,7 @@ {2} {3} {4} - {0}{1} + {0}{1} {2} {3} {4} @@ -50,22 +50,22 @@ Expected: - Expected: + Oczekiwane: But was: - But was: + Ale było: String lengths are both {0} but differ at index {1}. - String lengths are both {0} but differ at index {1}. + Długości ciągów są {0}, ale różnią się w indeksie {1}. Expected string length {0} but was {1}. - Expected string length {0} but was {1}. + Oczekiwano ciągu o długości {0}, ale miał wartość {1}. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf index a45be57fc2..bd1a49ab9d 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf @@ -42,7 +42,7 @@ {2} {3} {4} - {0}{1} + {0}{1} {2} {3} {4} @@ -50,22 +50,22 @@ Expected: - Expected: + Esperado: But was: - But was: + Mas foi: String lengths are both {0} but differ at index {1}. - String lengths are both {0} but differ at index {1}. + Os comprimentos de cadeia de caracteres são ambos {0}, mas diferem no índice {1}. Expected string length {0} but was {1}. - Expected string length {0} but was {1}. + Comprimento esperado da cadeia de caracteres {0}, mas foi {1}. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ru.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ru.xlf index f50b305b65..f7fca4b5e4 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ru.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ru.xlf @@ -42,7 +42,7 @@ {2} {3} {4} - {0}{1} + {0}{1} {2} {3} {4} @@ -50,22 +50,22 @@ Expected: - Expected: + Ожидалось: But was: - But was: + Было: String lengths are both {0} but differ at index {1}. - String lengths are both {0} but differ at index {1}. + Длины строк равны {0}, но различаются по индексу {1}. Expected string length {0} but was {1}. - Expected string length {0} but was {1}. + Ожидалась длина строки: {0}, фактическая длина строки: {1}. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.tr.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.tr.xlf index 30c58a310d..9a3c18b600 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.tr.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.tr.xlf @@ -42,7 +42,7 @@ {2} {3} {4} - {0}{1} + {0}{1} {2} {3} {4} @@ -50,22 +50,22 @@ Expected: - Expected: + Beklenen: But was: - But was: + Ancak: String lengths are both {0} but differ at index {1}. - String lengths are both {0} but differ at index {1}. + Dize uzunlukları her ikisi de {0} ama dizin {1} üzerinde farklılık gösterir. Expected string length {0} but was {1}. - Expected string length {0} but was {1}. + Beklenen dize uzunluğu {0} idi, ancak dize uzunluğu {1} oldu. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf index 79a0ed8b34..2e9d053375 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf @@ -42,7 +42,7 @@ {2} {3} {4} - {0}{1} + {0}{1} {2} {3} {4} @@ -50,22 +50,22 @@ Expected: - Expected: + 应为: But was: - But was: + 但却是: String lengths are both {0} but differ at index {1}. - String lengths are both {0} but differ at index {1}. + 字符串长度均为 {0},但在索引 {1} 处有所不同。 Expected string length {0} but was {1}. - Expected string length {0} but was {1}. + 字符串长度应为 {0},但为 {1}。 diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf index 7d6a4ba72e..ce0eb0b961 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf @@ -42,7 +42,7 @@ {2} {3} {4} - {0}{1} + {0}{1} {2} {3} {4} @@ -50,22 +50,22 @@ Expected: - Expected: + 預期為: But was: - But was: + 但為: String lengths are both {0} but differ at index {1}. - String lengths are both {0} but differ at index {1}. + 字串長度兩者都是 {0},但索引 {1} 不同。 Expected string length {0} but was {1}. - Expected string length {0} but was {1}. + 預期的字串長度為 {0},但為 {1}。 From f51f61ee09a7d13831f56d79f8c03997128d34dd Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Wed, 6 Aug 2025 04:16:31 +0000 Subject: [PATCH 372/541] [main] Update dependencies from devdiv/DevDiv/vs-code-coverage (#6314) [main] Update dependencies from devdiv/DevDiv/vs-code-coverage --- eng/Version.Details.xml | 4 ++-- eng/Versions.props | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index ad24ce66b1..0a1e09f443 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -13,9 +13,9 @@ https://github.com/dotnet/arcade 40693ae2ee51e447f6ca96d07bc1ba779dcb9b9c - + https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage - e653c22dca7a7603b0045551f8d370552eabfd92 + dd05eb43b1eaa5b16698ba7d5fb1927678c8e162 https://github.com/microsoft/testfx diff --git a/eng/Versions.props b/eng/Versions.props index 93adf7fa32..f746a45c95 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -8,7 +8,7 @@ 10.0.0-beta.25401.2 - 18.0.0-preview.25404.2 + 18.0.0-preview.25405.2 3.11.0-preview.25404.3 1.9.0-preview.25404.3 From a9a14aea8cfb9fa2c95f2637f1d722f4684c3f17 Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Wed, 6 Aug 2025 06:31:04 +0200 Subject: [PATCH 373/541] [main] Update dependencies from microsoft/testfx (#6315) Co-authored-by: dotnet-maestro[bot] --- eng/Version.Details.xml | 8 ++++---- eng/Versions.props | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index 0a1e09f443..a7919e826b 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -17,13 +17,13 @@ https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage dd05eb43b1eaa5b16698ba7d5fb1927678c8e162 - + https://github.com/microsoft/testfx - f3ec4dde6ee95396a53012dad96885827b7f932b + 07d36fd9a7959c757a9f0dade43667bdec159944 - + https://github.com/microsoft/testfx - f3ec4dde6ee95396a53012dad96885827b7f932b + 07d36fd9a7959c757a9f0dade43667bdec159944 diff --git a/eng/Versions.props b/eng/Versions.props index f746a45c95..49b3059759 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -10,7 +10,7 @@ 10.0.0-beta.25401.2 18.0.0-preview.25405.2 - 3.11.0-preview.25404.3 - 1.9.0-preview.25404.3 + 3.11.0-preview.25405.2 + 1.9.0-preview.25405.2 From 6dd46d8e11f925599e765ab85d7302a558f2a172 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Wed, 6 Aug 2025 09:12:33 +0200 Subject: [PATCH 374/541] Fix missing "throw" for unreachable code path in FormatStringComparisonMessage (#6299) --- src/TestFramework/TestFramework/Assertions/Assert.AreEqual.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/TestFramework/TestFramework/Assertions/Assert.AreEqual.cs b/src/TestFramework/TestFramework/Assertions/Assert.AreEqual.cs index 637039dd8e..6bb911e170 100644 --- a/src/TestFramework/TestFramework/Assertions/Assert.AreEqual.cs +++ b/src/TestFramework/TestFramework/Assertions/Assert.AreEqual.cs @@ -723,7 +723,7 @@ private static string FormatStringComparisonMessage(string? expected, string? ac if (diffIndex == -1) { // Strings are equal - should not happen in practice, we call this method only when they are not equal. - ApplicationStateGuard.Unreachable(); + throw ApplicationStateGuard.Unreachable(); } // Format the enhanced string comparison message From 7d9da5e7e1d2fa6a2a4f019c516b3aeddc70f0ef Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Wed, 6 Aug 2025 11:01:02 +0200 Subject: [PATCH 375/541] Performance: Reduce unnecessary logic in UpdateInfoIfTestInitializeOrCleanupMethod (#6318) --- .../Execution/TypeCache.cs | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Execution/TypeCache.cs b/src/Adapter/MSTestAdapter.PlatformServices/Execution/TypeCache.cs index b6ff25d055..e46ddd25b9 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Execution/TypeCache.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Execution/TypeCache.cs @@ -314,7 +314,7 @@ private TestClassInfo CreateClassInfo(Type classType) // which is used to decide whether TestInitialize/TestCleanup methods // present in the base type should be used or not. They are not used if // the method is overridden in the derived type. - var instanceMethods = new Dictionary(); + HashSet? instanceMethods = classType.BaseType == typeof(object) ? null : []; foreach (MethodInfo methodInfo in PlatformServiceProvider.Instance.ReflectionOperations.GetDeclaredMethods(classType)) { @@ -621,16 +621,16 @@ private void UpdateInfoIfTestInitializeOrCleanupMethod( TestClassInfo classInfo, MethodInfo methodInfo, bool isBase, - Dictionary instanceMethods) + HashSet? instanceMethods) { bool hasTestInitialize = _reflectionHelper.IsAttributeDefined(methodInfo, inherit: false); bool hasTestCleanup = _reflectionHelper.IsAttributeDefined(methodInfo, inherit: false); if (!hasTestCleanup && !hasTestInitialize) { - if (methodInfo.HasCorrectTestInitializeOrCleanupSignature()) + if (instanceMethods is not null && methodInfo.HasCorrectTestInitializeOrCleanupSignature()) { - instanceMethods[methodInfo.Name] = null; + instanceMethods.Add(methodInfo.Name); } return; @@ -655,7 +655,7 @@ private void UpdateInfoIfTestInitializeOrCleanupMethod( } else { - if (!instanceMethods.ContainsKey(methodInfo.Name)) + if (instanceMethods is not null && !instanceMethods.Contains(methodInfo.Name)) { classInfo.BaseTestInitializeMethodsQueue.Enqueue(methodInfo); } @@ -675,14 +675,14 @@ private void UpdateInfoIfTestInitializeOrCleanupMethod( } else { - if (!instanceMethods.ContainsKey(methodInfo.Name)) + if (instanceMethods is not null && !instanceMethods.Contains(methodInfo.Name)) { classInfo.BaseTestCleanupMethodsQueue.Enqueue(methodInfo); } } } - instanceMethods[methodInfo.Name] = null; + instanceMethods?.Add(methodInfo.Name); } /// From c7d4bc496f1b503ceca62ed62df822124b79d45d Mon Sep 17 00:00:00 2001 From: Muiz Atolagbe <46275427+AtolagbeMuiz@users.noreply.github.com> Date: Wed, 6 Aug 2025 10:05:28 +0100 Subject: [PATCH 376/541] Made changes to dev-guide (#6254) Co-authored-by: Youssef Victor --- docs/dev-guide.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/dev-guide.md b/docs/dev-guide.md index 515bfeb946..a5fbeed98d 100644 --- a/docs/dev-guide.md +++ b/docs/dev-guide.md @@ -166,3 +166,7 @@ Note that `-test` allows to run the unit tests and `-integrationTest` allows to If you are working with Visual Studio, we recommend opening it through the `open-vs.cmd` script at the repo root. This script will set all the required environment variables required so that Visual Studio picks up the locally downloaded version of the .NET SDK. If you prefer to use your machine-wide configuration, you can open Visual Studio directly. Inside Visual Studio, all projects can be built normally. All but acceptance tests can be tested directly from Visual Studio. The acceptance tests will always use the version of the NuGet packages produced in the `artifacts/packages/shipping` folder so if you have made some changes and run these tests, it's likely that the changes will not be applied. + +## Visual Studio version requirement + +If working with Visual Studio, this repository uses the new, modern, XML-based slnx solution file format (`TestFx.slnx`). This solution file can only be opened or loaded successfully using Visual Studio 2022 17.13 or higher. Opening the TestFx.slnx directly with a different version of Visual Studio installed other than Visual Studio 2022 17.13 or higher will just open the slnx file in a raw solution XML format. From 429c40332cddc486390163b836f48d1811f9cd1e Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Thu, 7 Aug 2025 07:23:51 +0200 Subject: [PATCH 377/541] [main] Update dependencies from microsoft/testfx (#6322) Co-authored-by: dotnet-maestro[bot] --- eng/Version.Details.xml | 8 ++++---- eng/Versions.props | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index a7919e826b..8ae24967a1 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -17,13 +17,13 @@ https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage dd05eb43b1eaa5b16698ba7d5fb1927678c8e162 - + https://github.com/microsoft/testfx - 07d36fd9a7959c757a9f0dade43667bdec159944 + c7d4bc496f1b503ceca62ed62df822124b79d45d - + https://github.com/microsoft/testfx - 07d36fd9a7959c757a9f0dade43667bdec159944 + c7d4bc496f1b503ceca62ed62df822124b79d45d diff --git a/eng/Versions.props b/eng/Versions.props index 49b3059759..3bb46770fb 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -10,7 +10,7 @@ 10.0.0-beta.25401.2 18.0.0-preview.25405.2 - 3.11.0-preview.25405.2 - 1.9.0-preview.25405.2 + 3.11.0-preview.25406.4 + 1.9.0-preview.25406.4 From 89636921f8c209d870d8f8b102d306081b3f28d6 Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Thu, 7 Aug 2025 05:45:50 +0000 Subject: [PATCH 378/541] [main] Update dependencies from devdiv/DevDiv/vs-code-coverage (#6321) [main] Update dependencies from devdiv/DevDiv/vs-code-coverage --- eng/Version.Details.xml | 4 ++-- eng/Versions.props | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index 8ae24967a1..d90c696735 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -13,9 +13,9 @@ https://github.com/dotnet/arcade 40693ae2ee51e447f6ca96d07bc1ba779dcb9b9c - + https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage - dd05eb43b1eaa5b16698ba7d5fb1927678c8e162 + 288c5f9d739ec170567f2b09c4f86cc168529a8d https://github.com/microsoft/testfx diff --git a/eng/Versions.props b/eng/Versions.props index 3bb46770fb..060e4f1f63 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -8,7 +8,7 @@ 10.0.0-beta.25401.2 - 18.0.0-preview.25405.2 + 18.0.0-preview.25406.1 3.11.0-preview.25406.4 1.9.0-preview.25406.4 From e1f0a9d0bde8b48c4fbc69737642c1026f1ad062 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Thu, 7 Aug 2025 09:24:15 +0200 Subject: [PATCH 379/541] Avoid ManagedNameHelper when possible (#6319) --- .../Discovery/AssemblyEnumerator.cs | 17 +++++++++++------ .../Discovery/TypeEnumerator.cs | 6 +++++- .../Discovery/UnitTestDiscoverer.cs | 12 ------------ .../Execution/TypeCache.cs | 15 ++++++++++++++- .../Extensions/TestCaseExtensions.cs | 9 +++++---- .../ObjectModel/TestMethod.cs | 7 +++++-- .../ObjectModel/UnitTestElement.cs | 2 ++ 7 files changed, 42 insertions(+), 26 deletions(-) diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Discovery/AssemblyEnumerator.cs b/src/Adapter/MSTestAdapter.PlatformServices/Discovery/AssemblyEnumerator.cs index c11031c378..f960d7909f 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Discovery/AssemblyEnumerator.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Discovery/AssemblyEnumerator.cs @@ -303,7 +303,7 @@ static UnitTestElement GetAssemblyFixtureTest(MethodInfo methodInfo, string asse { string methodName = GetMethodName(methodInfo); string[] hierarchy = [null!, assemblyName, EngineConstants.AssemblyFixturesHierarchyClassName, methodName]; - return GetFixtureTest(classFullName, assemblyLocation, fixtureType, methodName, hierarchy); + return GetFixtureTest(classFullName, assemblyLocation, fixtureType, methodName, hierarchy, methodInfo); } static UnitTestElement GetClassFixtureTest(MethodInfo methodInfo, string classFullName, @@ -311,7 +311,7 @@ static UnitTestElement GetClassFixtureTest(MethodInfo methodInfo, string classFu { string methodName = GetMethodName(methodInfo); string[] hierarchy = [null!, classFullName, methodName]; - return GetFixtureTest(classFullName, assemblyLocation, fixtureType, methodName, hierarchy); + return GetFixtureTest(classFullName, assemblyLocation, fixtureType, methodName, hierarchy, methodInfo); } static string GetMethodName(MethodInfo methodInfo) @@ -322,12 +322,16 @@ static string GetMethodName(MethodInfo methodInfo) : methodInfo.Name; } - static UnitTestElement GetFixtureTest(string classFullName, string assemblyLocation, string fixtureType, string methodName, string[] hierarchy) + static UnitTestElement GetFixtureTest(string classFullName, string assemblyLocation, string fixtureType, string methodName, string[] hierarchy, MethodInfo methodInfo) { - var method = new TestMethod(classFullName, methodName, hierarchy, methodName, classFullName, assemblyLocation, null, TestIdGenerationStrategy.FullyQualified); + string displayName = $"[{fixtureType}] {methodName}"; + var method = new TestMethod(classFullName, methodName, hierarchy, methodName, classFullName, assemblyLocation, displayName, TestIdGenerationStrategy.FullyQualified) + { + MethodInfo = methodInfo, + }; return new UnitTestElement(method) { - DisplayName = $"[{fixtureType}] {methodName}", + DisplayName = displayName, Traits = [new Trait(EngineConstants.FixturesTestTrait, fixtureType)], }; } @@ -423,7 +427,7 @@ private static bool TryUnfoldITestDataSource(ITestDataSource dataSource, TestDat discoveredTest.TestMethod.DataType = DynamicDataType.None; discoveredTest.TestMethod.TestDataSourceIgnoreMessage = testDataSourceIgnoreMessage; discoveredTest.DisplayName = dataSource.GetDisplayName(methodInfo, null) ?? discoveredTest.DisplayName; - + discoveredTest.TestMethod.DisplayName = discoveredTest.DisplayName ?? discoveredTest.TestMethod.DisplayName; tests.Add(discoveredTest); return true; @@ -464,6 +468,7 @@ private static bool TryUnfoldITestDataSource(ITestDataSource dataSource, TestDat UnitTestElement discoveredTest = test.Clone(); discoveredTest.DisplayName = displayNameFromTestDataRow ?? dataSource.GetDisplayName(methodInfo, d) ?? discoveredTest.DisplayName; + discoveredTest.TestMethod.DisplayName = discoveredTest.DisplayName ?? discoveredTest.TestMethod.DisplayName; // Merge test categories from the test data row with the existing categories if (testCategoriesFromTestDataRow is { Count: > 0 }) diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Discovery/TypeEnumerator.cs b/src/Adapter/MSTestAdapter.PlatformServices/Discovery/TypeEnumerator.cs index 8b7e0db86c..b5bad75071 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Discovery/TypeEnumerator.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Discovery/TypeEnumerator.cs @@ -130,7 +130,10 @@ internal UnitTestElement GetTestFromMethod(MethodInfo method, bool isDeclaredInT ManagedNameHelper.GetManagedName(method, out string managedType, out string managedMethod, out string?[]? hierarchyValues); hierarchyValues[HierarchyConstants.Levels.ContainerIndex] = null; // This one will be set by test windows to current test project name. - var testMethod = new TestMethod(managedType, managedMethod, hierarchyValues, method.Name, _type.FullName!, _assemblyFilePath, null, _testIdGenerationStrategy); + var testMethod = new TestMethod(managedType, managedMethod, hierarchyValues, method.Name, _type.FullName!, _assemblyFilePath, null, _testIdGenerationStrategy) + { + MethodInfo = method, + }; if (!string.Equals(method.DeclaringType!.FullName, _type.FullName, StringComparison.Ordinal)) { @@ -189,6 +192,7 @@ internal UnitTestElement GetTestFromMethod(MethodInfo method, bool isDeclaredInT // get DisplayName from TestMethodAttribute (or any inherited attribute) testElement.DisplayName = testMethodAttribute?.DisplayName ?? method.Name; + testMethod.DisplayName = testElement.DisplayName; return testElement; } diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Discovery/UnitTestDiscoverer.cs b/src/Adapter/MSTestAdapter.PlatformServices/Discovery/UnitTestDiscoverer.cs index 79a2d02642..2de1b9dcb4 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Discovery/UnitTestDiscoverer.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Discovery/UnitTestDiscoverer.cs @@ -85,13 +85,6 @@ internal virtual void DiscoverTestsInSource( SendTestCases(source, testElements, discoverySink, discoveryContext, logger); } -#pragma warning disable IDE0028 // Collection initialization can be simplified - cannot be done for all TFMs. So suppressing. - private static readonly ConditionalWeakTable TestCaseToDataDictionary = new(); -#pragma warning restore IDE0028 // Collection initialization can be simplified - - internal static bool TryGetActualData(TestCase testCase, [NotNullWhen(true)] out object?[]? actualData) - => TestCaseToDataDictionary.TryGetValue(testCase, out actualData); - internal void SendTestCases(string source, IEnumerable testElements, ITestCaseDiscoverySink discoverySink, IDiscoveryContext? discoveryContext, IMessageLogger logger) { bool shouldCollectSourceInformation = MSTestSettings.RunConfigurationSettings.CollectSourceInformation; @@ -130,11 +123,6 @@ internal void SendTestCases(string source, IEnumerable testElem continue; } - if (testElement.TestMethod.ActualData is { } actualData) - { - TestCaseToDataDictionary.Add(testCase, actualData); - } - if (!hasAnyRunnableTests) { hasAnyRunnableTests = !hasFixtureTraits; diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Execution/TypeCache.cs b/src/Adapter/MSTestAdapter.PlatformServices/Execution/TypeCache.cs index e46ddd25b9..9749a81a4d 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Execution/TypeCache.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Execution/TypeCache.cs @@ -747,7 +747,10 @@ private MethodInfo GetMethodInfoForTestMethod(TestMethod testMethod, TestClassIn MethodBase? methodBase = null; try { - methodBase = ManagedNameHelper.GetMethod(testClassInfo.Parent.Assembly, testMethod.ManagedTypeName!, testMethod.ManagedMethodName!); + // testMethod.MethodInfo can be null if 'TestMethod' instance crossed app domain boundaries. + // This happens on .NET Framework when app domain is enabled, and the MethodInfo is calculated and set during discovery. + // Then, execution will cause TestMethod to cross to a different app domain, and MethodInfo will be null. + methodBase = testMethod.MethodInfo ?? ManagedNameHelper.GetMethod(testClassInfo.Parent.Assembly, testMethod.ManagedTypeName!, testMethod.ManagedMethodName!); } catch (InvalidManagedNameException) { @@ -773,6 +776,16 @@ private MethodInfo GetMethodInfoForTestMethod(TestMethod testMethod, TestClassIn private static MethodInfo? GetMethodInfoUsingRuntimeMethods(TestMethod testMethod, TestClassInfo testClassInfo, bool discoverInternals) { + // testMethod.MethodInfo can be null if 'TestMethod' instance crossed app domain boundaries. + // This happens on .NET Framework when app domain is enabled, and the MethodInfo is calculated and set during discovery. + // Then, execution will cause TestMethod to cross to a different app domain, and MethodInfo will be null. + // Note: This whole GetMethodInfoUsingRuntimeMethods is likely never reachable. + // It's called if HasManagedMethodAndTypeProperties is false, but it should always be true per the current implementation. + if (testMethod.MethodInfo is { } methodInfo) + { + return methodInfo.HasCorrectTestMethodSignature(true, discoverInternals) ? methodInfo : null; + } + IEnumerable methods = PlatformServiceProvider.Instance.ReflectionOperations.GetRuntimeMethods(testClassInfo.ClassType) .Where(method => method.Name == testMethod.Name && method.HasCorrectTestMethodSignature(true, discoverInternals)); diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Extensions/TestCaseExtensions.cs b/src/Adapter/MSTestAdapter.PlatformServices/Extensions/TestCaseExtensions.cs index a016393e82..28719dfc74 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Extensions/TestCaseExtensions.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Extensions/TestCaseExtensions.cs @@ -70,6 +70,11 @@ internal static string GetTestName(this TestCase testCase, string? testClassName /// The converted . internal static UnitTestElement ToUnitTestElement(this TestCase testCase, string source) { + if (testCase.LocalExtensionData is UnitTestElement unitTestElement) + { + return unitTestElement; + } + string? testClassName = testCase.GetPropertyValue(EngineConstants.TestClassNameProperty) as string; string name = testCase.GetTestName(testClassName); var testIdGenerationStrategy = (TestIdGenerationStrategy)testCase.GetPropertyValue( @@ -86,10 +91,6 @@ internal static UnitTestElement ToUnitTestElement(this TestCase testCase, string testMethod.DataType = dataType; testMethod.SerializedData = data; - if (UnitTestDiscoverer.TryGetActualData(testCase, out object?[]? actualData)) - { - testMethod.ActualData = actualData; - } testMethod.TestDataSourceIgnoreMessage = testCase.GetPropertyValue(EngineConstants.TestDataSourceIgnoreMessageProperty) as string; } diff --git a/src/Adapter/MSTestAdapter.PlatformServices/ObjectModel/TestMethod.cs b/src/Adapter/MSTestAdapter.PlatformServices/ObjectModel/TestMethod.cs index 92eaf123e3..5ac8e29b26 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/ObjectModel/TestMethod.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/ObjectModel/TestMethod.cs @@ -153,6 +153,9 @@ public string? DeclaringClassFullName [field: NonSerialized] internal object?[]? ActualData { get; set; } + [field: NonSerialized] + internal MethodInfo? MethodInfo { get; set; } + /// /// Gets or sets the test data source ignore message. /// @@ -167,9 +170,9 @@ public string? DeclaringClassFullName internal string? TestGroup { get; set; } /// - /// Gets the display name set during discovery. + /// Gets or sets the display name set during discovery. /// - internal string DisplayName { get; } + internal string DisplayName { get; set; } internal TestMethod Clone() => (TestMethod)MemberwiseClone(); } diff --git a/src/Adapter/MSTestAdapter.PlatformServices/ObjectModel/UnitTestElement.cs b/src/Adapter/MSTestAdapter.PlatformServices/ObjectModel/UnitTestElement.cs index aa7fd4ec74..e4d9877c4d 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/ObjectModel/UnitTestElement.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/ObjectModel/UnitTestElement.cs @@ -62,6 +62,7 @@ public UnitTestElement(TestMethod testMethod) /// /// Gets or sets the DisplayName. /// + // TODO: Remove this property and simply use TestMethod.DisplayName public string? DisplayName { get; set; } /// @@ -111,6 +112,7 @@ internal TestCase ToTestCase() TestCase testCase = new(testFullName, EngineConstants.ExecutorUri, TestMethod.AssemblyName) { DisplayName = GetDisplayName(), + LocalExtensionData = this, }; if (TestMethod.HasManagedMethodAndTypeProperties) From 6f57c7d5237e7a8e2ddab19337ce72dc27234c27 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Thu, 7 Aug 2025 11:10:28 +0200 Subject: [PATCH 380/541] Revert Assert.That obsoletion (#6323) --- .../TestFramework/Assertions/Assert.cs | 18 +----------------- .../Assertions/CollectionAssert.cs | 18 +----------------- .../TestFramework/Assertions/StringAssert.cs | 18 +----------------- .../PublicAPI/PublicAPI.Unshipped.txt | 3 +++ .../FxExtensibilityTestProject/AssertExTest.cs | 8 ++++---- .../Assertions/AssertTests.cs | 4 ++-- .../Assertions/CollectionAssertTests.cs | 4 ++-- .../Assertions/StringAssertTests.cs | 4 ++-- 8 files changed, 16 insertions(+), 61 deletions(-) diff --git a/src/TestFramework/TestFramework/Assertions/Assert.cs b/src/TestFramework/TestFramework/Assertions/Assert.cs index ba2c122a2c..9d5e9ccdae 100644 --- a/src/TestFramework/TestFramework/Assertions/Assert.cs +++ b/src/TestFramework/TestFramework/Assertions/Assert.cs @@ -14,17 +14,6 @@ private Assert() { } - /// - /// Gets the singleton instance of the Assert functionality. - /// - /// - /// Users can use this to plug-in custom assertions through C# extension methods. - /// For instance, the signature of a custom assertion provider could be "public static void IsOfType<T>(this Assert assert, object obj)" - /// Users could then use a syntax similar to the default assertions which in this case is "Assert.Instance.IsOfType<Dog>(animal);" - /// More documentation is at "https://github.com/Microsoft/testfx/docs/README.md". - /// - public static Assert Instance { get; } = new Assert(); - /// /// Gets the singleton instance of the Assert functionality. /// @@ -34,12 +23,7 @@ private Assert() /// Users could then use a syntax similar to the default assertions which in this case is "Assert.That.IsOfType<Dog>(animal);" /// More documentation is at "https://github.com/Microsoft/testfx/docs/README.md". /// -#if NET6_0_OR_GREATER - [Obsolete(FrameworkConstants.ThatPropertyObsoleteMessage, DiagnosticId = "MSTESTOBS")] -#else - [Obsolete(FrameworkConstants.ThatPropertyObsoleteMessage)] -#endif - public static Assert That => Instance; + public static Assert That { get; } = new(); /// /// Replaces null characters ('\0') with "\\0". diff --git a/src/TestFramework/TestFramework/Assertions/CollectionAssert.cs b/src/TestFramework/TestFramework/Assertions/CollectionAssert.cs index bb65e2780e..bc8104a47c 100644 --- a/src/TestFramework/TestFramework/Assertions/CollectionAssert.cs +++ b/src/TestFramework/TestFramework/Assertions/CollectionAssert.cs @@ -16,17 +16,6 @@ private CollectionAssert() { } - /// - /// Gets the singleton instance of the CollectionAssert functionality. - /// - /// - /// Users can use this to plug-in custom assertions through C# extension methods. - /// For instance, the signature of a custom assertion provider could be "public static void AreEqualUnordered(this CollectionAssert customAssert, ICollection expected, ICollection actual)" - /// Users could then use a syntax similar to the default assertions which in this case is "CollectionAssert.Instance.AreEqualUnordered(list1, list2);" - /// More documentation is at "https://github.com/Microsoft/testfx/docs/README.md". - /// - public static CollectionAssert Instance { get; } = new CollectionAssert(); - /// /// Gets the singleton instance of the CollectionAssert functionality. /// @@ -36,12 +25,7 @@ private CollectionAssert() /// Users could then use a syntax similar to the default assertions which in this case is "CollectionAssert.That.AreEqualUnordered(list1, list2);" /// More documentation is at "https://github.com/Microsoft/testfx/docs/README.md". /// -#if NET6_0_OR_GREATER - [Obsolete(FrameworkConstants.ThatPropertyObsoleteMessage, DiagnosticId = "MSTESTOBS")] -#else - [Obsolete(FrameworkConstants.ThatPropertyObsoleteMessage)] -#endif - public static CollectionAssert That => Instance; + public static CollectionAssert That { get; } = new(); #endregion diff --git a/src/TestFramework/TestFramework/Assertions/StringAssert.cs b/src/TestFramework/TestFramework/Assertions/StringAssert.cs index a70c740716..741076b7c6 100644 --- a/src/TestFramework/TestFramework/Assertions/StringAssert.cs +++ b/src/TestFramework/TestFramework/Assertions/StringAssert.cs @@ -16,17 +16,6 @@ private StringAssert() { } - /// - /// Gets the singleton instance of the StringAssert functionality. - /// - /// - /// Users can use this to plug-in custom assertions through C# extension methods. - /// For instance, the signature of a custom assertion provider could be "public static void ContainsWords(this StringAssert customAssert, string value, ICollection substrings)" - /// Users could then use a syntax similar to the default assertions which in this case is "StringAssert.Instance.ContainsWords(value, substrings);" - /// More documentation is at "https://github.com/Microsoft/testfx/docs/README.md". - /// - public static StringAssert Instance { get; } = new StringAssert(); - /// /// Gets the singleton instance of the StringAssert functionality. /// @@ -36,12 +25,7 @@ private StringAssert() /// Users could then use a syntax similar to the default assertions which in this case is "StringAssert.That.ContainsWords(value, substrings);" /// More documentation is at "https://github.com/Microsoft/testfx/docs/README.md". /// -#if NET6_0_OR_GREATER - [Obsolete(FrameworkConstants.ThatPropertyObsoleteMessage, DiagnosticId = "MSTESTOBS")] -#else - [Obsolete(FrameworkConstants.ThatPropertyObsoleteMessage)] -#endif - public static StringAssert That => Instance; + public static StringAssert That { get; } = new(); #endregion diff --git a/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Unshipped.txt b/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Unshipped.txt index 880fc26f4b..7d27ebf1af 100644 --- a/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Unshipped.txt +++ b/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Unshipped.txt @@ -1,2 +1,5 @@ #nullable enable Microsoft.VisualStudio.TestTools.UnitTesting.DynamicDataSourceType.Field = 3 -> Microsoft.VisualStudio.TestTools.UnitTesting.DynamicDataSourceType +*REMOVED*static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.Instance.get -> Microsoft.VisualStudio.TestTools.UnitTesting.Assert! +*REMOVED*static Microsoft.VisualStudio.TestTools.UnitTesting.CollectionAssert.Instance.get -> Microsoft.VisualStudio.TestTools.UnitTesting.CollectionAssert! +*REMOVED*static Microsoft.VisualStudio.TestTools.UnitTesting.StringAssert.Instance.get -> Microsoft.VisualStudio.TestTools.UnitTesting.StringAssert! diff --git a/test/IntegrationTests/TestAssets/FxExtensibilityTestProject/AssertExTest.cs b/test/IntegrationTests/TestAssets/FxExtensibilityTestProject/AssertExTest.cs index e6852bc745..37e0f8709f 100644 --- a/test/IntegrationTests/TestAssets/FxExtensibilityTestProject/AssertExTest.cs +++ b/test/IntegrationTests/TestAssets/FxExtensibilityTestProject/AssertExTest.cs @@ -11,16 +11,16 @@ namespace FxExtensibilityTestProject; public class AssertExTest { [TestMethod] - public void BasicAssertExtensionTest() => Assert.Instance.IsOfType(new ArgumentOutOfRangeException()); + public void BasicAssertExtensionTest() => Assert.That.IsOfType(new ArgumentOutOfRangeException()); [TestMethod] [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] - public void BasicFailingAssertExtensionTest() => Assert.Instance.IsOfType(new ArgumentNullException()); + public void BasicFailingAssertExtensionTest() => Assert.That.IsOfType(new ArgumentNullException()); [TestMethod] - public void ChainedAssertExtensionTest() => Assert.Instance.Is().Divisor(120, 5); + public void ChainedAssertExtensionTest() => Assert.That.Is().Divisor(120, 5); [TestMethod] [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] - public void ChainedFailingAssertExtensionTest() => Assert.Instance.Is().Positive(-10); + public void ChainedFailingAssertExtensionTest() => Assert.That.Is().Positive(-10); } diff --git a/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.cs b/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.cs index c14d13fe4c..6c1efaf5ce 100644 --- a/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.cs +++ b/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.cs @@ -6,9 +6,9 @@ namespace Microsoft.VisualStudio.TestPlatform.TestFramework.UnitTests; public partial class AssertTests { #region Instance tests - public void InstanceShouldReturnAnInstanceOfAssert() => Verify(Assert.Instance is not null); + public void InstanceShouldReturnAnInstanceOfAssert() => Verify(Assert.That is not null); - public void InstanceShouldCacheAssertInstance() => Verify(ReferenceEquals(Assert.Instance, Assert.Instance)); + public void InstanceShouldCacheAssertInstance() => Verify(ReferenceEquals(Assert.That, Assert.That)); #endregion #region ReplaceNullChars tests diff --git a/test/UnitTests/TestFramework.UnitTests/Assertions/CollectionAssertTests.cs b/test/UnitTests/TestFramework.UnitTests/Assertions/CollectionAssertTests.cs index 66131b5ec1..50c4cfa2dd 100644 --- a/test/UnitTests/TestFramework.UnitTests/Assertions/CollectionAssertTests.cs +++ b/test/UnitTests/TestFramework.UnitTests/Assertions/CollectionAssertTests.cs @@ -9,9 +9,9 @@ namespace Microsoft.VisualStudio.TestPlatform.TestFramework.UnitTests.Assertions public class CollectionAssertTests : TestContainer { - public void InstanceShouldReturnAnInstanceOfCollectionAssert() => Verify(CollectionAssert.Instance is not null); + public void InstanceShouldReturnAnInstanceOfCollectionAssert() => Verify(CollectionAssert.That is not null); - public void InstanceShouldCacheCollectionAssertInstance() => Verify(CollectionAssert.Instance == CollectionAssert.Instance); + public void InstanceShouldCacheCollectionAssertInstance() => Verify(CollectionAssert.That == CollectionAssert.That); public void CollectionAssertContainsNullabilityPostConditions() { diff --git a/test/UnitTests/TestFramework.UnitTests/Assertions/StringAssertTests.cs b/test/UnitTests/TestFramework.UnitTests/Assertions/StringAssertTests.cs index 0f9469d391..49002e6b66 100644 --- a/test/UnitTests/TestFramework.UnitTests/Assertions/StringAssertTests.cs +++ b/test/UnitTests/TestFramework.UnitTests/Assertions/StringAssertTests.cs @@ -7,9 +7,9 @@ namespace Microsoft.VisualStudio.TestPlatform.TestFramework.UnitTests.Assertions public class StringAssertTests : TestContainer { - public void InstanceShouldReturnAnInstanceOfStringAssert() => Verify(StringAssert.Instance is not null); + public void InstanceShouldReturnAnInstanceOfStringAssert() => Verify(StringAssert.That is not null); - public void InstanceShouldCacheStringAssertInstance() => Verify(StringAssert.Instance == StringAssert.Instance); + public void InstanceShouldCacheStringAssertInstance() => Verify(StringAssert.That == StringAssert.That); public void StringAssertContains() { From 7162bf85921074796dfa2b6f2597c602974a9063 Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Fri, 8 Aug 2025 06:40:32 +0200 Subject: [PATCH 381/541] [main] Update dependencies from microsoft/testfx (#6328) Co-authored-by: dotnet-maestro[bot] --- eng/Version.Details.xml | 8 ++++---- eng/Versions.props | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index d90c696735..cd85aca2a0 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -17,13 +17,13 @@ https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage 288c5f9d739ec170567f2b09c4f86cc168529a8d - + https://github.com/microsoft/testfx - c7d4bc496f1b503ceca62ed62df822124b79d45d + e1f0a9d0bde8b48c4fbc69737642c1026f1ad062 - + https://github.com/microsoft/testfx - c7d4bc496f1b503ceca62ed62df822124b79d45d + e1f0a9d0bde8b48c4fbc69737642c1026f1ad062 diff --git a/eng/Versions.props b/eng/Versions.props index 060e4f1f63..4b6b2cb578 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -10,7 +10,7 @@ 10.0.0-beta.25401.2 18.0.0-preview.25406.1 - 3.11.0-preview.25406.4 - 1.9.0-preview.25406.4 + 3.11.0-preview.25407.1 + 1.9.0-preview.25407.1 From a995127b79cb0691333b8ec172128ac5e7abb9b2 Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Sat, 9 Aug 2025 03:27:33 +0000 Subject: [PATCH 382/541] [main] Update dependencies from devdiv/DevDiv/vs-code-coverage, dotnet/arcade (#6330) [main] Update dependencies from devdiv/DevDiv/vs-code-coverage, dotnet/arcade --- eng/Version.Details.xml | 16 +++++----- eng/Versions.props | 4 +-- eng/common/core-templates/job/onelocbuild.yml | 30 +++++++++---------- eng/common/tools.ps1 | 13 ++++++++ eng/common/tools.sh | 24 +++++++++++++++ global.json | 6 ++-- 6 files changed, 64 insertions(+), 29 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index cd85aca2a0..1b1b975858 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -1,21 +1,21 @@ - + https://github.com/dotnet/arcade - 40693ae2ee51e447f6ca96d07bc1ba779dcb9b9c + d27184f7cb92b4abb4b20e91ecb5c43bc43de65b - + https://github.com/dotnet/arcade - 40693ae2ee51e447f6ca96d07bc1ba779dcb9b9c + d27184f7cb92b4abb4b20e91ecb5c43bc43de65b - + https://github.com/dotnet/arcade - 40693ae2ee51e447f6ca96d07bc1ba779dcb9b9c + d27184f7cb92b4abb4b20e91ecb5c43bc43de65b - + https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage - 288c5f9d739ec170567f2b09c4f86cc168529a8d + 5877eadeb2d78c45d3bb1996f74b8a96f2e4a1da https://github.com/microsoft/testfx diff --git a/eng/Versions.props b/eng/Versions.props index 4b6b2cb578..550afee2d9 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -7,8 +7,8 @@ preview - 10.0.0-beta.25401.2 - 18.0.0-preview.25406.1 + 10.0.0-beta.25408.3 + 18.0.0-preview.25408.1 3.11.0-preview.25407.1 1.9.0-preview.25407.1 diff --git a/eng/common/core-templates/job/onelocbuild.yml b/eng/common/core-templates/job/onelocbuild.yml index 8034815f42..8bf7d23355 100644 --- a/eng/common/core-templates/job/onelocbuild.yml +++ b/eng/common/core-templates/job/onelocbuild.yml @@ -4,7 +4,7 @@ parameters: # Optional: A defined YAML pool - https://docs.microsoft.com/en-us/azure/devops/pipelines/yaml-schema?view=vsts&tabs=schema#pool pool: '' - + CeapexPat: $(dn-bot-ceapex-package-r) # PAT for the loc AzDO instance https://dev.azure.com/ceapex GithubPat: $(BotAccount-dotnet-bot-repo-PAT) @@ -27,7 +27,7 @@ parameters: is1ESPipeline: '' jobs: - job: OneLocBuild${{ parameters.JobNameSuffix }} - + dependsOn: ${{ parameters.dependsOn }} displayName: OneLocBuild${{ parameters.JobNameSuffix }} @@ -99,22 +99,20 @@ jobs: mirrorBranch: ${{ parameters.MirrorBranch }} condition: ${{ parameters.condition }} - - template: /eng/common/core-templates/steps/publish-build-artifacts.yml - parameters: - is1ESPipeline: ${{ parameters.is1ESPipeline }} - args: - displayName: Publish Localization Files - pathToPublish: '$(Build.ArtifactStagingDirectory)/loc' - publishLocation: Container - artifactName: Loc - condition: ${{ parameters.condition }} + # Copy the locProject.json to the root of the Loc directory, then publish a pipeline artifact + - task: CopyFiles@2 + displayName: Copy LocProject.json + inputs: + SourceFolder: '$(Build.SourcesDirectory)/eng/Localize/' + Contents: 'LocProject.json' + TargetFolder: '$(Build.ArtifactStagingDirectory)/loc' + condition: ${{ parameters.condition }} - - template: /eng/common/core-templates/steps/publish-build-artifacts.yml + - template: /eng/common/core-templates/steps/publish-pipeline-artifacts.yml parameters: is1ESPipeline: ${{ parameters.is1ESPipeline }} args: - displayName: Publish LocProject.json - pathToPublish: '$(Build.SourcesDirectory)/eng/Localize/' - publishLocation: Container - artifactName: Loc + targetPath: '$(Build.ArtifactStagingDirectory)/loc' + artifactName: 'Loc' + displayName: 'Publish Localization Files' condition: ${{ parameters.condition }} diff --git a/eng/common/tools.ps1 b/eng/common/tools.ps1 index 996a5f9c87..d4cfd9ccd8 100644 --- a/eng/common/tools.ps1 +++ b/eng/common/tools.ps1 @@ -257,7 +257,20 @@ function Retry($downloadBlock, $maxRetries = 5) { function GetDotNetInstallScript([string] $dotnetRoot) { $installScript = Join-Path $dotnetRoot 'dotnet-install.ps1' + $shouldDownload = $false + if (!(Test-Path $installScript)) { + $shouldDownload = $true + } else { + # Check if the script is older than 30 days + $fileAge = (Get-Date) - (Get-Item $installScript).LastWriteTime + if ($fileAge.Days -gt 30) { + Write-Host "Existing install script is too old, re-downloading..." + $shouldDownload = $true + } + } + + if ($shouldDownload) { Create-Directory $dotnetRoot $ProgressPreference = 'SilentlyContinue' # Don't display the console progress UI - it's a huge perf hit $uri = "https://builds.dotnet.microsoft.com/dotnet/scripts/$dotnetInstallScriptVersion/dotnet-install.ps1" diff --git a/eng/common/tools.sh b/eng/common/tools.sh index 3def02a638..c1841c9dfd 100644 --- a/eng/common/tools.sh +++ b/eng/common/tools.sh @@ -300,8 +300,29 @@ function GetDotNetInstallScript { local root=$1 local install_script="$root/dotnet-install.sh" local install_script_url="https://builds.dotnet.microsoft.com/dotnet/scripts/$dotnetInstallScriptVersion/dotnet-install.sh" + local timestamp_file="$root/.dotnet-install.timestamp" + local should_download=false if [[ ! -a "$install_script" ]]; then + should_download=true + elif [[ -f "$timestamp_file" ]]; then + # Check if the script is older than 30 days using timestamp file + local download_time=$(cat "$timestamp_file" 2>/dev/null || echo "0") + local current_time=$(date +%s) + local age_seconds=$((current_time - download_time)) + + # 30 days = 30 * 24 * 60 * 60 = 2592000 seconds + if [[ $age_seconds -gt 2592000 ]]; then + echo "Existing install script is too old, re-downloading..." + should_download=true + fi + else + # No timestamp file exists, assume script is old and re-download + echo "No timestamp found for existing install script, re-downloading..." + should_download=true + fi + + if [[ "$should_download" == true ]]; then mkdir -p "$root" echo "Downloading '$install_script_url'" @@ -328,6 +349,9 @@ function GetDotNetInstallScript { ExitWithExitCode $exit_code } fi + + # Create timestamp file to track download time in seconds from epoch + date +%s > "$timestamp_file" fi # return value _GetDotNetInstallScript="$install_script" diff --git a/global.json b/global.json index 552650a9d8..0fb5e94ef5 100644 --- a/global.json +++ b/global.json @@ -1,6 +1,6 @@ { "tools": { - "dotnet": "10.0.100-preview.7.25368.105", + "dotnet": "10.0.100-preview.7.25372.107", "runtimes": { "dotnet": [ "3.1.32", @@ -23,7 +23,7 @@ } }, "sdk": { - "version": "10.0.100-preview.7.25368.105", + "version": "10.0.100-preview.7.25372.107", "paths": [ ".dotnet", "$host$" @@ -33,7 +33,7 @@ "rollForward": "latestFeature" }, "msbuild-sdks": { - "Microsoft.DotNet.Arcade.Sdk": "10.0.0-beta.25401.2", + "Microsoft.DotNet.Arcade.Sdk": "10.0.0-beta.25408.3", "MSBuild.Sdk.Extras": "3.0.44" } } From a2f4caf24047ec2e050c99174edc755745b58a21 Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Sun, 10 Aug 2025 09:24:39 +0200 Subject: [PATCH 383/541] [main] Update dependencies from microsoft/testfx (#6336) Co-authored-by: dotnet-maestro[bot] --- eng/Version.Details.xml | 8 ++++---- eng/Versions.props | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index 1b1b975858..5931e0db6c 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -17,13 +17,13 @@ https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage 5877eadeb2d78c45d3bb1996f74b8a96f2e4a1da - + https://github.com/microsoft/testfx - e1f0a9d0bde8b48c4fbc69737642c1026f1ad062 + a995127b79cb0691333b8ec172128ac5e7abb9b2 - + https://github.com/microsoft/testfx - e1f0a9d0bde8b48c4fbc69737642c1026f1ad062 + a995127b79cb0691333b8ec172128ac5e7abb9b2 diff --git a/eng/Versions.props b/eng/Versions.props index 550afee2d9..5d6bd1ce4c 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -10,7 +10,7 @@ 10.0.0-beta.25408.3 18.0.0-preview.25408.1 - 3.11.0-preview.25407.1 - 1.9.0-preview.25407.1 + 3.11.0-preview.25408.2 + 1.9.0-preview.25408.2 From f3c3a80c44644eaa116508746b7d0d09d7ebe8b9 Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Tue, 12 Aug 2025 05:56:59 +0200 Subject: [PATCH 384/541] [main] Update dependencies from devdiv/DevDiv/vs-code-coverage (#6345) Co-authored-by: dotnet-maestro[bot] --- eng/Version.Details.xml | 4 ++-- eng/Versions.props | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index 5931e0db6c..ca29b6bdd3 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -13,9 +13,9 @@ https://github.com/dotnet/arcade d27184f7cb92b4abb4b20e91ecb5c43bc43de65b - + https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage - 5877eadeb2d78c45d3bb1996f74b8a96f2e4a1da + 8d5e7b7e875d1945baaab1020e7c76e57aa51cac https://github.com/microsoft/testfx diff --git a/eng/Versions.props b/eng/Versions.props index 5d6bd1ce4c..d1be61c7ab 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -8,7 +8,7 @@ 10.0.0-beta.25408.3 - 18.0.0-preview.25408.1 + 18.0.0-preview.25411.2 3.11.0-preview.25408.2 1.9.0-preview.25408.2 From d81d2008e93311ef2b752580a18eac90503ab150 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Tue, 12 Aug 2025 12:19:49 +0200 Subject: [PATCH 385/541] Update Changelog.md (#6346) --- docs/Changelog-Platform.md | 20 ++++++++++++++++++++ docs/Changelog.md | 18 ++++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/docs/Changelog-Platform.md b/docs/Changelog-Platform.md index c5fbe74f15..e198af28f6 100644 --- a/docs/Changelog-Platform.md +++ b/docs/Changelog-Platform.md @@ -4,6 +4,26 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) +## [1.8.2] - 2025-08-12 + +See full log [of v3.10.1...v3.10.2](https://github.com/microsoft/testfx/compare/v3.10.1...v3.10.2) + +* No change, released to keep version aligned with MSTest. + +### Artifacts + +* Microsoft.Testing.Platform: [1.8.2](https://www.nuget.org/packages/Microsoft.Testing.Platform/1.8.2) +* Microsoft.Testing.Platform.MSBuild: [1.8.2](https://www.nuget.org/packages/Microsoft.Testing.Platform.MSBuild/1.8.2) +* Microsoft.Testing.Extensions.CrashDump: [1.8.2](https://www.nuget.org/packages/Microsoft.Testing.Extensions.CrashDump/1.8.2) +* Microsoft.Testing.Extensions.HangDump: [1.8.2](https://www.nuget.org/packages/Microsoft.Testing.Extensions.HangDump/1.8.2) +* Microsoft.Testing.Extensions.HotReload: [1.8.2](https://www.nuget.org/packages/Microsoft.Testing.Extensions.HotReload/1.8.2) +* Microsoft.Testing.Extensions.Retry: [1.8.2](https://www.nuget.org/packages/Microsoft.Testing.Extensions.Retry/1.8.2) +* Microsoft.Testing.Extensions.Telemetry: [1.8.2](https://www.nuget.org/packages/Microsoft.Testing.Extensions.Telemetry/1.8.2) +* Microsoft.Testing.Extensions.TrxReport: [1.8.2](https://www.nuget.org/packages/Microsoft.Testing.Extensions.TrxReport/1.8.2) +* Microsoft.Testing.Extensions.TrxReport.Abstractions: [1.8.2](https://www.nuget.org/packages/Microsoft.Testing.Extensions.TrxReport.Abstractions/1.8.2) +* Microsoft.Testing.Extensions.VSTestBridge: [1.8.2](https://www.nuget.org/packages/Microsoft.Testing.Extensions.VSTestBridge/1.8.2) +* Microsoft.Testing.Extensions.AzureDevOpsReport [1.0.0-alpha.25411.2](https://www.nuget.org/packages/Microsoft.Testing.Extensions.AzureDevOpsReport/1.0.0-alpha.25411.2) + ## [1.8.1] - 2025-08-05 See full log [of v3.10.0...v3.10.1](https://github.com/microsoft/testfx/compare/v3.10.0...v3.10.1) diff --git a/docs/Changelog.md b/docs/Changelog.md index e183bbf85a..bcafd56547 100644 --- a/docs/Changelog.md +++ b/docs/Changelog.md @@ -4,6 +4,24 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) +## [3.10.2] - 2025-08-12 + +See full log [of v3.10.1...v3.10.2](https://github.com/microsoft/testfx/compare/v3.10.1...v3.10.2) + +### Fixed + +* Revert Assert.That obsoletion by @Youssef1313 in [#6323](https://github.com/microsoft/testfx/pull/6323) + +### Artifacts + +* MSTest: [3.10.2](https://www.nuget.org/packages/MSTest/3.10.2) +* MSTest.TestFramework: [3.10.2](https://www.nuget.org/packages/MSTest.TestFramework/3.10.2) +* MSTest.TestAdapter: [3.10.2](https://www.nuget.org/packages/MSTest.TestAdapter/3.10.2) +* MSTest.Analyzers: [3.10.2](https://www.nuget.org/packages/MSTest.Analyzers/3.10.2) +* MSTest.Sdk: [3.10.2](https://www.nuget.org/packages/MSTest.Sdk/3.10.2) +* MSTest.SourceGeneration: [1.0.0-alpha.25411.2](https://www.nuget.org/packages/MSTest.SourceGeneration/1.0.0-alpha.25411.2) +* MSTest.Engine: [1.0.0-alpha.25411.2](https://www.nuget.org/packages/MSTest.Engine/1.0.0-alpha.25411.2) + ## [3.10.1] - 2025-08-05 See full log [of v3.10.0...v3.10.1](https://github.com/microsoft/testfx/compare/v3.10.0...v3.10.1) From d64da42485ebcccfa5191c543c91a35f22f070d0 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Tue, 12 Aug 2025 20:48:37 +0200 Subject: [PATCH 386/541] Avoid accessing TestCase.Traits when possible (#6353) --- .../Discovery/UnitTestDiscoverer.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Discovery/UnitTestDiscoverer.cs b/src/Adapter/MSTestAdapter.PlatformServices/Discovery/UnitTestDiscoverer.cs index 2de1b9dcb4..597a7dfd3f 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Discovery/UnitTestDiscoverer.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Discovery/UnitTestDiscoverer.cs @@ -109,7 +109,7 @@ internal void SendTestCases(string source, IEnumerable testElem foreach (UnitTestElement testElement in testElements) { var testCase = testElement.ToTestCase(); - bool hasFixtureTraits = testCase.Traits.Any(t => t.Name == EngineConstants.FixturesTestTrait); + bool hasFixtureTraits = testElement.Traits?.Any(t => t.Name == EngineConstants.FixturesTestTrait) == true; // Filter tests based on test case filters if (filterExpression != null && !filterExpression.MatchTestCase(testCase, p => _testMethodFilter.PropertyValueProvider(testCase, p))) From bea887d310420970a9f122d3738b92f484f0d625 Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Wed, 13 Aug 2025 07:40:41 +0200 Subject: [PATCH 387/541] [main] Update dependencies from microsoft/testfx (#6355) Co-authored-by: dotnet-maestro[bot] --- eng/Version.Details.xml | 8 ++++---- eng/Versions.props | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index ca29b6bdd3..48f0de1fe2 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -17,13 +17,13 @@ https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage 8d5e7b7e875d1945baaab1020e7c76e57aa51cac - + https://github.com/microsoft/testfx - a995127b79cb0691333b8ec172128ac5e7abb9b2 + d64da42485ebcccfa5191c543c91a35f22f070d0 - + https://github.com/microsoft/testfx - a995127b79cb0691333b8ec172128ac5e7abb9b2 + d64da42485ebcccfa5191c543c91a35f22f070d0 diff --git a/eng/Versions.props b/eng/Versions.props index d1be61c7ab..ddb30a4af5 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -10,7 +10,7 @@ 10.0.0-beta.25408.3 18.0.0-preview.25411.2 - 3.11.0-preview.25408.2 - 1.9.0-preview.25408.2 + 3.11.0-preview.25412.3 + 1.9.0-preview.25412.3 From 3ff84dca228466c2c889146fcfa7559ed608b738 Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Wed, 13 Aug 2025 07:41:03 +0200 Subject: [PATCH 388/541] [main] Update dependencies from devdiv/DevDiv/vs-code-coverage, dotnet/arcade (#6354) Co-authored-by: dotnet-maestro[bot] --- eng/Version.Details.xml | 16 ++++++++-------- eng/Versions.props | 4 ++-- global.json | 2 +- 3 files changed, 11 insertions(+), 11 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index 48f0de1fe2..7c0382616f 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -1,21 +1,21 @@ - + https://github.com/dotnet/arcade - d27184f7cb92b4abb4b20e91ecb5c43bc43de65b + 0a1768a159fc30f6b1a790710eba5fb4469d543e - + https://github.com/dotnet/arcade - d27184f7cb92b4abb4b20e91ecb5c43bc43de65b + 0a1768a159fc30f6b1a790710eba5fb4469d543e - + https://github.com/dotnet/arcade - d27184f7cb92b4abb4b20e91ecb5c43bc43de65b + 0a1768a159fc30f6b1a790710eba5fb4469d543e - + https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage - 8d5e7b7e875d1945baaab1020e7c76e57aa51cac + 956834fab85544c87b8a781d8f95e283698e6bab https://github.com/microsoft/testfx diff --git a/eng/Versions.props b/eng/Versions.props index ddb30a4af5..eca65fe594 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -7,8 +7,8 @@ preview - 10.0.0-beta.25408.3 - 18.0.0-preview.25411.2 + 10.0.0-beta.25412.1 + 18.0.0-preview.25412.4 3.11.0-preview.25412.3 1.9.0-preview.25412.3 diff --git a/global.json b/global.json index 0fb5e94ef5..2e8fca344c 100644 --- a/global.json +++ b/global.json @@ -33,7 +33,7 @@ "rollForward": "latestFeature" }, "msbuild-sdks": { - "Microsoft.DotNet.Arcade.Sdk": "10.0.0-beta.25408.3", + "Microsoft.DotNet.Arcade.Sdk": "10.0.0-beta.25412.1", "MSBuild.Sdk.Extras": "3.0.44" } } From 4f5cbf164c74d87bd0badbbaced1dbdc170d4cf6 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Wed, 13 Aug 2025 09:32:26 +0200 Subject: [PATCH 389/541] Cleanup TestContextImplementation (#6352) --- .../Execution/UnitTestRunner.cs | 12 ++-- .../PublicAPI/PublicAPI.Unshipped.txt | 1 + .../Services/TestContextImplementation.cs | 66 ++++++++----------- 3 files changed, 34 insertions(+), 45 deletions(-) diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Execution/UnitTestRunner.cs b/src/Adapter/MSTestAdapter.PlatformServices/Execution/UnitTestRunner.cs index 0934c7792a..7e8a8d9f92 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Execution/UnitTestRunner.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Execution/UnitTestRunner.cs @@ -145,6 +145,7 @@ internal TestResult[] RunSingleTest(TestMethod testMethod, IDictionary RunSingleTestAsync(TestMethod testMethod, IDictionary testContextProperties, IMessageLogger messageLogger) { Guard.NotNull(testMethod); + Guard.NotNull(testContextProperties); ITestContext? testContextForTestExecution = null; ITestContext? testContextForAssemblyInit = null; @@ -154,8 +155,7 @@ internal async Task RunSingleTestAsync(TestMethod testMethod, IDic try { - var properties = new Dictionary(testContextProperties); - testContextForTestExecution = PlatformServiceProvider.Instance.GetTestContext(testMethod, properties, messageLogger, UTF.UnitTestOutcome.InProgress); + testContextForTestExecution = PlatformServiceProvider.Instance.GetTestContext(testMethod, testContextProperties, messageLogger, UTF.UnitTestOutcome.InProgress); // Get the testMethod TestMethodInfo? testMethodInfo = _typeCache.GetTestMethodInfo( @@ -175,7 +175,7 @@ internal async Task RunSingleTestAsync(TestMethod testMethod, IDic _assemblyFixtureTests.TryAdd(testMethod.AssemblyName, testMethodInfo.Parent.Parent); _classFixtureTests.TryAdd(testMethod.AssemblyName + testMethod.FullClassName, testMethodInfo.Parent); - testContextForAssemblyInit = PlatformServiceProvider.Instance.GetTestContext(testMethod, properties, messageLogger, testContextForTestExecution.Context.CurrentTestOutcome); + testContextForAssemblyInit = PlatformServiceProvider.Instance.GetTestContext(testMethod, testContextProperties, messageLogger, testContextForTestExecution.Context.CurrentTestOutcome); TestResult assemblyInitializeResult = RunAssemblyInitializeIfNeeded(testMethodInfo, testContextForAssemblyInit); @@ -185,7 +185,7 @@ internal async Task RunSingleTestAsync(TestMethod testMethod, IDic } else { - testContextForClassInit = PlatformServiceProvider.Instance.GetTestContext(testMethod, properties, messageLogger, testContextForAssemblyInit.Context.CurrentTestOutcome); + testContextForClassInit = PlatformServiceProvider.Instance.GetTestContext(testMethod, testContextProperties, messageLogger, testContextForAssemblyInit.Context.CurrentTestOutcome); TestResult classInitializeResult = testMethodInfo.Parent.GetResultOrRunClassInitialize(testContextForClassInit, assemblyInitializeResult.LogOutput, assemblyInitializeResult.LogError, assemblyInitializeResult.DebugTrace, assemblyInitializeResult.TestContextMessages); DebugEx.Assert(testMethodInfo.Parent.IsClassInitializeExecuted, "IsClassInitializeExecuted should be true after attempting to run it."); @@ -213,12 +213,12 @@ internal async Task RunSingleTestAsync(TestMethod testMethod, IDic } } - testContextForClassCleanup = PlatformServiceProvider.Instance.GetTestContext(testMethod, properties, messageLogger, testContextForTestExecution.Context.CurrentTestOutcome); + testContextForClassCleanup = PlatformServiceProvider.Instance.GetTestContext(testMethod, testContextProperties, messageLogger, testContextForTestExecution.Context.CurrentTestOutcome); testMethodInfo?.Parent.RunClassCleanup(testContextForClassCleanup, _classCleanupManager, testMethodInfo, result); if (testMethodInfo?.Parent.Parent.IsAssemblyInitializeExecuted == true) { - testContextForAssemblyCleanup = PlatformServiceProvider.Instance.GetTestContext(testMethod, properties, messageLogger, testContextForClassCleanup.Context.CurrentTestOutcome); + testContextForAssemblyCleanup = PlatformServiceProvider.Instance.GetTestContext(testMethod, testContextProperties, messageLogger, testContextForClassCleanup.Context.CurrentTestOutcome); RunAssemblyCleanupIfNeeded(testContextForAssemblyCleanup, _classCleanupManager, _typeCache, result); } diff --git a/src/Adapter/MSTestAdapter.PlatformServices/PublicAPI/PublicAPI.Unshipped.txt b/src/Adapter/MSTestAdapter.PlatformServices/PublicAPI/PublicAPI.Unshipped.txt index 7dc5c58110..07e3531963 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/PublicAPI/PublicAPI.Unshipped.txt +++ b/src/Adapter/MSTestAdapter.PlatformServices/PublicAPI/PublicAPI.Unshipped.txt @@ -1 +1,2 @@ #nullable enable +*REMOVED*virtual Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.TestContextImplementation.Dispose(bool disposing) -> void diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Services/TestContextImplementation.cs b/src/Adapter/MSTestAdapter.PlatformServices/Services/TestContextImplementation.cs index 2dcb6d291c..60bac5bbdc 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Services/TestContextImplementation.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Services/TestContextImplementation.cs @@ -25,7 +25,7 @@ namespace Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; #else [Obsolete(FrameworkConstants.PublicTypeObsoleteMessage)] #endif -public class TestContextImplementation : TestContext, ITestContext, IDisposable +public sealed class TestContextImplementation : TestContext, ITestContext, IDisposable { internal sealed class SynchronizedStringBuilder { @@ -50,11 +50,6 @@ public override string ToString() private static readonly AsyncLocal CurrentTestContextAsyncLocal = new(); - /// - /// List of result files associated with the test. - /// - private readonly List _testResultFiles; - // This should be removed. Don't rely on it. // We only keep it for public constructor, but we don't pass it by the adapter. private readonly StringWriter? _stringWriter; @@ -64,15 +59,19 @@ public override string ToString() /// private readonly Dictionary _properties; private readonly IMessageLogger? _messageLogger; - private readonly CancellationTokenRegistration? _cancellationTokenRegistration; + + private CancellationTokenRegistration? _cancellationTokenRegistration; + + /// + /// List of result files associated with the test. + /// + private List? _testResultFiles; private SynchronizedStringBuilder? _stdOutStringBuilder; private SynchronizedStringBuilder? _stdErrStringBuilder; private SynchronizedStringBuilder? _traceStringBuilder; private StringBuilder? _testContextMessageStringBuilder; - private bool _isDisposed; - /// /// Unit test outcome. /// @@ -118,17 +117,23 @@ public TestContextImplementation(ITestMethod? testMethod, StringWriter stringWri DebugEx.Assert(properties != null, "properties is not null"); _stringWriter = stringWriter; - _properties = testMethod is null - ? new Dictionary(properties) - : new Dictionary(properties) + if (testMethod is null) + { + _properties = new Dictionary(properties); + } + else + { + _properties = new Dictionary(properties.Count + 4); + foreach (KeyValuePair kvp in properties) { - [FullyQualifiedTestClassNameLabel] = testMethod.FullClassName, - [ManagedTypeLabel] = testMethod.ManagedTypeName, - [ManagedMethodLabel] = testMethod.ManagedMethodName, - [TestNameLabel] = testMethod.Name, - }; + _properties[kvp.Key] = kvp.Value; + } - _testResultFiles = []; + _properties[FullyQualifiedTestClassNameLabel] = testMethod.FullClassName; + _properties[ManagedTypeLabel] = testMethod.ManagedTypeName; + _properties[ManagedMethodLabel] = testMethod.ManagedMethodName; + _properties[TestNameLabel] = testMethod.Name; + } } internal static TestContextImplementation? CurrentTestContext => CurrentTestContextAsyncLocal.Value; @@ -193,7 +198,7 @@ public override void AddResultFile(string fileName) throw new ArgumentException(Resource.Common_CannotBeNullOrEmpty, nameof(fileName)); } - _testResultFiles.Add(Path.GetFullPath(fileName)); + (_testResultFiles ??= []).Add(Path.GetFullPath(fileName)); } /// @@ -317,7 +322,7 @@ public void AddProperty(string propertyName, string propertyValue) /// Results files generated in run. public IList? GetResultFiles() { - if (_testResultFiles.Count == 0) + if (_testResultFiles is null || _testResultFiles.Count == 0) { return null; } @@ -358,25 +363,8 @@ public override void DisplayMessage(MessageLevel messageLevel, string message) /// public void Dispose() { - Dispose(true); - GC.SuppressFinalize(this); - } - - /// - /// The dispose pattern. - /// - /// Whether to dispose managed state. - protected virtual void Dispose(bool disposing) - { - if (!_isDisposed) - { - _isDisposed = true; - - if (disposing) - { - _cancellationTokenRegistration?.Dispose(); - } - } + _cancellationTokenRegistration?.Dispose(); + _cancellationTokenRegistration = null; } internal readonly struct ScopedTestContextSetter : IDisposable From 4669ef652da8fc0d831cffd04db9994737d7154c Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Wed, 13 Aug 2025 09:58:11 +0200 Subject: [PATCH 390/541] Add missing pipe protocol features (#6342) --- .../IPC/Serializers/BaseSerializer.cs | 12 ++ .../DotnetTest/DotnetTestConnection.cs | 6 + .../ServerMode/DotnetTest/IPC/Constants.cs | 2 + .../DotnetTest/IPC/DotnetTestDataConsumer.cs | 23 ++- .../IPC/Models/DiscoveredTestMessages.cs | 4 +- .../IPC/Models/TestResultMessages.cs | 2 + .../DotnetTest/IPC/ObjectFieldIds.cs | 12 ++ .../DiscoveredTestMessagesSerializer.cs | 168 +++++++++++++++++- .../IPC/ProtocolTests.cs | 43 +++++ 9 files changed, 261 insertions(+), 11 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Platform/IPC/Serializers/BaseSerializer.cs b/src/Platform/Microsoft.Testing.Platform/IPC/Serializers/BaseSerializer.cs index 5847336210..7625d3a39e 100644 --- a/src/Platform/Microsoft.Testing.Platform/IPC/Serializers/BaseSerializer.cs +++ b/src/Platform/Microsoft.Testing.Platform/IPC/Serializers/BaseSerializer.cs @@ -291,6 +291,18 @@ protected static void WriteField(Stream stream, ushort id, long? value) WriteLong(stream, value.Value); } + protected static void WriteField(Stream stream, ushort id, int? value) + { + if (value is null) + { + return; + } + + WriteShort(stream, id); + WriteSize(stream); + WriteInt(stream, value.Value); + } + protected static void WriteField(Stream stream, string? value) { if (value is null) diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/DotnetTestConnection.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/DotnetTestConnection.cs index faeea63c18..25dcc9d34c 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/DotnetTestConnection.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/DotnetTestConnection.cs @@ -88,6 +88,8 @@ public async Task HelpInvokedAsync() await _dotnetTestPipeClient.RequestReplyAsync(new CommandLineOptionMessages(_testApplicationModuleInfo.GetCurrentTestApplicationFullPath(), [.. commandLineHelpOptions.OrderBy(option => option.Name)]), _cancellationTokenSource.CancellationToken).ConfigureAwait(false); } + public bool IsIDE { get; private set; } + public async Task IsCompatibleProtocolAsync(string hostType) { RoslynDebug.Assert(_dotnetTestPipeClient is not null); @@ -108,6 +110,10 @@ public async Task IsCompatibleProtocolAsync(string hostType) HandshakeMessage response = await _dotnetTestPipeClient.RequestReplyAsync(handshakeMessage, _cancellationTokenSource.CancellationToken).ConfigureAwait(false); + IsIDE = response.Properties?.TryGetValue(HandshakeMessagePropertyNames.IsIDE, out string? isIDEValue) == true && + bool.TryParse(isIDEValue, out bool isIDE) && + isIDE; + return response.Properties?.TryGetValue(HandshakeMessagePropertyNames.SupportedProtocolVersions, out string? protocolVersion) == true && IsVersionCompatible(protocolVersion, supportedProtocolVersions); } diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Constants.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Constants.cs index 263abfa2b9..11239b8039 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Constants.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Constants.cs @@ -12,6 +12,7 @@ internal static class TestStates internal const byte Error = 4; internal const byte Timeout = 5; internal const byte Cancelled = 6; + internal const byte InProgress = 7; } internal static class SessionEventTypes @@ -31,6 +32,7 @@ internal static class HandshakeMessagePropertyNames internal const byte ModulePath = 6; internal const byte ExecutionId = 7; internal const byte InstanceId = 8; + internal const byte IsIDE = 9; } internal static class ProtocolConstants diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/DotnetTestDataConsumer.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/DotnetTestDataConsumer.cs index f15c188df0..585e5aff1a 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/DotnetTestDataConsumer.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/DotnetTestDataConsumer.cs @@ -56,13 +56,29 @@ public async Task ConsumeAsync(IDataProducer dataProducer, IData value, Cancella switch (testNodeDetails.State) { case TestStates.Discovered: + TestFileLocationProperty? testFileLocationProperty = null; + TestMethodIdentifierProperty? testMethodIdentifierProperty = null; + TestMetadataProperty[] traits = []; + if (_dotnetTestConnection.IsIDE) + { + testFileLocationProperty = testNodeUpdateMessage.TestNode.Properties.SingleOrDefault(); + testMethodIdentifierProperty = testNodeUpdateMessage.TestNode.Properties.SingleOrDefault(); + traits = testNodeUpdateMessage.TestNode.Properties.OfType(); + } + DiscoveredTestMessages discoveredTestMessages = new( ExecutionId, DotnetTestConnection.InstanceId, [ new DiscoveredTestMessage( testNodeUpdateMessage.TestNode.Uid.Value, - testNodeUpdateMessage.TestNode.DisplayName) + testNodeUpdateMessage.TestNode.DisplayName, + testFileLocationProperty?.FilePath, + testFileLocationProperty?.LineSpan.Start.Line, + testMethodIdentifierProperty?.Namespace, + testMethodIdentifierProperty?.TypeName, + testMethodIdentifierProperty?.MethodName, + traits) ]); await _dotnetTestConnection.SendMessageAsync(discoveredTestMessages).ConfigureAwait(false); @@ -70,6 +86,7 @@ public async Task ConsumeAsync(IDataProducer dataProducer, IData value, Cancella case TestStates.Passed: case TestStates.Skipped: + case TestStates.InProgress when _dotnetTestConnection.IsIDE: TestResultMessages testResultMessages = new( ExecutionId, DotnetTestConnection.InstanceId, @@ -229,6 +246,10 @@ public async Task ConsumeAsync(IDataProducer dataProducer, IData value, Cancella reason = nodeState.Explanation; exceptions = FlattenToExceptionMessages(reason, cancelledTestNodeStateProperty.Exception); break; + + case InProgressTestNodeStateProperty: + state = TestStates.InProgress; + break; } return new TestNodeDetails(state, duration, reason, exceptions, standardOutput, standardError); diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Models/DiscoveredTestMessages.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Models/DiscoveredTestMessages.cs index 4d83410741..2685de08ef 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Models/DiscoveredTestMessages.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Models/DiscoveredTestMessages.cs @@ -1,8 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using Microsoft.Testing.Platform.Extensions.Messages; + namespace Microsoft.Testing.Platform.IPC.Models; -internal sealed record DiscoveredTestMessage(string? Uid, string? DisplayName); +internal sealed record DiscoveredTestMessage(string? Uid, string? DisplayName, string? FilePath, int? LineNumber, string? Namespace, string? TypeName, string? MethodName, TestMetadataProperty[] Traits); internal sealed record DiscoveredTestMessages(string? ExecutionId, string? InstanceId, DiscoveredTestMessage[] DiscoveredMessages) : IRequest; diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Models/TestResultMessages.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Models/TestResultMessages.cs index a1ebc94504..fac3cb9f44 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Models/TestResultMessages.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Models/TestResultMessages.cs @@ -7,6 +7,8 @@ internal sealed record SuccessfulTestResultMessage(string? Uid, string? DisplayN internal sealed record FailedTestResultMessage(string? Uid, string? DisplayName, byte? State, long? Duration, string? Reason, ExceptionMessage[]? Exceptions, string? StandardOutput, string? ErrorOutput, string? SessionUid); +internal sealed record InProgressTestResultMessage(string? Uid, string? DisplayName, string? SessionUid); + internal sealed record ExceptionMessage(string? ErrorMessage, string? ErrorType, string? StackTrace); internal sealed record TestResultMessages(string? ExecutionId, string? InstanceId, SuccessfulTestResultMessage[] SuccessfulTestMessages, FailedTestResultMessage[] FailedTestMessages) : IRequest; diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/ObjectFieldIds.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/ObjectFieldIds.cs index d052766562..46c634ebf8 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/ObjectFieldIds.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/ObjectFieldIds.cs @@ -51,6 +51,18 @@ internal static class DiscoveredTestMessageFieldsId { public const ushort Uid = 1; public const ushort DisplayName = 2; + public const ushort FilePath = 3; + public const ushort LineNumber = 4; + public const ushort Namespace = 5; + public const ushort TypeName = 6; + public const ushort MethodName = 7; + public const ushort Traits = 8; +} + +internal static class TraitMessageFieldsId +{ + public const ushort Key = 1; + public const ushort Value = 2; } internal static class TestResultMessagesFieldsId diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Serializers/DiscoveredTestMessagesSerializer.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Serializers/DiscoveredTestMessagesSerializer.cs index 0ea49f5d83..67c35e5417 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Serializers/DiscoveredTestMessagesSerializer.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Serializers/DiscoveredTestMessagesSerializer.cs @@ -1,6 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using Microsoft.Testing.Platform.Extensions.Messages; using Microsoft.Testing.Platform.IPC.Models; namespace Microsoft.Testing.Platform.IPC.Serializers; @@ -30,7 +31,42 @@ namespace Microsoft.Testing.Platform.IPC.Serializers; |---DiscoveredTestMessageList[0].DisplayName Id---| (2 bytes) |---DiscoveredTestMessageList[0].DisplayName Size---| (4 bytes) |---DiscoveredTestMessageList[0].DisplayName Value---| (n bytes) - */ + + |---DiscoveredTestMessageList[0].FilePath Id---| (2 bytes) + |---DiscoveredTestMessageList[0].FilePath Size---| (4 bytes) + |---DiscoveredTestMessageList[0].FilePath Value---| (n bytes) + + |---DiscoveredTestMessageList[0].LineNumber Id---| (2 bytes) + |---DiscoveredTestMessageList[0].LineNumber Size---| (4 bytes) + |---DiscoveredTestMessageList[0].LineNumber Value---| (4 bytes) + + |---DiscoveredTestMessageList[0].Namespace Id---| (2 bytes) + |---DiscoveredTestMessageList[0].Namespace Size---| (4 bytes) + |---DiscoveredTestMessageList[0].Namespace Value---| (n bytes) + + |---DiscoveredTestMessageList[0].TypeName Id---| (2 bytes) + |---DiscoveredTestMessageList[0].TypeName Size---| (4 bytes) + |---DiscoveredTestMessageList[0].TypeName Value---| (n bytes) + + |---DiscoveredTestMessageList[0].MethodName Id---| (2 bytes) + |---DiscoveredTestMessageList[0].MethodName Size---| (4 bytes) + |---DiscoveredTestMessageList[0].MethodName Value---| (n bytes) + + |---DiscoveredTestMessageList[0].Traits Id---| (2 bytes) + |---DiscoveredTestMessageList[0].Traits Size---| (4 bytes) + |---DiscoveredTestMessageList[0].Traits Value---| (n bytes) + |---DiscoveredTestMessageList[0].Traits Length---| (4 bytes) + + |---DiscoveredTestMessageList[0].Trits[0] FieldCount---| 2 bytes + + |---DiscoveredTestMessageList[0].Trits[0].Key Id---| (2 bytes) + |---DiscoveredTestMessageList[0].Trits[0].Key Size---| (4 bytes) + |---DiscoveredTestMessageList[0].Trits[0].Key Value---| (n bytes) + + |---DiscoveredTestMessageList[0].Trits[0].Value Id---| (2 bytes) + |---DiscoveredTestMessageList[0].Trits[0].Value Size---| (4 bytes) + |---DiscoveredTestMessageList[0].Trits[0].Value Value---| (n bytes) +*/ internal sealed class DiscoveredTestMessagesSerializer : BaseSerializer, INamedPipeSerializer { @@ -40,7 +76,7 @@ public object Deserialize(Stream stream) { string? executionId = null; string? instanceId = null; - List? discoveredTestMessages = null; + DiscoveredTestMessage[]? discoveredTestMessages = []; ushort fieldCount = ReadShort(stream); @@ -70,17 +106,23 @@ public object Deserialize(Stream stream) } } - return new DiscoveredTestMessages(executionId, instanceId, discoveredTestMessages is null ? [] : [.. discoveredTestMessages]); + return new DiscoveredTestMessages(executionId, instanceId, discoveredTestMessages); } - private static List ReadDiscoveredTestMessagesPayload(Stream stream) + private static DiscoveredTestMessage[] ReadDiscoveredTestMessagesPayload(Stream stream) { - List discoveredTestMessages = []; - int length = ReadInt(stream); + var discoveredTestMessages = new DiscoveredTestMessage[length]; for (int i = 0; i < length; i++) { - string? uid = null, displayName = null; + string? uid = null; + string? displayName = null; + string? filePath = null; + int? lineNumber = null; + string? @namespace = null; + string? typeName = null; + string? methodName = null; + TestMetadataProperty[] traits = []; int fieldCount = ReadShort(stream); @@ -99,18 +141,81 @@ private static List ReadDiscoveredTestMessagesPayload(Str displayName = ReadStringValue(stream, fieldSize); break; + case DiscoveredTestMessageFieldsId.FilePath: + filePath = ReadStringValue(stream, fieldSize); + break; + + case DiscoveredTestMessageFieldsId.LineNumber: + lineNumber = ReadInt(stream); + break; + + case DiscoveredTestMessageFieldsId.Namespace: + @namespace = ReadStringValue(stream, fieldSize); + break; + + case DiscoveredTestMessageFieldsId.TypeName: + typeName = ReadStringValue(stream, fieldSize); + break; + + case DiscoveredTestMessageFieldsId.MethodName: + methodName = ReadStringValue(stream, fieldSize); + break; + + case DiscoveredTestMessageFieldsId.Traits: + traits = ReadTraitsPayload(stream); + break; + default: SetPosition(stream, stream.Position + fieldSize); break; } } - discoveredTestMessages.Add(new DiscoveredTestMessage(uid, displayName)); + discoveredTestMessages[i] = new DiscoveredTestMessage(uid, displayName, filePath, lineNumber, @namespace, typeName, methodName, traits); } return discoveredTestMessages; } + private static TestMetadataProperty[] ReadTraitsPayload(Stream stream) + { + int length = ReadInt(stream); + var traits = new TestMetadataProperty[length]; + for (int i = 0; i < length; i++) + { + string? key = null; + string? value = null; + int fieldCount = ReadShort(stream); + + for (int j = 0; j < fieldCount; j++) + { + int fieldId = ReadShort(stream); + int fieldSize = ReadInt(stream); + + switch (fieldId) + { + case TraitMessageFieldsId.Key: + key = ReadStringValue(stream, fieldSize); + break; + + case TraitMessageFieldsId.Value: + value = ReadStringValue(stream, fieldSize); + break; + + default: + SetPosition(stream, stream.Position + fieldSize); + break; + } + } + + Guard.NotNull(key); + Guard.NotNull(value); + traits[i] = new TestMetadataProperty(key, value); + } + + return traits; + } + public void Serialize(object objectToSerialize, Stream stream) { RoslynDebug.Assert(stream.CanSeek, "We expect a seekable stream."); @@ -145,6 +250,41 @@ private static void WriteDiscoveredTestMessagesPayload(Stream stream, Discovered WriteField(stream, DiscoveredTestMessageFieldsId.Uid, discoveredTestMessage.Uid); WriteField(stream, DiscoveredTestMessageFieldsId.DisplayName, discoveredTestMessage.DisplayName); + WriteField(stream, DiscoveredTestMessageFieldsId.FilePath, discoveredTestMessage.FilePath); + WriteField(stream, DiscoveredTestMessageFieldsId.LineNumber, discoveredTestMessage.LineNumber); + WriteField(stream, DiscoveredTestMessageFieldsId.Namespace, discoveredTestMessage.Namespace); + WriteField(stream, DiscoveredTestMessageFieldsId.TypeName, discoveredTestMessage.TypeName); + WriteField(stream, DiscoveredTestMessageFieldsId.MethodName, discoveredTestMessage.MethodName); + + WriteTraitsPayload(stream, discoveredTestMessage.Traits); + } + + // NOTE: We are able to seek only if we are using a MemoryStream + // thus, the seek operation is fast as we are only changing the value of a property + WriteAtPosition(stream, (int)(stream.Position - before), before - sizeof(int)); + } + + private static void WriteTraitsPayload(Stream stream, TestMetadataProperty[]? traits) + { + if (traits is null || traits.Length == 0) + { + return; + } + + WriteShort(stream, DiscoveredTestMessageFieldsId.Traits); + + // We will reserve an int (4 bytes) + // so that we fill the size later, once we write the payload + WriteInt(stream, 0); + + long before = stream.Position; + WriteInt(stream, traits.Length); + foreach (TestMetadataProperty trait in traits) + { + WriteShort(stream, GetFieldCount(trait)); + + WriteField(stream, TraitMessageFieldsId.Key, trait.Key); + WriteField(stream, TraitMessageFieldsId.Value, trait.Value); } // NOTE: We are able to seek only if we are using a MemoryStream @@ -159,5 +299,15 @@ private static ushort GetFieldCount(DiscoveredTestMessages discoveredTestMessage private static ushort GetFieldCount(DiscoveredTestMessage discoveredTestMessage) => (ushort)((discoveredTestMessage.Uid is null ? 0 : 1) + - (discoveredTestMessage.DisplayName is null ? 0 : 1)); + (discoveredTestMessage.DisplayName is null ? 0 : 1) + + (discoveredTestMessage.FilePath is null ? 0 : 1) + + (discoveredTestMessage.LineNumber is null ? 0 : 1) + + (discoveredTestMessage.Namespace is null ? 0 : 1) + + (discoveredTestMessage.TypeName is null ? 0 : 1) + + (discoveredTestMessage.MethodName is null ? 0 : 1) + + (IsNullOrEmpty(discoveredTestMessage.Traits) ? 0 : 1)); + + private static ushort GetFieldCount(TestMetadataProperty trait) => + (ushort)((trait.Key is null ? 0 : 1) + + (trait.Value is null ? 0 : 1)); } diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/ProtocolTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/ProtocolTests.cs index 73f4309e2f..b28de2b031 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/ProtocolTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/ProtocolTests.cs @@ -26,4 +26,47 @@ public void TestResultMessagesSerializeDeserialize() #endif Assert.AreEqual(message.FailedTestMessages?[0].Exceptions?[0].ErrorMessage, actual.FailedTestMessages?[0].Exceptions?[0].ErrorMessage); } + + [TestMethod] + public void DiscoveredTestMessagesSerializeDeserialize() + { + var serializer = new DiscoveredTestMessagesSerializer(); + var stream = new MemoryStream(); + + var message = new DiscoveredTestMessages( + "MyExecId", + "MyInstId", + [ + new DiscoveredTestMessage("MyFirstUid", "DispName1", "path/to/file1.cs", 19, "MyNamespace1", "FirstType", "TM1", []), + new DiscoveredTestMessage("My2ndUid", "SecondDisplay", "file2.cs", 21, string.Empty, null, string.Empty, []), + new DiscoveredTestMessage("My3rdUid", "3rdDisplay", null, null, "MyNamespace3", "TestClass3", "TM3", [new("Key1", "Value"), new("Key2", string.Empty)]), + ]); + + serializer.Serialize(message, stream); + stream.Seek(0, SeekOrigin.Begin); + + var deserialized = (DiscoveredTestMessages)serializer.Deserialize(stream); + Assert.IsNotNull(deserialized); + Assert.AreEqual(message.ExecutionId, deserialized.ExecutionId); + Assert.AreEqual(message.InstanceId, deserialized.InstanceId); + Assert.AreEqual(message.DiscoveredMessages.Length, deserialized.DiscoveredMessages.Length); + for (int i = 0; i < message.DiscoveredMessages.Length; i++) + { + DiscoveredTestMessage expected = message.DiscoveredMessages[i]; + DiscoveredTestMessage actual = deserialized.DiscoveredMessages[i]; + Assert.AreEqual(expected.Uid, actual.Uid); + Assert.AreEqual(expected.DisplayName, actual.DisplayName); + Assert.AreEqual(expected.FilePath, actual.FilePath); + Assert.AreEqual(expected.LineNumber, actual.LineNumber); + Assert.AreEqual(expected.Namespace, actual.Namespace); + Assert.AreEqual(expected.TypeName, actual.TypeName); + Assert.AreEqual(expected.MethodName, actual.MethodName); + Assert.AreEqual(expected.Traits.Length, actual.Traits.Length); + for (int j = 0; j < expected.Traits.Length; j++) + { + Assert.AreEqual(expected.Traits[j].Key, actual.Traits[j].Key); + Assert.AreEqual(expected.Traits[j].Value, actual.Traits[j].Value); + } + } + } } From 58274d77714e611408cda5370d6697f385868c74 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 13 Aug 2025 10:37:18 +0200 Subject: [PATCH 391/541] Bump dotnet-sdk from 10.0.100-preview.7.25372.107 to 10.0.100-preview.7.25380.108 (#6356) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: Youssef Victor --- global.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/global.json b/global.json index 2e8fca344c..c98ea8932f 100644 --- a/global.json +++ b/global.json @@ -1,6 +1,6 @@ { "tools": { - "dotnet": "10.0.100-preview.7.25372.107", + "dotnet": "10.0.100-preview.7.25380.108", "runtimes": { "dotnet": [ "3.1.32", @@ -23,7 +23,7 @@ } }, "sdk": { - "version": "10.0.100-preview.7.25372.107", + "version": "10.0.100-preview.7.25380.108", "paths": [ ".dotnet", "$host$" From 26b1f1b86bbaa1c524e4b91c6bbd838687ea23cc Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Wed, 13 Aug 2025 14:33:21 +0200 Subject: [PATCH 392/541] Use string interpolation in UnitTestElement.ToTestCase (#6362) --- .../ObjectModel/UnitTestElement.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/Adapter/MSTestAdapter.PlatformServices/ObjectModel/UnitTestElement.cs b/src/Adapter/MSTestAdapter.PlatformServices/ObjectModel/UnitTestElement.cs index e4d9877c4d..a84baae914 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/ObjectModel/UnitTestElement.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/ObjectModel/UnitTestElement.cs @@ -105,9 +105,9 @@ internal TestCase ToTestCase() { // This causes compatibility problems with older runners. // string testFullName = this.TestMethod.HasManagedMethodAndTypeProperties - // ? string.Format(CultureInfo.InvariantCulture, "{0}.{1}", this.TestMethod.ManagedTypeName, this.TestMethod.ManagedMethodName) - // : string.Format(CultureInfo.InvariantCulture, "{0}.{1}", this.TestMethod.FullClassName, this.TestMethod.Name); - string testFullName = string.Format(CultureInfo.InvariantCulture, "{0}.{1}", TestMethod.FullClassName, TestMethod.Name); + // ? $"{TestMethod.ManagedTypeName}.{TestMethod.ManagedMethodName}" + // : $"{TestMethod.FullClassName}.{TestMethod.Name}"; + string testFullName = $"{TestMethod.FullClassName}.{TestMethod.Name}"; TestCase testCase = new(testFullName, EngineConstants.ExecutorUri, TestMethod.AssemblyName) { From 3a0755abb5d70c2a032d3539fa793cf82d171981 Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Thu, 14 Aug 2025 06:55:32 +0200 Subject: [PATCH 393/541] [main] Update dependencies from microsoft/testfx (#6374) Co-authored-by: dotnet-maestro[bot] --- eng/Version.Details.xml | 8 ++++---- eng/Versions.props | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index 7c0382616f..0bd039b8e5 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -17,13 +17,13 @@ https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage 956834fab85544c87b8a781d8f95e283698e6bab - + https://github.com/microsoft/testfx - d64da42485ebcccfa5191c543c91a35f22f070d0 + 26b1f1b86bbaa1c524e4b91c6bbd838687ea23cc - + https://github.com/microsoft/testfx - d64da42485ebcccfa5191c543c91a35f22f070d0 + 26b1f1b86bbaa1c524e4b91c6bbd838687ea23cc diff --git a/eng/Versions.props b/eng/Versions.props index eca65fe594..2ca1708065 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -10,7 +10,7 @@ 10.0.0-beta.25412.1 18.0.0-preview.25412.4 - 3.11.0-preview.25412.3 - 1.9.0-preview.25412.3 + 3.11.0-preview.25413.5 + 1.9.0-preview.25413.5 From cb9616f15d86e81276a6c4cc3737e8aa0a67cab4 Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Thu, 14 Aug 2025 06:56:06 +0200 Subject: [PATCH 394/541] [main] Update dependencies from devdiv/DevDiv/vs-code-coverage, dotnet/arcade (#6373) Co-authored-by: dotnet-maestro[bot] --- eng/Version.Details.xml | 16 ++++++++-------- eng/Versions.props | 4 ++-- global.json | 2 +- 3 files changed, 11 insertions(+), 11 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index 0bd039b8e5..7d999df090 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -1,21 +1,21 @@ - + https://github.com/dotnet/arcade - 0a1768a159fc30f6b1a790710eba5fb4469d543e + ea9e51a7080f13abb409a9dcfd9ea957ecab01ae - + https://github.com/dotnet/arcade - 0a1768a159fc30f6b1a790710eba5fb4469d543e + ea9e51a7080f13abb409a9dcfd9ea957ecab01ae - + https://github.com/dotnet/arcade - 0a1768a159fc30f6b1a790710eba5fb4469d543e + ea9e51a7080f13abb409a9dcfd9ea957ecab01ae - + https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage - 956834fab85544c87b8a781d8f95e283698e6bab + 707da42f9e3e7d31c4ca03c2823cd75a9ddd4a98 https://github.com/microsoft/testfx diff --git a/eng/Versions.props b/eng/Versions.props index 2ca1708065..928421be20 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -7,8 +7,8 @@ preview - 10.0.0-beta.25412.1 - 18.0.0-preview.25412.4 + 10.0.0-beta.25413.1 + 18.0.0-preview.25413.2 3.11.0-preview.25413.5 1.9.0-preview.25413.5 diff --git a/global.json b/global.json index c98ea8932f..854a24144a 100644 --- a/global.json +++ b/global.json @@ -33,7 +33,7 @@ "rollForward": "latestFeature" }, "msbuild-sdks": { - "Microsoft.DotNet.Arcade.Sdk": "10.0.0-beta.25412.1", + "Microsoft.DotNet.Arcade.Sdk": "10.0.0-beta.25413.1", "MSBuild.Sdk.Extras": "3.0.44" } } From 0565b1ac56a5185799ce43d09d493ac1d106b742 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Thu, 14 Aug 2025 07:47:04 +0200 Subject: [PATCH 395/541] Prevent unnecessary List allocations (#6370) --- .../Execution/TestExecutionManager.cs | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestExecutionManager.cs b/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestExecutionManager.cs index 5f88bfbea8..7f68de2fd7 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestExecutionManager.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestExecutionManager.cs @@ -511,7 +511,7 @@ private async Task ExecuteTestsWithTestRunnerAsync( bool usesAppDomains) { bool hasAnyRunnableTests = false; - var fixtureTests = new List(); + List? fixtureTests = null; IEnumerable orderedTests = MSTestSettings.CurrentSettings.OrderTestsByNameInClass ? tests.OrderBy(t => t.GetManagedType()).ThenBy(t => t.GetManagedMethod()) @@ -535,7 +535,7 @@ private async Task ExecuteTestsWithTestRunnerAsync( // It is executed by test itself. if (currentTest.Traits.Any(t => t.Name == EngineConstants.FixturesTestTrait)) { - fixtureTests.Add(currentTest); + (fixtureTests ??= []).Add(currentTest); continue; } @@ -578,6 +578,11 @@ private async Task ExecuteTestsWithTestRunnerAsync( } // Once all tests have been executed, update the status of fixture tests. + if (fixtureTests is null) + { + return; + } + foreach (TestCase currentTest in fixtureTests) { _testRunCancellationToken?.ThrowIfCancellationRequested(); From 4479f198f682b2594996ed9119704bb5f10b1d90 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Thu, 14 Aug 2025 07:48:57 +0200 Subject: [PATCH 396/541] Avoid iterator allocations (#6369) --- .../Execution/TypeCache.cs | 23 ++++-- .../Helpers/ReflectHelper.cs | 70 +++++++++++++++++-- 2 files changed, 79 insertions(+), 14 deletions(-) diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Execution/TypeCache.cs b/src/Adapter/MSTestAdapter.PlatformServices/Execution/TypeCache.cs index 9749a81a4d..553fd6fa40 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Execution/TypeCache.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Execution/TypeCache.cs @@ -815,17 +815,26 @@ private void SetCustomProperties(TestMethodInfo testMethodInfo, ITestContext tes DebugEx.Assert(testMethodInfo != null, "testMethodInfo is Null"); DebugEx.Assert(testMethodInfo.MethodInfo != null, "testMethodInfo.TestMethod is Null"); - IEnumerable attributes = _reflectionHelper.GetAttributes(testMethodInfo.MethodInfo, inherit: true); - DebugEx.Assert(attributes != null, "attributes is null"); + // Avoid calling GetAttributes to prevent iterator state machine allocations. + _ = ValidateAttributes(_reflectionHelper.GetCustomAttributesCached(testMethodInfo.MethodInfo, inherit: true), testMethodInfo, testContext) && + ValidateAttributes(_reflectionHelper.GetCustomAttributesCached(testMethodInfo.Parent.ClassType, inherit: true), testMethodInfo, testContext); - attributes = attributes.Concat(_reflectionHelper.GetAttributes(testMethodInfo.Parent.ClassType, inherit: true)); - - foreach (TestPropertyAttribute attribute in attributes) + static bool ValidateAttributes(Attribute[] attributes, TestMethodInfo testMethodInfo, ITestContext testContext) { - if (!ValidateAndAssignTestProperty(testMethodInfo, testContext, attribute.Name, attribute.Value, isPredefinedAttribute: attribute is OwnerAttribute or PriorityAttribute)) + foreach (Attribute attribute in attributes) { - break; + if (attribute is not TestPropertyAttribute testPropertyAttribute) + { + continue; + } + + if (!ValidateAndAssignTestProperty(testMethodInfo, testContext, testPropertyAttribute.Name, testPropertyAttribute.Value, isPredefinedAttribute: attribute is OwnerAttribute or PriorityAttribute)) + { + return false; + } } + + return true; } } diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Helpers/ReflectHelper.cs b/src/Adapter/MSTestAdapter.PlatformServices/Helpers/ReflectHelper.cs index be1a1a8fe4..75868f2095 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Helpers/ReflectHelper.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Helpers/ReflectHelper.cs @@ -217,20 +217,52 @@ internal static bool IsDoNotParallelizeSet(Assembly assembly) /// /// The member to inspect. /// List of traits. - internal virtual IEnumerable GetTestPropertiesAsTraits(MemberInfo testPropertyProvider) + internal Trait[] GetTestPropertiesAsTraits(MethodInfo testPropertyProvider) { - IEnumerable testPropertyAttributes = GetAttributes(testPropertyProvider, inherit: true); + Attribute[] attributesFromMethod = GetCustomAttributesCached(testPropertyProvider, inherit: true); + Attribute[] attributesFromClass = testPropertyProvider.ReflectedType is { } testClass ? GetCustomAttributesCached(testClass, inherit: true) : []; + int countTestPropertyAttribute = 0; + foreach (Attribute attribute in attributesFromMethod) + { + if (attribute is TestPropertyAttribute) + { + countTestPropertyAttribute++; + } + } + + foreach (Attribute attribute in attributesFromClass) + { + if (attribute is TestPropertyAttribute) + { + countTestPropertyAttribute++; + } + } - if (testPropertyProvider.DeclaringType is { } testClass) + if (countTestPropertyAttribute == 0) { - testPropertyAttributes = testPropertyAttributes.Concat(GetAttributes(testClass, inherit: true)); + // This is the common case that we optimize for. This method used to be an iterator (uses yield return) which is allocating unnecessarily in common cases. + return []; } - foreach (TestPropertyAttribute testProperty in testPropertyAttributes) + var traits = new Trait[countTestPropertyAttribute]; + int index = 0; + foreach (Attribute attribute in attributesFromMethod) { - var testPropertyPair = new Trait(testProperty.Name, testProperty.Value); - yield return testPropertyPair; + if (attribute is TestPropertyAttribute testProperty) + { + traits[index++] = new Trait(testProperty.Name, testProperty.Value); + } } + + foreach (Attribute attribute in attributesFromClass) + { + if (attribute is TestPropertyAttribute testProperty) + { + traits[index++] = new Trait(testProperty.Name, testProperty.Value); + } + } + + return traits; } /// @@ -257,6 +289,30 @@ internal virtual IEnumerable GetTestPropertiesAsTraits(MemberInfo testPro } } + /// + /// Get attribute defined on a method which is of given type of subtype of given type. + /// + /// The attribute type. + /// The type of state to be passed to Action. + /// The member to inspect. + /// Look at inheritance chain. + /// The action to perform. + /// The state to pass to action. + internal void PerformActionOnAttribute(ICustomAttributeProvider attributeProvider, bool inherit, Action action, TState? state) + where TAttributeType : Attribute + { + Attribute[] attributes = GetCustomAttributesCached(attributeProvider, inherit); + foreach (Attribute attribute in attributes) + { + DebugEx.Assert(attribute != null, "ReflectHelper.DefinesAttributeDerivedFrom: internal error: wrong value in the attributes dictionary."); + + if (attribute is TAttributeType attributeAsAttributeType) + { + action(attributeAsAttributeType, state); + } + } + } + /// /// Gets and caches the attributes for the given type, or method. /// From 35af83c545c5e48b9a782c5d12b9b075c85ddc14 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Thu, 14 Aug 2025 07:50:57 +0200 Subject: [PATCH 397/541] Optimize tcm properties (#6372) --- .../Execution/TcmTestPropertiesProvider.cs | 45 ++++++++++--------- .../Execution/TestExecutionManager.cs | 9 +++- .../TcmTestPropertiesProviderTests.cs | 23 +++++----- 3 files changed, 42 insertions(+), 35 deletions(-) diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Execution/TcmTestPropertiesProvider.cs b/src/Adapter/MSTestAdapter.PlatformServices/Execution/TcmTestPropertiesProvider.cs index 5a80df389a..92d8534c6b 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Execution/TcmTestPropertiesProvider.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Execution/TcmTestPropertiesProvider.cs @@ -17,35 +17,36 @@ internal static class TcmTestPropertiesProvider /// /// Test case. /// Tcm properties. - public static IDictionary GetTcmProperties(TestPlatformObjectModel.TestCase? testCase) + public static IDictionary? GetTcmProperties(TestPlatformObjectModel.TestCase? testCase) { - var tcmProperties = new Dictionary(); - // Return empty properties when testCase is null or when test case id is zero. if (testCase == null || testCase.GetPropertyValue(EngineConstants.TestCaseIdProperty, default) == 0) { - return tcmProperties; + return null; } - // Step 1: Add common properties. - tcmProperties[EngineConstants.TestRunIdProperty] = testCase.GetPropertyValue(EngineConstants.TestRunIdProperty, default); - tcmProperties[EngineConstants.TestPlanIdProperty] = testCase.GetPropertyValue(EngineConstants.TestPlanIdProperty, default); - tcmProperties[EngineConstants.BuildConfigurationIdProperty] = testCase.GetPropertyValue(EngineConstants.BuildConfigurationIdProperty, default); - tcmProperties[EngineConstants.BuildDirectoryProperty] = testCase.GetPropertyValue(EngineConstants.BuildDirectoryProperty, default); - tcmProperties[EngineConstants.BuildFlavorProperty] = testCase.GetPropertyValue(EngineConstants.BuildFlavorProperty, default); - tcmProperties[EngineConstants.BuildNumberProperty] = testCase.GetPropertyValue(EngineConstants.BuildNumberProperty, default); - tcmProperties[EngineConstants.BuildPlatformProperty] = testCase.GetPropertyValue(EngineConstants.BuildPlatformProperty, default); - tcmProperties[EngineConstants.BuildUriProperty] = testCase.GetPropertyValue(EngineConstants.BuildUriProperty, default); - tcmProperties[EngineConstants.TfsServerCollectionUrlProperty] = testCase.GetPropertyValue(EngineConstants.TfsServerCollectionUrlProperty, default); - tcmProperties[EngineConstants.TfsTeamProjectProperty] = testCase.GetPropertyValue(EngineConstants.TfsTeamProjectProperty, default); - tcmProperties[EngineConstants.IsInLabEnvironmentProperty] = testCase.GetPropertyValue(EngineConstants.IsInLabEnvironmentProperty, default); - - // Step 2: Add test case specific properties. - tcmProperties[EngineConstants.TestCaseIdProperty] = testCase.GetPropertyValue(EngineConstants.TestCaseIdProperty, default); - tcmProperties[EngineConstants.TestConfigurationIdProperty] = testCase.GetPropertyValue(EngineConstants.TestConfigurationIdProperty, default); - tcmProperties[EngineConstants.TestConfigurationNameProperty] = testCase.GetPropertyValue(EngineConstants.TestConfigurationNameProperty, default); - tcmProperties[EngineConstants.TestPointIdProperty] = testCase.GetPropertyValue(EngineConstants.TestPointIdProperty, default); + var tcmProperties = new Dictionary(capacity: 15) + { + // Step 1: Add common properties. + [EngineConstants.TestRunIdProperty] = testCase.GetPropertyValue(EngineConstants.TestRunIdProperty, default), + [EngineConstants.TestPlanIdProperty] = testCase.GetPropertyValue(EngineConstants.TestPlanIdProperty, default), + [EngineConstants.BuildConfigurationIdProperty] = testCase.GetPropertyValue(EngineConstants.BuildConfigurationIdProperty, default), + [EngineConstants.BuildDirectoryProperty] = testCase.GetPropertyValue(EngineConstants.BuildDirectoryProperty, default), + [EngineConstants.BuildFlavorProperty] = testCase.GetPropertyValue(EngineConstants.BuildFlavorProperty, default), + [EngineConstants.BuildNumberProperty] = testCase.GetPropertyValue(EngineConstants.BuildNumberProperty, default), + [EngineConstants.BuildPlatformProperty] = testCase.GetPropertyValue(EngineConstants.BuildPlatformProperty, default), + [EngineConstants.BuildUriProperty] = testCase.GetPropertyValue(EngineConstants.BuildUriProperty, default), + [EngineConstants.TfsServerCollectionUrlProperty] = testCase.GetPropertyValue(EngineConstants.TfsServerCollectionUrlProperty, default), + [EngineConstants.TfsTeamProjectProperty] = testCase.GetPropertyValue(EngineConstants.TfsTeamProjectProperty, default), + [EngineConstants.IsInLabEnvironmentProperty] = testCase.GetPropertyValue(EngineConstants.IsInLabEnvironmentProperty, default), + + // Step 2: Add test case specific properties. + [EngineConstants.TestCaseIdProperty] = testCase.GetPropertyValue(EngineConstants.TestCaseIdProperty, default), + [EngineConstants.TestConfigurationIdProperty] = testCase.GetPropertyValue(EngineConstants.TestConfigurationIdProperty, default), + [EngineConstants.TestConfigurationNameProperty] = testCase.GetPropertyValue(EngineConstants.TestConfigurationNameProperty, default), + [EngineConstants.TestPointIdProperty] = testCase.GetPropertyValue(EngineConstants.TestPointIdProperty, default), + }; return tcmProperties; } diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestExecutionManager.cs b/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestExecutionManager.cs index 7f68de2fd7..d4d007b998 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestExecutionManager.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestExecutionManager.cs @@ -549,7 +549,7 @@ private async Task ExecuteTestsWithTestRunnerAsync( PlatformServiceProvider.Instance.AdapterTraceLogger.LogInfo("Executing test {0}", unitTestElement.TestMethod.Name); // Run single test passing test context properties to it. - IDictionary tcmProperties = TcmTestPropertiesProvider.GetTcmProperties(currentTest); + IDictionary? tcmProperties = TcmTestPropertiesProvider.GetTcmProperties(currentTest); Dictionary testContextProperties = GetTestContextProperties(tcmProperties, sourceLevelParameters); TestTools.UnitTesting.TestResult[] unitTestResult; @@ -623,9 +623,14 @@ private async Task ExecuteTestsWithTestRunnerAsync( /// Source level parameters. /// Test context properties. private static Dictionary GetTestContextProperties( - IDictionary tcmProperties, + IDictionary? tcmProperties, IDictionary sourceLevelParameters) { + if (tcmProperties is null) + { + return new Dictionary(sourceLevelParameters!); + } + // This dictionary will have *at least* 8 entries. Those are the sourceLevelParameters // which were originally calculated from TestDeployment.GetDeploymentInformation. var testContextProperties = new Dictionary(capacity: 8); diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TcmTestPropertiesProviderTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TcmTestPropertiesProviderTests.cs index 44116b386d..320b2de9a5 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TcmTestPropertiesProviderTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TcmTestPropertiesProviderTests.cs @@ -32,8 +32,8 @@ public class TcmTestPropertiesProviderTests : TestContainer public void GetTcmPropertiesShouldReturnEmptyDictionaryIfTestCaseIsNull() { - IDictionary tcmProperties = TcmTestPropertiesProvider.GetTcmProperties(null); - Verify(tcmProperties.Count == 0); + IDictionary? tcmProperties = TcmTestPropertiesProvider.GetTcmProperties(null); + Verify(tcmProperties is null); } public void GetTcmPropertiesShouldReturnEmptyDictionaryIfTestCaseIdIsZero() @@ -59,8 +59,8 @@ public void GetTcmPropertiesShouldReturnEmptyDictionaryIfTestCaseIdIsZero() ]; SetTestCaseProperties(testCase, propertiesValue); - IDictionary tcmProperties = TcmTestPropertiesProvider.GetTcmProperties(testCase); - Verify(tcmProperties.Count == 0); + IDictionary? tcmProperties = TcmTestPropertiesProvider.GetTcmProperties(testCase); + Verify(tcmProperties is null); } public void GetTcmPropertiesShouldGetAllPropertiesFromTestCase() @@ -86,7 +86,7 @@ public void GetTcmPropertiesShouldGetAllPropertiesFromTestCase() ]; SetTestCaseProperties(testCase, propertiesValue); - IDictionary tcmProperties = TcmTestPropertiesProvider.GetTcmProperties(testCase); + IDictionary? tcmProperties = TcmTestPropertiesProvider.GetTcmProperties(testCase); VerifyTcmProperties(tcmProperties, testCase); } @@ -114,7 +114,7 @@ public void GetTcmPropertiesShouldCopyMultiplePropertiesCorrectlyFromTestCase() 345 ]; SetTestCaseProperties(testCase1, propertiesValue1); - IDictionary tcmProperties1 = TcmTestPropertiesProvider.GetTcmProperties(testCase1); + IDictionary? tcmProperties1 = TcmTestPropertiesProvider.GetTcmProperties(testCase1); VerifyTcmProperties(tcmProperties1, testCase1); // Verify 2nd call. @@ -138,7 +138,7 @@ public void GetTcmPropertiesShouldCopyMultiplePropertiesCorrectlyFromTestCase() 346 ]; SetTestCaseProperties(testCase2, propertiesValue2); - IDictionary tcmProperties2 = TcmTestPropertiesProvider.GetTcmProperties(testCase2); + IDictionary? tcmProperties2 = TcmTestPropertiesProvider.GetTcmProperties(testCase2); VerifyTcmProperties(tcmProperties2, testCase2); } @@ -165,7 +165,7 @@ public void GetTcmPropertiesShouldHandleDuplicateTestsProperlyFromTestCase() 345 ]; SetTestCaseProperties(testCase1, propertiesValue1); - IDictionary tcmProperties1 = TcmTestPropertiesProvider.GetTcmProperties(testCase1); + IDictionary? tcmProperties1 = TcmTestPropertiesProvider.GetTcmProperties(testCase1); VerifyTcmProperties(tcmProperties1, testCase1); // Verify 2nd call. @@ -189,7 +189,7 @@ public void GetTcmPropertiesShouldHandleDuplicateTestsProperlyFromTestCase() 346 ]; SetTestCaseProperties(testCase2, propertiesValue2); - IDictionary tcmProperties2 = TcmTestPropertiesProvider.GetTcmProperties(testCase2); + IDictionary? tcmProperties2 = TcmTestPropertiesProvider.GetTcmProperties(testCase2); VerifyTcmProperties(tcmProperties2, testCase2); // Verify 3rd call. @@ -213,7 +213,7 @@ public void GetTcmPropertiesShouldHandleDuplicateTestsProperlyFromTestCase() 347 ]; SetTestCaseProperties(testCase3, propertiesValue3); - IDictionary tcmProperties3 = TcmTestPropertiesProvider.GetTcmProperties(testCase3); + IDictionary? tcmProperties3 = TcmTestPropertiesProvider.GetTcmProperties(testCase3); VerifyTcmProperties(tcmProperties3, testCase3); } @@ -230,8 +230,9 @@ private void SetTestCaseProperties(TestCase testCase, object[] propertiesValue) } } - private void VerifyTcmProperties(IDictionary tcmProperties, TestCase testCase) + private void VerifyTcmProperties(IDictionary? tcmProperties, TestCase testCase) { + Verify(tcmProperties is not null); foreach (TestProperty property in _tcmKnownProperties) { Verify(testCase.GetPropertyValue(property)!.Equals(tcmProperties[property])); From 23618a9c7ae0f0bb1ce5bad8c66e1f6858f04f35 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Thu, 14 Aug 2025 14:12:50 +0200 Subject: [PATCH 398/541] Early exit RunTestCleanupMethodAsync if no cleanups (#6379) --- .../Execution/TestMethodInfo.cs | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestMethodInfo.cs b/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestMethodInfo.cs index 97af7c95f6..8717823504 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestMethodInfo.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestMethodInfo.cs @@ -719,7 +719,10 @@ private static TestFailedException HandleMethodException(Exception ex, Exception { DebugEx.Assert(result != null, "result != null"); - if (_classInstance is null || !_isTestContextSet || _isTestCleanupInvoked) + if (_classInstance is null || !_isTestContextSet || _isTestCleanupInvoked || + // Fast check to see if we can return early. + // This avoids the code below that allocates CancellationTokenSource + !HasCleanupsToInvoke()) { #if NET6_0_OR_GREATER return; @@ -814,6 +817,15 @@ private static TestFailedException HandleMethodException(Exception ex, Exception #endif } + private bool HasCleanupsToInvoke() => + Parent.TestCleanupMethod is not null || + Parent.BaseTestCleanupMethodsQueue is { Count: > 0 } || + _classInstance is IDisposable || +#if NET6_0_OR_GREATER + _classInstance is IAsyncDisposable || +#endif + Parent.Parent.GlobalTestCleanups is { Count: > 0 }; + /// /// Runs TestInitialize methods of parent TestClass and the base classes. /// From 6a4eb60360fc24ad9e9c7e66e4d11f84f03f8c8d Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Thu, 14 Aug 2025 14:14:49 +0200 Subject: [PATCH 399/541] Don't store fixture tests when the feature isn't used (#6378) --- .../Execution/UnitTestRunner.cs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Execution/UnitTestRunner.cs b/src/Adapter/MSTestAdapter.PlatformServices/Execution/UnitTestRunner.cs index 7e8a8d9f92..f554851dba 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Execution/UnitTestRunner.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Execution/UnitTestRunner.cs @@ -172,8 +172,11 @@ internal async Task RunSingleTestAsync(TestMethod testMethod, IDic DebugEx.Assert(testMethodInfo is not null, "testMethodInfo should not be null."); // Keep track of all non-runnable methods so that we can return the appropriate result at the end. - _assemblyFixtureTests.TryAdd(testMethod.AssemblyName, testMethodInfo.Parent.Parent); - _classFixtureTests.TryAdd(testMethod.AssemblyName + testMethod.FullClassName, testMethodInfo.Parent); + if (MSTestSettings.CurrentSettings.ConsiderFixturesAsSpecialTests) + { + _assemblyFixtureTests.TryAdd(testMethod.AssemblyName, testMethodInfo.Parent.Parent); + _classFixtureTests.TryAdd(testMethod.AssemblyName + testMethod.FullClassName, testMethodInfo.Parent); + } testContextForAssemblyInit = PlatformServiceProvider.Instance.GetTestContext(testMethod, testContextProperties, messageLogger, testContextForTestExecution.Context.CurrentTestOutcome); From 26e9583afe1c21c3d4fb89ca3628f80a298e8f30 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Thu, 14 Aug 2025 17:46:42 +0200 Subject: [PATCH 400/541] Avoid LINQ in TryExecuteFoldedDataDrivenTestsAsync (#6376) --- .../Execution/TestMethodRunner.cs | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestMethodRunner.cs b/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestMethodRunner.cs index de0d83bb16..e9791ad0b4 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestMethodRunner.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestMethodRunner.cs @@ -263,14 +263,15 @@ private async Task TryExecuteDataSourceBasedTestsAsync(List re private async Task TryExecuteFoldedDataDrivenTestsAsync(List results) { - IEnumerable? testDataSources = _testMethodInfo.GetAttributes(false)?.OfType(); - if (testDataSources?.Any() != true) + bool hasTestDataSource = false; + foreach (Attribute attribute in ReflectHelper.Instance.GetCustomAttributesCached(_testMethodInfo.MethodInfo, false)) { - return false; - } + if (attribute is not UTF.ITestDataSource testDataSource) + { + continue; + } - foreach (UTF.ITestDataSource testDataSource in testDataSources) - { + hasTestDataSource = true; if (testDataSource is ITestDataSourceIgnoreCapability { IgnoreMessage: { } ignoreMessage }) { results.Add(TestResult.CreateIgnoredResult(ignoreMessage)); @@ -313,7 +314,7 @@ private async Task TryExecuteFoldedDataDrivenTestsAsync(List r } } - return true; + return hasTestDataSource; } private async Task ExecuteTestFromDataSourceAttributeAsync(List results) From 04e470b4ce1be33c350eff0f16798650dc0becea Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Fri, 15 Aug 2025 06:22:27 +0200 Subject: [PATCH 401/541] [main] Update dependencies from microsoft/testfx (#6386) Co-authored-by: dotnet-maestro[bot] --- eng/Version.Details.xml | 8 ++++---- eng/Versions.props | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index 7d999df090..5774d2dac9 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -17,13 +17,13 @@ https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage 707da42f9e3e7d31c4ca03c2823cd75a9ddd4a98 - + https://github.com/microsoft/testfx - 26b1f1b86bbaa1c524e4b91c6bbd838687ea23cc + 26e9583afe1c21c3d4fb89ca3628f80a298e8f30 - + https://github.com/microsoft/testfx - 26b1f1b86bbaa1c524e4b91c6bbd838687ea23cc + 26e9583afe1c21c3d4fb89ca3628f80a298e8f30 diff --git a/eng/Versions.props b/eng/Versions.props index 928421be20..17888d41d4 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -10,7 +10,7 @@ 10.0.0-beta.25413.1 18.0.0-preview.25413.2 - 3.11.0-preview.25413.5 - 1.9.0-preview.25413.5 + 3.11.0-preview.25414.4 + 1.9.0-preview.25414.4 From 4009af14e25d18074c19c086ad8b644e31c266c8 Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Fri, 15 Aug 2025 06:22:49 +0200 Subject: [PATCH 402/541] [main] Update dependencies from devdiv/DevDiv/vs-code-coverage (#6385) Co-authored-by: dotnet-maestro[bot] --- eng/Version.Details.xml | 4 ++-- eng/Versions.props | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index 5774d2dac9..0d5b7bbea3 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -13,9 +13,9 @@ https://github.com/dotnet/arcade ea9e51a7080f13abb409a9dcfd9ea957ecab01ae - + https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage - 707da42f9e3e7d31c4ca03c2823cd75a9ddd4a98 + dd3e010148361acad26e2ed22061ab61b1c9c976 https://github.com/microsoft/testfx diff --git a/eng/Versions.props b/eng/Versions.props index 17888d41d4..64280158e4 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -8,7 +8,7 @@ 10.0.0-beta.25413.1 - 18.0.0-preview.25413.2 + 18.0.0-preview.25414.4 3.11.0-preview.25414.4 1.9.0-preview.25414.4 From c3a3bf49f7f336dd9ac737841382895b108b9e12 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Fri, 15 Aug 2025 11:04:58 +0200 Subject: [PATCH 403/541] Add missing MSTest.GlobalConfigsGenerator to MSTest.slnf (#6388) --- MSTest.slnf | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/MSTest.slnf b/MSTest.slnf index 5b52bd185f..0c106eb1f7 100644 --- a/MSTest.slnf +++ b/MSTest.slnf @@ -9,6 +9,7 @@ "src\\Analyzers\\MSTest.Analyzers.CodeFixes\\MSTest.Analyzers.CodeFixes.csproj", "src\\Analyzers\\MSTest.Analyzers.Package\\MSTest.Analyzers.Package.csproj", "src\\Analyzers\\MSTest.Analyzers\\MSTest.Analyzers.csproj", + "src\\Analyzers\\MSTest.GlobalConfigsGenerator\\MSTest.GlobalConfigsGenerator.csproj", "src\\Package\\MSTest.Sdk\\MSTest.Sdk.csproj", "src\\Package\\MSTest\\MSTest.csproj", "src\\TestFramework\\TestFramework.Extensions\\TestFramework.Extensions.csproj", @@ -58,4 +59,4 @@ "test\\Utilities\\TestFramework.ForTestingMSTest\\TestFramework.ForTestingMSTest.csproj" ] } -} \ No newline at end of file +} From ebb88a49ff4a58258cec98d36dd463f1a0ed1a83 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Jare=C5=A1?= Date: Fri, 15 Aug 2025 12:39:48 +0200 Subject: [PATCH 404/541] Fix equal sign in file name (#6389) --- .../Services/FileOperations.cs | 6 +++++- .../Services/FileOperationsTests.cs | 14 ++++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Services/FileOperations.cs b/src/Adapter/MSTestAdapter.PlatformServices/Services/FileOperations.cs index 7fb908212a..d62f517c60 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Services/FileOperations.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Services/FileOperations.cs @@ -45,7 +45,11 @@ public Assembly LoadAssembly(string assemblyName, bool isReflectionOnly) } #endif string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(assemblyName); - Assembly assembly = _assemblyCache.GetOrAdd(fileNameWithoutExtension, fileNameWithoutExtension => Assembly.Load(new AssemblyName(fileNameWithoutExtension))); + // Do NOT use `new AssemblyName(fileNameWithoutExtension)` here. The provided string is a FullName of assembly and needs to be properly escaped (but there is no utility for it). + // To correctly construct AssemblyName from file name, we need to just set the Name, and it will be escaped correct when constructing FullName. + // https://github.com/dotnet/runtime/blob/da322a2260bcb07347df3082fca211987ec8f2fc/src/libraries/Common/src/System/Reflection/AssemblyNameFormatter.cs#L120 + // When we did it wrong the exception thrown is "The given assembly name was invalid." for files that have `=` or any other special characters in their names (see the AssemblyNameFormatter.cs code). + Assembly assembly = _assemblyCache.GetOrAdd(fileNameWithoutExtension, fileNameWithoutExtension => Assembly.Load(new AssemblyName { Name = fileNameWithoutExtension })); return assembly; #elif NETFRAMEWORK diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/FileOperationsTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/FileOperationsTests.cs index dfb8ee49d4..8d09fe5e9d 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/FileOperationsTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/FileOperationsTests.cs @@ -26,6 +26,20 @@ public void LoadAssemblyShouldThrowExceptionIfTheFileNameHasInvalidCharacters() #endif } + public void LoadAssemblyShouldNotThrowFileLoadExceptionIfTheFileNameHasValidFileCharacterButInvalidFullAssemblyNameCharacter() + { +#if NETCOREAPP + // = (for example) is a valid file name character, but not a valid character in an full assembly name. + // If we construct assembly name by calling new AssemblyName(filePath), it will throw FileLoadException for a correct file name. + // This test is checking that. It still fails with FileNotFoundException, because the file does not exist, but it should not throw FileLoadException. + // (The FileLoadException used for the unparseable name is weird choice, and confusing to me, but that is what the runtime decided to do. No dll is being loaded.) + string filePath = "temp=txt"; + void A() => _fileOperations.LoadAssembly(filePath, false); + + VerifyThrows(A); +#endif + } + public void LoadAssemblyShouldThrowExceptionIfFileIsNotFound() => VerifyThrows(() => _fileOperations.LoadAssembly("temptxt", false)); From c80125587262e91e86b731fbbfee68a372a36a95 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Fri, 15 Aug 2025 14:46:46 +0200 Subject: [PATCH 405/541] Add more missing projects to MSTest.slnf (#6391) --- MSTest.slnf | 2 ++ 1 file changed, 2 insertions(+) diff --git a/MSTest.slnf b/MSTest.slnf index 0c106eb1f7..c629708190 100644 --- a/MSTest.slnf +++ b/MSTest.slnf @@ -4,12 +4,14 @@ "projects": [ "samples\\FxExtensibility\\FxExtensibility.csproj", "samples\\Playground\\Playground.csproj", + "src\\Adapter\\MSTest.Engine\\MSTest.Engine.csproj", "src\\Adapter\\MSTest.TestAdapter\\MSTest.TestAdapter.csproj", "src\\Adapter\\MSTestAdapter.PlatformServices\\MSTestAdapter.PlatformServices.csproj", "src\\Analyzers\\MSTest.Analyzers.CodeFixes\\MSTest.Analyzers.CodeFixes.csproj", "src\\Analyzers\\MSTest.Analyzers.Package\\MSTest.Analyzers.Package.csproj", "src\\Analyzers\\MSTest.Analyzers\\MSTest.Analyzers.csproj", "src\\Analyzers\\MSTest.GlobalConfigsGenerator\\MSTest.GlobalConfigsGenerator.csproj", + "src\\Analyzers\\MSTest.SourceGeneration\\MSTest.SourceGeneration.csproj", "src\\Package\\MSTest.Sdk\\MSTest.Sdk.csproj", "src\\Package\\MSTest\\MSTest.csproj", "src\\TestFramework\\TestFramework.Extensions\\TestFramework.Extensions.csproj", From 18e769d3f1b48ff5533c11dc057c50ac967a336f Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Fri, 15 Aug 2025 22:35:05 +0200 Subject: [PATCH 406/541] Remove unused JsonRpc protocol properties (#6395) --- docs/mstest-runner-protocol/001-protocol-intro.md | 6 ------ .../ServerMode/JsonRpc/Json/Json.cs | 2 -- .../ServerMode/JsonRpc/SerializerUtilities.cs | 2 -- .../ServerMode/FormatterUtilitiesTests.cs | 4 ++-- 4 files changed, 2 insertions(+), 12 deletions(-) diff --git a/docs/mstest-runner-protocol/001-protocol-intro.md b/docs/mstest-runner-protocol/001-protocol-intro.md index 98b662980f..5f2d04539c 100644 --- a/docs/mstest-runner-protocol/001-protocol-intro.md +++ b/docs/mstest-runner-protocol/001-protocol-intro.md @@ -394,12 +394,6 @@ interface TestNode { // Example: "time.duration-ms": 45.8143, 'time.duration-ms'?: number; - // Example: "time.start-utc": "2023-06-20T11:09:41.6882661+00:00" - 'time.start-utc'?: string; - - // Example: "time.stop-utc": "2023-06-20T11:09:41.6882661+00:00" - 'time.stop-utc'?: string; - // Note: The error consists of the stacktrace, error message and also the assertion properties. // If assertion properties are missing the exception would show in the UI as: // Message: diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/Json/Json.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/Json/Json.cs index 0b8952079c..e2597d52b6 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/Json/Json.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/Json/Json.cs @@ -270,8 +270,6 @@ public Json(Dictionary? serializers = null, Dictionary Date: Sat, 16 Aug 2025 06:50:11 +0200 Subject: [PATCH 407/541] Avoid unnecessary `List` allocations in ObjectModelConverters (#6396) --- .../ObjectModel/ObjectModelConverters.cs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/ObjectModelConverters.cs b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/ObjectModelConverters.cs index 46a63890ef..66ea0696b2 100644 --- a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/ObjectModelConverters.cs +++ b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/ObjectModelConverters.cs @@ -181,8 +181,8 @@ public static TestNode ToTestNode( testNode.Properties.Add(new TimingProperty(new(testResult.StartTime, testResult.EndTime, testResult.Duration), [])); - var standardErrorMessages = new List(); - var standardOutputMessages = new List(); + List? standardErrorMessages = null; + List? standardOutputMessages = null; bool addVSTestProviderProperties = ShouldAddVSTestProviderProperties(namedFeatureCapability, commandLineOptions); foreach (TestResultMessage testResultMessage in testResult.Messages) { @@ -194,7 +194,7 @@ public static TestNode ToTestNode( testNode.Properties.Add(new SerializableKeyValuePairStringProperty("vstest.TestCase.StandardError", message)); } - standardErrorMessages.Add(message); + (standardErrorMessages ??= []).Add(message); } if (testResultMessage.Category == TestResultMessage.StandardOutCategory) @@ -205,7 +205,7 @@ public static TestNode ToTestNode( testNode.Properties.Add(new SerializableKeyValuePairStringProperty("vstest.TestCase.StandardOutput", message)); } - standardOutputMessages.Add(message); + (standardOutputMessages ??= []).Add(message); } } @@ -217,12 +217,12 @@ public static TestNode ToTestNode( } } - if (standardErrorMessages.Count > 0) + if (standardErrorMessages is { Count: > 0 }) { testNode.Properties.Add(new StandardErrorProperty(string.Join(Environment.NewLine, standardErrorMessages))); } - if (standardOutputMessages.Count > 0) + if (standardOutputMessages is { Count: > 0 }) { testNode.Properties.Add(new StandardOutputProperty(string.Join(Environment.NewLine, standardOutputMessages))); } From c46f272638470abed4a639e2b10ba7ff3fd7fe72 Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Sat, 16 Aug 2025 08:44:50 +0200 Subject: [PATCH 408/541] [main] Update dependencies from dotnet/arcade (#6397) Co-authored-by: dotnet-maestro[bot] --- eng/Version.Details.xml | 12 ++--- eng/Versions.props | 2 +- .../steps/install-microbuild.yml | 6 +-- eng/common/generate-locproject.ps1 | 49 ++++++++++++++++--- eng/common/tools.ps1 | 6 ++- global.json | 2 +- 6 files changed, 57 insertions(+), 20 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index 0d5b7bbea3..e00b8ac454 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -1,17 +1,17 @@ - + https://github.com/dotnet/arcade - ea9e51a7080f13abb409a9dcfd9ea957ecab01ae + fac534d85b77789bd4daf2b4c916117f1ca381e7 - + https://github.com/dotnet/arcade - ea9e51a7080f13abb409a9dcfd9ea957ecab01ae + fac534d85b77789bd4daf2b4c916117f1ca381e7 - + https://github.com/dotnet/arcade - ea9e51a7080f13abb409a9dcfd9ea957ecab01ae + fac534d85b77789bd4daf2b4c916117f1ca381e7 https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage diff --git a/eng/Versions.props b/eng/Versions.props index 64280158e4..20d4ef0733 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -7,7 +7,7 @@ preview - 10.0.0-beta.25413.1 + 10.0.0-beta.25414.2 18.0.0-preview.25414.4 3.11.0-preview.25414.4 diff --git a/eng/common/core-templates/steps/install-microbuild.yml b/eng/common/core-templates/steps/install-microbuild.yml index da30e67bc3..f614d1440e 100644 --- a/eng/common/core-templates/steps/install-microbuild.yml +++ b/eng/common/core-templates/steps/install-microbuild.yml @@ -53,10 +53,8 @@ steps: zipSources: false feedSource: https://dnceng.pkgs.visualstudio.com/_packaging/MicroBuildToolset/nuget/v3/index.json ${{ if eq(parameters.microbuildUseESRP, true) }}: - ${{ if eq(parameters.enableMicrobuildForMacAndLinux, 'true') }}: - azureSubscription: 'MicroBuild Signing Task (DevDiv)' - useEsrpCli: true - ${{ elseif eq(variables['System.TeamProject'], 'DevDiv') }}: + ConnectedServiceName: 'MicroBuild Signing Task (DevDiv)' + ${{ if eq(variables['System.TeamProject'], 'DevDiv') }}: ConnectedPMEServiceName: 6cc74545-d7b9-4050-9dfa-ebefcc8961ea ${{ else }}: ConnectedPMEServiceName: 248d384a-b39b-46e3-8ad5-c2c210d5e7ca diff --git a/eng/common/generate-locproject.ps1 b/eng/common/generate-locproject.ps1 index 524aaa57f2..fa1cdc2b30 100644 --- a/eng/common/generate-locproject.ps1 +++ b/eng/common/generate-locproject.ps1 @@ -33,15 +33,27 @@ $jsonTemplateFiles | ForEach-Object { $jsonWinformsTemplateFiles = Get-ChildItem -Recurse -Path "$SourcesDirectory" | Where-Object { $_.FullName -Match "en\\strings\.json" } # current winforms pattern +$wxlFilesV3 = @() +$wxlFilesV5 = @() $wxlFiles = Get-ChildItem -Recurse -Path "$SourcesDirectory" | Where-Object { $_.FullName -Match "\\.+\.wxl" -And -Not( $_.Directory.Name -Match "\d{4}" ) } # localized files live in four digit lang ID directories; this excludes them if (-not $wxlFiles) { $wxlEnFiles = Get-ChildItem -Recurse -Path "$SourcesDirectory" | Where-Object { $_.FullName -Match "\\1033\\.+\.wxl" } # pick up en files (1033 = en) specifically so we can copy them to use as the neutral xlf files if ($wxlEnFiles) { - $wxlFiles = @() - $wxlEnFiles | ForEach-Object { - $destinationFile = "$($_.Directory.Parent.FullName)\$($_.Name)" - $wxlFiles += Copy-Item "$($_.FullName)" -Destination $destinationFile -PassThru - } + $wxlFiles = @() + $wxlEnFiles | ForEach-Object { + $destinationFile = "$($_.Directory.Parent.FullName)\$($_.Name)" + $content = Get-Content $_.FullName -Raw + + # Split files on schema to select different parser settings in the generated project. + if ($content -like "*http://wixtoolset.org/schemas/v4/wxl*") + { + $wxlFilesV5 += Copy-Item $_.FullName -Destination $destinationFile -PassThru + } + elseif ($content -like "*http://schemas.microsoft.com/wix/2006/localization*") + { + $wxlFilesV3 += Copy-Item $_.FullName -Destination $destinationFile -PassThru + } + } } } @@ -114,7 +126,32 @@ $locJson = @{ CloneLanguageSet = "WiX_CloneLanguages" LssFiles = @( "wxl_loc.lss" ) LocItems = @( - $wxlFiles | ForEach-Object { + $wxlFilesV3 | ForEach-Object { + $outputPath = "$($_.Directory.FullName | Resolve-Path -Relative)\" + $continue = $true + foreach ($exclusion in $exclusions.Exclusions) { + if ($_.FullName.Contains($exclusion)) { + $continue = $false + } + } + $sourceFile = ($_.FullName | Resolve-Path -Relative) + if ($continue) + { + return @{ + SourceFile = $sourceFile + CopyOption = "LangIDOnPath" + OutputPath = $outputPath + } + } + } + ) + }, + @{ + LanguageSet = $LanguageSet + CloneLanguageSet = "WiX_CloneLanguages" + LssFiles = @( "P210WxlSchemaV4.lss" ) + LocItems = @( + $wxlFilesV5 | ForEach-Object { $outputPath = "$($_.Directory.FullName | Resolve-Path -Relative)\" $continue = $true foreach ($exclusion in $exclusions.Exclusions) { diff --git a/eng/common/tools.ps1 b/eng/common/tools.ps1 index d4cfd9ccd8..4920464cc4 100644 --- a/eng/common/tools.ps1 +++ b/eng/common/tools.ps1 @@ -544,7 +544,8 @@ function LocateVisualStudio([object]$vsRequirements = $null){ if (Get-Member -InputObject $GlobalJson.tools -Name 'vswhere') { $vswhereVersion = $GlobalJson.tools.vswhere } else { - $vswhereVersion = '2.5.2' + # keep this in sync with the VSWhereVersion in DefaultVersions.props + $vswhereVersion = '3.1.7' } $vsWhereDir = Join-Path $ToolsDir "vswhere\$vswhereVersion" @@ -552,7 +553,8 @@ function LocateVisualStudio([object]$vsRequirements = $null){ if (!(Test-Path $vsWhereExe)) { Create-Directory $vsWhereDir - Write-Host 'Downloading vswhere' + Write-Host 'Downloading vswhere $vswhereVersion' + $ProgressPreference = 'SilentlyContinue' # Don't display the console progress UI - it's a huge perf hit Retry({ Invoke-WebRequest "https://netcorenativeassets.blob.core.windows.net/resource-packages/external/windows/vswhere/$vswhereVersion/vswhere.exe" -OutFile $vswhereExe }) diff --git a/global.json b/global.json index 854a24144a..ff9e479dc4 100644 --- a/global.json +++ b/global.json @@ -33,7 +33,7 @@ "rollForward": "latestFeature" }, "msbuild-sdks": { - "Microsoft.DotNet.Arcade.Sdk": "10.0.0-beta.25413.1", + "Microsoft.DotNet.Arcade.Sdk": "10.0.0-beta.25414.2", "MSBuild.Sdk.Extras": "3.0.44" } } From 4fff5964ffc55cda6384546c29a1c44fb0b37a8a Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Sat, 16 Aug 2025 08:45:23 +0200 Subject: [PATCH 409/541] [main] Update dependencies from microsoft/testfx (#6398) Co-authored-by: dotnet-maestro[bot] --- eng/Version.Details.xml | 8 ++++---- eng/Versions.props | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index e00b8ac454..be61bc0cb6 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -17,13 +17,13 @@ https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage dd3e010148361acad26e2ed22061ab61b1c9c976 - + https://github.com/microsoft/testfx - 26e9583afe1c21c3d4fb89ca3628f80a298e8f30 + 18e769d3f1b48ff5533c11dc057c50ac967a336f - + https://github.com/microsoft/testfx - 26e9583afe1c21c3d4fb89ca3628f80a298e8f30 + 18e769d3f1b48ff5533c11dc057c50ac967a336f diff --git a/eng/Versions.props b/eng/Versions.props index 20d4ef0733..2383cee971 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -10,7 +10,7 @@ 10.0.0-beta.25414.2 18.0.0-preview.25414.4 - 3.11.0-preview.25414.4 - 1.9.0-preview.25414.4 + 3.11.0-preview.25415.10 + 1.9.0-preview.25415.10 From ed62f8edbccce6b5bb3d837bb5b214e62af3a1d6 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Sat, 16 Aug 2025 12:33:46 +0200 Subject: [PATCH 410/541] Cleanup MS.CA version for source gen (#6399) --- Directory.Packages.props | 2 +- .../MSTest.SourceGeneration/MSTest.SourceGeneration.csproj | 2 +- .../MSTest.SourceGeneration.UnitTests.csproj | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Directory.Packages.props b/Directory.Packages.props index 784d1ceb9b..bdb6f86c35 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -16,6 +16,7 @@ 17.11.4 3.11.0 4.10.0 + 4.8.0 4.14.0 $(MicrosoftCodeAnalysisPublicApiAnalyzersVersion) @@ -43,7 +44,6 @@ - diff --git a/src/Analyzers/MSTest.SourceGeneration/MSTest.SourceGeneration.csproj b/src/Analyzers/MSTest.SourceGeneration/MSTest.SourceGeneration.csproj index 4f3d375201..3eb6317ab6 100644 --- a/src/Analyzers/MSTest.SourceGeneration/MSTest.SourceGeneration.csproj +++ b/src/Analyzers/MSTest.SourceGeneration/MSTest.SourceGeneration.csproj @@ -39,7 +39,7 @@ This package provides the C# source generators for MSTest test framework.]]> - + diff --git a/test/UnitTests/MSTest.SourceGeneration.UnitTests/MSTest.SourceGeneration.UnitTests.csproj b/test/UnitTests/MSTest.SourceGeneration.UnitTests/MSTest.SourceGeneration.UnitTests.csproj index 6921c11bde..5813aaa051 100644 --- a/test/UnitTests/MSTest.SourceGeneration.UnitTests/MSTest.SourceGeneration.UnitTests.csproj +++ b/test/UnitTests/MSTest.SourceGeneration.UnitTests/MSTest.SourceGeneration.UnitTests.csproj @@ -10,7 +10,7 @@ - + From 0870449c3bf24d5207dd49b8719beab97e30ecfd Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Mon, 18 Aug 2025 07:05:48 +0200 Subject: [PATCH 411/541] [main] Update dependencies from microsoft/testfx (#6401) Co-authored-by: dotnet-maestro[bot] --- eng/Version.Details.xml | 8 ++++---- eng/Versions.props | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index be61bc0cb6..661aa48267 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -17,13 +17,13 @@ https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage dd3e010148361acad26e2ed22061ab61b1c9c976 - + https://github.com/microsoft/testfx - 18e769d3f1b48ff5533c11dc057c50ac967a336f + 5182881d93b55c942460dc43ebbcfa87a2fb84bd - + https://github.com/microsoft/testfx - 18e769d3f1b48ff5533c11dc057c50ac967a336f + 5182881d93b55c942460dc43ebbcfa87a2fb84bd diff --git a/eng/Versions.props b/eng/Versions.props index 2383cee971..3cd8a45ea7 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -10,7 +10,7 @@ 10.0.0-beta.25414.2 18.0.0-preview.25414.4 - 3.11.0-preview.25415.10 - 1.9.0-preview.25415.10 + 3.11.0-preview.25415.13 + 1.9.0-preview.25415.13 From 7dbbb116afea737b0c4078e81d0368d331cff72e Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Mon, 18 Aug 2025 07:30:29 +0200 Subject: [PATCH 412/541] [main] Update dependencies from dotnet/arcade (#6400) Co-authored-by: dotnet-maestro[bot] --- eng/Version.Details.xml | 12 +++--- eng/Versions.props | 2 +- eng/common/SetupNugetSources.ps1 | 4 +- eng/common/SetupNugetSources.sh | 4 +- eng/common/core-templates/job/job.yml | 6 +-- eng/common/core-templates/job/onelocbuild.yml | 6 +-- .../job/publish-build-assets.yml | 10 +++-- .../core-templates/jobs/codeql-build.yml | 2 +- eng/common/core-templates/jobs/jobs.yml | 2 + .../core-templates/post-build/post-build.yml | 8 ++-- .../post-build/setup-maestro-vars.yml | 2 +- .../steps/enable-internal-sources.yml | 12 +++--- .../core-templates/steps/generate-sbom.yml | 2 +- .../steps/install-microbuild.yml | 41 ++++++++++++------- .../core-templates/steps/publish-logs.yml | 14 +++---- .../steps/source-index-stage1-publish.yml | 2 +- eng/common/template-guidance.md | 2 +- eng/common/templates-official/job/job.yml | 2 +- .../variables/sdl-variables.yml | 2 +- eng/common/templates/job/job.yml | 4 +- global.json | 2 +- 21 files changed, 79 insertions(+), 62 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index 661aa48267..59d2376b14 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -1,17 +1,17 @@ - + https://github.com/dotnet/arcade - fac534d85b77789bd4daf2b4c916117f1ca381e7 + e58b086a85a1df5762c8980308f7e4e330edd0aa - + https://github.com/dotnet/arcade - fac534d85b77789bd4daf2b4c916117f1ca381e7 + e58b086a85a1df5762c8980308f7e4e330edd0aa - + https://github.com/dotnet/arcade - fac534d85b77789bd4daf2b4c916117f1ca381e7 + e58b086a85a1df5762c8980308f7e4e330edd0aa https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage diff --git a/eng/Versions.props b/eng/Versions.props index 3cd8a45ea7..fa95b356e1 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -7,7 +7,7 @@ preview - 10.0.0-beta.25414.2 + 10.0.0-beta.25415.5 18.0.0-preview.25414.4 3.11.0-preview.25415.13 diff --git a/eng/common/SetupNugetSources.ps1 b/eng/common/SetupNugetSources.ps1 index 5db4ad71ee..792b60b49d 100644 --- a/eng/common/SetupNugetSources.ps1 +++ b/eng/common/SetupNugetSources.ps1 @@ -10,8 +10,8 @@ # displayName: Setup Private Feeds Credentials # condition: eq(variables['Agent.OS'], 'Windows_NT') # inputs: -# filePath: $(Build.SourcesDirectory)/eng/common/SetupNugetSources.ps1 -# arguments: -ConfigFile $(Build.SourcesDirectory)/NuGet.config -Password $Env:Token +# filePath: $(System.DefaultWorkingDirectory)/eng/common/SetupNugetSources.ps1 +# arguments: -ConfigFile $(System.DefaultWorkingDirectory)/NuGet.config -Password $Env:Token # env: # Token: $(dn-bot-dnceng-artifact-feeds-rw) # diff --git a/eng/common/SetupNugetSources.sh b/eng/common/SetupNugetSources.sh index 4604b61b03..facb415ca6 100644 --- a/eng/common/SetupNugetSources.sh +++ b/eng/common/SetupNugetSources.sh @@ -11,8 +11,8 @@ # - task: Bash@3 # displayName: Setup Internal Feeds # inputs: -# filePath: $(Build.SourcesDirectory)/eng/common/SetupNugetSources.sh -# arguments: $(Build.SourcesDirectory)/NuGet.config +# filePath: $(System.DefaultWorkingDirectory)/eng/common/SetupNugetSources.sh +# arguments: $(System.DefaultWorkingDirectory)/NuGet.config # condition: ne(variables['Agent.OS'], 'Windows_NT') # - task: NuGetAuthenticate@1 # diff --git a/eng/common/core-templates/job/job.yml b/eng/common/core-templates/job/job.yml index d901325154..5ce5184061 100644 --- a/eng/common/core-templates/job/job.yml +++ b/eng/common/core-templates/job/job.yml @@ -163,7 +163,7 @@ jobs: inputs: testResultsFormat: 'xUnit' testResultsFiles: '*.xml' - searchFolder: '$(Build.SourcesDirectory)/artifacts/TestResults/$(_BuildConfig)' + searchFolder: '$(System.DefaultWorkingDirectory)/artifacts/TestResults/$(_BuildConfig)' testRunTitle: ${{ coalesce(parameters.testRunTitle, parameters.name, '$(System.JobName)') }}-xunit mergeTestResults: ${{ parameters.mergeTestResults }} continueOnError: true @@ -174,7 +174,7 @@ jobs: inputs: testResultsFormat: 'VSTest' testResultsFiles: '*.trx' - searchFolder: '$(Build.SourcesDirectory)/artifacts/TestResults/$(_BuildConfig)' + searchFolder: '$(System.DefaultWorkingDirectory)/artifacts/TestResults/$(_BuildConfig)' testRunTitle: ${{ coalesce(parameters.testRunTitle, parameters.name, '$(System.JobName)') }}-trx mergeTestResults: ${{ parameters.mergeTestResults }} continueOnError: true @@ -218,7 +218,7 @@ jobs: - task: CopyFiles@2 displayName: Gather buildconfiguration for build retry inputs: - SourceFolder: '$(Build.SourcesDirectory)/eng/common/BuildConfiguration' + SourceFolder: '$(System.DefaultWorkingDirectory)/eng/common/BuildConfiguration' Contents: '**' TargetFolder: '$(Build.ArtifactStagingDirectory)/eng/common/BuildConfiguration' continueOnError: true diff --git a/eng/common/core-templates/job/onelocbuild.yml b/eng/common/core-templates/job/onelocbuild.yml index 8bf7d23355..c5788829a8 100644 --- a/eng/common/core-templates/job/onelocbuild.yml +++ b/eng/common/core-templates/job/onelocbuild.yml @@ -8,7 +8,7 @@ parameters: CeapexPat: $(dn-bot-ceapex-package-r) # PAT for the loc AzDO instance https://dev.azure.com/ceapex GithubPat: $(BotAccount-dotnet-bot-repo-PAT) - SourcesDirectory: $(Build.SourcesDirectory) + SourcesDirectory: $(System.DefaultWorkingDirectory) CreatePr: true AutoCompletePr: false ReusePr: true @@ -68,7 +68,7 @@ jobs: - ${{ if ne(parameters.SkipLocProjectJsonGeneration, 'true') }}: - task: Powershell@2 inputs: - filePath: $(Build.SourcesDirectory)/eng/common/generate-locproject.ps1 + filePath: $(System.DefaultWorkingDirectory)/eng/common/generate-locproject.ps1 arguments: $(_GenerateLocProjectArguments) displayName: Generate LocProject.json condition: ${{ parameters.condition }} @@ -103,7 +103,7 @@ jobs: - task: CopyFiles@2 displayName: Copy LocProject.json inputs: - SourceFolder: '$(Build.SourcesDirectory)/eng/Localize/' + SourceFolder: '$(System.DefaultWorkingDirectory)/eng/Localize/' Contents: 'LocProject.json' TargetFolder: '$(Build.ArtifactStagingDirectory)/loc' condition: ${{ parameters.condition }} diff --git a/eng/common/core-templates/job/publish-build-assets.yml b/eng/common/core-templates/job/publish-build-assets.yml index d5303229c9..348cd16376 100644 --- a/eng/common/core-templates/job/publish-build-assets.yml +++ b/eng/common/core-templates/job/publish-build-assets.yml @@ -38,6 +38,8 @@ parameters: # Optional: A minimatch pattern for the asset manifests to publish to BAR assetManifestsPattern: '*/manifests/**/*.xml' + repositoryAlias: self + jobs: - job: Asset_Registry_Publish @@ -78,7 +80,7 @@ jobs: - 'Illegal entry point, is1ESPipeline is not defined. Repository yaml should not directly reference templates in core-templates folder.': error - ${{ if and(eq(parameters.runAsPublic, 'false'), ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest')) }}: - - checkout: self + - checkout: ${{ parameters.repositoryAlias }} fetchDepth: 3 clean: true @@ -117,7 +119,7 @@ jobs: azureSubscription: "Darc: Maestro Production" scriptType: ps scriptLocation: scriptPath - scriptPath: $(Build.SourcesDirectory)/eng/common/sdk-task.ps1 + scriptPath: $(System.DefaultWorkingDirectory)/eng/common/sdk-task.ps1 arguments: -task PublishBuildAssets -restore -msbuildEngine dotnet /p:ManifestsPath='$(Build.StagingDirectory)/AssetManifests' /p:IsAssetlessBuild=${{ parameters.isAssetlessBuild }} @@ -137,7 +139,7 @@ jobs: Add-Content -Path $filePath -Value "$(DefaultChannels)" Add-Content -Path $filePath -Value $(IsStableBuild) - $symbolExclusionfile = "$(Build.SourcesDirectory)/eng/SymbolPublishingExclusionsFile.txt" + $symbolExclusionfile = "$(System.DefaultWorkingDirectory)/eng/SymbolPublishingExclusionsFile.txt" if (Test-Path -Path $symbolExclusionfile) { Write-Host "SymbolExclusionFile exists" @@ -177,7 +179,7 @@ jobs: azureSubscription: "Darc: Maestro Production" scriptType: ps scriptLocation: scriptPath - scriptPath: $(Build.SourcesDirectory)/eng/common/post-build/publish-using-darc.ps1 + scriptPath: $(System.DefaultWorkingDirectory)/eng/common/post-build/publish-using-darc.ps1 arguments: > -BuildId $(BARBuildId) -PublishingInfraVersion 3 diff --git a/eng/common/core-templates/jobs/codeql-build.yml b/eng/common/core-templates/jobs/codeql-build.yml index 693b00b370..dbc14ac580 100644 --- a/eng/common/core-templates/jobs/codeql-build.yml +++ b/eng/common/core-templates/jobs/codeql-build.yml @@ -24,7 +24,7 @@ jobs: - name: DefaultGuardianVersion value: 0.109.0 - name: GuardianPackagesConfigFile - value: $(Build.SourcesDirectory)\eng\common\sdl\packages.config + value: $(System.DefaultWorkingDirectory)\eng\common\sdl\packages.config - name: GuardianVersion value: ${{ coalesce(parameters.overrideGuardianVersion, '$(DefaultGuardianVersion)') }} diff --git a/eng/common/core-templates/jobs/jobs.yml b/eng/common/core-templates/jobs/jobs.yml index 2f992b2c6e..b637cb6e94 100644 --- a/eng/common/core-templates/jobs/jobs.yml +++ b/eng/common/core-templates/jobs/jobs.yml @@ -43,6 +43,7 @@ parameters: artifacts: {} is1ESPipeline: '' + repositoryAlias: self # Internal resources (telemetry, microbuild) can only be accessed from non-public projects, # and some (Microbuild) should only be applied to non-PR cases for internal builds. @@ -114,3 +115,4 @@ jobs: enablePublishBuildArtifacts: ${{ parameters.enablePublishBuildArtifacts }} artifactsPublishingAdditionalParameters: ${{ parameters.artifactsPublishingAdditionalParameters }} signingValidationAdditionalParameters: ${{ parameters.signingValidationAdditionalParameters }} + repositoryAlias: ${{ parameters.repositoryAlias }} diff --git a/eng/common/core-templates/post-build/post-build.yml b/eng/common/core-templates/post-build/post-build.yml index a151fd811e..f6f87fe5c6 100644 --- a/eng/common/core-templates/post-build/post-build.yml +++ b/eng/common/core-templates/post-build/post-build.yml @@ -154,7 +154,7 @@ stages: - task: PowerShell@2 displayName: Validate inputs: - filePath: $(Build.SourcesDirectory)/eng/common/post-build/nuget-validation.ps1 + filePath: $(System.DefaultWorkingDirectory)/eng/common/post-build/nuget-validation.ps1 arguments: -PackagesPath $(Build.ArtifactStagingDirectory)/PackageArtifacts/ - job: @@ -208,7 +208,7 @@ stages: filePath: eng\common\sdk-task.ps1 arguments: -task SigningValidation -restore -msbuildEngine vs /p:PackageBasePath='$(Build.ArtifactStagingDirectory)/PackageArtifacts' - /p:SignCheckExclusionsFile='$(Build.SourcesDirectory)/eng/SignCheckExclusionsFile.txt' + /p:SignCheckExclusionsFile='$(System.DefaultWorkingDirectory)/eng/SignCheckExclusionsFile.txt' ${{ parameters.signingValidationAdditionalParameters }} - template: /eng/common/core-templates/steps/publish-logs.yml @@ -258,7 +258,7 @@ stages: - task: PowerShell@2 displayName: Validate inputs: - filePath: $(Build.SourcesDirectory)/eng/common/post-build/sourcelink-validation.ps1 + filePath: $(System.DefaultWorkingDirectory)/eng/common/post-build/sourcelink-validation.ps1 arguments: -InputPath $(Build.ArtifactStagingDirectory)/BlobArtifacts/ -ExtractPath $(Agent.BuildDirectory)/Extract/ -GHRepoName $(Build.Repository.Name) @@ -313,7 +313,7 @@ stages: azureSubscription: "Darc: Maestro Production" scriptType: ps scriptLocation: scriptPath - scriptPath: $(Build.SourcesDirectory)/eng/common/post-build/publish-using-darc.ps1 + scriptPath: $(System.DefaultWorkingDirectory)/eng/common/post-build/publish-using-darc.ps1 arguments: > -BuildId $(BARBuildId) -PublishingInfraVersion ${{ parameters.publishingInfraVersion }} diff --git a/eng/common/core-templates/post-build/setup-maestro-vars.yml b/eng/common/core-templates/post-build/setup-maestro-vars.yml index f7602980db..a7abd58c4b 100644 --- a/eng/common/core-templates/post-build/setup-maestro-vars.yml +++ b/eng/common/core-templates/post-build/setup-maestro-vars.yml @@ -36,7 +36,7 @@ steps: $AzureDevOpsBuildId = $Env:Build_BuildId } else { - . $(Build.SourcesDirectory)\eng\common\tools.ps1 + . $(System.DefaultWorkingDirectory)\eng\common\tools.ps1 $darc = Get-Darc $buildInfo = & $darc get-build ` --id ${{ parameters.BARBuildId }} ` diff --git a/eng/common/core-templates/steps/enable-internal-sources.yml b/eng/common/core-templates/steps/enable-internal-sources.yml index 64f881bffc..4085512b69 100644 --- a/eng/common/core-templates/steps/enable-internal-sources.yml +++ b/eng/common/core-templates/steps/enable-internal-sources.yml @@ -17,8 +17,8 @@ steps: - task: PowerShell@2 displayName: Setup Internal Feeds inputs: - filePath: $(Build.SourcesDirectory)/eng/common/SetupNugetSources.ps1 - arguments: -ConfigFile $(Build.SourcesDirectory)/NuGet.config -Password $Env:Token + filePath: $(System.DefaultWorkingDirectory)/eng/common/SetupNugetSources.ps1 + arguments: -ConfigFile $(System.DefaultWorkingDirectory)/NuGet.config -Password $Env:Token env: Token: ${{ parameters.legacyCredential }} # If running on dnceng (internal project), just use the default behavior for NuGetAuthenticate. @@ -29,8 +29,8 @@ steps: - task: PowerShell@2 displayName: Setup Internal Feeds inputs: - filePath: $(Build.SourcesDirectory)/eng/common/SetupNugetSources.ps1 - arguments: -ConfigFile $(Build.SourcesDirectory)/NuGet.config + filePath: $(System.DefaultWorkingDirectory)/eng/common/SetupNugetSources.ps1 + arguments: -ConfigFile $(System.DefaultWorkingDirectory)/NuGet.config - ${{ else }}: - template: /eng/common/templates/steps/get-federated-access-token.yml parameters: @@ -39,8 +39,8 @@ steps: - task: PowerShell@2 displayName: Setup Internal Feeds inputs: - filePath: $(Build.SourcesDirectory)/eng/common/SetupNugetSources.ps1 - arguments: -ConfigFile $(Build.SourcesDirectory)/NuGet.config -Password $(dnceng-artifacts-feeds-read-access-token) + filePath: $(System.DefaultWorkingDirectory)/eng/common/SetupNugetSources.ps1 + arguments: -ConfigFile $(System.DefaultWorkingDirectory)/NuGet.config -Password $(dnceng-artifacts-feeds-read-access-token) # This is required in certain scenarios to install the ADO credential provider. # It installed by default in some msbuild invocations (e.g. VS msbuild), but needs to be installed for others # (e.g. dotnet msbuild). diff --git a/eng/common/core-templates/steps/generate-sbom.yml b/eng/common/core-templates/steps/generate-sbom.yml index 44a9636cdf..c05f650279 100644 --- a/eng/common/core-templates/steps/generate-sbom.yml +++ b/eng/common/core-templates/steps/generate-sbom.yml @@ -6,7 +6,7 @@ parameters: PackageVersion: 10.0.0 - BuildDropPath: '$(Build.SourcesDirectory)/artifacts' + BuildDropPath: '$(System.DefaultWorkingDirectory)/artifacts' PackageName: '.NET' ManifestDirPath: $(Build.ArtifactStagingDirectory)/sbom IgnoreDirectories: '' diff --git a/eng/common/core-templates/steps/install-microbuild.yml b/eng/common/core-templates/steps/install-microbuild.yml index f614d1440e..d6b9878f54 100644 --- a/eng/common/core-templates/steps/install-microbuild.yml +++ b/eng/common/core-templates/steps/install-microbuild.yml @@ -12,6 +12,7 @@ parameters: # variable is not available in template expression. _SignType has a very large proliferation across .NET, so replacing it is tough. microbuildUseESRP: true # Location of the MicroBuild output folder + # NOTE: There's something that relies on this being in the "default" source directory for tasks such as Signing to work properly. microBuildOutputFolder: '$(Build.SourcesDirectory)' continueOnError: false @@ -46,8 +47,12 @@ steps: displayName: 'Validate ESRP usage (Non-Windows)' condition: and(succeeded(), ne(variables['Agent.Os'], 'Windows_NT')) + # Two different MB install steps. This is due to not being able to use the agent OS during + # YAML expansion, and Windows vs. Linux/Mac uses different service connections. However, + # we can avoid including the MB install step if not enabled at all. This avoids a bunch of + # extra pipeline authorizations, since most pipelines do not sign on non-Windows. - task: MicroBuildSigningPlugin@4 - displayName: Install MicroBuild plugin + displayName: Install MicroBuild plugin (Windows) inputs: signType: $(_SignType) zipSources: false @@ -63,16 +68,24 @@ steps: MicroBuildOutputFolderOverride: ${{ parameters.microBuildOutputFolder }} SYSTEM_ACCESSTOKEN: $(System.AccessToken) continueOnError: ${{ parameters.continueOnError }} - condition: and( - succeeded(), - or( - and( - eq(variables['Agent.Os'], 'Windows_NT'), - in(variables['_SignType'], 'real', 'test') - ), - and( - ${{ eq(parameters.enableMicrobuildForMacAndLinux, true) }}, - ne(variables['Agent.Os'], 'Windows_NT'), - eq(variables['_SignType'], 'real') - ) - )) + condition: and(succeeded(), eq(variables['Agent.Os'], 'Windows_NT'), in(variables['_SignType'], 'real', 'test')) + + - ${{ if eq(parameters.enableMicrobuildForMacAndLinux, true) }}: + - task: MicroBuildSigningPlugin@4 + displayName: Install MicroBuild plugin (non-Windows) + inputs: + signType: $(_SignType) + zipSources: false + feedSource: https://dnceng.pkgs.visualstudio.com/_packaging/MicroBuildToolset/nuget/v3/index.json + ${{ if eq(parameters.microbuildUseESRP, true) }}: + ConnectedServiceName: 'MicroBuild Signing Task (DevDiv)' + ${{ if eq(variables['System.TeamProject'], 'DevDiv') }}: + ConnectedPMEServiceName: beb8cb23-b303-4c95-ab26-9e44bc958d39 + ${{ else }}: + ConnectedPMEServiceName: c24de2a5-cc7a-493d-95e4-8e5ff5cad2bc + env: + TeamName: $(_TeamName) + MicroBuildOutputFolderOverride: ${{ parameters.microBuildOutputFolder }} + SYSTEM_ACCESSTOKEN: $(System.AccessToken) + continueOnError: ${{ parameters.continueOnError }} + condition: and(succeeded(), ne(variables['Agent.Os'], 'Windows_NT'), eq(variables['_SignType'], 'real')) diff --git a/eng/common/core-templates/steps/publish-logs.yml b/eng/common/core-templates/steps/publish-logs.yml index de24d0087c..10f825e270 100644 --- a/eng/common/core-templates/steps/publish-logs.yml +++ b/eng/common/core-templates/steps/publish-logs.yml @@ -12,22 +12,22 @@ steps: inputs: targetType: inline script: | - New-Item -ItemType Directory $(Build.SourcesDirectory)/PostBuildLogs/${{parameters.StageLabel}}/${{parameters.JobLabel}}/ - Move-Item -Path $(Build.SourcesDirectory)/artifacts/log/Debug/* $(Build.SourcesDirectory)/PostBuildLogs/${{parameters.StageLabel}}/${{parameters.JobLabel}}/ + New-Item -ItemType Directory $(System.DefaultWorkingDirectory)/PostBuildLogs/${{parameters.StageLabel}}/${{parameters.JobLabel}}/ + Move-Item -Path $(System.DefaultWorkingDirectory)/artifacts/log/Debug/* $(System.DefaultWorkingDirectory)/PostBuildLogs/${{parameters.StageLabel}}/${{parameters.JobLabel}}/ continueOnError: true condition: always() - task: PowerShell@2 displayName: Redact Logs inputs: - filePath: $(Build.SourcesDirectory)/eng/common/post-build/redact-logs.ps1 + filePath: $(System.DefaultWorkingDirectory)/eng/common/post-build/redact-logs.ps1 # For now this needs to have explicit list of all sensitive data. Taken from eng/publishing/v3/publish.yml - # Sensitive data can as well be added to $(Build.SourcesDirectory)/eng/BinlogSecretsRedactionFile.txt' + # Sensitive data can as well be added to $(System.DefaultWorkingDirectory)/eng/BinlogSecretsRedactionFile.txt' # If the file exists - sensitive data for redaction will be sourced from it # (single entry per line, lines starting with '# ' are considered comments and skipped) - arguments: -InputPath '$(Build.SourcesDirectory)/PostBuildLogs' + arguments: -InputPath '$(System.DefaultWorkingDirectory)/PostBuildLogs' -BinlogToolVersion ${{parameters.BinlogToolVersion}} - -TokensFilePath '$(Build.SourcesDirectory)/eng/BinlogSecretsRedactionFile.txt' + -TokensFilePath '$(System.DefaultWorkingDirectory)/eng/BinlogSecretsRedactionFile.txt' '$(publishing-dnceng-devdiv-code-r-build-re)' '$(MaestroAccessToken)' '$(dn-bot-all-orgs-artifact-feeds-rw)' @@ -44,7 +44,7 @@ steps: - task: CopyFiles@2 displayName: Gather post build logs inputs: - SourceFolder: '$(Build.SourcesDirectory)/PostBuildLogs' + SourceFolder: '$(System.DefaultWorkingDirectory)/PostBuildLogs' Contents: '**' TargetFolder: '$(Build.ArtifactStagingDirectory)/PostBuildLogs' condition: always() diff --git a/eng/common/core-templates/steps/source-index-stage1-publish.yml b/eng/common/core-templates/steps/source-index-stage1-publish.yml index c2917c1efc..75600735f1 100644 --- a/eng/common/core-templates/steps/source-index-stage1-publish.yml +++ b/eng/common/core-templates/steps/source-index-stage1-publish.yml @@ -20,7 +20,7 @@ steps: # Set working directory to temp directory so 'dotnet' doesn't try to use global.json and use the repo's sdk. workingDirectory: $(Agent.TempDirectory) -- script: $(Agent.TempDirectory)/.source-index/tools/BinLogToSln -i ${{parameters.BinlogPath}} -r $(Build.SourcesDirectory) -n $(Build.Repository.Name) -o .source-index/stage1output +- script: $(Agent.TempDirectory)/.source-index/tools/BinLogToSln -i ${{parameters.BinlogPath}} -r $(System.DefaultWorkingDirectory) -n $(Build.Repository.Name) -o .source-index/stage1output displayName: "Source Index: Process Binlog into indexable sln" - ${{ if and(ne(parameters.runAsPublic, 'true'), ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest')) }}: diff --git a/eng/common/template-guidance.md b/eng/common/template-guidance.md index 98bbc1ded0..4bf4cf41bd 100644 --- a/eng/common/template-guidance.md +++ b/eng/common/template-guidance.md @@ -50,7 +50,7 @@ extends: - task: CopyFiles@2 displayName: Gather build output inputs: - SourceFolder: '$(Build.SourcesDirectory)/artifacts/marvel' + SourceFolder: '$(System.DefaultWorkingDirectory)/artifacts/marvel' Contents: '**' TargetFolder: '$(Build.ArtifactStagingDirectory)/artifacts/marvel' ``` diff --git a/eng/common/templates-official/job/job.yml b/eng/common/templates-official/job/job.yml index a8a9432874..92a0664f56 100644 --- a/eng/common/templates-official/job/job.yml +++ b/eng/common/templates-official/job/job.yml @@ -3,7 +3,7 @@ parameters: enableSbom: true runAsPublic: false PackageVersion: 9.0.0 - BuildDropPath: '$(Build.SourcesDirectory)/artifacts' + BuildDropPath: '$(System.DefaultWorkingDirectory)/artifacts' jobs: - template: /eng/common/core-templates/job/job.yml diff --git a/eng/common/templates-official/variables/sdl-variables.yml b/eng/common/templates-official/variables/sdl-variables.yml index dbdd66d4a4..f1311bbb1b 100644 --- a/eng/common/templates-official/variables/sdl-variables.yml +++ b/eng/common/templates-official/variables/sdl-variables.yml @@ -4,4 +4,4 @@ variables: - name: DefaultGuardianVersion value: 0.109.0 - name: GuardianPackagesConfigFile - value: $(Build.SourcesDirectory)\eng\common\sdl\packages.config \ No newline at end of file + value: $(System.DefaultWorkingDirectory)\eng\common\sdl\packages.config \ No newline at end of file diff --git a/eng/common/templates/job/job.yml b/eng/common/templates/job/job.yml index 7cbf668c22..238fa0818f 100644 --- a/eng/common/templates/job/job.yml +++ b/eng/common/templates/job/job.yml @@ -6,7 +6,7 @@ parameters: enableSbom: true runAsPublic: false PackageVersion: 9.0.0 - BuildDropPath: '$(Build.SourcesDirectory)/artifacts' + BuildDropPath: '$(System.DefaultWorkingDirectory)/artifacts' jobs: - template: /eng/common/core-templates/job/job.yml @@ -77,7 +77,7 @@ jobs: parameters: is1ESPipeline: false args: - targetPath: '$(Build.SourcesDirectory)\eng\common\BuildConfiguration' + targetPath: '$(System.DefaultWorkingDirectory)\eng\common\BuildConfiguration' artifactName: 'BuildConfiguration' displayName: 'Publish build retry configuration' continueOnError: true diff --git a/global.json b/global.json index ff9e479dc4..2da7b9e028 100644 --- a/global.json +++ b/global.json @@ -33,7 +33,7 @@ "rollForward": "latestFeature" }, "msbuild-sdks": { - "Microsoft.DotNet.Arcade.Sdk": "10.0.0-beta.25414.2", + "Microsoft.DotNet.Arcade.Sdk": "10.0.0-beta.25415.5", "MSBuild.Sdk.Extras": "3.0.44" } } From 3ba3ee490c7aa0e7887df3e2603a78050738c110 Mon Sep 17 00:00:00 2001 From: Copilot <198982749+Copilot@users.noreply.github.com> Date: Mon, 18 Aug 2025 12:55:33 +0200 Subject: [PATCH 413/541] Fix escape character handling in test display names (#6174) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: Evangelink <11340282+Evangelink@users.noreply.github.com> Co-authored-by: Amaury Levé --- .../Terminal/TerminalTestReporter.cs | 109 +++++++++++- .../Terminal/TerminalTestReporterTests.cs | 159 ++++++++++++++++++ 2 files changed, 259 insertions(+), 9 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporter.cs b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporter.cs index 960e47d3ca..db8c1a05f7 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporter.cs +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporter.cs @@ -426,7 +426,7 @@ private void RenderTestCompleted( terminal.Append(outcomeText); terminal.ResetColor(); terminal.Append(' '); - terminal.Append(displayName); + terminal.Append(MakeControlCharactersVisible(displayName, true)); terminal.SetColor(TerminalColor.DarkGray); terminal.Append(' '); AppendLongDuration(terminal, duration); @@ -536,11 +536,11 @@ private static void FormatStandardAndErrorOutput(ITerminal terminal, string? sta terminal.SetColor(TerminalColor.DarkGray); terminal.Append(SingleIndentation); terminal.AppendLine(PlatformResources.StandardOutput); - string? standardOutputWithoutSpecialChars = NormalizeSpecialCharacters(standardOutput); + string? standardOutputWithoutSpecialChars = MakeControlCharactersVisible(standardOutput, normalizeWhitespaceCharacters: false); AppendIndentedLine(terminal, standardOutputWithoutSpecialChars, DoubleIndentation); terminal.Append(SingleIndentation); terminal.AppendLine(PlatformResources.StandardError); - string? standardErrorWithoutSpecialChars = NormalizeSpecialCharacters(standardError); + string? standardErrorWithoutSpecialChars = MakeControlCharactersVisible(standardError, normalizeWhitespaceCharacters: false); AppendIndentedLine(terminal, standardErrorWithoutSpecialChars, DoubleIndentation); terminal.ResetColor(); } @@ -651,10 +651,101 @@ internal void AssemblyRunCompleted() _terminalWithProgress.RemoveWorker(assemblyRun.SlotIndex); } - private static string? NormalizeSpecialCharacters(string? text) - => text?.Replace('\0', '\x2400') - // escape char - .Replace('\x001b', '\x241b'); + // SearchValues for efficient detection of control characters +#if NET8_0_OR_GREATER + private static readonly System.Buffers.SearchValues AllControlChars = CreateControlCharSearchValues(includeWhitespace: true); + private static readonly System.Buffers.SearchValues NonWhitespaceControlChars = CreateControlCharSearchValues(includeWhitespace: false); + + private static System.Buffers.SearchValues CreateControlCharSearchValues(bool includeWhitespace) + { + var controlChars = new List(); + for (char c = '\0'; c <= '\u00FF'; c++) // Check first 256 characters for performance + { + if (char.IsControl(c)) + { + if (includeWhitespace || (c != '\t' && c != '\n' && c != '\r')) + { + controlChars.Add(c); + } + } + } + + return System.Buffers.SearchValues.Create(controlChars.ToArray()); + } +#else + private static readonly char[] AllControlChars = CreateControlCharArray(includeWhitespace: true); + private static readonly char[] NonWhitespaceControlChars = CreateControlCharArray(includeWhitespace: false); + + private static char[] CreateControlCharArray(bool includeWhitespace) + { + var controlChars = new List(); + for (char c = '\0'; c <= '\u00FF'; c++) // Check first 256 characters for performance + { + if (char.IsControl(c)) + { + if (includeWhitespace || (c != '\t' && c != '\n' && c != '\r')) + { + controlChars.Add(c); + } + } + } + + return [.. controlChars]; + } +#endif + + [return: NotNullIfNotNull(nameof(text))] + private static string? MakeControlCharactersVisible(string? text, bool normalizeWhitespaceCharacters) + { + if (text is null) + { + return null; + } + +#if NET8_0_OR_GREATER + // Use SearchValues to efficiently check if we need to do any work + System.Buffers.SearchValues searchValues = normalizeWhitespaceCharacters ? AllControlChars : NonWhitespaceControlChars; + if (text.AsSpan().IndexOfAny(searchValues) == -1) + { + return text; // No control characters found, return original string + } +#else + // Use IndexOfAny to check if we need to do any work + char[] searchChars = normalizeWhitespaceCharacters ? AllControlChars : NonWhitespaceControlChars; + if (text.IndexOfAny(searchChars) == -1) + { + return text; // No control characters found, return original string + } +#endif + + // Pre-allocate StringBuilder with known capacity + var sb = new StringBuilder(text.Length); + + foreach (char c in text) + { + if (char.IsControl(c)) + { + // Skip normalization for whitespace characters when not requested + if (!normalizeWhitespaceCharacters && (c == '\t' || c == '\n' || c == '\r')) + { + sb.Append(c); + } + else + { + // Convert to Unicode control picture using bit manipulation (0x2400 + char value) + // For C0 control characters (0x00-0x1F), this produces proper Unicode control pictures (U+2400-U+241F) + // For other control characters, this produces printable characters that won't break console formatting + sb.Append((char)(0x2400 + c)); + } + } + else + { + sb.Append(c); + } + } + + return sb.ToString(); + } /// /// Appends a long duration in human readable format such as 1h 23m 500ms. @@ -752,7 +843,7 @@ internal void TestDiscovered(string displayName) asm.TotalTests++; } - asm.DiscoveredTestDisplayNames.Add(displayName); + asm.DiscoveredTestDisplayNames.Add(MakeControlCharactersVisible(displayName, true)); _terminalWithProgress.UpdateWorker(asm.SlotIndex); } @@ -836,7 +927,7 @@ public void TestInProgress( { asm.TestNodeResultsState ??= new(Interlocked.Increment(ref _counter)); asm.TestNodeResultsState.AddRunningTestNode( - Interlocked.Increment(ref _counter), testNodeUid, displayName, CreateStopwatch()); + Interlocked.Increment(ref _counter), testNodeUid, MakeControlCharactersVisible(displayName, true), CreateStopwatch()); } _terminalWithProgress.UpdateWorker(asm.SlotIndex); diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/OutputDevice/Terminal/TerminalTestReporterTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/OutputDevice/Terminal/TerminalTestReporterTests.cs index cfba5bf030..05299af231 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/OutputDevice/Terminal/TerminalTestReporterTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/OutputDevice/Terminal/TerminalTestReporterTests.cs @@ -596,4 +596,163 @@ private class StackTraceException : Exception public override string? StackTrace { get; } } + + // Test data for all C0 control characters (U+0000-U+001F) that are normalized + [DataRow('\x0000', '\x2400', "NULL")] + [DataRow('\x0001', '\x2401', "START OF HEADING")] + [DataRow('\x0002', '\x2402', "START OF TEXT")] + [DataRow('\x0003', '\x2403', "END OF TEXT")] + [DataRow('\x0004', '\x2404', "END OF TRANSMISSION")] + [DataRow('\x0005', '\x2405', "ENQUIRY")] + [DataRow('\x0006', '\x2406', "ACKNOWLEDGE")] + [DataRow('\x0007', '\x2407', "BELL")] + [DataRow('\x0008', '\x2408', "BACKSPACE")] + [DataRow('\t', '\x2409', "TAB")] + [DataRow('\n', '\x240A', "LINE FEED")] + [DataRow('\x000B', '\x240B', "VERTICAL TAB")] + [DataRow('\x000C', '\x240C', "FORM FEED")] + [DataRow('\r', '\x240D', "CARRIAGE RETURN")] + [DataRow('\x000E', '\x240E', "SHIFT OUT")] + [DataRow('\x000F', '\x240F', "SHIFT IN")] + [DataRow('\x0010', '\x2410', "DATA LINK ESCAPE")] + [DataRow('\x0011', '\x2411', "DEVICE CONTROL ONE")] + [DataRow('\x0012', '\x2412', "DEVICE CONTROL TWO")] + [DataRow('\x0013', '\x2413', "DEVICE CONTROL THREE")] + [DataRow('\x0014', '\x2414', "DEVICE CONTROL FOUR")] + [DataRow('\x0015', '\x2415', "NEGATIVE ACKNOWLEDGE")] + [DataRow('\x0016', '\x2416', "SYNCHRONOUS IDLE")] + [DataRow('\x0017', '\x2417', "END OF TRANSMISSION BLOCK")] + [DataRow('\x0018', '\x2418', "CANCEL")] + [DataRow('\x0019', '\x2419', "END OF MEDIUM")] + [DataRow('\x001A', '\x241A', "SUBSTITUTE")] + [DataRow('\x001B', '\x241B', "ESCAPE")] + [DataRow('\x001C', '\x241C', "FILE SEPARATOR")] + [DataRow('\x001D', '\x241D', "GROUP SEPARATOR")] + [DataRow('\x001E', '\x241E', "RECORD SEPARATOR")] + [DataRow('\x001F', '\x241F', "UNIT SEPARATOR")] + [TestMethod] + public void TestDisplayNames_WithControlCharacters_AreNormalized(char controlChar, char expectedChar, string charName) + { + string targetFramework = "net8.0"; + string architecture = "x64"; + string assembly = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? @"C:\work\assembly.dll" : "/mnt/work/assembly.dll"; + + var stringBuilderConsole = new StringBuilderConsole(); + var terminalReporter = new TerminalTestReporter(assembly, targetFramework, architecture, stringBuilderConsole, new CTRLPlusCCancellationTokenSource(), new TerminalTestReporterOptions + { + ShowPassedTests = () => true, + UseAnsi = false, + ShowProgress = () => false, + }); + + DateTimeOffset startTime = DateTimeOffset.MinValue; + DateTimeOffset endTime = DateTimeOffset.MaxValue; + terminalReporter.TestExecutionStarted(startTime, 1, isDiscovery: false); + + terminalReporter.AssemblyRunStarted(); + + // Test display name with the specific control character + string testDisplayName = $"Test{controlChar}Name"; + terminalReporter.TestCompleted(testNodeUid: "Test1", testDisplayName, TestOutcome.Passed, TimeSpan.FromSeconds(1), + informativeMessage: null, errorMessage: null, exception: null, expected: null, actual: null, standardOutput: null, errorOutput: null); + + terminalReporter.AssemblyRunCompleted(); + terminalReporter.TestExecutionCompleted(endTime); + + string output = stringBuilderConsole.Output; + + // Verify that the control character is replaced with its Unicode control picture + string normalizedDisplayName = $"Test{expectedChar}Name"; + Assert.Contains(normalizedDisplayName, output, $"{charName} should be replaced with {expectedChar}"); + + // Verify that the literal control character is not present in the test display name + // Note: We skip this assertion for whitespace characters (\t, \n, \r) because these + // characters naturally appear in console output formatting (e.g., line breaks between tests) + // and asserting their complete absence would cause false positives + string literalDisplayName = $"Test{controlChar}Name"; + bool isWhitespaceChar = controlChar is '\t' or '\n' or '\r'; + if (!isWhitespaceChar) + { + Assert.DoesNotContain(literalDisplayName, output, $"Literal {charName} should not be present in test display name"); + } + } + + // Test data for all C0 control characters (U+0000-U+001F) that are normalized + [DataRow('\x0000', '\x2400', "NULL")] + [DataRow('\x0001', '\x2401', "START OF HEADING")] + [DataRow('\x0002', '\x2402', "START OF TEXT")] + [DataRow('\x0003', '\x2403', "END OF TEXT")] + [DataRow('\x0004', '\x2404', "END OF TRANSMISSION")] + [DataRow('\x0005', '\x2405', "ENQUIRY")] + [DataRow('\x0006', '\x2406', "ACKNOWLEDGE")] + [DataRow('\x0007', '\x2407', "BELL")] + [DataRow('\x0008', '\x2408', "BACKSPACE")] + [DataRow('\t', '\x2409', "TAB")] + [DataRow('\n', '\x240A', "LINE FEED")] + [DataRow('\x000B', '\x240B', "VERTICAL TAB")] + [DataRow('\x000C', '\x240C', "FORM FEED")] + [DataRow('\r', '\x240D', "CARRIAGE RETURN")] + [DataRow('\x000E', '\x240E', "SHIFT OUT")] + [DataRow('\x000F', '\x240F', "SHIFT IN")] + [DataRow('\x0010', '\x2410', "DATA LINK ESCAPE")] + [DataRow('\x0011', '\x2411', "DEVICE CONTROL ONE")] + [DataRow('\x0012', '\x2412', "DEVICE CONTROL TWO")] + [DataRow('\x0013', '\x2413', "DEVICE CONTROL THREE")] + [DataRow('\x0014', '\x2414', "DEVICE CONTROL FOUR")] + [DataRow('\x0015', '\x2415', "NEGATIVE ACKNOWLEDGE")] + [DataRow('\x0016', '\x2416', "SYNCHRONOUS IDLE")] + [DataRow('\x0017', '\x2417', "END OF TRANSMISSION BLOCK")] + [DataRow('\x0018', '\x2418', "CANCEL")] + [DataRow('\x0019', '\x2419', "END OF MEDIUM")] + [DataRow('\x001A', '\x241A', "SUBSTITUTE")] + [DataRow('\x001B', '\x241B', "ESCAPE")] + [DataRow('\x001C', '\x241C', "FILE SEPARATOR")] + [DataRow('\x001D', '\x241D', "GROUP SEPARATOR")] + [DataRow('\x001E', '\x241E', "RECORD SEPARATOR")] + [DataRow('\x001F', '\x241F', "UNIT SEPARATOR")] + [TestMethod] + public void TestDiscovery_WithControlCharacters_AreNormalized(char controlChar, char expectedChar, string charName) + { + string targetFramework = "net8.0"; + string architecture = "x64"; + string assembly = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? @"C:\work\assembly.dll" : "/mnt/work/assembly.dll"; + + var stringBuilderConsole = new StringBuilderConsole(); + var terminalReporter = new TerminalTestReporter(assembly, targetFramework, architecture, stringBuilderConsole, new CTRLPlusCCancellationTokenSource(), new TerminalTestReporterOptions + { + ShowPassedTests = () => true, + UseAnsi = false, + ShowProgress = () => false, + }); + + DateTimeOffset startTime = DateTimeOffset.MinValue; + DateTimeOffset endTime = DateTimeOffset.MaxValue; + terminalReporter.TestExecutionStarted(startTime, 1, isDiscovery: true); + + terminalReporter.AssemblyRunStarted(); + + // Test discovery with the specific control character + string testDisplayName = $"Test{controlChar}Name"; + terminalReporter.TestDiscovered(testDisplayName); + + terminalReporter.AssemblyRunCompleted(); + terminalReporter.TestExecutionCompleted(endTime); + + string output = stringBuilderConsole.Output; + + // Verify that the control character is replaced with its Unicode control picture + string normalizedDisplayName = $"Test{expectedChar}Name"; + Assert.Contains(normalizedDisplayName, output, $"{charName} should be replaced with {expectedChar} in discovery"); + + // Verify that the literal control character is not present in the test display name + // Note: We skip this assertion for whitespace characters (\t, \n, \r) because these + // characters naturally appear in console output formatting (e.g., line breaks between tests) + // and asserting their complete absence would cause false positives + string literalDisplayName = $"Test{controlChar}Name"; + bool isWhitespaceChar = controlChar is '\t' or '\n' or '\r'; + if (!isWhitespaceChar) + { + Assert.DoesNotContain(literalDisplayName, output, $"Literal {charName} should not be present in test display name"); + } + } } From 6eb8c97f903f366a5e75e97d0131728a2fab08c8 Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Tue, 19 Aug 2025 08:25:08 +0200 Subject: [PATCH 414/541] [main] Update dependencies from dotnet/arcade (#6407) Co-authored-by: dotnet-maestro[bot] --- eng/Version.Details.xml | 12 ++++++------ eng/Versions.props | 2 +- eng/common/sdk-task.ps1 | 3 ++- eng/common/sdk-task.sh | 7 ++++++- global.json | 2 +- 5 files changed, 16 insertions(+), 10 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index 59d2376b14..4853c618d4 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -1,17 +1,17 @@ - + https://github.com/dotnet/arcade - e58b086a85a1df5762c8980308f7e4e330edd0aa + 5bb3e45c964be0076b22510ce60218284c7bba53 - + https://github.com/dotnet/arcade - e58b086a85a1df5762c8980308f7e4e330edd0aa + 5bb3e45c964be0076b22510ce60218284c7bba53 - + https://github.com/dotnet/arcade - e58b086a85a1df5762c8980308f7e4e330edd0aa + 5bb3e45c964be0076b22510ce60218284c7bba53 https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage diff --git a/eng/Versions.props b/eng/Versions.props index fa95b356e1..c32e4c7619 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -7,7 +7,7 @@ preview - 10.0.0-beta.25415.5 + 10.0.0-beta.25418.4 18.0.0-preview.25414.4 3.11.0-preview.25415.13 diff --git a/eng/common/sdk-task.ps1 b/eng/common/sdk-task.ps1 index a9d2a2d269..b62e132d32 100644 --- a/eng/common/sdk-task.ps1 +++ b/eng/common/sdk-task.ps1 @@ -7,13 +7,14 @@ Param( [switch] $restore, [switch] $prepareMachine, [switch][Alias('nobl')]$excludeCIBinaryLog, + [switch]$noWarnAsError, [switch] $help, [Parameter(ValueFromRemainingArguments=$true)][String[]]$properties ) $ci = $true $binaryLog = if ($excludeCIBinaryLog) { $false } else { $true } -$warnAsError = $true +$warnAsError = if ($noWarnAsError) { $false } else { $true } . $PSScriptRoot\tools.ps1 diff --git a/eng/common/sdk-task.sh b/eng/common/sdk-task.sh index 2f83adc026..0c92f81d74 100644 --- a/eng/common/sdk-task.sh +++ b/eng/common/sdk-task.sh @@ -10,6 +10,7 @@ show_usage() { echo "Advanced settings:" echo " --excludeCIBinarylog Don't output binary log (short: -nobl)" + echo " --noWarnAsError Do not warn as error echo "" echo "Command line arguments not listed above are passed thru to msbuild." } @@ -52,6 +53,7 @@ exclude_ci_binary_log=false restore=false help=false properties='' +warnAsError=true while (($# > 0)); do lowerI="$(echo $1 | tr "[:upper:]" "[:lower:]")" @@ -73,6 +75,10 @@ while (($# > 0)); do exclude_ci_binary_log=true shift 1 ;; + --noWarnAsError) + warnAsError=false + shift 1 + ;; --help) help=true shift 1 @@ -85,7 +91,6 @@ while (($# > 0)); do done ci=true -warnAsError=true if $help; then show_usage diff --git a/global.json b/global.json index 2da7b9e028..7ccd877cf6 100644 --- a/global.json +++ b/global.json @@ -33,7 +33,7 @@ "rollForward": "latestFeature" }, "msbuild-sdks": { - "Microsoft.DotNet.Arcade.Sdk": "10.0.0-beta.25415.5", + "Microsoft.DotNet.Arcade.Sdk": "10.0.0-beta.25418.4", "MSBuild.Sdk.Extras": "3.0.44" } } From 67537aedc25a657f70d9bb74cd2e39b258b0d4b8 Mon Sep 17 00:00:00 2001 From: Copilot <198982749+Copilot@users.noreply.github.com> Date: Tue, 19 Aug 2025 15:05:08 +0000 Subject: [PATCH 415/541] Fix MSTEST0046 code fix removing empty lines by preserving leading trivia (#6363) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: Evangelink <11340282+Evangelink@users.noreply.github.com> Co-authored-by: Amaury Levé --- .../StringAssertToAssertFixer.cs | 17 +++-- .../StringAssertToAssertAnalyzerTests.cs | 70 +++++++++++++++++++ 2 files changed, 80 insertions(+), 7 deletions(-) diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/StringAssertToAssertFixer.cs b/src/Analyzers/MSTest.Analyzers.CodeFixes/StringAssertToAssertFixer.cs index 735626a8d1..b933d3014d 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/StringAssertToAssertFixer.cs +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/StringAssertToAssertFixer.cs @@ -11,7 +11,6 @@ using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; -using Microsoft.CodeAnalysis.Editing; using MSTest.Analyzers.Helpers; @@ -78,13 +77,15 @@ private static async Task FixStringAssertAsync( return document; } - DocumentEditor editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false); + SyntaxNode root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); // Create new argument list with swapped first two arguments - ArgumentSyntax[] newArguments = [.. arguments]; - (newArguments[0], newArguments[1]) = (newArguments[1], newArguments[0]); + // We keep the existing separators in case there is trivia attached to them. + var newArguments = arguments.GetWithSeparators().ToList(); + // NOTE: Index 1 has the "separator" (comma) between the first and second arguments. + (newArguments[0], newArguments[2]) = (newArguments[2], newArguments[0]); - ArgumentListSyntax newArgumentList = SyntaxFactory.ArgumentList(SyntaxFactory.SeparatedList(newArguments)); + ArgumentListSyntax newArgumentList = invocationExpr.ArgumentList.WithArguments(SyntaxFactory.SeparatedList(newArguments)); InvocationExpressionSyntax newInvocationExpr = invocationExpr.WithArgumentList(newArgumentList); // Replace StringAssert with Assert in the member access expression @@ -93,7 +94,9 @@ private static async Task FixStringAssertAsync( .WithName(SyntaxFactory.IdentifierName(properAssertMethodName)); newInvocationExpr = newInvocationExpr.WithExpression(newMemberAccess); - editor.ReplaceNode(invocationExpr, newInvocationExpr); - return editor.GetChangedDocument(); + // Preserve leading trivia (including empty lines) from the original invocation + newInvocationExpr = newInvocationExpr.WithLeadingTrivia(invocationExpr.GetLeadingTrivia()); + + return document.WithSyntaxRoot(root.ReplaceNode(invocationExpr, newInvocationExpr)); } } diff --git a/test/UnitTests/MSTest.Analyzers.UnitTests/StringAssertToAssertAnalyzerTests.cs b/test/UnitTests/MSTest.Analyzers.UnitTests/StringAssertToAssertAnalyzerTests.cs index 7f41a59d10..bc4bb02ca8 100644 --- a/test/UnitTests/MSTest.Analyzers.UnitTests/StringAssertToAssertAnalyzerTests.cs +++ b/test/UnitTests/MSTest.Analyzers.UnitTests/StringAssertToAssertAnalyzerTests.cs @@ -308,4 +308,74 @@ public void MyTestMethod() await VerifyCS.VerifyAnalyzerAsync(code); } + + [TestMethod] + public async Task WhenStringAssertContains_ShouldPreserveEmptyLines() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void ShouldNotRemoveEmptyLine() + { + WrappedMethodCall( + 1, + 2, + 3); + + {|#0:StringAssert.Contains("value", "v")|}; + + {|#1:StringAssert.Contains("value", "v")|}; + + {|#2:StringAssert.Contains( + "value", + "v")|}; + } + + private void WrappedMethodCall(int a, int b, int c) { } + } + """; + + string fixedCode = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void ShouldNotRemoveEmptyLine() + { + WrappedMethodCall( + 1, + 2, + 3); + + Assert.Contains("v", "value"); + + Assert.Contains("v", "value"); + + Assert.Contains( + "v", + "value"); + } + + private void WrappedMethodCall(int a, int b, int c) { } + } + """; + + await VerifyCS.VerifyCodeFixAsync( + code, + [ + // /0/Test0.cs(12,9): info MSTEST0046: Use 'Assert.Contains' instead of 'StringAssert.Contains' + VerifyCS.Diagnostic().WithLocation(0).WithArguments("Contains", "Contains"), + // /0/Test0.cs(14,9): info MSTEST0046: Use 'Assert.Contains' instead of 'StringAssert.Contains' + VerifyCS.Diagnostic().WithLocation(1).WithArguments("Contains", "Contains"), + // /0/Test0.cs(16,9): info MSTEST0046: Use 'Assert.Contains' instead of 'StringAssert.Contains' + VerifyCS.Diagnostic().WithLocation(2).WithArguments("Contains", "Contains"), + ], + fixedCode); + } } From 2bdc0477e8501b8a431af5918dbdbef5347a9c86 Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Wed, 20 Aug 2025 07:19:45 +0200 Subject: [PATCH 416/541] [main] Update dependencies from dotnet/arcade (#6411) Co-authored-by: dotnet-maestro[bot] --- eng/Version.Details.xml | 12 ++++++------ eng/Versions.props | 2 +- .../steps/source-index-stage1-publish.yml | 4 ++-- eng/common/tools.ps1 | 2 +- global.json | 2 +- 5 files changed, 11 insertions(+), 11 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index 4853c618d4..c9c1bc779e 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -1,17 +1,17 @@ - + https://github.com/dotnet/arcade - 5bb3e45c964be0076b22510ce60218284c7bba53 + bc34438ebc563e85fa31f010c3c376eaaf67b91c - + https://github.com/dotnet/arcade - 5bb3e45c964be0076b22510ce60218284c7bba53 + bc34438ebc563e85fa31f010c3c376eaaf67b91c - + https://github.com/dotnet/arcade - 5bb3e45c964be0076b22510ce60218284c7bba53 + bc34438ebc563e85fa31f010c3c376eaaf67b91c https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage diff --git a/eng/Versions.props b/eng/Versions.props index c32e4c7619..a2a41d6f79 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -7,7 +7,7 @@ preview - 10.0.0-beta.25418.4 + 10.0.0-beta.25419.1 18.0.0-preview.25414.4 3.11.0-preview.25415.13 diff --git a/eng/common/core-templates/steps/source-index-stage1-publish.yml b/eng/common/core-templates/steps/source-index-stage1-publish.yml index 75600735f1..e9a694afa5 100644 --- a/eng/common/core-templates/steps/source-index-stage1-publish.yml +++ b/eng/common/core-templates/steps/source-index-stage1-publish.yml @@ -1,6 +1,6 @@ parameters: - sourceIndexUploadPackageVersion: 2.0.0-20250425.2 - sourceIndexProcessBinlogPackageVersion: 1.0.1-20250515.1 + sourceIndexUploadPackageVersion: 2.0.0-20250818.1 + sourceIndexProcessBinlogPackageVersion: 1.0.1-20250818.1 sourceIndexPackageSource: https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-tools/nuget/v3/index.json binlogPath: artifacts/log/Debug/Build.binlog diff --git a/eng/common/tools.ps1 b/eng/common/tools.ps1 index 4920464cc4..06b44de787 100644 --- a/eng/common/tools.ps1 +++ b/eng/common/tools.ps1 @@ -553,7 +553,7 @@ function LocateVisualStudio([object]$vsRequirements = $null){ if (!(Test-Path $vsWhereExe)) { Create-Directory $vsWhereDir - Write-Host 'Downloading vswhere $vswhereVersion' + Write-Host "Downloading vswhere $vswhereVersion" $ProgressPreference = 'SilentlyContinue' # Don't display the console progress UI - it's a huge perf hit Retry({ Invoke-WebRequest "https://netcorenativeassets.blob.core.windows.net/resource-packages/external/windows/vswhere/$vswhereVersion/vswhere.exe" -OutFile $vswhereExe diff --git a/global.json b/global.json index 7ccd877cf6..64bbacb10e 100644 --- a/global.json +++ b/global.json @@ -33,7 +33,7 @@ "rollForward": "latestFeature" }, "msbuild-sdks": { - "Microsoft.DotNet.Arcade.Sdk": "10.0.0-beta.25418.4", + "Microsoft.DotNet.Arcade.Sdk": "10.0.0-beta.25419.1", "MSBuild.Sdk.Extras": "3.0.44" } } From 3a619fc42234ccc8e566f349dfe9c08ecbc70c50 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Wed, 20 Aug 2025 09:20:21 +0200 Subject: [PATCH 417/541] Fix link in AnalyzerReleases.Shipped.txt (#6412) --- src/Analyzers/MSTest.Analyzers/AnalyzerReleases.Shipped.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Analyzers/MSTest.Analyzers/AnalyzerReleases.Shipped.md b/src/Analyzers/MSTest.Analyzers/AnalyzerReleases.Shipped.md index 343cb53a91..2aa27e3422 100644 --- a/src/Analyzers/MSTest.Analyzers/AnalyzerReleases.Shipped.md +++ b/src/Analyzers/MSTest.Analyzers/AnalyzerReleases.Shipped.md @@ -7,7 +7,7 @@ Rule ID | Category | Severity | Notes MSTEST0044 | Design | Warning | PreferTestMethodOverDataTestMethodAnalyzer, [Documentation](https://learn.microsoft.com/dotnet/core/testing/mstest-analyzers/mstest0044) MSTEST0045 | Usage | Info | UseCooperativeCancellationForTimeoutAnalyzer, [Documentation](https://learn.microsoft.com/dotnet/core/testing/mstest-analyzers/mstest0045) MSTEST0046 | Usage | Info | StringAssertToAssertAnalyzer, [Documentation](https://learn.microsoft.com/dotnet/core/testing/mstest-analyzers/mstest0046) -MSTEST0048 | Usage | Warning | TestContextPropertyUsageAnalyzer, [Documentation](https://learn.microsoft.com/dotnet/core/testing/mstest-analyzers/mstest0047) +MSTEST0048 | Usage | Warning | TestContextPropertyUsageAnalyzer, [Documentation](https://learn.microsoft.com/dotnet/core/testing/mstest-analyzers/mstest0048) MSTEST0049 | Usage | Info | FlowTestContextCancellationTokenAnalyzer, [Documentation](https://learn.microsoft.com/dotnet/core/testing/mstest-analyzers/mstest0049) MSTEST0050 | Usage | Error | GlobalTestFixtureShouldBeValidAnalyzer, [Documentation](https://learn.microsoft.com/dotnet/core/testing/mstest-analyzers/mstest0050) From 77eefdaf65f34df55f2e399e6642052d9634fa08 Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Thu, 21 Aug 2025 08:39:16 +0200 Subject: [PATCH 418/541] [main] Update dependencies from devdiv/DevDiv/vs-code-coverage, dotnet/arcade (#6418) Co-authored-by: dotnet-maestro[bot] --- eng/Version.Details.xml | 16 ++++++++-------- eng/Versions.props | 4 ++-- global.json | 2 +- 3 files changed, 11 insertions(+), 11 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index c9c1bc779e..0fece2ed8d 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -1,21 +1,21 @@ - + https://github.com/dotnet/arcade - bc34438ebc563e85fa31f010c3c376eaaf67b91c + 86b53945e6b6b239d68fa465e62fcf4323ff3b7b - + https://github.com/dotnet/arcade - bc34438ebc563e85fa31f010c3c376eaaf67b91c + 86b53945e6b6b239d68fa465e62fcf4323ff3b7b - + https://github.com/dotnet/arcade - bc34438ebc563e85fa31f010c3c376eaaf67b91c + 86b53945e6b6b239d68fa465e62fcf4323ff3b7b - + https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage - dd3e010148361acad26e2ed22061ab61b1c9c976 + c2d3c3f2103d9116f778f6d2ad6ec0f0f5b5b586 https://github.com/microsoft/testfx diff --git a/eng/Versions.props b/eng/Versions.props index a2a41d6f79..5e99cc5807 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -7,8 +7,8 @@ preview - 10.0.0-beta.25419.1 - 18.0.0-preview.25414.4 + 10.0.0-beta.25419.2 + 18.0.0-preview.25420.1 3.11.0-preview.25415.13 1.9.0-preview.25415.13 diff --git a/global.json b/global.json index 64bbacb10e..58372260be 100644 --- a/global.json +++ b/global.json @@ -33,7 +33,7 @@ "rollForward": "latestFeature" }, "msbuild-sdks": { - "Microsoft.DotNet.Arcade.Sdk": "10.0.0-beta.25419.1", + "Microsoft.DotNet.Arcade.Sdk": "10.0.0-beta.25419.2", "MSBuild.Sdk.Extras": "3.0.44" } } From 56a664458ea6e2f871fd2aab605a29bb473a6183 Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Thu, 21 Aug 2025 06:59:29 +0000 Subject: [PATCH 419/541] [main] Update dependencies from microsoft/testfx (#6419) Co-authored-by: dotnet-maestro[bot] --- eng/Version.Details.xml | 8 ++++---- eng/Versions.props | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index 0fece2ed8d..33e0d736c6 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -17,13 +17,13 @@ https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage c2d3c3f2103d9116f778f6d2ad6ec0f0f5b5b586 - + https://github.com/microsoft/testfx - 5182881d93b55c942460dc43ebbcfa87a2fb84bd + 4fff5964ffc55cda6384546c29a1c44fb0b37a8a - + https://github.com/microsoft/testfx - 5182881d93b55c942460dc43ebbcfa87a2fb84bd + 4fff5964ffc55cda6384546c29a1c44fb0b37a8a diff --git a/eng/Versions.props b/eng/Versions.props index 5e99cc5807..9f0985909a 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -10,7 +10,7 @@ 10.0.0-beta.25419.2 18.0.0-preview.25420.1 - 3.11.0-preview.25415.13 - 1.9.0-preview.25415.13 + 3.11.0-preview.25415.14 + 1.9.0-preview.25415.14 From 15ce9a04d44c531c73beef565dace114526d5fbc Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Thu, 21 Aug 2025 17:43:08 +0200 Subject: [PATCH 420/541] MSTEST0037: Recognize IsTrue(collection.[Count|Length] [==|>|!=] 0) patterns and cleanup (#6416) --- .../UseProperAssertMethodsAnalyzer.cs | 191 +++--- .../UseProperAssertMethodsAnalyzerTests.cs | 600 ++++++++++++++++++ 2 files changed, 718 insertions(+), 73 deletions(-) diff --git a/src/Analyzers/MSTest.Analyzers/UseProperAssertMethodsAnalyzer.cs b/src/Analyzers/MSTest.Analyzers/UseProperAssertMethodsAnalyzer.cs index 2d51ae27da..4d62220efa 100644 --- a/src/Analyzers/MSTest.Analyzers/UseProperAssertMethodsAnalyzer.cs +++ b/src/Analyzers/MSTest.Analyzers/UseProperAssertMethodsAnalyzer.cs @@ -71,6 +71,11 @@ namespace MSTest.Analyzers; /// Assert.AreEqual([0|X], myCollection.[Count|Length]) /// /// +/// +/// +/// Assert.IsTrue(myCollection.[Count|Length] [>|!=|==] 0) +/// +/// /// /// [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] @@ -532,89 +537,68 @@ private static void AnalyzeIsTrueOrIsFalseInvocation(OperationAnalysisContext co if (stringMethodStatus != StringMethodCheckStatus.Unknown) { // Handle both IsTrue and IsFalse cases with string methods - if (isTrueInvocation) + string properAssertMethod = stringMethodStatus switch { - string properAssertMethod = stringMethodStatus switch - { - StringMethodCheckStatus.StartsWith => "StartsWith", - StringMethodCheckStatus.EndsWith => "EndsWith", - StringMethodCheckStatus.Contains => "Contains", - _ => throw new InvalidOperationException("Unexpected StringMethodCheckStatus value."), - }; + StringMethodCheckStatus.StartsWith => isTrueInvocation ? "StartsWith" : "DoesNotStartWith", + StringMethodCheckStatus.EndsWith => isTrueInvocation ? "EndsWith" : "DoesNotEndWith", + StringMethodCheckStatus.Contains => isTrueInvocation ? "Contains" : "DoesNotContain", + _ => throw new InvalidOperationException("Unexpected StringMethodCheckStatus value."), + }; - ImmutableDictionary.Builder properties = ImmutableDictionary.CreateBuilder(); - properties.Add(ProperAssertMethodNameKey, properAssertMethod); - properties.Add(CodeFixModeKey, CodeFixModeAddArgument); - context.ReportDiagnostic(context.Operation.CreateDiagnostic( - Rule, - additionalLocations: ImmutableArray.Create(conditionArgument.Syntax.GetLocation(), substringExpr!.GetLocation(), stringExpr!.GetLocation()), - properties: properties.ToImmutable(), - properAssertMethod, - "IsTrue")); - return; - } - else + ImmutableDictionary.Builder properties = ImmutableDictionary.CreateBuilder(); + properties.Add(ProperAssertMethodNameKey, properAssertMethod); + properties.Add(CodeFixModeKey, CodeFixModeAddArgument); + context.ReportDiagnostic(context.Operation.CreateDiagnostic( + Rule, + additionalLocations: ImmutableArray.Create(conditionArgument.Syntax.GetLocation(), substringExpr!.GetLocation(), stringExpr!.GetLocation()), + properties: properties.ToImmutable(), + properAssertMethod, + isTrueInvocation ? "IsTrue" : "IsFalse")); + return; + } + + // Check for collection method patterns: myCollection.Contains(...) + CollectionCheckStatus collectionMethodStatus = RecognizeCollectionMethodCheck(conditionArgument, objectTypeSymbol, out SyntaxNode? collectionExpr, out SyntaxNode? itemExpr); + if (collectionMethodStatus != CollectionCheckStatus.Unknown) + { + if (collectionMethodStatus == CollectionCheckStatus.Contains) { - // For IsFalse with string methods, suggest the negative assertions - string properAssertMethod = stringMethodStatus switch - { - StringMethodCheckStatus.StartsWith => "DoesNotStartWith", - StringMethodCheckStatus.EndsWith => "DoesNotEndWith", - StringMethodCheckStatus.Contains => "DoesNotContain", - _ => throw new InvalidOperationException("Unexpected StringMethodCheckStatus value."), - }; + string properAssertMethod = isTrueInvocation ? "Contains" : "DoesNotContain"; ImmutableDictionary.Builder properties = ImmutableDictionary.CreateBuilder(); properties.Add(ProperAssertMethodNameKey, properAssertMethod); properties.Add(CodeFixModeKey, CodeFixModeAddArgument); context.ReportDiagnostic(context.Operation.CreateDiagnostic( Rule, - additionalLocations: ImmutableArray.Create(conditionArgument.Syntax.GetLocation(), substringExpr!.GetLocation(), stringExpr!.GetLocation()), + additionalLocations: ImmutableArray.Create(conditionArgument.Syntax.GetLocation(), itemExpr!.GetLocation(), collectionExpr!.GetLocation()), properties: properties.ToImmutable(), properAssertMethod, - "IsFalse")); + isTrueInvocation ? "IsTrue" : "IsFalse")); return; } } - // Check for collection method patterns: myCollection.Contains(...) - CollectionCheckStatus collectionMethodStatus = RecognizeCollectionMethodCheck(conditionArgument, objectTypeSymbol, out SyntaxNode? collectionExpr, out SyntaxNode? itemExpr); - if (collectionMethodStatus != CollectionCheckStatus.Unknown) + // Check for collection emptiness patterns: myCollection.Count > 0, myCollection.Count != 0, or myCollection.Count == 0 + CountCheckStatus countStatus = RecognizeCountCheck(conditionArgument, objectTypeSymbol, out SyntaxNode? collectionEmptinessExpr); + if (countStatus != CountCheckStatus.Unknown) { - if (collectionMethodStatus == CollectionCheckStatus.Contains) + string properAssertMethod = countStatus switch { - if (isTrueInvocation) - { - string properAssertMethod = "Contains"; - - ImmutableDictionary.Builder properties = ImmutableDictionary.CreateBuilder(); - properties.Add(ProperAssertMethodNameKey, properAssertMethod); - properties.Add(CodeFixModeKey, CodeFixModeAddArgument); - context.ReportDiagnostic(context.Operation.CreateDiagnostic( - Rule, - additionalLocations: ImmutableArray.Create(conditionArgument.Syntax.GetLocation(), itemExpr!.GetLocation(), collectionExpr!.GetLocation()), - properties: properties.ToImmutable(), - properAssertMethod, - "IsTrue")); - return; - } - else - { - // For IsFalse with collection Contains, suggest DoesNotContain - string properAssertMethod = "DoesNotContain"; + CountCheckStatus.IsEmpty => isTrueInvocation ? "IsEmpty" : "IsNotEmpty", + CountCheckStatus.HasCount => isTrueInvocation ? "IsNotEmpty" : "IsEmpty", + _ => throw ApplicationStateGuard.Unreachable(), + }; - ImmutableDictionary.Builder properties = ImmutableDictionary.CreateBuilder(); - properties.Add(ProperAssertMethodNameKey, properAssertMethod); - properties.Add(CodeFixModeKey, CodeFixModeAddArgument); - context.ReportDiagnostic(context.Operation.CreateDiagnostic( - Rule, - additionalLocations: ImmutableArray.Create(conditionArgument.Syntax.GetLocation(), itemExpr!.GetLocation(), collectionExpr!.GetLocation()), - properties: properties.ToImmutable(), - properAssertMethod, - "IsFalse")); - return; - } - } + ImmutableDictionary.Builder properties = ImmutableDictionary.CreateBuilder(); + properties.Add(ProperAssertMethodNameKey, properAssertMethod); + properties.Add(CodeFixModeKey, CodeFixModeSimple); + context.ReportDiagnostic(context.Operation.CreateDiagnostic( + Rule, + additionalLocations: ImmutableArray.Create(conditionArgument.Syntax.GetLocation(), collectionEmptinessExpr!.GetLocation()), + properties: properties.ToImmutable(), + properAssertMethod, + isTrueInvocation ? "IsTrue" : "IsFalse")); + return; } // Check for comparison patterns: a > b, a >= b, a < b, a <= b @@ -823,6 +807,64 @@ actualArgumentValue.Type is { } actualType && } } + private static CountCheckStatus RecognizeCountCheck( + IOperation operation, + INamedTypeSymbol objectTypeSymbol, + out SyntaxNode? collectionExpression) + { + collectionExpression = null; + + // Check for collection.Count > 0 or collection.Length > 0 + if (operation is IBinaryOperation { OperatorKind: BinaryOperatorKind.GreaterThan, LeftOperand: IPropertyReferenceOperation propertyRef, RightOperand: ILiteralOperation { ConstantValue: { HasValue: true, Value: 0 } } } && + TryGetCollectionExpressionIfBCLCollectionLengthOrCount(propertyRef, objectTypeSymbol) is { } expression) + { + collectionExpression = expression; + return CountCheckStatus.HasCount; + } + + // Check for 0 < collection.Count or 0 < collection.Length + if (operation is IBinaryOperation { OperatorKind: BinaryOperatorKind.LessThan, LeftOperand: ILiteralOperation { ConstantValue: { HasValue: true, Value: 0 } }, RightOperand: IPropertyReferenceOperation propertyRef2 } && + TryGetCollectionExpressionIfBCLCollectionLengthOrCount(propertyRef2, objectTypeSymbol) is { } expression2) + { + collectionExpression = expression2; + return CountCheckStatus.HasCount; + } + + // Check for collection.Count != 0 or collection.Length != 0 + if (operation is IBinaryOperation { OperatorKind: BinaryOperatorKind.NotEquals, LeftOperand: IPropertyReferenceOperation propertyRef3, RightOperand: ILiteralOperation { ConstantValue: { HasValue: true, Value: 0 } } } && + TryGetCollectionExpressionIfBCLCollectionLengthOrCount(propertyRef3, objectTypeSymbol) is { } expression3) + { + collectionExpression = expression3; + return CountCheckStatus.HasCount; + } + + // Check for 0 != collection.Count or 0 != collection.Length (reverse order) + if (operation is IBinaryOperation { OperatorKind: BinaryOperatorKind.NotEquals, LeftOperand: ILiteralOperation { ConstantValue: { HasValue: true, Value: 0 } }, RightOperand: IPropertyReferenceOperation propertyRef4 } && + TryGetCollectionExpressionIfBCLCollectionLengthOrCount(propertyRef4, objectTypeSymbol) is { } expression4) + { + collectionExpression = expression4; + return CountCheckStatus.HasCount; + } + + // Check for collection.Count == 0 or collection.Length == 0 + if (operation is IBinaryOperation { OperatorKind: BinaryOperatorKind.Equals, LeftOperand: IPropertyReferenceOperation propertyRef5, RightOperand: ILiteralOperation { ConstantValue: { HasValue: true, Value: 0 } } } && + TryGetCollectionExpressionIfBCLCollectionLengthOrCount(propertyRef5, objectTypeSymbol) is { } expression5) + { + collectionExpression = expression5; + return CountCheckStatus.IsEmpty; + } + + // Check for 0 == collection.Count or 0 == collection.Length (reverse order) + if (operation is IBinaryOperation { OperatorKind: BinaryOperatorKind.Equals, LeftOperand: ILiteralOperation { ConstantValue: { HasValue: true, Value: 0 } }, RightOperand: IPropertyReferenceOperation propertyRef6 } && + TryGetCollectionExpressionIfBCLCollectionLengthOrCount(propertyRef6, objectTypeSymbol) is { } expression6) + { + collectionExpression = expression6; + return CountCheckStatus.IsEmpty; + } + + return CountCheckStatus.Unknown; + } + private static CountCheckStatus RecognizeCountCheck( IOperation expectedArgument, IOperation actualArgument, @@ -836,11 +878,9 @@ private static CountCheckStatus RecognizeCountCheck( expectedArgument.ConstantValue.Value is int expectedValue && expectedValue >= 0 && actualArgument is IPropertyReferenceOperation propertyRef && - propertyRef.Property.Name is "Count" or "Length" && - propertyRef.Instance?.Type is not null && - IsBCLCollectionType(propertyRef.Property.ContainingType, objectTypeSymbol)) + TryGetCollectionExpressionIfBCLCollectionLengthOrCount(propertyRef, objectTypeSymbol) is { } expression) { - collectionExpression = propertyRef.Instance.Syntax; + collectionExpression = expression; countExpression = propertyRef.Syntax; countValue = expectedValue; return expectedValue == 0 ? CountCheckStatus.IsEmpty : CountCheckStatus.HasCount; @@ -851,11 +891,9 @@ propertyRef.Property.Name is "Count" or "Length" && actualArgument.ConstantValue.Value is int actualValue && actualValue >= 0 && expectedArgument is IPropertyReferenceOperation propertyRef2 && - propertyRef2.Property.Name is "Count" or "Length" && - propertyRef2.Instance?.Type is not null && - IsBCLCollectionType(propertyRef2.Property.ContainingType, objectTypeSymbol)) + TryGetCollectionExpressionIfBCLCollectionLengthOrCount(propertyRef2, objectTypeSymbol) is { } expression2) { - collectionExpression = propertyRef2.Instance.Syntax; + collectionExpression = expression2; countExpression = propertyRef2.Syntax; countValue = actualValue; return actualValue == 0 ? CountCheckStatus.IsEmpty : CountCheckStatus.HasCount; @@ -867,6 +905,13 @@ propertyRef2.Property.Name is "Count" or "Length" && return CountCheckStatus.Unknown; } + private static SyntaxNode? TryGetCollectionExpressionIfBCLCollectionLengthOrCount(IPropertyReferenceOperation propertyReference, INamedTypeSymbol objectTypeSymbol) + => propertyReference.Property.Name is "Count" or "Length" && + propertyReference.Instance?.Type is not null && + (propertyReference.Instance.Type.TypeKind == TypeKind.Array || IsBCLCollectionType(propertyReference.Property.ContainingType, objectTypeSymbol)) + ? propertyReference.Instance.Syntax + : null; + private static bool TryGetFirstArgumentValue(IInvocationOperation operation, [NotNullWhen(true)] out IOperation? argumentValue) => TryGetArgumentValueForParameterOrdinal(operation, 0, out argumentValue); diff --git a/test/UnitTests/MSTest.Analyzers.UnitTests/UseProperAssertMethodsAnalyzerTests.cs b/test/UnitTests/MSTest.Analyzers.UnitTests/UseProperAssertMethodsAnalyzerTests.cs index e2809bc1a9..9af795ab9f 100644 --- a/test/UnitTests/MSTest.Analyzers.UnitTests/UseProperAssertMethodsAnalyzerTests.cs +++ b/test/UnitTests/MSTest.Analyzers.UnitTests/UseProperAssertMethodsAnalyzerTests.cs @@ -2160,4 +2160,604 @@ public void MyTestMethod() await VerifyCS.VerifyCodeFixAsync(code, code); } #endregion + + #region New test cases for collection emptiness checks + + [TestMethod] + public async Task WhenAssertIsTrueWithCollectionCountGreaterThanZero() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + using System.Collections.Generic; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + var list = new List { 1, 2, 3 }; + {|#0:Assert.IsTrue(list.Count > 0)|}; + } + } + """; + + string fixedCode = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + using System.Collections.Generic; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + var list = new List { 1, 2, 3 }; + Assert.IsNotEmpty(list); + } + } + """; + + await VerifyCS.VerifyCodeFixAsync( + code, + // /0/Test0.cs(11,9): info MSTEST0037: Use 'Assert.IsNotEmpty' instead of 'Assert.IsTrue' + VerifyCS.DiagnosticIgnoringAdditionalLocations().WithLocation(0).WithArguments("IsNotEmpty", "IsTrue"), + fixedCode); + } + + [TestMethod] + public async Task WhenAssertIsTrueWithCollectionCountNotEqualToZero() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + using System.Collections.Generic; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + var list = new List { 1, 2, 3 }; + {|#0:Assert.IsTrue(list.Count != 0)|}; + } + } + """; + + string fixedCode = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + using System.Collections.Generic; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + var list = new List { 1, 2, 3 }; + Assert.IsNotEmpty(list); + } + } + """; + + await VerifyCS.VerifyCodeFixAsync( + code, + // /0/Test0.cs(11,9): info MSTEST0037: Use 'Assert.IsNotEmpty' instead of 'Assert.IsTrue' + VerifyCS.DiagnosticIgnoringAdditionalLocations().WithLocation(0).WithArguments("IsNotEmpty", "IsTrue"), + fixedCode); + } + + [TestMethod] + public async Task WhenAssertIsTrueWithCollectionCountEqualsZero() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + using System.Collections.Generic; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + var list = new List { 1, 2, 3 }; + {|#0:Assert.IsTrue(list.Count == 0)|}; + {|#1:Assert.IsTrue(0 == list.Count)|}; + } + } + """; + + string fixedCode = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + using System.Collections.Generic; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + var list = new List { 1, 2, 3 }; + Assert.IsEmpty(list); + Assert.IsEmpty(list); + } + } + """; + + await VerifyCS.VerifyCodeFixAsync( + code, + [ + // /0/Test0.cs(11,9): info MSTEST0037: Use 'Assert.IsEmpty' instead of 'Assert.IsTrue' + VerifyCS.DiagnosticIgnoringAdditionalLocations().WithLocation(0).WithArguments("IsEmpty", "IsTrue"), + // /0/Test0.cs(12,9): info MSTEST0037: Use 'Assert.IsEmpty' instead of 'Assert.IsTrue' + VerifyCS.DiagnosticIgnoringAdditionalLocations().WithLocation(1).WithArguments("IsEmpty", "IsTrue"), + ], + fixedCode); + } + + [TestMethod] + public async Task WhenAssertIsTrueWithArrayLengthGreaterThanZero() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + var array = new int[] { 1, 2, 3 }; + {|#0:Assert.IsTrue(array.Length > 0)|}; + } + } + """; + + string fixedCode = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + var array = new int[] { 1, 2, 3 }; + Assert.IsNotEmpty(array); + } + } + """; + + await VerifyCS.VerifyCodeFixAsync( + code, + // /0/Test0.cs(10,9): info MSTEST0037: Use 'Assert.IsNotEmpty' instead of 'Assert.IsTrue' + VerifyCS.DiagnosticIgnoringAdditionalLocations().WithLocation(0).WithArguments("IsNotEmpty", "IsTrue"), + fixedCode); + } + + [TestMethod] + public async Task WhenAssertIsTrueWithArrayLengthNotEqualToZero() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + var array = new int[] { 1, 2, 3 }; + {|#0:Assert.IsTrue(array.Length != 0)|}; + } + } + """; + + string fixedCode = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + var array = new int[] { 1, 2, 3 }; + Assert.IsNotEmpty(array); + } + } + """; + + await VerifyCS.VerifyCodeFixAsync( + code, + // /0/Test0.cs(10,9): info MSTEST0037: Use 'Assert.IsNotEmpty' instead of 'Assert.IsTrue' + VerifyCS.DiagnosticIgnoringAdditionalLocations().WithLocation(0).WithArguments("IsNotEmpty", "IsTrue"), + fixedCode); + } + + [TestMethod] + public async Task WhenAssertIsTrueWithArrayLengthEqualToZero() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + var array = new int[] { 1, 2, 3 }; + {|#0:Assert.IsTrue(array.Length == 0)|}; + {|#1:Assert.IsTrue(0 == array.Length)|}; + } + } + """; + + string fixedCode = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + var array = new int[] { 1, 2, 3 }; + Assert.IsEmpty(array); + Assert.IsEmpty(array); + } + } + """; + + await VerifyCS.VerifyCodeFixAsync( + code, + [ + // /0/Test0.cs(10,9): info MSTEST0037: Use 'Assert.IsEmpty' instead of 'Assert.IsTrue' + VerifyCS.DiagnosticIgnoringAdditionalLocations().WithLocation(0).WithArguments("IsEmpty", "IsTrue"), + // /0/Test0.cs(11,9): info MSTEST0037: Use 'Assert.IsEmpty' instead of 'Assert.IsTrue' + VerifyCS.DiagnosticIgnoringAdditionalLocations().WithLocation(1).WithArguments("IsEmpty", "IsTrue"), + ], + fixedCode); + } + + [TestMethod] + public async Task WhenAssertIsTrueWithZeroNotEqualToCollectionCount() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + using System.Collections.Generic; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + var list = new List { 1, 2, 3 }; + {|#0:Assert.IsTrue(0 != list.Count)|}; + } + } + """; + + string fixedCode = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + using System.Collections.Generic; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + var list = new List { 1, 2, 3 }; + Assert.IsNotEmpty(list); + } + } + """; + + await VerifyCS.VerifyCodeFixAsync( + code, + // /0/Test0.cs(11,9): info MSTEST0037: Use 'Assert.IsNotEmpty' instead of 'Assert.IsTrue' + VerifyCS.DiagnosticIgnoringAdditionalLocations().WithLocation(0).WithArguments("IsNotEmpty", "IsTrue"), + fixedCode); + } + + [TestMethod] + public async Task WhenAssertIsFalseWithCollectionCountGreaterThanZero() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + using System.Collections.Generic; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + var list = new List { 1, 2, 3 }; + {|#0:Assert.IsFalse(list.Count > 0)|}; + } + } + """; + + string fixedCode = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + using System.Collections.Generic; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + var list = new List { 1, 2, 3 }; + Assert.IsEmpty(list); + } + } + """; + + await VerifyCS.VerifyCodeFixAsync( + code, + // /0/Test0.cs(11,9): info MSTEST0037: Use 'Assert.IsEmpty' instead of 'Assert.IsFalse' + VerifyCS.DiagnosticIgnoringAdditionalLocations().WithLocation(0).WithArguments("IsEmpty", "IsFalse"), + fixedCode); + } + + [TestMethod] + public async Task WhenAssertIsFalseWithCollectionCountEqualZero() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + using System.Collections.Generic; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + var list = new List { 1, 2, 3 }; + {|#0:Assert.IsFalse(list.Count == 0)|}; + {|#1:Assert.IsFalse(0 == list.Count)|}; + } + } + """; + + string fixedCode = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + using System.Collections.Generic; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + var list = new List { 1, 2, 3 }; + Assert.IsNotEmpty(list); + Assert.IsNotEmpty(list); + } + } + """; + + await VerifyCS.VerifyCodeFixAsync( + code, + [ + // /0/Test0.cs(11,9): info MSTEST0037: Use 'Assert.IsNotEmpty' instead of 'Assert.IsFalse' + VerifyCS.DiagnosticIgnoringAdditionalLocations().WithLocation(0).WithArguments("IsNotEmpty", "IsFalse"), + // /0/Test0.cs(12,9): info MSTEST0037: Use 'Assert.IsNotEmpty' instead of 'Assert.IsFalse' + VerifyCS.DiagnosticIgnoringAdditionalLocations().WithLocation(1).WithArguments("IsNotEmpty", "IsFalse"), + ], + fixedCode); + } + + [TestMethod] + public async Task WhenAssertIsFalseWithCollectionCountNotEqualToZero() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + using System.Collections.Generic; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + var list = new List { 1, 2, 3 }; + {|#0:Assert.IsFalse(list.Count != 0)|}; + } + } + """; + + string fixedCode = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + using System.Collections.Generic; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + var list = new List { 1, 2, 3 }; + Assert.IsEmpty(list); + } + } + """; + + await VerifyCS.VerifyCodeFixAsync( + code, + // /0/Test0.cs(11,9): info MSTEST0037: Use 'Assert.IsEmpty' instead of 'Assert.IsFalse' + VerifyCS.DiagnosticIgnoringAdditionalLocations().WithLocation(0).WithArguments("IsEmpty", "IsFalse"), + fixedCode); + } + + [TestMethod] + public async Task WhenAssertIsTrueWithCollectionCountGreaterThanNonZero_ShouldUseIsGreaterThan() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + using System.Collections.Generic; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + var list = new List { 1, 2, 3 }; + // This should use the generic comparison logic, not IsNotEmpty + {|#0:Assert.IsTrue(list.Count > 2)|}; + } + } + """; + + string fixedCode = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + using System.Collections.Generic; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + var list = new List { 1, 2, 3 }; + // This should use the generic comparison logic, not IsNotEmpty + Assert.IsGreaterThan(2, list.Count); + } + } + """; + + await VerifyCS.VerifyCodeFixAsync( + code, + // /0/Test0.cs(11,9): info MSTEST0037: Use 'Assert.IsGreaterThan' instead of 'Assert.IsTrue' + VerifyCS.DiagnosticIgnoringAdditionalLocations().WithLocation(0).WithArguments("IsGreaterThan", "IsTrue"), + fixedCode); + } + + [TestMethod] + public async Task WhenAssertIsTrueWithCollectionCountNotEqualToNonZero_ShouldUseAreNotEqual() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + using System.Collections.Generic; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + var list = new List { 1, 2, 3 }; + {|#0:Assert.IsTrue(list.Count != 5)|}; + } + } + """; + + string fixedCode = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + using System.Collections.Generic; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + var list = new List { 1, 2, 3 }; + Assert.AreNotEqual(5, list.Count); + } + } + """; + + await VerifyCS.VerifyCodeFixAsync( + code, + // /0/Test0.cs(11,9): info MSTEST0037: Use 'Assert.AreNotEqual' instead of 'Assert.IsTrue' + VerifyCS.DiagnosticIgnoringAdditionalLocations().WithLocation(0).WithArguments("AreNotEqual", "IsTrue"), + fixedCode); + } + + [TestMethod] + public async Task WhenAssertIsTrueWithNonBCLCollectionCount_ShouldUseGenericComparison() + { + string code = """ + using System; + using System.Collections; + using System.Collections.Generic; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + internal sealed class MyCustomCollection : IEnumerable + { + public IEnumerator GetEnumerator() + { + throw new NotImplementedException(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + throw new NotImplementedException(); + } + + public int Count => 5; + } + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + var customCollection = new MyCustomCollection(); + // This should use the generic comparison logic since it's not a BCL collection + {|#0:Assert.IsTrue(customCollection.Count > 0)|}; + } + } + """; + + string fixedCode = """ + using System; + using System.Collections; + using System.Collections.Generic; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + internal sealed class MyCustomCollection : IEnumerable + { + public IEnumerator GetEnumerator() + { + throw new NotImplementedException(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + throw new NotImplementedException(); + } + + public int Count => 5; + } + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + var customCollection = new MyCustomCollection(); + // This should use the generic comparison logic since it's not a BCL collection + Assert.IsGreaterThan(0, customCollection.Count); + } + } + """; + + await VerifyCS.VerifyCodeFixAsync( + code, + // /0/Test0.cs(25,9): info MSTEST0037: Use 'Assert.IsGreaterThan' instead of 'Assert.IsTrue' + VerifyCS.DiagnosticIgnoringAdditionalLocations().WithLocation(0).WithArguments("IsGreaterThan", "IsTrue"), + fixedCode); + } + + #endregion } From b6e4331e0c11a01178d4a832cb0eb6beeebe945a Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Thu, 21 Aug 2025 19:35:19 +0200 Subject: [PATCH 421/541] Unify reading runsettings (#6422) --- .../RunSettingsConfigurationProvider.cs | 18 ++---- .../Helpers/RunSettingsHelpers.cs | 55 +++++++++++++++++++ .../ObjectModel/RunSettingsAdapter.cs | 29 +--------- 3 files changed, 63 insertions(+), 39 deletions(-) create mode 100644 src/Platform/Microsoft.Testing.Extensions.VSTestBridge/Helpers/RunSettingsHelpers.cs diff --git a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/Configurations/RunSettingsConfigurationProvider.cs b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/Configurations/RunSettingsConfigurationProvider.cs index d61233e864..9651a8ce33 100644 --- a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/Configurations/RunSettingsConfigurationProvider.cs +++ b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/Configurations/RunSettingsConfigurationProvider.cs @@ -1,7 +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 Microsoft.Testing.Extensions.VSTestBridge.CommandLine; +using Microsoft.Testing.Extensions.VSTestBridge.Helpers; +using Microsoft.Testing.Platform; using Microsoft.Testing.Platform.CommandLine; using Microsoft.Testing.Platform.Configurations; using Microsoft.Testing.Platform.Helpers; @@ -37,7 +38,7 @@ internal sealed class RunSettingsConfigurationProvider(IFileSystem fileSystem) : /// public bool TryGet(string key, out string? value) { - if (_runSettingsFileContent is null) + if (RoslynString.IsNullOrEmpty(_runSettingsFileContent)) { value = null; return false; @@ -58,16 +59,9 @@ public bool TryGet(string key, out string? value) } /// - public async Task BuildAsync(CommandLineParseResult commandLineParseResult) + public Task BuildAsync(CommandLineParseResult commandLineParseResult) { - if (commandLineParseResult.TryGetOptionArgumentList(RunSettingsCommandLineOptionsProvider.RunSettingsOptionName, out string[]? runSettingsFilePath)) - { - if (_fileSystem.ExistFile(runSettingsFilePath[0])) - { - _runSettingsFileContent = await _fileSystem.ReadAllTextAsync(runSettingsFilePath[0]).ConfigureAwait(false); - } - } - - return this; + _runSettingsFileContent = RunSettingsHelpers.ReadRunSettings(commandLineParseResult, _fileSystem); + return Task.FromResult(this); } } diff --git a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/Helpers/RunSettingsHelpers.cs b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/Helpers/RunSettingsHelpers.cs new file mode 100644 index 0000000000..b46a062d81 --- /dev/null +++ b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/Helpers/RunSettingsHelpers.cs @@ -0,0 +1,55 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using Microsoft.Testing.Extensions.VSTestBridge.CommandLine; +using Microsoft.Testing.Platform; +using Microsoft.Testing.Platform.CommandLine; +using Microsoft.Testing.Platform.Helpers; + +namespace Microsoft.Testing.Extensions.VSTestBridge.Helpers; + +internal static class RunSettingsHelpers +{ + // TODO: There are two code paths that read runsettings. One is calling the ICommandLineOptions overload, other is calling the CommandLineParseResult overload. + // Figure out if they can/should be unified so that we do one I/O operation instead of two. + public static string ReadRunSettings(ICommandLineOptions commandLineOptions, IFileSystem fileSystem) + { + _ = commandLineOptions.TryGetOptionArgumentList(RunSettingsCommandLineOptionsProvider.RunSettingsOptionName, out string[]? fileNames); + return ReadRunSettings(fileNames, fileSystem); + } + + public static string ReadRunSettings(CommandLineParseResult commandLineParseResult, IFileSystem fileSystem) + { + _ = commandLineParseResult.TryGetOptionArgumentList(RunSettingsCommandLineOptionsProvider.RunSettingsOptionName, out string[]? fileNames); + return ReadRunSettings(fileNames, fileSystem); + } + + private static string ReadRunSettings(string[]? runsettingsFileFromCommandLine, IFileSystem fileSystem) + { + if (runsettingsFileFromCommandLine is not null && + runsettingsFileFromCommandLine.Length == 1 && + fileSystem.ExistFile(runsettingsFileFromCommandLine[0])) + { + return fileSystem.ReadAllText(runsettingsFileFromCommandLine[0]); + } + else + { + string? envVariableRunSettings = Environment.GetEnvironmentVariable("TESTINGPLATFORM_EXPERIMENTAL_VSTEST_RUNSETTINGS"); + if (!RoslynString.IsNullOrEmpty(envVariableRunSettings)) + { + return envVariableRunSettings; + } + else + { + string? runSettingsFilePath = Environment.GetEnvironmentVariable("TESTINGPLATFORM_VSTESTBRIDGE_RUNSETTINGS_FILE"); + + if (!RoslynString.IsNullOrEmpty(runSettingsFilePath) && File.Exists(runSettingsFilePath)) + { + return fileSystem.ReadAllText(runSettingsFilePath); + } + } + } + + return string.Empty; + } +} diff --git a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/RunSettingsAdapter.cs b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/RunSettingsAdapter.cs index 76dc6dc0ab..06cc0ce7a2 100644 --- a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/RunSettingsAdapter.cs +++ b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/RunSettingsAdapter.cs @@ -1,9 +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 Microsoft.Testing.Extensions.VSTestBridge.CommandLine; +using Microsoft.Testing.Extensions.VSTestBridge.Helpers; using Microsoft.Testing.Extensions.VSTestBridge.Resources; -using Microsoft.Testing.Platform; using Microsoft.Testing.Platform.CommandLine; using Microsoft.Testing.Platform.Configurations; using Microsoft.Testing.Platform.Helpers; @@ -38,31 +37,7 @@ public RunSettingsAdapter( ILoggerFactory loggerFactory, IMessageLogger messageLogger) { - string? runSettingsXml = string.Empty; - - if (commandLineOptions.TryGetOptionArgumentList(RunSettingsCommandLineOptionsProvider.RunSettingsOptionName, out string[]? fileNames) - && fileNames is not null - && fileNames.Length == 1 - && fileSystem.ExistFile(fileNames[0])) - { - runSettingsXml = fileSystem.ReadAllText(fileNames[0]); - } - else - { - if (!RoslynString.IsNullOrEmpty(Environment.GetEnvironmentVariable("TESTINGPLATFORM_EXPERIMENTAL_VSTEST_RUNSETTINGS"))) - { - runSettingsXml = Environment.GetEnvironmentVariable("TESTINGPLATFORM_EXPERIMENTAL_VSTEST_RUNSETTINGS"); - } - else - { - string? runSettingsFilePath = Environment.GetEnvironmentVariable("TESTINGPLATFORM_VSTESTBRIDGE_RUNSETTINGS_FILE"); - - if (!RoslynString.IsNullOrEmpty(runSettingsFilePath) && File.Exists(runSettingsFilePath)) - { - runSettingsXml = fileSystem.ReadAllText(runSettingsFilePath); - } - } - } + string runSettingsXml = RunSettingsHelpers.ReadRunSettings(commandLineOptions, fileSystem); XDocument runSettingsDocument = RunSettingsPatcher.Patch(runSettingsXml, configuration, client, commandLineOptions); WarnOnUnsupportedEntries(runSettingsDocument, messageLogger); From 6fa513db579ed232421896aaf03273a3c7147e47 Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Fri, 22 Aug 2025 12:51:39 +0200 Subject: [PATCH 422/541] [main] Update dependencies from microsoft/testfx (#6425) Co-authored-by: dotnet-maestro[bot] --- eng/Version.Details.xml | 8 ++++---- eng/Versions.props | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index 33e0d736c6..bbb739ca18 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -17,13 +17,13 @@ https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage c2d3c3f2103d9116f778f6d2ad6ec0f0f5b5b586 - + https://github.com/microsoft/testfx - 4fff5964ffc55cda6384546c29a1c44fb0b37a8a + b6e4331e0c11a01178d4a832cb0eb6beeebe945a - + https://github.com/microsoft/testfx - 4fff5964ffc55cda6384546c29a1c44fb0b37a8a + b6e4331e0c11a01178d4a832cb0eb6beeebe945a diff --git a/eng/Versions.props b/eng/Versions.props index 9f0985909a..0544f88f80 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -10,7 +10,7 @@ 10.0.0-beta.25419.2 18.0.0-preview.25420.1 - 3.11.0-preview.25415.14 - 1.9.0-preview.25415.14 + 3.11.0-preview.25421.4 + 1.9.0-preview.25421.4 From 8f99258760961972b88c1e60efc81d31d1464af6 Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Fri, 22 Aug 2025 12:53:04 +0200 Subject: [PATCH 423/541] [main] Update dependencies from devdiv/DevDiv/vs-code-coverage (#6424) Co-authored-by: dotnet-maestro[bot] --- eng/Version.Details.xml | 4 ++-- eng/Versions.props | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index bbb739ca18..43a4e0b7b9 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -13,9 +13,9 @@ https://github.com/dotnet/arcade 86b53945e6b6b239d68fa465e62fcf4323ff3b7b - + https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage - c2d3c3f2103d9116f778f6d2ad6ec0f0f5b5b586 + ad8260f1662c4c5e3099cb3ee5b96f38b01a6c6e https://github.com/microsoft/testfx diff --git a/eng/Versions.props b/eng/Versions.props index 0544f88f80..9744f4e978 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -8,7 +8,7 @@ 10.0.0-beta.25419.2 - 18.0.0-preview.25420.1 + 18.0.0-preview.25421.1 3.11.0-preview.25421.4 1.9.0-preview.25421.4 From b7cc9b766fca5b987a29ff71dd0ed52643e26226 Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Sat, 23 Aug 2025 09:03:15 +0200 Subject: [PATCH 424/541] [main] Update dependencies from microsoft/testfx (#6427) Co-authored-by: dotnet-maestro[bot] --- eng/Version.Details.xml | 8 ++++---- eng/Versions.props | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index 43a4e0b7b9..123d97240b 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -17,13 +17,13 @@ https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage ad8260f1662c4c5e3099cb3ee5b96f38b01a6c6e - + https://github.com/microsoft/testfx - b6e4331e0c11a01178d4a832cb0eb6beeebe945a + 8f99258760961972b88c1e60efc81d31d1464af6 - + https://github.com/microsoft/testfx - b6e4331e0c11a01178d4a832cb0eb6beeebe945a + 8f99258760961972b88c1e60efc81d31d1464af6 diff --git a/eng/Versions.props b/eng/Versions.props index 9744f4e978..6cfce83b7c 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -10,7 +10,7 @@ 10.0.0-beta.25419.2 18.0.0-preview.25421.1 - 3.11.0-preview.25421.4 - 1.9.0-preview.25421.4 + 3.11.0-preview.25422.2 + 1.9.0-preview.25422.2 From f05f838a052f95baf89216f0f4fc5eeb5b3b9814 Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Sun, 24 Aug 2025 06:19:04 +0200 Subject: [PATCH 425/541] [main] Update dependencies from microsoft/testfx (#6431) Co-authored-by: dotnet-maestro[bot] --- eng/Version.Details.xml | 8 ++++---- eng/Versions.props | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index 123d97240b..c5e7d3632a 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -17,13 +17,13 @@ https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage ad8260f1662c4c5e3099cb3ee5b96f38b01a6c6e - + https://github.com/microsoft/testfx - 8f99258760961972b88c1e60efc81d31d1464af6 + b7cc9b766fca5b987a29ff71dd0ed52643e26226 - + https://github.com/microsoft/testfx - 8f99258760961972b88c1e60efc81d31d1464af6 + b7cc9b766fca5b987a29ff71dd0ed52643e26226 diff --git a/eng/Versions.props b/eng/Versions.props index 6cfce83b7c..688c0c15f5 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -10,7 +10,7 @@ 10.0.0-beta.25419.2 18.0.0-preview.25421.1 - 3.11.0-preview.25422.2 - 1.9.0-preview.25422.2 + 3.11.0-preview.25423.1 + 1.9.0-preview.25423.1 From 1d18680a131cfe055c13a9807b90b7d5a5066e6b Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Sun, 24 Aug 2025 17:58:23 +0200 Subject: [PATCH 426/541] Improve collection.Count/Length detection in MSTEST0037 (#6428) --- .../UseProperAssertMethodsFixer.cs | 96 ++++-------- .../UseProperAssertMethodsAnalyzer.cs | 146 ++++++++++++------ .../UseProperAssertMethodsAnalyzerTests.cs | 30 +++- 3 files changed, 158 insertions(+), 114 deletions(-) diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/UseProperAssertMethodsFixer.cs b/src/Analyzers/MSTest.Analyzers.CodeFixes/UseProperAssertMethodsFixer.cs index 3c5ef8c80f..a2b22ce340 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/UseProperAssertMethodsFixer.cs +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/UseProperAssertMethodsFixer.cs @@ -70,7 +70,7 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) switch (mode) { case UseProperAssertMethodsAnalyzer.CodeFixModeSimple: - createChangedDocument = ct => FixAssertMethodForSimpleModeAsync(context.Document, diagnostic.AdditionalLocations[0], diagnostic.AdditionalLocations[1], root, simpleNameSyntax, properAssertMethodName, ct); + createChangedDocument = ct => FixAssertMethodForSimpleModeAsync(context.Document, diagnostic.AdditionalLocations, root, simpleNameSyntax, properAssertMethodName, ct); break; case UseProperAssertMethodsAnalyzer.CodeFixModeAddArgument: createChangedDocument = ct => FixAssertMethodForAddArgumentModeAsync(context.Document, diagnostic.AdditionalLocations[0], diagnostic.AdditionalLocations[1], diagnostic.AdditionalLocations[2], root, simpleNameSyntax, properAssertMethodName, ct); @@ -78,8 +78,8 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) case UseProperAssertMethodsAnalyzer.CodeFixModeRemoveArgument: createChangedDocument = ct => FixAssertMethodForRemoveArgumentModeAsync(context.Document, diagnostic.AdditionalLocations, root, simpleNameSyntax, properAssertMethodName, diagnostic.Properties.ContainsKey(UseProperAssertMethodsAnalyzer.NeedsNullableBooleanCastKey), ct); break; - case UseProperAssertMethodsAnalyzer.CodeFixModeCollectionCount: - createChangedDocument = ct => FixAssertMethodForCollectionCountModeAsync(context.Document, diagnostic.AdditionalLocations, root, simpleNameSyntax, properAssertMethodName, ct); + case UseProperAssertMethodsAnalyzer.CodeFixModeRemoveArgumentAndReplaceArgument: + createChangedDocument = ct => FixAssertMethodForRemoveArgumentAndReplaceArgumentModeAsync(context.Document, diagnostic.AdditionalLocations, root, simpleNameSyntax, properAssertMethodName, ct); break; default: break; @@ -96,25 +96,29 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) } } - private static async Task FixAssertMethodForSimpleModeAsync(Document document, Location conditionLocationToBeReplaced, Location replacementExpressionLocation, SyntaxNode root, SimpleNameSyntax simpleNameSyntax, string properAssertMethodName, CancellationToken cancellationToken) + private static async Task FixAssertMethodForSimpleModeAsync(Document document, IReadOnlyList additionalLocations, SyntaxNode root, SimpleNameSyntax simpleNameSyntax, string properAssertMethodName, CancellationToken cancellationToken) { - // This doesn't properly handle cases like Assert.IsTrue(message: "My message", condition: x == null) - // The proper handling of this may be Assert.IsNull(message: "My message", value: x) - // Or: Assert.IsNull(x, "My message") - // For now this is not handled. - if (root.FindNode(conditionLocationToBeReplaced.SourceSpan) is not ArgumentSyntax conditionNodeToBeReplaced) - { - return document; - } + DocumentEditor editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false); + FixInvocationMethodName(editor, simpleNameSyntax, properAssertMethodName); - if (root.FindNode(replacementExpressionLocation.SourceSpan) is not ExpressionSyntax replacementExpressionNode) + for (int i = 0; i < additionalLocations.Count; i += 2) { - return document; - } + // This doesn't properly handle cases like Assert.IsTrue(message: "My message", condition: x == null) + // The proper handling of this may be Assert.IsNull(message: "My message", value: x) + // Or: Assert.IsNull(x, "My message") + // For now this is not handled. + if (root.FindNode(additionalLocations[i].SourceSpan) is not ArgumentSyntax conditionNodeToBeReplaced) + { + return document; + } - DocumentEditor editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false); - FixInvocationMethodName(editor, simpleNameSyntax, properAssertMethodName); - editor.ReplaceNode(conditionNodeToBeReplaced, SyntaxFactory.Argument(replacementExpressionNode).WithAdditionalAnnotations(Formatter.Annotation)); + if (root.FindNode(additionalLocations[i + 1].SourceSpan, getInnermostNodeForTie: true) is not ExpressionSyntax replacementExpressionNode) + { + return document; + } + + editor.ReplaceNode(conditionNodeToBeReplaced, SyntaxFactory.Argument(replacementExpressionNode).WithAdditionalAnnotations(Formatter.Annotation)); + } return editor.GetChangedDocument(); } @@ -213,7 +217,7 @@ private static async Task FixAssertMethodForRemoveArgumentModeAsync( return editor.GetChangedDocument(); } - private static async Task FixAssertMethodForCollectionCountModeAsync( + private static async Task FixAssertMethodForRemoveArgumentAndReplaceArgumentModeAsync( Document document, IReadOnlyList additionalLocations, SyntaxNode root, @@ -223,61 +227,29 @@ private static async Task FixAssertMethodForCollectionCountModeAsync( { // Handle collection count transformations: // Assert.AreEqual(0, list.Count) -> Assert.IsEmpty(list) - // Assert.AreEqual(3, list.Count) -> Assert.HasCount(3, list) // Assert.AreEqual(list.Count, 0) -> Assert.IsEmpty(list) - // Assert.AreEqual(list.Count, 3) -> Assert.HasCount(3, list) - if (root.FindNode(additionalLocations[0].SourceSpan) is not ArgumentSyntax firstArgument || - root.FindNode(additionalLocations[1].SourceSpan) is not ArgumentSyntax || - firstArgument.Parent is not ArgumentListSyntax argumentList) + if (root.FindNode(additionalLocations[0].SourceSpan) is not ArgumentSyntax expectedArgumentToRemove) { return document; } - if (root.FindNode(additionalLocations[2].SourceSpan) is not ExpressionSyntax collectionExpression) + if (root.FindNode(additionalLocations[1].SourceSpan) is not ArgumentSyntax argumentToBeReplaced || + root.FindNode(additionalLocations[2].SourceSpan) is not ExpressionSyntax replacement) { return document; } - DocumentEditor editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false); - FixInvocationMethodName(editor, simpleNameSyntax, properAssertMethodName); - - // Preserve any additional arguments beyond the first two (expected/actual) - var additionalArguments = argumentList.Arguments.Skip(2).ToList(); - - ArgumentListSyntax newArgumentList; - - if (properAssertMethodName == "IsEmpty") - { - // For IsEmpty, we just need the collection argument plus any additional arguments - var newArguments = new List - { - SyntaxFactory.Argument(collectionExpression).WithAdditionalAnnotations(Formatter.Annotation), - }; - newArguments.AddRange(additionalArguments); - newArgumentList = argumentList.WithArguments(SyntaxFactory.SeparatedList(newArguments)); - } - else // HasCount + if (expectedArgumentToRemove.Parent is not ArgumentListSyntax argumentList) { - // For HasCount, we need count and collection arguments plus any additional arguments - // additionalLocations[3] should contain the count expression - if (additionalLocations.Count > 3 && - root.FindNode(additionalLocations[3].SourceSpan) is ArgumentSyntax countArgument) - { - var newArguments = new List - { - SyntaxFactory.Argument(countArgument.Expression).WithAdditionalAnnotations(Formatter.Annotation), - SyntaxFactory.Argument(collectionExpression).WithAdditionalAnnotations(Formatter.Annotation), - }; - newArguments.AddRange(additionalArguments); - newArgumentList = argumentList.WithArguments(SyntaxFactory.SeparatedList(newArguments)); - } - else - { - // Fallback: something went wrong, don't apply the fix - return document; - } + return document; } + DocumentEditor editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false); + FixInvocationMethodName(editor, simpleNameSyntax, properAssertMethodName); + + int argumentIndexToRemove = argumentList.Arguments.IndexOf(expectedArgumentToRemove); + ArgumentListSyntax newArgumentList = argumentList.ReplaceNode(argumentToBeReplaced, argumentToBeReplaced.WithExpression(replacement)); + newArgumentList = newArgumentList.WithArguments(newArgumentList.Arguments.RemoveAt(argumentIndexToRemove)); editor.ReplaceNode(argumentList, newArgumentList); return editor.GetChangedDocument(); diff --git a/src/Analyzers/MSTest.Analyzers/UseProperAssertMethodsAnalyzer.cs b/src/Analyzers/MSTest.Analyzers/UseProperAssertMethodsAnalyzer.cs index 4d62220efa..932774bd5a 100644 --- a/src/Analyzers/MSTest.Analyzers/UseProperAssertMethodsAnalyzer.cs +++ b/src/Analyzers/MSTest.Analyzers/UseProperAssertMethodsAnalyzer.cs @@ -149,6 +149,7 @@ private enum CountCheckStatus /// The value for ProperAssertMethodNameKey is "IsNull". /// The first additional location will point to the "x == null" node. /// The second additional location will point to the "x" node. + /// Optionally, more additional locations will also be interpreted as "replace" operations. /// internal const string CodeFixModeSimple = nameof(CodeFixModeSimple); @@ -173,7 +174,7 @@ private enum CountCheckStatus /// /// Find the right assert method name from the properties bag using . /// Replace the identifier syntax for the invocation with the right assert method name. The identifier syntax is calculated by the codefix. - /// Remove the argument which the second additional locations points to. + /// Remove the argument which the first additional location points to. /// /// Example: For Assert.AreEqual(false, x), it will become Assert.IsFalse(x). /// The value for ProperAssertMethodNameKey is "IsFalse". @@ -186,16 +187,20 @@ private enum CountCheckStatus internal const string CodeFixModeRemoveArgument = nameof(CodeFixModeRemoveArgument); /// - /// This mode means the codefix operation is as follows for collection count checks: + /// This mode means the codefix operation is as follows: /// /// Find the right assert method name from the properties bag using . - /// Replace the identifier syntax for the invocation with the right assert method name. - /// Transform arguments based on the count check pattern. + /// Replace the identifier syntax for the invocation with the right assert method name. The identifier syntax is calculated by the codefix. + /// Remove the argument which the first additional location points to. + /// Replace the argument which the second additional location points to with the expression pointed to by the third additional location /// /// Example: For Assert.AreEqual(0, list.Count), it will become Assert.IsEmpty(list). - /// Example: For Assert.AreEqual(3, list.Count), it will become Assert.HasCount(3, list). + /// The value for ProperAssertMethodNameKey is "IsEmpty". + /// The first additional location will point to the "0" node. + /// The second additional location will point to the "list.Count" node. + /// The third additional location will point to the "list" node. /// - internal const string CodeFixModeCollectionCount = nameof(CodeFixModeCollectionCount); + internal const string CodeFixModeRemoveArgumentAndReplaceArgument = nameof(CodeFixModeRemoveArgumentAndReplaceArgument); private static readonly LocalizableResourceString Title = new(nameof(Resources.UseProperAssertMethodsTitle), Resources.ResourceManager, typeof(Resources)); private static readonly LocalizableResourceString MessageFormat = new(nameof(Resources.UseProperAssertMethodsMessageFormat), Resources.ResourceManager, typeof(Resources)); @@ -704,45 +709,46 @@ private static void AnalyzeAreEqualOrAreNotEqualInvocation(OperationAnalysisCont expectedArgument, actualArgumentValue, objectTypeSymbol, - out SyntaxNode? collectionExpr, - out _, - out _); + out SyntaxNode? nodeToBeReplaced1, + out SyntaxNode? replacement1, + out SyntaxNode? nodeToBeReplaced2, + out SyntaxNode? replacement2); if (countStatus != CountCheckStatus.Unknown) { + if (nodeToBeReplaced1 is null || replacement1 is null) + { + throw ApplicationStateGuard.Unreachable(); + } + string properAssertMethod = countStatus == CountCheckStatus.IsEmpty ? "IsEmpty" : "HasCount"; ImmutableDictionary.Builder properties = ImmutableDictionary.CreateBuilder(); properties.Add(ProperAssertMethodNameKey, properAssertMethod); - if (countStatus == CountCheckStatus.IsEmpty) + if (nodeToBeReplaced2 is not null && replacement2 is null) { - // Assert.IsEmpty(collection) - properties.Add(CodeFixModeKey, CodeFixModeCollectionCount); + // Here we suggest Assert.IsEmpty(collection) + properties.Add(CodeFixModeKey, CodeFixModeRemoveArgumentAndReplaceArgument); context.ReportDiagnostic(context.Operation.CreateDiagnostic( Rule, additionalLocations: ImmutableArray.Create( - expectedArgument.Syntax.GetLocation(), // argument to remove/modify - actualArgumentValue.Syntax.GetLocation(), // argument to remove/modify - collectionExpr!.GetLocation()), // collection expression + nodeToBeReplaced2.GetLocation(), + nodeToBeReplaced1.GetLocation(), + replacement1.GetLocation()), properties: properties.ToImmutable(), properAssertMethod, "AreEqual")); } else { - // Assert.HasCount(expectedCount, collection) - properties.Add(CodeFixModeKey, CodeFixModeCollectionCount); - SyntaxNode expectedCountExpr = expectedArgument.ConstantValue.HasValue && expectedArgument.ConstantValue.Value is int ? - expectedArgument.Syntax : actualArgumentValue.Syntax; - + // Here we suggest Assert.HasCount(expectedCount, collection) + properties.Add(CodeFixModeKey, CodeFixModeSimple); context.ReportDiagnostic(context.Operation.CreateDiagnostic( Rule, - additionalLocations: ImmutableArray.Create( - expectedArgument.Syntax.GetLocation(), // first original argument - actualArgumentValue.Syntax.GetLocation(), // second original argument - collectionExpr!.GetLocation(), // collection expression - expectedCountExpr.GetLocation()), // count value expression + additionalLocations: nodeToBeReplaced2 is not null && replacement2 is not null + ? ImmutableArray.Create(nodeToBeReplaced1.GetLocation(), replacement1.GetLocation(), nodeToBeReplaced2.GetLocation(), replacement2.GetLocation()) + : ImmutableArray.Create(nodeToBeReplaced1.GetLocation(), replacement1.GetLocation()), properties: properties.ToImmutable(), properAssertMethod, "AreEqual")); @@ -869,39 +875,83 @@ private static CountCheckStatus RecognizeCountCheck( IOperation expectedArgument, IOperation actualArgument, INamedTypeSymbol objectTypeSymbol, - out SyntaxNode? collectionExpression, - out SyntaxNode? countExpression, - out int countValue) + out SyntaxNode? nodeToBeReplaced1, + out SyntaxNode? replacement1, + out SyntaxNode? nodeToBeReplaced2, + out SyntaxNode? replacement2) { - // Check if expectedArgument is a literal and actualArgument is a count/length property - if (expectedArgument.ConstantValue.HasValue && - expectedArgument.ConstantValue.Value is int expectedValue && - expectedValue >= 0 && - actualArgument is IPropertyReferenceOperation propertyRef && + // Check if actualArgument is a count/length property + if (actualArgument is IPropertyReferenceOperation propertyRef && TryGetCollectionExpressionIfBCLCollectionLengthOrCount(propertyRef, objectTypeSymbol) is { } expression) { - collectionExpression = expression; - countExpression = propertyRef.Syntax; - countValue = expectedValue; - return expectedValue == 0 ? CountCheckStatus.IsEmpty : CountCheckStatus.HasCount; + bool isEmpty = expectedArgument.ConstantValue.HasValue && + expectedArgument.ConstantValue.Value is int expectedValue && + expectedValue == 0; + + if (isEmpty) + { + // We have Assert.AreEqual(0, collection.Count/Length) + // We want Assert.IsEmpty(collection) + // So, only a single replacement is needed. We replace collection.Count with collection. + nodeToBeReplaced1 = actualArgument.Syntax; // collection.Count + replacement1 = expression; // collection + nodeToBeReplaced2 = expectedArgument.Syntax; // 0 + replacement2 = null; + return CountCheckStatus.IsEmpty; + } + else + { + // We have Assert.AreEqual(expectedCount, collection.Count/Length) + // We want Assert.HasCount(expectedCount, collection) + // So, only a single replacement is needed. We replace collection.Count with collection. + nodeToBeReplaced1 = actualArgument.Syntax; // collection.Count + replacement1 = expression; // collection + nodeToBeReplaced2 = null; + replacement2 = null; + return CountCheckStatus.HasCount; + } } // Check if actualArgument is a literal and expectedArgument is a count/length property - if (actualArgument.ConstantValue.HasValue && - actualArgument.ConstantValue.Value is int actualValue && - actualValue >= 0 && - expectedArgument is IPropertyReferenceOperation propertyRef2 && + if (expectedArgument is IPropertyReferenceOperation propertyRef2 && TryGetCollectionExpressionIfBCLCollectionLengthOrCount(propertyRef2, objectTypeSymbol) is { } expression2) { - collectionExpression = expression2; - countExpression = propertyRef2.Syntax; - countValue = actualValue; - return actualValue == 0 ? CountCheckStatus.IsEmpty : CountCheckStatus.HasCount; + bool isEmpty = actualArgument.ConstantValue.HasValue && + actualArgument.ConstantValue.Value is int actualValue && + actualValue == 0; + + if (isEmpty) + { + // We have Assert.AreEqual(collection.Count/Length, expectedCount) + // We want Assert.IsEmpty(collection) + // So, only two replacements are needed: + // 1. Replace collection.Count/Length with expectedCount + // 2. Replace expectedCount with collection + nodeToBeReplaced1 = expectedArgument.Syntax; // collection.Count/Length + replacement1 = expression2; // collection + nodeToBeReplaced2 = actualArgument.Syntax; // expectedCount + replacement2 = null; + return CountCheckStatus.IsEmpty; + } + else + { + // We have Assert.AreEqual(collection.Count/Length, expectedCount) + // We want Assert.HasCount(expectedCount, collection) + // So, only two replacements are needed: + // 1. Replace collection.Count/Length with expectedCount + // 2. Replace expectedCount with collection + nodeToBeReplaced1 = expectedArgument.Syntax; // collection.Count/Length + replacement1 = actualArgument.Syntax; // expectedCount + nodeToBeReplaced2 = actualArgument.Syntax; // expectedCount + replacement2 = expression2; // collection + return CountCheckStatus.HasCount; + } } - collectionExpression = null; - countExpression = null; - countValue = 0; + nodeToBeReplaced1 = null; + replacement1 = null; + nodeToBeReplaced2 = null; + replacement2 = null; return CountCheckStatus.Unknown; } diff --git a/test/UnitTests/MSTest.Analyzers.UnitTests/UseProperAssertMethodsAnalyzerTests.cs b/test/UnitTests/MSTest.Analyzers.UnitTests/UseProperAssertMethodsAnalyzerTests.cs index 9af795ab9f..e2e64f51f1 100644 --- a/test/UnitTests/MSTest.Analyzers.UnitTests/UseProperAssertMethodsAnalyzerTests.cs +++ b/test/UnitTests/MSTest.Analyzers.UnitTests/UseProperAssertMethodsAnalyzerTests.cs @@ -1831,6 +1831,7 @@ public void MyTestMethod() { var list = new List(); {|#0:Assert.AreEqual(0, list.Count)|}; + {|#1:Assert.AreEqual(list.Count, 0)|}; } } """; @@ -1847,14 +1848,19 @@ public void MyTestMethod() { var list = new List(); Assert.IsEmpty(list); + Assert.IsEmpty(list); } } """; await VerifyCS.VerifyCodeFixAsync( code, - // /0/Test0.cs(11,9): info MSTEST0037: Use 'Assert.IsEmpty' instead of 'Assert.AreEqual' - VerifyCS.DiagnosticIgnoringAdditionalLocations().WithLocation(0).WithArguments("IsEmpty", "AreEqual"), + [ + // /0/Test0.cs(11,9): info MSTEST0037: Use 'Assert.IsEmpty' instead of 'Assert.AreEqual' + VerifyCS.DiagnosticIgnoringAdditionalLocations().WithLocation(0).WithArguments("IsEmpty", "AreEqual"), + // /0/Test0.cs(12,9): info MSTEST0037: Use 'Assert.IsEmpty' instead of 'Assert.AreEqual' + VerifyCS.DiagnosticIgnoringAdditionalLocations().WithLocation(1).WithArguments("IsEmpty", "AreEqual"), + ], fixedCode); } @@ -1872,7 +1878,11 @@ public class MyTestClass public void MyTestMethod() { var list = new List { 1, 2, 3 }; + int x = 3; {|#0:Assert.AreEqual(3, list.Count)|}; + {|#1:Assert.AreEqual(list.Count, 3)|}; + {|#2:Assert.AreEqual(x, list.Count)|}; + {|#3:Assert.AreEqual(list.Count, x)|}; } } """; @@ -1888,15 +1898,27 @@ public class MyTestClass public void MyTestMethod() { var list = new List { 1, 2, 3 }; + int x = 3; Assert.HasCount(3, list); + Assert.HasCount(3, list); + Assert.HasCount(x, list); + Assert.HasCount(x, list); } } """; await VerifyCS.VerifyCodeFixAsync( code, - // /0/Test0.cs(11,9): info MSTEST0037: Use 'Assert.HasCount' instead of 'Assert.AreEqual' - VerifyCS.DiagnosticIgnoringAdditionalLocations().WithLocation(0).WithArguments("HasCount", "AreEqual"), + [ + // /0/Test0.cs(12,9): info MSTEST0037: Use 'Assert.HasCount' instead of 'Assert.AreEqual' + VerifyCS.DiagnosticIgnoringAdditionalLocations().WithLocation(0).WithArguments("HasCount", "AreEqual"), + // /0/Test0.cs(13,9): info MSTEST0037: Use 'Assert.HasCount' instead of 'Assert.AreEqual' + VerifyCS.DiagnosticIgnoringAdditionalLocations().WithLocation(1).WithArguments("HasCount", "AreEqual"), + // /0/Test0.cs(14,9): info MSTEST0037: Use 'Assert.HasCount' instead of 'Assert.AreEqual' + VerifyCS.DiagnosticIgnoringAdditionalLocations().WithLocation(2).WithArguments("HasCount", "AreEqual"), + // /0/Test0.cs(15,9): info MSTEST0037: Use 'Assert.HasCount' instead of 'Assert.AreEqual' + VerifyCS.DiagnosticIgnoringAdditionalLocations().WithLocation(3).WithArguments("HasCount", "AreEqual"), + ], fixedCode); } From 9b4aa7a3bac6e3a876b8874a34a5426672ba7cf5 Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Mon, 25 Aug 2025 09:06:53 +0200 Subject: [PATCH 427/541] [main] Update dependencies from microsoft/testfx (#6433) Co-authored-by: dotnet-maestro[bot] Co-authored-by: Youssef1313 --- eng/Version.Details.xml | 8 ++++---- eng/Versions.props | 4 ++-- .../RetryFailedTestsTests.cs | 2 +- .../IPC/ProtocolTests.cs | 4 ++-- .../Messages/AsynchronousMessageBusTests.cs | 4 ++-- .../Services/ServiceProviderTests.cs | 2 +- 6 files changed, 12 insertions(+), 12 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index c5e7d3632a..71f882615b 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -17,13 +17,13 @@ https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage ad8260f1662c4c5e3099cb3ee5b96f38b01a6c6e - + https://github.com/microsoft/testfx - b7cc9b766fca5b987a29ff71dd0ed52643e26226 + 1d18680a131cfe055c13a9807b90b7d5a5066e6b - + https://github.com/microsoft/testfx - b7cc9b766fca5b987a29ff71dd0ed52643e26226 + 1d18680a131cfe055c13a9807b90b7d5a5066e6b diff --git a/eng/Versions.props b/eng/Versions.props index 688c0c15f5..ea5b4bf388 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -10,7 +10,7 @@ 10.0.0-beta.25419.2 18.0.0-preview.25421.1 - 3.11.0-preview.25423.1 - 1.9.0-preview.25423.1 + 3.11.0-preview.25424.2 + 1.9.0-preview.25424.2 diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/RetryFailedTestsTests.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/RetryFailedTestsTests.cs index cb4a6221fd..86a1f1476c 100644 --- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/RetryFailedTestsTests.cs +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/RetryFailedTestsTests.cs @@ -201,7 +201,7 @@ public async Task RetryFailedTests_PassingFromFirstTime_UsingOldDotnetTest_MoveF // File names are on the form: RetryFailedTests_tfm_architecture.log string[] logFilesFromInvokeTestingPlatformTask = Directory.GetFiles(resultDirectory, "RetryFailedTests_*_*.log"); - Assert.AreEqual(TargetFrameworks.All.Length, logFilesFromInvokeTestingPlatformTask.Length); + Assert.HasCount(TargetFrameworks.All.Length, logFilesFromInvokeTestingPlatformTask); foreach (string logFile in logFilesFromInvokeTestingPlatformTask) { string logFileContents = File.ReadAllText(logFile); diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/ProtocolTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/ProtocolTests.cs index b28de2b031..4343493322 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/ProtocolTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/ProtocolTests.cs @@ -49,7 +49,7 @@ public void DiscoveredTestMessagesSerializeDeserialize() Assert.IsNotNull(deserialized); Assert.AreEqual(message.ExecutionId, deserialized.ExecutionId); Assert.AreEqual(message.InstanceId, deserialized.InstanceId); - Assert.AreEqual(message.DiscoveredMessages.Length, deserialized.DiscoveredMessages.Length); + Assert.HasCount(message.DiscoveredMessages.Length, deserialized.DiscoveredMessages); for (int i = 0; i < message.DiscoveredMessages.Length; i++) { DiscoveredTestMessage expected = message.DiscoveredMessages[i]; @@ -61,7 +61,7 @@ public void DiscoveredTestMessagesSerializeDeserialize() Assert.AreEqual(expected.Namespace, actual.Namespace); Assert.AreEqual(expected.TypeName, actual.TypeName); Assert.AreEqual(expected.MethodName, actual.MethodName); - Assert.AreEqual(expected.Traits.Length, actual.Traits.Length); + Assert.HasCount(expected.Traits.Length, actual.Traits); for (int j = 0; j < expected.Traits.Length; j++) { Assert.AreEqual(expected.Traits[j].Key, actual.Traits[j].Key); diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Messages/AsynchronousMessageBusTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Messages/AsynchronousMessageBusTests.cs index afcbfd4392..7c69ab1d7b 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Messages/AsynchronousMessageBusTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Messages/AsynchronousMessageBusTests.cs @@ -126,10 +126,10 @@ public async Task Consumers_ConsumeData_ShouldNotMissAnyPayload() await proxy.DrainDataAsync(); - Assert.AreEqual(totalConsumers, dummyConsumers.Count); + Assert.HasCount(totalConsumers, dummyConsumers); foreach (DummyConsumer consumer in dummyConsumers) { - Assert.AreEqual(totalPayloads, consumer.DummyDataList.Count); + Assert.HasCount(totalPayloads, consumer.DummyDataList); int i = 1; foreach (DummyConsumer.DummyData payload in consumer.DummyDataList.OrderBy(x => x.Data)) diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Services/ServiceProviderTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Services/ServiceProviderTests.cs index 431b5054a3..330c943b49 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Services/ServiceProviderTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Services/ServiceProviderTests.cs @@ -71,7 +71,7 @@ public void Clone_WithoutFilter_Succeeded() var clonedServiceProvider = (ServiceProvider)_serviceProvider.Clone(); - Assert.AreEqual(_serviceProvider.Services.Count, clonedServiceProvider.Services.Count); + Assert.HasCount(_serviceProvider.Services.Count, clonedServiceProvider.Services); for (int i = 0; i < _serviceProvider.Services.Count; i++) { Assert.AreEqual(_serviceProvider.Services.ToArray()[i], clonedServiceProvider.Services.ToArray()[i]); From f69014cd1e40c54f109d0b9907546ad0015c8155 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Mon, 25 Aug 2025 11:02:18 +0200 Subject: [PATCH 428/541] Don't set insert_final_newline for xlf/resx files (#6435) --- .editorconfig | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.editorconfig b/.editorconfig index 2fa5b7363d..5d3beb0336 100644 --- a/.editorconfig +++ b/.editorconfig @@ -13,6 +13,9 @@ vsspell_dictionary_languages = en-US vsspell_section_id = 842f80e2d4aa4288afdcd0e42833eeaf vsspell_ignored_words_842f80e2d4aa4288afdcd0e42833eeaf = runsettings|nullable|args|testhost|mutex|trx|vstest|arity|async|bool|inlined|json|jsonite|jsonrpc|localhost|readonly|xml|stylecop|indices|dotnet|lifecycle +[*.{xlf,resx}] +insert_final_newline = unset + # Xml localization files [*.xlf] vsspell_spell_check_as_you_type = false From 1240b1f4a6a64a96a0c8d244078d43a9536fe9af Mon Sep 17 00:00:00 2001 From: Copilot <198982749+Copilot@users.noreply.github.com> Date: Mon, 25 Aug 2025 13:54:39 +0200 Subject: [PATCH 429/541] Add analyzer for Assert APIs with format parameters (MSTEST0053) (#6294) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: Evangelink <11340282+Evangelink@users.noreply.github.com> Co-authored-by: Amaury Levé --- .../AvoidAssertFormatParametersFixer.cs | 287 ++++++++++++ .../CodeFixResources.resx | 6 + .../xlf/CodeFixResources.cs.xlf | 10 + .../xlf/CodeFixResources.de.xlf | 10 + .../xlf/CodeFixResources.es.xlf | 10 + .../xlf/CodeFixResources.fr.xlf | 10 + .../xlf/CodeFixResources.it.xlf | 10 + .../xlf/CodeFixResources.ja.xlf | 10 + .../xlf/CodeFixResources.ko.xlf | 10 + .../xlf/CodeFixResources.pl.xlf | 10 + .../xlf/CodeFixResources.pt-BR.xlf | 10 + .../xlf/CodeFixResources.ru.xlf | 10 + .../xlf/CodeFixResources.tr.xlf | 10 + .../xlf/CodeFixResources.zh-Hans.xlf | 10 + .../xlf/CodeFixResources.zh-Hant.xlf | 10 + .../AnalyzerReleases.Unshipped.md | 1 + .../AvoidAssertFormatParametersAnalyzer.cs | 91 ++++ .../MSTest.Analyzers/Helpers/DiagnosticIds.cs | 1 + src/Analyzers/MSTest.Analyzers/Resources.resx | 6 + .../MSTest.Analyzers/xlf/Resources.cs.xlf | 10 + .../MSTest.Analyzers/xlf/Resources.de.xlf | 10 + .../MSTest.Analyzers/xlf/Resources.es.xlf | 10 + .../MSTest.Analyzers/xlf/Resources.fr.xlf | 10 + .../MSTest.Analyzers/xlf/Resources.it.xlf | 10 + .../MSTest.Analyzers/xlf/Resources.ja.xlf | 10 + .../MSTest.Analyzers/xlf/Resources.ko.xlf | 10 + .../MSTest.Analyzers/xlf/Resources.pl.xlf | 10 + .../MSTest.Analyzers/xlf/Resources.pt-BR.xlf | 10 + .../MSTest.Analyzers/xlf/Resources.ru.xlf | 10 + .../MSTest.Analyzers/xlf/Resources.tr.xlf | 10 + .../xlf/Resources.zh-Hans.xlf | 10 + .../xlf/Resources.zh-Hant.xlf | 10 + ...voidAssertFormatParametersAnalyzerTests.cs | 413 ++++++++++++++++++ 33 files changed, 1065 insertions(+) create mode 100644 src/Analyzers/MSTest.Analyzers.CodeFixes/AvoidAssertFormatParametersFixer.cs create mode 100644 src/Analyzers/MSTest.Analyzers/AvoidAssertFormatParametersAnalyzer.cs create mode 100644 test/UnitTests/MSTest.Analyzers.UnitTests/AvoidAssertFormatParametersAnalyzerTests.cs diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/AvoidAssertFormatParametersFixer.cs b/src/Analyzers/MSTest.Analyzers.CodeFixes/AvoidAssertFormatParametersFixer.cs new file mode 100644 index 0000000000..da9a71e2be --- /dev/null +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/AvoidAssertFormatParametersFixer.cs @@ -0,0 +1,287 @@ +// 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.Immutable; +using System.Composition; + +using Analyzer.Utilities; + +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CodeActions; +using Microsoft.CodeAnalysis.CodeFixes; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Operations; +using Microsoft.CodeAnalysis.Simplification; + +using MSTest.Analyzers.Helpers; + +namespace MSTest.Analyzers.CodeFixes; + +/// +/// Code fix for MSTEST0053: Avoid using Assert methods with format parameters. +/// +[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(AvoidAssertFormatParametersFixer))] +[Shared] +public sealed class AvoidAssertFormatParametersFixer : CodeFixProvider +{ + /// + public override ImmutableArray FixableDiagnosticIds { get; } + = ImmutableArray.Create(DiagnosticIds.AvoidAssertFormatParametersRuleId); + + /// + public override FixAllProvider GetFixAllProvider() + => WellKnownFixAllProviders.BatchFixer; + + /// + public override async Task RegisterCodeFixesAsync(CodeFixContext context) + { + SyntaxNode root = await context.Document.GetRequiredSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); + Diagnostic diagnostic = context.Diagnostics[0]; + if (root.FindNode(context.Span, getInnermostNodeForTie: true) is InvocationExpressionSyntax invocation) + { + RegisterStringFormatCodeFix(context, diagnostic, root, invocation); + await RegisterInterpolatedStringCodeFixAsync(context, diagnostic, root, invocation).ConfigureAwait(false); + } + } + + private static void RegisterStringFormatCodeFix(CodeFixContext context, Diagnostic diagnostic, SyntaxNode root, InvocationExpressionSyntax invocation) + { + var codeAction = CodeAction.Create( + title: CodeFixResources.AvoidAssertFormatParametersUseStringFormat, + createChangedDocument: ct => CreateStringFormatFixAsync(context.Document, root, invocation, ct), + equivalenceKey: $"{nameof(AvoidAssertFormatParametersFixer)}_StringFormat"); + + context.RegisterCodeFix(codeAction, diagnostic); + } + + private static async Task RegisterInterpolatedStringCodeFixAsync(CodeFixContext context, Diagnostic diagnostic, SyntaxNode root, InvocationExpressionSyntax invocation) + { + // Only offer interpolated string fix for simple cases + if (await CanConvertToInterpolatedStringAsync(context.Document, invocation, context.CancellationToken).ConfigureAwait(false)) + { + var codeAction = CodeAction.Create( + title: CodeFixResources.AvoidAssertFormatParametersUseInterpolatedString, + createChangedDocument: ct => CreateInterpolatedStringFixAsync(context.Document, root, invocation, ct), + equivalenceKey: $"{nameof(AvoidAssertFormatParametersFixer)}_InterpolatedString"); + + context.RegisterCodeFix(codeAction, diagnostic); + } + } + + private static async Task CreateStringFormatFixAsync(Document document, SyntaxNode root, InvocationExpressionSyntax invocation, CancellationToken cancellationToken) + { + ArgumentListSyntax oldArgumentList = invocation.ArgumentList; + if (oldArgumentList.Arguments.Count < 2) + { + return document; + } + + SemanticModel semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); + if (semanticModel.GetOperation(invocation, cancellationToken) is not IInvocationOperation invocationOperation) + { + return document; + } + + if (!TryGetMessageAndMessageArgsArguments(invocationOperation, out IArgumentOperation? messageArgumentOperation, out IArgumentOperation? paramsArgumentOperation)) + { + return document; + } + + if (paramsArgumentOperation is null || messageArgumentOperation is null) + { + return document; + } + + ArgumentListSyntax newArgumentList = oldArgumentList; + var formatArgument = (ArgumentSyntax)messageArgumentOperation.Syntax; + if (paramsArgumentOperation.ArgumentKind == ArgumentKind.ParamArray) + { + ImmutableArray elementValues = ((IArrayCreationOperation)paramsArgumentOperation.Value).Initializer!.ElementValues; + IEnumerable paramsArguments = elementValues.Select(e => (ArgumentSyntax)e.Syntax.Parent!); + + InvocationExpressionSyntax stringFormatInvocation = CreateStringFormatCall([formatArgument, .. paramsArguments]); + + newArgumentList = newArgumentList.ReplaceNode(formatArgument, formatArgument.WithExpression(stringFormatInvocation)); + foreach (IOperation element in elementValues.OrderByDescending(e => oldArgumentList.Arguments.IndexOf((ArgumentSyntax)e.Syntax.Parent!))) + { + newArgumentList = newArgumentList.WithArguments(newArgumentList.Arguments.RemoveAt(oldArgumentList.Arguments.IndexOf((ArgumentSyntax)element.Syntax.Parent!))); + } + } + else if (paramsArgumentOperation.ArgumentKind == ArgumentKind.Explicit) + { + var paramsArgumentSyntax = (ArgumentSyntax)paramsArgumentOperation.Syntax; + InvocationExpressionSyntax stringFormatInvocation = CreateStringFormatCall([formatArgument, paramsArgumentSyntax]); + + newArgumentList = newArgumentList.ReplaceNode(formatArgument, formatArgument.WithExpression(stringFormatInvocation)); + newArgumentList = newArgumentList.WithArguments(newArgumentList.Arguments.RemoveAt(oldArgumentList.Arguments.IndexOf(paramsArgumentSyntax))); + } + + return document.WithSyntaxRoot(root.ReplaceNode(oldArgumentList, newArgumentList)); + + static InvocationExpressionSyntax CreateStringFormatCall(IEnumerable arguments) + => SyntaxFactory.InvocationExpression( + SyntaxFactory.MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.StringKeyword)), + SyntaxFactory.IdentifierName("Format")), + SyntaxFactory.ArgumentList(SyntaxFactory.SeparatedList(arguments))); + } + + private static async Task CreateInterpolatedStringFixAsync( + Document document, + SyntaxNode root, + InvocationExpressionSyntax invocation, + CancellationToken cancellationToken) + { + ArgumentListSyntax oldArgumentList = invocation.ArgumentList; + if (oldArgumentList.Arguments.Count < 2) + { + return document; + } + + SemanticModel semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); + if (semanticModel.GetOperation(invocation, cancellationToken) is not IInvocationOperation invocationOperation) + { + return document; + } + + if (!TryGetMessageAndMessageArgsArguments(invocationOperation, out IArgumentOperation? messageArgumentOperation, out IArgumentOperation? paramsArgumentOperation)) + { + return document; + } + + ImmutableArray elementValues = ((IArrayCreationOperation)paramsArgumentOperation.Value).Initializer!.ElementValues; + ArgumentSyntax[] paramsArguments = [.. elementValues.Select(e => (ArgumentSyntax)e.Syntax.Parent!)]; + ArgumentListSyntax newArgumentList = oldArgumentList; + + var formatArgument = (ArgumentSyntax)messageArgumentOperation.Syntax; + + if (TryCreateInterpolatedString(formatArgument, paramsArguments, out InterpolatedStringExpressionSyntax? interpolatedString)) + { + newArgumentList = newArgumentList.ReplaceNode(formatArgument, formatArgument.WithExpression(interpolatedString)); + } + + foreach (IOperation element in elementValues.OrderByDescending(e => oldArgumentList.Arguments.IndexOf((ArgumentSyntax)e.Syntax.Parent!))) + { + newArgumentList = newArgumentList.WithArguments(newArgumentList.Arguments.RemoveAt(oldArgumentList.Arguments.IndexOf((ArgumentSyntax)element.Syntax.Parent!))); + } + + return document.WithSyntaxRoot(root.ReplaceNode(oldArgumentList, newArgumentList)); + } + + private static async Task CanConvertToInterpolatedStringAsync( + Document document, + InvocationExpressionSyntax invocation, + CancellationToken cancellationToken) + { + SeparatedSyntaxList arguments = invocation.ArgumentList.Arguments; + if (arguments.Count < 2) + { + return false; + } + + SemanticModel semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); + if (semanticModel.GetOperation(invocation, cancellationToken) is not IInvocationOperation invocationOperation || + !TryGetMessageAndMessageArgsArguments(invocationOperation, out IArgumentOperation? messageArgumentOperation, out IArgumentOperation? paramsArgumentOperation) || + paramsArgumentOperation.ArgumentKind != ArgumentKind.ParamArray || + messageArgumentOperation.Syntax is not ArgumentSyntax formatArgument) + { + return false; + } + + // We can only offer a fix if the message is a string literal already. + return formatArgument.Expression is LiteralExpressionSyntax literal && + literal.Token.IsKind(SyntaxKind.StringLiteralToken); + } + + private static bool TryCreateInterpolatedString( + ArgumentSyntax formatArgument, + ArgumentSyntax[] paramsArguments, + [NotNullWhen(true)] out InterpolatedStringExpressionSyntax? interpolatedString) + { + interpolatedString = null; + if (formatArgument.Expression is not LiteralExpressionSyntax literal || + !literal.Token.IsKind(SyntaxKind.StringLiteralToken)) + { + return false; + } + + string formatString = literal.Token.ValueText; + var interpolatedContents = new List(); + int currentIndex = 0; + + for (int i = 0; i < formatString.Length; i++) + { + if (formatString[i] == '{' && i + 1 < formatString.Length) + { + // Add text before the placeholder + if (i > currentIndex) + { + string text = formatString[currentIndex..i]; + interpolatedContents.Add(SyntaxFactory.InterpolatedStringText( + SyntaxFactory.Token(SyntaxTriviaList.Empty, SyntaxKind.InterpolatedStringTextToken, text, text, SyntaxTriviaList.Empty))); + } + + // Find the end of the placeholder + int closeIndex = formatString.IndexOf('}', i + 1); + if (closeIndex == -1) + { + return false; // Invalid format string + } + + // Extract the placeholder index + string placeholder = formatString.Substring(i + 1, closeIndex - i - 1); + if (int.TryParse(placeholder, NumberStyles.Integer, CultureInfo.InvariantCulture, out int paramIndex) && paramIndex < paramsArguments.Length) + { + // Create interpolation expression + InterpolationSyntax interpolation = SyntaxFactory.Interpolation( + SyntaxFactory.ParenthesizedExpression( + paramsArguments[paramIndex].Expression).WithAdditionalAnnotations(Simplifier.Annotation)); + interpolatedContents.Add(interpolation); + } + else + { + return false; // Invalid or out-of-range parameter index + } + + currentIndex = closeIndex + 1; + i = closeIndex; + } + } + + // Add remaining text + if (currentIndex < formatString.Length) + { + string text = formatString[currentIndex..]; + interpolatedContents.Add(SyntaxFactory.InterpolatedStringText( + SyntaxFactory.Token(SyntaxTriviaList.Empty, SyntaxKind.InterpolatedStringTextToken, text, text, SyntaxTriviaList.Empty))); + } + + interpolatedString = SyntaxFactory.InterpolatedStringExpression( + SyntaxFactory.Token(SyntaxKind.InterpolatedStringStartToken), + SyntaxFactory.List(interpolatedContents), + SyntaxFactory.Token(SyntaxKind.InterpolatedStringEndToken)); + + return true; + } + + private static bool TryGetMessageAndMessageArgsArguments( + IInvocationOperation invocationOperation, + [NotNullWhen(true)] out IArgumentOperation? messageArgument, + [NotNullWhen(true)] out IArgumentOperation? messageArgsArgument) + { + ImmutableArray parameters = invocationOperation.TargetMethod.Parameters; + if (parameters.Length < 2 || + parameters.SingleOrDefault(p => p.Name == "message" && p.Type.SpecialType == SpecialType.System_String) is not IParameterSymbol messageParameter) + { + messageArgument = null; + messageArgsArgument = null; + return false; + } + + messageArgument = invocationOperation.Arguments.SingleOrDefault(arg => arg.Parameter?.Ordinal == messageParameter.Ordinal); + messageArgsArgument = invocationOperation.Arguments.SingleOrDefault(arg => arg.Parameter?.Ordinal == invocationOperation.TargetMethod.Parameters.Length - 1); + return messageArgument is not null && messageArgsArgument is not null; + } +} diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/CodeFixResources.resx b/src/Analyzers/MSTest.Analyzers.CodeFixes/CodeFixResources.resx index be5663f1eb..587889be53 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/CodeFixResources.resx +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/CodeFixResources.resx @@ -195,4 +195,10 @@ Remove 'DynamicDataSourceType' parameter to use default 'AutoDetect' + + Use 'string.Format' instead of format parameters + + + Use interpolated string instead of format parameters + \ No newline at end of file diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.cs.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.cs.xlf index 6c49aec94f..3eb36cbe9c 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.cs.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.cs.xlf @@ -22,6 +22,16 @@ Použít {0} + + Use interpolated string instead of format parameters + Use interpolated string instead of format parameters + + + + Use 'string.Format' instead of format parameters + Use 'string.Format' instead of format parameters + + Change method accessibility to 'private' Změnit přístupnost metody na private diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.de.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.de.xlf index 3873329568..d4b5ed8ef8 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.de.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.de.xlf @@ -22,6 +22,16 @@ „{0}“ verwenden + + Use interpolated string instead of format parameters + Use interpolated string instead of format parameters + + + + Use 'string.Format' instead of format parameters + Use 'string.Format' instead of format parameters + + Change method accessibility to 'private' Methodenzugriff auf „privat“ ändern diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.es.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.es.xlf index 35fd8a4a02..0572f07414 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.es.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.es.xlf @@ -22,6 +22,16 @@ Usar "{0}" + + Use interpolated string instead of format parameters + Use interpolated string instead of format parameters + + + + Use 'string.Format' instead of format parameters + Use 'string.Format' instead of format parameters + + Change method accessibility to 'private' Cambiar la accesibilidad del método a "private" diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.fr.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.fr.xlf index a5cf0cf2bf..5b52cbca94 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.fr.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.fr.xlf @@ -22,6 +22,16 @@ Utiliser « {0} » + + Use interpolated string instead of format parameters + Use interpolated string instead of format parameters + + + + Use 'string.Format' instead of format parameters + Use 'string.Format' instead of format parameters + + Change method accessibility to 'private' Remplacer l’accessibilité de la méthode par « privé » diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.it.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.it.xlf index f31da6ce1f..c1bd9ff27d 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.it.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.it.xlf @@ -22,6 +22,16 @@ Usare ‘{0}’ + + Use interpolated string instead of format parameters + Use interpolated string instead of format parameters + + + + Use 'string.Format' instead of format parameters + Use 'string.Format' instead of format parameters + + Change method accessibility to 'private' Modifica l'accessibilità del metodo in 'privato' diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ja.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ja.xlf index c767a0d5de..14a21f07af 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ja.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ja.xlf @@ -22,6 +22,16 @@ '{0}' を使用する + + Use interpolated string instead of format parameters + Use interpolated string instead of format parameters + + + + Use 'string.Format' instead of format parameters + Use 'string.Format' instead of format parameters + + Change method accessibility to 'private' メソッドのアクセシビリティを 'private' に変更する diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ko.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ko.xlf index c61eb3cf53..9942b48d93 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ko.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ko.xlf @@ -22,6 +22,16 @@ '{0}' 사용 + + Use interpolated string instead of format parameters + Use interpolated string instead of format parameters + + + + Use 'string.Format' instead of format parameters + Use 'string.Format' instead of format parameters + + Change method accessibility to 'private' 메서드 접근성 '비공개'로 변경하기 diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pl.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pl.xlf index 8679a32ddc..dfcba58a37 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pl.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pl.xlf @@ -22,6 +22,16 @@ Użyj „{0}” + + Use interpolated string instead of format parameters + Use interpolated string instead of format parameters + + + + Use 'string.Format' instead of format parameters + Use 'string.Format' instead of format parameters + + Change method accessibility to 'private' Zmień dostępność metody na „private” (prywatna) diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pt-BR.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pt-BR.xlf index d905b23073..929a2064f7 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pt-BR.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pt-BR.xlf @@ -22,6 +22,16 @@ Usar '{0}' + + Use interpolated string instead of format parameters + Use interpolated string instead of format parameters + + + + Use 'string.Format' instead of format parameters + Use 'string.Format' instead of format parameters + + Change method accessibility to 'private' Alterar a acessibilidade do método para 'privado' diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ru.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ru.xlf index e9309b69c1..37375a63ea 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ru.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ru.xlf @@ -22,6 +22,16 @@ Использовать "{0}" + + Use interpolated string instead of format parameters + Use interpolated string instead of format parameters + + + + Use 'string.Format' instead of format parameters + Use 'string.Format' instead of format parameters + + Change method accessibility to 'private' Изменить доступность метода на "private" diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.tr.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.tr.xlf index 3d7c8d0257..2567a91287 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.tr.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.tr.xlf @@ -22,6 +22,16 @@ '{0}' kullan + + Use interpolated string instead of format parameters + Use interpolated string instead of format parameters + + + + Use 'string.Format' instead of format parameters + Use 'string.Format' instead of format parameters + + Change method accessibility to 'private' Yöntem erişilebilirliğini ‘özel’ olarak değiştir diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hans.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hans.xlf index e77f1cb076..c1d62914a5 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hans.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hans.xlf @@ -22,6 +22,16 @@ 使用“{0}” + + Use interpolated string instead of format parameters + Use interpolated string instead of format parameters + + + + Use 'string.Format' instead of format parameters + Use 'string.Format' instead of format parameters + + Change method accessibility to 'private' 将方法可访问性更改为“private” diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hant.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hant.xlf index 032eb8be4c..08b0b1a7a3 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hant.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hant.xlf @@ -22,6 +22,16 @@ 使用 '{0}' + + Use interpolated string instead of format parameters + Use interpolated string instead of format parameters + + + + Use 'string.Format' instead of format parameters + Use 'string.Format' instead of format parameters + + Change method accessibility to 'private' 將方法協助工具變更為 'private' diff --git a/src/Analyzers/MSTest.Analyzers/AnalyzerReleases.Unshipped.md b/src/Analyzers/MSTest.Analyzers/AnalyzerReleases.Unshipped.md index f68f3db8ab..6d2b4723c8 100644 --- a/src/Analyzers/MSTest.Analyzers/AnalyzerReleases.Unshipped.md +++ b/src/Analyzers/MSTest.Analyzers/AnalyzerReleases.Unshipped.md @@ -7,3 +7,4 @@ Rule ID | Category | Severity | Notes --------|----------|----------|------- MSTEST0051 | Usage | Info | AssertThrowsShouldContainSingleStatementAnalyzer, [Documentation](https://learn.microsoft.com/dotnet/core/testing/mstest-analyzers/mstest0051) MSTEST0052 | Usage | Warning | PreferDynamicDataSourceTypeAutoDetectAnalyzer, [Documentation](https://learn.microsoft.com/dotnet/core/testing/mstest-analyzers/mstest0052) +MSTEST0053 | Usage | Warning | AvoidAssertFormatParametersAnalyzer, [Documentation](https://learn.microsoft.com/dotnet/core/testing/mstest-analyzers/mstest0053) diff --git a/src/Analyzers/MSTest.Analyzers/AvoidAssertFormatParametersAnalyzer.cs b/src/Analyzers/MSTest.Analyzers/AvoidAssertFormatParametersAnalyzer.cs new file mode 100644 index 0000000000..3440e5e8e2 --- /dev/null +++ b/src/Analyzers/MSTest.Analyzers/AvoidAssertFormatParametersAnalyzer.cs @@ -0,0 +1,91 @@ +// 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.Immutable; + +using Analyzer.Utilities.Extensions; + +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Diagnostics; +using Microsoft.CodeAnalysis.Operations; + +using MSTest.Analyzers.Helpers; + +namespace MSTest.Analyzers; + +/// +/// MSTEST0053: . +/// +[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] +public sealed class AvoidAssertFormatParametersAnalyzer : DiagnosticAnalyzer +{ + private static readonly LocalizableResourceString Title = new(nameof(Resources.AvoidAssertFormatParametersTitle), Resources.ResourceManager, typeof(Resources)); + private static readonly LocalizableResourceString MessageFormat = new(nameof(Resources.AvoidAssertFormatParametersMessageFormat), Resources.ResourceManager, typeof(Resources)); + + internal static readonly DiagnosticDescriptor Rule = DiagnosticDescriptorHelper.Create( + DiagnosticIds.AvoidAssertFormatParametersRuleId, + Title, + MessageFormat, + null, + Category.Usage, + DiagnosticSeverity.Warning, + isEnabledByDefault: true); + + /// + public override ImmutableArray SupportedDiagnostics { get; } + = ImmutableArray.Create(Rule); + + /// + public override void Initialize(AnalysisContext context) + { + context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); + context.EnableConcurrentExecution(); + + context.RegisterCompilationStartAction(context => + { + if (context.Compilation.TryGetOrCreateTypeByMetadataName(WellKnownTypeNames.MicrosoftVisualStudioTestToolsUnitTestingAssert, out INamedTypeSymbol? assertSymbol) && + context.Compilation.TryGetOrCreateTypeByMetadataName(WellKnownTypeNames.MicrosoftVisualStudioTestToolsUnitTestingCollectionAssert, out INamedTypeSymbol? collectionAssertSymbol) && + context.Compilation.TryGetOrCreateTypeByMetadataName(WellKnownTypeNames.MicrosoftVisualStudioTestToolsUnitTestingStringAssert, out INamedTypeSymbol? stringAssertSymbol)) + { + context.RegisterOperationAction(context => AnalyzeOperation(context, assertSymbol, collectionAssertSymbol, stringAssertSymbol), OperationKind.Invocation); + } + }); + } + + private static void AnalyzeOperation(OperationAnalysisContext context, INamedTypeSymbol? assertSymbol, INamedTypeSymbol? collectionAssertSymbol, INamedTypeSymbol? stringAssertSymbol) + { + var invocationOperation = (IInvocationOperation)context.Operation; + + // Check if this is a call to Assert, CollectionAssert, or StringAssert + if (!IsTargetAssertType(invocationOperation.TargetMethod.ContainingType, assertSymbol, collectionAssertSymbol, stringAssertSymbol)) + { + return; + } + + // Check if this method call has the format string + params pattern + if (HasFormatStringParamsPattern(invocationOperation)) + { + context.ReportDiagnostic(invocationOperation.CreateDiagnostic(Rule, invocationOperation.TargetMethod.Name)); + } + } + + private static bool IsTargetAssertType(INamedTypeSymbol? containingType, INamedTypeSymbol? assertSymbol, INamedTypeSymbol? collectionAssertSymbol, INamedTypeSymbol? stringAssertSymbol) + => SymbolEqualityComparer.Default.Equals(containingType, assertSymbol) || + SymbolEqualityComparer.Default.Equals(containingType, collectionAssertSymbol) || + SymbolEqualityComparer.Default.Equals(containingType, stringAssertSymbol); + + private static bool HasFormatStringParamsPattern(IInvocationOperation invocationOperation) + { + ImmutableArray parameters = invocationOperation.TargetMethod.Parameters; + + // Look for the pattern: ([other params...], string message, params object[] parameters) + // The last two parameters should be string message and params object[] + return parameters.Length >= 2 && + parameters[parameters.Length - 1] is { IsParams: true, Type: IArrayTypeSymbol { ElementType.SpecialType: SpecialType.System_Object } } && + invocationOperation.Arguments.SingleOrDefault(arg => arg.Parameter?.Ordinal == parameters.Length - 1) is not IArgumentOperation + { + ArgumentKind: ArgumentKind.ParamArray, + Value: IArrayCreationOperation { Initializer.ElementValues.Length: 0 } + }; + } +} diff --git a/src/Analyzers/MSTest.Analyzers/Helpers/DiagnosticIds.cs b/src/Analyzers/MSTest.Analyzers/Helpers/DiagnosticIds.cs index 0b2cbe6f9e..4d02b8b161 100644 --- a/src/Analyzers/MSTest.Analyzers/Helpers/DiagnosticIds.cs +++ b/src/Analyzers/MSTest.Analyzers/Helpers/DiagnosticIds.cs @@ -57,4 +57,5 @@ internal static class DiagnosticIds public const string GlobalTestFixtureShouldBeValidRuleId = "MSTEST0050"; public const string AssertThrowsShouldContainSingleStatementRuleId = "MSTEST0051"; public const string AvoidExplicitDynamicDataSourceTypeRuleId = "MSTEST0052"; + public const string AvoidAssertFormatParametersRuleId = "MSTEST0053"; } diff --git a/src/Analyzers/MSTest.Analyzers/Resources.resx b/src/Analyzers/MSTest.Analyzers/Resources.resx index 4cb1c3b193..982a951879 100644 --- a/src/Analyzers/MSTest.Analyzers/Resources.resx +++ b/src/Analyzers/MSTest.Analyzers/Resources.resx @@ -678,4 +678,10 @@ The type declaring these methods should also respect the following rules: Remove the 'DynamicDataSourceType' argument to use the default auto detect behavior + + Avoid using Assert methods with format parameters + + + Replace '{0}' with format parameters with string.Format or string interpolation + diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf index 757d1d378c..0b416881be 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf @@ -132,6 +132,16 @@ Typ deklarující tyto metody by měl také respektovat následující pravidla: Nepoužívejte Assert.AreSame ani Assert.AreNotSame s typy hodnot. + + Replace '{0}' with format parameters with string.Format or string interpolation + Replace '{0}' with format parameters with string.Format or string interpolation + + + + Avoid using Assert methods with format parameters + Avoid using Assert methods with format parameters + + Prefer 'Assert.ThrowsExactly' or 'Assert.ThrowsExactlyAsync' over '[ExpectedException]' as it ensures that only the expected call throws the expected exception. The assert APIs also provide more flexibility and allow you to assert extra properties of the exception. Preferujte Assert.ThrowsExactly nebo Assert.ThrowsExactlyAsync před [ExpectedException], protože zajišťuje, že očekávanou výjimku vyvolá pouze očekávané volání. Rozhraní API pro vyhodnocení také poskytují větší flexibilitu a umožňují vyhodnocovat další vlastnosti výjimky. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf index 6743426439..0548f41ce3 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf @@ -132,6 +132,16 @@ Der Typ, der diese Methoden deklariert, sollte auch die folgenden Regeln beachte Verwenden Sie "Assert.AreSame" oder "Assert.AreNotSame" nicht mit Werttypen. + + Replace '{0}' with format parameters with string.Format or string interpolation + Replace '{0}' with format parameters with string.Format or string interpolation + + + + Avoid using Assert methods with format parameters + Avoid using Assert methods with format parameters + + Prefer 'Assert.ThrowsExactly' or 'Assert.ThrowsExactlyAsync' over '[ExpectedException]' as it ensures that only the expected call throws the expected exception. The assert APIs also provide more flexibility and allow you to assert extra properties of the exception. „Assert.ThrowsExactly“ oder „Assert.ThrowsExactlyAsync“ gegenüber „[ExpectedException]“ bevorzugen, da dadurch sichergestellt wird, dass nur der erwartete Aufruf die erwartete Ausnahme auslöst. Die Assert-APIs bieten außerdem mehr Flexibilität und ermöglichen es Ihnen, zusätzliche Eigenschaften der Ausführung zu bestätigen. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf index 352e39a299..9928e8bbb2 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf @@ -132,6 +132,16 @@ El tipo que declara estos métodos también debe respetar las reglas siguientes: No use "Assert.AreSame" o "Assert.AreNotSame" con tipos de valor + + Replace '{0}' with format parameters with string.Format or string interpolation + Replace '{0}' with format parameters with string.Format or string interpolation + + + + Avoid using Assert methods with format parameters + Avoid using Assert methods with format parameters + + Prefer 'Assert.ThrowsExactly' or 'Assert.ThrowsExactlyAsync' over '[ExpectedException]' as it ensures that only the expected call throws the expected exception. The assert APIs also provide more flexibility and allow you to assert extra properties of the exception. Preferir "Assert.ThrowsExactly" o "Assert.ThrowsExactlyAsync" en lugar de "[ExpectedException]", ya que garantiza que solo la llamada esperada inicie la excepción esperada. Las API de aserción también proporcionan más flexibilidad y permiten declarar propiedades adicionales de la ejecución. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf index e39e5e5d39..1ed9dbd910 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf @@ -132,6 +132,16 @@ Le type doit être une classe N’utilisez pas 'Assert.AreSame' ou 'Assert.AreNotSame' avec des types valeur + + Replace '{0}' with format parameters with string.Format or string interpolation + Replace '{0}' with format parameters with string.Format or string interpolation + + + + Avoid using Assert methods with format parameters + Avoid using Assert methods with format parameters + + Prefer 'Assert.ThrowsExactly' or 'Assert.ThrowsExactlyAsync' over '[ExpectedException]' as it ensures that only the expected call throws the expected exception. The assert APIs also provide more flexibility and allow you to assert extra properties of the exception. Préférez « Assert.ThrowsExactly » ou « Assert.ThrowsExactlyAsync » à « [ExpectedException] », car il garantit que seul l’appel attendu lève l’exception attendue. Les API d’assertion offrent également plus de flexibilité et vous permettent de déclarer des propriétés supplémentaires de l’exception. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf index c06853d2c8..7e2ca6c047 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf @@ -132,6 +132,16 @@ Anche il tipo che dichiara questi metodi deve rispettare le regole seguenti: Non usare 'Assert.AreSame' o 'Assert.AreNotSame' con i tipi di valore + + Replace '{0}' with format parameters with string.Format or string interpolation + Replace '{0}' with format parameters with string.Format or string interpolation + + + + Avoid using Assert methods with format parameters + Avoid using Assert methods with format parameters + + Prefer 'Assert.ThrowsExactly' or 'Assert.ThrowsExactlyAsync' over '[ExpectedException]' as it ensures that only the expected call throws the expected exception. The assert APIs also provide more flexibility and allow you to assert extra properties of the exception. Preferire 'Assert.ThrowsExactly' o 'Assert.ThrowsExactlyAsync' a '[ExpectedException]' perché assicura che solo la chiamata prevista generi l'eccezione prevista. Le API di asserzione offrono anche maggiore flessibilità e consentono di dichiarare proprietà aggiuntive dell'eccezione. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf index d389192ede..1adef5422d 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf @@ -132,6 +132,16 @@ The type declaring these methods should also respect the following rules: 値型に 'Assert.AreSame' または 'Assert.AreNotSame' を使用しないでください + + Replace '{0}' with format parameters with string.Format or string interpolation + Replace '{0}' with format parameters with string.Format or string interpolation + + + + Avoid using Assert methods with format parameters + Avoid using Assert methods with format parameters + + Prefer 'Assert.ThrowsExactly' or 'Assert.ThrowsExactlyAsync' over '[ExpectedException]' as it ensures that only the expected call throws the expected exception. The assert APIs also provide more flexibility and allow you to assert extra properties of the exception. '[ExpectedException]' よりも 'Assert.ThrowsExactly' または 'Assert.ThrowsExactlyAsync' を優先します。これは、予期された呼び出しのみが予期された例外をスローするようにするためです。アサート API もさらに柔軟性が高く、これにより例外の追加プロパティをアサートできます。 diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf index fc7a972260..91d0e0ebf5 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf @@ -132,6 +132,16 @@ The type declaring these methods should also respect the following rules: 값 형식에 'Assert.AreSame' 또는 'Assert.AreNotSame'을 사용하지 마세요. + + Replace '{0}' with format parameters with string.Format or string interpolation + Replace '{0}' with format parameters with string.Format or string interpolation + + + + Avoid using Assert methods with format parameters + Avoid using Assert methods with format parameters + + Prefer 'Assert.ThrowsExactly' or 'Assert.ThrowsExactlyAsync' over '[ExpectedException]' as it ensures that only the expected call throws the expected exception. The assert APIs also provide more flexibility and allow you to assert extra properties of the exception. 예상되는 호출만 예상되는 예외를 던지도록 하기 위해 '[ExpectedException]보다 'Assert.ThrowsExactly' 또는 'Assert.ThrowsExactlyAsync'를 사용하는 것이 좋습니다. 또한 어설션 API는 더 많은 유연성을 제공하고 예외의 추가 속성을 어설션할 수 있습니다. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf index 8e9a9d5a89..9c7fba96ee 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf @@ -132,6 +132,16 @@ Typ deklarujący te metody powinien również przestrzegać następujących regu Nie używaj elementu "Assert.AreSame" ani "Assert.AreNotSame" z typami wartości + + Replace '{0}' with format parameters with string.Format or string interpolation + Replace '{0}' with format parameters with string.Format or string interpolation + + + + Avoid using Assert methods with format parameters + Avoid using Assert methods with format parameters + + Prefer 'Assert.ThrowsExactly' or 'Assert.ThrowsExactlyAsync' over '[ExpectedException]' as it ensures that only the expected call throws the expected exception. The assert APIs also provide more flexibility and allow you to assert extra properties of the exception. Preferuj opcję „Assert.ThrowsExactly” lub „Assert.ThrowsExactlyAsync” zamiast „[ExpectedException]”, ponieważ gwarantuje ona, że tylko oczekiwane wywołanie rzuci oczekiwany wyjątek. Interfejsy API potwierdzenia zapewniają również większą elastyczność i pozwalają na potwierdzenie dodatkowych właściwości wyjątku. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf index 9cd4ae78f7..db4f2926bc 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf @@ -132,6 +132,16 @@ O tipo que declara esses métodos também deve respeitar as seguintes regras: Não use 'Assert.AreSame' ou 'Assert.AreNotSame' com tipos de valor + + Replace '{0}' with format parameters with string.Format or string interpolation + Replace '{0}' with format parameters with string.Format or string interpolation + + + + Avoid using Assert methods with format parameters + Avoid using Assert methods with format parameters + + Prefer 'Assert.ThrowsExactly' or 'Assert.ThrowsExactlyAsync' over '[ExpectedException]' as it ensures that only the expected call throws the expected exception. The assert APIs also provide more flexibility and allow you to assert extra properties of the exception. Prefira 'Assert.ThrowsExactly' ou 'Assert.ThrowsExactlyAsync' em vez de '[ExpectedException]', pois isso garante que apenas a chamada esperada lance a exceção esperada. As APIs de assert também oferecem mais flexibilidade e permitem que você afirme propriedades adicionais da exceção. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf index 3f957ef057..7bbe063b93 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf @@ -135,6 +135,16 @@ The type declaring these methods should also respect the following rules: Не используйте Assert.AreSame или Assert.AreNotSame с типами значений + + Replace '{0}' with format parameters with string.Format or string interpolation + Replace '{0}' with format parameters with string.Format or string interpolation + + + + Avoid using Assert methods with format parameters + Avoid using Assert methods with format parameters + + Prefer 'Assert.ThrowsExactly' or 'Assert.ThrowsExactlyAsync' over '[ExpectedException]' as it ensures that only the expected call throws the expected exception. The assert APIs also provide more flexibility and allow you to assert extra properties of the exception. Предпочтите "Assert.ThrowsExactly' или 'Assert.ThrowsExactlyAsync" вместо "[ExpectedException]", так как это гарантирует, что только ожидаемый вызов вызовет ожидаемое исключение. API-интерфейсы утверждения также обеспечивают дополнительную гибкость и позволяют утверждать дополнительные свойства исключения. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf index 6dece6197c..facbce52cc 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf @@ -132,6 +132,16 @@ Bu yöntemleri bildiren tipin ayrıca aşağıdaki kurallara uyması gerekir: Değer türleriyle 'Assert.AreSame' veya 'Assert.AreNotSame' kullanma + + Replace '{0}' with format parameters with string.Format or string interpolation + Replace '{0}' with format parameters with string.Format or string interpolation + + + + Avoid using Assert methods with format parameters + Avoid using Assert methods with format parameters + + Prefer 'Assert.ThrowsExactly' or 'Assert.ThrowsExactlyAsync' over '[ExpectedException]' as it ensures that only the expected call throws the expected exception. The assert APIs also provide more flexibility and allow you to assert extra properties of the exception. Yalnızca beklenen çağrının beklenen özel durumu oluşturmasını sağladığı için '[ExpectedException]' yerine 'Assert.ThrowsExactly' veya 'Assert.ThrowsExceptionAsync' tercih edin. Onaylama API'leri de daha fazla esneklik sağlar ve özel durumun ek özelliklerini onaylamanıza izin verir. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf index 00008832d0..05b8942b48 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf @@ -132,6 +132,16 @@ The type declaring these methods should also respect the following rules: 不要将 “Assert.AreSame” 或 “Assert.AreNotSame” 与值类型一起使用 + + Replace '{0}' with format parameters with string.Format or string interpolation + Replace '{0}' with format parameters with string.Format or string interpolation + + + + Avoid using Assert methods with format parameters + Avoid using Assert methods with format parameters + + Prefer 'Assert.ThrowsExactly' or 'Assert.ThrowsExactlyAsync' over '[ExpectedException]' as it ensures that only the expected call throws the expected exception. The assert APIs also provide more flexibility and allow you to assert extra properties of the exception. 首选“Assert.ThrowsExactly”或“Assert.ThrowsExactlyAsync”,而不是“[ExpectedException]”,因为它确保只有预期调用才会引发预期异常。断言 API 还提供更多的灵活性,并允许你断言异常的额外属性。 diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf index 3d64a914d8..b38bf21dfa 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf @@ -132,6 +132,16 @@ The type declaring these methods should also respect the following rules: 不要在值類型中使用 'Assert.AreSame' 或 'Assert.AreNotSame' + + Replace '{0}' with format parameters with string.Format or string interpolation + Replace '{0}' with format parameters with string.Format or string interpolation + + + + Avoid using Assert methods with format parameters + Avoid using Assert methods with format parameters + + Prefer 'Assert.ThrowsExactly' or 'Assert.ThrowsExactlyAsync' over '[ExpectedException]' as it ensures that only the expected call throws the expected exception. The assert APIs also provide more flexibility and allow you to assert extra properties of the exception. 偏好 'Assert.ThrowsExactly' 或 'Assert.ThrowsExactlyAsync' 而不是 '[ExpectedException]',因為它可確保只有預期的呼叫會擲出預期的例外狀況。判斷提示 API 也提供更多彈性,並允許您判斷提示例外狀況的額外屬性。 diff --git a/test/UnitTests/MSTest.Analyzers.UnitTests/AvoidAssertFormatParametersAnalyzerTests.cs b/test/UnitTests/MSTest.Analyzers.UnitTests/AvoidAssertFormatParametersAnalyzerTests.cs new file mode 100644 index 0000000000..af3a29788e --- /dev/null +++ b/test/UnitTests/MSTest.Analyzers.UnitTests/AvoidAssertFormatParametersAnalyzerTests.cs @@ -0,0 +1,413 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using VerifyCS = MSTest.Analyzers.Test.CSharpCodeFixVerifier< + MSTest.Analyzers.AvoidAssertFormatParametersAnalyzer, + MSTest.Analyzers.CodeFixes.AvoidAssertFormatParametersFixer>; + +namespace MSTest.Analyzers.UnitTests; + +[TestClass] +public sealed class AvoidAssertFormatParametersAnalyzerTests +{ + [TestMethod] + public async Task WhenAssertMethodWithoutFormatParameters_NoDiagnostic() + { + const string code = """ + using System; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + Assert.IsTrue(true); + Assert.IsTrue(true, "Simple message"); + Assert.AreEqual(1, 2); + Assert.AreEqual(1, 2, "Simple message"); + Assert.Throws(() => { }); + Assert.Throws(() => { }, "message"); + } + } + """; + + await VerifyCS.VerifyAnalyzerAsync(code); + } + + [TestMethod] + public async Task WhenAssertIsTrueWithFormatParameters_Diagnostic() + { + const string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + [|Assert.IsTrue(true, "Value: {0}", 42)|]; + } + } + """; + + await VerifyCS.VerifyAnalyzerAsync(code); + } + + [TestMethod] + public async Task WhenAssertIsFalseWithFormatParameters_Diagnostic() + { + const string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + [|Assert.IsFalse(false, "Value: {0}", 42)|]; + } + } + """; + + await VerifyCS.VerifyAnalyzerAsync(code); + } + + [TestMethod] + public async Task WhenAssertAreEqualWithFormatParameters_Diagnostic() + { + const string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + [|Assert.AreEqual(1, 2, "Expected {0} but got {1}", 1, 2)|]; + } + } + """; + + await VerifyCS.VerifyAnalyzerAsync(code); + } + + [TestMethod] + public async Task WhenCollectionAssertWithFormatParameters_Diagnostic() + { + const string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + using System.Collections.Generic; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + var list1 = new List { 1, 2, 3 }; + var list2 = new List { 1, 2, 3 }; + [|CollectionAssert.AreEqual(list1, list2, "Collections differ: {0}", "details")|]; + } + } + """; + + await VerifyCS.VerifyAnalyzerAsync(code); + } + + [TestMethod] + public async Task WhenStringAssertWithFormatParameters_Diagnostic() + { + const string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + [|StringAssert.Contains("hello", "world", "String '{0}' not found in '{1}'", "hello", "world")|]; + } + } + """; + + await VerifyCS.VerifyAnalyzerAsync(code); + } + + [TestMethod] + public async Task WhenAssertWithFormatParameters_FixWithStringFormat() + { + const string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + [|Assert.IsTrue(true, "Value: {0}", 42)|]; + } + } + """; + + const string fixedCode = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + Assert.IsTrue(true, string.Format("Value: {0}", 42)); + } + } + """; + + await new VerifyCS.Test + { + CodeActionIndex = 0, // Use first code fix (string.Format) + TestCode = code, + FixedCode = fixedCode, + }.RunAsync(); + } + + [TestMethod] + public async Task WhenAssertWithFormatParameters_FixWithInterpolatedString() + { + const string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + [|Assert.IsTrue(true, "Value: {0}", 42)|]; + [|Assert.IsTrue(true, "Value: {0} {2} {1} {3}", 42, 44, 43, true ? "True" : "False")|]; + } + } + """; + + const string fixedCode = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + Assert.IsTrue(true, $"Value: {42}"); + Assert.IsTrue(true, $"Value: {42} {43} {44} {(true ? "True" : "False")}"); + } + } + """; + + await new VerifyCS.Test + { + CodeActionIndex = 1, // Use second code fix (interpolated string) + TestCode = code, + FixedCode = fixedCode, + }.RunAsync(); + } + + [TestMethod] + public async Task WhenAssertWithMultipleFormatParameters_FixWithStringFormat() + { + const string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + [|Assert.AreEqual(1, 2, "Expected {0} but got {1}", 1, 2)|]; + } + } + """; + + const string fixedCode = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + Assert.AreEqual(1, 2, string.Format("Expected {0} but got {1}", 1, 2)); + } + } + """; + + await new VerifyCS.Test + { + CodeActionIndex = 0, // Use first code fix (string.Format) + TestCode = code, + FixedCode = fixedCode, + }.RunAsync(); + } + + [TestMethod] + public async Task WhenAssertWithArrayFormatParameters_FixWithStringFormat() + { + const string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + [|Assert.AreEqual(1, 2, "Expected {0} but got {1}", new object[] { 1, 2 })|]; + } + } + """; + + const string fixedCode = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + Assert.AreEqual(1, 2, string.Format("Expected {0} but got {1}", new object[] { 1, 2 })); + } + } + """; + + await new VerifyCS.Test + { + CodeActionIndex = 0, // Use first code fix (string.Format) + TestCode = code, + FixedCode = fixedCode, + }.RunAsync(); + } + + [TestMethod] + public async Task WhenAssertWithMultipleFormatParameters_FixWithInterpolatedString() + { + const string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + [|Assert.AreEqual(1, 2, "Expected {0} but got {1}", 1, 2)|]; + } + } + """; + + const string fixedCode = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + Assert.AreEqual(1, 2, $"Expected {1} but got {2}"); + } + } + """; + + await new VerifyCS.Test + { + CodeActionIndex = 1, // Use second code fix (interpolated string) + TestCode = code, + FixedCode = fixedCode, + }.RunAsync(); + } + + [TestMethod] + public async Task WhenStringAssertWithFormatParameters_FixWithStringFormat() + { + const string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + [|StringAssert.Contains("hello", "world", "String '{0}' not found", "hello")|]; + } + } + """; + + const string fixedCode = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + StringAssert.Contains("hello", "world", string.Format("String '{0}' not found", "hello")); + } + } + """; + + await new VerifyCS.Test + { + CodeActionIndex = 0, // Use first code fix (string.Format) + TestCode = code, + FixedCode = fixedCode, + }.RunAsync(); + } + + [TestMethod] + public async Task WhenNonStringLiteralFormatString_OnlyStringFormatFix() + { + const string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + string format = "Value: {0}"; + [|Assert.IsTrue(true, format, 42)|]; + } + } + """; + + const string fixedCode = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + string format = "Value: {0}"; + Assert.IsTrue(true, string.Format(format, 42)); + } + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, fixedCode); + } +} From 0956f7bd3e0fdf2aa34dd392bdefe1dd7619603a Mon Sep 17 00:00:00 2001 From: Copilot <198982749+Copilot@users.noreply.github.com> Date: Mon, 25 Aug 2025 12:44:00 +0000 Subject: [PATCH 430/541] Obsolete TestContext.CancellationTokenSource and expose TestContext.CancellationToken (#6429) Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: Youssef1313 <31348972+Youssef1313@users.noreply.github.com> Co-authored-by: Youssef Victor --- .../CodeFixResources.resx | 5 +- .../FlowTestContextCancellationTokenFixer.cs | 9 +- .../UseCancellationTokenPropertyFixer.cs | 71 ++++++++ .../xlf/CodeFixResources.cs.xlf | 9 +- .../xlf/CodeFixResources.de.xlf | 9 +- .../xlf/CodeFixResources.es.xlf | 9 +- .../xlf/CodeFixResources.fr.xlf | 9 +- .../xlf/CodeFixResources.it.xlf | 9 +- .../xlf/CodeFixResources.ja.xlf | 9 +- .../xlf/CodeFixResources.ko.xlf | 9 +- .../xlf/CodeFixResources.pl.xlf | 9 +- .../xlf/CodeFixResources.pt-BR.xlf | 9 +- .../xlf/CodeFixResources.ru.xlf | 9 +- .../xlf/CodeFixResources.tr.xlf | 9 +- .../xlf/CodeFixResources.zh-Hans.xlf | 9 +- .../xlf/CodeFixResources.zh-Hant.xlf | 9 +- .../AnalyzerReleases.Unshipped.md | 1 + .../MSTest.Analyzers/Helpers/DiagnosticIds.cs | 1 + .../Helpers/WellKnownTypeNames.cs | 1 + src/Analyzers/MSTest.Analyzers/Resources.resx | 13 +- .../UseCancellationTokenPropertyAnalyzer.cs | 63 +++++++ .../MSTest.Analyzers/xlf/Resources.cs.xlf | 23 ++- .../MSTest.Analyzers/xlf/Resources.de.xlf | 23 ++- .../MSTest.Analyzers/xlf/Resources.es.xlf | 23 ++- .../MSTest.Analyzers/xlf/Resources.fr.xlf | 23 ++- .../MSTest.Analyzers/xlf/Resources.it.xlf | 23 ++- .../MSTest.Analyzers/xlf/Resources.ja.xlf | 23 ++- .../MSTest.Analyzers/xlf/Resources.ko.xlf | 23 ++- .../MSTest.Analyzers/xlf/Resources.pl.xlf | 23 ++- .../MSTest.Analyzers/xlf/Resources.pt-BR.xlf | 23 ++- .../MSTest.Analyzers/xlf/Resources.ru.xlf | 23 ++- .../MSTest.Analyzers/xlf/Resources.tr.xlf | 23 ++- .../xlf/Resources.zh-Hans.xlf | 23 ++- .../xlf/Resources.zh-Hant.xlf | 23 ++- .../PublicAPI/PublicAPI.Unshipped.txt | 1 + .../TestFramework.Extensions/TestContext.cs | 8 + ...stContextCancellationTokenAnalyzerTests.cs | 48 ++--- ...eCancellationTokenPropertyAnalyzerTests.cs | 165 ++++++++++++++++++ 38 files changed, 691 insertions(+), 111 deletions(-) create mode 100644 src/Analyzers/MSTest.Analyzers.CodeFixes/UseCancellationTokenPropertyFixer.cs create mode 100644 src/Analyzers/MSTest.Analyzers/UseCancellationTokenPropertyAnalyzer.cs create mode 100644 test/UnitTests/MSTest.Analyzers.UnitTests/UseCancellationTokenPropertyAnalyzerTests.cs diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/CodeFixResources.resx b/src/Analyzers/MSTest.Analyzers.CodeFixes/CodeFixResources.resx index 587889be53..b88c2f5b10 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/CodeFixResources.resx +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/CodeFixResources.resx @@ -190,11 +190,14 @@ Use 'Assert.{0}' instead of 'StringAssert' - Pass 'TestContext.CancellationTokenSource.Token' argument to method call + Pass 'TestContext.CancellationToken' argument to method call Remove 'DynamicDataSourceType' parameter to use default 'AutoDetect' + + Use 'TestContext.CancellationToken' instead + Use 'string.Format' instead of format parameters diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/FlowTestContextCancellationTokenFixer.cs b/src/Analyzers/MSTest.Analyzers.CodeFixes/FlowTestContextCancellationTokenFixer.cs index 83ec8e124d..87f67ebc1b 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/FlowTestContextCancellationTokenFixer.cs +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/FlowTestContextCancellationTokenFixer.cs @@ -130,14 +130,11 @@ internal static void AddCancellationTokenArgument( // Find the containing method to determine the context MethodDeclarationSyntax? containingMethod = invocationExpression.FirstAncestorOrSelf(); - // Create the TestContext.CancellationTokenSource.Token expression + // Create the TestContext.CancellationToken expression MemberAccessExpressionSyntax testContextExpression = SyntaxFactory.MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, - SyntaxFactory.MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - SyntaxFactory.IdentifierName(testContextMemberName), - SyntaxFactory.IdentifierName("CancellationTokenSource")), - SyntaxFactory.IdentifierName("Token")); + SyntaxFactory.IdentifierName(testContextMemberName), + SyntaxFactory.IdentifierName("CancellationToken")); editor.ReplaceNode(invocationExpression, (node, _) => { diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/UseCancellationTokenPropertyFixer.cs b/src/Analyzers/MSTest.Analyzers.CodeFixes/UseCancellationTokenPropertyFixer.cs new file mode 100644 index 0000000000..f1f4238461 --- /dev/null +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/UseCancellationTokenPropertyFixer.cs @@ -0,0 +1,71 @@ +// 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.Immutable; +using System.Composition; + +using Analyzer.Utilities; + +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CodeActions; +using Microsoft.CodeAnalysis.CodeFixes; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +using MSTest.Analyzers.Helpers; + +namespace MSTest.Analyzers; + +/// +/// Code fixer for . +/// +[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(UseCancellationTokenPropertyFixer))] +[Shared] +public sealed class UseCancellationTokenPropertyFixer : CodeFixProvider +{ + /// + public sealed override ImmutableArray FixableDiagnosticIds { get; } + = ImmutableArray.Create(DiagnosticIds.UseCancellationTokenPropertyRuleId); + + /// + public override FixAllProvider? GetFixAllProvider() + => WellKnownFixAllProviders.BatchFixer; + + /// + public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) + { + SyntaxNode root = await context.Document.GetRequiredSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); + Diagnostic diagnostic = context.Diagnostics[0]; + + // The node here is a the node accessing CancellationTokenSource property on testContext. + SyntaxNode node = root.FindNode(diagnostic.Location.SourceSpan, getInnermostNodeForTie: true); + if (node is not MemberAccessExpressionSyntax memberAccessExpression) + { + return; + } + + // We are looking for testContext.CancellationTokenSource.Token. + // We already have testContext.CancellationTokenSource, so we get the parent, and check if it's accessing 'Token'. + if (memberAccessExpression.Parent is not MemberAccessExpressionSyntax parentMemberAccess || + parentMemberAccess.Name is not IdentifierNameSyntax { Identifier.ValueText: "Token" }) + { + return; + } + + context.RegisterCodeFix( + CodeAction.Create( + title: CodeFixResources.UseCancellationTokenPropertyFix, + createChangedDocument: c => + { + // Replace testContext.CancellationTokenSource.Token with testContext.CancellationToken + MemberAccessExpressionSyntax newExpression = SyntaxFactory.MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + memberAccessExpression.Expression, // testContext part + SyntaxFactory.IdentifierName("CancellationToken")); + + return Task.FromResult(context.Document.WithSyntaxRoot(root.ReplaceNode(parentMemberAccess, newExpression))); + }, + equivalenceKey: nameof(UseCancellationTokenPropertyFixer)), + diagnostic); + } +} diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.cs.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.cs.xlf index 3eb36cbe9c..fac59d57ed 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.cs.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.cs.xlf @@ -58,8 +58,8 @@ - Pass 'TestContext.CancellationTokenSource.Token' argument to method call - Předejte argument TestContext.CancellationTokenSource.Token volání metody. + Pass 'TestContext.CancellationToken' argument to method call + Předejte argument TestContext.CancellationTokenSource.Token volání metody. @@ -127,6 +127,11 @@ Přidat [TestMethod] + + Use 'TestContext.CancellationToken' instead + Use 'TestContext.CancellationToken' instead + + Use 'CooperativeCancellation = true' Použijte „CooperativeCancellation = true“ diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.de.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.de.xlf index d4b5ed8ef8..83c2944f2e 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.de.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.de.xlf @@ -58,8 +58,8 @@ - Pass 'TestContext.CancellationTokenSource.Token' argument to method call - Argument „TestContext.CancellationTokenSource.Token“ an den Methodenaufruf übergeben + Pass 'TestContext.CancellationToken' argument to method call + Argument „TestContext.CancellationTokenSource.Token“ an den Methodenaufruf übergeben @@ -127,6 +127,11 @@ „[TestMethod]“ hinzufügen + + Use 'TestContext.CancellationToken' instead + Use 'TestContext.CancellationToken' instead + + Use 'CooperativeCancellation = true' Verwenden Sie „CooperativeCancellation = true“. diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.es.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.es.xlf index 0572f07414..b71c43e4c4 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.es.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.es.xlf @@ -58,8 +58,8 @@ - Pass 'TestContext.CancellationTokenSource.Token' argument to method call - Pasa el argumento 'TestContext.CancellationTokenSource.Token' a la llamada de método + Pass 'TestContext.CancellationToken' argument to method call + Pasa el argumento 'TestContext.CancellationTokenSource.Token' a la llamada de método @@ -127,6 +127,11 @@ Agregar '[TestMethod]' + + Use 'TestContext.CancellationToken' instead + Use 'TestContext.CancellationToken' instead + + Use 'CooperativeCancellation = true' Usa "CooperativeCancellation = true" diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.fr.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.fr.xlf index 5b52cbca94..3fb1a5c955 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.fr.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.fr.xlf @@ -58,8 +58,8 @@ - Pass 'TestContext.CancellationTokenSource.Token' argument to method call - Passer l’argument « TestContext.CancellationTokenSource.Token » à l’appel de méthode + Pass 'TestContext.CancellationToken' argument to method call + Passer l’argument « TestContext.CancellationTokenSource.Token » à l’appel de méthode @@ -127,6 +127,11 @@ Ajouter « [TestMethod] » + + Use 'TestContext.CancellationToken' instead + Use 'TestContext.CancellationToken' instead + + Use 'CooperativeCancellation = true' Utilisez 'CooperativeCancellation = true' diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.it.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.it.xlf index c1bd9ff27d..596e081d38 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.it.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.it.xlf @@ -58,8 +58,8 @@ - Pass 'TestContext.CancellationTokenSource.Token' argument to method call - Passare l'argomento 'TestContext.CancellationTokenSource.Token' alla chiamata al metodo + Pass 'TestContext.CancellationToken' argument to method call + Passare l'argomento 'TestContext.CancellationTokenSource.Token' alla chiamata al metodo @@ -127,6 +127,11 @@ Aggiungi '[TestMethod]' + + Use 'TestContext.CancellationToken' instead + Use 'TestContext.CancellationToken' instead + + Use 'CooperativeCancellation = true' Usa "CooperativeCancellation = true" diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ja.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ja.xlf index 14a21f07af..3fcfdc9860 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ja.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ja.xlf @@ -58,8 +58,8 @@ - Pass 'TestContext.CancellationTokenSource.Token' argument to method call - 'TestContext.CancellationTokenSource.Token' 引数をメソッド呼び出しに渡す + Pass 'TestContext.CancellationToken' argument to method call + 'TestContext.CancellationTokenSource.Token' 引数をメソッド呼び出しに渡す @@ -127,6 +127,11 @@ '[TestMethod]' の追加 + + Use 'TestContext.CancellationToken' instead + Use 'TestContext.CancellationToken' instead + + Use 'CooperativeCancellation = true' 'CooperativeCancellation = true' を使用する diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ko.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ko.xlf index 9942b48d93..959bb20f6f 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ko.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ko.xlf @@ -58,8 +58,8 @@ - Pass 'TestContext.CancellationTokenSource.Token' argument to method call - 메서드 호출에 'TestContext.CancellationTokenSource.Token' 인수 전달 + Pass 'TestContext.CancellationToken' argument to method call + 메서드 호출에 'TestContext.CancellationTokenSource.Token' 인수 전달 @@ -127,6 +127,11 @@ '[TestMethod]' 추가 + + Use 'TestContext.CancellationToken' instead + Use 'TestContext.CancellationToken' instead + + Use 'CooperativeCancellation = true' 'CooperativeCancellation = true'를 사용하세요. diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pl.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pl.xlf index dfcba58a37..1e42db617b 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pl.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pl.xlf @@ -58,8 +58,8 @@ - Pass 'TestContext.CancellationTokenSource.Token' argument to method call - Przekaż argument „TestContext.CancellationTokenSource.Token” do wywołania metody + Pass 'TestContext.CancellationToken' argument to method call + Przekaż argument „TestContext.CancellationTokenSource.Token” do wywołania metody @@ -127,6 +127,11 @@ Dodaj „[TestMethod]” + + Use 'TestContext.CancellationToken' instead + Use 'TestContext.CancellationToken' instead + + Use 'CooperativeCancellation = true' Użyj opcji „CooperativeCancellation = true” diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pt-BR.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pt-BR.xlf index 929a2064f7..2a77ade652 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pt-BR.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pt-BR.xlf @@ -58,8 +58,8 @@ - Pass 'TestContext.CancellationTokenSource.Token' argument to method call - Passe o argumento 'TestContext.CancellationTokenSource.Token' para a chamada do método + Pass 'TestContext.CancellationToken' argument to method call + Passe o argumento 'TestContext.CancellationTokenSource.Token' para a chamada do método @@ -127,6 +127,11 @@ Adicionar ''[TestMethod]" + + Use 'TestContext.CancellationToken' instead + Use 'TestContext.CancellationToken' instead + + Use 'CooperativeCancellation = true' Usar “CooperativoCancellation = true” diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ru.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ru.xlf index 37375a63ea..cc40a84da6 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ru.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ru.xlf @@ -58,8 +58,8 @@ - Pass 'TestContext.CancellationTokenSource.Token' argument to method call - Передайте аргумент "TestContext.CancellationTokenSource.Token" вызов метода + Pass 'TestContext.CancellationToken' argument to method call + Передайте аргумент "TestContext.CancellationTokenSource.Token" вызов метода @@ -127,6 +127,11 @@ Добавить "[TestMethod]" + + Use 'TestContext.CancellationToken' instead + Use 'TestContext.CancellationToken' instead + + Use 'CooperativeCancellation = true' Использовать "CooperativeCancellation = true" diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.tr.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.tr.xlf index 2567a91287..bbbcf90ca1 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.tr.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.tr.xlf @@ -58,8 +58,8 @@ - Pass 'TestContext.CancellationTokenSource.Token' argument to method call - ‘TestContext.CancellationTokenSource.Token’ bağımsız değişkeni metot çağrısına geçirin + Pass 'TestContext.CancellationToken' argument to method call + ‘TestContext.CancellationTokenSource.Token’ bağımsız değişkeni metot çağrısına geçirin @@ -127,6 +127,11 @@ '[TestMethod]' ekle + + Use 'TestContext.CancellationToken' instead + Use 'TestContext.CancellationToken' instead + + Use 'CooperativeCancellation = true' 'CooperativeCancellation = true' kullanın diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hans.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hans.xlf index c1d62914a5..f5f0e12a0d 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hans.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hans.xlf @@ -58,8 +58,8 @@ - Pass 'TestContext.CancellationTokenSource.Token' argument to method call - 将 'TestContext.CancellationTokenSource.Token' 参数传递给方法调用 + Pass 'TestContext.CancellationToken' argument to method call + 将 'TestContext.CancellationTokenSource.Token' 参数传递给方法调用 @@ -127,6 +127,11 @@ 添加“[TestMethod]” + + Use 'TestContext.CancellationToken' instead + Use 'TestContext.CancellationToken' instead + + Use 'CooperativeCancellation = true' 使用 'CooperativeCancellation = true' diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hant.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hant.xlf index 08b0b1a7a3..1854dea724 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hant.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hant.xlf @@ -58,8 +58,8 @@ - Pass 'TestContext.CancellationTokenSource.Token' argument to method call - 將 'TestContext.CancellationTokenSource.Token' 引數傳遞給方法呼叫 + Pass 'TestContext.CancellationToken' argument to method call + 將 'TestContext.CancellationTokenSource.Token' 引數傳遞給方法呼叫 @@ -127,6 +127,11 @@ 新增 '[TestMethod]' + + Use 'TestContext.CancellationToken' instead + Use 'TestContext.CancellationToken' instead + + Use 'CooperativeCancellation = true' 使用 'CooperativeCancellation = true' diff --git a/src/Analyzers/MSTest.Analyzers/AnalyzerReleases.Unshipped.md b/src/Analyzers/MSTest.Analyzers/AnalyzerReleases.Unshipped.md index 6d2b4723c8..bf640848e6 100644 --- a/src/Analyzers/MSTest.Analyzers/AnalyzerReleases.Unshipped.md +++ b/src/Analyzers/MSTest.Analyzers/AnalyzerReleases.Unshipped.md @@ -8,3 +8,4 @@ Rule ID | Category | Severity | Notes MSTEST0051 | Usage | Info | AssertThrowsShouldContainSingleStatementAnalyzer, [Documentation](https://learn.microsoft.com/dotnet/core/testing/mstest-analyzers/mstest0051) MSTEST0052 | Usage | Warning | PreferDynamicDataSourceTypeAutoDetectAnalyzer, [Documentation](https://learn.microsoft.com/dotnet/core/testing/mstest-analyzers/mstest0052) MSTEST0053 | Usage | Warning | AvoidAssertFormatParametersAnalyzer, [Documentation](https://learn.microsoft.com/dotnet/core/testing/mstest-analyzers/mstest0053) +MSTEST0054 | Usage | Info | UseCancellationTokenPropertyAnalyzer, [Documentation](https://learn.microsoft.com/dotnet/core/testing/mstest-analyzers/mstest0054) diff --git a/src/Analyzers/MSTest.Analyzers/Helpers/DiagnosticIds.cs b/src/Analyzers/MSTest.Analyzers/Helpers/DiagnosticIds.cs index 4d02b8b161..e625e4ad22 100644 --- a/src/Analyzers/MSTest.Analyzers/Helpers/DiagnosticIds.cs +++ b/src/Analyzers/MSTest.Analyzers/Helpers/DiagnosticIds.cs @@ -58,4 +58,5 @@ internal static class DiagnosticIds public const string AssertThrowsShouldContainSingleStatementRuleId = "MSTEST0051"; public const string AvoidExplicitDynamicDataSourceTypeRuleId = "MSTEST0052"; public const string AvoidAssertFormatParametersRuleId = "MSTEST0053"; + public const string UseCancellationTokenPropertyRuleId = "MSTEST0054"; } diff --git a/src/Analyzers/MSTest.Analyzers/Helpers/WellKnownTypeNames.cs b/src/Analyzers/MSTest.Analyzers/Helpers/WellKnownTypeNames.cs index 8481ca81e1..0de14b1386 100644 --- a/src/Analyzers/MSTest.Analyzers/Helpers/WellKnownTypeNames.cs +++ b/src/Analyzers/MSTest.Analyzers/Helpers/WellKnownTypeNames.cs @@ -53,6 +53,7 @@ internal static class WellKnownTypeNames public const string SystemIDisposable = "System.IDisposable"; public const string SystemReflectionMethodInfo = "System.Reflection.MethodInfo"; public const string SystemThreadingCancellationToken = "System.Threading.CancellationToken"; + public const string SystemThreadingCancellationTokenSource = "System.Threading.CancellationTokenSource"; public const string SystemThreadingTasksTask = "System.Threading.Tasks.Task"; public const string SystemThreadingTasksTask1 = "System.Threading.Tasks.Task`1"; public const string SystemThreadingTasksValueTask = "System.Threading.Tasks.ValueTask"; diff --git a/src/Analyzers/MSTest.Analyzers/Resources.resx b/src/Analyzers/MSTest.Analyzers/Resources.resx index 982a951879..946106e7c3 100644 --- a/src/Analyzers/MSTest.Analyzers/Resources.resx +++ b/src/Analyzers/MSTest.Analyzers/Resources.resx @@ -634,10 +634,10 @@ The type declaring these methods should also respect the following rules: Flow TestContext.CancellationToken to async operations - Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationTokenSource.Token' + Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationToken' - When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationTokenSource.Token to enable cooperative cancellation and respect test timeouts. + When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationToken to enable cooperative cancellation and respect test timeouts. Assert.Throws should contain only a single statement/expression @@ -678,6 +678,15 @@ The type declaring these methods should also respect the following rules: Remove the 'DynamicDataSourceType' argument to use the default auto detect behavior + + Use TestContext.CancellationToken instead of TestContext.CancellationTokenSource.Token + + + Use 'TestContext.CancellationToken' instead of 'TestContext.CancellationTokenSource.Token' + + + TestContext.CancellationToken provides a more direct way to access the cancellation token compared to TestContext.CancellationTokenSource.Token. + Avoid using Assert methods with format parameters diff --git a/src/Analyzers/MSTest.Analyzers/UseCancellationTokenPropertyAnalyzer.cs b/src/Analyzers/MSTest.Analyzers/UseCancellationTokenPropertyAnalyzer.cs new file mode 100644 index 0000000000..5e58cae96b --- /dev/null +++ b/src/Analyzers/MSTest.Analyzers/UseCancellationTokenPropertyAnalyzer.cs @@ -0,0 +1,63 @@ +// 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.Immutable; + +using Analyzer.Utilities.Extensions; + +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Diagnostics; +using Microsoft.CodeAnalysis.Operations; + +using MSTest.Analyzers.Helpers; + +namespace MSTest.Analyzers; + +/// +/// MSTEST0054: . +/// +[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] +public sealed class UseCancellationTokenPropertyAnalyzer : DiagnosticAnalyzer +{ + private static readonly LocalizableResourceString Title = new(nameof(Resources.UseCancellationTokenPropertyTitle), Resources.ResourceManager, typeof(Resources)); + private static readonly LocalizableResourceString Description = new(nameof(Resources.UseCancellationTokenPropertyDescription), Resources.ResourceManager, typeof(Resources)); + private static readonly LocalizableResourceString MessageFormat = new(nameof(Resources.UseCancellationTokenPropertyMessageFormat), Resources.ResourceManager, typeof(Resources)); + + internal static readonly DiagnosticDescriptor UseCancellationTokenPropertyRule = DiagnosticDescriptorHelper.Create( + DiagnosticIds.UseCancellationTokenPropertyRuleId, + Title, + MessageFormat, + Description, + Category.Usage, + DiagnosticSeverity.Info, + isEnabledByDefault: true); + + /// + public override ImmutableArray SupportedDiagnostics { get; } + = ImmutableArray.Create(UseCancellationTokenPropertyRule); + + /// + public override void Initialize(AnalysisContext context) + { + context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); + context.EnableConcurrentExecution(); + + context.RegisterCompilationStartAction(context => + { + if (context.Compilation.TryGetOrCreateTypeByMetadataName(WellKnownTypeNames.MicrosoftVisualStudioTestToolsUnitTestingTestContext, out INamedTypeSymbol? testContextSymbol) && + testContextSymbol.GetMembers("CancellationTokenSource") is [IPropertySymbol cancellationTokenSourcePropertySymbol]) + { + context.RegisterOperationAction(context => AnalyzePropertyReference(context, cancellationTokenSourcePropertySymbol), OperationKind.PropertyReference); + } + }); + } + + private static void AnalyzePropertyReference(OperationAnalysisContext context, IPropertySymbol cancellationTokenSourcePropertySymbol) + { + var propertyReferenceOperation = (IPropertyReferenceOperation)context.Operation; + if (propertyReferenceOperation.Property.Equals(cancellationTokenSourcePropertySymbol, SymbolEqualityComparer.Default)) + { + context.ReportDiagnostic(propertyReferenceOperation.Syntax.CreateDiagnostic(UseCancellationTokenPropertyRule)); + } + } +} diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf index 0b416881be..72821bf0ff 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf @@ -463,13 +463,13 @@ Typ deklarující tyto metody by měl také respektovat následující pravidla: - When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationTokenSource.Token to enable cooperative cancellation and respect test timeouts. - Při volání asynchronních metod, které mají přetížení akceptující parametr CancellationToken, upřednostňujte použití přetížení s TestContext.CancellationTokenSource.Token, aby se umožnilo kooperativní rušení a dodržování časových limitů testů. + When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationToken to enable cooperative cancellation and respect test timeouts. + Při volání asynchronních metod, které mají přetížení akceptující parametr CancellationToken, upřednostňujte použití přetížení s TestContext.CancellationTokenSource.Token, aby se umožnilo kooperativní rušení a dodržování časových limitů testů. - Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationTokenSource.Token' - Zvažte použití přetížení, které přijímá CancellationToken a předejte TestContext.CancellationTokenSource.Token. + Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationToken' + Zvažte použití přetížení, které přijímá CancellationToken a předejte TestContext.CancellationTokenSource.Token. @@ -652,6 +652,21 @@ Typ deklarující tyto metody by měl také respektovat následující pravidla: Signatura {0} metody Test je neplatná. + + TestContext.CancellationToken provides a more direct way to access the cancellation token compared to TestContext.CancellationTokenSource.Token. + TestContext.CancellationToken provides a more direct way to access the cancellation token compared to TestContext.CancellationTokenSource.Token. + + + + Use 'TestContext.CancellationToken' instead of 'TestContext.CancellationTokenSource.Token' + Use 'TestContext.CancellationToken' instead of 'TestContext.CancellationTokenSource.Token' + + + + Use TestContext.CancellationToken instead of TestContext.CancellationTokenSource.Token + Use TestContext.CancellationToken instead of TestContext.CancellationTokenSource.Token + + Without using 'ClassCleanupBehavior.EndOfClass', the '[ClassCleanup]' will by default be run at the end of the assembly and not at the end of the class. Když nepoužijete ClassCleanupBehavior.EndOfClass, [ClassCleanup] se ve výchozím nastavení spustí na konci sestavení, nikoli na konci třídy. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf index 0548f41ce3..caf33624e8 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf @@ -464,13 +464,13 @@ Der Typ, der diese Methoden deklariert, sollte auch die folgenden Regeln beachte - When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationTokenSource.Token to enable cooperative cancellation and respect test timeouts. - Wenn Sie asynchrone Methoden aufrufen, die über Überladungen verfügen, die einen CancellationToken-Parameter akzeptieren, bevorzugen Sie die Verwendung der Überladung mit TestContext.CancellationTokenSource.Token, um einen kooperativen Abbruch zu ermöglichen und Testtimeouts zu berücksichtigen. + When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationToken to enable cooperative cancellation and respect test timeouts. + Wenn Sie asynchrone Methoden aufrufen, die über Überladungen verfügen, die einen CancellationToken-Parameter akzeptieren, bevorzugen Sie die Verwendung der Überladung mit TestContext.CancellationTokenSource.Token, um einen kooperativen Abbruch zu ermöglichen und Testtimeouts zu berücksichtigen. - Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationTokenSource.Token' - Erwägen Sie die Verwendung der Überladung, die ein CancellationToken akzeptiert, und übergeben Sie „TestContext.CancellationTokenSource.Token“. + Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationToken' + Erwägen Sie die Verwendung der Überladung, die ein CancellationToken akzeptiert, und übergeben Sie „TestContext.CancellationTokenSource.Token“. @@ -653,6 +653,21 @@ Der Typ, der diese Methoden deklariert, sollte auch die folgenden Regeln beachte Signatur der Testmethode "{0}" ist ungültig + + TestContext.CancellationToken provides a more direct way to access the cancellation token compared to TestContext.CancellationTokenSource.Token. + TestContext.CancellationToken provides a more direct way to access the cancellation token compared to TestContext.CancellationTokenSource.Token. + + + + Use 'TestContext.CancellationToken' instead of 'TestContext.CancellationTokenSource.Token' + Use 'TestContext.CancellationToken' instead of 'TestContext.CancellationTokenSource.Token' + + + + Use TestContext.CancellationToken instead of TestContext.CancellationTokenSource.Token + Use TestContext.CancellationToken instead of TestContext.CancellationTokenSource.Token + + Without using 'ClassCleanupBehavior.EndOfClass', the '[ClassCleanup]' will by default be run at the end of the assembly and not at the end of the class. Ohne Verwendung von „ClassCleanupBehavior.EndOfClass“ wird „[ClassCleanup]“ standardmäßig am Ende der Assembly und nicht am Ende der Klasse ausgeführt. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf index 9928e8bbb2..749203e259 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf @@ -463,13 +463,13 @@ El tipo que declara estos métodos también debe respetar las reglas siguientes: - When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationTokenSource.Token to enable cooperative cancellation and respect test timeouts. - Al llamar a métodos asincrónicos que tienen sobrecargas que aceptan un parámetro CancellationToken, es preferible utilizar la sobrecarga con TestContext.CancellationTokenSource.Token para habilitar la cancelación cooperativa y respetar los tiempos de espera de las pruebas. + When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationToken to enable cooperative cancellation and respect test timeouts. + Al llamar a métodos asincrónicos que tienen sobrecargas que aceptan un parámetro CancellationToken, es preferible utilizar la sobrecarga con TestContext.CancellationTokenSource.Token para habilitar la cancelación cooperativa y respetar los tiempos de espera de las pruebas. - Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationTokenSource.Token' - Considere utilizar la sobrecarga que acepta un CancellationToken y pase 'TestContext.CancellationTokenSource.Token' + Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationToken' + Considere utilizar la sobrecarga que acepta un CancellationToken y pase 'TestContext.CancellationTokenSource.Token' @@ -652,6 +652,21 @@ El tipo que declara estos métodos también debe respetar las reglas siguientes: La firma del método de prueba '{0}' no es válida + + TestContext.CancellationToken provides a more direct way to access the cancellation token compared to TestContext.CancellationTokenSource.Token. + TestContext.CancellationToken provides a more direct way to access the cancellation token compared to TestContext.CancellationTokenSource.Token. + + + + Use 'TestContext.CancellationToken' instead of 'TestContext.CancellationTokenSource.Token' + Use 'TestContext.CancellationToken' instead of 'TestContext.CancellationTokenSource.Token' + + + + Use TestContext.CancellationToken instead of TestContext.CancellationTokenSource.Token + Use TestContext.CancellationToken instead of TestContext.CancellationTokenSource.Token + + Without using 'ClassCleanupBehavior.EndOfClass', the '[ClassCleanup]' will by default be run at the end of the assembly and not at the end of the class. Sin usar 'ClassCleanupBehavior.EndOfClass', el '[ClassCleanup]' se ejecutará de forma predeterminada al final del ensamblado y no al final de la clase. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf index 1ed9dbd910..94aaf50771 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf @@ -463,13 +463,13 @@ Le type doit être une classe - When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationTokenSource.Token to enable cooperative cancellation and respect test timeouts. - Lors de l’appel de méthodes asynchrones qui ont des surcharges acceptant un paramètre CancellationToken, préférez utiliser la surcharge avec TestContext.CancellationTokenSource.Token pour activer l’annulation collaborative et respecter les délais d’expiration des tests. + When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationToken to enable cooperative cancellation and respect test timeouts. + Lors de l’appel de méthodes asynchrones qui ont des surcharges acceptant un paramètre CancellationToken, préférez utiliser la surcharge avec TestContext.CancellationTokenSource.Token pour activer l’annulation collaborative et respecter les délais d’expiration des tests. - Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationTokenSource.Token' - Envisagez d’utiliser la surcharge qui accepte un CancellationToken et passe « TestContext.CancellationTokenSource.Token » + Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationToken' + Envisagez d’utiliser la surcharge qui accepte un CancellationToken et passe « TestContext.CancellationTokenSource.Token » @@ -652,6 +652,21 @@ Le type déclarant ces méthodes doit également respecter les règles suivantes La signature « {0} » de la méthode de test n’est pas valide + + TestContext.CancellationToken provides a more direct way to access the cancellation token compared to TestContext.CancellationTokenSource.Token. + TestContext.CancellationToken provides a more direct way to access the cancellation token compared to TestContext.CancellationTokenSource.Token. + + + + Use 'TestContext.CancellationToken' instead of 'TestContext.CancellationTokenSource.Token' + Use 'TestContext.CancellationToken' instead of 'TestContext.CancellationTokenSource.Token' + + + + Use TestContext.CancellationToken instead of TestContext.CancellationTokenSource.Token + Use TestContext.CancellationToken instead of TestContext.CancellationTokenSource.Token + + Without using 'ClassCleanupBehavior.EndOfClass', the '[ClassCleanup]' will by default be run at the end of the assembly and not at the end of the class. Sans utiliser 'ClassCleanupBehavior.EndOfClass', '[ClassCleanup]' sera exécuté par défaut à la fin de l’assemblée et non à la fin de la classe. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf index 7e2ca6c047..f7f35c846f 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf @@ -463,13 +463,13 @@ Anche il tipo che dichiara questi metodi deve rispettare le regole seguenti: - When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationTokenSource.Token to enable cooperative cancellation and respect test timeouts. - Quando si chiamano metodi asincroni con overload che accettano un parametro CancellationToken, preferire l'uso dell'overload con TestContext.CancellationTokenSource.Token per abilitare l'annullamento cooperativo e rispettare i timeout di test. + When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationToken to enable cooperative cancellation and respect test timeouts. + Quando si chiamano metodi asincroni con overload che accettano un parametro CancellationToken, preferire l'uso dell'overload con TestContext.CancellationTokenSource.Token per abilitare l'annullamento cooperativo e rispettare i timeout di test. - Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationTokenSource.Token' - Valutare la possibilità di usare l'overload che accetta un CancellationToken e a passare 'TestContext.CancellationTokenSource.Token' + Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationToken' + Valutare la possibilità di usare l'overload che accetta un CancellationToken e a passare 'TestContext.CancellationTokenSource.Token' @@ -652,6 +652,21 @@ Anche il tipo che dichiara questi metodi deve rispettare le regole seguenti: La firma del metodo di test '{0}' non è valida + + TestContext.CancellationToken provides a more direct way to access the cancellation token compared to TestContext.CancellationTokenSource.Token. + TestContext.CancellationToken provides a more direct way to access the cancellation token compared to TestContext.CancellationTokenSource.Token. + + + + Use 'TestContext.CancellationToken' instead of 'TestContext.CancellationTokenSource.Token' + Use 'TestContext.CancellationToken' instead of 'TestContext.CancellationTokenSource.Token' + + + + Use TestContext.CancellationToken instead of TestContext.CancellationTokenSource.Token + Use TestContext.CancellationToken instead of TestContext.CancellationTokenSource.Token + + Without using 'ClassCleanupBehavior.EndOfClass', the '[ClassCleanup]' will by default be run at the end of the assembly and not at the end of the class. Se non si usa 'ClassCleanupBehavior.EndOfClass', '[ClassCleanup]' verrà eseguito per impostazione predefinita alla fine dell'assembly e non alla fine della classe. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf index 1adef5422d..46bc1f4999 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf @@ -463,13 +463,13 @@ The type declaring these methods should also respect the following rules: - When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationTokenSource.Token to enable cooperative cancellation and respect test timeouts. - CancellationToken パラメーターを受け入れるオーバーロードを持つ非同期メソッドを呼び出す場合は、TestContext.CancellationTokenSource.Token でオーバーロードを使用して協調的な取り消しを有効にし、テスト タイムアウトを考慮します。 + When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationToken to enable cooperative cancellation and respect test timeouts. + CancellationToken パラメーターを受け入れるオーバーロードを持つ非同期メソッドを呼び出す場合は、TestContext.CancellationTokenSource.Token でオーバーロードを使用して協調的な取り消しを有効にし、テスト タイムアウトを考慮します。 - Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationTokenSource.Token' - CancellationToken を受け取り、'TestContext.CancellationTokenSource.Token' を渡すオーバーロードの使用を検討してください + Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationToken' + CancellationToken を受け取り、'TestContext.CancellationTokenSource.Token' を渡すオーバーロードの使用を検討してください @@ -652,6 +652,21 @@ The type declaring these methods should also respect the following rules: テスト メソッド '{0}' シグネチャが無効です + + TestContext.CancellationToken provides a more direct way to access the cancellation token compared to TestContext.CancellationTokenSource.Token. + TestContext.CancellationToken provides a more direct way to access the cancellation token compared to TestContext.CancellationTokenSource.Token. + + + + Use 'TestContext.CancellationToken' instead of 'TestContext.CancellationTokenSource.Token' + Use 'TestContext.CancellationToken' instead of 'TestContext.CancellationTokenSource.Token' + + + + Use TestContext.CancellationToken instead of TestContext.CancellationTokenSource.Token + Use TestContext.CancellationToken instead of TestContext.CancellationTokenSource.Token + + Without using 'ClassCleanupBehavior.EndOfClass', the '[ClassCleanup]' will by default be run at the end of the assembly and not at the end of the class. 'ClassCleanupBehavior.EndOfClass' を使用しない場合、'[ClassCleanup]' は既定でアセンブリの最後に実行され、クラスの最後には実行されません。 diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf index 91d0e0ebf5..6bbea18a33 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf @@ -463,13 +463,13 @@ The type declaring these methods should also respect the following rules: - When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationTokenSource.Token to enable cooperative cancellation and respect test timeouts. - CancellationToken 매개변수를 허용하는 오버로드가 있는 비동기 메서드를 호출할 때는 협력적 취소를 활성화하고 테스트 시간 제한을 준수하기 위해 TestContext.CancellationTokenSource.Token이 있는 오버로드를 사용하는 것이 좋습니다. + When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationToken to enable cooperative cancellation and respect test timeouts. + CancellationToken 매개변수를 허용하는 오버로드가 있는 비동기 메서드를 호출할 때는 협력적 취소를 활성화하고 테스트 시간 제한을 준수하기 위해 TestContext.CancellationTokenSource.Token이 있는 오버로드를 사용하는 것이 좋습니다. - Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationTokenSource.Token' - CancellationToken을 수락하고 'TestContext.CancellationTokenSource.Token'을 전달하는 오버로드를 사용하는 것이 좋습니다. + Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationToken' + CancellationToken을 수락하고 'TestContext.CancellationTokenSource.Token'을 전달하는 오버로드를 사용하는 것이 좋습니다. @@ -652,6 +652,21 @@ The type declaring these methods should also respect the following rules: 테스트 메서드 '{0}' 시그니처가 잘못되었습니다. + + TestContext.CancellationToken provides a more direct way to access the cancellation token compared to TestContext.CancellationTokenSource.Token. + TestContext.CancellationToken provides a more direct way to access the cancellation token compared to TestContext.CancellationTokenSource.Token. + + + + Use 'TestContext.CancellationToken' instead of 'TestContext.CancellationTokenSource.Token' + Use 'TestContext.CancellationToken' instead of 'TestContext.CancellationTokenSource.Token' + + + + Use TestContext.CancellationToken instead of TestContext.CancellationTokenSource.Token + Use TestContext.CancellationToken instead of TestContext.CancellationTokenSource.Token + + Without using 'ClassCleanupBehavior.EndOfClass', the '[ClassCleanup]' will by default be run at the end of the assembly and not at the end of the class. 'ClassCleanupBehavior.EndOfClass'를 사용하지 않으면 '[ClassCleanup]'은 기본적으로 클래스의 끝이 아니라 어셈블리의 끝에서 실행됩니다. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf index 9c7fba96ee..381af5d610 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf @@ -463,13 +463,13 @@ Typ deklarujący te metody powinien również przestrzegać następujących regu - When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationTokenSource.Token to enable cooperative cancellation and respect test timeouts. - W przypadku wywoływania metod asynchronicznych, które mają przeciążenia akceptujące parametr CancellationToken, preferuj użycie przeciążenia z elementem TestContext.CancellationTokenSource.Token, aby umożliwić współpracujące anulowanie i uwzględnić limity czasu testu. + When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationToken to enable cooperative cancellation and respect test timeouts. + W przypadku wywoływania metod asynchronicznych, które mają przeciążenia akceptujące parametr CancellationToken, preferuj użycie przeciążenia z elementem TestContext.CancellationTokenSource.Token, aby umożliwić współpracujące anulowanie i uwzględnić limity czasu testu. - Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationTokenSource.Token' - Rozważ użycie przeciążenia akceptującego parametr CancellationToken i przekazanie elementu „TestContext.CancellationTokenSource.Token” + Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationToken' + Rozważ użycie przeciążenia akceptującego parametr CancellationToken i przekazanie elementu „TestContext.CancellationTokenSource.Token” @@ -652,6 +652,21 @@ Typ deklarujący te metody powinien również przestrzegać następujących regu Podpis metody testowej „{0}” jest nieprawidłowy + + TestContext.CancellationToken provides a more direct way to access the cancellation token compared to TestContext.CancellationTokenSource.Token. + TestContext.CancellationToken provides a more direct way to access the cancellation token compared to TestContext.CancellationTokenSource.Token. + + + + Use 'TestContext.CancellationToken' instead of 'TestContext.CancellationTokenSource.Token' + Use 'TestContext.CancellationToken' instead of 'TestContext.CancellationTokenSource.Token' + + + + Use TestContext.CancellationToken instead of TestContext.CancellationTokenSource.Token + Use TestContext.CancellationToken instead of TestContext.CancellationTokenSource.Token + + Without using 'ClassCleanupBehavior.EndOfClass', the '[ClassCleanup]' will by default be run at the end of the assembly and not at the end of the class. Bez użycia elementu „ClassCleanupBehavior.EndOfClass” element „[ClassCleanup]” będzie domyślnie uruchamiany na końcu zestawu, a nie na końcu klasy. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf index db4f2926bc..bc41e1133b 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf @@ -463,13 +463,13 @@ O tipo que declara esses métodos também deve respeitar as seguintes regras: - When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationTokenSource.Token to enable cooperative cancellation and respect test timeouts. - Ao chamar métodos assíncronos que tenham sobrecargas que aceitam um parâmetro CancellationToken, prefira usar a sobrecarga com TestContext.CancellationTokenSource.Token para habilitar o cancelamento cooperativo e respeitar os tempos limite do teste. + When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationToken to enable cooperative cancellation and respect test timeouts. + Ao chamar métodos assíncronos que tenham sobrecargas que aceitam um parâmetro CancellationToken, prefira usar a sobrecarga com TestContext.CancellationTokenSource.Token para habilitar o cancelamento cooperativo e respeitar os tempos limite do teste. - Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationTokenSource.Token' - Considere usar a sobrecarga que aceita um CancellationToken e passar "TestContext.CancellationTokenSource.Token" + Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationToken' + Considere usar a sobrecarga que aceita um CancellationToken e passar "TestContext.CancellationTokenSource.Token" @@ -652,6 +652,21 @@ O tipo que declara esses métodos também deve respeitar as seguintes regras: A assinatura "{0}" do método de teste é inválida + + TestContext.CancellationToken provides a more direct way to access the cancellation token compared to TestContext.CancellationTokenSource.Token. + TestContext.CancellationToken provides a more direct way to access the cancellation token compared to TestContext.CancellationTokenSource.Token. + + + + Use 'TestContext.CancellationToken' instead of 'TestContext.CancellationTokenSource.Token' + Use 'TestContext.CancellationToken' instead of 'TestContext.CancellationTokenSource.Token' + + + + Use TestContext.CancellationToken instead of TestContext.CancellationTokenSource.Token + Use TestContext.CancellationToken instead of TestContext.CancellationTokenSource.Token + + Without using 'ClassCleanupBehavior.EndOfClass', the '[ClassCleanup]' will by default be run at the end of the assembly and not at the end of the class. Sem usar o "ClassCleanupBehavior.EndOfClass", o "[ClassCleanup]" será executado, por padrão, no final do assembly e não no final da classe. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf index 7bbe063b93..3771c466dd 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf @@ -469,13 +469,13 @@ The type declaring these methods should also respect the following rules: - When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationTokenSource.Token to enable cooperative cancellation and respect test timeouts. - При вызове асинхронных методов с перегрузками, принимающими параметр CancellationToken, рекомендуется использовать перегрузку с TestContext.CancellationTokenSource.Token, чтобы обеспечить кооперативную отмену и учитывать времена ожидания теста. + When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationToken to enable cooperative cancellation and respect test timeouts. + При вызове асинхронных методов с перегрузками, принимающими параметр CancellationToken, рекомендуется использовать перегрузку с TestContext.CancellationTokenSource.Token, чтобы обеспечить кооперативную отмену и учитывать времена ожидания теста. - Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationTokenSource.Token' - Рассмотрите возможность использования перегрузки, которая принимает CancellationToken, и передавайте "TestContext.CancellationTokenSource.Token" + Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationToken' + Рассмотрите возможность использования перегрузки, которая принимает CancellationToken, и передавайте "TestContext.CancellationTokenSource.Token" @@ -658,6 +658,21 @@ The type declaring these methods should also respect the following rules: Подпись тестового метода "{0}" недействительна + + TestContext.CancellationToken provides a more direct way to access the cancellation token compared to TestContext.CancellationTokenSource.Token. + TestContext.CancellationToken provides a more direct way to access the cancellation token compared to TestContext.CancellationTokenSource.Token. + + + + Use 'TestContext.CancellationToken' instead of 'TestContext.CancellationTokenSource.Token' + Use 'TestContext.CancellationToken' instead of 'TestContext.CancellationTokenSource.Token' + + + + Use TestContext.CancellationToken instead of TestContext.CancellationTokenSource.Token + Use TestContext.CancellationToken instead of TestContext.CancellationTokenSource.Token + + Without using 'ClassCleanupBehavior.EndOfClass', the '[ClassCleanup]' will by default be run at the end of the assembly and not at the end of the class. Без использования "ClassCleanupBehavior.EndOfClass" "[ClassCleanup]" по умолчанию будет выполняться в конце сборки, а не в конце класса. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf index facbce52cc..d55ce3f117 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf @@ -463,13 +463,13 @@ Bu yöntemleri bildiren tipin ayrıca aşağıdaki kurallara uyması gerekir: - When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationTokenSource.Token to enable cooperative cancellation and respect test timeouts. - CancellationToken parametresini kabul eden aşırı yüklemeleri olan asenkron yöntemleri çağırırken, işbirliğine dayalı iptal işlemini etkinleştirmek ve test zaman aşımlarını dikkate almak için TestContext.CancellationTokenSource.Token ile aşırı yüklemeyi kullanmayı tercih edin. + When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationToken to enable cooperative cancellation and respect test timeouts. + CancellationToken parametresini kabul eden aşırı yüklemeleri olan asenkron yöntemleri çağırırken, işbirliğine dayalı iptal işlemini etkinleştirmek ve test zaman aşımlarını dikkate almak için TestContext.CancellationTokenSource.Token ile aşırı yüklemeyi kullanmayı tercih edin. - Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationTokenSource.Token' - CancellationToken'ı kabul eden aşırı yüklemeyi kullanmayı düşünün ve 'TestContext.CancellationTokenSource.Token'i geçirin. + Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationToken' + CancellationToken'ı kabul eden aşırı yüklemeyi kullanmayı düşünün ve 'TestContext.CancellationTokenSource.Token'i geçirin. @@ -652,6 +652,21 @@ Bu metotları bildiren türün ayrıca aşağıdaki kurallara uyması gerekir: '{0}' test yöntemi imzası geçersiz + + TestContext.CancellationToken provides a more direct way to access the cancellation token compared to TestContext.CancellationTokenSource.Token. + TestContext.CancellationToken provides a more direct way to access the cancellation token compared to TestContext.CancellationTokenSource.Token. + + + + Use 'TestContext.CancellationToken' instead of 'TestContext.CancellationTokenSource.Token' + Use 'TestContext.CancellationToken' instead of 'TestContext.CancellationTokenSource.Token' + + + + Use TestContext.CancellationToken instead of TestContext.CancellationTokenSource.Token + Use TestContext.CancellationToken instead of TestContext.CancellationTokenSource.Token + + Without using 'ClassCleanupBehavior.EndOfClass', the '[ClassCleanup]' will by default be run at the end of the assembly and not at the end of the class. 'ClassCleanupBehavior.EndOfClass' kullanılmadığında, '[ClassCleanup]' varsayılan olarak sınıfın sonunda değil derlemenin sonunda çalıştırılır. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf index 05b8942b48..29d6d5b4aa 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf @@ -463,13 +463,13 @@ The type declaring these methods should also respect the following rules: - When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationTokenSource.Token to enable cooperative cancellation and respect test timeouts. - 在调用包含接受 CancellationToken 参数的重载的异步方法时,建议使用 TestContext.CancellationTokenSource.Token 的重载,以启用协作取消并遵守测试超时。 + When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationToken to enable cooperative cancellation and respect test timeouts. + 在调用包含接受 CancellationToken 参数的重载的异步方法时,建议使用 TestContext.CancellationTokenSource.Token 的重载,以启用协作取消并遵守测试超时。 - Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationTokenSource.Token' - 请考虑使用接受 CancellationToken 的重载,并传递 'TestContext.CancellationTokenSource.Token' + Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationToken' + 请考虑使用接受 CancellationToken 的重载,并传递 'TestContext.CancellationTokenSource.Token' @@ -652,6 +652,21 @@ The type declaring these methods should also respect the following rules: 测试方法“{0}”签名无效 + + TestContext.CancellationToken provides a more direct way to access the cancellation token compared to TestContext.CancellationTokenSource.Token. + TestContext.CancellationToken provides a more direct way to access the cancellation token compared to TestContext.CancellationTokenSource.Token. + + + + Use 'TestContext.CancellationToken' instead of 'TestContext.CancellationTokenSource.Token' + Use 'TestContext.CancellationToken' instead of 'TestContext.CancellationTokenSource.Token' + + + + Use TestContext.CancellationToken instead of TestContext.CancellationTokenSource.Token + Use TestContext.CancellationToken instead of TestContext.CancellationTokenSource.Token + + Without using 'ClassCleanupBehavior.EndOfClass', the '[ClassCleanup]' will by default be run at the end of the assembly and not at the end of the class. 如果不使用 "ClassCleanupBehavior.EndOfClass","[ClassCleanup]" 将默认在程序集末尾运行,而不是在类的末尾运行。 diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf index b38bf21dfa..4208bb80c7 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf @@ -463,13 +463,13 @@ The type declaring these methods should also respect the following rules: - When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationTokenSource.Token to enable cooperative cancellation and respect test timeouts. - 在呼叫接受 CancellationToken 參數的多載非同步方法時,建議使用 TestContext.CancellationTokenSource.Token 的多載,以啟用共同取消並遵守測試逾時。 + When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationToken to enable cooperative cancellation and respect test timeouts. + 在呼叫接受 CancellationToken 參數的多載非同步方法時,建議使用 TestContext.CancellationTokenSource.Token 的多載,以啟用共同取消並遵守測試逾時。 - Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationTokenSource.Token' - 請考慮使用接受 CancellationToken 的多載,並傳遞 'TestContext.CancellationTokenSource.Token' + Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationToken' + 請考慮使用接受 CancellationToken 的多載,並傳遞 'TestContext.CancellationTokenSource.Token' @@ -652,6 +652,21 @@ The type declaring these methods should also respect the following rules: 測試方法 '{0}' 簽章無效 + + TestContext.CancellationToken provides a more direct way to access the cancellation token compared to TestContext.CancellationTokenSource.Token. + TestContext.CancellationToken provides a more direct way to access the cancellation token compared to TestContext.CancellationTokenSource.Token. + + + + Use 'TestContext.CancellationToken' instead of 'TestContext.CancellationTokenSource.Token' + Use 'TestContext.CancellationToken' instead of 'TestContext.CancellationTokenSource.Token' + + + + Use TestContext.CancellationToken instead of TestContext.CancellationTokenSource.Token + Use TestContext.CancellationToken instead of TestContext.CancellationTokenSource.Token + + Without using 'ClassCleanupBehavior.EndOfClass', the '[ClassCleanup]' will by default be run at the end of the assembly and not at the end of the class. 如不使用 'ClassCleanupBehavior.EndOfClass',則預設會在組件結尾執行 '[ClassCleanup]',而非在類別的結尾執行。 diff --git a/src/TestFramework/TestFramework.Extensions/PublicAPI/PublicAPI.Unshipped.txt b/src/TestFramework/TestFramework.Extensions/PublicAPI/PublicAPI.Unshipped.txt index 7dc5c58110..7505aa4cf1 100644 --- a/src/TestFramework/TestFramework.Extensions/PublicAPI/PublicAPI.Unshipped.txt +++ b/src/TestFramework/TestFramework.Extensions/PublicAPI/PublicAPI.Unshipped.txt @@ -1 +1,2 @@ #nullable enable +Microsoft.VisualStudio.TestTools.UnitTesting.TestContext.CancellationToken.get -> System.Threading.CancellationToken diff --git a/src/TestFramework/TestFramework.Extensions/TestContext.cs b/src/TestFramework/TestFramework.Extensions/TestContext.cs index ce78b1a0c1..8031c2f87d 100644 --- a/src/TestFramework/TestFramework.Extensions/TestContext.cs +++ b/src/TestFramework/TestFramework.Extensions/TestContext.cs @@ -6,6 +6,8 @@ using System.Data.Common; #endif +using System.ComponentModel; + namespace Microsoft.VisualStudio.TestTools.UnitTesting; /// @@ -49,8 +51,14 @@ public abstract class TestContext /// Gets or sets the cancellation token source. This token source is canceled when test times out. Also when explicitly canceled the test will be aborted. /// // Disposing isn't important per https://github.com/dotnet/runtime/issues/29970#issuecomment-717840778 + [EditorBrowsable(EditorBrowsableState.Never)] public virtual CancellationTokenSource CancellationTokenSource { get; protected internal set; } = new(); + /// + /// Gets the cancellation token. This token is canceled when test times out. Also when explicitly canceled the test will be aborted. + /// + public CancellationToken CancellationToken => CancellationTokenSource.Token; + /// /// Gets or sets the test data for the test method being executed. /// diff --git a/test/UnitTests/MSTest.Analyzers.UnitTests/FlowTestContextCancellationTokenAnalyzerTests.cs b/test/UnitTests/MSTest.Analyzers.UnitTests/FlowTestContextCancellationTokenAnalyzerTests.cs index 9ba0988c3a..311d1d4cff 100644 --- a/test/UnitTests/MSTest.Analyzers.UnitTests/FlowTestContextCancellationTokenAnalyzerTests.cs +++ b/test/UnitTests/MSTest.Analyzers.UnitTests/FlowTestContextCancellationTokenAnalyzerTests.cs @@ -44,7 +44,7 @@ public class MyTestClass [TestMethod] public async Task MyTestMethod() { - await Task.Delay(1000, TestContext.CancellationTokenSource.Token); + await Task.Delay(1000, TestContext.CancellationToken); } } """; @@ -68,7 +68,7 @@ public class MyTestClass [TestMethod] public async Task MyTestMethod() { - await Task.Delay(1000, TestContext.CancellationTokenSource.Token); + await Task.Delay(1000, TestContext.CancellationToken); } } """; @@ -155,7 +155,7 @@ public class MyTestClass [TestInitialize] public async Task TestInit() { - await Task.Delay(1000, TestContext.CancellationTokenSource.Token); + await Task.Delay(1000, TestContext.CancellationToken); } } """; @@ -197,7 +197,7 @@ public class MyTestClass [TestCleanup] public async Task TestCleanup() { - await Task.Delay(1000, TestContext.CancellationTokenSource.Token); + await Task.Delay(1000, TestContext.CancellationToken); } } """; @@ -235,7 +235,7 @@ public class MyTestClass [ClassInitialize] public static async Task ClassInit(TestContext testContext) { - await Task.Delay(1000, testContext.CancellationTokenSource.Token); + await Task.Delay(1000, testContext.CancellationToken); } } """; @@ -273,7 +273,7 @@ public class MyTestClass [ClassCleanup] public static async Task ClassCleanup(TestContext testContext) { - await Task.Delay(1000, testContext.CancellationTokenSource.Token); + await Task.Delay(1000, testContext.CancellationToken); } } """; @@ -312,8 +312,8 @@ public class MyTestClass [ClassCleanup] public static async Task ClassCleanup(TestContext testContext) { - await Task.Delay(1000, testContext.CancellationTokenSource.Token); - await Task.Delay(1000, testContext.CancellationTokenSource.Token); + await Task.Delay(1000, testContext.CancellationToken); + await Task.Delay(1000, testContext.CancellationToken); } } """; @@ -360,7 +360,7 @@ public class MyTestClass [TestMethod] public async Task Test1() { - await Task.Delay(1000, TestContext.CancellationTokenSource.Token); + await Task.Delay(1000, TestContext.CancellationToken); } [TestMethod] @@ -368,8 +368,8 @@ public async Task Test1() [DataRow(1)] public async Task Test2(int _) { - await Task.Delay(1000, TestContext.CancellationTokenSource.Token); - await Task.Delay(1000, TestContext.CancellationTokenSource.Token); + await Task.Delay(1000, TestContext.CancellationToken); + await Task.Delay(1000, TestContext.CancellationToken); } public TestContext TestContext { get; set; } @@ -419,7 +419,7 @@ public MyTestClass(TestContext testContext) [TestMethod] public async Task Test1() { - await Task.Delay(1000, _testContext.CancellationTokenSource.Token); + await Task.Delay(1000, _testContext.CancellationToken); } } """; @@ -459,7 +459,7 @@ public class MyTestClass(TestContext MyTestContext) public async Task Test1() { _ = MyTestContext; - await Task.Delay(1000, MyTestContext.CancellationTokenSource.Token); + await Task.Delay(1000, MyTestContext.CancellationToken); } } """; @@ -529,7 +529,7 @@ public class MyTestClass public async Task MyTestMethod() { using var client = new HttpClient(); - var response = await client.GetAsync("https://example.com", TestContext.CancellationTokenSource.Token); + var response = await client.GetAsync("https://example.com", TestContext.CancellationToken); } } """; @@ -574,14 +574,14 @@ public class MyTestClass [TestMethod] public async Task Test1() { - await Task.Delay(1000, TestContext.CancellationTokenSource.Token); - await Task.Delay(2000, TestContext.CancellationTokenSource.Token); + await Task.Delay(1000, TestContext.CancellationToken); + await Task.Delay(2000, TestContext.CancellationToken); } [TestMethod] public async Task Test2() { - await Task.Delay(3000, TestContext.CancellationTokenSource.Token); + await Task.Delay(3000, TestContext.CancellationToken); } public TestContext TestContext { get; set; } @@ -660,14 +660,14 @@ public partial class MyTestClass [TestMethod] public async Task Test1() { - await Task.Delay(1000, TestContext.CancellationTokenSource.Token); - await Task.Delay(2000, TestContext.CancellationTokenSource.Token); + await Task.Delay(1000, TestContext.CancellationToken); + await Task.Delay(2000, TestContext.CancellationToken); } [TestMethod] public async Task Test2() { - await Task.Delay(3000, TestContext.CancellationTokenSource.Token); + await Task.Delay(3000, TestContext.CancellationToken); } public TestContext TestContext { get; set; } @@ -683,14 +683,14 @@ public partial class MyTestClass [TestMethod] public async Task Test3() { - await Task.Delay(1000, TestContext.CancellationTokenSource.Token); - await Task.Delay(2000, TestContext.CancellationTokenSource.Token); + await Task.Delay(1000, TestContext.CancellationToken); + await Task.Delay(2000, TestContext.CancellationToken); } [TestMethod] public async Task Test4() { - await Task.Delay(3000, TestContext.CancellationTokenSource.Token); + await Task.Delay(3000, TestContext.CancellationToken); } } """, @@ -731,7 +731,7 @@ public class MyTestClass [AssemblyCleanup] public static async Task AssemblyCleanup(TestContext testContext) { - await Task.Delay(1000, testContext.CancellationTokenSource.Token); + await Task.Delay(1000, testContext.CancellationToken); } } """; diff --git a/test/UnitTests/MSTest.Analyzers.UnitTests/UseCancellationTokenPropertyAnalyzerTests.cs b/test/UnitTests/MSTest.Analyzers.UnitTests/UseCancellationTokenPropertyAnalyzerTests.cs new file mode 100644 index 0000000000..476f35c123 --- /dev/null +++ b/test/UnitTests/MSTest.Analyzers.UnitTests/UseCancellationTokenPropertyAnalyzerTests.cs @@ -0,0 +1,165 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using VerifyCS = MSTest.Analyzers.Test.CSharpCodeFixVerifier< + MSTest.Analyzers.UseCancellationTokenPropertyAnalyzer, + MSTest.Analyzers.UseCancellationTokenPropertyFixer>; + +namespace MSTest.Analyzers.Test; + +[TestClass] +public sealed class UseCancellationTokenPropertyAnalyzerTests +{ + [TestMethod] + public async Task WhenUsingCancellationTokenSourceToken_ShouldReportDiagnostic() + { + const string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + using System.Threading; + using System.Threading.Tasks; + + [TestClass] + public class MyTestClass + { + public TestContext TestContext { get; set; } + + [TestMethod] + public async Task MyTest() + { + await SomeAsyncOperation([|TestContext.CancellationTokenSource|].Token); + } + + private static Task SomeAsyncOperation(CancellationToken cancellationToken) + => Task.CompletedTask; + } + """; + + const string fixedCode = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + using System.Threading; + using System.Threading.Tasks; + + [TestClass] + public class MyTestClass + { + public TestContext TestContext { get; set; } + + [TestMethod] + public async Task MyTest() + { + await SomeAsyncOperation(TestContext.CancellationToken); + } + + private static Task SomeAsyncOperation(CancellationToken cancellationToken) + => Task.CompletedTask; + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, fixedCode); + } + + [TestMethod] + public async Task WhenUsingCancellationTokenSourceTokenWithVariable_ShouldReportDiagnostic() + { + const string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + using System.Threading; + using System.Threading.Tasks; + + [TestClass] + public class MyTestClass + { + public TestContext TestContext { get; set; } + + [TestMethod] + public async Task MyTest() + { + var context = TestContext; + await SomeAsyncOperation([|context.CancellationTokenSource|].Token); + } + + private static Task SomeAsyncOperation(CancellationToken cancellationToken) + => Task.CompletedTask; + } + """; + + const string fixedCode = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + using System.Threading; + using System.Threading.Tasks; + + [TestClass] + public class MyTestClass + { + public TestContext TestContext { get; set; } + + [TestMethod] + public async Task MyTest() + { + var context = TestContext; + await SomeAsyncOperation(context.CancellationToken); + } + + private static Task SomeAsyncOperation(CancellationToken cancellationToken) + => Task.CompletedTask; + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, fixedCode); + } + + [TestMethod] + public async Task WhenUsingCancellationToken_ShouldNotReportDiagnostic() + { + const string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + using System.Threading; + using System.Threading.Tasks; + + [TestClass] + public class MyTestClass + { + public TestContext TestContext { get; set; } + + [TestMethod] + public async Task MyTest() + { + await SomeAsyncOperation(TestContext.CancellationToken); + } + + private static Task SomeAsyncOperation(CancellationToken cancellationToken) + => Task.CompletedTask; + } + """; + + await VerifyCS.VerifyAnalyzerAsync(code); + } + + [TestMethod] + public async Task WhenUsingDifferentTokenSource_ShouldNotReportDiagnostic() + { + const string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + using System.Threading; + using System.Threading.Tasks; + + [TestClass] + public class MyTestClass + { + private readonly CancellationTokenSource _cts = new(); + public TestContext TestContext { get; set; } + + [TestMethod] + public async Task MyTest() + { + await SomeAsyncOperation(_cts.Token); + } + + private static Task SomeAsyncOperation(CancellationToken cancellationToken) + => Task.CompletedTask; + } + """; + + await VerifyCS.VerifyAnalyzerAsync(code); + } +} From a4db51e179ac2caab28782b53c4e3d3e192fc5b6 Mon Sep 17 00:00:00 2001 From: dotnet bot Date: Mon, 25 Aug 2025 05:52:20 -0700 Subject: [PATCH 431/541] Localized file check-in by OneLocBuild Task: Build definition ID 1218: Build ID 2779664 --- .../MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.cs.xlf | 2 +- .../MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.de.xlf | 2 +- .../MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.es.xlf | 2 +- .../MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.fr.xlf | 2 +- .../MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.it.xlf | 2 +- .../MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ja.xlf | 2 +- .../MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ko.xlf | 2 +- .../MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pl.xlf | 2 +- .../MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pt-BR.xlf | 2 +- .../MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ru.xlf | 2 +- .../MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.tr.xlf | 2 +- .../xlf/CodeFixResources.zh-Hans.xlf | 2 +- .../xlf/CodeFixResources.zh-Hant.xlf | 2 +- src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf | 4 ++-- src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf | 4 ++-- src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf | 4 ++-- src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf | 4 ++-- src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf | 4 ++-- src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf | 4 ++-- src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf | 4 ++-- src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf | 4 ++-- src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf | 4 ++-- src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf | 4 ++-- src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf | 4 ++-- src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf | 4 ++-- src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf | 4 ++-- 26 files changed, 39 insertions(+), 39 deletions(-) diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.cs.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.cs.xlf index fac59d57ed..7663f714a9 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.cs.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.cs.xlf @@ -59,7 +59,7 @@ Pass 'TestContext.CancellationToken' argument to method call - Předejte argument TestContext.CancellationTokenSource.Token volání metody. + Pass 'TestContext.CancellationToken' argument to method call diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.de.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.de.xlf index 83c2944f2e..030c66a367 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.de.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.de.xlf @@ -59,7 +59,7 @@ Pass 'TestContext.CancellationToken' argument to method call - Argument „TestContext.CancellationTokenSource.Token“ an den Methodenaufruf übergeben + Pass 'TestContext.CancellationToken' argument to method call diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.es.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.es.xlf index b71c43e4c4..1c88f1a1a3 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.es.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.es.xlf @@ -59,7 +59,7 @@ Pass 'TestContext.CancellationToken' argument to method call - Pasa el argumento 'TestContext.CancellationTokenSource.Token' a la llamada de método + Pass 'TestContext.CancellationToken' argument to method call diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.fr.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.fr.xlf index 3fb1a5c955..7738ee286e 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.fr.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.fr.xlf @@ -59,7 +59,7 @@ Pass 'TestContext.CancellationToken' argument to method call - Passer l’argument « TestContext.CancellationTokenSource.Token » à l’appel de méthode + Pass 'TestContext.CancellationToken' argument to method call diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.it.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.it.xlf index 596e081d38..e6fe586632 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.it.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.it.xlf @@ -59,7 +59,7 @@ Pass 'TestContext.CancellationToken' argument to method call - Passare l'argomento 'TestContext.CancellationTokenSource.Token' alla chiamata al metodo + Pass 'TestContext.CancellationToken' argument to method call diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ja.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ja.xlf index 3fcfdc9860..1f1399b186 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ja.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ja.xlf @@ -59,7 +59,7 @@ Pass 'TestContext.CancellationToken' argument to method call - 'TestContext.CancellationTokenSource.Token' 引数をメソッド呼び出しに渡す + Pass 'TestContext.CancellationToken' argument to method call diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ko.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ko.xlf index 959bb20f6f..2d6a51fed8 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ko.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ko.xlf @@ -59,7 +59,7 @@ Pass 'TestContext.CancellationToken' argument to method call - 메서드 호출에 'TestContext.CancellationTokenSource.Token' 인수 전달 + Pass 'TestContext.CancellationToken' argument to method call diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pl.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pl.xlf index 1e42db617b..baf335c1ed 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pl.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pl.xlf @@ -59,7 +59,7 @@ Pass 'TestContext.CancellationToken' argument to method call - Przekaż argument „TestContext.CancellationTokenSource.Token” do wywołania metody + Pass 'TestContext.CancellationToken' argument to method call diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pt-BR.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pt-BR.xlf index 2a77ade652..5bd2a7c2bd 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pt-BR.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pt-BR.xlf @@ -59,7 +59,7 @@ Pass 'TestContext.CancellationToken' argument to method call - Passe o argumento 'TestContext.CancellationTokenSource.Token' para a chamada do método + Pass 'TestContext.CancellationToken' argument to method call diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ru.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ru.xlf index cc40a84da6..a0833716dd 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ru.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ru.xlf @@ -59,7 +59,7 @@ Pass 'TestContext.CancellationToken' argument to method call - Передайте аргумент "TestContext.CancellationTokenSource.Token" вызов метода + Pass 'TestContext.CancellationToken' argument to method call diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.tr.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.tr.xlf index bbbcf90ca1..2ffc424368 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.tr.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.tr.xlf @@ -59,7 +59,7 @@ Pass 'TestContext.CancellationToken' argument to method call - ‘TestContext.CancellationTokenSource.Token’ bağımsız değişkeni metot çağrısına geçirin + Pass 'TestContext.CancellationToken' argument to method call diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hans.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hans.xlf index f5f0e12a0d..6c20d4e8e9 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hans.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hans.xlf @@ -59,7 +59,7 @@ Pass 'TestContext.CancellationToken' argument to method call - 将 'TestContext.CancellationTokenSource.Token' 参数传递给方法调用 + Pass 'TestContext.CancellationToken' argument to method call diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hant.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hant.xlf index 1854dea724..bc2241fcd8 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hant.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hant.xlf @@ -59,7 +59,7 @@ Pass 'TestContext.CancellationToken' argument to method call - 將 'TestContext.CancellationTokenSource.Token' 引數傳遞給方法呼叫 + Pass 'TestContext.CancellationToken' argument to method call diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf index 72821bf0ff..7e94ceec1b 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf @@ -464,12 +464,12 @@ Typ deklarující tyto metody by měl také respektovat následující pravidla: When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationToken to enable cooperative cancellation and respect test timeouts. - Při volání asynchronních metod, které mají přetížení akceptující parametr CancellationToken, upřednostňujte použití přetížení s TestContext.CancellationTokenSource.Token, aby se umožnilo kooperativní rušení a dodržování časových limitů testů. + When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationToken to enable cooperative cancellation and respect test timeouts. Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationToken' - Zvažte použití přetížení, které přijímá CancellationToken a předejte TestContext.CancellationTokenSource.Token. + Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationToken' diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf index caf33624e8..6779a5303e 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf @@ -465,12 +465,12 @@ Der Typ, der diese Methoden deklariert, sollte auch die folgenden Regeln beachte When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationToken to enable cooperative cancellation and respect test timeouts. - Wenn Sie asynchrone Methoden aufrufen, die über Überladungen verfügen, die einen CancellationToken-Parameter akzeptieren, bevorzugen Sie die Verwendung der Überladung mit TestContext.CancellationTokenSource.Token, um einen kooperativen Abbruch zu ermöglichen und Testtimeouts zu berücksichtigen. + When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationToken to enable cooperative cancellation and respect test timeouts. Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationToken' - Erwägen Sie die Verwendung der Überladung, die ein CancellationToken akzeptiert, und übergeben Sie „TestContext.CancellationTokenSource.Token“. + Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationToken' diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf index 749203e259..1ba04d86ff 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf @@ -464,12 +464,12 @@ El tipo que declara estos métodos también debe respetar las reglas siguientes: When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationToken to enable cooperative cancellation and respect test timeouts. - Al llamar a métodos asincrónicos que tienen sobrecargas que aceptan un parámetro CancellationToken, es preferible utilizar la sobrecarga con TestContext.CancellationTokenSource.Token para habilitar la cancelación cooperativa y respetar los tiempos de espera de las pruebas. + When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationToken to enable cooperative cancellation and respect test timeouts. Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationToken' - Considere utilizar la sobrecarga que acepta un CancellationToken y pase 'TestContext.CancellationTokenSource.Token' + Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationToken' diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf index 94aaf50771..b8c68db047 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf @@ -464,12 +464,12 @@ Le type doit être une classe When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationToken to enable cooperative cancellation and respect test timeouts. - Lors de l’appel de méthodes asynchrones qui ont des surcharges acceptant un paramètre CancellationToken, préférez utiliser la surcharge avec TestContext.CancellationTokenSource.Token pour activer l’annulation collaborative et respecter les délais d’expiration des tests. + When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationToken to enable cooperative cancellation and respect test timeouts. Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationToken' - Envisagez d’utiliser la surcharge qui accepte un CancellationToken et passe « TestContext.CancellationTokenSource.Token » + Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationToken' diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf index f7f35c846f..283b08e6f0 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf @@ -464,12 +464,12 @@ Anche il tipo che dichiara questi metodi deve rispettare le regole seguenti: When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationToken to enable cooperative cancellation and respect test timeouts. - Quando si chiamano metodi asincroni con overload che accettano un parametro CancellationToken, preferire l'uso dell'overload con TestContext.CancellationTokenSource.Token per abilitare l'annullamento cooperativo e rispettare i timeout di test. + When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationToken to enable cooperative cancellation and respect test timeouts. Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationToken' - Valutare la possibilità di usare l'overload che accetta un CancellationToken e a passare 'TestContext.CancellationTokenSource.Token' + Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationToken' diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf index 46bc1f4999..aedc5b5caa 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf @@ -464,12 +464,12 @@ The type declaring these methods should also respect the following rules: When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationToken to enable cooperative cancellation and respect test timeouts. - CancellationToken パラメーターを受け入れるオーバーロードを持つ非同期メソッドを呼び出す場合は、TestContext.CancellationTokenSource.Token でオーバーロードを使用して協調的な取り消しを有効にし、テスト タイムアウトを考慮します。 + When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationToken to enable cooperative cancellation and respect test timeouts. Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationToken' - CancellationToken を受け取り、'TestContext.CancellationTokenSource.Token' を渡すオーバーロードの使用を検討してください + Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationToken' diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf index 6bbea18a33..71bd34ea2c 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf @@ -464,12 +464,12 @@ The type declaring these methods should also respect the following rules: When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationToken to enable cooperative cancellation and respect test timeouts. - CancellationToken 매개변수를 허용하는 오버로드가 있는 비동기 메서드를 호출할 때는 협력적 취소를 활성화하고 테스트 시간 제한을 준수하기 위해 TestContext.CancellationTokenSource.Token이 있는 오버로드를 사용하는 것이 좋습니다. + When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationToken to enable cooperative cancellation and respect test timeouts. Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationToken' - CancellationToken을 수락하고 'TestContext.CancellationTokenSource.Token'을 전달하는 오버로드를 사용하는 것이 좋습니다. + Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationToken' diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf index 381af5d610..c2bc027848 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf @@ -464,12 +464,12 @@ Typ deklarujący te metody powinien również przestrzegać następujących regu When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationToken to enable cooperative cancellation and respect test timeouts. - W przypadku wywoływania metod asynchronicznych, które mają przeciążenia akceptujące parametr CancellationToken, preferuj użycie przeciążenia z elementem TestContext.CancellationTokenSource.Token, aby umożliwić współpracujące anulowanie i uwzględnić limity czasu testu. + When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationToken to enable cooperative cancellation and respect test timeouts. Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationToken' - Rozważ użycie przeciążenia akceptującego parametr CancellationToken i przekazanie elementu „TestContext.CancellationTokenSource.Token” + Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationToken' diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf index bc41e1133b..9df61d4f1d 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf @@ -464,12 +464,12 @@ O tipo que declara esses métodos também deve respeitar as seguintes regras: When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationToken to enable cooperative cancellation and respect test timeouts. - Ao chamar métodos assíncronos que tenham sobrecargas que aceitam um parâmetro CancellationToken, prefira usar a sobrecarga com TestContext.CancellationTokenSource.Token para habilitar o cancelamento cooperativo e respeitar os tempos limite do teste. + When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationToken to enable cooperative cancellation and respect test timeouts. Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationToken' - Considere usar a sobrecarga que aceita um CancellationToken e passar "TestContext.CancellationTokenSource.Token" + Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationToken' diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf index 3771c466dd..cdee824d0a 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf @@ -470,12 +470,12 @@ The type declaring these methods should also respect the following rules: When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationToken to enable cooperative cancellation and respect test timeouts. - При вызове асинхронных методов с перегрузками, принимающими параметр CancellationToken, рекомендуется использовать перегрузку с TestContext.CancellationTokenSource.Token, чтобы обеспечить кооперативную отмену и учитывать времена ожидания теста. + When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationToken to enable cooperative cancellation and respect test timeouts. Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationToken' - Рассмотрите возможность использования перегрузки, которая принимает CancellationToken, и передавайте "TestContext.CancellationTokenSource.Token" + Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationToken' diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf index d55ce3f117..6c678e7889 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf @@ -464,12 +464,12 @@ Bu yöntemleri bildiren tipin ayrıca aşağıdaki kurallara uyması gerekir: When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationToken to enable cooperative cancellation and respect test timeouts. - CancellationToken parametresini kabul eden aşırı yüklemeleri olan asenkron yöntemleri çağırırken, işbirliğine dayalı iptal işlemini etkinleştirmek ve test zaman aşımlarını dikkate almak için TestContext.CancellationTokenSource.Token ile aşırı yüklemeyi kullanmayı tercih edin. + When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationToken to enable cooperative cancellation and respect test timeouts. Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationToken' - CancellationToken'ı kabul eden aşırı yüklemeyi kullanmayı düşünün ve 'TestContext.CancellationTokenSource.Token'i geçirin. + Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationToken' diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf index 29d6d5b4aa..a82db9a12b 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf @@ -464,12 +464,12 @@ The type declaring these methods should also respect the following rules: When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationToken to enable cooperative cancellation and respect test timeouts. - 在调用包含接受 CancellationToken 参数的重载的异步方法时,建议使用 TestContext.CancellationTokenSource.Token 的重载,以启用协作取消并遵守测试超时。 + When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationToken to enable cooperative cancellation and respect test timeouts. Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationToken' - 请考虑使用接受 CancellationToken 的重载,并传递 'TestContext.CancellationTokenSource.Token' + Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationToken' diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf index 4208bb80c7..577ed5db55 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf @@ -464,12 +464,12 @@ The type declaring these methods should also respect the following rules: When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationToken to enable cooperative cancellation and respect test timeouts. - 在呼叫接受 CancellationToken 參數的多載非同步方法時,建議使用 TestContext.CancellationTokenSource.Token 的多載,以啟用共同取消並遵守測試逾時。 + When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationToken to enable cooperative cancellation and respect test timeouts. Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationToken' - 請考慮使用接受 CancellationToken 的多載,並傳遞 'TestContext.CancellationTokenSource.Token' + Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationToken' From bdb485f694202675acf0d6e7ab74ca75d2bcb5b3 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Tue, 26 Aug 2025 09:49:57 +0200 Subject: [PATCH 432/541] Update Changelog for 3.10.3 (#6440) --- docs/Changelog-Platform.md | 22 ++++++++++++++++++++++ docs/Changelog.md | 18 ++++++++++++++++++ 2 files changed, 40 insertions(+) diff --git a/docs/Changelog-Platform.md b/docs/Changelog-Platform.md index e198af28f6..5f6bd3f67e 100644 --- a/docs/Changelog-Platform.md +++ b/docs/Changelog-Platform.md @@ -4,6 +4,28 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) +## [1.8.3] - 2025-08-26 + +See full log [of v3.10.2...v3.10.3](https://github.com/microsoft/testfx/compare/v3.10.2...v3.10.3) + +### Fixed + +* Unify reading runsettings by @Youssef1313 in [#6434](https://github.com/microsoft/testfx/pull/6434) + +### Artifacts + +* Microsoft.Testing.Platform: [1.8.3](https://www.nuget.org/packages/Microsoft.Testing.Platform/1.8.3) +* Microsoft.Testing.Platform.MSBuild: [1.8.3](https://www.nuget.org/packages/Microsoft.Testing.Platform.MSBuild/1.8.3) +* Microsoft.Testing.Extensions.CrashDump: [1.8.3](https://www.nuget.org/packages/Microsoft.Testing.Extensions.CrashDump/1.8.3) +* Microsoft.Testing.Extensions.HangDump: [1.8.3](https://www.nuget.org/packages/Microsoft.Testing.Extensions.HangDump/1.8.3) +* Microsoft.Testing.Extensions.HotReload: [1.8.3](https://www.nuget.org/packages/Microsoft.Testing.Extensions.HotReload/1.8.3) +* Microsoft.Testing.Extensions.Retry: [1.8.3](https://www.nuget.org/packages/Microsoft.Testing.Extensions.Retry/1.8.3) +* Microsoft.Testing.Extensions.Telemetry: [1.8.3](https://www.nuget.org/packages/Microsoft.Testing.Extensions.Telemetry/1.8.3) +* Microsoft.Testing.Extensions.TrxReport: [1.8.3](https://www.nuget.org/packages/Microsoft.Testing.Extensions.TrxReport/1.8.3) +* Microsoft.Testing.Extensions.TrxReport.Abstractions: [1.8.3](https://www.nuget.org/packages/Microsoft.Testing.Extensions.TrxReport.Abstractions/1.8.3) +* Microsoft.Testing.Extensions.VSTestBridge: [1.8.3](https://www.nuget.org/packages/Microsoft.Testing.Extensions.VSTestBridge/1.8.3) +* Microsoft.Testing.Extensions.AzureDevOpsReport [1.0.0-alpha.25425.9](https://www.nuget.org/packages/Microsoft.Testing.Extensions.AzureDevOpsReport/1.0.0-alpha.25425.9) + ## [1.8.2] - 2025-08-12 See full log [of v3.10.1...v3.10.2](https://github.com/microsoft/testfx/compare/v3.10.1...v3.10.2) diff --git a/docs/Changelog.md b/docs/Changelog.md index bcafd56547..a1a5cb4e74 100644 --- a/docs/Changelog.md +++ b/docs/Changelog.md @@ -4,6 +4,24 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) +## [3.10.3] - 2025-08-26 + +See full log [of v3.10.2...v3.10.3](https://github.com/microsoft/testfx/compare/v3.10.2...v3.10.3) + +### Fixed + +* No change, released to keep version aligned with Microsoft.Testing.Platform. + +### Artifacts + +* MSTest: [3.10.3](https://www.nuget.org/packages/MSTest/3.10.3) +* MSTest.TestFramework: [3.10.3](https://www.nuget.org/packages/MSTest.TestFramework/3.10.3) +* MSTest.TestAdapter: [3.10.3](https://www.nuget.org/packages/MSTest.TestAdapter/3.10.3) +* MSTest.Analyzers: [3.10.3](https://www.nuget.org/packages/MSTest.Analyzers/3.10.3) +* MSTest.Sdk: [3.10.3](https://www.nuget.org/packages/MSTest.Sdk/3.10.3) +* MSTest.SourceGeneration: [1.0.0-alpha.25425.9](https://www.nuget.org/packages/MSTest.SourceGeneration/1.0.0-alpha.25425.9) +* MSTest.Engine: [1.0.0-alpha.25425.9](https://www.nuget.org/packages/MSTest.Engine/1.0.0-alpha.25425.9) + ## [3.10.2] - 2025-08-12 See full log [of v3.10.1...v3.10.2](https://github.com/microsoft/testfx/compare/v3.10.1...v3.10.2) From e743f358a79c64391703070a592ef8cadec9b104 Mon Sep 17 00:00:00 2001 From: Copilot <198982749+Copilot@users.noreply.github.com> Date: Tue, 26 Aug 2025 11:33:28 +0000 Subject: [PATCH 433/541] Fix OneLoc syntax: Replace natural language locking instructions with proper {Locked=""} format (#6442) Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: Youssef1313 <31348972+Youssef1313@users.noreply.github.com> Co-authored-by: Youssef Victor --- .../Resources/Resource.resx | 8 ++++---- .../Resources/xlf/Resource.cs.xlf | 16 ++++++++-------- .../Resources/xlf/Resource.de.xlf | 16 ++++++++-------- .../Resources/xlf/Resource.es.xlf | 16 ++++++++-------- .../Resources/xlf/Resource.fr.xlf | 16 ++++++++-------- .../Resources/xlf/Resource.it.xlf | 16 ++++++++-------- .../Resources/xlf/Resource.ja.xlf | 16 ++++++++-------- .../Resources/xlf/Resource.ko.xlf | 16 ++++++++-------- .../Resources/xlf/Resource.pl.xlf | 16 ++++++++-------- .../Resources/xlf/Resource.pt-BR.xlf | 16 ++++++++-------- .../Resources/xlf/Resource.ru.xlf | 16 ++++++++-------- .../Resources/xlf/Resource.tr.xlf | 16 ++++++++-------- .../Resources/xlf/Resource.zh-Hans.xlf | 16 ++++++++-------- .../Resources/xlf/Resource.zh-Hant.xlf | 16 ++++++++-------- .../Resources/AzureDevOpsResources.resx | 2 +- .../Resources/xlf/AzureDevOpsResources.cs.xlf | 4 ++-- .../Resources/xlf/AzureDevOpsResources.de.xlf | 4 ++-- .../Resources/xlf/AzureDevOpsResources.es.xlf | 4 ++-- .../Resources/xlf/AzureDevOpsResources.fr.xlf | 4 ++-- .../Resources/xlf/AzureDevOpsResources.it.xlf | 4 ++-- .../Resources/xlf/AzureDevOpsResources.ja.xlf | 4 ++-- .../Resources/xlf/AzureDevOpsResources.ko.xlf | 4 ++-- .../Resources/xlf/AzureDevOpsResources.pl.xlf | 4 ++-- .../Resources/xlf/AzureDevOpsResources.pt-BR.xlf | 4 ++-- .../Resources/xlf/AzureDevOpsResources.ru.xlf | 4 ++-- .../Resources/xlf/AzureDevOpsResources.tr.xlf | 4 ++-- .../xlf/AzureDevOpsResources.zh-Hans.xlf | 4 ++-- .../xlf/AzureDevOpsResources.zh-Hant.xlf | 4 ++-- 28 files changed, 135 insertions(+), 135 deletions(-) diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/Resource.resx b/src/Adapter/MSTestAdapter.PlatformServices/Resources/Resource.resx index 473060ad60..01a75aa4da 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/Resource.resx +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/Resource.resx @@ -292,15 +292,15 @@ but received {4} argument(s), with types '{5}'. Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. - 'ClassCleanupLifecycle' is a setting name that shouldn't be localized. + {Locked="ClassCleanupLifecycle"} Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. - 'Scope' is a setting name that shouldn't be localized. + {Locked="Scope"} Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. - `Workers` is a setting name that shouldn't be localized. + {Locked="Workers"} Invalid settings '{0}'. Unexpected XmlAttribute: '{1}'. @@ -349,7 +349,7 @@ but received {4} argument(s), with types '{5}'. Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) - `Workers` is a setting name that shouldn't be localized. 'Scope' is a setting name that shouldn't be localized. + {Locked="Workers"}{Locked="Scope"} Unable to load types from the test source '{0}'. Some or all of the tests in this source may not be discovered. diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.cs.xlf b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.cs.xlf index 1efbb9e1cc..959f31219a 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.cs.xlf +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.cs.xlf @@ -236,18 +236,18 @@ byl však přijat tento počet argumentů: {4} s typy {5}. Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. - Pro classCleanupLifecycle byla zadána neplatná hodnota {0}. Podporované obory jsou {1}. - 'ClassCleanupLifecycle' is a setting name that shouldn't be localized. + Pro classCleanupLifecycle byla zadána neplatná hodnota {0}. Podporované obory jsou {1}. + {Locked="ClassCleanupLifecycle"} Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. - Pro Obor je zadaná neplatná hodnota {0}. Podporované obory jsou {1}. - 'Scope' is a setting name that shouldn't be localized. + Pro Obor je zadaná neplatná hodnota {0}. Podporované obory jsou {1}. + {Locked="Scope"} Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. - Pro Pracovní procesy je zadaná neplatná hodnota {0}. Hodnota by měla být nezáporné celé číslo. - `Workers` is a setting name that shouldn't be localized. + Pro Pracovní procesy je zadaná neplatná hodnota {0}. Hodnota by měla být nezáporné celé číslo. + {Locked="Workers"} Invalid settings '{0}'. Unexpected XmlAttribute: '{1}'. @@ -351,8 +351,8 @@ byl však přijat tento počet argumentů: {4} s typy {5}. Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) - Je povolená paralelizace testu pro {0} (pracovní procesy: {1}, obor: {2}). - `Workers` is a setting name that shouldn't be localized. 'Scope' is a setting name that shouldn't be localized. + Je povolená paralelizace testu pro {0} (pracovní procesy: {1}, obor: {2}). + {Locked="Workers"}{Locked="Scope"} {0}_{1} {2} diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.de.xlf b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.de.xlf index 45fefe8360..035202910f 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.de.xlf +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.de.xlf @@ -236,18 +236,18 @@ aber empfing {4} Argument(e) mit den Typen „{5}“. Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. - Für "ClassCleanupLifecycle" wurde ein ungültiger Wert "{0}" angegeben. Unterstützte Bereiche sind {1}. - 'ClassCleanupLifecycle' is a setting name that shouldn't be localized. + Für "ClassCleanupLifecycle" wurde ein ungültiger Wert "{0}" angegeben. Unterstützte Bereiche sind {1}. + {Locked="ClassCleanupLifecycle"} Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. - Ungültiger Wert "{0}" für "Scope" angegeben. Unterstützte Bereiche: {1}. - 'Scope' is a setting name that shouldn't be localized. + Ungültiger Wert "{0}" für "Scope" angegeben. Unterstützte Bereiche: {1}. + {Locked="Scope"} Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. - Ungültiger Wert "{0}" für "Workers" angegeben. Der Wert muss eine nicht negative Ganzzahl sein. - `Workers` is a setting name that shouldn't be localized. + Ungültiger Wert "{0}" für "Workers" angegeben. Der Wert muss eine nicht negative Ganzzahl sein. + {Locked="Workers"} Invalid settings '{0}'. Unexpected XmlAttribute: '{1}'. @@ -351,8 +351,8 @@ aber empfing {4} Argument(e) mit den Typen „{5}“. Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) - Testparallelisierung aktiviert für {0} (Worker: {1}, Bereich: {2}) - `Workers` is a setting name that shouldn't be localized. 'Scope' is a setting name that shouldn't be localized. + Testparallelisierung aktiviert für {0} (Worker: {1}, Bereich: {2}) + {Locked="Workers"}{Locked="Scope"} {0}_{1} {2} diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.es.xlf b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.es.xlf index d2af8480fa..fac9cbabdb 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.es.xlf +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.es.xlf @@ -236,18 +236,18 @@ pero recibió {4} argumentos, con los tipos '{5}'. Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. - Valor no válido "{0}" especificado para "ClassCleanupLifecycle". Los ámbitos admitidos son {1}. - 'ClassCleanupLifecycle' is a setting name that shouldn't be localized. + Valor no válido "{0}" especificado para "ClassCleanupLifecycle". Los ámbitos admitidos son {1}. + {Locked="ClassCleanupLifecycle"} Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. - Valor no válido "{0}" especificado para "Ámbito". Los ámbitos admitidos son {1}. - 'Scope' is a setting name that shouldn't be localized. + Valor no válido "{0}" especificado para "Ámbito". Los ámbitos admitidos son {1}. + {Locked="Scope"} Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. - Valor no válido "{0}" especificado para "Trabajadores". El valor debe ser un entero no negativo. - `Workers` is a setting name that shouldn't be localized. + Valor no válido "{0}" especificado para "Trabajadores". El valor debe ser un entero no negativo. + {Locked="Workers"} Invalid settings '{0}'. Unexpected XmlAttribute: '{1}'. @@ -351,8 +351,8 @@ pero recibió {4} argumentos, con los tipos '{5}'. Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) - Probar paralelización habilitada para {0} (Trabajos: {1}, Ámbito: {2}) - `Workers` is a setting name that shouldn't be localized. 'Scope' is a setting name that shouldn't be localized. + Probar paralelización habilitada para {0} (Trabajos: {1}, Ámbito: {2}) + {Locked="Workers"}{Locked="Scope"} {0}_{1} {2} diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.fr.xlf b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.fr.xlf index 1929980124..19a739188b 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.fr.xlf +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.fr.xlf @@ -236,18 +236,18 @@ mais a reçu {4} argument(s), avec les types « {5} ». Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. - Valeur non valide '{0}' spécifiée pour la 'ClassCleanupLifecycle'. Les portées prises en charge sont {1}. - 'ClassCleanupLifecycle' is a setting name that shouldn't be localized. + Valeur non valide '{0}' spécifiée pour la 'ClassCleanupLifecycle'. Les portées prises en charge sont {1}. + {Locked="ClassCleanupLifecycle"} Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. - Valeur non valide '{0}' spécifiée pour la 'Portée'. Les portées prises en charge sont {1}. - 'Scope' is a setting name that shouldn't be localized. + Valeur non valide '{0}' spécifiée pour la 'Portée'. Les portées prises en charge sont {1}. + {Locked="Scope"} Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. - Valeur non valide '{0}' spécifiée pour 'Workers'. La valeur doit être un entier non négatif. - `Workers` is a setting name that shouldn't be localized. + Valeur non valide '{0}' spécifiée pour 'Workers'. La valeur doit être un entier non négatif. + {Locked="Workers"} Invalid settings '{0}'. Unexpected XmlAttribute: '{1}'. @@ -351,8 +351,8 @@ mais a reçu {4} argument(s), avec les types « {5} ». Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) - Parallélisation des tests activée pour {0} (Workers : {1}, Étendue : {2}). - `Workers` is a setting name that shouldn't be localized. 'Scope' is a setting name that shouldn't be localized. + Parallélisation des tests activée pour {0} (Workers : {1}, Étendue : {2}). + {Locked="Workers"}{Locked="Scope"} {0}_{1} {2} diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.it.xlf b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.it.xlf index 237f15eff0..b732bf5b5e 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.it.xlf +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.it.xlf @@ -236,18 +236,18 @@ ma ha ricevuto {4} argomenti, con tipi '{5}'. Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. - Il valore '{0}', specificato per 'ClassCleanupLifecycle', non è valido. I valori supportati per Scope sono {1}. - 'ClassCleanupLifecycle' is a setting name that shouldn't be localized. + Il valore '{0}', specificato per 'ClassCleanupLifecycle', non è valido. I valori supportati per Scope sono {1}. + {Locked="ClassCleanupLifecycle"} Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. - Il valore '{0}', specificato per 'Scope', non è valido. I valori supportati per Scope sono {1}. - 'Scope' is a setting name that shouldn't be localized. + Il valore '{0}', specificato per 'Scope', non è valido. I valori supportati per Scope sono {1}. + {Locked="Scope"} Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. - Il valore '{0}', specificato per 'Workers', non è valido. Il valore deve essere un numero intero non negativo. - `Workers` is a setting name that shouldn't be localized. + Il valore '{0}', specificato per 'Workers', non è valido. Il valore deve essere un numero intero non negativo. + {Locked="Workers"} Invalid settings '{0}'. Unexpected XmlAttribute: '{1}'. @@ -351,8 +351,8 @@ ma ha ricevuto {4} argomenti, con tipi '{5}'. Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) - Parallelizzazione test abilitata per {0} (Processi di lavoro: {1}. Ambito: {2}). - `Workers` is a setting name that shouldn't be localized. 'Scope' is a setting name that shouldn't be localized. + Parallelizzazione test abilitata per {0} (Processi di lavoro: {1}. Ambito: {2}). + {Locked="Workers"}{Locked="Scope"} {0}_{1} {2} diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.ja.xlf b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.ja.xlf index 59cf4cb86e..31e8cc0126 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.ja.xlf +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.ja.xlf @@ -237,18 +237,18 @@ but received {4} argument(s), with types '{5}'. Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. - 'ClassCleanupLifecycle' に無効な値 '{0}' が指定されました。サポートされているスコープは {1} です。 - 'ClassCleanupLifecycle' is a setting name that shouldn't be localized. + 'ClassCleanupLifecycle' に無効な値 '{0}' が指定されました。サポートされているスコープは {1} です。 + {Locked="ClassCleanupLifecycle"} Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. - 無効な値 '{0}' が 'Scope' に指定されました。サポートされているスコープは {1} です。 - 'Scope' is a setting name that shouldn't be localized. + 無効な値 '{0}' が 'Scope' に指定されました。サポートされているスコープは {1} です。 + {Locked="Scope"} Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. - 無効な値 '{0}' が 'Workers' に指定されました。値は負ではない整数である必要があります。 - `Workers` is a setting name that shouldn't be localized. + 無効な値 '{0}' が 'Workers' に指定されました。値は負ではない整数である必要があります。 + {Locked="Workers"} Invalid settings '{0}'. Unexpected XmlAttribute: '{1}'. @@ -352,8 +352,8 @@ but received {4} argument(s), with types '{5}'. Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) - {0} でテスト並列処理が有効にされています (Workers: {1}、Scope: {2})。 - `Workers` is a setting name that shouldn't be localized. 'Scope' is a setting name that shouldn't be localized. + {0} でテスト並列処理が有効にされています (Workers: {1}、Scope: {2})。 + {Locked="Workers"}{Locked="Scope"} {0}_{1} {2} diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.ko.xlf b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.ko.xlf index 56084fe47c..71366d3efe 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.ko.xlf +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.ko.xlf @@ -236,18 +236,18 @@ but received {4} argument(s), with types '{5}'. Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. - 'ClassCleanupLifecycle'에 대해 '{0}' 잘못된 값이 지정되었습니다. 지원되는 범위는 {1}입니다. - 'ClassCleanupLifecycle' is a setting name that shouldn't be localized. + 'ClassCleanupLifecycle'에 대해 '{0}' 잘못된 값이 지정되었습니다. 지원되는 범위는 {1}입니다. + {Locked="ClassCleanupLifecycle"} Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. - 'Scope'에 대해 잘못된 값 '{0}'이(가) 지정되었습니다. 지원되는 범위는 {1}입니다. - 'Scope' is a setting name that shouldn't be localized. + 'Scope'에 대해 잘못된 값 '{0}'이(가) 지정되었습니다. 지원되는 범위는 {1}입니다. + {Locked="Scope"} Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. - 'Workers'에 대해 잘못된 값 '{0}'이(가) 지정되었습니다. 이 값은 음수가 아닌 정수여야 합니다. - `Workers` is a setting name that shouldn't be localized. + 'Workers'에 대해 잘못된 값 '{0}'이(가) 지정되었습니다. 이 값은 음수가 아닌 정수여야 합니다. + {Locked="Workers"} Invalid settings '{0}'. Unexpected XmlAttribute: '{1}'. @@ -351,8 +351,8 @@ but received {4} argument(s), with types '{5}'. Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) - {0}에 대해 테스트 병렬 처리를 사용합니다(Workers: {1}, Scope: {2}). - `Workers` is a setting name that shouldn't be localized. 'Scope' is a setting name that shouldn't be localized. + {0}에 대해 테스트 병렬 처리를 사용합니다(Workers: {1}, Scope: {2}). + {Locked="Workers"}{Locked="Scope"} {0}_{1} {2} diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.pl.xlf b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.pl.xlf index ab1778d736..1b106ba676 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.pl.xlf +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.pl.xlf @@ -236,18 +236,18 @@ ale odebrał argumenty {4} z typami „{5}”. Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. - Dla ustawienia „ClassCleanupLifecycle” określono nieprawidłową wartość „{0}”. Obsługiwane zakresy to {1}. - 'ClassCleanupLifecycle' is a setting name that shouldn't be localized. + Dla ustawienia „ClassCleanupLifecycle” określono nieprawidłową wartość „{0}”. Obsługiwane zakresy to {1}. + {Locked="ClassCleanupLifecycle"} Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. - Określono nieprawidłową wartość „{0}” dla właściwości „Scope”. Obsługiwane zakresy to {1}. - 'Scope' is a setting name that shouldn't be localized. + Określono nieprawidłową wartość „{0}” dla właściwości „Scope”. Obsługiwane zakresy to {1}. + {Locked="Scope"} Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. - Określono nieprawidłową wartość „{0}” dla właściwości „Workers”. Wartość musi być nieujemną liczbą całkowitą. - `Workers` is a setting name that shouldn't be localized. + Określono nieprawidłową wartość „{0}” dla właściwości „Workers”. Wartość musi być nieujemną liczbą całkowitą. + {Locked="Workers"} Invalid settings '{0}'. Unexpected XmlAttribute: '{1}'. @@ -351,8 +351,8 @@ ale odebrał argumenty {4} z typami „{5}”. Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) - Przetwarzanie równoległe testów włączono dla {0} (procesy robocze: {1}, zakres: {2}) - `Workers` is a setting name that shouldn't be localized. 'Scope' is a setting name that shouldn't be localized. + Przetwarzanie równoległe testów włączono dla {0} (procesy robocze: {1}, zakres: {2}) + {Locked="Workers"}{Locked="Scope"} {0}_{1} {2} diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.pt-BR.xlf b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.pt-BR.xlf index 352c0d1f34..6c79c9bcea 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.pt-BR.xlf +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.pt-BR.xlf @@ -236,18 +236,18 @@ mas {4} argumentos recebidos, com tipos '{5}'. Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. - Valor inválido '{0}' especificado para 'ClassCleanupLifecycle'. Os escopos suportados são {1}. - 'ClassCleanupLifecycle' is a setting name that shouldn't be localized. + Valor inválido '{0}' especificado para 'ClassCleanupLifecycle'. Os escopos suportados são {1}. + {Locked="ClassCleanupLifecycle"} Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. - Valor inválido '{0}' especificado para 'Scope'. Os escopos compatíveis são {1}. - 'Scope' is a setting name that shouldn't be localized. + Valor inválido '{0}' especificado para 'Scope'. Os escopos compatíveis são {1}. + {Locked="Scope"} Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. - Valor inválido '{0}' especificado para 'Workers'. O valor deve ser um inteiro não negativo. - `Workers` is a setting name that shouldn't be localized. + Valor inválido '{0}' especificado para 'Workers'. O valor deve ser um inteiro não negativo. + {Locked="Workers"} Invalid settings '{0}'. Unexpected XmlAttribute: '{1}'. @@ -351,8 +351,8 @@ mas {4} argumentos recebidos, com tipos '{5}'. Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) - Paralelização de Teste habilitada para {0} (Trabalhos: {1}, Escopo: {2}) - `Workers` is a setting name that shouldn't be localized. 'Scope' is a setting name that shouldn't be localized. + Paralelização de Teste habilitada para {0} (Trabalhos: {1}, Escopo: {2}) + {Locked="Workers"}{Locked="Scope"} {0}_{1} {2} diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.ru.xlf b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.ru.xlf index 6fd7005d92..3b75fec8a5 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.ru.xlf +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.ru.xlf @@ -236,18 +236,18 @@ but received {4} argument(s), with types '{5}'. Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. - Для параметра "ClassCleanupLifecycle" указано недопустимое значение "{0}". Поддерживаемые области: {1}. - 'ClassCleanupLifecycle' is a setting name that shouldn't be localized. + Для параметра "ClassCleanupLifecycle" указано недопустимое значение "{0}". Поддерживаемые области: {1}. + {Locked="ClassCleanupLifecycle"} Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. - В поле "Область" указано недопустимое значение "{0}". Поддерживаемые области: {1}. - 'Scope' is a setting name that shouldn't be localized. + В поле "Область" указано недопустимое значение "{0}". Поддерживаемые области: {1}. + {Locked="Scope"} Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. - В поле "Рабочие роли" указано недопустимое значение "{0}". Оно должно быть неотрицательным целым числом. - `Workers` is a setting name that shouldn't be localized. + В поле "Рабочие роли" указано недопустимое значение "{0}". Оно должно быть неотрицательным целым числом. + {Locked="Workers"} Invalid settings '{0}'. Unexpected XmlAttribute: '{1}'. @@ -351,8 +351,8 @@ but received {4} argument(s), with types '{5}'. Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) - Включена параллелизация тестов для {0} (рабочие роли: {1}, область: {2}) - `Workers` is a setting name that shouldn't be localized. 'Scope' is a setting name that shouldn't be localized. + Включена параллелизация тестов для {0} (рабочие роли: {1}, область: {2}) + {Locked="Workers"}{Locked="Scope"} {0}_{1} {2} diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.tr.xlf b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.tr.xlf index 2c2dc60814..a32f933928 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.tr.xlf +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.tr.xlf @@ -236,18 +236,18 @@ ancak, '{5}' türünde {4} bağımsız değişken aldı. Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. - 'ClassCleanupLifecycle' için geçersiz '{0}' değeri belirtildi. Desteklenen kapsamlar {1}'dir. - 'ClassCleanupLifecycle' is a setting name that shouldn't be localized. + 'ClassCleanupLifecycle' için geçersiz '{0}' değeri belirtildi. Desteklenen kapsamlar {1}'dir. + {Locked="ClassCleanupLifecycle"} Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. - 'Scope' için geçersiz '{0}' değeri belirtildi. Desteklenen kapsamlar {1}. - 'Scope' is a setting name that shouldn't be localized. + 'Scope' için geçersiz '{0}' değeri belirtildi. Desteklenen kapsamlar {1}. + {Locked="Scope"} Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. - 'Workers' için geçersiz '{0}' değeri belirtildi. Değer negatif olmayan bir tamsayı olmalıdır. - `Workers` is a setting name that shouldn't be localized. + 'Workers' için geçersiz '{0}' değeri belirtildi. Değer negatif olmayan bir tamsayı olmalıdır. + {Locked="Workers"} Invalid settings '{0}'. Unexpected XmlAttribute: '{1}'. @@ -351,8 +351,8 @@ ancak, '{5}' türünde {4} bağımsız değişken aldı. Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) - {0} için Test Paralelleştirme etkin (Çalışanlar: {1}, Kapsam: {2}). - `Workers` is a setting name that shouldn't be localized. 'Scope' is a setting name that shouldn't be localized. + {0} için Test Paralelleştirme etkin (Çalışanlar: {1}, Kapsam: {2}). + {Locked="Workers"}{Locked="Scope"} {0}_{1} {2} diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.zh-Hans.xlf b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.zh-Hans.xlf index 4d80166a18..4404a3ec6d 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.zh-Hans.xlf +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.zh-Hans.xlf @@ -236,18 +236,18 @@ but received {4} argument(s), with types '{5}'. Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. - 为“ClassCleanupLifecycle”指定的值“{0}”无效。支持的作用域为 {1}。 - 'ClassCleanupLifecycle' is a setting name that shouldn't be localized. + 为“ClassCleanupLifecycle”指定的值“{0}”无效。支持的作用域为 {1}。 + {Locked="ClassCleanupLifecycle"} Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. - 为“范围”指定的值“{0}”无效。受支持的范围为 {1}。 - 'Scope' is a setting name that shouldn't be localized. + 为“范围”指定的值“{0}”无效。受支持的范围为 {1}。 + {Locked="Scope"} Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. - 为“辅助角色”指定的值“{0}”无效。该值应为非负整数。 - `Workers` is a setting name that shouldn't be localized. + 为“辅助角色”指定的值“{0}”无效。该值应为非负整数。 + {Locked="Workers"} Invalid settings '{0}'. Unexpected XmlAttribute: '{1}'. @@ -351,8 +351,8 @@ but received {4} argument(s), with types '{5}'. Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) - 已为 {0} 启用测试并行化(工作线程: {1},范围: {2}) - `Workers` is a setting name that shouldn't be localized. 'Scope' is a setting name that shouldn't be localized. + 已为 {0} 启用测试并行化(工作线程: {1},范围: {2}) + {Locked="Workers"}{Locked="Scope"} {0}_{1} {2} diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.zh-Hant.xlf b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.zh-Hant.xlf index b933d9305b..2186a8ae6f 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.zh-Hant.xlf +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.zh-Hant.xlf @@ -236,18 +236,18 @@ but received {4} argument(s), with types '{5}'. Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. - 為 'ClassCleanupLifecycle' 指定的值 '{0}' 無效。支援的範圍為 {1}。 - 'ClassCleanupLifecycle' is a setting name that shouldn't be localized. + 為 'ClassCleanupLifecycle' 指定的值 '{0}' 無效。支援的範圍為 {1}。 + {Locked="ClassCleanupLifecycle"} Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. - 為 'Scope' 指定的值 '{0}' 無效。支援的範圍為 {1}。 - 'Scope' is a setting name that shouldn't be localized. + 為 'Scope' 指定的值 '{0}' 無效。支援的範圍為 {1}。 + {Locked="Scope"} Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. - 為 'Workers' 的值 '{0}' 無效。值應為非負整數。 - `Workers` is a setting name that shouldn't be localized. + 為 'Workers' 的值 '{0}' 無效。值應為非負整數。 + {Locked="Workers"} Invalid settings '{0}'. Unexpected XmlAttribute: '{1}'. @@ -351,8 +351,8 @@ but received {4} argument(s), with types '{5}'. Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) - 已為 {0} 啟用平行測試 (背景工作角色: {1},範圍: {2}) - `Workers` is a setting name that shouldn't be localized. 'Scope' is a setting name that shouldn't be localized. + 已為 {0} 啟用平行測試 (背景工作角色: {1},範圍: {2}) + {Locked="Workers"}{Locked="Scope"} {0}_{1} {2} diff --git a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/AzureDevOpsResources.resx b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/AzureDevOpsResources.resx index cc27c6c8b4..516d5d4382 100644 --- a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/AzureDevOpsResources.resx +++ b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/AzureDevOpsResources.resx @@ -134,6 +134,6 @@ Severity to use for the reported event. Options are: error (default) and warning. - Do not translated 'error' or 'warning' those are literal values. + {Locked="error"}{Locked="warning"} \ No newline at end of file diff --git a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.cs.xlf b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.cs.xlf index 4689eb6b49..497fd8bdd9 100644 --- a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.cs.xlf +++ b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.cs.xlf @@ -29,8 +29,8 @@ Severity to use for the reported event. Options are: error (default) and warning. - Závažnost, která se má použít pro hlášenou událost. Možnosti: chyba (výchozí) a upozornění. - Do not translated 'error' or 'warning' those are literal values. + Závažnost, která se má použít pro hlášenou událost. Možnosti: chyba (výchozí) a upozornění. + {Locked="error"}{Locked="warning"} diff --git a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.de.xlf b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.de.xlf index d86ec79035..92c6822d4e 100644 --- a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.de.xlf +++ b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.de.xlf @@ -29,8 +29,8 @@ Severity to use for the reported event. Options are: error (default) and warning. - Schweregrad, der für das gemeldete Ereignis verwendet werden soll. Optionen sind: Fehler (Standard) und Warnung. - Do not translated 'error' or 'warning' those are literal values. + Schweregrad, der für das gemeldete Ereignis verwendet werden soll. Optionen sind: Fehler (Standard) und Warnung. + {Locked="error"}{Locked="warning"} diff --git a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.es.xlf b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.es.xlf index 8af2f91123..1d785313e5 100644 --- a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.es.xlf +++ b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.es.xlf @@ -29,8 +29,8 @@ Severity to use for the reported event. Options are: error (default) and warning. - Gravedad que se va a usar para el evento notificado. Las opciones son: error (valor predeterminado) y advertencia. - Do not translated 'error' or 'warning' those are literal values. + Gravedad que se va a usar para el evento notificado. Las opciones son: error (valor predeterminado) y advertencia. + {Locked="error"}{Locked="warning"} diff --git a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.fr.xlf b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.fr.xlf index 42e2e1d99d..fe1a15aaf7 100644 --- a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.fr.xlf +++ b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.fr.xlf @@ -29,8 +29,8 @@ Severity to use for the reported event. Options are: error (default) and warning. - Gravité à utiliser pour l’événement signalé. Les options sont : erreur (par défaut) et avertissement. - Do not translated 'error' or 'warning' those are literal values. + Gravité à utiliser pour l’événement signalé. Les options sont : erreur (par défaut) et avertissement. + {Locked="error"}{Locked="warning"} diff --git a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.it.xlf b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.it.xlf index 2e778e1102..92a2727133 100644 --- a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.it.xlf +++ b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.it.xlf @@ -29,8 +29,8 @@ Severity to use for the reported event. Options are: error (default) and warning. - Gravità da utilizzare per l'evento segnalato. Le opzioni sono: errore (impostazione predefinita) e avviso. - Do not translated 'error' or 'warning' those are literal values. + Gravità da utilizzare per l'evento segnalato. Le opzioni sono: errore (impostazione predefinita) e avviso. + {Locked="error"}{Locked="warning"} diff --git a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.ja.xlf b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.ja.xlf index 8bfb6808d3..b60650bea9 100644 --- a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.ja.xlf +++ b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.ja.xlf @@ -29,8 +29,8 @@ Severity to use for the reported event. Options are: error (default) and warning. - 報告されたイベントに使用する重大度。オプションは、エラー (既定) と警告です。 - Do not translated 'error' or 'warning' those are literal values. + 報告されたイベントに使用する重大度。オプションは、エラー (既定) と警告です。 + {Locked="error"}{Locked="warning"} diff --git a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.ko.xlf b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.ko.xlf index 9c7063b64c..6da94054e6 100644 --- a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.ko.xlf +++ b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.ko.xlf @@ -29,8 +29,8 @@ Severity to use for the reported event. Options are: error (default) and warning. - 보고된 이벤트에 사용할 심각도입니다. 옵션은 오류(기본값)와 경고, 두 가지입니다. - Do not translated 'error' or 'warning' those are literal values. + 보고된 이벤트에 사용할 심각도입니다. 옵션은 오류(기본값)와 경고, 두 가지입니다. + {Locked="error"}{Locked="warning"} diff --git a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.pl.xlf b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.pl.xlf index 6bd1122a9d..39b59857ef 100644 --- a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.pl.xlf +++ b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.pl.xlf @@ -29,8 +29,8 @@ Severity to use for the reported event. Options are: error (default) and warning. - Ważność do użycia dla zgłoszonego zdarzenia. Dostępne opcje to: błąd (domyślny) i ostrzeżenie. - Do not translated 'error' or 'warning' those are literal values. + Ważność do użycia dla zgłoszonego zdarzenia. Dostępne opcje to: błąd (domyślny) i ostrzeżenie. + {Locked="error"}{Locked="warning"} diff --git a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.pt-BR.xlf b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.pt-BR.xlf index ca51be8c38..075a8a05fc 100644 --- a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.pt-BR.xlf +++ b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.pt-BR.xlf @@ -29,8 +29,8 @@ Severity to use for the reported event. Options are: error (default) and warning. - A gravidade que será usada para o evento relatado. As opções são: erro (padrão) e aviso. - Do not translated 'error' or 'warning' those are literal values. + A gravidade que será usada para o evento relatado. As opções são: erro (padrão) e aviso. + {Locked="error"}{Locked="warning"} diff --git a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.ru.xlf b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.ru.xlf index 994718f04e..11e6fa156f 100644 --- a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.ru.xlf +++ b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.ru.xlf @@ -29,8 +29,8 @@ Severity to use for the reported event. Options are: error (default) and warning. - Уровень серьезности, используемый для события из отчета. Параметры: error (по умолчанию) и warning. - Do not translated 'error' or 'warning' those are literal values. + Уровень серьезности, используемый для события из отчета. Параметры: error (по умолчанию) и warning. + {Locked="error"}{Locked="warning"} diff --git a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.tr.xlf b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.tr.xlf index 727dc67065..a2e9344690 100644 --- a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.tr.xlf +++ b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.tr.xlf @@ -29,8 +29,8 @@ Severity to use for the reported event. Options are: error (default) and warning. - Raporlanan olay için kullanılacak önem derecesi. Seçenekler şunlardır: hata (varsayılan) ve uyarı. - Do not translated 'error' or 'warning' those are literal values. + Raporlanan olay için kullanılacak önem derecesi. Seçenekler şunlardır: hata (varsayılan) ve uyarı. + {Locked="error"}{Locked="warning"} diff --git a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.zh-Hans.xlf b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.zh-Hans.xlf index 3f3b35566e..394763200b 100644 --- a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.zh-Hans.xlf +++ b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.zh-Hans.xlf @@ -29,8 +29,8 @@ Severity to use for the reported event. Options are: error (default) and warning. - 要用于所报告事件的严重性。选项为: error (默认)和 warning。 - Do not translated 'error' or 'warning' those are literal values. + 要用于所报告事件的严重性。选项为: error (默认)和 warning。 + {Locked="error"}{Locked="warning"} diff --git a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.zh-Hant.xlf b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.zh-Hant.xlf index 5b3ebbf244..6feac334bd 100644 --- a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.zh-Hant.xlf +++ b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.zh-Hant.xlf @@ -29,8 +29,8 @@ Severity to use for the reported event. Options are: error (default) and warning. - 要用於所報告事件的嚴重性。選項為: 錯誤 (預設) 警告。 - Do not translated 'error' or 'warning' those are literal values. + 要用於所報告事件的嚴重性。選項為: 錯誤 (預設) 警告。 + {Locked="error"}{Locked="warning"} From 9ae11c86720c7d0051af5b4784cd2e54ccb13106 Mon Sep 17 00:00:00 2001 From: dotnet bot Date: Tue, 26 Aug 2025 04:52:52 -0700 Subject: [PATCH 434/541] Localized file check-in by OneLocBuild Task: Build definition ID 1218: Build ID 2780331 --- .../Resources/xlf/Resource.cs.xlf | 8 ++++---- .../Resources/xlf/Resource.de.xlf | 8 ++++---- .../Resources/xlf/Resource.es.xlf | 8 ++++---- .../Resources/xlf/Resource.fr.xlf | 8 ++++---- .../Resources/xlf/Resource.it.xlf | 8 ++++---- .../Resources/xlf/Resource.ja.xlf | 8 ++++---- .../Resources/xlf/Resource.ko.xlf | 8 ++++---- .../Resources/xlf/Resource.pl.xlf | 8 ++++---- .../Resources/xlf/Resource.pt-BR.xlf | 8 ++++---- .../Resources/xlf/Resource.ru.xlf | 8 ++++---- .../Resources/xlf/Resource.tr.xlf | 8 ++++---- .../Resources/xlf/Resource.zh-Hans.xlf | 8 ++++---- .../Resources/xlf/Resource.zh-Hant.xlf | 8 ++++---- .../Resources/xlf/AzureDevOpsResources.cs.xlf | 2 +- .../Resources/xlf/AzureDevOpsResources.de.xlf | 2 +- .../Resources/xlf/AzureDevOpsResources.es.xlf | 2 +- .../Resources/xlf/AzureDevOpsResources.fr.xlf | 2 +- .../Resources/xlf/AzureDevOpsResources.it.xlf | 2 +- .../Resources/xlf/AzureDevOpsResources.ja.xlf | 2 +- .../Resources/xlf/AzureDevOpsResources.ko.xlf | 2 +- .../Resources/xlf/AzureDevOpsResources.pl.xlf | 2 +- .../Resources/xlf/AzureDevOpsResources.pt-BR.xlf | 2 +- .../Resources/xlf/AzureDevOpsResources.ru.xlf | 2 +- .../Resources/xlf/AzureDevOpsResources.tr.xlf | 2 +- 24 files changed, 63 insertions(+), 63 deletions(-) diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.cs.xlf b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.cs.xlf index 959f31219a..ef564b606c 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.cs.xlf +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.cs.xlf @@ -236,17 +236,17 @@ byl však přijat tento počet argumentů: {4} s typy {5}. Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. - Pro classCleanupLifecycle byla zadána neplatná hodnota {0}. Podporované obory jsou {1}. + Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. {Locked="ClassCleanupLifecycle"} Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. - Pro Obor je zadaná neplatná hodnota {0}. Podporované obory jsou {1}. + Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. {Locked="Scope"} Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. - Pro Pracovní procesy je zadaná neplatná hodnota {0}. Hodnota by měla být nezáporné celé číslo. + Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. {Locked="Workers"} @@ -351,7 +351,7 @@ byl však přijat tento počet argumentů: {4} s typy {5}. Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) - Je povolená paralelizace testu pro {0} (pracovní procesy: {1}, obor: {2}). + Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) {Locked="Workers"}{Locked="Scope"} diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.de.xlf b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.de.xlf index 035202910f..0a48f74904 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.de.xlf +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.de.xlf @@ -236,17 +236,17 @@ aber empfing {4} Argument(e) mit den Typen „{5}“. Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. - Für "ClassCleanupLifecycle" wurde ein ungültiger Wert "{0}" angegeben. Unterstützte Bereiche sind {1}. + Für "ClassCleanupLifecycle" wurde ein ungültiger Wert "{0}" angegeben. Unterstützte Bereiche sind {1}. {Locked="ClassCleanupLifecycle"} Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. - Ungültiger Wert "{0}" für "Scope" angegeben. Unterstützte Bereiche: {1}. + Ungültiger Wert "{0}" für "Scope" angegeben. Unterstützte Bereiche: {1}. {Locked="Scope"} Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. - Ungültiger Wert "{0}" für "Workers" angegeben. Der Wert muss eine nicht negative Ganzzahl sein. + Ungültiger Wert "{0}" für "Workers" angegeben. Der Wert muss eine nicht negative Ganzzahl sein. {Locked="Workers"} @@ -351,7 +351,7 @@ aber empfing {4} Argument(e) mit den Typen „{5}“. Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) - Testparallelisierung aktiviert für {0} (Worker: {1}, Bereich: {2}) + Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) {Locked="Workers"}{Locked="Scope"} diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.es.xlf b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.es.xlf index fac9cbabdb..a7034ac99b 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.es.xlf +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.es.xlf @@ -236,17 +236,17 @@ pero recibió {4} argumentos, con los tipos '{5}'. Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. - Valor no válido "{0}" especificado para "ClassCleanupLifecycle". Los ámbitos admitidos son {1}. + Valor no válido "{0}" especificado para "ClassCleanupLifecycle". Los ámbitos admitidos son {1}. {Locked="ClassCleanupLifecycle"} Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. - Valor no válido "{0}" especificado para "Ámbito". Los ámbitos admitidos son {1}. + Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. {Locked="Scope"} Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. - Valor no válido "{0}" especificado para "Trabajadores". El valor debe ser un entero no negativo. + Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. {Locked="Workers"} @@ -351,7 +351,7 @@ pero recibió {4} argumentos, con los tipos '{5}'. Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) - Probar paralelización habilitada para {0} (Trabajos: {1}, Ámbito: {2}) + Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) {Locked="Workers"}{Locked="Scope"} diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.fr.xlf b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.fr.xlf index 19a739188b..088a6d86db 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.fr.xlf +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.fr.xlf @@ -236,17 +236,17 @@ mais a reçu {4} argument(s), avec les types « {5} ». Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. - Valeur non valide '{0}' spécifiée pour la 'ClassCleanupLifecycle'. Les portées prises en charge sont {1}. + Valeur non valide '{0}' spécifiée pour la 'ClassCleanupLifecycle'. Les portées prises en charge sont {1}. {Locked="ClassCleanupLifecycle"} Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. - Valeur non valide '{0}' spécifiée pour la 'Portée'. Les portées prises en charge sont {1}. + Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. {Locked="Scope"} Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. - Valeur non valide '{0}' spécifiée pour 'Workers'. La valeur doit être un entier non négatif. + Valeur non valide '{0}' spécifiée pour 'Workers'. La valeur doit être un entier non négatif. {Locked="Workers"} @@ -351,7 +351,7 @@ mais a reçu {4} argument(s), avec les types « {5} ». Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) - Parallélisation des tests activée pour {0} (Workers : {1}, Étendue : {2}). + Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) {Locked="Workers"}{Locked="Scope"} diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.it.xlf b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.it.xlf index b732bf5b5e..c76d8e8512 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.it.xlf +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.it.xlf @@ -236,17 +236,17 @@ ma ha ricevuto {4} argomenti, con tipi '{5}'. Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. - Il valore '{0}', specificato per 'ClassCleanupLifecycle', non è valido. I valori supportati per Scope sono {1}. + Il valore '{0}', specificato per 'ClassCleanupLifecycle', non è valido. I valori supportati per Scope sono {1}. {Locked="ClassCleanupLifecycle"} Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. - Il valore '{0}', specificato per 'Scope', non è valido. I valori supportati per Scope sono {1}. + Il valore '{0}', specificato per 'Scope', non è valido. I valori supportati per Scope sono {1}. {Locked="Scope"} Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. - Il valore '{0}', specificato per 'Workers', non è valido. Il valore deve essere un numero intero non negativo. + Il valore '{0}', specificato per 'Workers', non è valido. Il valore deve essere un numero intero non negativo. {Locked="Workers"} @@ -351,7 +351,7 @@ ma ha ricevuto {4} argomenti, con tipi '{5}'. Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) - Parallelizzazione test abilitata per {0} (Processi di lavoro: {1}. Ambito: {2}). + Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) {Locked="Workers"}{Locked="Scope"} diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.ja.xlf b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.ja.xlf index 31e8cc0126..132533c564 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.ja.xlf +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.ja.xlf @@ -237,17 +237,17 @@ but received {4} argument(s), with types '{5}'. Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. - 'ClassCleanupLifecycle' に無効な値 '{0}' が指定されました。サポートされているスコープは {1} です。 + 'ClassCleanupLifecycle' に無効な値 '{0}' が指定されました。サポートされているスコープは {1} です。 {Locked="ClassCleanupLifecycle"} Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. - 無効な値 '{0}' が 'Scope' に指定されました。サポートされているスコープは {1} です。 + 無効な値 '{0}' が 'Scope' に指定されました。サポートされているスコープは {1} です。 {Locked="Scope"} Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. - 無効な値 '{0}' が 'Workers' に指定されました。値は負ではない整数である必要があります。 + 無効な値 '{0}' が 'Workers' に指定されました。値は負ではない整数である必要があります。 {Locked="Workers"} @@ -352,7 +352,7 @@ but received {4} argument(s), with types '{5}'. Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) - {0} でテスト並列処理が有効にされています (Workers: {1}、Scope: {2})。 + {0} でテスト並列処理が有効にされています (Workers: {1}、Scope: {2})。 {Locked="Workers"}{Locked="Scope"} diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.ko.xlf b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.ko.xlf index 71366d3efe..55a932381d 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.ko.xlf +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.ko.xlf @@ -236,17 +236,17 @@ but received {4} argument(s), with types '{5}'. Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. - 'ClassCleanupLifecycle'에 대해 '{0}' 잘못된 값이 지정되었습니다. 지원되는 범위는 {1}입니다. + 'ClassCleanupLifecycle'에 대해 '{0}' 잘못된 값이 지정되었습니다. 지원되는 범위는 {1}입니다. {Locked="ClassCleanupLifecycle"} Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. - 'Scope'에 대해 잘못된 값 '{0}'이(가) 지정되었습니다. 지원되는 범위는 {1}입니다. + 'Scope'에 대해 잘못된 값 '{0}'이(가) 지정되었습니다. 지원되는 범위는 {1}입니다. {Locked="Scope"} Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. - 'Workers'에 대해 잘못된 값 '{0}'이(가) 지정되었습니다. 이 값은 음수가 아닌 정수여야 합니다. + 'Workers'에 대해 잘못된 값 '{0}'이(가) 지정되었습니다. 이 값은 음수가 아닌 정수여야 합니다. {Locked="Workers"} @@ -351,7 +351,7 @@ but received {4} argument(s), with types '{5}'. Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) - {0}에 대해 테스트 병렬 처리를 사용합니다(Workers: {1}, Scope: {2}). + {0}에 대해 테스트 병렬 처리를 사용합니다(Workers: {1}, Scope: {2}). {Locked="Workers"}{Locked="Scope"} diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.pl.xlf b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.pl.xlf index 1b106ba676..032a52c0eb 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.pl.xlf +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.pl.xlf @@ -236,17 +236,17 @@ ale odebrał argumenty {4} z typami „{5}”. Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. - Dla ustawienia „ClassCleanupLifecycle” określono nieprawidłową wartość „{0}”. Obsługiwane zakresy to {1}. + Dla ustawienia „ClassCleanupLifecycle” określono nieprawidłową wartość „{0}”. Obsługiwane zakresy to {1}. {Locked="ClassCleanupLifecycle"} Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. - Określono nieprawidłową wartość „{0}” dla właściwości „Scope”. Obsługiwane zakresy to {1}. + Określono nieprawidłową wartość „{0}” dla właściwości „Scope”. Obsługiwane zakresy to {1}. {Locked="Scope"} Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. - Określono nieprawidłową wartość „{0}” dla właściwości „Workers”. Wartość musi być nieujemną liczbą całkowitą. + Określono nieprawidłową wartość „{0}” dla właściwości „Workers”. Wartość musi być nieujemną liczbą całkowitą. {Locked="Workers"} @@ -351,7 +351,7 @@ ale odebrał argumenty {4} z typami „{5}”. Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) - Przetwarzanie równoległe testów włączono dla {0} (procesy robocze: {1}, zakres: {2}) + Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) {Locked="Workers"}{Locked="Scope"} diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.pt-BR.xlf b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.pt-BR.xlf index 6c79c9bcea..783f6f91f5 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.pt-BR.xlf +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.pt-BR.xlf @@ -236,17 +236,17 @@ mas {4} argumentos recebidos, com tipos '{5}'. Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. - Valor inválido '{0}' especificado para 'ClassCleanupLifecycle'. Os escopos suportados são {1}. + Valor inválido '{0}' especificado para 'ClassCleanupLifecycle'. Os escopos suportados são {1}. {Locked="ClassCleanupLifecycle"} Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. - Valor inválido '{0}' especificado para 'Scope'. Os escopos compatíveis são {1}. + Valor inválido '{0}' especificado para 'Scope'. Os escopos compatíveis são {1}. {Locked="Scope"} Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. - Valor inválido '{0}' especificado para 'Workers'. O valor deve ser um inteiro não negativo. + Valor inválido '{0}' especificado para 'Workers'. O valor deve ser um inteiro não negativo. {Locked="Workers"} @@ -351,7 +351,7 @@ mas {4} argumentos recebidos, com tipos '{5}'. Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) - Paralelização de Teste habilitada para {0} (Trabalhos: {1}, Escopo: {2}) + Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) {Locked="Workers"}{Locked="Scope"} diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.ru.xlf b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.ru.xlf index 3b75fec8a5..a8c3ef08f6 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.ru.xlf +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.ru.xlf @@ -236,17 +236,17 @@ but received {4} argument(s), with types '{5}'. Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. - Для параметра "ClassCleanupLifecycle" указано недопустимое значение "{0}". Поддерживаемые области: {1}. + Для параметра "ClassCleanupLifecycle" указано недопустимое значение "{0}". Поддерживаемые области: {1}. {Locked="ClassCleanupLifecycle"} Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. - В поле "Область" указано недопустимое значение "{0}". Поддерживаемые области: {1}. + Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. {Locked="Scope"} Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. - В поле "Рабочие роли" указано недопустимое значение "{0}". Оно должно быть неотрицательным целым числом. + Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. {Locked="Workers"} @@ -351,7 +351,7 @@ but received {4} argument(s), with types '{5}'. Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) - Включена параллелизация тестов для {0} (рабочие роли: {1}, область: {2}) + Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) {Locked="Workers"}{Locked="Scope"} diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.tr.xlf b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.tr.xlf index a32f933928..0f36222ea6 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.tr.xlf +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.tr.xlf @@ -236,17 +236,17 @@ ancak, '{5}' türünde {4} bağımsız değişken aldı. Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. - 'ClassCleanupLifecycle' için geçersiz '{0}' değeri belirtildi. Desteklenen kapsamlar {1}'dir. + 'ClassCleanupLifecycle' için geçersiz '{0}' değeri belirtildi. Desteklenen kapsamlar {1}'dir. {Locked="ClassCleanupLifecycle"} Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. - 'Scope' için geçersiz '{0}' değeri belirtildi. Desteklenen kapsamlar {1}. + 'Scope' için geçersiz '{0}' değeri belirtildi. Desteklenen kapsamlar {1}. {Locked="Scope"} Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. - 'Workers' için geçersiz '{0}' değeri belirtildi. Değer negatif olmayan bir tamsayı olmalıdır. + 'Workers' için geçersiz '{0}' değeri belirtildi. Değer negatif olmayan bir tamsayı olmalıdır. {Locked="Workers"} @@ -351,7 +351,7 @@ ancak, '{5}' türünde {4} bağımsız değişken aldı. Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) - {0} için Test Paralelleştirme etkin (Çalışanlar: {1}, Kapsam: {2}). + Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) {Locked="Workers"}{Locked="Scope"} diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.zh-Hans.xlf b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.zh-Hans.xlf index 4404a3ec6d..60889681fd 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.zh-Hans.xlf +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.zh-Hans.xlf @@ -236,17 +236,17 @@ but received {4} argument(s), with types '{5}'. Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. - 为“ClassCleanupLifecycle”指定的值“{0}”无效。支持的作用域为 {1}。 + 为“ClassCleanupLifecycle”指定的值“{0}”无效。支持的作用域为 {1}。 {Locked="ClassCleanupLifecycle"} Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. - 为“范围”指定的值“{0}”无效。受支持的范围为 {1}。 + Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. {Locked="Scope"} Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. - 为“辅助角色”指定的值“{0}”无效。该值应为非负整数。 + Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. {Locked="Workers"} @@ -351,7 +351,7 @@ but received {4} argument(s), with types '{5}'. Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) - 已为 {0} 启用测试并行化(工作线程: {1},范围: {2}) + Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) {Locked="Workers"}{Locked="Scope"} diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.zh-Hant.xlf b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.zh-Hant.xlf index 2186a8ae6f..9aa7014cf1 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.zh-Hant.xlf +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.zh-Hant.xlf @@ -236,17 +236,17 @@ but received {4} argument(s), with types '{5}'. Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. - 為 'ClassCleanupLifecycle' 指定的值 '{0}' 無效。支援的範圍為 {1}。 + 為 'ClassCleanupLifecycle' 指定的值 '{0}' 無效。支援的範圍為 {1}。 {Locked="ClassCleanupLifecycle"} Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. - 為 'Scope' 指定的值 '{0}' 無效。支援的範圍為 {1}。 + 為 'Scope' 指定的值 '{0}' 無效。支援的範圍為 {1}。 {Locked="Scope"} Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. - 為 'Workers' 的值 '{0}' 無效。值應為非負整數。 + 為 'Workers' 的值 '{0}' 無效。值應為非負整數。 {Locked="Workers"} @@ -351,7 +351,7 @@ but received {4} argument(s), with types '{5}'. Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) - 已為 {0} 啟用平行測試 (背景工作角色: {1},範圍: {2}) + Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) {Locked="Workers"}{Locked="Scope"} diff --git a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.cs.xlf b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.cs.xlf index 497fd8bdd9..501985e4ec 100644 --- a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.cs.xlf +++ b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.cs.xlf @@ -29,7 +29,7 @@ Severity to use for the reported event. Options are: error (default) and warning. - Závažnost, která se má použít pro hlášenou událost. Možnosti: chyba (výchozí) a upozornění. + Severity to use for the reported event. Options are: error (default) and warning. {Locked="error"}{Locked="warning"} diff --git a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.de.xlf b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.de.xlf index 92c6822d4e..25865f91a1 100644 --- a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.de.xlf +++ b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.de.xlf @@ -29,7 +29,7 @@ Severity to use for the reported event. Options are: error (default) and warning. - Schweregrad, der für das gemeldete Ereignis verwendet werden soll. Optionen sind: Fehler (Standard) und Warnung. + Severity to use for the reported event. Options are: error (default) and warning. {Locked="error"}{Locked="warning"} diff --git a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.es.xlf b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.es.xlf index 1d785313e5..b3cfd14eaf 100644 --- a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.es.xlf +++ b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.es.xlf @@ -29,7 +29,7 @@ Severity to use for the reported event. Options are: error (default) and warning. - Gravedad que se va a usar para el evento notificado. Las opciones son: error (valor predeterminado) y advertencia. + Severity to use for the reported event. Options are: error (default) and warning. {Locked="error"}{Locked="warning"} diff --git a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.fr.xlf b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.fr.xlf index fe1a15aaf7..9506e61cee 100644 --- a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.fr.xlf +++ b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.fr.xlf @@ -29,7 +29,7 @@ Severity to use for the reported event. Options are: error (default) and warning. - Gravité à utiliser pour l’événement signalé. Les options sont : erreur (par défaut) et avertissement. + Severity to use for the reported event. Options are: error (default) and warning. {Locked="error"}{Locked="warning"} diff --git a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.it.xlf b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.it.xlf index 92a2727133..d777478ae0 100644 --- a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.it.xlf +++ b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.it.xlf @@ -29,7 +29,7 @@ Severity to use for the reported event. Options are: error (default) and warning. - Gravità da utilizzare per l'evento segnalato. Le opzioni sono: errore (impostazione predefinita) e avviso. + Severity to use for the reported event. Options are: error (default) and warning. {Locked="error"}{Locked="warning"} diff --git a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.ja.xlf b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.ja.xlf index b60650bea9..2aded0feb3 100644 --- a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.ja.xlf +++ b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.ja.xlf @@ -29,7 +29,7 @@ Severity to use for the reported event. Options are: error (default) and warning. - 報告されたイベントに使用する重大度。オプションは、エラー (既定) と警告です。 + Severity to use for the reported event. Options are: error (default) and warning. {Locked="error"}{Locked="warning"} diff --git a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.ko.xlf b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.ko.xlf index 6da94054e6..60c865fe75 100644 --- a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.ko.xlf +++ b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.ko.xlf @@ -29,7 +29,7 @@ Severity to use for the reported event. Options are: error (default) and warning. - 보고된 이벤트에 사용할 심각도입니다. 옵션은 오류(기본값)와 경고, 두 가지입니다. + Severity to use for the reported event. Options are: error (default) and warning. {Locked="error"}{Locked="warning"} diff --git a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.pl.xlf b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.pl.xlf index 39b59857ef..a020d2abe7 100644 --- a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.pl.xlf +++ b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.pl.xlf @@ -29,7 +29,7 @@ Severity to use for the reported event. Options are: error (default) and warning. - Ważność do użycia dla zgłoszonego zdarzenia. Dostępne opcje to: błąd (domyślny) i ostrzeżenie. + Severity to use for the reported event. Options are: error (default) and warning. {Locked="error"}{Locked="warning"} diff --git a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.pt-BR.xlf b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.pt-BR.xlf index 075a8a05fc..792910812b 100644 --- a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.pt-BR.xlf +++ b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.pt-BR.xlf @@ -29,7 +29,7 @@ Severity to use for the reported event. Options are: error (default) and warning. - A gravidade que será usada para o evento relatado. As opções são: erro (padrão) e aviso. + Severity to use for the reported event. Options are: error (default) and warning. {Locked="error"}{Locked="warning"} diff --git a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.ru.xlf b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.ru.xlf index 11e6fa156f..756d7c9cae 100644 --- a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.ru.xlf +++ b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.ru.xlf @@ -29,7 +29,7 @@ Severity to use for the reported event. Options are: error (default) and warning. - Уровень серьезности, используемый для события из отчета. Параметры: error (по умолчанию) и warning. + Уровень серьезности, используемый для события из отчета. Параметры: error (по умолчанию) и warning. {Locked="error"}{Locked="warning"} diff --git a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.tr.xlf b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.tr.xlf index a2e9344690..4abfbda1c5 100644 --- a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.tr.xlf +++ b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.tr.xlf @@ -29,7 +29,7 @@ Severity to use for the reported event. Options are: error (default) and warning. - Raporlanan olay için kullanılacak önem derecesi. Seçenekler şunlardır: hata (varsayılan) ve uyarı. + Severity to use for the reported event. Options are: error (default) and warning. {Locked="error"}{Locked="warning"} From d4c7640704f4b6bb01cec7fc8b4442a57e2cc5c1 Mon Sep 17 00:00:00 2001 From: dotnet bot Date: Tue, 26 Aug 2025 04:54:23 -0700 Subject: [PATCH 435/541] Localized file check-in by OneLocBuild Task: Build definition ID 1218: Build ID 2780331 --- .../Resources/xlf/AzureDevOpsResources.zh-Hans.xlf | 2 +- .../Resources/xlf/AzureDevOpsResources.zh-Hant.xlf | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.zh-Hans.xlf b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.zh-Hans.xlf index 394763200b..2b5199f4ad 100644 --- a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.zh-Hans.xlf +++ b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.zh-Hans.xlf @@ -29,7 +29,7 @@ Severity to use for the reported event. Options are: error (default) and warning. - 要用于所报告事件的严重性。选项为: error (默认)和 warning。 + 要用于所报告事件的严重性。选项为: error (默认)和 warning。 {Locked="error"}{Locked="warning"} diff --git a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.zh-Hant.xlf b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.zh-Hant.xlf index 6feac334bd..9067fe5cc4 100644 --- a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.zh-Hant.xlf +++ b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.zh-Hant.xlf @@ -29,7 +29,7 @@ Severity to use for the reported event. Options are: error (default) and warning. - 要用於所報告事件的嚴重性。選項為: 錯誤 (預設) 警告。 + Severity to use for the reported event. Options are: error (default) and warning. {Locked="error"}{Locked="warning"} From 81122ba4a57f473582b6853b2aa800bf695727cd Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Tue, 26 Aug 2025 17:13:18 +0200 Subject: [PATCH 436/541] [main] Update dependencies from microsoft/testfx (#6438) Co-authored-by: dotnet-maestro[bot] Co-authored-by: Youssef1313 --- eng/Version.Details.xml | 8 ++-- eng/Versions.props | 4 +- .../Helpers/AcceptanceAssert.cs | 6 +-- .../UnhandledExceptionPolicyTests.cs | 4 +- .../DataRowAttributeGenerationTests.cs | 30 +++++++------- .../Generators/DynamicDataAttributeTests.cs | 4 +- .../IgnoreAttributeGenerationTests.cs | 2 +- .../Generators/StaticMethodGenerationTests.cs | 2 +- .../Generators/TestNodesGeneratorTests.cs | 40 +++++++++---------- .../Helpers/CountDownEventTests.cs | 6 +-- .../Helpers/SystemAsyncMonitorTests.cs | 4 +- .../Helpers/TaskExtensionsTests.cs | 16 ++++---- .../IPC/IPCTests.cs | 26 ++++++------ .../Logging/FileLoggerTests.cs | 6 +-- .../Messages/AsynchronousMessageBusTests.cs | 4 +- 15 files changed, 81 insertions(+), 81 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index 71f882615b..96e72403a1 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -17,13 +17,13 @@ https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage ad8260f1662c4c5e3099cb3ee5b96f38b01a6c6e - + https://github.com/microsoft/testfx - 1d18680a131cfe055c13a9807b90b7d5a5066e6b + 0956f7bd3e0fdf2aa34dd392bdefe1dd7619603a - + https://github.com/microsoft/testfx - 1d18680a131cfe055c13a9807b90b7d5a5066e6b + 0956f7bd3e0fdf2aa34dd392bdefe1dd7619603a diff --git a/eng/Versions.props b/eng/Versions.props index ea5b4bf388..9bdda405e2 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -10,7 +10,7 @@ 10.0.0-beta.25419.2 18.0.0-preview.25421.1 - 3.11.0-preview.25424.2 - 1.9.0-preview.25424.2 + 3.11.0-preview.25425.5 + 1.9.0-preview.25425.5 diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/Helpers/AcceptanceAssert.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/Helpers/AcceptanceAssert.cs index 8dd818cefa..88973c7c5d 100644 --- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/Helpers/AcceptanceAssert.cs +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/Helpers/AcceptanceAssert.cs @@ -85,7 +85,7 @@ public static void AssertOutputDoesNotMatchRegex(this TestHostResult testHostRes => Assert.IsFalse(Regex.IsMatch(testHostResult.StandardOutput, pattern), GenerateFailedAssertionMessage(testHostResult, callerMemberName: callerMemberName, callerFilePath: callerFilePath, callerLineNumber: callerLineNumber)); public static void AssertOutputContains(this TestHostResult testHostResult, string value, [CallerMemberName] string? callerMemberName = null, [CallerFilePath] string? callerFilePath = null, [CallerLineNumber] int callerLineNumber = 0) - => Assert.Contains(value, testHostResult.StandardOutput, GenerateFailedAssertionMessage(testHostResult, callerMemberName: callerMemberName, callerFilePath: callerFilePath, callerLineNumber: callerLineNumber), StringComparison.Ordinal); + => Assert.Contains(value, testHostResult.StandardOutput, StringComparison.Ordinal, GenerateFailedAssertionMessage(testHostResult, callerMemberName: callerMemberName, callerFilePath: callerFilePath, callerLineNumber: callerLineNumber)); public static void AssertExitCodeIs(this DotnetMuxerResult testHostResult, int exitCode, [CallerMemberName] string? callerMemberName = null, [CallerFilePath] string? callerFilePath = null, [CallerLineNumber] int callerLineNumber = 0) => Assert.AreEqual(exitCode, testHostResult.ExitCode, GenerateFailedAssertionMessage(testHostResult, callerMemberName: callerMemberName, callerFilePath: callerFilePath, callerLineNumber: callerLineNumber)); @@ -94,7 +94,7 @@ public static void AssertExitCodeIsNot(this DotnetMuxerResult testHostResult, in => Assert.AreNotEqual(exitCode, testHostResult.ExitCode, GenerateFailedAssertionMessage(testHostResult, callerMemberName: callerMemberName, callerFilePath: callerFilePath, callerLineNumber: callerLineNumber)); public static void AssertOutputContains(this DotnetMuxerResult dotnetMuxerResult, string value, [CallerMemberName] string? callerMemberName = null, [CallerFilePath] string? callerFilePath = null, [CallerLineNumber] int callerLineNumber = 0) - => Assert.Contains(value, dotnetMuxerResult.StandardOutput, GenerateFailedAssertionMessage(dotnetMuxerResult, callerMemberName: callerMemberName, callerFilePath: callerFilePath, callerLineNumber: callerLineNumber), StringComparison.Ordinal); + => Assert.Contains(value, dotnetMuxerResult.StandardOutput, StringComparison.Ordinal, GenerateFailedAssertionMessage(dotnetMuxerResult, callerMemberName: callerMemberName, callerFilePath: callerFilePath, callerLineNumber: callerLineNumber)); public static void AssertOutputDoesNotContain(this DotnetMuxerResult dotnetMuxerResult, string value, [CallerMemberName] string? callerMemberName = null, [CallerFilePath] string? callerFilePath = null, [CallerLineNumber] int callerLineNumber = 0) => Assert.IsFalse(dotnetMuxerResult.StandardOutput.Contains(value, StringComparison.Ordinal), GenerateFailedAssertionMessage(dotnetMuxerResult, callerMemberName: callerMemberName, callerFilePath: callerFilePath, callerLineNumber: callerLineNumber)); @@ -106,7 +106,7 @@ public static void AssertOutputDoesNotContain(this TestHostResult testHostResult => Assert.IsFalse(testHostResult.StandardOutput.Contains(value, StringComparison.Ordinal), GenerateFailedAssertionMessage(testHostResult, callerMemberName: callerMemberName, callerFilePath: callerFilePath, callerLineNumber: callerLineNumber)); public static void AssertStandardErrorContains(this TestHostResult testHostResult, string value, [CallerMemberName] string? callerMemberName = null, [CallerFilePath] string? callerFilePath = null, [CallerLineNumber] int callerLineNumber = 0) - => Assert.Contains(value, testHostResult.StandardError, GenerateFailedAssertionMessage(testHostResult, callerMemberName: callerMemberName, callerFilePath: callerFilePath, callerLineNumber: callerLineNumber), StringComparison.Ordinal); + => Assert.Contains(value, testHostResult.StandardError, StringComparison.Ordinal, GenerateFailedAssertionMessage(testHostResult, callerMemberName: callerMemberName, callerFilePath: callerFilePath, callerLineNumber: callerLineNumber)); public static void AssertOutputContainsSummary(this TestHostResult testHostResult, int failed, int passed, int skipped, bool? aborted = false, int? minimumNumberOfTests = null, [CallerMemberName] string? callerMemberName = null, [CallerFilePath] string? callerFilePath = null, [CallerLineNumber] int callerLineNumber = 0) { diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/UnhandledExceptionPolicyTests.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/UnhandledExceptionPolicyTests.cs index 57398ce7e5..69ec64519f 100644 --- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/UnhandledExceptionPolicyTests.cs +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/UnhandledExceptionPolicyTests.cs @@ -38,7 +38,7 @@ public async Task UnhandledExceptionPolicy_ConfigFile_UnobservedTaskException_Sh await clone.CopyDirectoryAsync(testHost.DirectoryName, clone.Path, retainAttributes: !RuntimeInformation.IsOSPlatform(OSPlatform.Windows)); testHost = TestInfrastructure.TestHost.LocateFrom(clone.Path, "UnhandledExceptionPolicyTests"); string configFileName = Path.Combine(testHost.DirectoryName, "UnhandledExceptionPolicyTests.testconfig.json"); - string contentFile = await File.ReadAllTextAsync(Path.Combine(testHost.DirectoryName, "UnhandledExceptionPolicyTests.testconfig.json"), TestContext.CancellationTokenSource.Token); + string contentFile = await File.ReadAllTextAsync(Path.Combine(testHost.DirectoryName, "UnhandledExceptionPolicyTests.testconfig.json"), TestContext.CancellationToken); TestHostResult? testHostResult; switch (mode) @@ -95,7 +95,7 @@ public async Task UnhandledExceptionPolicy_EnvironmentVariable_UnhandledExceptio await clone.CopyDirectoryAsync(testHost.DirectoryName, clone.Path, retainAttributes: !RuntimeInformation.IsOSPlatform(OSPlatform.Windows)); testHost = TestInfrastructure.TestHost.LocateFrom(clone.Path, "UnhandledExceptionPolicyTests"); string configFileName = Path.Combine(testHost.DirectoryName, "UnhandledExceptionPolicyTests.testconfig.json"); - string contentFile = await File.ReadAllTextAsync(Path.Combine(testHost.DirectoryName, "UnhandledExceptionPolicyTests.testconfig.json"), TestContext.CancellationTokenSource.Token); + string contentFile = await File.ReadAllTextAsync(Path.Combine(testHost.DirectoryName, "UnhandledExceptionPolicyTests.testconfig.json"), TestContext.CancellationToken); TestHostResult? testHostResult; switch (mode) diff --git a/test/UnitTests/MSTest.SourceGeneration.UnitTests/Generators/DataRowAttributeGenerationTests.cs b/test/UnitTests/MSTest.SourceGeneration.UnitTests/Generators/DataRowAttributeGenerationTests.cs index e98484efb2..4c46d80fea 100644 --- a/test/UnitTests/MSTest.SourceGeneration.UnitTests/Generators/DataRowAttributeGenerationTests.cs +++ b/test/UnitTests/MSTest.SourceGeneration.UnitTests/Generators/DataRowAttributeGenerationTests.cs @@ -100,7 +100,7 @@ public Task MethodWithUShort(ushort s) SyntaxTree? testClassTree = generatorResult.GeneratedTrees.FirstOrDefault(r => r.FilePath.EndsWith("TestClass.g.cs", StringComparison.OrdinalIgnoreCase)); testClassTree.Should().NotBeNull(); - SourceText testClass = await testClassTree!.GetTextAsync(TestContext.CancellationTokenSource.Token); + SourceText testClass = await testClassTree!.GetTextAsync(TestContext.CancellationToken); testClass.Should().ContainSourceCode(""" GetArguments = static () => new MSTF::InternalUnsafeTestArgumentsEntry[] @@ -215,7 +215,7 @@ public Task TestMethod(string s, int i, bool b, double d) SyntaxTree? testClassTree = generatorResult.GeneratedTrees.FirstOrDefault(r => r.FilePath.EndsWith("TestClass.g.cs", StringComparison.OrdinalIgnoreCase)); testClassTree.Should().NotBeNull(); - SourceText testClass = await testClassTree!.GetTextAsync(TestContext.CancellationTokenSource.Token); + SourceText testClass = await testClassTree!.GetTextAsync(TestContext.CancellationToken); testClass.Should().ContainSourceCode(""" GetArguments = static () => new MSTF::InternalUnsafeTestArgumentsEntry<(string s, int i)>[] @@ -259,7 +259,7 @@ public Task TestMethod(string a) SyntaxTree? testClassTree = generatorResult.GeneratedTrees.FirstOrDefault(r => r.FilePath.EndsWith("TestClass.g.cs", StringComparison.OrdinalIgnoreCase)); testClassTree.Should().NotBeNull(); - SourceText testClass = await testClassTree!.GetTextAsync(TestContext.CancellationTokenSource.Token); + SourceText testClass = await testClassTree!.GetTextAsync(TestContext.CancellationToken); testClass.Should().ContainSourceCode(""" GetArguments = static () => new MSTF::InternalUnsafeTestArgumentsEntry[] @@ -303,7 +303,7 @@ public Task TestMethod(Type a) SyntaxTree? testClassTree = generatorResult.GeneratedTrees.FirstOrDefault(r => r.FilePath.EndsWith("TestClass.g.cs", StringComparison.OrdinalIgnoreCase)); testClassTree.Should().NotBeNull(); - SourceText testClass = await testClassTree!.GetTextAsync(TestContext.CancellationTokenSource.Token); + SourceText testClass = await testClassTree!.GetTextAsync(TestContext.CancellationToken); testClass.Should().ContainSourceCode(""" GetArguments = static () => new MSTF::InternalUnsafeTestArgumentsEntry[] @@ -350,7 +350,7 @@ public Task TestMethod(MyEnum a) SyntaxTree? testClassTree = generatorResult.GeneratedTrees.FirstOrDefault(r => r.FilePath.EndsWith("TestClass.g.cs", StringComparison.OrdinalIgnoreCase)); testClassTree.Should().NotBeNull(); - SourceText testClass = await testClassTree!.GetTextAsync(TestContext.CancellationTokenSource.Token); + SourceText testClass = await testClassTree!.GetTextAsync(TestContext.CancellationToken); testClass.Should().ContainSourceCode(""" GetArguments = static () => new MSTF::InternalUnsafeTestArgumentsEntry[] @@ -410,7 +410,7 @@ public Task TestMethod(MyEnum a) SyntaxTree? testClassTree = generatorResult.GeneratedTrees.FirstOrDefault(r => r.FilePath.EndsWith("TestClass.g.cs", StringComparison.OrdinalIgnoreCase)); testClassTree.Should().NotBeNull(); - SourceText testClass = await testClassTree!.GetTextAsync(TestContext.CancellationTokenSource.Token); + SourceText testClass = await testClassTree!.GetTextAsync(TestContext.CancellationToken); testClass.Should().ContainSourceCode(""" GetArguments = static () => new MSTF::InternalUnsafeTestArgumentsEntry[] @@ -464,7 +464,7 @@ public Task TestMethod(ConflictingNamespace.MyEnum a) SyntaxTree? testClassTree = generatorResult.GeneratedTrees.FirstOrDefault(r => r.FilePath.EndsWith("TestClass.g.cs", StringComparison.OrdinalIgnoreCase)); testClassTree.Should().NotBeNull(); - SourceText testClass = await testClassTree!.GetTextAsync(TestContext.CancellationTokenSource.Token); + SourceText testClass = await testClassTree!.GetTextAsync(TestContext.CancellationToken); testClass.Should().ContainSourceCode(""" GetArguments = static () => new MSTF::InternalUnsafeTestArgumentsEntry[] @@ -513,7 +513,7 @@ public Task TestMethod1(string s, object a) SyntaxTree? testClassTree = generatorResult.GeneratedTrees.FirstOrDefault(r => r.FilePath.EndsWith("TestClass.g.cs", StringComparison.OrdinalIgnoreCase)); testClassTree.Should().NotBeNull(); - SourceText testClass = await testClassTree!.GetTextAsync(TestContext.CancellationTokenSource.Token); + SourceText testClass = await testClassTree!.GetTextAsync(TestContext.CancellationToken); testClass.Should().ContainSourceCode(""" GetArguments = static () => new MSTF::InternalUnsafeTestArgumentsEntry[] @@ -567,7 +567,7 @@ public Task TestMethod2(string a, string b) SyntaxTree? testClassTree = generatorResult.GeneratedTrees.FirstOrDefault(r => r.FilePath.EndsWith("TestClass.g.cs", StringComparison.OrdinalIgnoreCase)); testClassTree.Should().NotBeNull(); - SourceText testClass = await testClassTree!.GetTextAsync(TestContext.CancellationTokenSource.Token); + SourceText testClass = await testClassTree!.GetTextAsync(TestContext.CancellationToken); testClass.Should().ContainSourceCode(""" // The test method is parameterized but no argument was specified. @@ -648,7 +648,7 @@ public Task OneObjectArray(object[] args) SyntaxTree? testClassTree = generatorResult.GeneratedTrees.FirstOrDefault(r => r.FilePath.EndsWith("TestClass.g.cs", StringComparison.OrdinalIgnoreCase)); testClassTree.Should().NotBeNull(); - SourceText testClass = await testClassTree!.GetTextAsync(TestContext.CancellationTokenSource.Token); + SourceText testClass = await testClassTree!.GetTextAsync(TestContext.CancellationToken); testClass.Should().ContainSourceCode(""" GetArguments = static () => new MSTF::InternalUnsafeTestArgumentsEntry[] @@ -685,7 +685,7 @@ public Task OneIntArray(int[] args) SyntaxTree? testClassTree = generatorResult.GeneratedTrees.FirstOrDefault(r => r.FilePath.EndsWith("TestClass.g.cs", StringComparison.OrdinalIgnoreCase)); testClassTree.Should().NotBeNull(); - SourceText testClass = await testClassTree!.GetTextAsync(TestContext.CancellationTokenSource.Token); + SourceText testClass = await testClassTree!.GetTextAsync(TestContext.CancellationToken); testClass.Should().ContainSourceCode(""" GetArguments = static () => new MSTF::InternalUnsafeTestArgumentsEntry[] @@ -722,7 +722,7 @@ public Task OneStringArray(string[] args) SyntaxTree? testClassTree = generatorResult.GeneratedTrees.FirstOrDefault(r => r.FilePath.EndsWith("TestClass.g.cs", StringComparison.OrdinalIgnoreCase)); testClassTree.Should().NotBeNull(); - SourceText testClass = await testClassTree!.GetTextAsync(TestContext.CancellationTokenSource.Token); + SourceText testClass = await testClassTree!.GetTextAsync(TestContext.CancellationToken); testClass.Should().ContainSourceCode(""" GetArguments = static () => new MSTF::InternalUnsafeTestArgumentsEntry[] @@ -758,7 +758,7 @@ public Task OneParamsObjectArray2(object[] args) SyntaxTree? testClassTree = generatorResult.GeneratedTrees.FirstOrDefault(r => r.FilePath.EndsWith("TestClass.g.cs", StringComparison.OrdinalIgnoreCase)); testClassTree.Should().NotBeNull(); - SourceText testClass = await testClassTree!.GetTextAsync(TestContext.CancellationTokenSource.Token); + SourceText testClass = await testClassTree!.GetTextAsync(TestContext.CancellationToken); testClass.Should().ContainSourceCode(""" GetArguments = static () => new MSTF::InternalUnsafeTestArgumentsEntry[] @@ -796,7 +796,7 @@ public Task OneIntArray(object[] args) SyntaxTree? testClassTree = generatorResult.GeneratedTrees.FirstOrDefault(r => r.FilePath.EndsWith("TestClass.g.cs", StringComparison.OrdinalIgnoreCase)); testClassTree.Should().NotBeNull(); - SourceText testClass = await testClassTree!.GetTextAsync(TestContext.CancellationTokenSource.Token); + SourceText testClass = await testClassTree!.GetTextAsync(TestContext.CancellationToken); testClass.Should().ContainSourceCode(""" GetArguments = static () => new MSTF::InternalUnsafeTestArgumentsEntry[] @@ -833,7 +833,7 @@ public Task TwoObjectArrays(object[] args, object[] args2) SyntaxTree? testClassTree = generatorResult.GeneratedTrees.FirstOrDefault(r => r.FilePath.EndsWith("TestClass.g.cs", StringComparison.OrdinalIgnoreCase)); testClassTree.Should().NotBeNull(); - SourceText testClass = await testClassTree!.GetTextAsync(TestContext.CancellationTokenSource.Token); + SourceText testClass = await testClassTree!.GetTextAsync(TestContext.CancellationToken); testClass.Should().ContainSourceCode(""" GetArguments = static () => new MSTF::InternalUnsafeTestArgumentsEntry<(object[] args, object[] args2)>[] diff --git a/test/UnitTests/MSTest.SourceGeneration.UnitTests/Generators/DynamicDataAttributeTests.cs b/test/UnitTests/MSTest.SourceGeneration.UnitTests/Generators/DynamicDataAttributeTests.cs index e53515cd66..7ec15f78af 100644 --- a/test/UnitTests/MSTest.SourceGeneration.UnitTests/Generators/DynamicDataAttributeTests.cs +++ b/test/UnitTests/MSTest.SourceGeneration.UnitTests/Generators/DynamicDataAttributeTests.cs @@ -49,7 +49,7 @@ public void TestMethod(int expected, int actualPlus1) SyntaxTree? testClassTree = generatorResult.GeneratedTrees.FirstOrDefault(r => r.FilePath.EndsWith("TestClass.g.cs", StringComparison.OrdinalIgnoreCase)); testClassTree.Should().NotBeNull(); - SourceText testClass = await testClassTree!.GetTextAsync(TestContext.CancellationTokenSource.Token); + SourceText testClass = await testClassTree!.GetTextAsync(TestContext.CancellationToken); testClass.Should().ContainSourceCode(""" GetArguments = static () => { @@ -101,7 +101,7 @@ public static IEnumerable Data() => new[] SyntaxTree? testClassTree = generatorResult.GeneratedTrees.FirstOrDefault(r => r.FilePath.EndsWith("TestClass.g.cs", StringComparison.OrdinalIgnoreCase)); testClassTree.Should().NotBeNull(); - SourceText testClass = await testClassTree!.GetTextAsync(TestContext.CancellationTokenSource.Token); + SourceText testClass = await testClassTree!.GetTextAsync(TestContext.CancellationToken); testClass.Should().ContainSourceCode(""" GetArguments = static () => { diff --git a/test/UnitTests/MSTest.SourceGeneration.UnitTests/Generators/IgnoreAttributeGenerationTests.cs b/test/UnitTests/MSTest.SourceGeneration.UnitTests/Generators/IgnoreAttributeGenerationTests.cs index e80811eaba..aacf0c8eee 100644 --- a/test/UnitTests/MSTest.SourceGeneration.UnitTests/Generators/IgnoreAttributeGenerationTests.cs +++ b/test/UnitTests/MSTest.SourceGeneration.UnitTests/Generators/IgnoreAttributeGenerationTests.cs @@ -64,7 +64,7 @@ public void IgnoredVoidMethodWithReason() { } SyntaxTree? testClassTree = generatorResult.GeneratedTrees.FirstOrDefault(r => r.FilePath.EndsWith("TestClass.g.cs", StringComparison.OrdinalIgnoreCase)); testClassTree.Should().NotBeNull(); - SourceText testClass = await testClassTree!.GetTextAsync(TestContext.CancellationTokenSource.Token); + SourceText testClass = await testClassTree!.GetTextAsync(TestContext.CancellationToken); testClass.Should().ContainSourceCode("""StableUid = "TestAssembly.MyNamespace.TestClass.TestMethod1()","""); diff --git a/test/UnitTests/MSTest.SourceGeneration.UnitTests/Generators/StaticMethodGenerationTests.cs b/test/UnitTests/MSTest.SourceGeneration.UnitTests/Generators/StaticMethodGenerationTests.cs index aa801b8bfd..42107642a3 100644 --- a/test/UnitTests/MSTest.SourceGeneration.UnitTests/Generators/StaticMethodGenerationTests.cs +++ b/test/UnitTests/MSTest.SourceGeneration.UnitTests/Generators/StaticMethodGenerationTests.cs @@ -48,7 +48,7 @@ public static void StaticTestMethod() { } SyntaxTree? testClassTree = generatorResult.GeneratedTrees.FirstOrDefault(r => r.FilePath.EndsWith("TestClass.g.cs", StringComparison.OrdinalIgnoreCase)); testClassTree.Should().NotBeNull(); - SourceText testClass = await testClassTree!.GetTextAsync(TestContext.CancellationTokenSource.Token); + SourceText testClass = await testClassTree!.GetTextAsync(TestContext.CancellationToken); testClass.Should().ContainSourceCode("""StableUid = "TestAssembly.MyNamespace.TestClass.TestMethod1()","""); diff --git a/test/UnitTests/MSTest.SourceGeneration.UnitTests/Generators/TestNodesGeneratorTests.cs b/test/UnitTests/MSTest.SourceGeneration.UnitTests/Generators/TestNodesGeneratorTests.cs index a66808826e..6ceb1a9ed4 100644 --- a/test/UnitTests/MSTest.SourceGeneration.UnitTests/Generators/TestNodesGeneratorTests.cs +++ b/test/UnitTests/MSTest.SourceGeneration.UnitTests/Generators/TestNodesGeneratorTests.cs @@ -46,7 +46,7 @@ public Task TestMethod() generatorResult.AssertSuccessfulGeneration(); generatorResult.GeneratedTrees.Should().HaveCount(3); - SourceText myTypeSource = await generatorResult.RunResult.GeneratedTrees[0].GetTextAsync(TestContext.CancellationTokenSource.Token); + SourceText myTypeSource = await generatorResult.RunResult.GeneratedTrees[0].GetTextAsync(TestContext.CancellationToken); myTypeSource.Should().ContainSourceCode(""" public static readonly MSTF::TestNode TestNode = new MSTF::TestNode { @@ -91,7 +91,7 @@ public Task TestMethod() }; """); - SourceText rootSource = await generatorResult.RunResult.GeneratedTrees[1].GetTextAsync(TestContext.CancellationTokenSource.Token); + SourceText rootSource = await generatorResult.RunResult.GeneratedTrees[1].GetTextAsync(TestContext.CancellationToken); rootSource.Should().ContainSourceCode(""" MSTF::TestNode root = new MSTF::TestNode { @@ -225,7 +225,7 @@ public Task TestMethod() generatorResult.AssertSuccessfulGeneration(); generatorResult.GeneratedTrees.Should().HaveCount(3); - SourceText myTypeSource = await generatorResult.RunResult.GeneratedTrees[0].GetTextAsync(TestContext.CancellationTokenSource.Token); + SourceText myTypeSource = await generatorResult.RunResult.GeneratedTrees[0].GetTextAsync(TestContext.CancellationToken); myTypeSource.Should().ContainSourceCode(""" public static readonly MSTF::TestNode TestNode = new MSTF::TestNode { @@ -332,7 +332,7 @@ public Task TestMethod() generatorResult.AssertSuccessfulGeneration(); generatorResult.GeneratedTrees.Should().HaveCount(4); - SourceText myBaseClassSource = await generatorResult.GeneratedTrees[0].GetTextAsync(TestContext.CancellationTokenSource.Token); + SourceText myBaseClassSource = await generatorResult.GeneratedTrees[0].GetTextAsync(TestContext.CancellationToken); myBaseClassSource.Should().ContainSourceCode(""" public static readonly MSTF::TestNode TestNode = new MSTF::TestNode { @@ -377,7 +377,7 @@ public Task TestMethod() }; """); - SourceText myTypeSource = await generatorResult.GeneratedTrees[1].GetTextAsync(TestContext.CancellationTokenSource.Token); + SourceText myTypeSource = await generatorResult.GeneratedTrees[1].GetTextAsync(TestContext.CancellationToken); myTypeSource.Should().ContainSourceCode(""" public static readonly MSTF::TestNode TestNode = new MSTF::TestNode { @@ -490,7 +490,7 @@ public Task TestMethod() generatorResult.AssertSuccessfulGeneration(); generatorResult.RunResult.GeneratedTrees.Should().HaveCount(3); - SourceText testClass = await generatorResult.GeneratedTrees[0].GetTextAsync(TestContext.CancellationTokenSource.Token); + SourceText testClass = await generatorResult.GeneratedTrees[0].GetTextAsync(TestContext.CancellationToken); testClass.Should().ContainSourceCode( "public static readonly MSTF::TestNode TestNode = new MSTF::TestNode", @@ -535,7 +535,7 @@ public Task TestMethod2() SyntaxTree? testClassTree = generatorResult.GeneratedTrees.FirstOrDefault(r => r.FilePath.EndsWith("TestSubClass.g.cs", StringComparison.OrdinalIgnoreCase)); testClassTree.Should().NotBeNull(); - SourceText testClass = await testClassTree!.GetTextAsync(TestContext.CancellationTokenSource.Token); + SourceText testClass = await testClassTree!.GetTextAsync(TestContext.CancellationToken); testClass.Should().ContainSourceCode(""" new MSTF::InternalUnsafeAsyncActionTestNode { @@ -591,7 +591,7 @@ public Task TestMethod() generatorResult.AssertSuccessfulGeneration(); generatorResult.RunResult.GeneratedTrees.Should().HaveCount(3); - SourceText myTypeSource = await generatorResult.GeneratedTrees[0].GetTextAsync(TestContext.CancellationTokenSource.Token); + SourceText myTypeSource = await generatorResult.GeneratedTrees[0].GetTextAsync(TestContext.CancellationToken); myTypeSource.Should().ContainSourceCode(""" public static readonly MSTF::TestNode TestNode = new MSTF::TestNode { @@ -603,7 +603,7 @@ public Task TestMethod() }, """); - SourceText rootSource = await generatorResult.GeneratedTrees[1].GetTextAsync(TestContext.CancellationTokenSource.Token); + SourceText rootSource = await generatorResult.GeneratedTrees[1].GetTextAsync(TestContext.CancellationToken); rootSource.Should().ContainSourceCode(""" MSTF::TestNode root = new MSTF::TestNode { @@ -668,7 +668,7 @@ public Task TestMethod() generatorResult.AssertSuccessfulGeneration(); generatorResult.GeneratedTrees.Should().HaveCount(4); - SourceText rootSource = await generatorResult.RunResult.GeneratedTrees[2].GetTextAsync(TestContext.CancellationTokenSource.Token); + SourceText rootSource = await generatorResult.RunResult.GeneratedTrees[2].GetTextAsync(TestContext.CancellationToken); rootSource.Should().ContainSourceCode(""" ColGen::List namespace1Tests = new(); namespace1Tests.Add(MyNamespace_MyType1.TestNode); @@ -730,7 +730,7 @@ public Task InitializeAsync(InitializationContext context) generatorResult.AssertSuccessfulGeneration(); generatorResult.GeneratedTrees.Should().HaveCount(2); - SourceText myTypeSource = await generatorResult.RunResult.GeneratedTrees[0].GetTextAsync(TestContext.CancellationTokenSource.Token); + SourceText myTypeSource = await generatorResult.RunResult.GeneratedTrees[0].GetTextAsync(TestContext.CancellationToken); // The test node for the type should not have a test node for the InitializeAsync method. myTypeSource.Should().NotContain("StableUid = \"TestAssembly.MyNamespace.MyType.InitializeAsync\""); @@ -788,7 +788,7 @@ public Task CleanupAsync(CleanupContext context) generatorResult.AssertSuccessfulGeneration(); generatorResult.GeneratedTrees.Should().HaveCount(2); - SourceText myTypeSource = await generatorResult.RunResult.GeneratedTrees[0].GetTextAsync(TestContext.CancellationTokenSource.Token); + SourceText myTypeSource = await generatorResult.RunResult.GeneratedTrees[0].GetTextAsync(TestContext.CancellationToken); // The test node for the type should not have a test node for the CleanupAsync method. myTypeSource.Should().NotContain("StableUid = \"TestAssembly.MyNamespace.MyType.CleanupAsync\""); @@ -853,7 +853,7 @@ public void Dispose() generatorResult.AssertSuccessfulGeneration(); generatorResult.GeneratedTrees.Should().HaveCount(2); - SourceText myTypeSource = await generatorResult.RunResult.GeneratedTrees[0].GetTextAsync(TestContext.CancellationTokenSource.Token); + SourceText myTypeSource = await generatorResult.RunResult.GeneratedTrees[0].GetTextAsync(TestContext.CancellationToken); // The test node for the type should not have a test node for the Dispose method. myTypeSource.Should().NotContain("StableUid = \"TestAssembly.MyNamespace.MyType.Dispose\""); @@ -911,7 +911,7 @@ public ValueTask DisposeAsync() generatorResult.AssertSuccessfulGeneration(); generatorResult.GeneratedTrees.Should().HaveCount(2); - SourceText myTypeSource = await generatorResult.RunResult.GeneratedTrees[0].GetTextAsync(TestContext.CancellationTokenSource.Token); + SourceText myTypeSource = await generatorResult.RunResult.GeneratedTrees[0].GetTextAsync(TestContext.CancellationToken); // The test node for the type should not have a test node for the DisposeAsync method. myTypeSource.Should().NotContain("StableUid = \"TestAssembly.MyNamespace.MyType.DisposeAsync\""); @@ -973,7 +973,7 @@ public void Dispose() generatorResult.AssertSuccessfulGeneration(); generatorResult.GeneratedTrees.Should().HaveCount(2); - SourceText myTypeSource = await generatorResult.RunResult.GeneratedTrees[0].GetTextAsync(TestContext.CancellationTokenSource.Token); + SourceText myTypeSource = await generatorResult.RunResult.GeneratedTrees[0].GetTextAsync(TestContext.CancellationToken); // The body of the test node for the method should call only DisposeAsync after calling the test method. myTypeSource.Should().ContainSourceCode(""" @@ -1048,21 +1048,21 @@ public Task CleanupAsync(CleanupContext context) generatorResult.AssertSuccessfulGeneration(); generatorResult.GeneratedTrees.Should().HaveCount(4); - SourceText myClass1Source = await generatorResult.RunResult.GeneratedTrees[0].GetTextAsync(TestContext.CancellationTokenSource.Token); + SourceText myClass1Source = await generatorResult.RunResult.GeneratedTrees[0].GetTextAsync(TestContext.CancellationToken); myClass1Source.Should().ContainSourceCode(""" new MSTF::InternalUnsafeAsyncActionTestNode { StableUid = "TestAssembly.MyNamespace.MyClass1.TestMethod()", """); - SourceText myClass2Source = await generatorResult.RunResult.GeneratedTrees[1].GetTextAsync(TestContext.CancellationTokenSource.Token); + SourceText myClass2Source = await generatorResult.RunResult.GeneratedTrees[1].GetTextAsync(TestContext.CancellationToken); myClass2Source.Should().ContainSourceCode(""" new MSTF::InternalUnsafeAsyncActionTestNode { StableUid = "TestAssembly.MyNamespace.MyClass2.TestMethod()", """); - SourceText myClass3Source = await generatorResult.RunResult.GeneratedTrees[2].GetTextAsync(TestContext.CancellationTokenSource.Token); + SourceText myClass3Source = await generatorResult.RunResult.GeneratedTrees[2].GetTextAsync(TestContext.CancellationToken); myClass3Source.Should().ContainSourceCode(""" new MSTF::InternalUnsafeAsyncActionTestNode { @@ -1118,7 +1118,7 @@ public Task TestMethod4() generatorResult.AssertFailedGeneration("*error CS0619: 'MyType.TestMethod4()' is obsolete*"); generatorResult.GeneratedTrees.Should().HaveCount(3); - SourceText myTypeSource = await generatorResult.RunResult.GeneratedTrees[0].GetTextAsync(TestContext.CancellationTokenSource.Token); + SourceText myTypeSource = await generatorResult.RunResult.GeneratedTrees[0].GetTextAsync(TestContext.CancellationToken); myTypeSource.Should().ContainSourceCode(""" #pragma warning disable CS0612 // Type or member is obsolete await instance.TestMethod1(); @@ -1202,7 +1202,7 @@ public Task TestMethod2() generatorResult.AssertSuccessfulGeneration(); generatorResult.GeneratedTrees.Should().HaveCount(3); - SourceText myTypeSource = await generatorResult.RunResult.GeneratedTrees[0].GetTextAsync(TestContext.CancellationTokenSource.Token); + SourceText myTypeSource = await generatorResult.RunResult.GeneratedTrees[0].GetTextAsync(TestContext.CancellationToken); myTypeSource.Should().ContainSourceCode(""" public static class MyNamespace_MyType { diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Helpers/CountDownEventTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Helpers/CountDownEventTests.cs index 5659911c9d..49f81499da 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Helpers/CountDownEventTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Helpers/CountDownEventTests.cs @@ -17,11 +17,11 @@ public async Task CountDownEvent_WaitAsync_Succeeded() Task waiter1 = Task.Run(() => countdownEvent.WaitAsync(CancellationToken.None)); Task waiter2 = Task.Run(() => countdownEvent.WaitAsync(CancellationToken.None)); - await Task.Delay(500, TestContext.CancellationTokenSource.Token); + await Task.Delay(500, TestContext.CancellationToken); countdownEvent.Signal(); - await Task.Delay(500, TestContext.CancellationTokenSource.Token); + await Task.Delay(500, TestContext.CancellationToken); countdownEvent.Signal(); - await Task.Delay(500, TestContext.CancellationTokenSource.Token); + await Task.Delay(500, TestContext.CancellationToken); countdownEvent.Signal(); await waiter1.TimeoutAfterAsync(TimeSpan.FromSeconds(30)); diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Helpers/SystemAsyncMonitorTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Helpers/SystemAsyncMonitorTests.cs index 966a695bb3..c8718a391e 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Helpers/SystemAsyncMonitorTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Helpers/SystemAsyncMonitorTests.cs @@ -19,7 +19,7 @@ public async Task AsyncMonitor_ShouldCorrectlyLock() var stopwatch = Stopwatch.StartNew(); for (int i = 0; i < 3; i++) { - tasks.Add(Task.Run(TestLock, TestContext.CancellationTokenSource.Token)); + tasks.Add(Task.Run(TestLock, TestContext.CancellationToken)); } await Task.WhenAll([.. tasks]); @@ -39,7 +39,7 @@ async Task TestLock() } lockState = true; - await Task.Delay(1000, TestContext.CancellationTokenSource.Token); + await Task.Delay(1000, TestContext.CancellationToken); lockState = false; } } diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Helpers/TaskExtensionsTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Helpers/TaskExtensionsTests.cs index cc51318fd9..d418c53c16 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Helpers/TaskExtensionsTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Helpers/TaskExtensionsTests.cs @@ -13,19 +13,19 @@ public sealed class TaskExtensionsTests [TestMethod] public async Task TimeoutAfterAsync_Succeeds() => await Assert.ThrowsAsync(async () => - await Task.Delay(TimeSpan.FromSeconds(60), TestContext.CancellationTokenSource.Token).TimeoutAfterAsync(TimeSpan.FromSeconds(2))); + await Task.Delay(TimeSpan.FromSeconds(60), TestContext.CancellationToken).TimeoutAfterAsync(TimeSpan.FromSeconds(2))); [TestMethod] public async Task TimeoutAfterAsync_CancellationToken_Succeeds() => await Assert.ThrowsAsync(async () => - await Task.Delay(TimeSpan.FromSeconds(60), TestContext.CancellationTokenSource.Token).TimeoutAfterAsync( + await Task.Delay(TimeSpan.FromSeconds(60), TestContext.CancellationToken).TimeoutAfterAsync( TimeSpan.FromSeconds(30), new CancellationTokenSource(TimeSpan.FromSeconds(2)).Token)); [TestMethod] public async Task TimeoutAfterAsync_CancellationTokenNone_Succeeds() => await Assert.ThrowsAsync(async () => - await Task.Delay(TimeSpan.FromSeconds(60), TestContext.CancellationTokenSource.Token).TimeoutAfterAsync( + await Task.Delay(TimeSpan.FromSeconds(60), TestContext.CancellationToken).TimeoutAfterAsync( TimeSpan.FromSeconds(2), CancellationToken.None)); @@ -80,13 +80,13 @@ await Assert.ThrowsAsync(async () => await Task.Run( async () => { - await Task.Delay(TimeSpan.FromSeconds(10), TestContext.CancellationTokenSource.Token); + await Task.Delay(TimeSpan.FromSeconds(10), TestContext.CancellationToken); waitException.Set(); throw new InvalidOperationException(); - }, TestContext.CancellationTokenSource.Token).WithCancellationAsync(new CancellationTokenSource(TimeSpan.FromSeconds(1)).Token)); + }, TestContext.CancellationToken).WithCancellationAsync(new CancellationTokenSource(TimeSpan.FromSeconds(1)).Token)); waitException.WaitOne(); - await Task.Delay(TimeSpan.FromSeconds(4), TestContext.CancellationTokenSource.Token); + await Task.Delay(TimeSpan.FromSeconds(4), TestContext.CancellationToken); }, 3, TimeSpan.FromSeconds(3)); [TestMethod] @@ -98,7 +98,7 @@ public async Task CancellationAsyncWithReturnValue_ObserveException_Succeeds() await Assert.ThrowsAsync(async () => await Task.Run(async () => { - await Task.Delay(TimeSpan.FromSeconds(10), TestContext.CancellationTokenSource.Token); + await Task.Delay(TimeSpan.FromSeconds(10), TestContext.CancellationToken); try { return 2; @@ -113,7 +113,7 @@ await Assert.ThrowsAsync(async () }).WithCancellationAsync(new CancellationTokenSource(TimeSpan.FromSeconds(1)).Token)); waitException.WaitOne(); - await Task.Delay(TimeSpan.FromSeconds(4), TestContext.CancellationTokenSource.Token); + await Task.Delay(TimeSpan.FromSeconds(4), TestContext.CancellationToken); }, 3, TimeSpan.FromSeconds(3)); private static async Task DoSomething() diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/IPCTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/IPCTests.cs index d8126aea94..3a9fe86375 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/IPCTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/IPCTests.cs @@ -41,9 +41,9 @@ public async Task SingleConnectionNamedPipeServer_MultipleConnection_Fails() new SystemEnvironment(), new Mock().Object, new SystemTask(), - _testContext.CancellationTokenSource.Token); + _testContext.CancellationToken); - await singleConnectionNamedPipeServer.WaitConnectionAsync(_testContext.CancellationTokenSource.Token); + await singleConnectionNamedPipeServer.WaitConnectionAsync(_testContext.CancellationToken); openedPipe.Add(singleConnectionNamedPipeServer); } } @@ -52,11 +52,11 @@ public async Task SingleConnectionNamedPipeServer_MultipleConnection_Fails() exceptions.Add(ex); waitException.Set(); } - }, _testContext.CancellationTokenSource.Token); + }, _testContext.CancellationToken); NamedPipeClient namedPipeClient1 = new(pipeNameDescription.Name); - await namedPipeClient1.ConnectAsync(_testContext.CancellationTokenSource.Token); - waitException.Wait(_testContext.CancellationTokenSource.Token); + await namedPipeClient1.ConnectAsync(_testContext.CancellationToken); + waitException.Wait(_testContext.CancellationToken); Assert.HasCount(1, openedPipe); Assert.HasCount(1, exceptions); @@ -107,7 +107,7 @@ public async Task SingleConnectionNamedPipeServer_RequestReplySerialization_Succ manualResetEventSlim.Set(); break; } - catch (OperationCanceledException ct) when (ct.CancellationToken == _testContext.CancellationTokenSource.Token) + catch (OperationCanceledException ct) when (ct.CancellationToken == _testContext.CancellationToken) { throw new OperationCanceledException("SingleConnectionNamedPipeServer_RequestReplySerialization_Succeeded cancellation during connect, testContext.CancellationTokenSource.Token"); } @@ -119,7 +119,7 @@ public async Task SingleConnectionNamedPipeServer_RequestReplySerialization_Succ { } } - }, _testContext.CancellationTokenSource.Token); + }, _testContext.CancellationToken); NamedPipeServer singleConnectionNamedPipeServer = new( pipeNameDescription, request => @@ -136,7 +136,7 @@ public async Task SingleConnectionNamedPipeServer_RequestReplySerialization_Succ singleConnectionNamedPipeServer.RegisterSerializer(new IntMessageSerializer(), typeof(IntMessage)); singleConnectionNamedPipeServer.RegisterSerializer(new LongMessageSerializer(), typeof(LongMessage)); await singleConnectionNamedPipeServer.WaitConnectionAsync(CancellationToken.None); - manualResetEventSlim.Wait(_testContext.CancellationTokenSource.Token); + manualResetEventSlim.Wait(_testContext.CancellationToken); await clientConnected.WithCancellationAsync(CancellationToken.None); @@ -184,7 +184,7 @@ public async Task ConnectionNamedPipeServer_MultipleConnection_Succeeds() new Mock().Object, new SystemTask(), maxNumberOfServerInstances: 3, - _testContext.CancellationTokenSource.Token)); + _testContext.CancellationToken)); } IOException exception = Assert.ThrowsExactly(() => @@ -195,7 +195,7 @@ public async Task ConnectionNamedPipeServer_MultipleConnection_Succeeds() new Mock().Object, new SystemTask(), maxNumberOfServerInstances: 3, - _testContext.CancellationTokenSource.Token)); + _testContext.CancellationToken)); Assert.Contains("All pipe instances are busy.", exception.Message); List waitConnectionTask = []; @@ -205,9 +205,9 @@ public async Task ConnectionNamedPipeServer_MultipleConnection_Succeeds() waitConnectionTask.Add(Task.Run( async () => { - await namedPipeServer.WaitConnectionAsync(_testContext.CancellationTokenSource.Token); + await namedPipeServer.WaitConnectionAsync(_testContext.CancellationToken); Interlocked.Increment(ref connectionCompleted); - }, _testContext.CancellationTokenSource.Token)); + }, _testContext.CancellationToken)); } List connectedClients = []; @@ -215,7 +215,7 @@ public async Task ConnectionNamedPipeServer_MultipleConnection_Succeeds() { NamedPipeClient namedPipeClient = new(pipeNameDescription.Name); connectedClients.Add(namedPipeClient); - await namedPipeClient.ConnectAsync(_testContext.CancellationTokenSource.Token); + await namedPipeClient.ConnectAsync(_testContext.CancellationToken); } await Task.WhenAll([.. waitConnectionTask]); diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Logging/FileLoggerTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Logging/FileLoggerTests.cs index fce8ad8527..90e869eb9a 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Logging/FileLoggerTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Logging/FileLoggerTests.cs @@ -176,15 +176,15 @@ public async Task Log_WhenSyncFlush_StreamWriterIsCalledOnlyWhenLogLevelAllowsIt if (LogTestHelpers.IsLogEnabled(defaultLogLevel, currentLogLevel)) { - await _memoryStream.FlushAsync(TestContext.CancellationTokenSource.Token); + await _memoryStream.FlushAsync(TestContext.CancellationToken); int iteration = 0; while (_memoryStream.Length == 0 && iteration < 10) { iteration++; - await Task.Delay(200, TestContext.CancellationTokenSource.Token); + await Task.Delay(200, TestContext.CancellationToken); } - await _memoryStream.FlushAsync(TestContext.CancellationTokenSource.Token); + await _memoryStream.FlushAsync(TestContext.CancellationToken); _mockConsole.Verify(x => x.WriteLine(It.IsAny()), Times.Never); Assert.AreEqual($"[00:00:00.000 Test - {currentLogLevel}] Message{Environment.NewLine}", Encoding.Default.GetString(_memoryStream.ToArray())); diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Messages/AsynchronousMessageBusTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Messages/AsynchronousMessageBusTests.cs index 7c69ab1d7b..dce3b35b02 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Messages/AsynchronousMessageBusTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Messages/AsynchronousMessageBusTests.cs @@ -107,7 +107,7 @@ public async Task Consumers_ConsumeData_ShouldNotMissAnyPayload() Random random = new(); for (int i = 0; i < totalConsumers; i++) { - DummyConsumer dummyConsumer = new(async _ => await Task.Delay(random.Next(40, 80), TestContext.CancellationTokenSource.Token)); + DummyConsumer dummyConsumer = new(async _ => await Task.Delay(random.Next(40, 80), TestContext.CancellationToken)); dummyConsumers.Add(dummyConsumer); } @@ -122,7 +122,7 @@ public async Task Consumers_ConsumeData_ShouldNotMissAnyPayload() proxy.SetBuiltMessageBus(asynchronousMessageBus); DummyConsumer.DummyProducer producer = new(); - await Task.WhenAll([.. Enumerable.Range(1, totalPayloads).Select(i => Task.Run(async () => await proxy.PublishAsync(producer, new DummyConsumer.DummyData { Data = i }), TestContext.CancellationTokenSource.Token))]); + await Task.WhenAll([.. Enumerable.Range(1, totalPayloads).Select(i => Task.Run(async () => await proxy.PublishAsync(producer, new DummyConsumer.DummyData { Data = i }), TestContext.CancellationToken))]); await proxy.DrainDataAsync(); From d2ced942a709b5936d3e7f18d2f16705b391f519 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Tue, 26 Aug 2025 17:14:28 +0200 Subject: [PATCH 437/541] Fix build incrementality (#6443) --- Directory.Build.targets | 40 +++++++++++++++++++ ...sion.cs.template => BuildInfo.cs.template} | 0 .../MSTest.Engine/MSTest.Engine.csproj | 32 +-------------- ...sion.cs.template => BuildInfo.cs.template} | 0 .../MSTest.TestAdapter.csproj | 22 +--------- ...sion.cs.template => BuildInfo.cs.template} | 0 .../Microsoft.Testing.Platform.csproj | 18 +-------- 7 files changed, 45 insertions(+), 67 deletions(-) rename src/Adapter/MSTest.Engine/{RepositoryVersion.cs.template => BuildInfo.cs.template} (100%) rename src/Adapter/MSTest.TestAdapter/{MSTestVersion.cs.template => BuildInfo.cs.template} (100%) rename src/Platform/Microsoft.Testing.Platform/{PlatformVersion.cs.template => BuildInfo.cs.template} (100%) diff --git a/Directory.Build.targets b/Directory.Build.targets index f509b732e7..0b157c8623 100644 --- a/Directory.Build.targets +++ b/Directory.Build.targets @@ -29,4 +29,44 @@ + + + + + + + <_TemplateProperties>Version=$(Version) + <_TemplatePropertiesCacheFile>$(IntermediateOutputPath)$(MSBuildProjectFile).GenerateVersionSourceFile.cache + + + + + + + + + + + + + + + + + + + <_TemplateCsproj Include="$(MSBuildProjectDirectory)/BuildInfo.cs.template" Destination="$(IntermediateOutputPath)BuildInfo.cs" /> + + + + + + + + diff --git a/src/Adapter/MSTest.Engine/RepositoryVersion.cs.template b/src/Adapter/MSTest.Engine/BuildInfo.cs.template similarity index 100% rename from src/Adapter/MSTest.Engine/RepositoryVersion.cs.template rename to src/Adapter/MSTest.Engine/BuildInfo.cs.template diff --git a/src/Adapter/MSTest.Engine/MSTest.Engine.csproj b/src/Adapter/MSTest.Engine/MSTest.Engine.csproj index 1f19b9202b..a0ab34f686 100644 --- a/src/Adapter/MSTest.Engine/MSTest.Engine.csproj +++ b/src/Adapter/MSTest.Engine/MSTest.Engine.csproj @@ -13,6 +13,8 @@ $(NoWarn);CS1591 true + + true @@ -28,19 +30,6 @@ true - - - false - - - - - - - - - - @@ -83,23 +72,6 @@ This package provides a new experimental engine for MSTest test framework.]]> - - - - - - - <_TemplateProperties>Version=$(Version) - - - <_TemplateCsproj Include="$(MSBuildProjectDirectory)/RepositoryVersion.cs.template" Destination="$(IntermediateOutputPath)/RepositoryVersion.cs" /> - - - - - - - diff --git a/src/Adapter/MSTest.TestAdapter/MSTestVersion.cs.template b/src/Adapter/MSTest.TestAdapter/BuildInfo.cs.template similarity index 100% rename from src/Adapter/MSTest.TestAdapter/MSTestVersion.cs.template rename to src/Adapter/MSTest.TestAdapter/BuildInfo.cs.template diff --git a/src/Adapter/MSTest.TestAdapter/MSTest.TestAdapter.csproj b/src/Adapter/MSTest.TestAdapter/MSTest.TestAdapter.csproj index 2dcf69d6e8..2537f7345f 100644 --- a/src/Adapter/MSTest.TestAdapter/MSTest.TestAdapter.csproj +++ b/src/Adapter/MSTest.TestAdapter/MSTest.TestAdapter.csproj @@ -37,6 +37,8 @@ $(NoWarn);NU5127;NU5128;NU5100 + + true @@ -90,26 +92,6 @@ - - - - - - - <_TemplateProperties>Version=$(Version) - - - <_TemplateCsproj Include="$(MSBuildProjectDirectory)/MSTestVersion.cs.template" Destination="$(IntermediateOutputPath)/MSTestVersion.cs" /> - - - - - - - - - - diff --git a/src/Platform/Microsoft.Testing.Platform/PlatformVersion.cs.template b/src/Platform/Microsoft.Testing.Platform/BuildInfo.cs.template similarity index 100% rename from src/Platform/Microsoft.Testing.Platform/PlatformVersion.cs.template rename to src/Platform/Microsoft.Testing.Platform/BuildInfo.cs.template diff --git a/src/Platform/Microsoft.Testing.Platform/Microsoft.Testing.Platform.csproj b/src/Platform/Microsoft.Testing.Platform/Microsoft.Testing.Platform.csproj index 0e41d8bb55..81b4e1f2d5 100644 --- a/src/Platform/Microsoft.Testing.Platform/Microsoft.Testing.Platform.csproj +++ b/src/Platform/Microsoft.Testing.Platform/Microsoft.Testing.Platform.csproj @@ -3,6 +3,7 @@ $(MicrosoftTestingTargetFrameworks);netstandard2.0 true + true @@ -84,26 +85,9 @@ This package provides the core platform and the .NET implementation of the proto - - - - - <_TemplateProperties>Version=$(Version) - - - <_TemplateCsproj Include="$(MSBuildProjectDirectory)/PlatformVersion.cs.template" Destination="$(IntermediateOutputPath)/PlatformVersion.cs" /> - - - - - - - - - From 516eebb3c9b7e81eb2677c00b3d0b7867d8acb33 Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Wed, 27 Aug 2025 06:00:04 +0200 Subject: [PATCH 438/541] [main] Update dependencies from microsoft/testfx (#6449) Co-authored-by: dotnet-maestro[bot] --- eng/Version.Details.xml | 8 ++++---- eng/Versions.props | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index 96e72403a1..bf7d265c3e 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -17,13 +17,13 @@ https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage ad8260f1662c4c5e3099cb3ee5b96f38b01a6c6e - + https://github.com/microsoft/testfx - 0956f7bd3e0fdf2aa34dd392bdefe1dd7619603a + d2ced942a709b5936d3e7f18d2f16705b391f519 - + https://github.com/microsoft/testfx - 0956f7bd3e0fdf2aa34dd392bdefe1dd7619603a + d2ced942a709b5936d3e7f18d2f16705b391f519 diff --git a/eng/Versions.props b/eng/Versions.props index 9bdda405e2..cf4499a498 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -10,7 +10,7 @@ 10.0.0-beta.25419.2 18.0.0-preview.25421.1 - 3.11.0-preview.25425.5 - 1.9.0-preview.25425.5 + 3.11.0-preview.25426.4 + 1.9.0-preview.25426.4 From 5ac735fd65d59edb9fe80421f52aa0d969af943a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Wed, 27 Aug 2025 16:59:36 +0200 Subject: [PATCH 439/541] Fix some bugs with TestMethodShouldBeValidCodeFix (#6450) --- .../TestMethodShouldBeValidCodeFix.cs | 15 +++++++++++---- .../TestMethodShouldBeValidAnalyzerTests.cs | 16 ++++++++++++++-- 2 files changed, 25 insertions(+), 6 deletions(-) diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/TestMethodShouldBeValidCodeFix.cs b/src/Analyzers/MSTest.Analyzers.CodeFixes/TestMethodShouldBeValidCodeFix.cs index f7bf2b94e9..93a654286a 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/TestMethodShouldBeValidCodeFix.cs +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/TestMethodShouldBeValidCodeFix.cs @@ -93,7 +93,14 @@ private static async Task FixTestMethodAsync(Document document, Method SyntaxToken publicModifier = newMethodDeclaration.Modifiers.FirstOrDefault(m => m.IsKind(SyntaxKind.PublicKeyword)); if (publicModifier == default) { - newMethodDeclaration = newMethodDeclaration.WithModifiers(SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.PublicKeyword))); + IEnumerable modifiersWithoutAccessModifiers = newMethodDeclaration.Modifiers.Where(m => + !m.IsKind(SyntaxKind.PrivateKeyword) && + !m.IsKind(SyntaxKind.ProtectedKeyword) && + !m.IsKind(SyntaxKind.InternalKeyword)); + + newMethodDeclaration = newMethodDeclaration.WithModifiers( + new SyntaxTokenList(SyntaxFactory.Token(SyntaxKind.PublicKeyword)) + .AddRange(modifiersWithoutAccessModifiers)); } // Ensure the method returns void or Task/ValueTask. @@ -104,8 +111,8 @@ private static async Task FixTestMethodAsync(Document document, Method if (newMethodDeclaration.ReturnType != null && !newMethodDeclaration.ReturnType.IsVoid() && - (taskSymbol == null || !semanticModel.ClassifyConversion(newMethodDeclaration.ReturnType, taskSymbol).IsImplicit) && - (valueTaskSymbol == null || !semanticModel.ClassifyConversion(newMethodDeclaration.ReturnType, valueTaskSymbol).IsImplicit)) + (taskSymbol == null || !semanticModel.ClassifyConversion(methodDeclaration.ReturnType, taskSymbol).IsImplicit) && + (valueTaskSymbol == null || !semanticModel.ClassifyConversion(methodDeclaration.ReturnType, valueTaskSymbol).IsImplicit)) { // Change return type to void and remove return statements newMethodDeclaration = newMethodDeclaration.WithReturnType(SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.VoidKeyword))); @@ -122,7 +129,7 @@ private static async Task FixTestMethodAsync(Document document, Method bool asyncModifier = newMethodDeclaration.Modifiers.Any(m => m.IsKind(SyntaxKind.AsyncKeyword)); if (asyncModifier && newMethodDeclaration.ReturnType != null && newMethodDeclaration.ReturnType.IsVoid()) { - // Change the return type to Task + // Change the return type to Task. We have a space after Task to ensure we have a trailing trivia (space) after Task. newMethodDeclaration = newMethodDeclaration.WithReturnType(SyntaxFactory.ParseTypeName("Task ")); } diff --git a/test/UnitTests/MSTest.Analyzers.UnitTests/TestMethodShouldBeValidAnalyzerTests.cs b/test/UnitTests/MSTest.Analyzers.UnitTests/TestMethodShouldBeValidAnalyzerTests.cs index b311c1976f..b28d976280 100644 --- a/test/UnitTests/MSTest.Analyzers.UnitTests/TestMethodShouldBeValidAnalyzerTests.cs +++ b/test/UnitTests/MSTest.Analyzers.UnitTests/TestMethodShouldBeValidAnalyzerTests.cs @@ -38,12 +38,18 @@ public async Task WhenTestMethodIsNotPublic_Diagnostic(string accessibility) { string code = $$""" using Microsoft.VisualStudio.TestTools.UnitTesting; + using System.Threading.Tasks; [TestClass] public class MyTestClass { [TestMethod] - {{accessibility}} void [|MyTestMethod|]() + {{accessibility}} void [|MyTestMethod1|]() + { + } + + [TestMethod] + {{accessibility}} async Task [|MyTestMethod2|]() { } } @@ -52,12 +58,18 @@ public class MyTestClass string fixedCode = """ using Microsoft.VisualStudio.TestTools.UnitTesting; + using System.Threading.Tasks; [TestClass] public class MyTestClass { [TestMethod] - public void MyTestMethod() + public void MyTestMethod1() + { + } + + [TestMethod] + public async Task MyTestMethod2() { } } From db7f86925ac95d7cb4befd76cd1689e1783a5c47 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Wed, 27 Aug 2025 17:42:35 +0200 Subject: [PATCH 440/541] Use SyntaxFactory.IdentifierName instead of ParseTypeName (#6451) --- .../TestMethodShouldBeValidCodeFix.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/TestMethodShouldBeValidCodeFix.cs b/src/Analyzers/MSTest.Analyzers.CodeFixes/TestMethodShouldBeValidCodeFix.cs index 93a654286a..263cfe53e2 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/TestMethodShouldBeValidCodeFix.cs +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/TestMethodShouldBeValidCodeFix.cs @@ -130,7 +130,7 @@ private static async Task FixTestMethodAsync(Document document, Method if (asyncModifier && newMethodDeclaration.ReturnType != null && newMethodDeclaration.ReturnType.IsVoid()) { // Change the return type to Task. We have a space after Task to ensure we have a trailing trivia (space) after Task. - newMethodDeclaration = newMethodDeclaration.WithReturnType(SyntaxFactory.ParseTypeName("Task ")); + newMethodDeclaration = newMethodDeclaration.WithReturnType(SyntaxFactory.IdentifierName("Task")); } // Apply changes. From 605a2c741c420b1b7a6877fcce5a0fd69bb80e53 Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Thu, 28 Aug 2025 07:26:26 +0200 Subject: [PATCH 441/541] [main] Update dependencies from microsoft/testfx (#6452) Co-authored-by: dotnet-maestro[bot] --- eng/Version.Details.xml | 8 ++++---- eng/Versions.props | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index bf7d265c3e..1b3e3ddb0c 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -17,13 +17,13 @@ https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage ad8260f1662c4c5e3099cb3ee5b96f38b01a6c6e - + https://github.com/microsoft/testfx - d2ced942a709b5936d3e7f18d2f16705b391f519 + db7f86925ac95d7cb4befd76cd1689e1783a5c47 - + https://github.com/microsoft/testfx - d2ced942a709b5936d3e7f18d2f16705b391f519 + db7f86925ac95d7cb4befd76cd1689e1783a5c47 diff --git a/eng/Versions.props b/eng/Versions.props index cf4499a498..cae3a049dc 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -10,7 +10,7 @@ 10.0.0-beta.25419.2 18.0.0-preview.25421.1 - 3.11.0-preview.25426.4 - 1.9.0-preview.25426.4 + 3.11.0-preview.25427.3 + 1.9.0-preview.25427.3 From 3e608ee0bcf0a28fdf4a5399399cadcc1d197897 Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Fri, 29 Aug 2025 06:46:12 +0000 Subject: [PATCH 442/541] [main] Update dependencies from microsoft/testfx (#6461) Co-authored-by: dotnet-maestro[bot] --- eng/Version.Details.xml | 8 ++++---- eng/Versions.props | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index 1b3e3ddb0c..7650148b38 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -17,13 +17,13 @@ https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage ad8260f1662c4c5e3099cb3ee5b96f38b01a6c6e - + https://github.com/microsoft/testfx - db7f86925ac95d7cb4befd76cd1689e1783a5c47 + 605a2c741c420b1b7a6877fcce5a0fd69bb80e53 - + https://github.com/microsoft/testfx - db7f86925ac95d7cb4befd76cd1689e1783a5c47 + 605a2c741c420b1b7a6877fcce5a0fd69bb80e53 diff --git a/eng/Versions.props b/eng/Versions.props index cae3a049dc..f5d5c20f18 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -10,7 +10,7 @@ 10.0.0-beta.25419.2 18.0.0-preview.25421.1 - 3.11.0-preview.25427.3 - 1.9.0-preview.25427.3 + 3.11.0-preview.25427.4 + 1.9.0-preview.25427.4 From fbff8300474079f4770ba5c9d93f9459282ede8c Mon Sep 17 00:00:00 2001 From: Copilot <198982749+Copilot@users.noreply.github.com> Date: Fri, 29 Aug 2025 09:41:13 +0200 Subject: [PATCH 443/541] Fix MSTEST0017 false positive when comparing literals to properties with "expected" names (#6456) Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: Youssef1313 <31348972+Youssef1313@users.noreply.github.com> Co-authored-by: Youssef Victor --- ...rgsShouldBePassedInCorrectOrderAnalyzer.cs | 41 ++++++++--- ...ouldBePassedInCorrectOrderAnalyzerTests.cs | 73 +++++++++++++++++++ 2 files changed, 103 insertions(+), 11 deletions(-) diff --git a/src/Analyzers/MSTest.Analyzers/AssertionArgsShouldBePassedInCorrectOrderAnalyzer.cs b/src/Analyzers/MSTest.Analyzers/AssertionArgsShouldBePassedInCorrectOrderAnalyzer.cs index 1e08e3ee1f..24d659914c 100644 --- a/src/Analyzers/MSTest.Analyzers/AssertionArgsShouldBePassedInCorrectOrderAnalyzer.cs +++ b/src/Analyzers/MSTest.Analyzers/AssertionArgsShouldBePassedInCorrectOrderAnalyzer.cs @@ -74,31 +74,50 @@ private static void AnalyzeOperation(OperationAnalysisContext context, INamedTyp return; } + // If "expected" is already constant, we shouldn't report any diagnostics and we don't care about "actual". + if (IsConstant(expectedArgument)) + { + return; + } + // If the actual value is a constant or a literal and expected is not, then the arguments are in the wrong order. // Note that we don't report if both are literals or constants, as there is no real fix for this. // If both are literals or constants, the assert will always pass or always fail. - if (IsConstant(actualArgument) && !IsConstant(expectedArgument)) + if (IsConstant(actualArgument)) { context.ReportDiagnostic(invocationOperation.CreateDiagnostic(Rule)); return; } - if (actualArgument.Value.GetReferencedMemberOrLocalOrParameter() is { } actualSymbol) + ISymbol? actualSymbol = actualArgument.Value.GetReferencedMemberOrLocalOrParameter(); + ISymbol? expectedSymbol = expectedArgument.Value.GetReferencedMemberOrLocalOrParameter(); + bool actualIsExpected = actualSymbol is not null && NameIsExpected(actualSymbol.Name); + bool expectedIsExpected = expectedSymbol is not null && NameIsExpected(expectedSymbol.Name); + + // If both arguments have names indicating it's "expected", don't report a diagnostic. + if (actualIsExpected && !expectedIsExpected) { - if (actualSymbol.Name.StartsWith("expected", StringComparison.Ordinal) - || actualSymbol.Name.StartsWith("_expected", StringComparison.Ordinal) - || actualSymbol.Name.StartsWith("Expected", StringComparison.Ordinal)) - { - context.ReportDiagnostic(invocationOperation.CreateDiagnostic(Rule)); - return; - } + context.ReportDiagnostic(invocationOperation.CreateDiagnostic(Rule)); + return; } - if (expectedArgument.Value.GetReferencedMemberOrLocalOrParameter() is { } expectedSymbol - && expectedSymbol.Name.StartsWith("actual", StringComparison.Ordinal)) + bool expectedIsActual = expectedSymbol is not null && NameIsActual(expectedSymbol.Name); + bool actualIsActual = actualSymbol is not null && NameIsActual(actualSymbol.Name); + + // If both arguments have names indicating it's "actual", don't report a diagnostic. + if (expectedIsActual && !actualIsActual) { context.ReportDiagnostic(invocationOperation.CreateDiagnostic(Rule)); + return; } + + static bool NameIsExpected(string name) + => name.StartsWith("expected", StringComparison.Ordinal) || + name.StartsWith("_expected", StringComparison.Ordinal) || + name.StartsWith("Expected", StringComparison.Ordinal); + + static bool NameIsActual(string name) + => name.StartsWith("actual", StringComparison.Ordinal); } private static (IArgumentOperation ExpectedArgument, IArgumentOperation ActualArgument)? FindExpectedAndActualArguments(IInvocationOperation invocationOperation) diff --git a/test/UnitTests/MSTest.Analyzers.UnitTests/AssertionArgsShouldBePassedInCorrectOrderAnalyzerTests.cs b/test/UnitTests/MSTest.Analyzers.UnitTests/AssertionArgsShouldBePassedInCorrectOrderAnalyzerTests.cs index ba37e0da2b..bdf38f26de 100644 --- a/test/UnitTests/MSTest.Analyzers.UnitTests/AssertionArgsShouldBePassedInCorrectOrderAnalyzerTests.cs +++ b/test/UnitTests/MSTest.Analyzers.UnitTests/AssertionArgsShouldBePassedInCorrectOrderAnalyzerTests.cs @@ -816,4 +816,77 @@ await VerifyCS.VerifyCodeFixAsync( code, code); } + + [TestMethod] + public async Task LiteralWithExpectedNamedProperty_ShouldNotFlag() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + public class TestObject + { + public string ExpectedValue { get; set; } = ""; + public int expectedCount { get; set; } = 0; + public bool _expectedFlag { get; set; } = false; + } + + [TestMethod] + public void Compliant() + { + var obj = new TestObject(); + + // These should NOT be flagged - comparing literals to properties with "expected" names is correct + Assert.AreEqual("value1", obj.ExpectedValue); + Assert.AreEqual(42, obj.expectedCount); + Assert.AreEqual(true, obj._expectedFlag); + Assert.AreEqual(obj._expectedFlag, obj._expectedFlag); + Assert.AreEqual(obj.ExpectedValue, obj._expectedFlag); + + Assert.AreNotEqual("value2", obj.ExpectedValue); + Assert.AreNotEqual(24, obj.expectedCount); + Assert.AreNotEqual(false, obj._expectedFlag); + + Assert.AreSame("value3", obj.ExpectedValue); + Assert.AreNotSame("value4", obj.ExpectedValue); + } + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, code); + } + + [TestMethod] + public async Task ConstantWithExpectedNamedProperty_ShouldNotFlag() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + private const string EXPECTED_CONSTANT = "test"; + + public class TestObject + { + public string ExpectedValue { get; set; } = ""; + public string expectedResult { get; set; } = ""; + } + + [TestMethod] + public void Compliant() + { + var obj = new TestObject(); + + // These should NOT be flagged - comparing constants to properties with "expected" names is correct + Assert.AreEqual(EXPECTED_CONSTANT, obj.ExpectedValue); + Assert.AreNotEqual(EXPECTED_CONSTANT, obj.expectedResult); + } + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, code); + } } From 39be0d87585c19bd0d69aaa2614197dfb5e96d4e Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Fri, 29 Aug 2025 09:41:56 +0200 Subject: [PATCH 444/541] Synchronize _testContextMessageStringBuilder (#6459) --- .../Services/TestContextImplementation.cs | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Services/TestContextImplementation.cs b/src/Adapter/MSTestAdapter.PlatformServices/Services/TestContextImplementation.cs index 60bac5bbdc..44eb70f27c 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Services/TestContextImplementation.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Services/TestContextImplementation.cs @@ -43,6 +43,14 @@ internal void Append(string? value) internal void Append(char[] buffer, int index, int count) => _builder.Append(buffer, index, count); + [MethodImpl(MethodImplOptions.Synchronized)] + internal void AppendLine(string? value) + => _builder.AppendLine(value); + + [MethodImpl(MethodImplOptions.Synchronized)] + internal void Clear() + => _builder.Clear(); + [MethodImpl(MethodImplOptions.Synchronized)] public override string ToString() => _builder.ToString(); @@ -70,7 +78,7 @@ public override string ToString() private SynchronizedStringBuilder? _stdOutStringBuilder; private SynchronizedStringBuilder? _stdErrStringBuilder; private SynchronizedStringBuilder? _traceStringBuilder; - private StringBuilder? _testContextMessageStringBuilder; + private SynchronizedStringBuilder? _testContextMessageStringBuilder; /// /// Unit test outcome. @@ -421,7 +429,7 @@ private SynchronizedStringBuilder GetTraceStringBuilder() return _traceStringBuilder; } - private StringBuilder GetTestContextMessagesStringBuilder() + private SynchronizedStringBuilder GetTestContextMessagesStringBuilder() { // Prefer writing to the current test context instead of 'this'. // This is just a hack to preserve backward compatibility. @@ -429,7 +437,7 @@ private StringBuilder GetTestContextMessagesStringBuilder() // Then, they write to the "wrong" test context. // Here, we are correcting user's fault by finding out the correct TestContext that should receive the message. TestContextImplementation @this = CurrentTestContext ?? this; - _ = @this._testContextMessageStringBuilder ?? Interlocked.CompareExchange(ref @this._testContextMessageStringBuilder, new StringBuilder(), null)!; + _ = @this._testContextMessageStringBuilder ?? Interlocked.CompareExchange(ref @this._testContextMessageStringBuilder, new SynchronizedStringBuilder(), null)!; return @this._testContextMessageStringBuilder; } From ccabcb48349d16e50094f925e251169104aabf40 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Fri, 29 Aug 2025 11:39:41 +0200 Subject: [PATCH 445/541] [MTP] Support Trx Description (#6464) --- .../TrxReportEngine.cs | 10 ++++++++++ .../Microsoft.Testing.Extensions.UnitTests/TrxTests.cs | 2 ++ 2 files changed, 12 insertions(+) diff --git a/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxReportEngine.cs b/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxReportEngine.cs index c9e81e9b13..fbb1be1e21 100644 --- a/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxReportEngine.cs +++ b/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxReportEngine.cs @@ -561,6 +561,7 @@ private void AddResults(string testAppModule, XElement testRun, out XElement tes XElement? properties = null; XElement? owners = null; + XElement? description = null; foreach (TestMetadataProperty property in testNode.Properties.OfType()) { switch (property.Key) @@ -577,6 +578,10 @@ private void AddResults(string testAppModule, XElement testRun, out XElement tes break; + case "Description": + description ??= new XElement("Description", property.Value); + break; + default: // NOTE: VSTest doesn't produce Properties as of writing this. // It was historically fixed, but the fix wasn't correct and the fix was reverted and never revisited to be properly fixed. @@ -614,6 +619,11 @@ private void AddResults(string testAppModule, XElement testRun, out XElement tes unitTest.Add(owners); } + if (description is not null) + { + unitTest.Add(description); + } + if (properties is not null) { unitTest.Add(properties); diff --git a/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/TrxTests.cs b/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/TrxTests.cs index 0226f9bde0..d168f4be72 100644 --- a/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/TrxTests.cs +++ b/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/TrxTests.cs @@ -512,6 +512,7 @@ public async Task TrxReportEngine_GenerateReportAsync_WithMetadataProperties_Trx new( new PassedTestNodeStateProperty(), new TestMetadataProperty("Owner", "ValueOfOwner"), + new TestMetadataProperty("Description", "Description of my test"), new TestMetadataProperty("Priority", "5"), new TestMetadataProperty("MyProperty1", "MyValue1"), new TestMetadataProperty("MyProperty2", "MyValue2")), memoryStream); @@ -532,6 +533,7 @@ public async Task TrxReportEngine_GenerateReportAsync_WithMetadataProperties_Trx + Description of my test MyProperty2 From 453def16149919f6af3fd8d5ca4fffdfee082ad8 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Fri, 29 Aug 2025 11:54:32 +0200 Subject: [PATCH 446/541] Fix command-line arguments escaping when retry and test host controllers start child processes (#6462) --- .../RetryOrchestrator.cs | 26 ++--- .../Helpers/PasteArguments.cs | 98 +++++++++++++++++++ .../Hosts/TestHostControllersTestHost.cs | 10 +- 3 files changed, 118 insertions(+), 16 deletions(-) create mode 100644 src/Platform/Microsoft.Testing.Platform/Helpers/PasteArguments.cs diff --git a/src/Platform/Microsoft.Testing.Extensions.Retry/RetryOrchestrator.cs b/src/Platform/Microsoft.Testing.Extensions.Retry/RetryOrchestrator.cs index e06210513d..b5948b1eb6 100644 --- a/src/Platform/Microsoft.Testing.Extensions.Retry/RetryOrchestrator.cs +++ b/src/Platform/Microsoft.Testing.Extensions.Retry/RetryOrchestrator.cs @@ -169,23 +169,23 @@ public async Task OrchestrateTestHostExecutionAsync() finalArguments.Add($"--{RetryCommandLineOptionsProvider.RetryFailedTestsPipeNameOptionName}"); finalArguments.Add(retryFailedTestsPipeServer.PipeName); - // Prepare the process start - ProcessStartInfo processStartInfo = new() +#if NET8_0_OR_GREATER + List arguments = finalArguments; +#else + var builder = new StringBuilder(); + foreach (string arg in finalArguments) { - FileName = executableInfo.FilePath, -#if !NETCOREAPP - UseShellExecute = false, + PasteArguments.AppendArgument(builder, arg); + } + + string arguments = builder.ToString(); #endif - }; - foreach (string argument in finalArguments) + // Prepare the process start + ProcessStartInfo processStartInfo = new(executableInfo.FilePath, arguments) { -#if !NETCOREAPP - processStartInfo.Arguments += argument + " "; -#else - processStartInfo.ArgumentList.Add(argument); -#endif - } + UseShellExecute = false, + }; await logger.LogDebugAsync($"Starting test host process, attempt {attemptCount}/{userMaxRetryCount}").ConfigureAwait(false); IProcess testHostProcess = _serviceProvider.GetProcessHandler().Start(processStartInfo) diff --git a/src/Platform/Microsoft.Testing.Platform/Helpers/PasteArguments.cs b/src/Platform/Microsoft.Testing.Platform/Helpers/PasteArguments.cs new file mode 100644 index 0000000000..5107fe1799 --- /dev/null +++ b/src/Platform/Microsoft.Testing.Platform/Helpers/PasteArguments.cs @@ -0,0 +1,98 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +namespace Microsoft.Testing.Platform.Helpers; + +// https://github.com/dotnet/runtime/blob/019c8d72effbdb4f69564695f1df7c4417ec060d/src/libraries/System.Private.CoreLib/src/System/PasteArguments.cs +internal static partial class PasteArguments +{ + // WARNING: Don't change the signature of this internal method. It's exposed via IVT to other assemblies. + // Renaming it is a BREAKING CHANGE. + internal static void AppendArgument(StringBuilder stringBuilder, string argument) + { + if (stringBuilder.Length != 0) + { + stringBuilder.Append(' '); + } + + // Parsing rules for non-argv[0] arguments: + // - Backslash is a normal character except followed by a quote. + // - 2N backslashes followed by a quote ==> N literal backslashes followed by unescaped quote + // - 2N+1 backslashes followed by a quote ==> N literal backslashes followed by a literal quote + // - Parsing stops at first whitespace outside of quoted region. + // - (post 2008 rule): A closing quote followed by another quote ==> literal quote, and parsing remains in quoting mode. + if (argument.Length != 0 && ContainsNoWhitespaceOrQuotes(argument)) + { + // Simple case - no quoting or changes needed. + stringBuilder.Append(argument); + } + else + { + stringBuilder.Append(Quote); + int idx = 0; + while (idx < argument.Length) + { + char c = argument[idx++]; + if (c == Backslash) + { + int numBackSlash = 1; + while (idx < argument.Length && argument[idx] == Backslash) + { + idx++; + numBackSlash++; + } + + if (idx == argument.Length) + { + // We'll emit an end quote after this so must double the number of backslashes. + stringBuilder.Append(Backslash, numBackSlash * 2); + } + else if (argument[idx] == Quote) + { + // Backslashes will be followed by a quote. Must double the number of backslashes. + stringBuilder.Append(Backslash, (numBackSlash * 2) + 1); + stringBuilder.Append(Quote); + idx++; + } + else + { + // Backslash will not be followed by a quote, so emit as normal characters. + stringBuilder.Append(Backslash, numBackSlash); + } + + continue; + } + + if (c == Quote) + { + // Escape the quote so it appears as a literal. This also guarantees that we won't end up generating a closing quote followed + // by another quote (which parses differently pre-2008 vs. post-2008.) + stringBuilder.Append(Backslash); + stringBuilder.Append(Quote); + continue; + } + + stringBuilder.Append(c); + } + + stringBuilder.Append(Quote); + } + } + + private static bool ContainsNoWhitespaceOrQuotes(string s) + { + for (int i = 0; i < s.Length; i++) + { + char c = s[i]; + if (char.IsWhiteSpace(c) || c == Quote) + { + return false; + } + } + + return true; + } + + private const char Quote = '\"'; + private const char Backslash = '\\'; +} diff --git a/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostControllersTestHost.cs b/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostControllersTestHost.cs index 25bfabac0b..cc01e4864a 100644 --- a/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostControllersTestHost.cs +++ b/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostControllersTestHost.cs @@ -104,7 +104,13 @@ protected override async Task InternalRunAsync() #if NET8_0_OR_GREATER IEnumerable arguments = partialCommandLine; #else - string arguments = string.Join(' ', partialCommandLine); + var builder = new StringBuilder(); + foreach (string arg in partialCommandLine) + { + PasteArguments.AppendArgument(builder, arg); + } + + string arguments = builder.ToString(); #endif #pragma warning disable CA1416 // Validate platform compatibility @@ -119,9 +125,7 @@ protected override async Task InternalRunAsync() { $"{EnvironmentVariableConstants.TESTINGPLATFORM_TESTHOSTCONTROLLER_SKIPEXTENSION}_{currentPid}", "1" }, { $"{EnvironmentVariableConstants.TESTINGPLATFORM_TESTHOSTCONTROLLER_PIPENAME}_{currentPid}", testHostControllerIpc.PipeName.Name }, }, -#if !NETCOREAPP UseShellExecute = false, -#endif }; #pragma warning restore CA1416 From fbff9b0d7fffc38a1eeb8fda3b8c34aa4c72a7b5 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Fri, 29 Aug 2025 13:30:25 +0200 Subject: [PATCH 447/541] Add clarifying comments for command-line arg escaping (#6465) --- .../Microsoft.Testing.Extensions.Retry/RetryOrchestrator.cs | 5 +++++ .../Hosts/TestHostControllersTestHost.cs | 5 +++++ 2 files changed, 10 insertions(+) diff --git a/src/Platform/Microsoft.Testing.Extensions.Retry/RetryOrchestrator.cs b/src/Platform/Microsoft.Testing.Extensions.Retry/RetryOrchestrator.cs index b5948b1eb6..eab108c33f 100644 --- a/src/Platform/Microsoft.Testing.Extensions.Retry/RetryOrchestrator.cs +++ b/src/Platform/Microsoft.Testing.Extensions.Retry/RetryOrchestrator.cs @@ -170,8 +170,13 @@ public async Task OrchestrateTestHostExecutionAsync() finalArguments.Add(retryFailedTestsPipeServer.PipeName); #if NET8_0_OR_GREATER + // On net8.0+, we can pass the arguments as a collection directly to ProcessStartInfo. + // When passing the collection, it's expected to be unescaped, so we pass what we have directly. List arguments = finalArguments; #else + // Current target framework (.NET Framework and .NET Standard 2.0) only supports arguments as a single string. + // In this case, escaping is essential. For example, one of the arguments could already contain spaces. + // PasteArguments is borrowed from dotnet/runtime. var builder = new StringBuilder(); foreach (string arg in finalArguments) { diff --git a/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostControllersTestHost.cs b/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostControllersTestHost.cs index cc01e4864a..3a145667b3 100644 --- a/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostControllersTestHost.cs +++ b/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostControllersTestHost.cs @@ -102,8 +102,13 @@ protected override async Task InternalRunAsync() testHostControllerIpc.RegisterAllSerializers(); #if NET8_0_OR_GREATER + // On net8.0+, we can pass the arguments as a collection directly to ProcessStartInfo. + // When passing the collection, it's expected to be unescaped, so we pass what we have directly. IEnumerable arguments = partialCommandLine; #else + // Current target framework (.NET Framework and .NET Standard 2.0) only supports arguments as a single string. + // In this case, escaping is essential. For example, one of the arguments could already contain spaces. + // PasteArguments is borrowed from dotnet/runtime. var builder = new StringBuilder(); foreach (string arg in partialCommandLine) { From 03d09277f39a853db8117147aba77c1a14452094 Mon Sep 17 00:00:00 2001 From: dotnet bot Date: Fri, 29 Aug 2025 04:39:00 -0700 Subject: [PATCH 448/541] Localized file check-in by OneLocBuild Task: Build definition ID 1218: Build ID 2782504 --- .../xlf/CodeFixResources.de.xlf | 8 ++++---- .../xlf/CodeFixResources.ja.xlf | 8 ++++---- .../xlf/CodeFixResources.ru.xlf | 8 ++++---- .../xlf/CodeFixResources.zh-Hans.xlf | 8 ++++---- .../MSTest.Analyzers/xlf/Resources.de.xlf | 14 +++++++------- .../MSTest.Analyzers/xlf/Resources.ja.xlf | 14 +++++++------- .../MSTest.Analyzers/xlf/Resources.ru.xlf | 14 +++++++------- .../MSTest.Analyzers/xlf/Resources.zh-Hans.xlf | 14 +++++++------- 8 files changed, 44 insertions(+), 44 deletions(-) diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.de.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.de.xlf index 030c66a367..6a3d19f1bc 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.de.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.de.xlf @@ -24,12 +24,12 @@ Use interpolated string instead of format parameters - Use interpolated string instead of format parameters + Interpolierte Zeichenfolge anstelle von Formatparametern verwenden Use 'string.Format' instead of format parameters - Use 'string.Format' instead of format parameters + „string.Format“ anstelle von Formatparametern verwenden @@ -59,7 +59,7 @@ Pass 'TestContext.CancellationToken' argument to method call - Pass 'TestContext.CancellationToken' argument to method call + Argument „TestContext.CancellationToken“ an den Methodenaufruf übergeben @@ -129,7 +129,7 @@ Use 'TestContext.CancellationToken' instead - Use 'TestContext.CancellationToken' instead + Stattdessen „TestContext.CancellationToken“ verwenden diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ja.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ja.xlf index 1f1399b186..7d7b217dee 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ja.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ja.xlf @@ -24,12 +24,12 @@ Use interpolated string instead of format parameters - Use interpolated string instead of format parameters + 書式設定パラメーターの代わりに補間された文字列を使用する Use 'string.Format' instead of format parameters - Use 'string.Format' instead of format parameters + 書式設定パラメーターの代わりに 'string.Format' を使用する @@ -59,7 +59,7 @@ Pass 'TestContext.CancellationToken' argument to method call - Pass 'TestContext.CancellationToken' argument to method call + 'TestContext.CancellationToken' 引数をメソッド呼び出しに渡す @@ -129,7 +129,7 @@ Use 'TestContext.CancellationToken' instead - Use 'TestContext.CancellationToken' instead + 代わりに 'TestContext.CancellationToken' を使用する diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ru.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ru.xlf index a0833716dd..612dc20fd7 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ru.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ru.xlf @@ -24,12 +24,12 @@ Use interpolated string instead of format parameters - Use interpolated string instead of format parameters + Используйте интерполированную строку вместо параметров форматирования Use 'string.Format' instead of format parameters - Use 'string.Format' instead of format parameters + Используйте "string.Format" вместо параметров форматирования @@ -59,7 +59,7 @@ Pass 'TestContext.CancellationToken' argument to method call - Pass 'TestContext.CancellationToken' argument to method call + Передайте аргумент "TestContext.CancellationToken" в вызов метода @@ -129,7 +129,7 @@ Use 'TestContext.CancellationToken' instead - Use 'TestContext.CancellationToken' instead + Вместо этого используйте "TestContext.CancellationToken" diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hans.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hans.xlf index 6c20d4e8e9..97c4645e47 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hans.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hans.xlf @@ -24,12 +24,12 @@ Use interpolated string instead of format parameters - Use interpolated string instead of format parameters + 使用内插字符串而不是格式参数 Use 'string.Format' instead of format parameters - Use 'string.Format' instead of format parameters + 使用 'string.Format' 而不是格式参数 @@ -59,7 +59,7 @@ Pass 'TestContext.CancellationToken' argument to method call - Pass 'TestContext.CancellationToken' argument to method call + 将 'TestContext.CancellationToken' 参数传递给方法调用 @@ -129,7 +129,7 @@ Use 'TestContext.CancellationToken' instead - Use 'TestContext.CancellationToken' instead + 请改用 'TestContext.CancellationToken' diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf index 6779a5303e..6ad06bcceb 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf @@ -134,12 +134,12 @@ Der Typ, der diese Methoden deklariert, sollte auch die folgenden Regeln beachte Replace '{0}' with format parameters with string.Format or string interpolation - Replace '{0}' with format parameters with string.Format or string interpolation + „{0}“ durch Formatparameter mit string.Format oder Zeichenfolgeninterpolation ersetzen Avoid using Assert methods with format parameters - Avoid using Assert methods with format parameters + Verwendung von Assert-Methoden mit Formatparametern vermeiden @@ -465,12 +465,12 @@ Der Typ, der diese Methoden deklariert, sollte auch die folgenden Regeln beachte When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationToken to enable cooperative cancellation and respect test timeouts. - When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationToken to enable cooperative cancellation and respect test timeouts. + Wenn Sie asynchrone Methoden aufrufen, die über Überladungen verfügen, die einen CancellationToken-Parameter akzeptieren, bevorzugen Sie die Verwendung der Überladung mit TestContext.CancellationToken, um einen kooperativen Abbruch zu ermöglichen und Testtimeouts zu berücksichtigen. Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationToken' - Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationToken' + Verwendung der Überladung erwägen, die ein CancellationToken akzeptiert, und „TestContext.CancellationToken“ übergeben @@ -655,17 +655,17 @@ Der Typ, der diese Methoden deklariert, sollte auch die folgenden Regeln beachte TestContext.CancellationToken provides a more direct way to access the cancellation token compared to TestContext.CancellationTokenSource.Token. - TestContext.CancellationToken provides a more direct way to access the cancellation token compared to TestContext.CancellationTokenSource.Token. + TestContext.CancellationToken bietet im Vergleich mit TestContext.CancellationTokenSource.Token eine direktere Möglichkeit, auf das Abbruchtoken zuzugreifen. Use 'TestContext.CancellationToken' instead of 'TestContext.CancellationTokenSource.Token' - Use 'TestContext.CancellationToken' instead of 'TestContext.CancellationTokenSource.Token' + „TestContext.CancellationToken“ anstelle von „TestContext.CancellationTokenSource.Token“ verwenden Use TestContext.CancellationToken instead of TestContext.CancellationTokenSource.Token - Use TestContext.CancellationToken instead of TestContext.CancellationTokenSource.Token + TestContext.CancellationToken anstelle von TestContext.CancellationTokenSource.Token verwenden diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf index aedc5b5caa..da1edb5d99 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf @@ -134,12 +134,12 @@ The type declaring these methods should also respect the following rules: Replace '{0}' with format parameters with string.Format or string interpolation - Replace '{0}' with format parameters with string.Format or string interpolation + '{0}' を string.Format または文字列の補間で書式設定パラメーターに置き換える Avoid using Assert methods with format parameters - Avoid using Assert methods with format parameters + 書式設定パラメーターで Assert メソッドを使用しないようにする @@ -464,12 +464,12 @@ The type declaring these methods should also respect the following rules: When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationToken to enable cooperative cancellation and respect test timeouts. - When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationToken to enable cooperative cancellation and respect test timeouts. + CancellationToken パラメーターを受け入れるオーバーロードを持つ非同期メソッドを呼び出す場合は、TestContext.CancellationToken でオーバーロードを使用して協調的な取り消しを有効にし、テスト タイムアウトを考慮します。 Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationToken' - Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationToken' + CancellationToken を受け取り、'TestContext.CancellationToken' を渡すオーバーロードの使用を検討してください @@ -654,17 +654,17 @@ The type declaring these methods should also respect the following rules: TestContext.CancellationToken provides a more direct way to access the cancellation token compared to TestContext.CancellationTokenSource.Token. - TestContext.CancellationToken provides a more direct way to access the cancellation token compared to TestContext.CancellationTokenSource.Token. + TestContext.CancellationToken は、TestContext.CancellationTokenSource.Token と比較して、より直接的に取り消しトークンにアクセスできます。 Use 'TestContext.CancellationToken' instead of 'TestContext.CancellationTokenSource.Token' - Use 'TestContext.CancellationToken' instead of 'TestContext.CancellationTokenSource.Token' + 'TestContext.CancellationTokenSource.Token' の代わりに 'TestContext.CancellationToken' を使用する Use TestContext.CancellationToken instead of TestContext.CancellationTokenSource.Token - Use TestContext.CancellationToken instead of TestContext.CancellationTokenSource.Token + TestContext.CancellationTokenSource.Token の代わりに TestContext.CancellationToken を使用する diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf index cdee824d0a..ec1618cbfa 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf @@ -137,12 +137,12 @@ The type declaring these methods should also respect the following rules: Replace '{0}' with format parameters with string.Format or string interpolation - Replace '{0}' with format parameters with string.Format or string interpolation + Замените "{0}" на параметры формата с помощью string.Format или интерполяции строк Avoid using Assert methods with format parameters - Avoid using Assert methods with format parameters + Избегайте использования методов Assert с параметрами форматирования @@ -470,12 +470,12 @@ The type declaring these methods should also respect the following rules: When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationToken to enable cooperative cancellation and respect test timeouts. - When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationToken to enable cooperative cancellation and respect test timeouts. + При вызове асинхронных методов с перегрузками, принимающими параметр CancellationToken, рекомендуется использовать перегрузку с TestContext.CancellationTokenSource.Token, чтобы обеспечить совместные действия по отмене и учитывать лимиты времени ожидания тестов. Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationToken' - Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationToken' + Рассмотрите возможность использования перегрузки, которая принимает CancellationToken, и передавайте "TestContext.CancellationToken" @@ -660,17 +660,17 @@ The type declaring these methods should also respect the following rules: TestContext.CancellationToken provides a more direct way to access the cancellation token compared to TestContext.CancellationTokenSource.Token. - TestContext.CancellationToken provides a more direct way to access the cancellation token compared to TestContext.CancellationTokenSource.Token. + TestContext.CancellationToken предоставляет более прямой доступ к маркеру отмены по сравнению с TestContext.CancellationTokenSource.Token. Use 'TestContext.CancellationToken' instead of 'TestContext.CancellationTokenSource.Token' - Use 'TestContext.CancellationToken' instead of 'TestContext.CancellationTokenSource.Token' + Используйте "TestContext.CancellationToken" вместо "TestContext.CancellationTokenSource.Token" Use TestContext.CancellationToken instead of TestContext.CancellationTokenSource.Token - Use TestContext.CancellationToken instead of TestContext.CancellationTokenSource.Token + Используйте TestContext.CancellationToken вместо TestContext.CancellationTokenSource.Token diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf index a82db9a12b..0e0e78a5c2 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf @@ -134,12 +134,12 @@ The type declaring these methods should also respect the following rules: Replace '{0}' with format parameters with string.Format or string interpolation - Replace '{0}' with format parameters with string.Format or string interpolation + 将 ‘{0}’ 替换为 string.Format 或字符串内插 Avoid using Assert methods with format parameters - Avoid using Assert methods with format parameters + 避免将 Assert 方法与格式参数配合使用 @@ -464,12 +464,12 @@ The type declaring these methods should also respect the following rules: When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationToken to enable cooperative cancellation and respect test timeouts. - When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationToken to enable cooperative cancellation and respect test timeouts. + 在调用包含接受 CancellationToken 参数的重载的异步方法时,请优先使用带 TestContext.CancellationToken 的重载以启用协作取消并遵守测试超时。 Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationToken' - Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationToken' + 考虑使用接受 CancellationToken 的重载,并传递 'TestContext.CancellationToken' @@ -654,17 +654,17 @@ The type declaring these methods should also respect the following rules: TestContext.CancellationToken provides a more direct way to access the cancellation token compared to TestContext.CancellationTokenSource.Token. - TestContext.CancellationToken provides a more direct way to access the cancellation token compared to TestContext.CancellationTokenSource.Token. + 与 TestContext.CancellationTokenSource.Token 相比,TestContext.CancellationToken 提供了更直接的方式来访问取消令牌。 Use 'TestContext.CancellationToken' instead of 'TestContext.CancellationTokenSource.Token' - Use 'TestContext.CancellationToken' instead of 'TestContext.CancellationTokenSource.Token' + 使用 'TestContext.CancellationToken' 而不是 'TestContext.CancellationTokenSource.Token' Use TestContext.CancellationToken instead of TestContext.CancellationTokenSource.Token - Use TestContext.CancellationToken instead of TestContext.CancellationTokenSource.Token + 使用 TestContext.CancellationToken 而不是 TestContext.CancellationTokenSource.Token From 2b2b68ed88ee83013f0f79c7e09c0eb1101cd597 Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Sat, 30 Aug 2025 10:54:24 +0200 Subject: [PATCH 449/541] [main] Update dependencies from microsoft/testfx (#6469) Co-authored-by: dotnet-maestro[bot] --- eng/Version.Details.xml | 8 ++++---- eng/Versions.props | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index 7650148b38..7efbd7fec7 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -17,13 +17,13 @@ https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage ad8260f1662c4c5e3099cb3ee5b96f38b01a6c6e - + https://github.com/microsoft/testfx - 605a2c741c420b1b7a6877fcce5a0fd69bb80e53 + ba1eec5203c8856fe5437790dfb00cd448352bb8 - + https://github.com/microsoft/testfx - 605a2c741c420b1b7a6877fcce5a0fd69bb80e53 + ba1eec5203c8856fe5437790dfb00cd448352bb8 diff --git a/eng/Versions.props b/eng/Versions.props index f5d5c20f18..882183a16e 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -10,7 +10,7 @@ 10.0.0-beta.25419.2 18.0.0-preview.25421.1 - 3.11.0-preview.25427.4 - 1.9.0-preview.25427.4 + 3.11.0-preview.25429.7 + 1.9.0-preview.25429.7 From 8187608c8d2cdde25c6bead69ffcfc139a612440 Mon Sep 17 00:00:00 2001 From: dotnet bot Date: Sat, 30 Aug 2025 02:01:48 -0700 Subject: [PATCH 450/541] Localized file check-in by OneLocBuild Task: Build definition ID 1218: Build ID 2783009 --- .../xlf/CodeFixResources.cs.xlf | 8 ++++---- .../xlf/CodeFixResources.es.xlf | 8 ++++---- .../xlf/CodeFixResources.fr.xlf | 8 ++++---- .../xlf/CodeFixResources.it.xlf | 8 ++++---- .../xlf/CodeFixResources.ko.xlf | 8 ++++---- .../xlf/CodeFixResources.pl.xlf | 8 ++++---- .../xlf/CodeFixResources.pt-BR.xlf | 8 ++++---- .../xlf/CodeFixResources.zh-Hant.xlf | 8 ++++---- .../MSTest.Analyzers/xlf/Resources.es.xlf | 14 +++++++------- .../MSTest.Analyzers/xlf/Resources.fr.xlf | 14 +++++++------- .../MSTest.Analyzers/xlf/Resources.it.xlf | 14 +++++++------- .../MSTest.Analyzers/xlf/Resources.ko.xlf | 14 +++++++------- .../MSTest.Analyzers/xlf/Resources.pl.xlf | 14 +++++++------- .../MSTest.Analyzers/xlf/Resources.pt-BR.xlf | 14 +++++++------- .../MSTest.Analyzers/xlf/Resources.zh-Hant.xlf | 14 +++++++------- 15 files changed, 81 insertions(+), 81 deletions(-) diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.cs.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.cs.xlf index 7663f714a9..cc2d8dc45e 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.cs.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.cs.xlf @@ -24,12 +24,12 @@ Use interpolated string instead of format parameters - Use interpolated string instead of format parameters + Místo parametrů formátu použít interpolovaný řetězec Use 'string.Format' instead of format parameters - Use 'string.Format' instead of format parameters + Místo parametrů formátu použít argument string.Format @@ -59,7 +59,7 @@ Pass 'TestContext.CancellationToken' argument to method call - Pass 'TestContext.CancellationToken' argument to method call + Předat argument TestContext.CancellationToken volání metody @@ -129,7 +129,7 @@ Use 'TestContext.CancellationToken' instead - Use 'TestContext.CancellationToken' instead + Místo toho použít argument TestContext.CancellationToken diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.es.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.es.xlf index 1c88f1a1a3..e285a57aa0 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.es.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.es.xlf @@ -24,12 +24,12 @@ Use interpolated string instead of format parameters - Use interpolated string instead of format parameters + Usar cadena interpolada en lugar de parámetros de formato Use 'string.Format' instead of format parameters - Use 'string.Format' instead of format parameters + Usar 'string. Format' en lugar de parámetros de formato @@ -59,7 +59,7 @@ Pass 'TestContext.CancellationToken' argument to method call - Pass 'TestContext.CancellationToken' argument to method call + Pasar el argumento 'TestContext.CancellationToken' a la llamada al método @@ -129,7 +129,7 @@ Use 'TestContext.CancellationToken' instead - Use 'TestContext.CancellationToken' instead + Usar 'TestContext.CancellationToken' en su lugar diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.fr.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.fr.xlf index 7738ee286e..142da1b150 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.fr.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.fr.xlf @@ -24,12 +24,12 @@ Use interpolated string instead of format parameters - Use interpolated string instead of format parameters + Utiliser une chaîne interpolée au lieu de paramètres de format Use 'string.Format' instead of format parameters - Use 'string.Format' instead of format parameters + Utiliser « string.Format » au lieu des paramètres de format @@ -59,7 +59,7 @@ Pass 'TestContext.CancellationToken' argument to method call - Pass 'TestContext.CancellationToken' argument to method call + Transmettre l'argument « TestContext.CancellationToken » à l'appel de méthode @@ -129,7 +129,7 @@ Use 'TestContext.CancellationToken' instead - Use 'TestContext.CancellationToken' instead + Utiliser plutôt « TestContext.CancellationToken » diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.it.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.it.xlf index e6fe586632..c00367afaf 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.it.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.it.xlf @@ -24,12 +24,12 @@ Use interpolated string instead of format parameters - Use interpolated string instead of format parameters + Usare la stringa interpolata invece dei parametri di formato Use 'string.Format' instead of format parameters - Use 'string.Format' instead of format parameters + Usare 'string. Format' invece dei parametri di formato @@ -59,7 +59,7 @@ Pass 'TestContext.CancellationToken' argument to method call - Pass 'TestContext.CancellationToken' argument to method call + Passare l'argomento 'TestContext.CancellationToken' alla chiamata al metodo @@ -129,7 +129,7 @@ Use 'TestContext.CancellationToken' instead - Use 'TestContext.CancellationToken' instead + In alternativa, usare 'TestContext.CancellationToken' diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ko.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ko.xlf index 2d6a51fed8..c3457804a2 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ko.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.ko.xlf @@ -24,12 +24,12 @@ Use interpolated string instead of format parameters - Use interpolated string instead of format parameters + 형식 매개 변수 대신 보간된 문자열 사용 Use 'string.Format' instead of format parameters - Use 'string.Format' instead of format parameters + 형식 매개 변수 대신 'string.Format' 사용 @@ -59,7 +59,7 @@ Pass 'TestContext.CancellationToken' argument to method call - Pass 'TestContext.CancellationToken' argument to method call + 메서드 호출에 'TestContext.CancellationToken' 인수 전달 @@ -129,7 +129,7 @@ Use 'TestContext.CancellationToken' instead - Use 'TestContext.CancellationToken' instead + 대신 'TestContext.CancellationToken' 사용 diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pl.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pl.xlf index baf335c1ed..9e51816347 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pl.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pl.xlf @@ -24,12 +24,12 @@ Use interpolated string instead of format parameters - Use interpolated string instead of format parameters + Użyj ciągu interpolowanego zamiast parametrów formatu Use 'string.Format' instead of format parameters - Use 'string.Format' instead of format parameters + Użyj ciągu „string.Format” zamiast parametrów formatu @@ -59,7 +59,7 @@ Pass 'TestContext.CancellationToken' argument to method call - Pass 'TestContext.CancellationToken' argument to method call + Przekaż argument „TestContext.CancellationToken” do wywołania metody @@ -129,7 +129,7 @@ Use 'TestContext.CancellationToken' instead - Use 'TestContext.CancellationToken' instead + Zamiast tego użyj argumentu „TestContext.CancellationToken” diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pt-BR.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pt-BR.xlf index 5bd2a7c2bd..509eb8d8d4 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pt-BR.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.pt-BR.xlf @@ -24,12 +24,12 @@ Use interpolated string instead of format parameters - Use interpolated string instead of format parameters + Use cadeia de caracteres interpolada em vez de parâmetros de formato Use 'string.Format' instead of format parameters - Use 'string.Format' instead of format parameters + Use 'string.Format' em vez de parâmetros de formato @@ -59,7 +59,7 @@ Pass 'TestContext.CancellationToken' argument to method call - Pass 'TestContext.CancellationToken' argument to method call + Passar o argumento 'TestContext.CancellationToken' para a chamada de método @@ -129,7 +129,7 @@ Use 'TestContext.CancellationToken' instead - Use 'TestContext.CancellationToken' instead + Usar 'TestContext.CancellationToken' em vez disso diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hant.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hant.xlf index bc2241fcd8..67a726771e 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hant.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.zh-Hant.xlf @@ -24,12 +24,12 @@ Use interpolated string instead of format parameters - Use interpolated string instead of format parameters + 請使用差補字串而不是格式參數 Use 'string.Format' instead of format parameters - Use 'string.Format' instead of format parameters + 請使用 'string.Format' 而不是格式參數 @@ -59,7 +59,7 @@ Pass 'TestContext.CancellationToken' argument to method call - Pass 'TestContext.CancellationToken' argument to method call + 將 'TestContext.CancellationToken' 引數傳遞給方法呼叫 @@ -129,7 +129,7 @@ Use 'TestContext.CancellationToken' instead - Use 'TestContext.CancellationToken' instead + 請改為使用 'TestContext.CancellationToken' diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf index 1ba04d86ff..19ae83f02c 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf @@ -134,12 +134,12 @@ El tipo que declara estos métodos también debe respetar las reglas siguientes: Replace '{0}' with format parameters with string.Format or string interpolation - Replace '{0}' with format parameters with string.Format or string interpolation + Reemplace '{0}' con parámetros de formato utilizando string.Format o interpolación de cadenas Avoid using Assert methods with format parameters - Avoid using Assert methods with format parameters + Evite el uso de métodos Assert con parámetros de formato @@ -464,12 +464,12 @@ El tipo que declara estos métodos también debe respetar las reglas siguientes: When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationToken to enable cooperative cancellation and respect test timeouts. - When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationToken to enable cooperative cancellation and respect test timeouts. + Al llamar a métodos asincrónicos que tienen sobrecargas que aceptan un parámetro CancellationToken, es preferible utilizar la sobrecarga con TestContext.CancellationToken para habilitar la cancelación cooperativa y respetar los tiempos de espera de las pruebas. Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationToken' - Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationToken' + Considere utilizar la sobrecarga que acepta un CancellationToken y pase 'TestContext.CancellationToken' @@ -654,17 +654,17 @@ El tipo que declara estos métodos también debe respetar las reglas siguientes: TestContext.CancellationToken provides a more direct way to access the cancellation token compared to TestContext.CancellationTokenSource.Token. - TestContext.CancellationToken provides a more direct way to access the cancellation token compared to TestContext.CancellationTokenSource.Token. + TestContext.CancellationToken proporciona una manera más directa de acceder al token de cancelación en comparación con TestContext.CancellationTokenSource.Token. Use 'TestContext.CancellationToken' instead of 'TestContext.CancellationTokenSource.Token' - Use 'TestContext.CancellationToken' instead of 'TestContext.CancellationTokenSource.Token' + Use 'TestContext.CancellationToken' en lugar de 'TestContext.CancellationTokenSource.Token' Use TestContext.CancellationToken instead of TestContext.CancellationTokenSource.Token - Use TestContext.CancellationToken instead of TestContext.CancellationTokenSource.Token + Use TestContext.CancellationToken en lugar de TestContext.CancellationTokenSource.Token diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf index b8c68db047..f370899372 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf @@ -134,12 +134,12 @@ Le type doit être une classe Replace '{0}' with format parameters with string.Format or string interpolation - Replace '{0}' with format parameters with string.Format or string interpolation + Remplacez « {0} » par des paramètres de format par une chaîne. Mise en forme ou interpolation de chaîne Avoid using Assert methods with format parameters - Avoid using Assert methods with format parameters + Évitez d’utiliser des méthodes Assert avec des paramètres de format @@ -464,12 +464,12 @@ Le type doit être une classe When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationToken to enable cooperative cancellation and respect test timeouts. - When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationToken to enable cooperative cancellation and respect test timeouts. + Lors de l’appel de méthodes asynchrones qui ont des surcharges acceptant un paramètre CancellationToken, préférez utiliser la surcharge avec TestContext.CancellationToken pour activer l’annulation collaborative et respecter les délais d’expiration des tests. Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationToken' - Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationToken' + Envisagez d’utiliser la surcharge qui accepte un CancellationToken et passe « TestContext.CancellationToken » @@ -654,17 +654,17 @@ Le type déclarant ces méthodes doit également respecter les règles suivantes TestContext.CancellationToken provides a more direct way to access the cancellation token compared to TestContext.CancellationTokenSource.Token. - TestContext.CancellationToken provides a more direct way to access the cancellation token compared to TestContext.CancellationTokenSource.Token. + TestContext.CancellationToken offre un moyen plus direct d’accéder au jeton d’annulation par rapport à TestContext.CancellationTokenSource.Token. Use 'TestContext.CancellationToken' instead of 'TestContext.CancellationTokenSource.Token' - Use 'TestContext.CancellationToken' instead of 'TestContext.CancellationTokenSource.Token' + Utilisez « TestContext.CancellationToken » au lieu de « TestContext.CancellationTokenSource.Token » Use TestContext.CancellationToken instead of TestContext.CancellationTokenSource.Token - Use TestContext.CancellationToken instead of TestContext.CancellationTokenSource.Token + Utilisez TestContext.CancellationToken au lieu de TestContext.CancellationTokenSource.Token diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf index 283b08e6f0..0f0a54641f 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf @@ -134,12 +134,12 @@ Anche il tipo che dichiara questi metodi deve rispettare le regole seguenti: Replace '{0}' with format parameters with string.Format or string interpolation - Replace '{0}' with format parameters with string.Format or string interpolation + Sostituire '{0}' con i parametri di formato utilizzando string.Format o l'interpolazione di stringa Avoid using Assert methods with format parameters - Avoid using Assert methods with format parameters + Evitare di usare metodi Assert con parametri di formato @@ -464,12 +464,12 @@ Anche il tipo che dichiara questi metodi deve rispettare le regole seguenti: When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationToken to enable cooperative cancellation and respect test timeouts. - When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationToken to enable cooperative cancellation and respect test timeouts. + Quando si chiamano metodi asincroni con overload che accettano un parametro CancellationToken, preferire l'uso dell'overload con TestContext.CancellationToken per abilitare l'annullamento cooperativo e rispettare i timeout di test. Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationToken' - Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationToken' + Valutare la possibilità di usare l'overload che accetta un CancellationToken e a passare 'TestContext.CancellationToken' @@ -654,17 +654,17 @@ Anche il tipo che dichiara questi metodi deve rispettare le regole seguenti: TestContext.CancellationToken provides a more direct way to access the cancellation token compared to TestContext.CancellationTokenSource.Token. - TestContext.CancellationToken provides a more direct way to access the cancellation token compared to TestContext.CancellationTokenSource.Token. + TestContext.CancellationToken offre un modo più diretto per accedere al token di annullamento rispetto a TestContext.CancellationTokenSource.Token. Use 'TestContext.CancellationToken' instead of 'TestContext.CancellationTokenSource.Token' - Use 'TestContext.CancellationToken' instead of 'TestContext.CancellationTokenSource.Token' + Usare 'TestContext.CancellationToken' invece di 'TestContext.CancellationTokenSource.Token' Use TestContext.CancellationToken instead of TestContext.CancellationTokenSource.Token - Use TestContext.CancellationToken instead of TestContext.CancellationTokenSource.Token + Usare TestContext.CancellationToken invece di TestContext.CancellationTokenSource.Token diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf index 71bd34ea2c..539333cecb 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf @@ -134,12 +134,12 @@ The type declaring these methods should also respect the following rules: Replace '{0}' with format parameters with string.Format or string interpolation - Replace '{0}' with format parameters with string.Format or string interpolation + '{0}'을(를) string.Format이나 문자열 보간을 사용하는 포맷 매개변수로 변경하기 Avoid using Assert methods with format parameters - Avoid using Assert methods with format parameters + 형식 매개 변수를 사용하여 Assert 메서드는 사용하지 마세요 @@ -464,12 +464,12 @@ The type declaring these methods should also respect the following rules: When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationToken to enable cooperative cancellation and respect test timeouts. - When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationToken to enable cooperative cancellation and respect test timeouts. + CancellationToken 매개변수를 허용하는 오버로드가 있는 비동기 메서드를 호출할 때는 협력적 취소를 활성화하고 테스트 시간 제한을 준수하기 위해 TestContext.CancellationToken이 있는 오버로드를 사용하는 것이 좋습니다. Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationToken' - Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationToken' + CancellationToken을 수락하고 'TestContext.CancellationToken'을 전달하는 오버로드를 사용하는 것이 좋습니다. @@ -654,17 +654,17 @@ The type declaring these methods should also respect the following rules: TestContext.CancellationToken provides a more direct way to access the cancellation token compared to TestContext.CancellationTokenSource.Token. - TestContext.CancellationToken provides a more direct way to access the cancellation token compared to TestContext.CancellationTokenSource.Token. + TestContext.CancellationToken은 TestContext.CancellationTokenSource.Token보다 취소 토큰에 더 직접적으로 액세스할 수 있는 방법을 제공합니다. Use 'TestContext.CancellationToken' instead of 'TestContext.CancellationTokenSource.Token' - Use 'TestContext.CancellationToken' instead of 'TestContext.CancellationTokenSource.Token' + 'TestContext.CancellationTokenSource.Token' 대신 'TestContext.CancellationToken' 사용 Use TestContext.CancellationToken instead of TestContext.CancellationTokenSource.Token - Use TestContext.CancellationToken instead of TestContext.CancellationTokenSource.Token + TestContext.CancellationTokenSource.Token 대신 TestContext.CancellationToken 사용 diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf index c2bc027848..b4e579b204 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf @@ -134,12 +134,12 @@ Typ deklarujący te metody powinien również przestrzegać następujących regu Replace '{0}' with format parameters with string.Format or string interpolation - Replace '{0}' with format parameters with string.Format or string interpolation + Zamień „{0}” na parametry formatu za pomocą string.Format lub interpolacji ciągu Avoid using Assert methods with format parameters - Avoid using Assert methods with format parameters + Unikaj używania metod Assert z parametrami formatu @@ -464,12 +464,12 @@ Typ deklarujący te metody powinien również przestrzegać następujących regu When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationToken to enable cooperative cancellation and respect test timeouts. - When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationToken to enable cooperative cancellation and respect test timeouts. + W przypadku wywoływania metod asynchronicznych, które mają przeciążenia akceptujące parametr CancellationToken, preferuj użycie przeciążenia z argumentem TestContext.CancellationToken, aby umożliwić anulowanie w trybie współpracy i respektowanie limitów czasu testu. Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationToken' - Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationToken' + Rozważ użycie przeciążenia, które akceptuje element CancellationToken i przekaż argument „TestContext.CancellationToken” @@ -654,17 +654,17 @@ Typ deklarujący te metody powinien również przestrzegać następujących regu TestContext.CancellationToken provides a more direct way to access the cancellation token compared to TestContext.CancellationTokenSource.Token. - TestContext.CancellationToken provides a more direct way to access the cancellation token compared to TestContext.CancellationTokenSource.Token. + Element TestContext.CancellationToken zapewnia bardziej bezpośredni sposób uzyskiwania dostępu do tokenu anulowania w porównaniu z elementem TestContext.CancellationTokenSource.Token. Use 'TestContext.CancellationToken' instead of 'TestContext.CancellationTokenSource.Token' - Use 'TestContext.CancellationToken' instead of 'TestContext.CancellationTokenSource.Token' + Użyj argumentu „TestContext.CancellationToken” zamiast argumentu „TestContext.CancellationTokenSource.Token” Use TestContext.CancellationToken instead of TestContext.CancellationTokenSource.Token - Use TestContext.CancellationToken instead of TestContext.CancellationTokenSource.Token + Użyj argumentu TestContext.CancellationToken zamiast argumentu TestContext.CancellationTokenSource.Token diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf index 9df61d4f1d..212d7ceb61 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf @@ -134,12 +134,12 @@ O tipo que declara esses métodos também deve respeitar as seguintes regras: Replace '{0}' with format parameters with string.Format or string interpolation - Replace '{0}' with format parameters with string.Format or string interpolation + Substitua '{0}' com parâmetros de formato por cadeia de caracteres. Interpolação de formato ou cadeia de caracteres Avoid using Assert methods with format parameters - Avoid using Assert methods with format parameters + Evite usar métodos Assert com parâmetros de formato @@ -464,12 +464,12 @@ O tipo que declara esses métodos também deve respeitar as seguintes regras: When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationToken to enable cooperative cancellation and respect test timeouts. - When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationToken to enable cooperative cancellation and respect test timeouts. + Ao chamar métodos assíncronos que têm sobrecargas que aceitam um parâmetro CancellationToken, prefira usar a sobrecarga com TestContext.CancellationToken para habilitar o cancelamento cooperativo e respeitar os limites de tempo do teste. Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationToken' - Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationToken' + Considere usar a sobrecarga que aceita um CancellationToken e passar 'TestContext.CancellationToken' @@ -654,17 +654,17 @@ O tipo que declara esses métodos também deve respeitar as seguintes regras: TestContext.CancellationToken provides a more direct way to access the cancellation token compared to TestContext.CancellationTokenSource.Token. - TestContext.CancellationToken provides a more direct way to access the cancellation token compared to TestContext.CancellationTokenSource.Token. + TestContext.CancellationToken oferece uma maneira mais direta de acessar o token de cancelamento em comparação com TestContext.CancellationTokenSource.Token. Use 'TestContext.CancellationToken' instead of 'TestContext.CancellationTokenSource.Token' - Use 'TestContext.CancellationToken' instead of 'TestContext.CancellationTokenSource.Token' + Use 'TestContext.CancellationToken' em vez de 'TestContext.CancellationTokenSource.Token' Use TestContext.CancellationToken instead of TestContext.CancellationTokenSource.Token - Use TestContext.CancellationToken instead of TestContext.CancellationTokenSource.Token + Use TestContext.CancellationToken em vez de TestContext.CancellationTokenSource.Token diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf index 577ed5db55..b3ef5a1058 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf @@ -134,12 +134,12 @@ The type declaring these methods should also respect the following rules: Replace '{0}' with format parameters with string.Format or string interpolation - Replace '{0}' with format parameters with string.Format or string interpolation + 將 '{0}' 取代為具有 string.Format 或字串內插補點的格式參數 Avoid using Assert methods with format parameters - Avoid using Assert methods with format parameters + 避免使用 Assert 方法搭配格式參數 @@ -464,12 +464,12 @@ The type declaring these methods should also respect the following rules: When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationToken to enable cooperative cancellation and respect test timeouts. - When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationToken to enable cooperative cancellation and respect test timeouts. + 在呼叫接受 CancellationToken 參數的多載非同步方法時,建議使用 TestContext.CancellationToken 的多載,以啟用共同取消並遵守測試逾時。 Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationToken' - Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationToken' + 考慮使用接受 CancellationToken 的多載,並傳遞 'TestContext.CancellationToken' @@ -654,17 +654,17 @@ The type declaring these methods should also respect the following rules: TestContext.CancellationToken provides a more direct way to access the cancellation token compared to TestContext.CancellationTokenSource.Token. - TestContext.CancellationToken provides a more direct way to access the cancellation token compared to TestContext.CancellationTokenSource.Token. + 相較於 TestContext.CancellationTokenSource.Token,TestContext.CancellationToken 提供存取取消權杖更直接的方法。 Use 'TestContext.CancellationToken' instead of 'TestContext.CancellationTokenSource.Token' - Use 'TestContext.CancellationToken' instead of 'TestContext.CancellationTokenSource.Token' + 使用 'TestContext.CancellationToken' 而不是 'TestContext.CancellationTokenSource.Token' Use TestContext.CancellationToken instead of TestContext.CancellationTokenSource.Token - Use TestContext.CancellationToken instead of TestContext.CancellationTokenSource.Token + 使用 TestContext.CancellationToken 而不是 TestContext.CancellationTokenSource.Token From 368e8bf7c69fefcb17b9d05dc5db4ef0b24d5650 Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Sat, 30 Aug 2025 15:34:34 +0200 Subject: [PATCH 451/541] [main] Update dependencies from devdiv/DevDiv/vs-code-coverage, dotnet/arcade (#6426) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: dotnet-maestro[bot] Co-authored-by: Youssef Victor Co-authored-by: Amaury Levé --- eng/Version.Details.xml | 16 ++++++++-------- eng/Versions.props | 4 ++-- eng/common/sdk-task.sh | 2 +- global.json | 6 +++--- .../MSBuildTests.ConfigurationFile.cs | 8 +++++++- .../MSBuildTests.GenerateEntryPoint.cs | 12 +++++++++++- ...TestAdapter.PlatformServices.UnitTests.csproj | 2 -- .../MSTestAdapter.UnitTests.csproj | 2 -- 8 files changed, 32 insertions(+), 20 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index 7efbd7fec7..577f2eba08 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -1,21 +1,21 @@ - + https://github.com/dotnet/arcade - 86b53945e6b6b239d68fa465e62fcf4323ff3b7b + ee3cae9ed3ef1990505e891831163ef34220d4e0 - + https://github.com/dotnet/arcade - 86b53945e6b6b239d68fa465e62fcf4323ff3b7b + ee3cae9ed3ef1990505e891831163ef34220d4e0 - + https://github.com/dotnet/arcade - 86b53945e6b6b239d68fa465e62fcf4323ff3b7b + ee3cae9ed3ef1990505e891831163ef34220d4e0 - + https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage - ad8260f1662c4c5e3099cb3ee5b96f38b01a6c6e + 39b5945d998f10b47be7dd8652ddc3261b695a64 https://github.com/microsoft/testfx diff --git a/eng/Versions.props b/eng/Versions.props index 882183a16e..91593d4bd0 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -7,8 +7,8 @@ preview - 10.0.0-beta.25419.2 - 18.0.0-preview.25421.1 + 10.0.0-beta.25427.2 + 18.0.0-preview.25427.2 3.11.0-preview.25429.7 1.9.0-preview.25429.7 diff --git a/eng/common/sdk-task.sh b/eng/common/sdk-task.sh index 0c92f81d74..3270f83fa9 100644 --- a/eng/common/sdk-task.sh +++ b/eng/common/sdk-task.sh @@ -10,7 +10,7 @@ show_usage() { echo "Advanced settings:" echo " --excludeCIBinarylog Don't output binary log (short: -nobl)" - echo " --noWarnAsError Do not warn as error + echo " --noWarnAsError Do not warn as error" echo "" echo "Command line arguments not listed above are passed thru to msbuild." } diff --git a/global.json b/global.json index 58372260be..0afaa7173d 100644 --- a/global.json +++ b/global.json @@ -1,6 +1,6 @@ { "tools": { - "dotnet": "10.0.100-preview.7.25380.108", + "dotnet": "10.0.100-rc.1.25411.109", "runtimes": { "dotnet": [ "3.1.32", @@ -23,7 +23,7 @@ } }, "sdk": { - "version": "10.0.100-preview.7.25380.108", + "version": "10.0.100-rc.1.25411.109", "paths": [ ".dotnet", "$host$" @@ -33,7 +33,7 @@ "rollForward": "latestFeature" }, "msbuild-sdks": { - "Microsoft.DotNet.Arcade.Sdk": "10.0.0-beta.25419.2", + "Microsoft.DotNet.Arcade.Sdk": "10.0.0-beta.25427.2", "MSBuild.Sdk.Extras": "3.0.44" } } diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/MSBuildTests.ConfigurationFile.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/MSBuildTests.ConfigurationFile.cs index 42cbee1fee..12ea1b40ee 100644 --- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/MSBuildTests.ConfigurationFile.cs +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/MSBuildTests.ConfigurationFile.cs @@ -60,7 +60,13 @@ public async Task ConfigFileGeneration_NoConfigurationFile_TaskWontRun(string tf DotnetMuxerResult compilationResult = await DotnetCli.RunAsync($"{(verb == Verb.publish ? $"publish -f {tfm}" : "build")} -v:diagnostic -nodeReuse:false {testAsset.TargetAssetPath} -c {compilationMode}", AcceptanceFixture.NuGetGlobalPackagesFolder.Path); var testHost = TestInfrastructure.TestHost.LocateFrom(testAsset.TargetAssetPath, "MSBuildTests", tfm, verb: verb, buildConfiguration: compilationMode); - Assert.Contains("Target \"_GenerateTestingPlatformConfigurationFileCore\" skipped, due to false condition;", compilationResult.StandardOutput); + + // Working around MSBuild regression: waiting for fix https://github.com/dotnet/msbuild/pull/12431 + // After we insert a new SDK version that ships with a working MSBuild, the DoesNotContain assert will fail. + // Then, remove the DoesNotContain line, and uncomment the Contains line. + // Assert.Contains("Target \"_GenerateTestingPlatformConfigurationFileCore\" skipped, due to false condition;", compilationResult.StandardOutput); + Assert.DoesNotContain("_GenerateTestingPlatformConfigurationFileCore", compilationResult.StandardOutput); + string generatedConfigurationFile = Path.Combine(testHost.DirectoryName, "MSBuildTests.testconfig.json"); Assert.IsFalse(File.Exists(generatedConfigurationFile)); } diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/MSBuildTests.GenerateEntryPoint.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/MSBuildTests.GenerateEntryPoint.cs index 2f7e11173c..6818dca991 100644 --- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/MSBuildTests.GenerateEntryPoint.cs +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/MSBuildTests.GenerateEntryPoint.cs @@ -22,8 +22,18 @@ public async Task When_GenerateTestingPlatformEntryPoint_IsFalse_NoEntryPointInj DotnetMuxerResult compilationResult = await DotnetCli.RunAsync($"restore -r {RID} {testAsset.TargetAssetPath}{Path.DirectorySeparatorChar}MSBuildTests.csproj ", AcceptanceFixture.NuGetGlobalPackagesFolder.Path); compilationResult = await DotnetCli.RunAsync($"{(verb == Verb.publish ? $"publish -f {tfm}" : "build")} -c {compilationMode} -r {RID} -nodeReuse:false -p:GenerateTestingPlatformEntryPoint=False {testAsset.TargetAssetPath} -v:n", AcceptanceFixture.NuGetGlobalPackagesFolder.Path, failIfReturnValueIsNotZero: false); SL.Build binLog = SL.Serialization.Read(compilationResult.BinlogPath!); - SL.Target generateTestingPlatformEntryPoint = binLog.FindChildrenRecursive().Single(t => t.Name == "_GenerateTestingPlatformEntryPoint"); + + IEnumerable generateTestingPlatformEntryPointTargets = binLog.FindChildrenRecursive().Where(t => t.Name == "_GenerateTestingPlatformEntryPoint"); + + // Working around MSBuild regression: waiting for fix https://github.com/dotnet/msbuild/pull/12431 + // After we insert a new SDK version that ships with a working MSBuild, the IsEmpty assert will fail. + // Then, remove the IsEmpty line, and bring back the code in #if false. + Assert.IsEmpty(generateTestingPlatformEntryPointTargets); +#if false + SL.Target generateTestingPlatformEntryPoint = generateTestingPlatformEntryPointTargets.Single(); Assert.AreEqual("Target \"_GenerateTestingPlatformEntryPoint\" skipped, due to false condition; ( '$(GenerateTestingPlatformEntryPoint)' == 'true' ) was evaluated as ( 'False' == 'true' ).", ((SL.Message)generateTestingPlatformEntryPoint.Children[0]).Text); +#endif + SL.Target includeGenerateTestingPlatformEntryPointIntoCompilation = binLog.FindChildrenRecursive().Single(t => t.Name == "_IncludeGenerateTestingPlatformEntryPointIntoCompilation"); Assert.IsEmpty(includeGenerateTestingPlatformEntryPointIntoCompilation.Children); compilationResult.AssertExitCodeIsNot(0); diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/MSTestAdapter.PlatformServices.UnitTests.csproj b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/MSTestAdapter.PlatformServices.UnitTests.csproj index 46cd16bf11..4065f07f1f 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/MSTestAdapter.PlatformServices.UnitTests.csproj +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/MSTestAdapter.PlatformServices.UnitTests.csproj @@ -42,8 +42,6 @@ - - diff --git a/test/UnitTests/MSTestAdapter.UnitTests/MSTestAdapter.UnitTests.csproj b/test/UnitTests/MSTestAdapter.UnitTests/MSTestAdapter.UnitTests.csproj index bedb8b4472..cb3f94b7b0 100644 --- a/test/UnitTests/MSTestAdapter.UnitTests/MSTestAdapter.UnitTests.csproj +++ b/test/UnitTests/MSTestAdapter.UnitTests/MSTestAdapter.UnitTests.csproj @@ -38,8 +38,6 @@ - - From 51a063d985a9d69b7942c5b29e5bbc13fa55a9eb Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Sun, 31 Aug 2025 06:35:56 +0200 Subject: [PATCH 452/541] [main] Update dependencies from dotnet/arcade (#6473) Co-authored-by: dotnet-maestro[bot] --- eng/Version.Details.xml | 12 ++++++------ eng/Versions.props | 2 +- global.json | 2 +- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index 577f2eba08..8624b23391 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -1,17 +1,17 @@ - + https://github.com/dotnet/arcade - ee3cae9ed3ef1990505e891831163ef34220d4e0 + 6122520523105dacdd702177a76c9f6b982fd759 - + https://github.com/dotnet/arcade - ee3cae9ed3ef1990505e891831163ef34220d4e0 + 6122520523105dacdd702177a76c9f6b982fd759 - + https://github.com/dotnet/arcade - ee3cae9ed3ef1990505e891831163ef34220d4e0 + 6122520523105dacdd702177a76c9f6b982fd759 https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage diff --git a/eng/Versions.props b/eng/Versions.props index 91593d4bd0..12fee195e6 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -7,7 +7,7 @@ preview - 10.0.0-beta.25427.2 + 10.0.0-beta.25430.1 18.0.0-preview.25427.2 3.11.0-preview.25429.7 diff --git a/global.json b/global.json index 0afaa7173d..b3b2d78d99 100644 --- a/global.json +++ b/global.json @@ -33,7 +33,7 @@ "rollForward": "latestFeature" }, "msbuild-sdks": { - "Microsoft.DotNet.Arcade.Sdk": "10.0.0-beta.25427.2", + "Microsoft.DotNet.Arcade.Sdk": "10.0.0-beta.25430.1", "MSBuild.Sdk.Extras": "3.0.44" } } From 9d2e740bc8be46f45c6d69b33be1f5a913bf6231 Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Sun, 31 Aug 2025 08:17:55 +0200 Subject: [PATCH 453/541] [main] Update dependencies from microsoft/testfx (#6474) Co-authored-by: dotnet-maestro[bot] --- eng/Version.Details.xml | 8 ++++---- eng/Versions.props | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index 8624b23391..c6d49af08a 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -17,13 +17,13 @@ https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage 39b5945d998f10b47be7dd8652ddc3261b695a64 - + https://github.com/microsoft/testfx - ba1eec5203c8856fe5437790dfb00cd448352bb8 + 368e8bf7c69fefcb17b9d05dc5db4ef0b24d5650 - + https://github.com/microsoft/testfx - ba1eec5203c8856fe5437790dfb00cd448352bb8 + 368e8bf7c69fefcb17b9d05dc5db4ef0b24d5650 diff --git a/eng/Versions.props b/eng/Versions.props index 12fee195e6..416aab582e 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -10,7 +10,7 @@ 10.0.0-beta.25430.1 18.0.0-preview.25427.2 - 3.11.0-preview.25429.7 - 1.9.0-preview.25429.7 + 3.11.0-preview.25430.3 + 1.9.0-preview.25430.3 From a8bd57bd6f5eefbde2caf8ad9857436083da6cbb Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Mon, 1 Sep 2025 06:36:11 +0000 Subject: [PATCH 454/541] [main] Update dependencies from microsoft/testfx (#6476) Co-authored-by: dotnet-maestro[bot] --- eng/Version.Details.xml | 8 ++++---- eng/Versions.props | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index c6d49af08a..798337f3b4 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -17,13 +17,13 @@ https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage 39b5945d998f10b47be7dd8652ddc3261b695a64 - + https://github.com/microsoft/testfx - 368e8bf7c69fefcb17b9d05dc5db4ef0b24d5650 + 9d2e740bc8be46f45c6d69b33be1f5a913bf6231 - + https://github.com/microsoft/testfx - 368e8bf7c69fefcb17b9d05dc5db4ef0b24d5650 + 9d2e740bc8be46f45c6d69b33be1f5a913bf6231 diff --git a/eng/Versions.props b/eng/Versions.props index 416aab582e..85d48a0c29 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -10,7 +10,7 @@ 10.0.0-beta.25430.1 18.0.0-preview.25427.2 - 3.11.0-preview.25430.3 - 1.9.0-preview.25430.3 + 3.11.0-preview.25430.5 + 1.9.0-preview.25430.5 From 8d29291af97543579834e9109768c5ee89f63638 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Mon, 1 Sep 2025 11:09:41 +0200 Subject: [PATCH 455/541] Don't keep MTP process alive if pipe disconnects (#6477) --- .../HangDumpActivityIndicator.cs | 2 +- .../HangDumpProcessLifetimeHandler.cs | 2 +- .../TrxTestApplicationLifecycleCallbacks.cs | 2 +- .../Hosts/TestHostBuilder.cs | 2 +- .../IPC/NamedPipeClient.cs | 21 +++++++++++++++++-- .../DotnetTest/DotnetTestConnection.cs | 2 +- 6 files changed, 24 insertions(+), 7 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Extensions.HangDump/HangDumpActivityIndicator.cs b/src/Platform/Microsoft.Testing.Extensions.HangDump/HangDumpActivityIndicator.cs index ed6a65341d..cde00c838d 100644 --- a/src/Platform/Microsoft.Testing.Extensions.HangDump/HangDumpActivityIndicator.cs +++ b/src/Platform/Microsoft.Testing.Extensions.HangDump/HangDumpActivityIndicator.cs @@ -65,7 +65,7 @@ public HangDumpActivityIndicator( string pipeNameEnvironmentVariable = $"{HangDumpConfiguration.PipeName}_{FNV_1aHashHelper.ComputeStringHash(testApplicationModuleInfo.GetCurrentTestApplicationFullPath())}_{namedPipeSuffix}"; string namedPipeName = _environment.GetEnvironmentVariable(pipeNameEnvironmentVariable) ?? throw new InvalidOperationException($"Expected {pipeNameEnvironmentVariable} environment variable set."); - _namedPipeClient = new NamedPipeClient(namedPipeName); + _namedPipeClient = new NamedPipeClient(namedPipeName, _environment); _namedPipeClient.RegisterSerializer(new ActivityIndicatorMutexNameRequestSerializer(), typeof(ActivityIndicatorMutexNameRequest)); _namedPipeClient.RegisterSerializer(new VoidResponseSerializer(), typeof(VoidResponse)); _namedPipeClient.RegisterSerializer(new SessionEndSerializerRequestSerializer(), typeof(SessionEndSerializerRequest)); diff --git a/src/Platform/Microsoft.Testing.Extensions.HangDump/HangDumpProcessLifetimeHandler.cs b/src/Platform/Microsoft.Testing.Extensions.HangDump/HangDumpProcessLifetimeHandler.cs index 2f41e6fa6e..03130bdd14 100644 --- a/src/Platform/Microsoft.Testing.Extensions.HangDump/HangDumpProcessLifetimeHandler.cs +++ b/src/Platform/Microsoft.Testing.Extensions.HangDump/HangDumpProcessLifetimeHandler.cs @@ -159,7 +159,7 @@ private async Task CallbackAsync(IRequest request) else if (request is ConsumerPipeNameRequest consumerPipeNameRequest) { await _logger.LogDebugAsync($"Consumer pipe name received '{consumerPipeNameRequest.PipeName}'").ConfigureAwait(false); - _namedPipeClient = new NamedPipeClient(consumerPipeNameRequest.PipeName); + _namedPipeClient = new NamedPipeClient(consumerPipeNameRequest.PipeName, _environment); _namedPipeClient.RegisterSerializer(new GetInProgressTestsResponseSerializer(), typeof(GetInProgressTestsResponse)); _namedPipeClient.RegisterSerializer(new GetInProgressTestsRequestSerializer(), typeof(GetInProgressTestsRequest)); _namedPipeClient.RegisterSerializer(new ExitSignalActivityIndicatorTaskRequestSerializer(), typeof(ExitSignalActivityIndicatorTaskRequest)); diff --git a/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxTestApplicationLifecycleCallbacks.cs b/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxTestApplicationLifecycleCallbacks.cs index d1057fcef1..0fc71314fa 100644 --- a/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxTestApplicationLifecycleCallbacks.cs +++ b/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxTestApplicationLifecycleCallbacks.cs @@ -63,7 +63,7 @@ public async Task BeforeRunAsync(CancellationToken cancellationToken) { string namedPipeName = _environment.GetEnvironmentVariable(TrxEnvironmentVariableProvider.TRXNAMEDPIPENAME) ?? throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, ExtensionResources.TrxReportGeneratorMissingTrxNamedPipeEnvironmentVariable, TrxEnvironmentVariableProvider.TRXNAMEDPIPENAME)); - NamedPipeClient = new NamedPipeClient(namedPipeName); + NamedPipeClient = new NamedPipeClient(namedPipeName, _environment); NamedPipeClient.RegisterSerializer(new ReportFileNameRequestSerializer(), typeof(ReportFileNameRequest)); NamedPipeClient.RegisterSerializer(new TestAdapterInformationRequestSerializer(), typeof(TestAdapterInformationRequest)); NamedPipeClient.RegisterSerializer(new VoidResponseSerializer(), typeof(VoidResponse)); diff --git a/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostBuilder.cs b/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostBuilder.cs index b51e0dc081..2a88a5c5e1 100644 --- a/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostBuilder.cs +++ b/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostBuilder.cs @@ -545,7 +545,7 @@ await LogTestHostCreatedAsync( environment.SetEnvironmentVariable(pipeEnvironmentVariable, string.Empty); // Create client to connect to the monitor - NamedPipeClient client = new(pipeName); + NamedPipeClient client = new(pipeName, environment); client.RegisterAllSerializers(); // Connect to the monitor diff --git a/src/Platform/Microsoft.Testing.Platform/IPC/NamedPipeClient.cs b/src/Platform/Microsoft.Testing.Platform/IPC/NamedPipeClient.cs index 1ea5418212..9ed2f8d971 100644 --- a/src/Platform/Microsoft.Testing.Platform/IPC/NamedPipeClient.cs +++ b/src/Platform/Microsoft.Testing.Platform/IPC/NamedPipeClient.cs @@ -3,12 +3,12 @@ #if NETCOREAPP using System.Buffers; - -using Microsoft.Testing.Platform.Helpers; #endif using System.IO.Pipes; +using Microsoft.Testing.Platform.Helpers; + #if NET using Microsoft.Testing.Platform.Resources; #endif @@ -24,14 +24,21 @@ internal sealed class NamedPipeClient : NamedPipeBase, IClient private readonly MemoryStream _serializationBuffer = new(); private readonly MemoryStream _messageBuffer = new(); private readonly byte[] _readBuffer = new byte[250000]; + private readonly IEnvironment _environment; private bool _disposed; public NamedPipeClient(string name) + : this(name, new SystemEnvironment()) + { + } + + public NamedPipeClient(string name, IEnvironment environment) { Guard.NotNull(name); _namedPipeClientStream = new(".", name, PipeDirection.InOut); PipeName = name; + _environment = environment; } public string PipeName { get; } @@ -144,6 +151,16 @@ public async Task RequestReplyAsync(TRequest req int currentReadBytes = await _namedPipeClientStream.ReadAsync(_readBuffer, currentReadIndex, _readBuffer.Length, cancellationToken).ConfigureAwait(false); #endif + if (currentReadBytes == 0) + { + // We are reading a message response. + // If we cannot get a response, there is no way we can recover and continue executing. + // This can happen if the other processes gets killed or crashes while while it's sending the response. + // This is especially important for 'dotnet test', where the user can simply kill the dotnet.exe process themselves. + // In that case, we want the MTP process to also die. + _environment.FailFast("[NamedPipeClient] Connection lost with the other side."); + } + // Reset the current chunk size int missingBytesToReadOfCurrentChunk = currentReadBytes; diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/DotnetTestConnection.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/DotnetTestConnection.cs index 25dcc9d34c..dc9cc2902b 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/DotnetTestConnection.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/DotnetTestConnection.cs @@ -56,7 +56,7 @@ public async Task AfterCommonServiceSetupAsync() _environment.SetEnvironmentVariable(EnvironmentVariableConstants.TESTINGPLATFORM_DOTNETTEST_EXECUTIONID, Guid.NewGuid().ToString("N")); } - _dotnetTestPipeClient = new(arguments[0]); + _dotnetTestPipeClient = new(arguments[0], _environment); _dotnetTestPipeClient.RegisterAllSerializers(); await _dotnetTestPipeClient.ConnectAsync(_cancellationTokenSource.CancellationToken).ConfigureAwait(false); From 582c60ab38156f88b048802b221be2a929b3c452 Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Tue, 2 Sep 2025 03:36:57 +0000 Subject: [PATCH 456/541] [main] Update dependencies from microsoft/testfx (#6485) Co-authored-by: dotnet-maestro[bot] --- eng/Version.Details.xml | 8 ++++---- eng/Versions.props | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index 798337f3b4..d3a5e9bc06 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -17,13 +17,13 @@ https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage 39b5945d998f10b47be7dd8652ddc3261b695a64 - + https://github.com/microsoft/testfx - 9d2e740bc8be46f45c6d69b33be1f5a913bf6231 + 8d29291af97543579834e9109768c5ee89f63638 - + https://github.com/microsoft/testfx - 9d2e740bc8be46f45c6d69b33be1f5a913bf6231 + 8d29291af97543579834e9109768c5ee89f63638 diff --git a/eng/Versions.props b/eng/Versions.props index 85d48a0c29..f3b68d4ce7 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -10,7 +10,7 @@ 10.0.0-beta.25430.1 18.0.0-preview.25427.2 - 3.11.0-preview.25430.5 - 1.9.0-preview.25430.5 + 3.11.0-preview.25451.2 + 1.9.0-preview.25451.2 From 4920aff5a2d41bd0dff03a97e714b1c98bb7e26d Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Tue, 2 Sep 2025 09:10:28 +0200 Subject: [PATCH 457/541] Fix MSTEST0001 (parallelization analyzer) to work with VSTest (#6480) --- .../common/MSTest.TestAdapter.props | 1 + .../common/MSTest.TestAdapter.targets | 4 ++ .../uwp/MSTest.TestAdapter.props | 1 + .../uwp/MSTest.TestAdapter.targets | 4 ++ .../UseParallelizeAttributeAnalyzer.cs | 5 +- .../AnalyzersTests.cs | 56 +++++++++++++++++++ .../UseParallelizeAttributeAnalyzerTests.cs | 13 +++-- 7 files changed, 77 insertions(+), 7 deletions(-) diff --git a/src/Adapter/MSTest.TestAdapter/buildTransitive/common/MSTest.TestAdapter.props b/src/Adapter/MSTest.TestAdapter/buildTransitive/common/MSTest.TestAdapter.props index 639ce61536..1e14ef753e 100644 --- a/src/Adapter/MSTest.TestAdapter/buildTransitive/common/MSTest.TestAdapter.props +++ b/src/Adapter/MSTest.TestAdapter/buildTransitive/common/MSTest.TestAdapter.props @@ -2,6 +2,7 @@ true + true diff --git a/src/Adapter/MSTest.TestAdapter/buildTransitive/common/MSTest.TestAdapter.targets b/src/Adapter/MSTest.TestAdapter/buildTransitive/common/MSTest.TestAdapter.targets index 2feb8c652b..06b5afe773 100644 --- a/src/Adapter/MSTest.TestAdapter/buildTransitive/common/MSTest.TestAdapter.targets +++ b/src/Adapter/MSTest.TestAdapter/buildTransitive/common/MSTest.TestAdapter.targets @@ -51,6 +51,10 @@ + + + + diff --git a/src/Adapter/MSTest.TestAdapter/buildTransitive/uwp/MSTest.TestAdapter.props b/src/Adapter/MSTest.TestAdapter/buildTransitive/uwp/MSTest.TestAdapter.props index 259e47a969..d38f1c2bdf 100644 --- a/src/Adapter/MSTest.TestAdapter/buildTransitive/uwp/MSTest.TestAdapter.props +++ b/src/Adapter/MSTest.TestAdapter/buildTransitive/uwp/MSTest.TestAdapter.props @@ -2,6 +2,7 @@ true + true diff --git a/src/Adapter/MSTest.TestAdapter/buildTransitive/uwp/MSTest.TestAdapter.targets b/src/Adapter/MSTest.TestAdapter/buildTransitive/uwp/MSTest.TestAdapter.targets index e8d37601f3..46bf3f788d 100644 --- a/src/Adapter/MSTest.TestAdapter/buildTransitive/uwp/MSTest.TestAdapter.targets +++ b/src/Adapter/MSTest.TestAdapter/buildTransitive/uwp/MSTest.TestAdapter.targets @@ -27,6 +27,10 @@ + + + + 3.11.0-preview.25451.2 1.9.0-preview.25451.2 diff --git a/eng/common/core-templates/steps/generate-sbom.yml b/eng/common/core-templates/steps/generate-sbom.yml index c05f650279..003f7eae0f 100644 --- a/eng/common/core-templates/steps/generate-sbom.yml +++ b/eng/common/core-templates/steps/generate-sbom.yml @@ -5,7 +5,7 @@ # IgnoreDirectories - Directories to ignore for SBOM generation. This will be passed through to the CG component detector. parameters: - PackageVersion: 10.0.0 + PackageVersion: 11.0.0 BuildDropPath: '$(System.DefaultWorkingDirectory)/artifacts' PackageName: '.NET' ManifestDirPath: $(Build.ArtifactStagingDirectory)/sbom diff --git a/global.json b/global.json index b3b2d78d99..03bd9c8f95 100644 --- a/global.json +++ b/global.json @@ -33,7 +33,7 @@ "rollForward": "latestFeature" }, "msbuild-sdks": { - "Microsoft.DotNet.Arcade.Sdk": "10.0.0-beta.25430.1", + "Microsoft.DotNet.Arcade.Sdk": "11.0.0-beta.25452.3", "MSBuild.Sdk.Extras": "3.0.44" } } From fb728fe3575465724ba9a3e0f4d3e89ba3562b20 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Wed, 3 Sep 2025 09:23:09 +0200 Subject: [PATCH 463/541] Use AwesomeAssertions for framework UTs (#6446) --- .../Assertions/AssertTests.AreEqualTests.cs | 977 +++++++++++------- .../Assertions/AssertTests.AreSame.cs | 58 +- .../AssertTests.InconclusiveTests.cs | 14 +- .../Assertions/AssertTests.IsInRange.cs | 15 +- .../AssertTests.IsInstanceOfTypeTests.cs | 88 +- .../Assertions/AssertTests.IsNull.cs | 50 +- .../Assertions/AssertTests.IsTrueTests.cs | 122 ++- .../Assertions/AssertTests.Items.cs | 123 ++- .../AssertTests.ThrowsExceptionTests.cs | 249 ++--- .../Assertions/AssertTests.cs | 30 +- .../Assertions/CollectionAssertTests.cs | 99 +- .../Assertions/StringAssertTests.cs | 52 +- .../Attributes/DataRowAttributeTests.cs | 44 +- .../Attributes/DynamicDataAttributeTests.cs | 171 +-- .../ExpectedExceptionAttributeTests.cs | 20 +- .../ExpectedExceptionBaseAttributeTests.cs | 19 +- .../GitHubWorkItemTests.cs | 40 +- .../TestFramework.UnitTests/LoggerTests.cs | 16 +- .../TestDataRowTests.cs | 38 +- .../TestResultTests.cs | 20 +- 20 files changed, 1349 insertions(+), 896 deletions(-) diff --git a/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.AreEqualTests.cs b/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.AreEqualTests.cs index 805c9bc53d..a5b4d2223c 100644 --- a/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.AreEqualTests.cs +++ b/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.AreEqualTests.cs @@ -9,92 +9,139 @@ namespace Microsoft.VisualStudio.TestPlatform.TestFramework.UnitTests; public partial class AssertTests : TestContainer { - public void AreNotEqualShouldFailWhenNotEqualType() => - VerifyThrows(() => Assert.AreNotEqual(1, 1)); + public void AreNotEqualShouldFailWhenNotEqualType() + { + Action action = () => Assert.AreNotEqual(1, 1); + action.Should().Throw(); + } public void AreNotEqualShouldFailWhenNotEqualTypeWithMessage() { - Exception ex = VerifyThrows(() => Assert.AreNotEqual(1, 1, "A Message")); - Verify(ex.Message.Contains("A Message")); + Action action = () => Assert.AreNotEqual(1, 1, "A Message"); + action.Should().Throw() + .And.Message.Should().Contain("A Message"); } - public void AreNotEqualShouldFailWhenNotEqualString() => - VerifyThrows(() => Assert.AreNotEqual("A", "A")); + public void AreNotEqualShouldFailWhenNotEqualString() + { + Action action = () => Assert.AreNotEqual("A", "A"); + action.Should().Throw(); + } public void AreNotEqualShouldFailWhenNotEqualStringWithMessage() { - Exception ex = VerifyThrows(() => Assert.AreNotEqual("A", "A", "A Message")); - Verify(ex.Message.Contains("A Message")); + Action action = () => Assert.AreNotEqual("A", "A", "A Message"); + action.Should().Throw() + .And.Message.Should().Contain("A Message"); } [SuppressMessage("Globalization", "CA1304:Specify CultureInfo", Justification = "Testing the API without the culture")] - public void AreNotEqualShouldFailWhenNotEqualStringAndCaseIgnored() => - VerifyThrows(() => Assert.AreNotEqual("A", "a", true)); + public void AreNotEqualShouldFailWhenNotEqualStringAndCaseIgnored() + { + Action action = () => Assert.AreNotEqual("A", "a", true); + action.Should().Throw(); + } - public void AreNotEqualShouldFailWhenNotEqualInt() => - VerifyThrows(() => Assert.AreNotEqual(1, 1)); + public void AreNotEqualShouldFailWhenNotEqualInt() + { + Action action = () => Assert.AreNotEqual(1, 1); + action.Should().Throw(); + } public void AreNotEqualShouldFailWhenNotEqualIntWithMessage() { - Exception ex = VerifyThrows(() => Assert.AreNotEqual(1, 1, "A Message")); - Verify(ex.Message.Contains("A Message")); + Action action = () => Assert.AreNotEqual(1, 1, "A Message"); + action.Should().Throw() + .And.Message.Should().Contain("A Message"); } - public void AreNotEqualShouldFailWhenNotEqualLong() => - VerifyThrows(() => Assert.AreNotEqual(1L, 1L)); + public void AreNotEqualShouldFailWhenNotEqualLong() + { + Action action = () => Assert.AreNotEqual(1L, 1L); + action.Should().Throw(); + } public void AreNotEqualShouldFailWhenNotEqualLongWithMessage() { - Exception ex = VerifyThrows(() => Assert.AreNotEqual(1L, 1L, "A Message")); - Verify(ex.Message.Contains("A Message")); + Action action = () => Assert.AreNotEqual(1L, 1L, "A Message"); + action.Should().Throw() + .And.Message.Should().Contain("A Message"); } - public void AreNotEqualShouldFailWhenNotEqualLongWithDelta() => - VerifyThrows(() => Assert.AreNotEqual(1L, 2L, 1L)); + public void AreNotEqualShouldFailWhenNotEqualLongWithDelta() + { + Action action = () => Assert.AreNotEqual(1L, 2L, 1L); + action.Should().Throw(); + } - public void AreNotEqualShouldFailWhenNotEqualDecimal() => - VerifyThrows(() => Assert.AreNotEqual(0.1M, 0.1M)); + public void AreNotEqualShouldFailWhenNotEqualDecimal() + { + Action action = () => Assert.AreNotEqual(0.1M, 0.1M); + action.Should().Throw(); + } public void AreNotEqualShouldFailWhenNotEqualDecimalWithMessage() { - Exception ex = VerifyThrows(() => Assert.AreNotEqual(0.1M, 0.1M, "A Message")); - Verify(ex.Message.Contains("A Message")); + Action action = () => Assert.AreNotEqual(0.1M, 0.1M, "A Message"); + action.Should().Throw() + .And.Message.Should().Contain("A Message"); } - public void AreNotEqualShouldFailWhenNotEqualDecimalWithDelta() => - VerifyThrows(() => Assert.AreNotEqual(0.1M, 0.2M, 0.1M)); + public void AreNotEqualShouldFailWhenNotEqualDecimalWithDelta() + { + Action action = () => Assert.AreNotEqual(0.1M, 0.2M, 0.1M); + action.Should().Throw(); + } - public void AreNotEqualShouldFailWhenNotEqualDouble() => - VerifyThrows(() => Assert.AreNotEqual(0.1, 0.1)); + public void AreNotEqualShouldFailWhenNotEqualDouble() + { + Action action = () => Assert.AreNotEqual(0.1, 0.1); + action.Should().Throw(); + } public void AreNotEqualShouldFailWhenNotEqualDoubleWithMessage() { - Exception ex = VerifyThrows(() => Assert.AreNotEqual(0.1, 0.1, "A Message")); - Verify(ex.Message.Contains("A Message")); + Action action = () => Assert.AreNotEqual(0.1, 0.1, "A Message"); + action.Should().Throw() + .And.Message.Should().Contain("A Message"); } - public void AreNotEqualShouldFailWhenNotEqualDoubleWithDelta() => - VerifyThrows(() => Assert.AreNotEqual(0.1, 0.2, 0.1)); + public void AreNotEqualShouldFailWhenNotEqualDoubleWithDelta() + { + Action action = () => Assert.AreNotEqual(0.1, 0.2, 0.1); + action.Should().Throw(); + } - public void AreNotEqualShouldFailWhenFloatDouble() => - VerifyThrows(() => Assert.AreNotEqual(100E-2, 100E-2)); + public void AreNotEqualShouldFailWhenFloatDouble() + { + Action action = () => Assert.AreNotEqual(100E-2, 100E-2); + action.Should().Throw(); + } public void AreNotEqualShouldFailWhenFloatDoubleWithMessage() { - Exception ex = VerifyThrows(() => Assert.AreNotEqual(100E-2, 100E-2, "A Message")); - Verify(ex.Message.Contains("A Message")); + Action action = () => Assert.AreNotEqual(100E-2, 100E-2, "A Message"); + action.Should().Throw() + .And.Message.Should().Contain("A Message"); } - public void AreNotEqualShouldFailWhenNotEqualFloatWithDelta() => - VerifyThrows(() => Assert.AreNotEqual(100E-2, 200E-2, 100E-2)); + public void AreNotEqualShouldFailWhenNotEqualFloatWithDelta() + { + Action action = () => Assert.AreNotEqual(100E-2, 200E-2, 100E-2); + action.Should().Throw(); + } - public void AreEqualShouldFailWhenNotEqualType() => - VerifyThrows(() => Assert.AreEqual(null, "string")); + public void AreEqualShouldFailWhenNotEqualType() + { + Action action = () => Assert.AreEqual(null, "string"); + action.Should().Throw(); + } public void AreEqualShouldFailWhenNotEqualTypeWithMessage() { - Exception ex = VerifyThrows(() => Assert.AreEqual(null, "string", "A Message")); - Verify(ex.Message.Contains("A Message")); + Action action = () => Assert.AreEqual(null, "string", "A Message"); + action.Should().Throw() + .And.Message.Should().Contain("A Message"); } public void AreEqual_WithTurkishCultureAndIgnoreCase_Throws() @@ -104,7 +151,8 @@ public void AreEqual_WithTurkishCultureAndIgnoreCase_Throws() var turkishCulture = new CultureInfo("tr-TR"); // In the tr-TR culture, "i" and "I" are not considered equal when doing a case-insensitive comparison. - VerifyThrows(() => Assert.AreEqual(expected, actual, true, turkishCulture)); + Action action = () => Assert.AreEqual(expected, actual, true, turkishCulture); + action.Should().Throw(); } public void AreEqual_WithEnglishCultureAndIgnoreCase_DoesNotThrow() @@ -124,8 +172,9 @@ public void AreEqual_WithEnglishCultureAndDoesNotIgnoreCase_Throws() var englishCulture = new CultureInfo("en-EN"); // Won't ignore case. - Exception ex = VerifyThrows(() => Assert.AreEqual(expected, actual, false, englishCulture)); - Verify(ex.Message == "Assert.AreEqual failed. Expected:. Case is different for actual value:. "); + Action action = () => Assert.AreEqual(expected, actual, false, englishCulture); + action.Should().Throw() + .And.Message.Should().Be("Assert.AreEqual failed. Expected:. Case is different for actual value:. "); } public void AreEqual_WithTurkishCultureAndDoesNotIgnoreCase_Throws() @@ -135,86 +184,125 @@ public void AreEqual_WithTurkishCultureAndDoesNotIgnoreCase_Throws() var turkishCulture = new CultureInfo("tr-TR"); // Won't ignore case. - VerifyThrows(() => Assert.AreEqual(expected, actual, false, turkishCulture)); + Action action = () => Assert.AreEqual(expected, actual, false, turkishCulture); + action.Should().Throw(); } public void AreEqualShouldFailWhenNotEqualStringWithMessage() { - Exception ex = VerifyThrows(() => Assert.AreEqual("A", "a", "A Message")); - Verify(ex.Message.Contains("A Message")); + Action action = () => Assert.AreEqual("A", "a", "A Message"); + action.Should().Throw() + .And.Message.Should().Contain("A Message"); } [SuppressMessage("Globalization", "CA1304:Specify CultureInfo", Justification = "Testing the API without the culture")] - public void AreEqualShouldFailWhenNotEqualStringAndCaseIgnored() => - VerifyThrows(() => Assert.AreEqual("A", "a", false)); + public void AreEqualShouldFailWhenNotEqualStringAndCaseIgnored() + { + Action action = () => Assert.AreEqual("A", "a", false); + action.Should().Throw(); + } - public void AreEqualShouldFailWhenNotEqualInt() => - VerifyThrows(() => Assert.AreEqual(1, 2)); + public void AreEqualShouldFailWhenNotEqualInt() + { + Action action = () => Assert.AreEqual(1, 2); + action.Should().Throw(); + } public void AreEqualShouldFailWhenNotEqualIntWithMessage() { - Exception ex = VerifyThrows(() => Assert.AreEqual(1, 2, "A Message")); - Verify(ex.Message.Contains("A Message")); + Action action = () => Assert.AreEqual(1, 2, "A Message"); + action.Should().Throw() + .And.Message.Should().Contain("A Message"); } - public void AreEqualShouldFailWhenNotEqualLong() => - VerifyThrows(() => Assert.AreEqual(1L, 2L)); + public void AreEqualShouldFailWhenNotEqualLong() + { + Action action = () => Assert.AreEqual(1L, 2L); + action.Should().Throw(); + } public void AreEqualShouldFailWhenNotEqualLongWithMessage() { - Exception ex = VerifyThrows(() => Assert.AreEqual(1L, 2L, "A Message")); - Verify(ex.Message.Contains("A Message")); + Action action = () => Assert.AreEqual(1L, 2L, "A Message"); + action.Should().Throw() + .And.Message.Should().Contain("A Message"); } - public void AreEqualShouldFailWhenNotEqualLongWithDelta() => - VerifyThrows(() => Assert.AreEqual(10L, 20L, 5L)); + public void AreEqualShouldFailWhenNotEqualLongWithDelta() + { + Action action = () => Assert.AreEqual(10L, 20L, 5L); + action.Should().Throw(); + } - public void AreEqualShouldFailWhenNotEqualDouble() => - VerifyThrows(() => Assert.AreEqual(0.1, 0.2)); + public void AreEqualShouldFailWhenNotEqualDouble() + { + Action action = () => Assert.AreEqual(0.1, 0.2); + action.Should().Throw(); + } public void AreEqualShouldFailWhenNotEqualDoubleWithMessage() { - Exception ex = VerifyThrows(() => Assert.AreEqual(0.1, 0.2, "A Message")); - Verify(ex.Message.Contains("A Message")); + Action action = () => Assert.AreEqual(0.1, 0.2, "A Message"); + action.Should().Throw() + .And.Message.Should().Contain("A Message"); } - public void AreEqualShouldFailWhenNotEqualDoubleWithDelta() => - VerifyThrows(() => Assert.AreEqual(0.1, 0.2, 0.05)); + public void AreEqualShouldFailWhenNotEqualDoubleWithDelta() + { + Action action = () => Assert.AreEqual(0.1, 0.2, 0.05); + action.Should().Throw(); + } public void AreEqualShouldFailWhenNotEqualDecimal() { static void Action() => Assert.AreEqual(0.1M, 0.2M); - VerifyThrows(Action); + Action action = Action; + action.Should().Throw(); } public void AreEqualShouldFailWhenNotEqualDecimalWithMessage() { - Exception ex = VerifyThrows(() => Assert.AreEqual(0.1M, 0.2M, "A Message")); - Verify(ex.Message.Contains("A Message")); + Action action = () => Assert.AreEqual(0.1M, 0.2M, "A Message"); + action.Should().Throw() + .And.Message.Should().Contain("A Message"); } - public void AreEqualShouldFailWhenNotEqualDecimalWithDelta() => - VerifyThrows(() => Assert.AreEqual(0.1M, 0.2M, 0.05M)); + public void AreEqualShouldFailWhenNotEqualDecimalWithDelta() + { + Action action = () => Assert.AreEqual(0.1M, 0.2M, 0.05M); + action.Should().Throw(); + } - public void AreEqualShouldFailWhenFloatDouble() => - VerifyThrows(() => Assert.AreEqual(100E-2, 200E-2)); + public void AreEqualShouldFailWhenFloatDouble() + { + Action action = () => Assert.AreEqual(100E-2, 200E-2); + action.Should().Throw(); + } public void AreEqualShouldFailWhenFloatDoubleWithMessage() { - Exception ex = VerifyThrows(() => Assert.AreEqual(100E-2, 200E-2, "A Message")); - Verify(ex.Message.Contains("A Message")); + Action action = () => Assert.AreEqual(100E-2, 200E-2, "A Message"); + action.Should().Throw() + .And.Message.Should().Contain("A Message"); } - public void AreEqualShouldFailWhenNotEqualFloatWithDelta() => - VerifyThrows(() => Assert.AreEqual(100E-2, 200E-2, 50E-2)); + public void AreEqualShouldFailWhenNotEqualFloatWithDelta() + { + Action action = () => Assert.AreEqual(100E-2, 200E-2, 50E-2); + action.Should().Throw(); + } - public void AreEqualTwoObjectsShouldFail() => - VerifyThrows(() => Assert.AreEqual(new object(), new object())); + public void AreEqualTwoObjectsShouldFail() + { + Action action = () => Assert.AreEqual(new object(), new object()); + action.Should().Throw(); + } public void AreEqualTwoObjectsDifferentTypeShouldFail() { - AssertFailedException ex = VerifyThrows(() => Assert.AreEqual(new object(), 1)); - Verify(ex.Message.Contains("Assert.AreEqual failed. Expected:. Actual:<1 (System.Int32)>.")); + Action action = () => Assert.AreEqual(new object(), 1); + action.Should().Throw() + .And.Message.Should().Contain("Assert.AreEqual failed. Expected:. Actual:<1 (System.Int32)>."); } public void AreEqualWithTypeOverridingEqualsShouldWork() @@ -240,7 +328,8 @@ static void Action() Assert.AreEqual(a, b, new TypeOverridesEqualsEqualityComparer()); } - VerifyThrows(Action); + Action action = Action; + action.Should().Throw(); } public void AreEqualUsingCustomIEquatable() @@ -252,7 +341,8 @@ public void AreEqualUsingCustomIEquatable() Assert.AreEqual(instanceOfA, instanceOfB); // This one doesn't work - VerifyThrows(() => Assert.AreEqual(instanceOfB, instanceOfA)); + Action action = () => Assert.AreEqual(instanceOfB, instanceOfA); + action.Should().Throw(); } #pragma warning disable IDE0004 @@ -272,307 +362,347 @@ public void GenericAreEqual_InterpolatedString_EqualValues_ShouldPass() { DummyClassTrackingToStringCalls o = new(); Assert.AreEqual(o, o, $"User-provided message: {o}"); - Verify(!o.WasToStringCalled); + o.WasToStringCalled.Should().BeFalse(); } public async Task GenericAreEqual_InterpolatedString_DifferentValues_ShouldFail() { DummyClassTrackingToStringCalls o = new(); DateTime dateTime = DateTime.Now; - Exception ex = await VerifyThrowsAsync(async () => Assert.AreEqual(0, 1, $"User-provided message. {o}, {o,35}, {await GetHelloStringAsync()}, {new DummyIFormattable()}, {dateTime:tt}, {dateTime,5:tt}")); - Verify(ex.Message == $"Assert.AreEqual failed. Expected:<0>. Actual:<1>. User-provided message. DummyClassTrackingToStringCalls, DummyClassTrackingToStringCalls, Hello, DummyIFormattable.ToString(), {string.Format(null, "{0:tt}", dateTime)}, {string.Format(null, "{0,5:tt}", dateTime)}"); - Verify(o.WasToStringCalled); + Func action = async () => Assert.AreEqual(0, 1, $"User-provided message. {o}, {o,35}, {await GetHelloStringAsync()}, {new DummyIFormattable()}, {dateTime:tt}, {dateTime,5:tt}"); + (await action.Should().ThrowAsync()) + .And.Message.Should().Be($"Assert.AreEqual failed. Expected:<0>. Actual:<1>. User-provided message. DummyClassTrackingToStringCalls, DummyClassTrackingToStringCalls, Hello, DummyIFormattable.ToString(), {string.Format(null, "{0:tt}", dateTime)}, {string.Format(null, "{0,5:tt}", dateTime)}"); + o.WasToStringCalled.Should().BeTrue(); } public void GenericAreNotEqual_InterpolatedString_DifferentValues_ShouldPass() { DummyClassTrackingToStringCalls o = new(); Assert.AreNotEqual(0, 1, $"User-provided message: {o}"); - Verify(!o.WasToStringCalled); + o.WasToStringCalled.Should().BeFalse(); } public async Task GenericAreNotEqual_InterpolatedString_SameValues_ShouldFail() { DummyClassTrackingToStringCalls o = new(); DateTime dateTime = DateTime.Now; - Exception ex = await VerifyThrowsAsync(async () => Assert.AreNotEqual(0, 0, $"User-provided message. {o}, {o,35}, {await GetHelloStringAsync()}, {new DummyIFormattable()}, {dateTime:tt}, {dateTime,5:tt}")); - Verify(ex.Message == $"Assert.AreNotEqual failed. Expected any value except:<0>. Actual:<0>. User-provided message. DummyClassTrackingToStringCalls, DummyClassTrackingToStringCalls, Hello, DummyIFormattable.ToString(), {string.Format(null, "{0:tt}", dateTime)}, {string.Format(null, "{0,5:tt}", dateTime)}"); - Verify(o.WasToStringCalled); + Func action = async () => Assert.AreNotEqual(0, 0, $"User-provided message. {o}, {o,35}, {await GetHelloStringAsync()}, {new DummyIFormattable()}, {dateTime:tt}, {dateTime,5:tt}"); + (await action.Should().ThrowAsync()) + .And.Message.Should().Be($"Assert.AreNotEqual failed. Expected any value except:<0>. Actual:<0>. User-provided message. DummyClassTrackingToStringCalls, DummyClassTrackingToStringCalls, Hello, DummyIFormattable.ToString(), {string.Format(null, "{0:tt}", dateTime)}, {string.Format(null, "{0,5:tt}", dateTime)}"); + o.WasToStringCalled.Should().BeTrue(); } public void FloatAreEqual_InterpolatedString_EqualValues_ShouldPass() { DummyClassTrackingToStringCalls o = new(); Assert.AreEqual(1.0f, 1.1f, delta: 0.2f, $"User-provided message: {o}"); - Verify(!o.WasToStringCalled); + o.WasToStringCalled.Should().BeFalse(); } public async Task FloatAreEqual_InterpolatedString_DifferentValues_ShouldFail() { DummyClassTrackingToStringCalls o = new(); DateTime dateTime = DateTime.Now; - Exception ex = await VerifyThrowsAsync(async () => Assert.AreEqual(1.0f, 1.1f, 0.001f, $"User-provided message. {o}, {o,35}, {await GetHelloStringAsync()}, {new DummyIFormattable()}, {dateTime:tt}, {dateTime,5:tt}")); - Verify(ex.Message == $"Assert.AreEqual failed. Expected a difference no greater than <0.001> between expected value <1> and actual value <1.1>. User-provided message. DummyClassTrackingToStringCalls, DummyClassTrackingToStringCalls, Hello, DummyIFormattable.ToString(), {string.Format(null, "{0:tt}", dateTime)}, {string.Format(null, "{0,5:tt}", dateTime)}"); - Verify(o.WasToStringCalled); + Func action = async () => Assert.AreEqual(1.0f, 1.1f, 0.001f, $"User-provided message. {o}, {o,35}, {await GetHelloStringAsync()}, {new DummyIFormattable()}, {dateTime:tt}, {dateTime,5:tt}"); + (await action.Should().ThrowAsync()) + .And.Message.Should().Be($"Assert.AreEqual failed. Expected a difference no greater than <0.001> between expected value <1> and actual value <1.1>. User-provided message. DummyClassTrackingToStringCalls, DummyClassTrackingToStringCalls, Hello, DummyIFormattable.ToString(), {string.Format(null, "{0:tt}", dateTime)}, {string.Format(null, "{0,5:tt}", dateTime)}"); + o.WasToStringCalled.Should().BeTrue(); } public void FloatAreNotEqual_InterpolatedString_DifferentValues_ShouldPass() { DummyClassTrackingToStringCalls o = new(); Assert.AreNotEqual(1.0f, 1.1f, 0.001f, $"User-provided message: {o}"); - Verify(!o.WasToStringCalled); + o.WasToStringCalled.Should().BeFalse(); } public async Task FloatAreNotEqual_InterpolatedString_SameValues_ShouldFail() { DummyClassTrackingToStringCalls o = new(); DateTime dateTime = DateTime.Now; - Exception ex = await VerifyThrowsAsync(async () => Assert.AreNotEqual(1.0f, 1.1f, 0.2f, $"User-provided message. {o}, {o,35}, {await GetHelloStringAsync()}, {new DummyIFormattable()}, {dateTime:tt}, {dateTime,5:tt}")); - Verify(ex.Message == $"Assert.AreNotEqual failed. Expected a difference greater than <0.2> between expected value <1> and actual value <1.1>. User-provided message. DummyClassTrackingToStringCalls, DummyClassTrackingToStringCalls, Hello, DummyIFormattable.ToString(), {string.Format(null, "{0:tt}", dateTime)}, {string.Format(null, "{0,5:tt}", dateTime)}"); - Verify(o.WasToStringCalled); + Func action = async () => Assert.AreNotEqual(1.0f, 1.1f, 0.2f, $"User-provided message. {o}, {o,35}, {await GetHelloStringAsync()}, {new DummyIFormattable()}, {dateTime:tt}, {dateTime,5:tt}"); + (await action.Should().ThrowAsync()) + .And.Message.Should().Be($"Assert.AreNotEqual failed. Expected a difference greater than <0.2> between expected value <1> and actual value <1.1>. User-provided message. DummyClassTrackingToStringCalls, DummyClassTrackingToStringCalls, Hello, DummyIFormattable.ToString(), {string.Format(null, "{0:tt}", dateTime)}, {string.Format(null, "{0,5:tt}", dateTime)}"); + o.WasToStringCalled.Should().BeTrue(); } public void DecimalAreEqual_InterpolatedString_EqualValues_ShouldPass() { DummyClassTrackingToStringCalls o = new(); Assert.AreEqual(1.0m, 1.1m, delta: 0.2m, $"User-provided message: {o}"); - Verify(!o.WasToStringCalled); + o.WasToStringCalled.Should().BeFalse(); } public async Task DecimalAreEqual_InterpolatedString_DifferentValues_ShouldFail() { DummyClassTrackingToStringCalls o = new(); DateTime dateTime = DateTime.Now; - Exception ex = await VerifyThrowsAsync(async () => Assert.AreEqual(1.0m, 1.1m, 0.001m, $"User-provided message. {o}, {o,35}, {await GetHelloStringAsync()}, {new DummyIFormattable()}, {dateTime:tt}, {dateTime,5:tt}")); - Verify(ex.Message == $"Assert.AreEqual failed. Expected a difference no greater than <0.001> between expected value <1.0> and actual value <1.1>. User-provided message. DummyClassTrackingToStringCalls, DummyClassTrackingToStringCalls, Hello, DummyIFormattable.ToString(), {string.Format(null, "{0:tt}", dateTime)}, {string.Format(null, "{0,5:tt}", dateTime)}"); - Verify(o.WasToStringCalled); + Func action = async () => Assert.AreEqual(1.0m, 1.1m, 0.001m, $"User-provided message. {o}, {o,35}, {await GetHelloStringAsync()}, {new DummyIFormattable()}, {dateTime:tt}, {dateTime,5:tt}"); + (await action.Should().ThrowAsync()) + .And.Message.Should().Be($"Assert.AreEqual failed. Expected a difference no greater than <0.001> between expected value <1.0> and actual value <1.1>. User-provided message. DummyClassTrackingToStringCalls, DummyClassTrackingToStringCalls, Hello, DummyIFormattable.ToString(), {string.Format(null, "{0:tt}", dateTime)}, {string.Format(null, "{0,5:tt}", dateTime)}"); + o.WasToStringCalled.Should().BeTrue(); } public void DecimalAreNotEqual_InterpolatedString_DifferentValues_ShouldPass() { DummyClassTrackingToStringCalls o = new(); Assert.AreNotEqual(1.0m, 1.1m, 0.001m, $"User-provided message: {o}"); - Verify(!o.WasToStringCalled); + o.WasToStringCalled.Should().BeFalse(); } public async Task DecimalAreNotEqual_InterpolatedString_SameValues_ShouldFail() { DummyClassTrackingToStringCalls o = new(); DateTime dateTime = DateTime.Now; - Exception ex = await VerifyThrowsAsync(async () => Assert.AreNotEqual(1.0m, 1.1m, 0.2m, $"User-provided message. {o}, {o,35}, {await GetHelloStringAsync()}, {new DummyIFormattable()}, {dateTime:tt}, {dateTime,5:tt}")); - Verify(ex.Message == $"Assert.AreNotEqual failed. Expected a difference greater than <0.2> between expected value <1.0> and actual value <1.1>. User-provided message. DummyClassTrackingToStringCalls, DummyClassTrackingToStringCalls, Hello, DummyIFormattable.ToString(), {string.Format(null, "{0:tt}", dateTime)}, {string.Format(null, "{0,5:tt}", dateTime)}"); - Verify(o.WasToStringCalled); + Func action = async () => Assert.AreNotEqual(1.0m, 1.1m, 0.2m, $"User-provided message. {o}, {o,35}, {await GetHelloStringAsync()}, {new DummyIFormattable()}, {dateTime:tt}, {dateTime,5:tt}"); + (await action.Should().ThrowAsync()) + .And.Message.Should().Be($"Assert.AreNotEqual failed. Expected a difference greater than <0.2> between expected value <1.0> and actual value <1.1>. User-provided message. DummyClassTrackingToStringCalls, DummyClassTrackingToStringCalls, Hello, DummyIFormattable.ToString(), {string.Format(null, "{0:tt}", dateTime)}, {string.Format(null, "{0,5:tt}", dateTime)}"); + o.WasToStringCalled.Should().BeTrue(); } public void LongAreEqual_InterpolatedString_EqualValues_ShouldPass() { DummyClassTrackingToStringCalls o = new(); Assert.AreEqual(1L, 2L, delta: 1L, $"User-provided message: {o}"); - Verify(!o.WasToStringCalled); + o.WasToStringCalled.Should().BeFalse(); } public async Task LongAreEqual_InterpolatedString_DifferentValues_ShouldFail() { DummyClassTrackingToStringCalls o = new(); DateTime dateTime = DateTime.Now; - Exception ex = await VerifyThrowsAsync(async () => Assert.AreEqual(1L, 2L, 0L, $"User-provided message. {o}, {o,35}, {await GetHelloStringAsync()}, {new DummyIFormattable()}, {dateTime:tt}, {dateTime,5:tt}")); - Verify(ex.Message == $"Assert.AreEqual failed. Expected a difference no greater than <0> between expected value <1> and actual value <2>. User-provided message. DummyClassTrackingToStringCalls, DummyClassTrackingToStringCalls, Hello, DummyIFormattable.ToString(), {string.Format(null, "{0:tt}", dateTime)}, {string.Format(null, "{0,5:tt}", dateTime)}"); - Verify(o.WasToStringCalled); + Func action = async () => Assert.AreEqual(1L, 2L, 0L, $"User-provided message. {o}, {o,35}, {await GetHelloStringAsync()}, {new DummyIFormattable()}, {dateTime:tt}, {dateTime,5:tt}"); + (await action.Should().ThrowAsync()) + .And.Message.Should().Be($"Assert.AreEqual failed. Expected a difference no greater than <0> between expected value <1> and actual value <2>. User-provided message. DummyClassTrackingToStringCalls, DummyClassTrackingToStringCalls, Hello, DummyIFormattable.ToString(), {string.Format(null, "{0:tt}", dateTime)}, {string.Format(null, "{0,5:tt}", dateTime)}"); + o.WasToStringCalled.Should().BeTrue(); } public void LongAreNotEqual_InterpolatedString_DifferentValues_ShouldPass() { DummyClassTrackingToStringCalls o = new(); Assert.AreNotEqual(1L, 2L, 0L, $"User-provided message: {o}"); - Verify(!o.WasToStringCalled); + o.WasToStringCalled.Should().BeFalse(); } public async Task LongAreNotEqual_InterpolatedString_SameValues_ShouldFail() { DummyClassTrackingToStringCalls o = new(); DateTime dateTime = DateTime.Now; - Exception ex = await VerifyThrowsAsync(async () => Assert.AreNotEqual(1L, 2L, 1L, $"User-provided message. {o}, {o,35}, {await GetHelloStringAsync()}, {new DummyIFormattable()}, {dateTime:tt}, {dateTime,5:tt}")); - Verify(ex.Message == $"Assert.AreNotEqual failed. Expected a difference greater than <1> between expected value <1> and actual value <2>. User-provided message. DummyClassTrackingToStringCalls, DummyClassTrackingToStringCalls, Hello, DummyIFormattable.ToString(), {string.Format(null, "{0:tt}", dateTime)}, {string.Format(null, "{0,5:tt}", dateTime)}"); - Verify(o.WasToStringCalled); + Func action = async () => Assert.AreNotEqual(1L, 2L, 1L, $"User-provided message. {o}, {o,35}, {await GetHelloStringAsync()}, {new DummyIFormattable()}, {dateTime:tt}, {dateTime,5:tt}"); + (await action.Should().ThrowAsync()) + .And.Message.Should().Be($"Assert.AreNotEqual failed. Expected a difference greater than <1> between expected value <1> and actual value <2>. User-provided message. DummyClassTrackingToStringCalls, DummyClassTrackingToStringCalls, Hello, DummyIFormattable.ToString(), {string.Format(null, "{0:tt}", dateTime)}, {string.Format(null, "{0,5:tt}", dateTime)}"); + o.WasToStringCalled.Should().BeTrue(); } public void DoubleAreEqual_InterpolatedString_EqualValues_ShouldPass() { DummyClassTrackingToStringCalls o = new(); Assert.AreEqual(1.0d, 1.1d, delta: 0.2d, $"User-provided message: {o}"); - Verify(!o.WasToStringCalled); + o.WasToStringCalled.Should().BeFalse(); } public async Task DoubleAreEqual_InterpolatedString_DifferentValues_ShouldFail() { DummyClassTrackingToStringCalls o = new(); DateTime dateTime = DateTime.Now; - Exception ex = await VerifyThrowsAsync(async () => Assert.AreEqual(1.0d, 1.1d, 0.001d, $"User-provided message. {o}, {o,35}, {await GetHelloStringAsync()}, {new DummyIFormattable()}, {dateTime:tt}, {dateTime,5:tt}")); - Verify(ex.Message == $"Assert.AreEqual failed. Expected a difference no greater than <0.001> between expected value <1> and actual value <1.1>. User-provided message. DummyClassTrackingToStringCalls, DummyClassTrackingToStringCalls, Hello, DummyIFormattable.ToString(), {string.Format(null, "{0:tt}", dateTime)}, {string.Format(null, "{0,5:tt}", dateTime)}"); - Verify(o.WasToStringCalled); + Func action = async () => Assert.AreEqual(1.0d, 1.1d, 0.001d, $"User-provided message. {o}, {o,35}, {await GetHelloStringAsync()}, {new DummyIFormattable()}, {dateTime:tt}, {dateTime,5:tt}"); + (await action.Should().ThrowAsync()) + .And.Message.Should().Be($"Assert.AreEqual failed. Expected a difference no greater than <0.001> between expected value <1> and actual value <1.1>. User-provided message. DummyClassTrackingToStringCalls, DummyClassTrackingToStringCalls, Hello, DummyIFormattable.ToString(), {string.Format(null, "{0:tt}", dateTime)}, {string.Format(null, "{0,5:tt}", dateTime)}"); + o.WasToStringCalled.Should().BeTrue(); } public void DoubleAreNotEqual_InterpolatedString_DifferentValues_ShouldPass() { DummyClassTrackingToStringCalls o = new(); Assert.AreNotEqual(1.0d, 1.1d, 0.001d, $"User-provided message: {o}"); - Verify(!o.WasToStringCalled); + o.WasToStringCalled.Should().BeFalse(); } public async Task DoubleAreNotEqual_InterpolatedString_SameValues_ShouldFail() { DummyClassTrackingToStringCalls o = new(); DateTime dateTime = DateTime.Now; - Exception ex = await VerifyThrowsAsync(async () => Assert.AreNotEqual(1.0d, 1.1d, 0.2d, $"User-provided message. {o}, {o,35}, {await GetHelloStringAsync()}, {new DummyIFormattable()}, {dateTime:tt}, {dateTime,5:tt}")); - Verify(ex.Message == $"Assert.AreNotEqual failed. Expected a difference greater than <0.2> between expected value <1> and actual value <1.1>. User-provided message. DummyClassTrackingToStringCalls, DummyClassTrackingToStringCalls, Hello, DummyIFormattable.ToString(), {string.Format(null, "{0:tt}", dateTime)}, {string.Format(null, "{0,5:tt}", dateTime)}"); - Verify(o.WasToStringCalled); + Func action = async () => Assert.AreNotEqual(1.0d, 1.1d, 0.2d, $"User-provided message. {o}, {o,35}, {await GetHelloStringAsync()}, {new DummyIFormattable()}, {dateTime:tt}, {dateTime,5:tt}"); + (await action.Should().ThrowAsync()) + .And.Message.Should().Be($"Assert.AreNotEqual failed. Expected a difference greater than <0.2> between expected value <1> and actual value <1.1>. User-provided message. DummyClassTrackingToStringCalls, DummyClassTrackingToStringCalls, Hello, DummyIFormattable.ToString(), {string.Format(null, "{0:tt}", dateTime)}, {string.Format(null, "{0,5:tt}", dateTime)}"); + o.WasToStringCalled.Should().BeTrue(); } public void FloatAreEqual_ExpectedIsNumeric_ActualIsNumeric_ExpectedAndActualNotEquals_DeltaIsNaN_ShouldFail() { - Exception ex = VerifyThrows(() => Assert.AreEqual(1.0f, 2.0f, float.NaN)); - Verify(ex.Message is """ + Action action = () => Assert.AreEqual(1.0f, 2.0f, float.NaN); + action.Should().Throw().And.Message.Should().BeOneOf( + """ Specified argument was out of the range of valid values. Parameter name: delta - """ or "Specified argument was out of the range of valid values. (Parameter 'delta')"); + """, + "Specified argument was out of the range of valid values. (Parameter 'delta')"); } public void FloatAreEqual_ExpectedIsNumeric_ActualIsNumeric_ExpectedAndActualEquals_DeltaIsNaN_ShouldFail() { - Exception ex = VerifyThrows(() => Assert.AreEqual(1.0f, 1.0f, float.NaN)); - Verify(ex.Message is """ + Action action = () => Assert.AreEqual(1.0f, 1.0f, float.NaN); + action.Should().Throw().And.Message.Should().BeOneOf( + """ Specified argument was out of the range of valid values. Parameter name: delta - """ or "Specified argument was out of the range of valid values. (Parameter 'delta')"); + """, + "Specified argument was out of the range of valid values. (Parameter 'delta')"); } public void FloatAreEqual_ExpectedIsNaN_ActualIsNumeric_DeltaIsNaN_ShouldFail() { - Exception ex = VerifyThrows(() => Assert.AreEqual(float.NaN, 1.0f, float.NaN)); - Verify(ex.Message is """ + Action action = () => Assert.AreEqual(float.NaN, 1.0f, float.NaN); + action.Should().Throw().And.Message.Should().BeOneOf( + """ Specified argument was out of the range of valid values. Parameter name: delta - """ or "Specified argument was out of the range of valid values. (Parameter 'delta')"); + """, + "Specified argument was out of the range of valid values. (Parameter 'delta')"); } public void FloatAreEqual_ExpectedIsNaN_ActualIsNaN_DeltaIsNaN_ShouldFail() { - Exception ex = VerifyThrows(() => Assert.AreEqual(float.NaN, float.NaN, float.NaN)); - Verify(ex.Message is """ + Action action = () => Assert.AreEqual(float.NaN, float.NaN, float.NaN); + action.Should().Throw().And.Message.Should().BeOneOf( + """ Specified argument was out of the range of valid values. Parameter name: delta - """ or "Specified argument was out of the range of valid values. (Parameter 'delta')"); + """, + "Specified argument was out of the range of valid values. (Parameter 'delta')"); } public void FloatAreEqual_ExpectedIsNumeric_ActualIsNaN_DeltaIsNaN_ShouldFail() { - Exception ex = VerifyThrows(() => Assert.AreEqual(1.0f, float.NaN, float.NaN)); - Verify(ex.Message is """ + Action action = () => Assert.AreEqual(1.0f, float.NaN, float.NaN); + action.Should().Throw().And.Message.Should().BeOneOf( + """ Specified argument was out of the range of valid values. Parameter name: delta - """ or "Specified argument was out of the range of valid values. (Parameter 'delta')"); + """, + "Specified argument was out of the range of valid values. (Parameter 'delta')"); } public void FloatAreEqual_ExpectedIsNumeric_ActualIsNumeric_ExpectedAndActualNotEquals_DeltaIsNegative_ShouldFail() { - Exception ex = VerifyThrows(() => Assert.AreEqual(1.0f, 2.0f, -1.0f)); - Verify(ex.Message is """ + Action action = () => Assert.AreEqual(1.0f, 2.0f, -1.0f); + action.Should().Throw().And.Message.Should().BeOneOf( + """ Specified argument was out of the range of valid values. Parameter name: delta - """ or "Specified argument was out of the range of valid values. (Parameter 'delta')"); + """, + "Specified argument was out of the range of valid values. (Parameter 'delta')"); } public void FloatAreEqual_ExpectedIsNumeric_ActualIsNumeric_ExpectedAndActualEquals_DeltaIsNegative_ShouldFail() { - Exception ex = VerifyThrows(() => Assert.AreEqual(1.0f, 1.0f, -1.0f)); - Verify(ex.Message is """ + Action action = () => Assert.AreEqual(1.0f, 1.0f, -1.0f); + action.Should().Throw().And.Message.Should().BeOneOf( + """ Specified argument was out of the range of valid values. Parameter name: delta - """ or "Specified argument was out of the range of valid values. (Parameter 'delta')"); + """, + "Specified argument was out of the range of valid values. (Parameter 'delta')"); } public void FloatAreEqual_ExpectedIsNaN_ActualIsNumeric_DeltaIsNegative_ShouldFail() { - Exception ex = VerifyThrows(() => Assert.AreEqual(float.NaN, 1.0f, -1.0f)); - Verify(ex.Message is """ + Action action = () => Assert.AreEqual(float.NaN, 1.0f, -1.0f); + action.Should().Throw().And.Message.Should().BeOneOf( + """ Specified argument was out of the range of valid values. Parameter name: delta - """ or "Specified argument was out of the range of valid values. (Parameter 'delta')"); + """, + "Specified argument was out of the range of valid values. (Parameter 'delta')"); } public void FloatAreEqual_ExpectedIsNaN_ActualIsNaN_DeltaIsNegative_ShouldFail() { - Exception ex = VerifyThrows(() => Assert.AreEqual(float.NaN, float.NaN, -1.0f)); - Verify(ex.Message is """ + Action action = () => Assert.AreEqual(float.NaN, float.NaN, -1.0f); + action.Should().Throw().And.Message.Should().BeOneOf( + """ Specified argument was out of the range of valid values. Parameter name: delta - """ or "Specified argument was out of the range of valid values. (Parameter 'delta')"); + """, + "Specified argument was out of the range of valid values. (Parameter 'delta')"); } public void FloatAreEqual_ExpectedIsNumeric_ActualIsNaN_DeltaIsNegative_ShouldFail() { - Exception ex = VerifyThrows(() => Assert.AreEqual(1.0f, float.NaN, -1.0f)); - Verify(ex.Message is """ + Action action = () => Assert.AreEqual(1.0f, float.NaN, -1.0f); + action.Should().Throw().And.Message.Should().BeOneOf( + """ Specified argument was out of the range of valid values. Parameter name: delta - """ or "Specified argument was out of the range of valid values. (Parameter 'delta')"); + """, + "Specified argument was out of the range of valid values. (Parameter 'delta')"); } public void FloatAreEqual_ExpectedIsNumeric_ActualIsNumeric_ExpectedAndActualNotEquals_DeltaIsNegativeInf_ShouldFail() { - Exception ex = VerifyThrows(() => Assert.AreEqual(1.0f, 2.0f, float.NegativeInfinity)); - Verify(ex.Message is """ + Action action = () => Assert.AreEqual(1.0f, 2.0f, float.NegativeInfinity); + action.Should().Throw().And.Message.Should().BeOneOf( + """ Specified argument was out of the range of valid values. Parameter name: delta - """ or "Specified argument was out of the range of valid values. (Parameter 'delta')"); + """, + "Specified argument was out of the range of valid values. (Parameter 'delta')"); } public void FloatAreEqual_ExpectedIsNumeric_ActualIsNumeric_ExpectedAndActualEquals_DeltaIsNegativeInf_ShouldFail() { - Exception ex = VerifyThrows(() => Assert.AreEqual(1.0f, 1.0f, float.NegativeInfinity)); - Verify(ex.Message is """ + Action action = () => Assert.AreEqual(1.0f, 1.0f, float.NegativeInfinity); + action.Should().Throw().And.Message.Should().BeOneOf( + """ Specified argument was out of the range of valid values. Parameter name: delta - """ or "Specified argument was out of the range of valid values. (Parameter 'delta')"); + """, + "Specified argument was out of the range of valid values. (Parameter 'delta')"); } public void FloatAreEqual_ExpectedIsNaN_ActualIsNumeric_DeltaIsNegativeInf_ShouldFail() { - Exception ex = VerifyThrows(() => Assert.AreEqual(float.NaN, 1.0f, float.NegativeInfinity)); - Verify(ex.Message is """ + Action action = () => Assert.AreEqual(float.NaN, 1.0f, float.NegativeInfinity); + action.Should().Throw().And.Message.Should().BeOneOf( + """ Specified argument was out of the range of valid values. Parameter name: delta - """ or "Specified argument was out of the range of valid values. (Parameter 'delta')"); + """, + "Specified argument was out of the range of valid values. (Parameter 'delta')"); } public void FloatAreEqual_ExpectedIsNaN_ActualIsNaN_DeltaIsNegativeInf_ShouldFail() { - Exception ex = VerifyThrows(() => Assert.AreEqual(float.NaN, float.NaN, -1.0f)); - Verify(ex.Message is """ + Action action = () => Assert.AreEqual(float.NaN, float.NaN, -1.0f); + action.Should().Throw().And.Message.Should().BeOneOf( + """ Specified argument was out of the range of valid values. Parameter name: delta - """ or "Specified argument was out of the range of valid values. (Parameter 'delta')"); + """, + "Specified argument was out of the range of valid values. (Parameter 'delta')"); } public void FloatAreEqual_ExpectedIsNumeric_ActualIsNaN_DeltaIsNegativeInf_ShouldFail() { - Exception ex = VerifyThrows(() => Assert.AreEqual(1.0f, float.NaN, float.NegativeInfinity)); - Verify(ex.Message is """ + Action action = () => Assert.AreEqual(1.0f, float.NaN, float.NegativeInfinity); + action.Should().Throw().And.Message.Should().BeOneOf( + """ Specified argument was out of the range of valid values. Parameter name: delta - """ or "Specified argument was out of the range of valid values. (Parameter 'delta')"); + """, + "Specified argument was out of the range of valid values. (Parameter 'delta')"); } public void FloatAreEqual_ExpectedIsNumeric_ActualIsNumeric_ExpectedAndActualDifferenceGreaterThanDeltaPositive_DeltaIsNumeric_ShouldFail() { - Exception ex = VerifyThrows(() => Assert.AreEqual(5.0f, 2.0f, 2.0f)); // difference is 3. Delta is 2 - Verify(ex.Message == "Assert.AreEqual failed. Expected a difference no greater than <2> between expected value <5> and actual value <2>. "); + Action action = () => Assert.AreEqual(5.0f, 2.0f, 2.0f); // difference is 3. Delta is 2 + action.Should().Throw().And.Message.Should().Be("Assert.AreEqual failed. Expected a difference no greater than <2> between expected value <5> and actual value <2>. "); } public void FloatAreEqual_ExpectedIsNumeric_ActualIsNumeric_ExpectedAndActualDifferenceGreaterThanDeltaNegative_DeltaIsNumeric_ShouldFail() { - Exception ex = VerifyThrows(() => Assert.AreEqual(2.0f, 5.0f, 2.0f)); // difference is -3. Delta is 2 - Verify(ex.Message == "Assert.AreEqual failed. Expected a difference no greater than <2> between expected value <2> and actual value <5>. "); + Action action = () => Assert.AreEqual(2.0f, 5.0f, 2.0f); // difference is -3. Delta is 2 + action.Should().Throw().And.Message.Should().Be("Assert.AreEqual failed. Expected a difference no greater than <2> between expected value <2> and actual value <5>. "); } public void FloatAreEqual_ExpectedIsNumeric_ActualIsNumeric_ExpectedAndActualDifferenceLessThanDeltaPositive_DeltaIsNumeric_ShouldPass() @@ -583,14 +713,14 @@ public void FloatAreEqual_ExpectedIsNumeric_ActualIsNumeric_ExpectedAndActualDif public void FloatAreEqual_ExpectedIsNumeric_ActualIsNaN_DeltaIsNumeric_ShouldFail() { - Exception ex = VerifyThrows(() => Assert.AreEqual(5.0f, float.NaN, 2.0f)); - Verify(ex.Message == "Assert.AreEqual failed. Expected a difference no greater than <2> between expected value <5> and actual value . "); + Action action = () => Assert.AreEqual(5.0f, float.NaN, 2.0f); + action.Should().Throw().And.Message.Should().Be("Assert.AreEqual failed. Expected a difference no greater than <2> between expected value <5> and actual value . "); } public void FloatAreEqual_ExpectedIsNaN_ActualIsNumeric_DeltaIsNumeric_ShouldFail() { - Exception ex = VerifyThrows(() => Assert.AreEqual(float.NaN, 5.0f, 2.0f)); - Verify(ex.Message == "Assert.AreEqual failed. Expected a difference no greater than <2> between expected value and actual value <5>. "); + Action action = () => Assert.AreEqual(float.NaN, 5.0f, 2.0f); + action.Should().Throw().And.Message.Should().Be("Assert.AreEqual failed. Expected a difference no greater than <2> between expected value and actual value <5>. "); } public void FloatAreEqual_ExpectedIsNaN_ActualIsNaN_DeltaIsNumeric_ShouldPass() @@ -598,137 +728,175 @@ public void FloatAreEqual_ExpectedIsNaN_ActualIsNaN_DeltaIsNumeric_ShouldPass() public void FloatAreNotEqual_ExpectedIsNumeric_ActualIsNumeric_ExpectedAndActualNotEquals_DeltaIsNaN_ShouldFail() { - Exception ex = VerifyThrows(() => Assert.AreNotEqual(1.0f, 2.0f, float.NaN)); - Verify(ex.Message is """ + Action action = () => Assert.AreNotEqual(1.0f, 2.0f, float.NaN); + action.Should().Throw() + .And.Message.Should().BeOneOf( + """ Specified argument was out of the range of valid values. Parameter name: delta - """ or "Specified argument was out of the range of valid values. (Parameter 'delta')"); + """, + "Specified argument was out of the range of valid values. (Parameter 'delta')"); } public void FloatAreNotEqual_ExpectedIsNumeric_ActualIsNumeric_ExpectedAndActualEquals_DeltaIsNaN_ShouldFail() { - Exception ex = VerifyThrows(() => Assert.AreNotEqual(1.0f, 1.0f, float.NaN)); - Verify(ex.Message is """ + Action action = () => Assert.AreNotEqual(1.0f, 1.0f, float.NaN); + action.Should().Throw() + .And.Message.Should().BeOneOf( + """ Specified argument was out of the range of valid values. Parameter name: delta - """ or "Specified argument was out of the range of valid values. (Parameter 'delta')"); + """, + "Specified argument was out of the range of valid values. (Parameter 'delta')"); } public void FloatAreNotEqual_ExpectedIsNaN_ActualIsNumeric_DeltaIsNaN_ShouldFail() { - Exception ex = VerifyThrows(() => Assert.AreNotEqual(float.NaN, 1.0f, float.NaN)); - Verify(ex.Message is """ + Action action = () => Assert.AreNotEqual(float.NaN, 1.0f, float.NaN); + action.Should().Throw().And.Message.Should().BeOneOf( + """ Specified argument was out of the range of valid values. Parameter name: delta - """ or "Specified argument was out of the range of valid values. (Parameter 'delta')"); + """, + "Specified argument was out of the range of valid values. (Parameter 'delta')"); } public void FloatAreNotEqual_ExpectedIsNaN_ActualIsNaN_DeltaIsNaN_ShouldFail() { - Exception ex = VerifyThrows(() => Assert.AreNotEqual(float.NaN, float.NaN, float.NaN)); - Verify(ex.Message is """ + Action action = () => Assert.AreNotEqual(float.NaN, float.NaN, float.NaN); + action.Should().Throw().And.Message.Should().BeOneOf( + """ Specified argument was out of the range of valid values. Parameter name: delta - """ or "Specified argument was out of the range of valid values. (Parameter 'delta')"); + """, + "Specified argument was out of the range of valid values. (Parameter 'delta')"); } public void FloatAreNotEqual_ExpectedIsNumeric_ActualIsNaN_DeltaIsNaN_ShouldFail() { - Exception ex = VerifyThrows(() => Assert.AreNotEqual(1.0f, float.NaN, float.NaN)); - Verify(ex.Message is """ + Action action = () => Assert.AreNotEqual(1.0f, float.NaN, float.NaN); + action.Should().Throw().And.Message.Should().BeOneOf( + """ Specified argument was out of the range of valid values. Parameter name: delta - """ or "Specified argument was out of the range of valid values. (Parameter 'delta')"); + """, + "Specified argument was out of the range of valid values. (Parameter 'delta')"); } public void FloatAreNotEqual_ExpectedIsNumeric_ActualIsNumeric_ExpectedAndActualNotEquals_DeltaIsNegative_ShouldFail() { - Exception ex = VerifyThrows(() => Assert.AreNotEqual(1.0f, 2.0f, -1.0f)); - Verify(ex.Message is """ + Action action = () => Assert.AreNotEqual(1.0f, 2.0f, -1.0f); + action.Should().Throw() + .And.Message.Should().BeOneOf( + """ Specified argument was out of the range of valid values. Parameter name: delta - """ or "Specified argument was out of the range of valid values. (Parameter 'delta')"); + """, + "Specified argument was out of the range of valid values. (Parameter 'delta')"); } public void FloatAreNotEqual_ExpectedIsNumeric_ActualIsNumeric_ExpectedAndActualEquals_DeltaIsNegative_ShouldFail() { - Exception ex = VerifyThrows(() => Assert.AreNotEqual(1.0f, 1.0f, -1.0f)); - Verify(ex.Message is """ + Action action = () => Assert.AreNotEqual(1.0f, 1.0f, -1.0f); + action.Should().Throw().And.Message.Should().BeOneOf( + """ Specified argument was out of the range of valid values. Parameter name: delta - """ or "Specified argument was out of the range of valid values. (Parameter 'delta')"); + """, + "Specified argument was out of the range of valid values. (Parameter 'delta')"); } public void FloatAreNotEqual_ExpectedIsNaN_ActualIsNumeric_DeltaIsNegative_ShouldFail() { - Exception ex = VerifyThrows(() => Assert.AreNotEqual(float.NaN, 1.0f, -1.0f)); - Verify(ex.Message is """ + Action action = () => Assert.AreNotEqual(float.NaN, 1.0f, -1.0f); + action.Should().Throw().And.Message.Should().BeOneOf( + """ Specified argument was out of the range of valid values. Parameter name: delta - """ or "Specified argument was out of the range of valid values. (Parameter 'delta')"); + """, + "Specified argument was out of the range of valid values. (Parameter 'delta')"); } public void FloatAreNotEqual_ExpectedIsNaN_ActualIsNaN_DeltaIsNegative_ShouldFail() { - Exception ex = VerifyThrows(() => Assert.AreNotEqual(float.NaN, float.NaN, -1.0f)); - Verify(ex.Message is """ + Action action = () => Assert.AreNotEqual(float.NaN, float.NaN, -1.0f); + action.Should().Throw().And.Message.Should().BeOneOf( + """ Specified argument was out of the range of valid values. Parameter name: delta - """ or "Specified argument was out of the range of valid values. (Parameter 'delta')"); + """, + "Specified argument was out of the range of valid values. (Parameter 'delta')"); } public void FloatAreNotEqual_ExpectedIsNumeric_ActualIsNaN_DeltaIsNegative_ShouldFail() { - Exception ex = VerifyThrows(() => Assert.AreNotEqual(1.0f, float.NaN, -1.0f)); - Verify(ex.Message is """ + Action action = () => Assert.AreNotEqual(1.0f, float.NaN, -1.0f); + action.Should().Throw().And.Message.Should().BeOneOf( + """ Specified argument was out of the range of valid values. Parameter name: delta - """ or "Specified argument was out of the range of valid values. (Parameter 'delta')"); + """, + "Specified argument was out of the range of valid values. (Parameter 'delta')"); } public void FloatAreNotEqual_ExpectedIsNumeric_ActualIsNumeric_ExpectedAndActualNotEquals_DeltaIsNegativeInf_ShouldFail() { - Exception ex = VerifyThrows(() => Assert.AreNotEqual(1.0f, 2.0f, -1.0f)); - Verify(ex.Message is """ + Action action = () => Assert.AreNotEqual(1.0f, 2.0f, -1.0f); + action.Should().Throw() + .And.Message.Should().BeOneOf( + """ Specified argument was out of the range of valid values. Parameter name: delta - """ or "Specified argument was out of the range of valid values. (Parameter 'delta')"); + """, + "Specified argument was out of the range of valid values. (Parameter 'delta')"); } public void FloatAreNotEqual_ExpectedIsNumeric_ActualIsNumeric_ExpectedAndActualEquals_DeltaIsNegativeInf_ShouldFail() { - Exception ex = VerifyThrows(() => Assert.AreNotEqual(1.0f, 1.0f, float.NegativeInfinity)); - Verify(ex.Message is """ + Action action = () => Assert.AreNotEqual(1.0f, 1.0f, float.NegativeInfinity); + action.Should().Throw() + .And.Message.Should().BeOneOf( + """ Specified argument was out of the range of valid values. Parameter name: delta - """ or "Specified argument was out of the range of valid values. (Parameter 'delta')"); + """, + "Specified argument was out of the range of valid values. (Parameter 'delta')"); } public void FloatAreNotEqual_ExpectedIsNaN_ActualIsNumeric_DeltaIsNegativeInf_ShouldFail() { - Exception ex = VerifyThrows(() => Assert.AreNotEqual(float.NaN, 1.0f, float.NegativeInfinity)); - Verify(ex.Message is """ + Action action = () => Assert.AreNotEqual(float.NaN, 1.0f, float.NegativeInfinity); + action.Should().Throw() + .And.Message.Should().BeOneOf( + """ Specified argument was out of the range of valid values. Parameter name: delta - """ or "Specified argument was out of the range of valid values. (Parameter 'delta')"); + """, + "Specified argument was out of the range of valid values. (Parameter 'delta')"); } public void FloatAreNotEqual_ExpectedIsNaN_ActualIsNaN_DeltaIsNegativeInf_ShouldFail() { - Exception ex = VerifyThrows(() => Assert.AreNotEqual(float.NaN, float.NaN, float.NegativeInfinity)); - Verify(ex.Message is """ + Action action = () => Assert.AreNotEqual(float.NaN, float.NaN, float.NegativeInfinity); + action.Should().Throw() + .And.Message.Should().BeOneOf( + """ Specified argument was out of the range of valid values. Parameter name: delta - """ or "Specified argument was out of the range of valid values. (Parameter 'delta')"); + """, + "Specified argument was out of the range of valid values. (Parameter 'delta')"); } public void FloatAreNotEqual_ExpectedIsNumeric_ActualIsNaN_DeltaIsNegativeInf_ShouldFail() { - Exception ex = VerifyThrows(() => Assert.AreNotEqual(1.0f, float.NaN, float.NegativeInfinity)); - Verify(ex.Message is """ + Action action = () => Assert.AreNotEqual(1.0f, float.NaN, float.NegativeInfinity); + action.Should().Throw() + .And.Message.Should().BeOneOf( + """ Specified argument was out of the range of valid values. Parameter name: delta - """ or "Specified argument was out of the range of valid values. (Parameter 'delta')"); + """, + "Specified argument was out of the range of valid values. (Parameter 'delta')"); } public void FloatAreNotEqual_ExpectedIsNumeric_ActualIsNumeric_ExpectedAndActualDifferenceGreaterThanDeltaPositive_DeltaIsNumeric_ShouldPass() @@ -739,14 +907,14 @@ public void FloatAreNotEqual_ExpectedIsNumeric_ActualIsNumeric_ExpectedAndActual public void FloatAreNotEqual_ExpectedIsNumeric_ActualIsNumeric_ExpectedAndActualDifferenceLessThanDeltaPositive_DeltaIsNumeric_ShouldFail() { - Exception ex = VerifyThrows(() => Assert.AreNotEqual(5.0f, 4.0f, 2.0f)); // difference is 1. Delta is 2 - Verify(ex.Message == "Assert.AreNotEqual failed. Expected a difference greater than <2> between expected value <5> and actual value <4>. "); + Action action = () => Assert.AreNotEqual(5.0f, 4.0f, 2.0f); // difference is 1. Delta is 2 + action.Should().Throw().And.Message.Should().Be("Assert.AreNotEqual failed. Expected a difference greater than <2> between expected value <5> and actual value <4>. "); } public void FloatAreNotEqual_ExpectedIsNumeric_ActualIsNumeric_ExpectedAndActualDifferenceLessThanDeltaNegative_DeltaIsNumeric_ShouldFail() { - Exception ex = VerifyThrows(() => Assert.AreNotEqual(4.0f, 5.0f, 2.0f)); // difference is -1. Delta is 2 - Verify(ex.Message == "Assert.AreNotEqual failed. Expected a difference greater than <2> between expected value <4> and actual value <5>. "); + Action action = () => Assert.AreNotEqual(4.0f, 5.0f, 2.0f); // difference is -1. Delta is 2 + action.Should().Throw().And.Message.Should().Be("Assert.AreNotEqual failed. Expected a difference greater than <2> between expected value <4> and actual value <5>. "); } public void FloatAreNotEqual_ExpectedIsNumeric_ActualIsNaN_DeltaIsNumeric_ShouldPass() => Assert.AreNotEqual(5.0f, float.NaN, 2.0f); @@ -756,155 +924,199 @@ public void FloatAreNotEqual_ExpectedIsNaN_ActualIsNumeric_DeltaIsNumeric_Should public void FloatAreNotEqual_ExpectedIsNaN_ActualIsNaN_DeltaIsNumeric_ShouldFail() { - Exception ex = VerifyThrows(() => Assert.AreNotEqual(float.NaN, float.NaN, 2.0f)); - Verify(ex.Message == "Assert.AreNotEqual failed. Expected a difference greater than <2> between expected value and actual value . "); + Action action = () => Assert.AreNotEqual(float.NaN, float.NaN, 2.0f); + action.Should().Throw().And.Message.Should().Be("Assert.AreNotEqual failed. Expected a difference greater than <2> between expected value and actual value . "); } public void DoubleAreEqual_ExpectedIsNumeric_ActualIsNumeric_ExpectedAndActualNotEquals_DeltaIsNaN_ShouldFail() { - Exception ex = VerifyThrows(() => Assert.AreEqual(1.0d, 2.0d, double.NaN)); - Verify(ex.Message is """ + Action action = () => Assert.AreEqual(1.0d, 2.0d, double.NaN); + action.Should().Throw().And.Message.Should().BeOneOf( + """ Specified argument was out of the range of valid values. Parameter name: delta - """ or "Specified argument was out of the range of valid values. (Parameter 'delta')"); + """, + "Specified argument was out of the range of valid values. (Parameter 'delta')"); } public void DoubleAreEqual_ExpectedIsNumeric_ActualIsNumeric_ExpectedAndActualEquals_DeltaIsNaN_ShouldFail() { - Exception ex = VerifyThrows(() => Assert.AreEqual(1.0d, 1.0d, double.NaN)); - Verify(ex.Message is """ + Action action = () => Assert.AreEqual(1.0d, 1.0d, double.NaN); + action.Should().Throw().And.Message.Should().BeOneOf( + """ Specified argument was out of the range of valid values. Parameter name: delta - """ or "Specified argument was out of the range of valid values. (Parameter 'delta')"); + """, + "Specified argument was out of the range of valid values. (Parameter 'delta')"); } public void DoubleAreEqual_ExpectedIsNaN_ActualIsNumeric_DeltaIsNaN_ShouldFail() { - Exception ex = VerifyThrows(() => Assert.AreEqual(double.NaN, 1.0d, double.NaN)); - Verify(ex.Message is """ + Action action = () => Assert.AreEqual(double.NaN, 1.0d, double.NaN); + action.Should().Throw() + .And.Message.Should().BeOneOf( + """ Specified argument was out of the range of valid values. Parameter name: delta - """ or "Specified argument was out of the range of valid values. (Parameter 'delta')"); + """, + "Specified argument was out of the range of valid values. (Parameter 'delta')"); } public void DoubleAreEqual_ExpectedIsNaN_ActualIsNaN_DeltaIsNaN_ShouldFail() { - Exception ex = VerifyThrows(() => Assert.AreEqual(double.NaN, double.NaN, double.NaN)); - Verify(ex.Message is """ + Action action = () => Assert.AreEqual(double.NaN, double.NaN, double.NaN); + action.Should().Throw() + .And.Message.Should().BeOneOf( + """ Specified argument was out of the range of valid values. Parameter name: delta - """ or "Specified argument was out of the range of valid values. (Parameter 'delta')"); + """, + "Specified argument was out of the range of valid values. (Parameter 'delta')"); } public void DoubleAreEqual_ExpectedIsNumeric_ActualIsNaN_DeltaIsNaN_ShouldFail() { - Exception ex = VerifyThrows(() => Assert.AreEqual(1.0d, double.NaN, double.NaN)); - Verify(ex.Message is """ + Action action = () => Assert.AreEqual(1.0d, double.NaN, double.NaN); + action.Should().Throw() + .And.Message.Should().BeOneOf( + """ Specified argument was out of the range of valid values. Parameter name: delta - """ or "Specified argument was out of the range of valid values. (Parameter 'delta')"); + """, + "Specified argument was out of the range of valid values. (Parameter 'delta')"); } public void DoubleAreEqual_ExpectedIsNumeric_ActualIsNumeric_ExpectedAndActualNotEquals_DeltaIsNegative_ShouldFail() { - Exception ex = VerifyThrows(() => Assert.AreEqual(1.0d, 2.0d, -1.0d)); - Verify(ex.Message is """ + Action action = () => Assert.AreEqual(1.0d, 2.0d, -1.0d); + action.Should().Throw() + .And.Message.Should().BeOneOf( + """ Specified argument was out of the range of valid values. Parameter name: delta - """ or "Specified argument was out of the range of valid values. (Parameter 'delta')"); + """, + "Specified argument was out of the range of valid values. (Parameter 'delta')"); } public void DoubleAreEqual_ExpectedIsNumeric_ActualIsNumeric_ExpectedAndActualEquals_DeltaIsNegative_ShouldFail() { - Exception ex = VerifyThrows(() => Assert.AreEqual(1.0d, 1.0d, -1.0d)); - Verify(ex.Message is """ + Action action = () => Assert.AreEqual(1.0d, 1.0d, -1.0d); + action.Should().Throw() + .And.Message.Should().BeOneOf( + """ Specified argument was out of the range of valid values. Parameter name: delta - """ or "Specified argument was out of the range of valid values. (Parameter 'delta')"); + """, + "Specified argument was out of the range of valid values. (Parameter 'delta')"); } public void DoubleAreEqual_ExpectedIsNaN_ActualIsNumeric_DeltaIsNegative_ShouldFail() { - Exception ex = VerifyThrows(() => Assert.AreEqual(double.NaN, 1.0d, -1.0d)); - Verify(ex.Message is """ + Action action = () => Assert.AreEqual(double.NaN, 1.0d, -1.0d); + action.Should().Throw() + .And.Message.Should().BeOneOf( + """ Specified argument was out of the range of valid values. Parameter name: delta - """ or "Specified argument was out of the range of valid values. (Parameter 'delta')"); + """, + "Specified argument was out of the range of valid values. (Parameter 'delta')"); } public void DoubleAreEqual_ExpectedIsNaN_ActualIsNaN_DeltaIsNegative_ShouldFail() { - Exception ex = VerifyThrows(() => Assert.AreEqual(double.NaN, double.NaN, -1.0d)); - Verify(ex.Message is """ + Action action = () => Assert.AreEqual(double.NaN, double.NaN, -1.0d); + action.Should().Throw() + .And.Message.Should().BeOneOf( + """ Specified argument was out of the range of valid values. Parameter name: delta - """ or "Specified argument was out of the range of valid values. (Parameter 'delta')"); + """, + "Specified argument was out of the range of valid values. (Parameter 'delta')"); } public void DoubleAreEqual_ExpectedIsNumeric_ActualIsNaN_DeltaIsNegative_ShouldFail() { - Exception ex = VerifyThrows(() => Assert.AreEqual(1.0d, double.NaN, -1.0d)); - Verify(ex.Message is """ + Action action = () => Assert.AreEqual(1.0d, double.NaN, -1.0d); + action.Should().Throw() + .And.Message.Should().BeOneOf( + """ Specified argument was out of the range of valid values. Parameter name: delta - """ or "Specified argument was out of the range of valid values. (Parameter 'delta')"); + """, + "Specified argument was out of the range of valid values. (Parameter 'delta')"); } public void DoubleAreEqual_ExpectedIsNumeric_ActualIsNumeric_ExpectedAndActualNotEquals_DeltaIsNegativeInf_ShouldFail() { - Exception ex = VerifyThrows(() => Assert.AreEqual(1.0d, 2.0d, double.NegativeInfinity)); - Verify(ex.Message is """ + Action action = () => Assert.AreEqual(1.0d, 2.0d, double.NegativeInfinity); + action.Should().Throw() + .And.Message.Should().BeOneOf( + """ Specified argument was out of the range of valid values. Parameter name: delta - """ or "Specified argument was out of the range of valid values. (Parameter 'delta')"); + """, + "Specified argument was out of the range of valid values. (Parameter 'delta')"); } public void DoubleAreEqual_ExpectedIsNumeric_ActualIsNumeric_ExpectedAndActualEquals_DeltaIsNegativeInf_ShouldFail() { - Exception ex = VerifyThrows(() => Assert.AreEqual(1.0d, 1.0d, double.NegativeInfinity)); - Verify(ex.Message is """ + Action action = () => Assert.AreEqual(1.0d, 1.0d, double.NegativeInfinity); + action.Should().Throw() + .And.Message.Should().BeOneOf( + """ Specified argument was out of the range of valid values. Parameter name: delta - """ or "Specified argument was out of the range of valid values. (Parameter 'delta')"); + """, + "Specified argument was out of the range of valid values. (Parameter 'delta')"); } public void DoubleAreEqual_ExpectedIsNaN_ActualIsNumeric_DeltaIsNegativeInf_ShouldFail() { - Exception ex = VerifyThrows(() => Assert.AreEqual(double.NaN, 1.0d, double.NegativeInfinity)); - Verify(ex.Message is """ + Action action = () => Assert.AreEqual(double.NaN, 1.0d, double.NegativeInfinity); + action.Should().Throw() + .And.Message.Should().BeOneOf( + """ Specified argument was out of the range of valid values. Parameter name: delta - """ or "Specified argument was out of the range of valid values. (Parameter 'delta')"); + """, + "Specified argument was out of the range of valid values. (Parameter 'delta')"); } public void DoubleAreEqual_ExpectedIsNaN_ActualIsNaN_DeltaIsNegativeInf_ShouldFail() { - Exception ex = VerifyThrows(() => Assert.AreEqual(double.NaN, double.NaN, double.NegativeInfinity)); - Verify(ex.Message is """ + Action action = () => Assert.AreEqual(double.NaN, double.NaN, double.NegativeInfinity); + action.Should().Throw() + .And.Message.Should().BeOneOf( + """ Specified argument was out of the range of valid values. Parameter name: delta - """ or "Specified argument was out of the range of valid values. (Parameter 'delta')"); + """, "Specified argument was out of the range of valid values. (Parameter 'delta')"); } public void DoubleAreEqual_ExpectedIsNumeric_ActualIsNaN_DeltaIsNegativeInf_ShouldFail() { - Exception ex = VerifyThrows(() => Assert.AreEqual(1.0d, double.NaN, double.NegativeInfinity)); - Verify(ex.Message is """ + Action action = () => Assert.AreEqual(1.0d, double.NaN, double.NegativeInfinity); + action.Should().Throw() + .And.Message.Should().BeOneOf( + """ Specified argument was out of the range of valid values. Parameter name: delta - """ or "Specified argument was out of the range of valid values. (Parameter 'delta')"); + """, + "Specified argument was out of the range of valid values. (Parameter 'delta')"); } public void DoubleAreEqual_ExpectedIsNumeric_ActualIsNumeric_ExpectedAndActualDifferenceGreaterThanDeltaPositive_DeltaIsNumeric_ShouldFail() { - Exception ex = VerifyThrows(() => Assert.AreEqual(5.0d, 2.0d, 2.0d)); // difference is 3. Delta is 2 - Verify(ex.Message == "Assert.AreEqual failed. Expected a difference no greater than <2> between expected value <5> and actual value <2>. "); + Action action = () => Assert.AreEqual(5.0d, 2.0d, 2.0d); // difference is 3. Delta is 2 + action.Should().Throw().And + .Message.Should().Be("Assert.AreEqual failed. Expected a difference no greater than <2> between expected value <5> and actual value <2>. "); } public void DoubleAreEqual_ExpectedIsNumeric_ActualIsNumeric_ExpectedAndActualDifferenceGreaterThanDeltaNegative_DeltaIsNumeric_ShouldFail() { - Exception ex = VerifyThrows(() => Assert.AreEqual(2.0d, 5.0d, 2.0d)); // difference is -3. Delta is 2 - Verify(ex.Message == "Assert.AreEqual failed. Expected a difference no greater than <2> between expected value <2> and actual value <5>. "); + Action action = () => Assert.AreEqual(2.0d, 5.0d, 2.0d); // difference is -3. Delta is 2 + action.Should().Throw().And + .Message.Should().Be("Assert.AreEqual failed. Expected a difference no greater than <2> between expected value <2> and actual value <5>. "); } public void DoubleAreEqual_ExpectedIsNumeric_ActualIsNumeric_ExpectedAndActualDifferenceLessThanDeltaPositive_DeltaIsNumeric_ShouldPass() @@ -915,14 +1127,16 @@ public void DoubleAreEqual_ExpectedIsNumeric_ActualIsNumeric_ExpectedAndActualDi public void DoubleAreEqual_ExpectedIsNumeric_ActualIsNaN_DeltaIsNumeric_ShouldFail() { - Exception ex = VerifyThrows(() => Assert.AreEqual(5.0d, double.NaN, 2.0d)); - Verify(ex.Message == "Assert.AreEqual failed. Expected a difference no greater than <2> between expected value <5> and actual value . "); + Action action = () => Assert.AreEqual(5.0d, double.NaN, 2.0d); + action.Should().Throw().And + .Message.Should().Be("Assert.AreEqual failed. Expected a difference no greater than <2> between expected value <5> and actual value . "); } public void DoubleAreEqual_ExpectedIsNaN_ActualIsNumeric_DeltaIsNumeric_ShouldFail() { - Exception ex = VerifyThrows(() => Assert.AreEqual(double.NaN, 5.0d, 2.0d)); - Verify(ex.Message == "Assert.AreEqual failed. Expected a difference no greater than <2> between expected value and actual value <5>. "); + Action action = () => Assert.AreEqual(double.NaN, 5.0d, 2.0d); + action.Should().Throw().And + .Message.Should().Be("Assert.AreEqual failed. Expected a difference no greater than <2> between expected value and actual value <5>. "); } public void DoubleAreEqual_ExpectedIsNaN_ActualIsNaN_DeltaIsNumeric_ShouldPass() @@ -930,137 +1144,182 @@ public void DoubleAreEqual_ExpectedIsNaN_ActualIsNaN_DeltaIsNumeric_ShouldPass() public void DoubleAreNotEqual_ExpectedIsNumeric_ActualIsNumeric_ExpectedAndActualNotEquals_DeltaIsNaN_ShouldFail() { - Exception ex = VerifyThrows(() => Assert.AreNotEqual(1.0d, 2.0d, double.NaN)); - Verify(ex.Message is """ + Action action = () => Assert.AreNotEqual(1.0d, 2.0d, double.NaN); + action.Should().Throw() + .And.Message.Should().BeOneOf( + """ Specified argument was out of the range of valid values. Parameter name: delta - """ or "Specified argument was out of the range of valid values. (Parameter 'delta')"); + """, + "Specified argument was out of the range of valid values. (Parameter 'delta')"); } public void DoubleAreNotEqual_ExpectedIsNumeric_ActualIsNumeric_ExpectedAndActualEquals_DeltaIsNaN_ShouldFail() { - Exception ex = VerifyThrows(() => Assert.AreNotEqual(1.0d, 1.0d, double.NaN)); - Verify(ex.Message is """ + Action action = () => Assert.AreNotEqual(1.0d, 1.0d, double.NaN); + action.Should().Throw() + .And.Message.Should().BeOneOf( + """ Specified argument was out of the range of valid values. Parameter name: delta - """ or "Specified argument was out of the range of valid values. (Parameter 'delta')"); + """, + "Specified argument was out of the range of valid values. (Parameter 'delta')"); } public void DoubleAreNotEqual_ExpectedIsNaN_ActualIsNumeric_DeltaIsNaN_ShouldFail() { - Exception ex = VerifyThrows(() => Assert.AreNotEqual(double.NaN, 1.0d, double.NaN)); - Verify(ex.Message is """ + Action action = () => Assert.AreNotEqual(double.NaN, 1.0d, double.NaN); + action.Should().Throw() + .And.Message.Should().BeOneOf( + """ Specified argument was out of the range of valid values. Parameter name: delta - """ or "Specified argument was out of the range of valid values. (Parameter 'delta')"); + """, + "Specified argument was out of the range of valid values. (Parameter 'delta')"); } public void DoubleAreNotEqual_ExpectedIsNaN_ActualIsNaN_DeltaIsNaN_ShouldFail() { - Exception ex = VerifyThrows(() => Assert.AreNotEqual(double.NaN, double.NaN, double.NaN)); - Verify(ex.Message is """ + Action action = () => Assert.AreNotEqual(double.NaN, double.NaN, double.NaN); + action.Should().Throw() + .And.Message.Should().BeOneOf( + """ Specified argument was out of the range of valid values. Parameter name: delta - """ or "Specified argument was out of the range of valid values. (Parameter 'delta')"); + """, + "Specified argument was out of the range of valid values. (Parameter 'delta')"); } public void DoubleAreNotEqual_ExpectedIsNumeric_ActualIsNaN_DeltaIsNaN_ShouldFail() { - Exception ex = VerifyThrows(() => Assert.AreNotEqual(1.0d, double.NaN, double.NaN)); - Verify(ex.Message is """ + Action action = () => Assert.AreNotEqual(1.0d, double.NaN, double.NaN); + action.Should().Throw() + .And.Message.Should().BeOneOf( + """ Specified argument was out of the range of valid values. Parameter name: delta - """ or "Specified argument was out of the range of valid values. (Parameter 'delta')"); + """, + "Specified argument was out of the range of valid values. (Parameter 'delta')"); } public void DoubleAreNotEqual_ExpectedIsNumeric_ActualIsNumeric_ExpectedAndActualNotEquals_DeltaIsNegative_ShouldFail() { - Exception ex = VerifyThrows(() => Assert.AreNotEqual(1.0d, 2.0d, -1.0d)); - Verify(ex.Message is """ + Action action = () => Assert.AreNotEqual(1.0d, 2.0d, -1.0d); + action.Should().Throw() + .And.Message.Should().BeOneOf( + """ Specified argument was out of the range of valid values. Parameter name: delta - """ or "Specified argument was out of the range of valid values. (Parameter 'delta')"); + """, + "Specified argument was out of the range of valid values. (Parameter 'delta')"); } public void DoubleAreNotEqual_ExpectedIsNumeric_ActualIsNumeric_ExpectedAndActualEquals_DeltaIsNegative_ShouldFail() { - Exception ex = VerifyThrows(() => Assert.AreNotEqual(1.0d, 1.0d, -1.0d)); - Verify(ex.Message is """ + Action action = () => Assert.AreNotEqual(1.0d, 1.0d, -1.0d); + action.Should().Throw() + .And.Message.Should().BeOneOf( + """ Specified argument was out of the range of valid values. Parameter name: delta - """ or "Specified argument was out of the range of valid values. (Parameter 'delta')"); + """, + "Specified argument was out of the range of valid values. (Parameter 'delta')"); } public void DoubleAreNotEqual_ExpectedIsNaN_ActualIsNumeric_DeltaIsNegative_ShouldFail() { - Exception ex = VerifyThrows(() => Assert.AreNotEqual(double.NaN, 1.0d, -1.0d)); - Verify(ex.Message is """ + Action action = () => Assert.AreNotEqual(double.NaN, 1.0d, -1.0d); + action.Should().Throw() + .And.Message.Should().BeOneOf( + """ Specified argument was out of the range of valid values. Parameter name: delta - """ or "Specified argument was out of the range of valid values. (Parameter 'delta')"); + """, + "Specified argument was out of the range of valid values. (Parameter 'delta')"); } public void DoubleAreNotEqual_ExpectedIsNaN_ActualIsNaN_DeltaIsNegative_ShouldFail() { - Exception ex = VerifyThrows(() => Assert.AreNotEqual(double.NaN, double.NaN, -1.0d)); - Verify(ex.Message is """ + Action action = () => Assert.AreNotEqual(double.NaN, double.NaN, -1.0d); + action.Should().Throw() + .And.Message.Should().BeOneOf( + """ Specified argument was out of the range of valid values. Parameter name: delta - """ or "Specified argument was out of the range of valid values. (Parameter 'delta')"); + """, + "Specified argument was out of the range of valid values. (Parameter 'delta')"); } public void DoubleAreNotEqual_ExpectedIsNumeric_ActualIsNaN_DeltaIsNegative_ShouldFail() { - Exception ex = VerifyThrows(() => Assert.AreNotEqual(1.0d, double.NaN, -1.0d)); - Verify(ex.Message is """ + Action action = () => Assert.AreNotEqual(1.0d, double.NaN, -1.0d); + action.Should().Throw() + .And.Message.Should().BeOneOf( + """ Specified argument was out of the range of valid values. Parameter name: delta - """ or "Specified argument was out of the range of valid values. (Parameter 'delta')"); + """, + "Specified argument was out of the range of valid values. (Parameter 'delta')"); } public void DoubleAreNotEqual_ExpectedIsNumeric_ActualIsNumeric_ExpectedAndActualNotEquals_DeltaIsNegativeInf_ShouldFail() { - Exception ex = VerifyThrows(() => Assert.AreNotEqual(1.0d, 2.0d, double.NegativeInfinity)); - Verify(ex.Message is """ + Action action = () => Assert.AreNotEqual(1.0d, 2.0d, double.NegativeInfinity); + action.Should().Throw() + .And.Message.Should().BeOneOf( + """ Specified argument was out of the range of valid values. Parameter name: delta - """ or "Specified argument was out of the range of valid values. (Parameter 'delta')"); + """, + "Specified argument was out of the range of valid values. (Parameter 'delta')"); } public void DoubleAreNotEqual_ExpectedIsNumeric_ActualIsNumeric_ExpectedAndActualEquals_DeltaIsNegativeInf_ShouldFail() { - Exception ex = VerifyThrows(() => Assert.AreNotEqual(1.0d, 1.0d, double.NegativeInfinity)); - Verify(ex.Message is """ + Action action = () => Assert.AreNotEqual(1.0d, 1.0d, double.NegativeInfinity); + action.Should().Throw() + .And.Message.Should().BeOneOf( + """ Specified argument was out of the range of valid values. Parameter name: delta - """ or "Specified argument was out of the range of valid values. (Parameter 'delta')"); + """, + "Specified argument was out of the range of valid values. (Parameter 'delta')"); } public void DoubleAreNotEqual_ExpectedIsNaN_ActualIsNumeric_DeltaIsNegativeInf_ShouldFail() { - Exception ex = VerifyThrows(() => Assert.AreNotEqual(double.NaN, 1.0d, double.NegativeInfinity)); - Verify(ex.Message is """ + Action action = () => Assert.AreNotEqual(double.NaN, 1.0d, double.NegativeInfinity); + action.Should().Throw() + .And.Message.Should().BeOneOf( + """ Specified argument was out of the range of valid values. Parameter name: delta - """ or "Specified argument was out of the range of valid values. (Parameter 'delta')"); + """, + "Specified argument was out of the range of valid values. (Parameter 'delta')"); } public void DoubleAreNotEqual_ExpectedIsNaN_ActualIsNaN_DeltaIsNegativeInf_ShouldFail() { - Exception ex = VerifyThrows(() => Assert.AreNotEqual(double.NaN, double.NaN, double.NegativeInfinity)); - Verify(ex.Message is """ - Specified argument was out of the range of valid values. - Parameter name: delta - """ or "Specified argument was out of the range of valid values. (Parameter 'delta')"); + Action action = () => Assert.AreNotEqual(double.NaN, double.NaN, double.NegativeInfinity); + action.Should().Throw().And + .Message.Should().BeOneOf( + """ + Specified argument was out of the range of valid values. + Parameter name: delta + """, + "Specified argument was out of the range of valid values. (Parameter 'delta')"); } public void DoubleAreNotEqual_ExpectedIsNumeric_ActualIsNaN_DeltaIsNegativeInf_ShouldFail() { - Exception ex = VerifyThrows(() => Assert.AreNotEqual(1.0d, double.NaN, double.NegativeInfinity)); - Verify(ex.Message is """ - Specified argument was out of the range of valid values. - Parameter name: delta - """ or "Specified argument was out of the range of valid values. (Parameter 'delta')"); + Action action = () => Assert.AreNotEqual(1.0d, double.NaN, double.NegativeInfinity); + action.Should().Throw().And + .Message.Should().BeOneOf( + """ + Specified argument was out of the range of valid values. + Parameter name: delta + """, + "Specified argument was out of the range of valid values. (Parameter 'delta')"); } public void DoubleAreNotEqual_ExpectedIsNumeric_ActualIsNumeric_ExpectedAndActualDifferenceGreaterThanDeltaPositive_DeltaIsNumeric_ShouldPass() @@ -1071,14 +1330,16 @@ public void DoubleAreNotEqual_ExpectedIsNumeric_ActualIsNumeric_ExpectedAndActua public void DoubleAreNotEqual_ExpectedIsNumeric_ActualIsNumeric_ExpectedAndActualDifferenceLessThanDeltaPositive_DeltaIsNumeric_ShouldFail() { - Exception ex = VerifyThrows(() => Assert.AreNotEqual(5.0d, 4.0d, 2.0d)); // difference is 1. Delta is 2 - Verify(ex.Message == "Assert.AreNotEqual failed. Expected a difference greater than <2> between expected value <5> and actual value <4>. "); + Action action = () => Assert.AreNotEqual(5.0d, 4.0d, 2.0d); // difference is 1. Delta is 2 + action.Should().Throw().And + .Message.Should().Be("Assert.AreNotEqual failed. Expected a difference greater than <2> between expected value <5> and actual value <4>. "); } public void DoubleAreNotEqual_ExpectedIsNumeric_ActualIsNumeric_ExpectedAndActualDifferenceLessThanDeltaNegative_DeltaIsNumeric_ShouldFail() { - Exception ex = VerifyThrows(() => Assert.AreNotEqual(4.0d, 5.0d, 2.0d)); // difference is -1. Delta is 2 - Verify(ex.Message == "Assert.AreNotEqual failed. Expected a difference greater than <2> between expected value <4> and actual value <5>. "); + Action action = () => Assert.AreNotEqual(4.0d, 5.0d, 2.0d); // difference is -1. Delta is 2 + action.Should().Throw().And + .Message.Should().Be("Assert.AreNotEqual failed. Expected a difference greater than <2> between expected value <4> and actual value <5>. "); } public void DoubleAreNotEqual_ExpectedIsNumeric_ActualIsNaN_DeltaIsNumeric_ShouldPass() => Assert.AreNotEqual(5.0d, double.NaN, 2.0d); @@ -1088,8 +1349,9 @@ public void DoubleAreNotEqual_ExpectedIsNaN_ActualIsNumeric_DeltaIsNumeric_Shoul public void DoubleAreNotEqual_ExpectedIsNaN_ActualIsNaN_DeltaIsNumeric_ShouldFail() { - Exception ex = VerifyThrows(() => Assert.AreNotEqual(double.NaN, double.NaN, 2.0d)); - Verify(ex.Message == "Assert.AreNotEqual failed. Expected a difference greater than <2> between expected value and actual value . "); + Action action = () => Assert.AreNotEqual(double.NaN, double.NaN, 2.0d); + action.Should().Throw().And + .Message.Should().Be("Assert.AreNotEqual failed. Expected a difference greater than <2> between expected value and actual value . "); } private class TypeOverridesEquals @@ -1145,8 +1407,9 @@ public override int GetHashCode() public void AreEqualStringDifferenceAtBeginning() { - Exception ex = VerifyThrows(() => Assert.AreEqual("baaa", "aaaa")); - ex.Message.Should().Be(""" + Action action = () => Assert.AreEqual("baaa", "aaaa"); + action.Should().Throw() + .And.Message.Should().Be(""" Assert.AreEqual failed. String lengths are both 4 but differ at index 0. Expected: "baaa" But was: "aaaa" @@ -1156,8 +1419,9 @@ Assert.AreEqual failed. String lengths are both 4 but differ at index 0. public void AreEqualStringDifferenceAtEnd() { - Exception ex = VerifyThrows(() => Assert.AreEqual("aaaa", "aaab")); - ex.Message.Should().Be(""" + Action action = () => Assert.AreEqual("aaaa", "aaab"); + action.Should().Throw() + .And.Message.Should().Be(""" Assert.AreEqual failed. String lengths are both 4 but differ at index 3. Expected: "aaaa" But was: "aaab" @@ -1167,8 +1431,9 @@ Assert.AreEqual failed. String lengths are both 4 but differ at index 3. public void AreEqualStringWithSpecialCharactersShouldEscape() { - Exception ex = VerifyThrows(() => Assert.AreEqual("aa\ta", "aa a")); - ex.Message.Should().Be(""" + Action action = () => Assert.AreEqual("aa\ta", "aa a"); + action.Should().Throw() + .And.Message.Should().Be(""" Assert.AreEqual failed. String lengths are both 4 but differ at index 2. Expected: "aa␉a" But was: "aa a" @@ -1181,8 +1446,9 @@ public void AreEqualLongStringsShouldTruncateAndShowContext() string expected = new string('a', 100) + "b" + new string('c', 100); string actual = new string('a', 100) + "d" + new string('c', 100); - Exception ex = VerifyThrows(() => Assert.AreEqual(expected, actual)); - ex.Message.Should().Be(""" + Action action = () => Assert.AreEqual(expected, actual); + action.Should().Throw() + .And.Message.Should().Be(""" Assert.AreEqual failed. String lengths are both 201 but differ at index 100. Expected: "...aaaaaaaaaaaaaaaaaabcccccccccccccccc..." But was: "...aaaaaaaaaaaaaaaaaadcccccccccccccccc..." @@ -1192,8 +1458,9 @@ Assert.AreEqual failed. String lengths are both 201 but differ at index 100. public void AreEqualStringWithCultureShouldUseEnhancedMessage() { - Exception ex = VerifyThrows(() => Assert.AreEqual("aaaa", "aaab", false, CultureInfo.InvariantCulture)); - ex.Message.Should().Be(""" + Action action = () => Assert.AreEqual("aaaa", "aaab", false, CultureInfo.InvariantCulture); + action.Should().Throw() + .And.Message.Should().Be(""" Assert.AreEqual failed. String lengths are both 4 but differ at index 3. Expected: "aaaa" But was: "aaab" @@ -1203,8 +1470,9 @@ Assert.AreEqual failed. String lengths are both 4 but differ at index 3. public void AreEqualStringWithDifferentLength() { - Exception ex = VerifyThrows(() => Assert.AreEqual("aaaa", "aaa")); - ex.Message.Should().Be(""" + Action action = () => Assert.AreEqual("aaaa", "aaa"); + action.Should().Throw() + .And.Message.Should().Be(""" Assert.AreEqual failed. Expected string length 4 but was 3. Expected: "aaaa" But was: "aaa" @@ -1214,8 +1482,9 @@ Assert.AreEqual failed. Expected string length 4 but was 3. public void AreEqualShorterExpectedString() { - Exception ex = VerifyThrows(() => Assert.AreEqual("aaa", "aaab")); - ex.Message.Should().Be(""" + Action action = () => Assert.AreEqual("aaa", "aaab"); + action.Should().Throw() + .And.Message.Should().Be(""" Assert.AreEqual failed. Expected string length 3 but was 4. Expected: "aaa" But was: "aaab" @@ -1225,8 +1494,9 @@ Assert.AreEqual failed. Expected string length 3 but was 4. public void AreEqualStringWithUserMessage() { - Exception ex = VerifyThrows(() => Assert.AreEqual("aaaa", "aaab", "My custom message")); - ex.Message.Should().Be(""" + Action action = () => Assert.AreEqual("aaaa", "aaab", "My custom message"); + action.Should().Throw() + .And.Message.Should().Be(""" Assert.AreEqual failed. String lengths are both 4 but differ at index 3. My custom message Expected: "aaaa" But was: "aaab" @@ -1236,8 +1506,9 @@ Assert.AreEqual failed. String lengths are both 4 but differ at index 3. My cust public void AreEqualStringWithEmojis() { - Exception ex = VerifyThrows(() => Assert.AreEqual("🥰", "aaab")); - ex.Message.Should().Be(""" + Action action = () => Assert.AreEqual("🥰", "aaab"); + action.Should().Throw().And + .Message.Should().Be(""" Assert.AreEqual failed. Expected string length 2 but was 4. Expected: "🥰" But was: "aaab" diff --git a/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.AreSame.cs b/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.AreSame.cs index 853f3c1f37..57d9a643c4 100644 --- a/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.AreSame.cs +++ b/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.AreSame.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 AwesomeAssertions; + namespace Microsoft.VisualStudio.TestPlatform.TestFramework.UnitTests; public partial class AssertTests @@ -13,8 +15,8 @@ public void AreSame_PassSameObject_ShouldPass() public void AreSame_PassDifferentObject_ShouldFail() { - Exception ex = VerifyThrows(() => Assert.AreSame(new object(), new object())); - Verify(ex.Message == "Assert.AreSame failed. "); + Action action = () => Assert.AreSame(new object(), new object()); + action.Should().Throw().And.Message.Should().Be("Assert.AreSame failed. "); } public void AreSame_StringMessage_PassSameObject_ShouldPass() @@ -25,24 +27,24 @@ public void AreSame_StringMessage_PassSameObject_ShouldPass() public void AreSame_StringMessage_PassDifferentObject_ShouldFail() { - Exception ex = VerifyThrows(() => Assert.AreSame(new object(), new object(), "User-provided message")); - Verify(ex.Message == "Assert.AreSame failed. User-provided message"); + Action action = () => Assert.AreSame(new object(), new object(), "User-provided message"); + action.Should().Throw().And.Message.Should().Be("Assert.AreSame failed. User-provided message"); } public void AreSame_InterpolatedString_PassSameObject_ShouldPass() { DummyClassTrackingToStringCalls o = new(); Assert.AreSame(o, o, $"User-provided message: {o}"); - Verify(!o.WasToStringCalled); + o.WasToStringCalled.Should().BeFalse(); } public async Task AreSame_InterpolatedString_PassDifferentObject_ShouldFail() { DummyClassTrackingToStringCalls o = new(); DateTime dateTime = DateTime.Now; - Exception ex = await VerifyThrowsAsync(async () => Assert.AreSame(new object(), new object(), $"User-provided message. {o}, {o,35}, {await GetHelloStringAsync()}, {new DummyIFormattable()}, {dateTime:tt}, {dateTime,5:tt}")); - Verify(ex.Message == $"Assert.AreSame failed. User-provided message. DummyClassTrackingToStringCalls, DummyClassTrackingToStringCalls, Hello, DummyIFormattable.ToString(), {string.Format(null, "{0:tt}", dateTime)}, {string.Format(null, "{0,5:tt}", dateTime)}"); - Verify(o.WasToStringCalled); + Func action = async () => Assert.AreSame(new object(), new object(), $"User-provided message. {o}, {o,35}, {await GetHelloStringAsync()}, {new DummyIFormattable()}, {dateTime:tt}, {dateTime,5:tt}"); + (await action.Should().ThrowAsync()).And.Message.Should().Be($"Assert.AreSame failed. User-provided message. DummyClassTrackingToStringCalls, DummyClassTrackingToStringCalls, Hello, DummyIFormattable.ToString(), {string.Format(null, "{0:tt}", dateTime)}, {string.Format(null, "{0,5:tt}", dateTime)}"); + o.WasToStringCalled.Should().BeTrue(); } public void AreSame_MessageArgs_PassSameObject_ShouldPass() @@ -53,8 +55,8 @@ public void AreSame_MessageArgs_PassSameObject_ShouldPass() public void AreSame_MessageArgs_PassDifferentObject_ShouldFail() { - Exception ex = VerifyThrows(() => Assert.AreSame(new object(), new object(), "User-provided message: System.Object type: {0}", new object().GetType())); - Verify(ex.Message == "Assert.AreSame failed. User-provided message: System.Object type: System.Object"); + Action action = () => Assert.AreSame(new object(), new object(), "User-provided message: System.Object type: {0}", new object().GetType()); + action.Should().Throw().And.Message.Should().Be("Assert.AreSame failed. User-provided message: System.Object type: System.Object"); } public void AreNotSame_PassDifferentObject_ShouldPass() @@ -62,33 +64,33 @@ public void AreNotSame_PassDifferentObject_ShouldPass() public void AreSame_BothAreValueTypes_ShouldFailWithSpecializedMessage() { - Exception ex = VerifyThrows(() => Assert.AreSame(1, 1)); - Verify(ex.Message == "Assert.AreSame failed. Do not pass value types to AreSame(). Values converted to Object will never be the same. Consider using AreEqual(). "); + Action action = () => Assert.AreSame(1, 1); + action.Should().Throw().And.Message.Should().Be("Assert.AreSame failed. Do not pass value types to AreSame(). Values converted to Object will never be the same. Consider using AreEqual(). "); } public void AreSame_StringMessage_BothAreValueTypes_ShouldFailWithSpecializedMessage() { - Exception ex = VerifyThrows(() => Assert.AreSame(1, 1, "User-provided message")); - Verify(ex.Message == "Assert.AreSame failed. Do not pass value types to AreSame(). Values converted to Object will never be the same. Consider using AreEqual(). User-provided message"); + Action action = () => Assert.AreSame(1, 1, "User-provided message"); + action.Should().Throw().And.Message.Should().Be("Assert.AreSame failed. Do not pass value types to AreSame(). Values converted to Object will never be the same. Consider using AreEqual(). User-provided message"); } public void AreSame_InterpolatedString_BothAreValueTypes_ShouldFailWithSpecializedMessage() { - Exception ex = VerifyThrows(() => Assert.AreSame(1, 1, $"User-provided message {new object().GetType()}")); - Verify(ex.Message == "Assert.AreSame failed. Do not pass value types to AreSame(). Values converted to Object will never be the same. Consider using AreEqual(). User-provided message System.Object"); + Action action = () => Assert.AreSame(1, 1, $"User-provided message {new object().GetType()}"); + action.Should().Throw().And.Message.Should().Be("Assert.AreSame failed. Do not pass value types to AreSame(). Values converted to Object will never be the same. Consider using AreEqual(). User-provided message System.Object"); } public void AreSame_MessageArgs_BothAreValueTypes_ShouldFailWithSpecializedMessage() { - Exception ex = VerifyThrows(() => Assert.AreSame(1, 1, "User-provided message {0}", new object().GetType())); - Verify(ex.Message == "Assert.AreSame failed. Do not pass value types to AreSame(). Values converted to Object will never be the same. Consider using AreEqual(). User-provided message System.Object"); + Action action = () => Assert.AreSame(1, 1, "User-provided message {0}", new object().GetType()); + action.Should().Throw().And.Message.Should().Be("Assert.AreSame failed. Do not pass value types to AreSame(). Values converted to Object will never be the same. Consider using AreEqual(). User-provided message System.Object"); } public void AreNotSame_PassSameObject_ShouldFail() { object o = new(); - Exception ex = VerifyThrows(() => Assert.AreNotSame(o, o)); - Verify(ex.Message == "Assert.AreNotSame failed. "); + Action action = () => Assert.AreNotSame(o, o); + action.Should().Throw().And.Message.Should().Be("Assert.AreNotSame failed. "); } public void AreNotSame_StringMessage_PassDifferentObject_ShouldPass() @@ -97,24 +99,24 @@ public void AreNotSame_StringMessage_PassDifferentObject_ShouldPass() public void AreNotSame_StringMessage_PassSameObject_ShouldFail() { object o = new(); - Exception ex = VerifyThrows(() => Assert.AreNotSame(o, o, "User-provided message")); - Verify(ex.Message == "Assert.AreNotSame failed. User-provided message"); + Action action = () => Assert.AreNotSame(o, o, "User-provided message"); + action.Should().Throw().And.Message.Should().Be("Assert.AreNotSame failed. User-provided message"); } public void AreNotSame_InterpolatedString_PassDifferentObject_ShouldPass() { DummyClassTrackingToStringCalls o = new(); Assert.AreNotSame(new object(), new object(), $"User-provided message: {o}"); - Verify(!o.WasToStringCalled); + o.WasToStringCalled.Should().BeFalse(); } public async Task AreNotSame_InterpolatedString_PassSameObject_ShouldFail() { DummyClassTrackingToStringCalls o = new(); DateTime dateTime = DateTime.Now; - Exception ex = await VerifyThrowsAsync(async () => Assert.AreNotSame(o, o, $"User-provided message. {o}, {o,35}, {await GetHelloStringAsync()}, {new DummyIFormattable()}, {dateTime:tt}, {dateTime,5:tt}")); - Verify(ex.Message == $"Assert.AreNotSame failed. User-provided message. DummyClassTrackingToStringCalls, DummyClassTrackingToStringCalls, Hello, DummyIFormattable.ToString(), {string.Format(null, "{0:tt}", dateTime)}, {string.Format(null, "{0,5:tt}", dateTime)}"); - Verify(o.WasToStringCalled); + Func action = async () => Assert.AreNotSame(o, o, $"User-provided message. {o}, {o,35}, {await GetHelloStringAsync()}, {new DummyIFormattable()}, {dateTime:tt}, {dateTime,5:tt}"); + (await action.Should().ThrowAsync()).And.Message.Should().Be($"Assert.AreNotSame failed. User-provided message. DummyClassTrackingToStringCalls, DummyClassTrackingToStringCalls, Hello, DummyIFormattable.ToString(), {string.Format(null, "{0:tt}", dateTime)}, {string.Format(null, "{0,5:tt}", dateTime)}"); + o.WasToStringCalled.Should().BeTrue(); } public void AreNotSame_MessageArgs_PassDifferentObject_ShouldPass() @@ -123,7 +125,7 @@ public void AreNotSame_MessageArgs_PassDifferentObject_ShouldPass() public void AreNotSame_MessageArgs_PassSameObject_ShouldFail() { object o = new(); - Exception ex = VerifyThrows(() => Assert.AreNotSame(o, o, "User-provided message: System.Object type: {0}", new object().GetType())); - Verify(ex.Message == "Assert.AreNotSame failed. User-provided message: System.Object type: System.Object"); + Action action = () => Assert.AreNotSame(o, o, "User-provided message: System.Object type: {0}", new object().GetType()); + action.Should().Throw().And.Message.Should().Be("Assert.AreNotSame failed. User-provided message: System.Object type: System.Object"); } } diff --git a/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.InconclusiveTests.cs b/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.InconclusiveTests.cs index ab5402696e..cb58a2ecd2 100644 --- a/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.InconclusiveTests.cs +++ b/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.InconclusiveTests.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 AwesomeAssertions; + namespace Microsoft.VisualStudio.TestPlatform.TestFramework.UnitTests; public partial class AssertTests @@ -8,12 +10,16 @@ public partial class AssertTests // See https://github.com/dotnet/sdk/issues/25373 public void InconclusiveDoesNotThrowWhenMessageContainsInvalidStringFormatCompositeAndNoArgumentsPassed() { - Exception ex = VerifyThrows(() => Assert.Inconclusive("{")); - Verify(ex.Message.Contains("Assert.Inconclusive failed. {")); + Action action = () => Assert.Inconclusive("{"); + action.Should().Throw() + .And.Message.Should().Contain("Assert.Inconclusive failed. {"); } // See https://github.com/dotnet/sdk/issues/25373 [SuppressMessage("Usage", "CA2241:Provide correct arguments to formatting methods", Justification = "We want to test invalid format")] - public void InconclusiveThrowsWhenMessageContainsInvalidStringFormatComposite() => - VerifyThrows(() => Assert.Inconclusive("{", "arg")); + public void InconclusiveThrowsWhenMessageContainsInvalidStringFormatComposite() + { + Action action = () => Assert.Inconclusive("{", "arg"); + action.Should().Throw(); + } } diff --git a/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.IsInRange.cs b/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.IsInRange.cs index c3aef44bc3..1b729b9da6 100644 --- a/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.IsInRange.cs +++ b/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.IsInRange.cs @@ -55,8 +55,9 @@ public void IsInRange_WithValueBelowRange_ThrowsAssertFailedException() int value = 3; // Act & Assert - Exception ex = VerifyThrows(() => Assert.IsInRange(minValue, maxValue, value)); - Verify(ex.Message.Contains("Value '3' is not within the expected range [5, 10]")); + Action action = () => Assert.IsInRange(minValue, maxValue, value); + action.Should().Throw() + .And.Message.Should().Contain("Value '3' is not within the expected range [5, 10]"); } public void IsInRange_WithValueAboveRange_ThrowsAssertFailedException() @@ -67,8 +68,9 @@ public void IsInRange_WithValueAboveRange_ThrowsAssertFailedException() int value = 8; // Act & Assert - Exception ex = VerifyThrows(() => Assert.IsInRange(minValue, maxValue, value)); - Verify(ex.Message.Contains("Value '8' is not within the expected range [1, 5]")); + Action action = () => Assert.IsInRange(minValue, maxValue, value); + action.Should().Throw() + .And.Message.Should().Contain("Value '8' is not within the expected range [1, 5]"); } public void IsInRange_WithCustomMessage_IncludesCustomMessage() @@ -115,8 +117,9 @@ public void IsInRange_WithDoubleValues_WorksCorrectly() // Act & Assert Assert.IsInRange(minValue, maxValue, valueInRange); - Exception ex = VerifyThrows(() => Assert.IsInRange(minValue, maxValue, valueOutOfRange)); - Verify(ex.Message.Contains("Value '6' is not within the expected range [1.5, 5.5]")); + Action action = () => Assert.IsInRange(minValue, maxValue, valueOutOfRange); + action.Should().Throw() + .And.Message.Should().Contain("Value '6' is not within the expected range [1.5, 5.5]"); } public void IsInRange_WithDateTimeValues_WorksCorrectly() diff --git a/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.IsInstanceOfTypeTests.cs b/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.IsInstanceOfTypeTests.cs index b6517c2b60..8f8c1b5400 100644 --- a/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.IsInstanceOfTypeTests.cs +++ b/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.IsInstanceOfTypeTests.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 AwesomeAssertions; + namespace Microsoft.VisualStudio.TestPlatform.TestFramework.UnitTests; [SuppressMessage("Usage", "CA2263:Prefer generic overload when type is known", Justification = "We want to test also the non-generic API")] @@ -8,20 +10,23 @@ public partial class AssertTests { public void InstanceOfTypeShouldFailWhenValueIsNull() { - Exception ex = VerifyThrows(() => Assert.IsInstanceOfType(null, typeof(AssertTests))); - Verify(ex.Message == "Assert.IsInstanceOfType failed. "); + Action action = () => Assert.IsInstanceOfType(null, typeof(AssertTests)); + action.Should().Throw() + .And.Message.Should().Be("Assert.IsInstanceOfType failed. "); } public void InstanceOfTypeShouldFailWhenTypeIsNull() { - Exception ex = VerifyThrows(() => Assert.IsInstanceOfType(5, null)); - Verify(ex.Message == "Assert.IsInstanceOfType failed. "); + Action action = () => Assert.IsInstanceOfType(5, null); + action.Should().Throw() + .And.Message.Should().Be("Assert.IsInstanceOfType failed. "); } public void InstanceOfTypeShouldFailWhenTypeIsMismatched() { - Exception ex = VerifyThrows(() => Assert.IsInstanceOfType(5, typeof(string))); - Verify(ex.Message == "Assert.IsInstanceOfType failed. Expected type:. Actual type:."); + Action action = () => Assert.IsInstanceOfType(5, typeof(string)); + action.Should().Throw() + .And.Message.Should().Be("Assert.IsInstanceOfType failed. Expected type:. Actual type:."); } public void InstanceOfTypeShouldPassOnSameInstance() => Assert.IsInstanceOfType(5, typeof(int)); @@ -30,20 +35,23 @@ public void InstanceOfTypeShouldFailWhenTypeIsMismatched() public void InstanceOfType_WithStringMessage_ShouldFailWhenValueIsNull() { - Exception ex = VerifyThrows(() => Assert.IsInstanceOfType(null, typeof(AssertTests), "User-provided message")); - Verify(ex.Message == "Assert.IsInstanceOfType failed. User-provided message"); + Action action = () => Assert.IsInstanceOfType(null, typeof(AssertTests), "User-provided message"); + action.Should().Throw() + .And.Message.Should().Be("Assert.IsInstanceOfType failed. User-provided message"); } public void InstanceOfType_WithStringMessage_ShouldFailWhenTypeIsNull() { - Exception ex = VerifyThrows(() => Assert.IsInstanceOfType(5, null, "User-provided message")); - Verify(ex.Message == "Assert.IsInstanceOfType failed. User-provided message"); + Action action = () => Assert.IsInstanceOfType(5, null, "User-provided message"); + action.Should().Throw() + .And.Message.Should().Be("Assert.IsInstanceOfType failed. User-provided message"); } public void InstanceOfType_WithStringMessage_ShouldFailWhenTypeIsMismatched() { - Exception ex = VerifyThrows(() => Assert.IsInstanceOfType(5, typeof(string), "User-provided message")); - Verify(ex.Message == "Assert.IsInstanceOfType failed. User-provided message Expected type:. Actual type:."); + Action action = () => Assert.IsInstanceOfType(5, typeof(string), "User-provided message"); + action.Should().Throw() + .And.Message.Should().Be("Assert.IsInstanceOfType failed. User-provided message Expected type:. Actual type:."); } public void InstanceOfType_WithStringMessage_ShouldPassWhenTypeIsCorrect() @@ -53,38 +61,44 @@ public async Task InstanceOfType_WithInterpolatedString_ShouldFailWhenValueIsNul { DummyClassTrackingToStringCalls o = new(); DateTime dateTime = DateTime.Now; - Exception ex = await VerifyThrowsAsync(async () => Assert.IsInstanceOfType(null, typeof(AssertTests), $"User-provided message. {o}, {o,35}, {await GetHelloStringAsync()}, {new DummyIFormattable()}, {dateTime:tt}, {dateTime,5:tt}")); - Verify(ex.Message == $"Assert.IsInstanceOfType failed. User-provided message. DummyClassTrackingToStringCalls, DummyClassTrackingToStringCalls, Hello, DummyIFormattable.ToString(), {string.Format(null, "{0:tt}", dateTime)}, {string.Format(null, "{0,5:tt}", dateTime)}"); - Verify(o.WasToStringCalled); + Func action = async () => Assert.IsInstanceOfType(null, typeof(AssertTests), $"User-provided message. {o}, {o,35}, {await GetHelloStringAsync()}, {new DummyIFormattable()}, {dateTime:tt}, {dateTime,5:tt}"); + (await action.Should().ThrowAsync()) + .And.Message.Should().Be($"Assert.IsInstanceOfType failed. User-provided message. DummyClassTrackingToStringCalls, DummyClassTrackingToStringCalls, Hello, DummyIFormattable.ToString(), {string.Format(null, "{0:tt}", dateTime)}, {string.Format(null, "{0,5:tt}", dateTime)}"); + o.WasToStringCalled.Should().BeTrue(); } public void InstanceOfType_WithInterpolatedString_ShouldFailWhenTypeIsNull() { DummyClassTrackingToStringCalls o = new(); - Exception ex = VerifyThrows(() => Assert.IsInstanceOfType(5, null, $"User-provided message {o}")); - Verify(ex.Message == "Assert.IsInstanceOfType failed. User-provided message DummyClassTrackingToStringCalls"); - Verify(o.WasToStringCalled); + Action action = () => Assert.IsInstanceOfType(5, null, $"User-provided message {o}"); + action.Should().Throw() + .And.Message.Should().Be("Assert.IsInstanceOfType failed. User-provided message DummyClassTrackingToStringCalls"); + o.WasToStringCalled.Should().BeTrue(); } public void InstanceOfType_WithInterpolatedString_ShouldFailWhenTypeIsMismatched() { DummyClassTrackingToStringCalls o = new(); - Exception ex = VerifyThrows(() => Assert.IsInstanceOfType(5, typeof(string), $"User-provided message {o}")); - Verify(ex.Message == "Assert.IsInstanceOfType failed. User-provided message DummyClassTrackingToStringCalls Expected type:. Actual type:."); - Verify(o.WasToStringCalled); + Action action = () => Assert.IsInstanceOfType(5, typeof(string), $"User-provided message {o}"); + action.Should().Throw() + .And.Message.Should().Be("Assert.IsInstanceOfType failed. User-provided message DummyClassTrackingToStringCalls Expected type:. Actual type:."); + o.WasToStringCalled.Should().BeTrue(); } public void InstanceOfType_WithInterpolatedString_ShouldPassWhenTypeIsCorrect() { DummyClassTrackingToStringCalls o = new(); Assert.IsInstanceOfType(5, typeof(int), $"User-provided message {o}"); - Verify(!o.WasToStringCalled); + o.WasToStringCalled.Should().BeFalse(); } public void InstanceNotOfTypeShouldFailWhenValueIsNull() => Assert.IsNotInstanceOfType(null, typeof(object)); - public void InstanceNotOfTypeShouldFailWhenTypeIsNull() => - VerifyThrows(() => Assert.IsNotInstanceOfType(5, null)); + public void InstanceNotOfTypeShouldFailWhenTypeIsNull() + { + Action action = () => Assert.IsNotInstanceOfType(5, null); + action.Should().Throw(); + } public void InstanceNotOfTypeShouldPassOnWrongInstance() => Assert.IsNotInstanceOfType(5L, typeof(int)); @@ -92,27 +106,31 @@ public void InstanceNotOfTypeShouldFailWhenTypeIsNull() => public void IsInstanceOfTypeUsingGenericType_WhenValueIsNull_Fails() { - Exception ex = VerifyThrows(() => Assert.IsInstanceOfType(null)); - Verify(ex.Message == "Assert.IsInstanceOfType failed. "); + Action action = () => Assert.IsInstanceOfType(null); + action.Should().Throw() + .And.Message.Should().Be("Assert.IsInstanceOfType failed. "); } public void IsInstanceOfTypeUsingGenericType_WhenTypeMismatch_Fails() { - Exception ex = VerifyThrows(() => Assert.IsInstanceOfType(5)); - Verify(ex.Message == "Assert.IsInstanceOfType failed. Expected type:. Actual type:."); + Action action = () => Assert.IsInstanceOfType(5); + action.Should().Throw() + .And.Message.Should().Be("Assert.IsInstanceOfType failed. Expected type:. Actual type:."); } public void IsInstanceOfTypeUsingGenericTypeWithOutParameter_WhenValueIsNull_Fails() { AssertTests? assertTests = null; - VerifyThrows(() => Assert.IsInstanceOfType(null, out assertTests)); - Verify(assertTests is null); + Action action = () => Assert.IsInstanceOfType(null, out assertTests); + action.Should().Throw(); + assertTests.Should().BeNull(); } public void IsInstanceOfTypeUsingGenericTypeWithOutParameter_WhenTypeMismatch_Fails() { - Exception ex = VerifyThrows(() => Assert.IsInstanceOfType(5, out _)); - Verify(ex.Message == "Assert.IsInstanceOfType failed. Expected type:. Actual type:."); + Action action = () => Assert.IsInstanceOfType(5, out _); + action.Should().Throw() + .And.Message.Should().Be("Assert.IsInstanceOfType failed. Expected type:. Actual type:."); } public void IsInstanceOfTypeUsingGenericType_OnSameInstance_DoesNotThrow() => Assert.IsInstanceOfType(5); @@ -120,14 +138,14 @@ public void IsInstanceOfTypeUsingGenericTypeWithOutParameter_WhenTypeMismatch_Fa public void IsInstanceOfTypeUsingGenericTypeWithOutParameter_OnSameInstance_DoesNotThrow() { Assert.IsInstanceOfType(5, out int instance); - Verify(instance == 5); + instance.Should().Be(5); } public void IsInstanceOfTypeUsingGenericTypeWithOutParameter_OnSameInstanceReferenceType_DoesNotThrow() { object testInstance = new AssertTests(); Assert.IsInstanceOfType(testInstance, out AssertTests instance); - Verify(testInstance == instance); + testInstance.Should().BeSameAs(instance); } public void IsInstanceOfTypeUsingGenericType_OnHigherInstance_DoesNotThrow() => Assert.IsInstanceOfType(5); @@ -136,7 +154,7 @@ public void IsInstanceOfTypeUsingGenericTypeWithOutParameter_OnHigherInstance_Do { object testInstance = new AssertTests(); Assert.IsInstanceOfType(testInstance, out object instance); - Verify(instance == testInstance); + instance.Should().BeSameAs(testInstance); } public void IsNotInstanceOfTypeUsingGenericType_WhenValueIsNull_DoesNotThrow() => Assert.IsNotInstanceOfType(null); diff --git a/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.IsNull.cs b/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.IsNull.cs index 0063810a96..32582caaf5 100644 --- a/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.IsNull.cs +++ b/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.IsNull.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 AwesomeAssertions; + using TestFramework.ForTestingMSTest; namespace Microsoft.VisualStudio.TestPlatform.TestFramework.UnitTests; @@ -12,8 +14,9 @@ public void IsNull_PassNull_ShouldPass() public void IsNull_PassNonNull_ShouldFail() { - Exception ex = VerifyThrows(() => Assert.IsNull(new object())); - Verify(ex.Message == "Assert.IsNull failed. "); + Action action = () => Assert.IsNull(new object()); + action.Should().Throw() + .And.Message.Should().Be("Assert.IsNull failed. "); } public void IsNull_StringMessage_PassNull_ShouldPass() @@ -21,24 +24,26 @@ public void IsNull_StringMessage_PassNull_ShouldPass() public void IsNull_StringMessage_PassNonNull_ShouldFail() { - Exception ex = VerifyThrows(() => Assert.IsNull(new object(), "User-provided message")); - Verify(ex.Message == "Assert.IsNull failed. User-provided message"); + Action action = () => Assert.IsNull(new object(), "User-provided message"); + action.Should().Throw() + .And.Message.Should().Be("Assert.IsNull failed. User-provided message"); } public void IsNull_InterpolatedString_PassNull_ShouldPass() { DummyClassTrackingToStringCalls o = new(); Assert.IsNull(null, $"User-provided message {o}"); - Verify(!o.WasToStringCalled); + o.WasToStringCalled.Should().BeFalse(); } public async Task IsNull_InterpolatedString_PassNonNull_ShouldFail() { DummyClassTrackingToStringCalls o = new(); DateTime dateTime = DateTime.Now; - Exception ex = await VerifyThrowsAsync(async () => Assert.IsNull(new object(), $"User-provided message. {o}, {o,35}, {await GetHelloStringAsync()}, {new DummyIFormattable()}, {dateTime:tt}, {dateTime,5:tt}")); - Verify(ex.Message == $"Assert.IsNull failed. User-provided message. DummyClassTrackingToStringCalls, DummyClassTrackingToStringCalls, Hello, DummyIFormattable.ToString(), {string.Format(null, "{0:tt}", dateTime)}, {string.Format(null, "{0,5:tt}", dateTime)}"); - Verify(o.WasToStringCalled); + Func action = async () => Assert.IsNull(new object(), $"User-provided message. {o}, {o,35}, {await GetHelloStringAsync()}, {new DummyIFormattable()}, {dateTime:tt}, {dateTime,5:tt}"); + (await action.Should().ThrowAsync()) + .And.Message.Should().Be($"Assert.IsNull failed. User-provided message. DummyClassTrackingToStringCalls, DummyClassTrackingToStringCalls, Hello, DummyIFormattable.ToString(), {string.Format(null, "{0:tt}", dateTime)}, {string.Format(null, "{0,5:tt}", dateTime)}"); + o.WasToStringCalled.Should().BeTrue(); } public void IsNull_MessageFormat_PassNull_ShouldPass() @@ -46,8 +51,9 @@ public void IsNull_MessageFormat_PassNull_ShouldPass() public void IsNull_MessageFormat_PassNonNull_ShouldFail() { - Exception ex = VerifyThrows(() => Assert.IsNull(new object(), "User-provided message {0}", new object().GetType())); - Verify(ex.Message == "Assert.IsNull failed. User-provided message System.Object"); + Action action = () => Assert.IsNull(new object(), "User-provided message {0}", new object().GetType()); + action.Should().Throw().And + .Message.Should().Be("Assert.IsNull failed. User-provided message System.Object"); } public void IsNotNull_WhenNonNullNullableValue_DoesNotThrowAndLearnNotNull() @@ -69,7 +75,7 @@ public void IsNotNull_WhenNonNullNullableValueAndInterpolatedStringMessage_DoesN object? obj = GetObj(); DummyClassTrackingToStringCalls o = new(); Assert.IsNotNull(obj, $"my message {o}"); - Verify(!o.WasToStringCalled); + o.WasToStringCalled.Should().BeFalse(); _ = obj.ToString(); // No potential NRE warning } @@ -82,28 +88,32 @@ public void IsNotNull_WhenNonNullNullableValueAndCompositeMessage_DoesNotThrowAn public void IsNotNull_PassNull_ShouldFail() { - Exception ex = VerifyThrows(() => Assert.IsNotNull(null)); - Verify(ex.Message == "Assert.IsNotNull failed. "); + Action action = () => Assert.IsNotNull(null); + action.Should().Throw() + .And.Message.Should().Be("Assert.IsNotNull failed. "); } public void IsNotNull_StringMessage_PassNonNull_ShouldFail() { - Exception ex = VerifyThrows(() => Assert.IsNotNull(null, "User-provided message")); - Verify(ex.Message == "Assert.IsNotNull failed. User-provided message"); + Action action = () => Assert.IsNotNull(null, "User-provided message"); + action.Should().Throw() + .And.Message.Should().Be("Assert.IsNotNull failed. User-provided message"); } public async Task IsNotNull_InterpolatedString_PassNonNull_ShouldFail() { DummyClassTrackingToStringCalls o = new(); DateTime dateTime = DateTime.Now; - Exception ex = await VerifyThrowsAsync(async () => Assert.IsNotNull(null, $"User-provided message. {o}, {o,35}, {await GetHelloStringAsync()}, {new DummyIFormattable()}, {dateTime:tt}, {dateTime,5:tt}")); - Verify(ex.Message == $"Assert.IsNotNull failed. User-provided message. DummyClassTrackingToStringCalls, DummyClassTrackingToStringCalls, Hello, DummyIFormattable.ToString(), {string.Format(null, "{0:tt}", dateTime)}, {string.Format(null, "{0,5:tt}", dateTime)}"); - Verify(o.WasToStringCalled); + Func action = async () => Assert.IsNotNull(null, $"User-provided message. {o}, {o,35}, {await GetHelloStringAsync()}, {new DummyIFormattable()}, {dateTime:tt}, {dateTime,5:tt}"); + (await action.Should().ThrowAsync()) + .And.Message.Should().Be($"Assert.IsNotNull failed. User-provided message. DummyClassTrackingToStringCalls, DummyClassTrackingToStringCalls, Hello, DummyIFormattable.ToString(), {string.Format(null, "{0:tt}", dateTime)}, {string.Format(null, "{0,5:tt}", dateTime)}"); + o.WasToStringCalled.Should().BeTrue(); } public void IsNotNull_MessageFormat_PassNonNull_ShouldFail() { - Exception ex = VerifyThrows(() => Assert.IsNotNull(null, "User-provided message {0}", new object().GetType())); - Verify(ex.Message == "Assert.IsNotNull failed. User-provided message System.Object"); + Action action = () => Assert.IsNotNull(null, "User-provided message {0}", new object().GetType()); + action.Should().Throw().And + .Message.Should().Be("Assert.IsNotNull failed. User-provided message System.Object"); } } diff --git a/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.IsTrueTests.cs b/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.IsTrueTests.cs index dbc0444259..27bfc1eaaf 100644 --- a/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.IsTrueTests.cs +++ b/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.IsTrueTests.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 AwesomeAssertions; + namespace Microsoft.VisualStudio.TestPlatform.TestFramework.UnitTests; public partial class AssertTests @@ -8,15 +10,17 @@ public partial class AssertTests public void IsFalseNullableBooleanShouldFailWithNull() { bool? nullBool = null; - Exception ex = VerifyThrows(() => Assert.IsFalse(nullBool)); - Verify(ex.Message == "Assert.IsFalse failed. "); + Action action = () => Assert.IsFalse(nullBool); + action.Should().Throw() + .And.Message.Should().Be("Assert.IsFalse failed. "); } public void IsFalseNullableBooleanShouldFailWithTrue() { bool? nullBool = true; - Exception ex = VerifyThrows(() => Assert.IsFalse(nullBool)); - Verify(ex.Message == "Assert.IsFalse failed. "); + Action action = () => Assert.IsFalse(nullBool); + action.Should().Throw() + .And.Message.Should().Be("Assert.IsFalse failed. "); } public void IsFalseNullableBooleanShouldNotFailWithFalse() @@ -27,8 +31,9 @@ public void IsFalseNullableBooleanShouldNotFailWithFalse() public void IsFalseBooleanShouldFailWithTrue() { - Exception ex = VerifyThrows(() => Assert.IsFalse(true)); - Verify(ex.Message == "Assert.IsFalse failed. "); + Action action = () => Assert.IsFalse(true); + action.Should().Throw() + .And.Message.Should().Be("Assert.IsFalse failed. "); } public void IsFalseBooleanShouldNotFailWithFalse() @@ -37,15 +42,17 @@ public void IsFalseBooleanShouldNotFailWithFalse() public void IsFalseNullableBooleanStringMessageShouldFailWithNull() { bool? nullBool = null; - Exception ex = VerifyThrows(() => Assert.IsFalse(nullBool, "User-provided message")); - Verify(ex.Message == "Assert.IsFalse failed. User-provided message"); + Action action = () => Assert.IsFalse(nullBool, "User-provided message"); + action.Should().Throw() + .And.Message.Should().Be("Assert.IsFalse failed. User-provided message"); } public void IsFalseNullableBooleanStringMessageShouldFailWithTrue() { bool? nullBool = true; - Exception ex = VerifyThrows(() => Assert.IsFalse(nullBool, "User-provided message")); - Verify(ex.Message == "Assert.IsFalse failed. User-provided message"); + Action action = () => Assert.IsFalse(nullBool, "User-provided message"); + action.Should().Throw() + .And.Message.Should().Be("Assert.IsFalse failed. User-provided message"); } public void IsFalseNullableBooleanStringMessageShouldNotFailWithFalse() @@ -56,8 +63,9 @@ public void IsFalseNullableBooleanStringMessageShouldNotFailWithFalse() public void IsFalseBooleanStringMessageShouldFailWithTrue() { - Exception ex = VerifyThrows(() => Assert.IsFalse(true, "User-provided message")); - Verify(ex.Message == "Assert.IsFalse failed. User-provided message"); + Action action = () => Assert.IsFalse(true, "User-provided message"); + action.Should().Throw() + .And.Message.Should().Be("Assert.IsFalse failed. User-provided message"); } public void IsFalseBooleanStringMessageShouldNotFailWithFalse() @@ -68,8 +76,9 @@ public async Task IsFalseNullableBooleanInterpolatedStringMessageShouldFailWithN bool? nullBool = null; DummyClassTrackingToStringCalls o = new(); DateTime dateTime = DateTime.Now; - Exception ex = await VerifyThrowsAsync(async () => Assert.IsFalse(nullBool, $"User-provided message. {o}, {o,35}, {await GetHelloStringAsync()}, {new DummyIFormattable()}, {dateTime:tt}, {dateTime,5:tt}")); - Verify(ex.Message == $"Assert.IsFalse failed. User-provided message. DummyClassTrackingToStringCalls, DummyClassTrackingToStringCalls, Hello, DummyIFormattable.ToString(), {string.Format(null, "{0:tt}", dateTime)}, {string.Format(null, "{0,5:tt}", dateTime)}"); + Func action = async () => Assert.IsFalse(nullBool, $"User-provided message. {o}, {o,35}, {await GetHelloStringAsync()}, {new DummyIFormattable()}, {dateTime:tt}, {dateTime,5:tt}"); + (await action.Should().ThrowAsync()) + .And.Message.Should().Be($"Assert.IsFalse failed. User-provided message. DummyClassTrackingToStringCalls, DummyClassTrackingToStringCalls, Hello, DummyIFormattable.ToString(), {string.Format(null, "{0:tt}", dateTime)}, {string.Format(null, "{0,5:tt}", dateTime)}"); } public async Task IsFalseNullableBooleanInterpolatedStringMessageShouldFailWithTrue() @@ -77,8 +86,9 @@ public async Task IsFalseNullableBooleanInterpolatedStringMessageShouldFailWithT bool? nullBool = true; DummyClassTrackingToStringCalls o = new(); DateTime dateTime = DateTime.Now; - Exception ex = await VerifyThrowsAsync(async () => Assert.IsFalse(nullBool, $"User-provided message. {o}, {o,35}, {await GetHelloStringAsync()}, {new DummyIFormattable()}, {dateTime:tt}, {dateTime,5:tt}")); - Verify(ex.Message == $"Assert.IsFalse failed. User-provided message. DummyClassTrackingToStringCalls, DummyClassTrackingToStringCalls, Hello, DummyIFormattable.ToString(), {string.Format(null, "{0:tt}", dateTime)}, {string.Format(null, "{0,5:tt}", dateTime)}"); + Func action = async () => Assert.IsFalse(nullBool, $"User-provided message. {o}, {o,35}, {await GetHelloStringAsync()}, {new DummyIFormattable()}, {dateTime:tt}, {dateTime,5:tt}"); + (await action.Should().ThrowAsync()) + .And.Message.Should().Be($"Assert.IsFalse failed. User-provided message. DummyClassTrackingToStringCalls, DummyClassTrackingToStringCalls, Hello, DummyIFormattable.ToString(), {string.Format(null, "{0:tt}", dateTime)}, {string.Format(null, "{0,5:tt}", dateTime)}"); } public void IsFalseNullableBooleanInterpolatedStringMessageShouldNotFailWithFalse() @@ -91,8 +101,9 @@ public async Task IsFalseBooleanInterpolatedStringMessageShouldFailWithTrue() { DummyClassTrackingToStringCalls o = new(); DateTime dateTime = DateTime.Now; - Exception ex = await VerifyThrowsAsync(async () => Assert.IsFalse(true, $"User-provided message. {o}, {o,35}, {await GetHelloStringAsync()}, {new DummyIFormattable()}, {dateTime:tt}, {dateTime,5:tt}")); - Verify(ex.Message == $"Assert.IsFalse failed. User-provided message. DummyClassTrackingToStringCalls, DummyClassTrackingToStringCalls, Hello, DummyIFormattable.ToString(), {string.Format(null, "{0:tt}", dateTime)}, {string.Format(null, "{0,5:tt}", dateTime)}"); + Func action = async () => Assert.IsFalse(true, $"User-provided message. {o}, {o,35}, {await GetHelloStringAsync()}, {new DummyIFormattable()}, {dateTime:tt}, {dateTime,5:tt}"); + (await action.Should().ThrowAsync()) + .And.Message.Should().Be($"Assert.IsFalse failed. User-provided message. DummyClassTrackingToStringCalls, DummyClassTrackingToStringCalls, Hello, DummyIFormattable.ToString(), {string.Format(null, "{0:tt}", dateTime)}, {string.Format(null, "{0,5:tt}", dateTime)}"); } public void IsFalseBooleanInterpolatedStringMessageShouldNotFailWithFalse() @@ -101,15 +112,17 @@ public void IsFalseBooleanInterpolatedStringMessageShouldNotFailWithFalse() public void IsFalseNullableBooleanMessageArgsShouldFailWithNull() { bool? nullBool = null; - Exception ex = VerifyThrows(() => Assert.IsFalse(nullBool, "User-provided message. Input: {0}", nullBool)); - Verify(ex.Message == "Assert.IsFalse failed. User-provided message. Input: "); + Action action = () => Assert.IsFalse(nullBool, "User-provided message. Input: {0}", nullBool); + action.Should().Throw() + .And.Message.Should().Be("Assert.IsFalse failed. User-provided message. Input: "); } public void IsFalseNullableBooleanMessageArgsShouldFailWithTrue() { bool? nullBool = true; - Exception ex = VerifyThrows(() => Assert.IsFalse(nullBool, "User-provided message. Input: {0}", nullBool)); - Verify(ex.Message == "Assert.IsFalse failed. User-provided message. Input: True"); + Action action = () => Assert.IsFalse(nullBool, "User-provided message. Input: {0}", nullBool); + action.Should().Throw() + .And.Message.Should().Be("Assert.IsFalse failed. User-provided message. Input: True"); } public void IsFalseNullableBooleanMessageArgsShouldNotFailWithFalse() @@ -120,8 +133,9 @@ public void IsFalseNullableBooleanMessageArgsShouldNotFailWithFalse() public void IsFalseBooleanMessageArgsShouldFailWithTrue() { - Exception ex = VerifyThrows(() => Assert.IsFalse(true, "User-provided message. Input: {0}", true)); - Verify(ex.Message == "Assert.IsFalse failed. User-provided message. Input: True"); + Action action = () => Assert.IsFalse(true, "User-provided message. Input: {0}", true); + action.Should().Throw() + .And.Message.Should().Be("Assert.IsFalse failed. User-provided message. Input: True"); } public void IsFalseBooleanMessageArgsShouldNotFailWithFalse() @@ -130,15 +144,17 @@ public void IsFalseBooleanMessageArgsShouldNotFailWithFalse() public void IsTrueNullableBooleanShouldFailWithNull() { bool? nullBool = null; - Exception ex = VerifyThrows(() => Assert.IsTrue(nullBool)); - Verify(ex.Message == "Assert.IsTrue failed. "); + Action action = () => Assert.IsTrue(nullBool); + action.Should().Throw() + .And.Message.Should().Be("Assert.IsTrue failed. "); } public void IsTrueNullableBooleanShouldFailWithFalse() { bool? nullBool = false; - Exception ex = VerifyThrows(() => Assert.IsTrue(nullBool)); - Verify(ex.Message == "Assert.IsTrue failed. "); + Action action = () => Assert.IsTrue(nullBool); + action.Should().Throw() + .And.Message.Should().Be("Assert.IsTrue failed. "); } public void IsTrueNullableBooleanShouldNotFailWithTrue() @@ -149,8 +165,9 @@ public void IsTrueNullableBooleanShouldNotFailWithTrue() public void IsTrueBooleanShouldFailWithFalse() { - Exception ex = VerifyThrows(() => Assert.IsTrue(false)); - Verify(ex.Message == "Assert.IsTrue failed. "); + Action action = () => Assert.IsTrue(false); + action.Should().Throw() + .And.Message.Should().Be("Assert.IsTrue failed. "); } public void IsTrueBooleanShouldNotFailWithTrue() @@ -159,15 +176,17 @@ public void IsTrueBooleanShouldNotFailWithTrue() public void IsTrueNullableBooleanStringMessageShouldFailWithNull() { bool? nullBool = null; - Exception ex = VerifyThrows(() => Assert.IsTrue(nullBool, "User-provided message")); - Verify(ex.Message == "Assert.IsTrue failed. User-provided message"); + Action action = () => Assert.IsTrue(nullBool, "User-provided message"); + action.Should().Throw() + .And.Message.Should().Be("Assert.IsTrue failed. User-provided message"); } public void IsTrueNullableBooleanStringMessageShouldFailWithFalse() { bool? nullBool = false; - Exception ex = VerifyThrows(() => Assert.IsTrue(nullBool, "User-provided message")); - Verify(ex.Message == "Assert.IsTrue failed. User-provided message"); + Action action = () => Assert.IsTrue(nullBool, "User-provided message"); + action.Should().Throw() + .And.Message.Should().Be("Assert.IsTrue failed. User-provided message"); } public void IsTrueNullableBooleanStringMessageShouldNotFailWithTrue() @@ -178,8 +197,9 @@ public void IsTrueNullableBooleanStringMessageShouldNotFailWithTrue() public void IsTrueBooleanStringMessageShouldFailWithFalse() { - Exception ex = VerifyThrows(() => Assert.IsTrue(false, "User-provided message")); - Verify(ex.Message == "Assert.IsTrue failed. User-provided message"); + Action action = () => Assert.IsTrue(false, "User-provided message"); + action.Should().Throw() + .And.Message.Should().Be("Assert.IsTrue failed. User-provided message"); } public void IsTrueBooleanStringMessageShouldNotFailWithTrue() @@ -190,8 +210,9 @@ public async Task IsTrueNullableBooleanInterpolatedStringMessageShouldFailWithNu bool? nullBool = null; DummyClassTrackingToStringCalls o = new(); DateTime dateTime = DateTime.Now; - Exception ex = await VerifyThrowsAsync(async () => Assert.IsTrue(nullBool, $"User-provided message. {o}, {o,35}, {await GetHelloStringAsync()}, {new DummyIFormattable()}, {dateTime:tt}, {dateTime,5:tt}")); - Verify(ex.Message == $"Assert.IsTrue failed. User-provided message. DummyClassTrackingToStringCalls, DummyClassTrackingToStringCalls, Hello, DummyIFormattable.ToString(), {string.Format(null, "{0:tt}", dateTime)}, {string.Format(null, "{0,5:tt}", dateTime)}"); + Func action = async () => Assert.IsTrue(nullBool, $"User-provided message. {o}, {o,35}, {await GetHelloStringAsync()}, {new DummyIFormattable()}, {dateTime:tt}, {dateTime,5:tt}"); + (await action.Should().ThrowAsync()) + .And.Message.Should().Be($"Assert.IsTrue failed. User-provided message. DummyClassTrackingToStringCalls, DummyClassTrackingToStringCalls, Hello, DummyIFormattable.ToString(), {string.Format(null, "{0:tt}", dateTime)}, {string.Format(null, "{0,5:tt}", dateTime)}"); } public async Task IsTrueNullableBooleanInterpolatedStringMessageShouldFailWithFalse() @@ -199,8 +220,9 @@ public async Task IsTrueNullableBooleanInterpolatedStringMessageShouldFailWithFa bool? nullBool = false; DummyClassTrackingToStringCalls o = new(); DateTime dateTime = DateTime.Now; - Exception ex = await VerifyThrowsAsync(async () => Assert.IsTrue(nullBool, $"User-provided message. {o}, {o,35}, {await GetHelloStringAsync()}, {new DummyIFormattable()}, {dateTime:tt}, {dateTime,5:tt}")); - Verify(ex.Message == $"Assert.IsTrue failed. User-provided message. DummyClassTrackingToStringCalls, DummyClassTrackingToStringCalls, Hello, DummyIFormattable.ToString(), {string.Format(null, "{0:tt}", dateTime)}, {string.Format(null, "{0,5:tt}", dateTime)}"); + Func action = async () => Assert.IsTrue(nullBool, $"User-provided message. {o}, {o,35}, {await GetHelloStringAsync()}, {new DummyIFormattable()}, {dateTime:tt}, {dateTime,5:tt}"); + (await action.Should().ThrowAsync()) + .And.Message.Should().Be($"Assert.IsTrue failed. User-provided message. DummyClassTrackingToStringCalls, DummyClassTrackingToStringCalls, Hello, DummyIFormattable.ToString(), {string.Format(null, "{0:tt}", dateTime)}, {string.Format(null, "{0,5:tt}", dateTime)}"); } public void IsTrueNullableBooleanInterpolatedStringMessageShouldNotFailWithTrue() @@ -213,8 +235,9 @@ public async Task IsTrueBooleanInterpolatedStringMessageShouldFailWithFalse() { DummyClassTrackingToStringCalls o = new(); DateTime dateTime = DateTime.Now; - Exception ex = await VerifyThrowsAsync(async () => Assert.IsTrue(false, $"User-provided message. {o}, {o,35}, {await GetHelloStringAsync()}, {new DummyIFormattable()}, {dateTime:tt}, {dateTime,5:tt}")); - Verify(ex.Message == $"Assert.IsTrue failed. User-provided message. DummyClassTrackingToStringCalls, DummyClassTrackingToStringCalls, Hello, DummyIFormattable.ToString(), {string.Format(null, "{0:tt}", dateTime)}, {string.Format(null, "{0,5:tt}", dateTime)}"); + Func action = async () => Assert.IsTrue(false, $"User-provided message. {o}, {o,35}, {await GetHelloStringAsync()}, {new DummyIFormattable()}, {dateTime:tt}, {dateTime,5:tt}"); + (await action.Should().ThrowAsync()) + .And.Message.Should().Be($"Assert.IsTrue failed. User-provided message. DummyClassTrackingToStringCalls, DummyClassTrackingToStringCalls, Hello, DummyIFormattable.ToString(), {string.Format(null, "{0:tt}", dateTime)}, {string.Format(null, "{0,5:tt}", dateTime)}"); } public void IsTrueBooleanInterpolatedStringMessageShouldNotFailWithTrue() @@ -223,15 +246,17 @@ public void IsTrueBooleanInterpolatedStringMessageShouldNotFailWithTrue() public void IsTrueNullableBooleanMessageArgsShouldFailWithNull() { bool? nullBool = null; - Exception ex = VerifyThrows(() => Assert.IsTrue(nullBool, "User-provided message. Input: {0}", nullBool)); - Verify(ex.Message == "Assert.IsTrue failed. User-provided message. Input: "); + Action action = () => Assert.IsTrue(nullBool, "User-provided message. Input: {0}", nullBool); + action.Should().Throw() + .And.Message.Should().Be("Assert.IsTrue failed. User-provided message. Input: "); } public void IsTrueNullableBooleanMessageArgsShouldFailWithFalse() { bool? nullBool = false; - Exception ex = VerifyThrows(() => Assert.IsTrue(nullBool, "User-provided message. Input: {0}", nullBool)); - Verify(ex.Message == "Assert.IsTrue failed. User-provided message. Input: False"); + Action action = () => Assert.IsTrue(nullBool, "User-provided message. Input: {0}", nullBool); + action.Should().Throw() + .And.Message.Should().Be("Assert.IsTrue failed. User-provided message. Input: False"); } public void IsTrueNullableBooleanMessageArgsShouldNotFailWithTrue() @@ -242,8 +267,9 @@ public void IsTrueNullableBooleanMessageArgsShouldNotFailWithTrue() public void IsTrueBooleanMessageArgsShouldFailWithFalse() { - Exception ex = VerifyThrows(() => Assert.IsTrue(false, "User-provided message. Input: {0}", false)); - Verify(ex.Message == "Assert.IsTrue failed. User-provided message. Input: False"); + Action action = () => Assert.IsTrue(false, "User-provided message. Input: {0}", false); + action.Should().Throw() + .And.Message.Should().Be("Assert.IsTrue failed. User-provided message. Input: False"); } public void IsTrueBooleanMessageArgsShouldNotFailWithTrue() diff --git a/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.Items.cs b/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.Items.cs index 46dba4d95f..4bd5b6f912 100644 --- a/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.Items.cs +++ b/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.Items.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 AwesomeAssertions; + namespace Microsoft.VisualStudio.TestPlatform.TestFramework.UnitTests; public partial class AssertTests @@ -15,29 +17,32 @@ public void Count_InterpolatedString_WhenCountIsSame_ShouldPass() { DummyClassTrackingToStringCalls o = new(); Assert.HasCount(0, Array.Empty(), $"User-provided message: {o}"); - Verify(!o.WasToStringCalled); + o.WasToStringCalled.Should().BeFalse(); } public void Count_WhenCountIsNotSame_ShouldFail() { var collection = new List { 1 }; - Exception ex = VerifyThrows(() => Assert.HasCount(3, collection)); - Verify(ex.Message == "Assert.HasCount failed. Expected collection of size 3. Actual: 1. "); + Action action = () => Assert.HasCount(3, collection); + action.Should().Throw().And + .Message.Should().Be("Assert.HasCount failed. Expected collection of size 3. Actual: 1. "); } public void Count_MessageArgs_WhenCountIsNotSame_ShouldFail() { - Exception ex = VerifyThrows(() => Assert.HasCount(1, Array.Empty(), "User-provided message: System.Object type: {0}", new object().GetType())); - Verify(ex.Message == "Assert.HasCount failed. Expected collection of size 1. Actual: 0. User-provided message: System.Object type: System.Object"); + Action action = () => Assert.HasCount(1, Array.Empty(), "User-provided message: System.Object type: {0}", new object().GetType()); + action.Should().Throw().And + .Message.Should().Be("Assert.HasCount failed. Expected collection of size 1. Actual: 0. User-provided message: System.Object type: System.Object"); } public async Task Count_InterpolatedString_WhenCountIsNotSame_ShouldFail() { DummyClassTrackingToStringCalls o = new(); DateTime dateTime = DateTime.Now; - Exception ex = await VerifyThrowsAsync(async () => Assert.HasCount(1, Array.Empty(), $"User-provided message. {o}, {o,35}, {await GetHelloStringAsync()}, {new DummyIFormattable()}, {dateTime:tt}, {dateTime,5:tt}")); - Verify(ex.Message == $"Assert.HasCount failed. Expected collection of size 1. Actual: 0. User-provided message. DummyClassTrackingToStringCalls, DummyClassTrackingToStringCalls, Hello, DummyIFormattable.ToString(), {string.Format(null, "{0:tt}", dateTime)}, {string.Format(null, "{0,5:tt}", dateTime)}"); - Verify(o.WasToStringCalled); + Func action = async () => Assert.HasCount(1, Array.Empty(), $"User-provided message. {o}, {o,35}, {await GetHelloStringAsync()}, {new DummyIFormattable()}, {dateTime:tt}, {dateTime,5:tt}"); + (await action.Should().ThrowAsync()).And + .Message.Should().Be($"Assert.HasCount failed. Expected collection of size 1. Actual: 0. User-provided message. DummyClassTrackingToStringCalls, DummyClassTrackingToStringCalls, Hello, DummyIFormattable.ToString(), {string.Format(null, "{0:tt}", dateTime)}, {string.Format(null, "{0,5:tt}", dateTime)}"); + o.WasToStringCalled.Should().BeTrue(); } public void NotAny_WhenEmpty_ShouldPass() @@ -47,21 +52,23 @@ public void NotAny_InterpolatedString_WhenEmpty_ShouldPass() { DummyClassTrackingToStringCalls o = new(); Assert.IsEmpty(Array.Empty(), $"User-provided message: {o}"); - Verify(!o.WasToStringCalled); + o.WasToStringCalled.Should().BeFalse(); } public void NotAny_WhenNotEmpty_ShouldFail() { var collection = new List { 1 }; - Exception ex = VerifyThrows(() => Assert.IsEmpty(collection)); - Verify(ex.Message == "Assert.IsEmpty failed. Expected collection of size 0. Actual: 1. "); + Action action = () => Assert.IsEmpty(collection); + action.Should().Throw().And + .Message.Should().Be("Assert.IsEmpty failed. Expected collection of size 0. Actual: 1. "); } public void NotAny_MessageArgs_WhenNotEmpty_ShouldFail() { var collection = new List { 1 }; - Exception ex = VerifyThrows(() => Assert.IsEmpty(collection, "User-provided message: System.Object type: {0}", new object().GetType())); - Verify(ex.Message == "Assert.IsEmpty failed. Expected collection of size 0. Actual: 1. User-provided message: System.Object type: System.Object"); + Action action = () => Assert.IsEmpty(collection, "User-provided message: System.Object type: {0}", new object().GetType()); + action.Should().Throw().And + .Message.Should().Be("Assert.IsEmpty failed. Expected collection of size 0. Actual: 1. User-provided message: System.Object type: System.Object"); } public async Task NotAny_InterpolatedString_WhenNotEmpty_ShouldFail() @@ -69,16 +76,17 @@ public async Task NotAny_InterpolatedString_WhenNotEmpty_ShouldFail() var collection = new List { 1 }; DummyClassTrackingToStringCalls o = new(); DateTime dateTime = DateTime.Now; - Exception ex = await VerifyThrowsAsync(async () => Assert.IsEmpty(collection, $"User-provided message. {o}, {o,35}, {await GetHelloStringAsync()}, {new DummyIFormattable()}, {dateTime:tt}, {dateTime,5:tt}")); - Verify(ex.Message == $"Assert.IsEmpty failed. Expected collection of size 0. Actual: 1. User-provided message. DummyClassTrackingToStringCalls, DummyClassTrackingToStringCalls, Hello, DummyIFormattable.ToString(), {string.Format(null, "{0:tt}", dateTime)}, {string.Format(null, "{0,5:tt}", dateTime)}"); - Verify(o.WasToStringCalled); + Func action = async () => Assert.IsEmpty(collection, $"User-provided message. {o}, {o,35}, {await GetHelloStringAsync()}, {new DummyIFormattable()}, {dateTime:tt}, {dateTime,5:tt}"); + (await action.Should().ThrowAsync()).And + .Message.Should().Be($"Assert.IsEmpty failed. Expected collection of size 0. Actual: 1. User-provided message. DummyClassTrackingToStringCalls, DummyClassTrackingToStringCalls, Hello, DummyIFormattable.ToString(), {string.Format(null, "{0:tt}", dateTime)}, {string.Format(null, "{0,5:tt}", dateTime)}"); + o.WasToStringCalled.Should().BeTrue(); } public void Single_WhenOneItem_ShouldPass() { var collection = new List { 1 }; int first = Assert.ContainsSingle(collection); - Verify(first == 1); + (first == 1).Should().BeTrue(); } public void Single_InterpolatedString_WhenOneItem_ShouldPass() @@ -86,56 +94,62 @@ public void Single_InterpolatedString_WhenOneItem_ShouldPass() var collection = new List { 1 }; DummyClassTrackingToStringCalls o = new(); Assert.ContainsSingle(collection, $"User-provided message: {o}"); - Verify(!o.WasToStringCalled); + o.WasToStringCalled.Should().BeFalse(); } public void Single_WhenNoItems_ShouldFail() { - Exception ex = VerifyThrows(() => Assert.ContainsSingle(Array.Empty())); - Verify(ex.Message == "Assert.ContainsSingle failed. Expected collection to contain exactly one element but found 0 element(s). "); + Action action = () => Assert.ContainsSingle(Array.Empty()); + action.Should().Throw().And + .Message.Should().Be("Assert.ContainsSingle failed. Expected collection to contain exactly one element but found 0 element(s). "); } public void Single_WhenMultipleItems_ShouldFail() { - Exception ex = VerifyThrows(() => Assert.ContainsSingle([1, 2, 3])); - Verify(ex.Message == "Assert.ContainsSingle failed. Expected collection to contain exactly one element but found 3 element(s). "); + Action action = () => Assert.ContainsSingle([1, 2, 3]); + action.Should().Throw().And + .Message.Should().Be("Assert.ContainsSingle failed. Expected collection to contain exactly one element but found 3 element(s). "); } public void Single_MessageArgs_WhenNoItem_ShouldFail() { - Exception ex = VerifyThrows(() => Assert.ContainsSingle(Array.Empty(), "User-provided message: System.Object type: {0}", new object().GetType())); - Verify(ex.Message == "Assert.ContainsSingle failed. Expected collection to contain exactly one element but found 0 element(s). User-provided message: System.Object type: System.Object"); + Action action = () => Assert.ContainsSingle(Array.Empty(), "User-provided message: System.Object type: {0}", new object().GetType()); + action.Should().Throw().And + .Message.Should().Be("Assert.ContainsSingle failed. Expected collection to contain exactly one element but found 0 element(s). User-provided message: System.Object type: System.Object"); } public void Single_MessageArgs_WhenMultipleItems_ShouldFail() { - Exception ex = VerifyThrows(() => Assert.ContainsSingle([1, 2, 3], "User-provided message: System.Object type: {0}", new object().GetType())); - Verify(ex.Message == "Assert.ContainsSingle failed. Expected collection to contain exactly one element but found 3 element(s). User-provided message: System.Object type: System.Object"); + Action action = () => Assert.ContainsSingle([1, 2, 3], "User-provided message: System.Object type: {0}", new object().GetType()); + action.Should().Throw().And + .Message.Should().Be("Assert.ContainsSingle failed. Expected collection to contain exactly one element but found 3 element(s). User-provided message: System.Object type: System.Object"); } public async Task Single_InterpolatedString_WhenNoItem_ShouldFail() { DummyClassTrackingToStringCalls o = new(); DateTime dateTime = DateTime.Now; - Exception ex = await VerifyThrowsAsync(async () => Assert.ContainsSingle(Array.Empty(), $"User-provided message. {o}, {o,35}, {await GetHelloStringAsync()}, {new DummyIFormattable()}, {dateTime:tt}, {dateTime,5:tt}")); - Verify(ex.Message == $"Assert.ContainsSingle failed. Expected collection to contain exactly one element but found 0 element(s). User-provided message. DummyClassTrackingToStringCalls, DummyClassTrackingToStringCalls, Hello, DummyIFormattable.ToString(), {string.Format(null, "{0:tt}", dateTime)}, {string.Format(null, "{0,5:tt}", dateTime)}"); - Verify(o.WasToStringCalled); + Func action = async () => Assert.ContainsSingle(Array.Empty(), $"User-provided message. {o}, {o,35}, {await GetHelloStringAsync()}, {new DummyIFormattable()}, {dateTime:tt}, {dateTime,5:tt}"); + (await action.Should().ThrowAsync()).And + .Message.Should().Be($"Assert.ContainsSingle failed. Expected collection to contain exactly one element but found 0 element(s). User-provided message. DummyClassTrackingToStringCalls, DummyClassTrackingToStringCalls, Hello, DummyIFormattable.ToString(), {string.Format(null, "{0:tt}", dateTime)}, {string.Format(null, "{0,5:tt}", dateTime)}"); + o.WasToStringCalled.Should().BeTrue(); } public async Task Single_InterpolatedString_WhenMultipleItems_ShouldFail() { DummyClassTrackingToStringCalls o = new(); DateTime dateTime = DateTime.Now; - Exception ex = await VerifyThrowsAsync(async () => Assert.ContainsSingle([1, 2, 3], $"User-provided message. {o}, {o,35}, {await GetHelloStringAsync()}, {new DummyIFormattable()}, {dateTime:tt}, {dateTime,5:tt}")); - Verify(ex.Message == $"Assert.ContainsSingle failed. Expected collection to contain exactly one element but found 3 element(s). User-provided message. DummyClassTrackingToStringCalls, DummyClassTrackingToStringCalls, Hello, DummyIFormattable.ToString(), {string.Format(null, "{0:tt}", dateTime)}, {string.Format(null, "{0,5:tt}", dateTime)}"); - Verify(o.WasToStringCalled); + Func action = async () => Assert.ContainsSingle([1, 2, 3], $"User-provided message. {o}, {o,35}, {await GetHelloStringAsync()}, {new DummyIFormattable()}, {dateTime:tt}, {dateTime,5:tt}"); + (await action.Should().ThrowAsync()).And + .Message.Should().Be($"Assert.ContainsSingle failed. Expected collection to contain exactly one element but found 3 element(s). User-provided message. DummyClassTrackingToStringCalls, DummyClassTrackingToStringCalls, Hello, DummyIFormattable.ToString(), {string.Format(null, "{0:tt}", dateTime)}, {string.Format(null, "{0,5:tt}", dateTime)}"); + o.WasToStringCalled.Should().BeTrue(); } public void SinglePredicate_WhenOneItemMatches_ShouldPass() { var collection = new List { 1, 3, 5 }; int result = Assert.ContainsSingle(x => x == 3, collection); - Verify(result == 3); + result.Should().Be(3); } public void SinglePredicate_WithMessage_WhenOneItemMatches_ShouldPass() @@ -144,35 +158,39 @@ public void SinglePredicate_WithMessage_WhenOneItemMatches_ShouldPass() #pragma warning disable CA1865 // Use char overload - not netfx string result = Assert.ContainsSingle(x => x.StartsWith("b", StringComparison.Ordinal), collection, "Expected one item starting with 'b'"); #pragma warning restore CA1865 - Verify(result == "banana"); + result.Should().Be("banana"); } public void SinglePredicate_WhenNoItemMatches_ShouldFail() { var collection = new List { 1, 3, 5 }; - Exception ex = VerifyThrows(() => Assert.ContainsSingle(x => x % 2 == 0, collection)); - Verify(ex.Message == "Assert.ContainsSingle failed. Expected exactly one item to match the predicate but found 0 item(s). "); + Action action = () => Assert.ContainsSingle(x => x % 2 == 0, collection); + action.Should().Throw().And + .Message.Should().Be("Assert.ContainsSingle failed. Expected exactly one item to match the predicate but found 0 item(s). "); } public void SinglePredicate_WhenMultipleItemsMatch_ShouldFail() { var collection = new List { 2, 4, 6 }; - Exception ex = VerifyThrows(() => Assert.ContainsSingle(x => x % 2 == 0, collection)); - Verify(ex.Message == "Assert.ContainsSingle failed. Expected exactly one item to match the predicate but found 3 item(s). "); + Action action = () => Assert.ContainsSingle(x => x % 2 == 0, collection); + action.Should().Throw().And + .Message.Should().Be("Assert.ContainsSingle failed. Expected exactly one item to match the predicate but found 3 item(s). "); } public void SinglePredicate_Message_WhenNoItemMatches_ShouldFail() { var collection = new List { 1, 3, 5 }; - Exception ex = VerifyThrows(() => Assert.ContainsSingle(x => x % 2 == 0, collection, "No even numbers found: test")); - Verify(ex.Message == "Assert.ContainsSingle failed. Expected exactly one item to match the predicate but found 0 item(s). No even numbers found: test"); + Action action = () => Assert.ContainsSingle(x => x % 2 == 0, collection, "No even numbers found: test"); + action.Should().Throw().And + .Message.Should().Be("Assert.ContainsSingle failed. Expected exactly one item to match the predicate but found 0 item(s). No even numbers found: test"); } public void SinglePredicate_Message_WhenMultipleItemsMatch_ShouldFail() { var collection = new List { 2, 4, 6 }; - Exception ex = VerifyThrows(() => Assert.ContainsSingle(x => x % 2 == 0, collection, "Too many even numbers: test")); - Verify(ex.Message == "Assert.ContainsSingle failed. Expected exactly one item to match the predicate but found 3 item(s). Too many even numbers: test"); + Action action = () => Assert.ContainsSingle(x => x % 2 == 0, collection, "Too many even numbers: test"); + action.Should().Throw().And + .Message.Should().Be("Assert.ContainsSingle failed. Expected exactly one item to match the predicate but found 3 item(s). Too many even numbers: test"); } public void Any_WhenOneItem_ShouldPass() @@ -191,34 +209,37 @@ public void Any_InterpolatedString_WhenAnyOneItem_ShouldPass() { DummyClassTrackingToStringCalls o = new(); Assert.IsNotEmpty([1], $"User-provided message: {o}"); - Verify(!o.WasToStringCalled); + o.WasToStringCalled.Should().BeFalse(); } public void Any_InterpolatedString_WhenMultipleItems_ShouldPass() { DummyClassTrackingToStringCalls o = new(); Assert.IsNotEmpty([1, 2, 3], $"User-provided message: {o}"); - Verify(!o.WasToStringCalled); + o.WasToStringCalled.Should().BeFalse(); } public void Any_WhenNoItem_ShouldFail() { - Exception ex = VerifyThrows(() => Assert.IsNotEmpty(Array.Empty())); - Verify(ex.Message == "Assert.IsNotEmpty failed. Expected collection to contain any item but it is empty. "); + Action action = () => Assert.IsNotEmpty(Array.Empty()); + action.Should().Throw().And + .Message.Should().Be("Assert.IsNotEmpty failed. Expected collection to contain any item but it is empty. "); } public void Any_MessageArgs_WhenNoItem_ShouldFail() { - Exception ex = VerifyThrows(() => Assert.IsNotEmpty(Array.Empty(), "User-provided message: System.Object type: {0}", new object().GetType())); - Verify(ex.Message == "Assert.IsNotEmpty failed. Expected collection to contain any item but it is empty. User-provided message: System.Object type: System.Object"); + Action action = () => Assert.IsNotEmpty(Array.Empty(), "User-provided message: System.Object type: {0}", new object().GetType()); + action.Should().Throw().And + .Message.Should().Be("Assert.IsNotEmpty failed. Expected collection to contain any item but it is empty. User-provided message: System.Object type: System.Object"); } public async Task Any_InterpolatedString_WhenNoItem_ShouldFail() { DummyClassTrackingToStringCalls o = new(); DateTime dateTime = DateTime.Now; - Exception ex = await VerifyThrowsAsync(async () => Assert.IsNotEmpty(Array.Empty(), $"User-provided message. {o}, {o,35}, {await GetHelloStringAsync()}, {new DummyIFormattable()}, {dateTime:tt}, {dateTime,5:tt}")); - Verify(ex.Message == $"Assert.IsNotEmpty failed. Expected collection to contain any item but it is empty. User-provided message. DummyClassTrackingToStringCalls, DummyClassTrackingToStringCalls, Hello, DummyIFormattable.ToString(), {string.Format(null, "{0:tt}", dateTime)}, {string.Format(null, "{0,5:tt}", dateTime)}"); - Verify(o.WasToStringCalled); + Func action = async () => Assert.IsNotEmpty(Array.Empty(), $"User-provided message. {o}, {o,35}, {await GetHelloStringAsync()}, {new DummyIFormattable()}, {dateTime:tt}, {dateTime,5:tt}"); + (await action.Should().ThrowAsync()).And + .Message.Should().Be($"Assert.IsNotEmpty failed. Expected collection to contain any item but it is empty. User-provided message. DummyClassTrackingToStringCalls, DummyClassTrackingToStringCalls, Hello, DummyIFormattable.ToString(), {string.Format(null, "{0:tt}", dateTime)}, {string.Format(null, "{0,5:tt}", dateTime)}"); + o.WasToStringCalled.Should().BeTrue(); } } diff --git a/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.ThrowsExceptionTests.cs b/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.ThrowsExceptionTests.cs index 6ce17da296..cdbc092f5e 100644 --- a/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.ThrowsExceptionTests.cs +++ b/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.ThrowsExceptionTests.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 AwesomeAssertions; + namespace Microsoft.VisualStudio.TestPlatform.TestFramework.UnitTests; public partial class AssertTests @@ -9,40 +11,46 @@ public partial class AssertTests // See https://github.com/dotnet/sdk/issues/25373 public void ThrowAssertFailedDoesNotThrowIfMessageContainsInvalidStringFormatComposite() { - Exception ex = VerifyThrows(() => Assert.ThrowAssertFailed("name", "{")); - Verify(ex.Message.Contains("name failed. {")); + Action action = () => Assert.ThrowAssertFailed("name", "{"); + action.Should().Throw() + .And.Message.Should().Contain("name failed. {"); } #endregion #region ThrowsException tests public void ThrowsExceptionWithLambdaExpressionsShouldThrowAssertionOnNoException() { - Exception ex = VerifyThrows(() => Assert.ThrowsException(() => { })); - Verify(ex.Message.Equals("Assert.ThrowsException failed. Expected exception type: but no exception was thrown. ", StringComparison.Ordinal)); + Action action = () => Assert.ThrowsException(() => { }); + action.Should().Throw() + .And.Message.Should().Be("Assert.ThrowsException failed. Expected exception type: but no exception was thrown. "); } public void ThrowsExceptionWithLambdaExpressionsShouldThrowAssertionOnWrongException() { - Exception ex = VerifyThrows(() => Assert.ThrowsException(() => throw new FormatException())); - Verify(ex.Message.Equals("Assert.ThrowsException failed. Expected exception type:. Actual exception type:. ", StringComparison.Ordinal)); + Action action = () => Assert.ThrowsException(() => throw new FormatException()); + action.Should().Throw() + .And.Message.Should().Be("Assert.ThrowsException failed. Expected exception type:. Actual exception type:. "); } public void ThrowsException_FuncArgument_AllowsToReturnNull() { - Exception ex = VerifyThrows(() => Assert.ThrowsException(() => null)); - Verify(ex.Message.Equals("Assert.ThrowsException failed. Expected exception type: but no exception was thrown. ", StringComparison.Ordinal)); + Action action = () => Assert.ThrowsException(() => null); + action.Should().Throw() + .And.Message.Should().Be("Assert.ThrowsException failed. Expected exception type: but no exception was thrown. "); } public void ThrowsException_FuncArgumentOverloadWithMessage_AllowsToReturnNull() { - Exception ex = VerifyThrows(() => Assert.ThrowsException(() => null, "message")); - Verify(ex.Message.Equals("Assert.ThrowsException failed. Expected exception type: but no exception was thrown. message", StringComparison.Ordinal)); + Action action = () => Assert.ThrowsException(() => null, "message"); + action.Should().Throw() + .And.Message.Should().Be("Assert.ThrowsException failed. Expected exception type: but no exception was thrown. message"); } public void ThrowsException_FuncArgumentOverloadWithMessagesAndParameters_AllowsToReturnNull() { - Exception ex = VerifyThrows(() => Assert.ThrowsException(() => null, "message {0}", 1)); - Verify(ex.Message.Equals("Assert.ThrowsException failed. Expected exception type: but no exception was thrown. message 1", StringComparison.Ordinal)); + Action action = () => Assert.ThrowsException(() => null, "message {0}", 1); + action.Should().Throw() + .And.Message.Should().Be("Assert.ThrowsException failed. Expected exception type: but no exception was thrown. message 1"); } #endregion @@ -64,13 +72,12 @@ public void ThrowsExceptionAsyncShouldThrowAssertionOnNoException() { Task t = Assert.ThrowsExceptionAsync( async () => await Task.Delay(5).ConfigureAwait(false)); - Exception ex = VerifyThrows(t.Wait); - - Exception? innerException = ex.InnerException; + Action action = t.Wait; + AggregateException ex = action.Should().Throw().Which; - Verify(innerException is not null); - Verify(typeof(AssertFailedException) == innerException.GetType()); - Verify(innerException.Message.Equals("Assert.ThrowsExceptionAsync failed. Expected exception type: but no exception was thrown. ", StringComparison.Ordinal)); + ex.InnerException.Should().NotBeNull(); + ex.InnerException!.Should().BeOfType(); + ex.InnerException!.Message.Should().Be("Assert.ThrowsExceptionAsync failed. Expected exception type: but no exception was thrown. "); } public void ThrowsExceptionAsyncShouldThrowAssertionOnWrongException() @@ -81,13 +88,12 @@ public void ThrowsExceptionAsyncShouldThrowAssertionOnWrongException() await Task.Delay(5).ConfigureAwait(false); throw new FormatException(); }); - Exception ex = VerifyThrows(t.Wait); - - Exception? innerException = ex.InnerException; + Action action = t.Wait; + AggregateException ex = action.Should().Throw().Which; - Verify(innerException is not null); - Assert.AreEqual(typeof(AssertFailedException), innerException.GetType()); - Verify(innerException.Message.Equals("Assert.ThrowsExceptionAsync failed. Expected exception type:. Actual exception type:. ", StringComparison.Ordinal)); + ex.InnerException.Should().NotBeNull(); + ex.InnerException!.Should().BeOfType(); + ex.InnerException!.Message.Should().Be("Assert.ThrowsExceptionAsync failed. Expected exception type:. Actual exception type:. "); } public void ThrowsExceptionAsyncWithMessageShouldThrowAssertionOnNoException() @@ -95,13 +101,12 @@ public void ThrowsExceptionAsyncWithMessageShouldThrowAssertionOnNoException() Task t = Assert.ThrowsExceptionAsync( async () => await Task.Delay(5).ConfigureAwait(false), "The world is not on fire."); - Exception ex = VerifyThrows(t.Wait); + Action action = t.Wait; + AggregateException ex = action.Should().Throw().Which; - Exception? innerException = ex.InnerException; - - Verify(innerException is not null); - Assert.AreEqual(typeof(AssertFailedException), innerException.GetType()); - Verify(innerException.Message.Equals("Assert.ThrowsExceptionAsync failed. Expected exception type: but no exception was thrown. The world is not on fire.", StringComparison.Ordinal)); + ex.InnerException.Should().NotBeNull(); + ex.InnerException!.Should().BeOfType(); + ex.InnerException!.Message.Should().Be("Assert.ThrowsExceptionAsync failed. Expected exception type: but no exception was thrown. The world is not on fire."); } public void ThrowsExceptionAsyncWithMessageShouldThrowAssertionOnWrongException() @@ -113,13 +118,12 @@ public void ThrowsExceptionAsyncWithMessageShouldThrowAssertionOnWrongException( throw new FormatException(); }, "Happily ever after."); - Exception ex = VerifyThrows(t.Wait); - - Exception? innerException = ex.InnerException; + Action action = t.Wait; + AggregateException ex = action.Should().Throw().Which; - Verify(innerException is not null); - Assert.AreEqual(typeof(AssertFailedException), innerException.GetType()); - Verify(innerException.Message.Equals("Assert.ThrowsExceptionAsync failed. Expected exception type:. Actual exception type:. Happily ever after.", StringComparison.Ordinal)); + ex.InnerException.Should().NotBeNull(); + ex.InnerException!.Should().BeOfType(); + ex.InnerException!.Message.Should().Be("Assert.ThrowsExceptionAsync failed. Expected exception type:. Actual exception type:. Happily ever after."); } public void ThrowsExceptionAsyncWithMessageAndParamsShouldThrowOnNullAction() @@ -130,12 +134,11 @@ static void A() t.Wait(); } - Exception ex = VerifyThrows(A); + Action action = A; + AggregateException ex = action.Should().Throw().Which; - Exception? innerException = ex.InnerException; - - Verify(innerException is not null); - Verify(typeof(ArgumentNullException) == innerException.GetType()); + ex.InnerException.Should().NotBeNull(); + ex.InnerException!.Should().BeOfType(); } public void ThrowsExceptionAsyncWithMessageAndParamsShouldThrowOnNullMessage() @@ -146,12 +149,11 @@ static void A() t.Wait(); } - Exception ex = VerifyThrows(A); - - Exception? innerException = ex.InnerException; + Action action = A; + AggregateException ex = action.Should().Throw().Which; - Verify(innerException is not null); - Verify(typeof(ArgumentNullException) == innerException.GetType()); + ex.InnerException.Should().NotBeNull(); + ex.InnerException!.Should().BeOfType(); } public void ThrowsExceptionAsyncWithMessageAndParamsShouldThrowAssertionOnNoException() @@ -162,13 +164,12 @@ public void ThrowsExceptionAsyncWithMessageAndParamsShouldThrowAssertionOnNoExce "ta", "da", 123); - Exception ex = VerifyThrows(t.Wait); + Action action = t.Wait; + AggregateException ex = action.Should().Throw().Which; - Exception? innerException = ex.InnerException; - - Verify(innerException is not null); - Assert.AreEqual(typeof(AssertFailedException), innerException.GetType()); - Verify(innerException.Message.Equals("Assert.ThrowsExceptionAsync failed. Expected exception type: but no exception was thrown. The world is not on fire ta.da-123.", StringComparison.Ordinal)); + ex.InnerException.Should().NotBeNull(); + Assert.AreEqual(typeof(AssertFailedException), ex.InnerException.GetType()); + ex.InnerException!.Message.Should().Be("Assert.ThrowsExceptionAsync failed. Expected exception type: but no exception was thrown. The world is not on fire ta.da-123."); } public void ThrowsExceptionAsyncWithMessageAndParamsShouldThrowAssertionOnWrongException() @@ -182,13 +183,12 @@ public void ThrowsExceptionAsyncWithMessageAndParamsShouldThrowAssertionOnWrongE "Happily ever after. {0} {1}.", "The", "End"); - Exception ex = VerifyThrows(t.Wait); - - Exception? innerException = ex.InnerException; + Action action = t.Wait; + AggregateException ex = action.Should().Throw().Which; - Verify(innerException is not null); - Assert.AreEqual(typeof(AssertFailedException), innerException.GetType()); - Verify(innerException.Message.Equals("Assert.ThrowsExceptionAsync failed. Expected exception type:. Actual exception type:. Happily ever after. The End.", StringComparison.Ordinal)); + ex.InnerException.Should().NotBeNull(); + Assert.AreEqual(typeof(AssertFailedException), ex.InnerException.GetType()); + ex.InnerException!.Message.Should().Be("Assert.ThrowsExceptionAsync failed. Expected exception type:. Actual exception type:. Happily ever after. The End."); } #endregion @@ -198,8 +198,8 @@ public void Throws_WhenExceptionIsDerivedFromExpectedType_ShouldNotThrow() public void Throws_WhenExceptionIsNotExpectedType_ShouldThrow() { static void Action() => Assert.Throws(() => throw new Exception()); - Exception ex = VerifyThrows(Action); - Verify(ex is AssertFailedException); + Action action = Action; + action.Should().Throw(); } public void Throws_WithInterpolation() @@ -210,8 +210,8 @@ public void Throws_WithInterpolation() Exception ex = Assert.Throws(() => GetString(), $"Hello {GetString()}"); #pragma warning restore IDE0200 // Remove unnecessary lambda expression Exception ex2 = Assert.Throws(GetString, $"Hello {GetString()}"); - Verify(ex is not null); - Verify(ex2 is not null); + ex.Should().NotBeNull(); + ex2.Should().NotBeNull(); } public void ThrowsExactly_WithInterpolation() @@ -222,15 +222,15 @@ public void ThrowsExactly_WithInterpolation() Exception ex = Assert.ThrowsExactly(() => GetString(), $"Hello {GetString()}"); #pragma warning restore IDE0200 // Remove unnecessary lambda expression Exception ex2 = Assert.ThrowsExactly(GetString, $"Hello {GetString()}"); - Verify(ex is not null); - Verify(ex2 is not null); + ex.Should().NotBeNull(); + ex2.Should().NotBeNull(); } public void ThrowsExactly_WhenExceptionIsDerivedFromExpectedType_ShouldThrow() { static void Action() => Assert.ThrowsExactly(() => throw new ArgumentNullException()); - Exception ex = VerifyThrows(Action); - Verify(ex is AssertFailedException); + Action action = Action; + action.Should().Throw(); } public void ThrowsExactly_WhenExceptionExpectedType_ShouldNotThrow() @@ -242,22 +242,21 @@ public async Task ThrowsAsync_WhenExceptionIsDerivedFromExpectedType_ShouldNotTh public void ThrowsAsync_WhenExceptionIsNotExpectedType_ShouldThrow() { Task t = Assert.ThrowsAsync(() => throw new Exception()); - Exception ex = VerifyThrows(t.Wait); - Assert.IsInstanceOfType(ex.InnerException, out AssertFailedException assertFailedException); - Assert.AreEqual("Assert.ThrowsAsync failed. Expected exception type:. Actual exception type:. ", assertFailedException.Message); + Action action = t.Wait; + AggregateException ex = action.Should().Throw().Which; + ex.InnerException.Should().BeOfType(); + ex.InnerException!.Message.Should().Be("Assert.ThrowsAsync failed. Expected exception type:. Actual exception type:. "); } public void ThrowsExactlyAsync_WhenExceptionIsDerivedFromExpectedType_ShouldThrow() { Task t = Assert.ThrowsExactlyAsync(() => throw new ArgumentNullException()); - Exception ex = VerifyThrows(t.Wait); - Assert.IsInstanceOfType(ex.InnerException, out AssertFailedException assertFailedException); - Assert.AreEqual("Assert.ThrowsExactlyAsync failed. Expected exception type:. Actual exception type:. ", assertFailedException.Message); + Action action = t.Wait; + AggregateException ex = action.Should().Throw().Which; + ex.InnerException.Should().BeOfType(); + ex.InnerException!.Message.Should().Be("Assert.ThrowsExactlyAsync failed. Expected exception type:. Actual exception type:. "); } - public async Task ThrowsExactlyAsync_WhenExceptionExpectedType_ShouldNotThrow() - => await Assert.ThrowsExactlyAsync(() => throw new ArgumentNullException()); - public void Throws_WithMessageBuilder_Passes() { bool wasBuilderCalled = false; @@ -267,39 +266,42 @@ public void Throws_WithMessageBuilder_Passes() return "message constructed via builder."; }); - Verify(!wasBuilderCalled); + wasBuilderCalled.Should().BeFalse(); } public void Throws_WithMessageBuilder_FailsBecauseNoException() { bool wasBuilderCalled = false; Exception? exceptionPassedToBuilder = null; - AssertFailedException assertFailedEx = VerifyThrows(() => Assert.Throws(() => { }, messageBuilder: ex => + Action action = () => Assert.Throws(() => { }, messageBuilder: ex => { wasBuilderCalled = true; exceptionPassedToBuilder = ex; return "message constructed via builder."; - })); + }); + action.Should().Throw() + .And.Message.Should().Be("Assert.Throws failed. Expected exception type: but no exception was thrown. message constructed via builder."); - Verify(wasBuilderCalled); - Verify(exceptionPassedToBuilder is null); - Verify(assertFailedEx.Message == "Assert.Throws failed. Expected exception type: but no exception was thrown. message constructed via builder."); + wasBuilderCalled.Should().BeTrue(); + exceptionPassedToBuilder.Should().BeNull(); } public void Throws_WithMessageBuilder_FailsBecauseTypeMismatch() { bool wasBuilderCalled = false; Exception? exceptionPassedToBuilder = null; - AssertFailedException assertFailedEx = VerifyThrows(() => Assert.Throws(() => throw new ArgumentOutOfRangeException("MyParamNameHere"), messageBuilder: ex => + Action action = () => Assert.Throws(() => throw new ArgumentOutOfRangeException("MyParamNameHere"), messageBuilder: ex => { wasBuilderCalled = true; exceptionPassedToBuilder = ex; return "message constructed via builder."; - })); + }); + action.Should().Throw() + .And.Message.Should().Be("Assert.Throws failed. Expected exception type:. Actual exception type:. message constructed via builder."); - Verify(wasBuilderCalled); - Verify(exceptionPassedToBuilder is ArgumentOutOfRangeException { ParamName: "MyParamNameHere" }); - Verify(assertFailedEx.Message == "Assert.Throws failed. Expected exception type:. Actual exception type:. message constructed via builder."); + wasBuilderCalled.Should().BeTrue(); + exceptionPassedToBuilder.Should().BeOfType(); + ((ArgumentOutOfRangeException)exceptionPassedToBuilder!).ParamName.Should().Be("MyParamNameHere"); } public void ThrowsExactly_WithMessageBuilder_Passes() @@ -311,39 +313,42 @@ public void ThrowsExactly_WithMessageBuilder_Passes() return "message constructed via builder."; }); - Verify(!wasBuilderCalled); + wasBuilderCalled.Should().BeFalse(); } public void ThrowsExactly_WithMessageBuilder_FailsBecauseNoException() { bool wasBuilderCalled = false; Exception? exceptionPassedToBuilder = null; - AssertFailedException assertFailedEx = VerifyThrows(() => Assert.ThrowsExactly(() => { }, messageBuilder: ex => + Action action = () => Assert.ThrowsExactly(() => { }, messageBuilder: ex => { wasBuilderCalled = true; exceptionPassedToBuilder = ex; return "message constructed via builder."; - })); + }); + action.Should().Throw() + .And.Message.Should().Be("Assert.ThrowsExactly failed. Expected exception type: but no exception was thrown. message constructed via builder."); - Verify(wasBuilderCalled); - Verify(exceptionPassedToBuilder is null); - Verify(assertFailedEx.Message == "Assert.ThrowsExactly failed. Expected exception type: but no exception was thrown. message constructed via builder."); + wasBuilderCalled.Should().BeTrue(); + exceptionPassedToBuilder.Should().BeNull(); } public void ThrowsExactly_WithMessageBuilder_FailsBecauseTypeMismatch() { bool wasBuilderCalled = false; Exception? exceptionPassedToBuilder = null; - AssertFailedException assertFailedEx = VerifyThrows(() => Assert.ThrowsExactly(() => throw new ArgumentOutOfRangeException("MyParamNameHere"), messageBuilder: ex => + Action action = () => Assert.ThrowsExactly(() => throw new ArgumentOutOfRangeException("MyParamNameHere"), messageBuilder: ex => { wasBuilderCalled = true; exceptionPassedToBuilder = ex; return "message constructed via builder."; - })); + }); + action.Should().Throw() + .And.Message.Should().Be("Assert.ThrowsExactly failed. Expected exception type:. Actual exception type:. message constructed via builder."); - Verify(wasBuilderCalled); - Verify(exceptionPassedToBuilder is ArgumentOutOfRangeException { ParamName: "MyParamNameHere" }); - Verify(assertFailedEx.Message == "Assert.ThrowsExactly failed. Expected exception type:. Actual exception type:. message constructed via builder."); + wasBuilderCalled.Should().BeTrue(); + exceptionPassedToBuilder.Should().BeOfType(); + ((ArgumentOutOfRangeException)exceptionPassedToBuilder!).ParamName.Should().Be("MyParamNameHere"); } public async Task ThrowsAsync_WithMessageBuilder_Passes() @@ -355,39 +360,42 @@ await Assert.ThrowsAsync(() => Task.FromException(new Arg return "message constructed via builder."; }); - Verify(!wasBuilderCalled); + wasBuilderCalled.Should().BeFalse(); } public async Task ThrowsAsync_WithMessageBuilder_FailsBecauseNoException() { bool wasBuilderCalled = false; Exception? exceptionPassedToBuilder = null; - AssertFailedException assertFailedEx = await VerifyThrowsAsync(async () => await Assert.ThrowsAsync(() => Task.CompletedTask, messageBuilder: ex => + Func action = async () => await Assert.ThrowsAsync(() => Task.CompletedTask, messageBuilder: ex => { wasBuilderCalled = true; exceptionPassedToBuilder = ex; return "message constructed via builder."; - })); + }); + (await action.Should().ThrowAsync()) + .And.Message.Should().Be("Assert.ThrowsAsync failed. Expected exception type: but no exception was thrown. message constructed via builder."); - Verify(wasBuilderCalled); - Verify(exceptionPassedToBuilder is null); - Verify(assertFailedEx.Message == "Assert.ThrowsAsync failed. Expected exception type: but no exception was thrown. message constructed via builder."); + wasBuilderCalled.Should().BeTrue(); + exceptionPassedToBuilder.Should().BeNull(); } public async Task ThrowsAsync_WithMessageBuilder_FailsBecauseTypeMismatch() { bool wasBuilderCalled = false; Exception? exceptionPassedToBuilder = null; - AssertFailedException assertFailedEx = await VerifyThrowsAsync(async () => await Assert.ThrowsAsync(() => Task.FromException(new ArgumentOutOfRangeException("MyParamNameHere")), messageBuilder: ex => + Func action = async () => await Assert.ThrowsAsync(() => Task.FromException(new ArgumentOutOfRangeException("MyParamNameHere")), messageBuilder: ex => { wasBuilderCalled = true; exceptionPassedToBuilder = ex; return "message constructed via builder."; - })); + }); + (await action.Should().ThrowAsync()) + .And.Message.Should().Be("Assert.ThrowsAsync failed. Expected exception type:. Actual exception type:. message constructed via builder."); - Verify(wasBuilderCalled); - Verify(exceptionPassedToBuilder is ArgumentOutOfRangeException { ParamName: "MyParamNameHere" }); - Verify(assertFailedEx.Message == "Assert.ThrowsAsync failed. Expected exception type:. Actual exception type:. message constructed via builder."); + wasBuilderCalled.Should().BeTrue(); + exceptionPassedToBuilder.Should().BeOfType(); + ((ArgumentOutOfRangeException)exceptionPassedToBuilder!).ParamName.Should().Be("MyParamNameHere"); } public async Task ThrowsExactlyAsync_WithMessageBuilder_Passes() @@ -399,38 +407,41 @@ await Assert.ThrowsExactlyAsync(() => Task.FromException( return "message constructed via builder."; }); - Verify(!wasBuilderCalled); + wasBuilderCalled.Should().BeFalse(); } public async Task ThrowsExactlyAsync_WithMessageBuilder_FailsBecauseNoException() { bool wasBuilderCalled = false; Exception? exceptionPassedToBuilder = null; - AssertFailedException assertFailedEx = await VerifyThrowsAsync(async () => await Assert.ThrowsExactlyAsync(() => Task.CompletedTask, messageBuilder: ex => + Func action = async () => await Assert.ThrowsExactlyAsync(() => Task.CompletedTask, messageBuilder: ex => { wasBuilderCalled = true; exceptionPassedToBuilder = ex; return "message constructed via builder."; - })); + }); + (await action.Should().ThrowAsync()) + .And.Message.Should().Be("Assert.ThrowsExactlyAsync failed. Expected exception type: but no exception was thrown. message constructed via builder."); - Verify(wasBuilderCalled); - Verify(exceptionPassedToBuilder is null); - Verify(assertFailedEx.Message == "Assert.ThrowsExactlyAsync failed. Expected exception type: but no exception was thrown. message constructed via builder."); + wasBuilderCalled.Should().BeTrue(); + exceptionPassedToBuilder.Should().BeNull(); } public async Task ThrowsExactlyAsync_WithMessageBuilder_FailsBecauseTypeMismatch() { bool wasBuilderCalled = false; Exception? exceptionPassedToBuilder = null; - AssertFailedException assertFailedEx = await VerifyThrowsAsync(async () => await Assert.ThrowsExactlyAsync(() => Task.FromException(new ArgumentOutOfRangeException("MyParamNameHere")), messageBuilder: ex => + Func action = async () => await Assert.ThrowsExactlyAsync(() => Task.FromException(new ArgumentOutOfRangeException("MyParamNameHere")), messageBuilder: ex => { wasBuilderCalled = true; exceptionPassedToBuilder = ex; return "message constructed via builder."; - })); + }); + (await action.Should().ThrowAsync()) + .And.Message.Should().Be("Assert.ThrowsExactlyAsync failed. Expected exception type:. Actual exception type:. message constructed via builder."); - Verify(wasBuilderCalled); - Verify(exceptionPassedToBuilder is ArgumentOutOfRangeException { ParamName: "MyParamNameHere" }); - Verify(assertFailedEx.Message == "Assert.ThrowsExactlyAsync failed. Expected exception type:. Actual exception type:. message constructed via builder."); + wasBuilderCalled.Should().BeTrue(); + exceptionPassedToBuilder.Should().BeOfType(); + ((ArgumentOutOfRangeException)exceptionPassedToBuilder!).ParamName.Should().Be("MyParamNameHere"); } } diff --git a/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.cs b/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.cs index 6c1efaf5ce..9e5ac645e7 100644 --- a/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.cs +++ b/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.cs @@ -1,24 +1,26 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using AwesomeAssertions; + namespace Microsoft.VisualStudio.TestPlatform.TestFramework.UnitTests; public partial class AssertTests { #region Instance tests - public void InstanceShouldReturnAnInstanceOfAssert() => Verify(Assert.That is not null); + public void InstanceShouldReturnAnInstanceOfAssert() => Assert.That.Should().NotBeNull(); - public void InstanceShouldCacheAssertInstance() => Verify(ReferenceEquals(Assert.That, Assert.That)); + public void InstanceShouldCacheAssertInstance() => Assert.That.Should().BeSameAs(Assert.That); #endregion #region ReplaceNullChars tests public void ReplaceNullCharsShouldReturnStringIfNullOrEmpty() { - Verify(Assert.ReplaceNullChars(null) == null); - Verify(Assert.ReplaceNullChars(string.Empty) == string.Empty); + Assert.ReplaceNullChars(null).Should().BeNull(); + Assert.ReplaceNullChars(string.Empty).Should().BeSameAs(string.Empty); } - public void ReplaceNullCharsShouldReplaceNullCharsInAString() => Verify(Assert.ReplaceNullChars("The quick brown fox \0 jumped over the la\0zy dog\0") == "The quick brown fox \\0 jumped over the la\\0zy dog\\0"); + public void ReplaceNullCharsShouldReplaceNullCharsInAString() => Assert.ReplaceNullChars("The quick brown fox \0 jumped over the la\0zy dog\0").Should().Be("The quick brown fox \\0 jumped over the la\\0zy dog\\0"); #endregion #region BuildUserMessage tests @@ -26,15 +28,15 @@ public void ReplaceNullCharsShouldReturnStringIfNullOrEmpty() // See https://github.com/dotnet/sdk/issues/25373 public void BuildUserMessageThrowsWhenMessageContainsInvalidStringFormatComposite() { - Exception ex = VerifyThrows(() => Assert.BuildUserMessage("{", "arg")); - Verify(ex is FormatException); + Action act = () => Assert.BuildUserMessage("{", "arg"); + act.Should().Throw(); } // See https://github.com/dotnet/sdk/issues/25373 public void BuildUserMessageDoesNotThrowWhenMessageContainsInvalidStringFormatCompositeAndNoArgumentsPassed() { string message = Assert.BuildUserMessage("{"); - Verify(message == "{"); + message.Should().Be("{"); } #endregion @@ -43,20 +45,20 @@ public void BuildUserMessageDoesNotThrowWhenMessageContainsInvalidStringFormatCo public void ObsoleteEqualsMethodThrowsAssertFailedException() { #pragma warning disable CS0618 // Type or member is obsolete - Exception ex = VerifyThrows(() => Assert.Equals("test", "test")); + Action act = () => Assert.Equals("test", "test"); #pragma warning restore CS0618 // Type or member is obsolete - Verify(ex is AssertFailedException); - Verify(ex.Message.Contains("Assert.Equals should not be used for Assertions")); + act.Should().Throw() + .WithMessage("*Assert.Equals should not be used for Assertions*"); } public void ObsoleteReferenceEqualsMethodThrowsAssertFailedException() { object obj = new(); #pragma warning disable CS0618 // Type or member is obsolete - Exception ex = VerifyThrows(() => Assert.ReferenceEquals(obj, obj)); + Action act = () => Assert.ReferenceEquals(obj, obj); #pragma warning restore CS0618 // Type or member is obsolete - Verify(ex is AssertFailedException); - Verify(ex.Message.Contains("Assert.ReferenceEquals should not be used for Assertions")); + act.Should().Throw() + .WithMessage("*Assert.ReferenceEquals should not be used for Assertions*"); } #endif #endregion diff --git a/test/UnitTests/TestFramework.UnitTests/Assertions/CollectionAssertTests.cs b/test/UnitTests/TestFramework.UnitTests/Assertions/CollectionAssertTests.cs index 50c4cfa2dd..a521130da3 100644 --- a/test/UnitTests/TestFramework.UnitTests/Assertions/CollectionAssertTests.cs +++ b/test/UnitTests/TestFramework.UnitTests/Assertions/CollectionAssertTests.cs @@ -3,15 +3,17 @@ using System.Collections.ObjectModel; +using AwesomeAssertions; + using TestFramework.ForTestingMSTest; namespace Microsoft.VisualStudio.TestPlatform.TestFramework.UnitTests.Assertions; public class CollectionAssertTests : TestContainer { - public void InstanceShouldReturnAnInstanceOfCollectionAssert() => Verify(CollectionAssert.That is not null); + public void InstanceShouldReturnAnInstanceOfCollectionAssert() => (CollectionAssert.That is not null).Should().BeTrue(); - public void InstanceShouldCacheCollectionAssertInstance() => Verify(CollectionAssert.That == CollectionAssert.That); + public void InstanceShouldCacheCollectionAssertInstance() => (CollectionAssert.That == CollectionAssert.That).Should().BeTrue(); public void CollectionAssertContainsNullabilityPostConditions() { @@ -204,14 +206,16 @@ public void CollectionAssertAreEqual_WithNestedDiffSizedArrays_Fails() { int[][] expected = [[1, 2], [3, 4], [5, 6], [7, 8], [9]]; int[][] actual = [[1, 2], [999, 999, 999, 999, 999], [5, 6], [], [9]]; - VerifyThrows(() => CollectionAssert.AreEqual(expected, actual)); + Action action = () => CollectionAssert.AreEqual(expected, actual); + action.Should().Throw(); } public void CollectionAssertAreEqual_WithCaseSensetiveComparer_Fails() { List expected = ["one", "two"]; List actual = ["ONE", "tWo"]; - VerifyThrows(() => CollectionAssert.AreEqual(expected, actual, StringComparer.Ordinal)); + Action action = () => CollectionAssert.AreEqual(expected, actual, StringComparer.Ordinal); + action.Should().Throw(); } public void CollectionAssertAreEqualComparerMessageNullabilityPostConditions() @@ -253,7 +257,8 @@ public void CollectionAssertAreEqual_NotEqualNestedLists_Fails() ICollection? collection1 = GetNestedLists(); ICollection? collection2 = GetNotMatchingNestedLists(); - VerifyThrows(() => CollectionAssert.AreEqual(collection1, collection2)); + Action action = () => CollectionAssert.AreEqual(collection1, collection2); + action.Should().Throw(); } public void CollectionAssertAreEqual_EqualNonICollectionInnerCollection_Passes() @@ -269,7 +274,8 @@ public void CollectionAssertAreEqual_NotEqualNonICollectionInnerCollection_Fails ICollection? collection1 = GetNonICollectionInnerCollection(); ICollection? collection2 = GetNotMatchingGetNonICollectionInnerCollection(); - VerifyThrows(() => CollectionAssert.AreEqual(collection1, collection2)); + Action action = () => CollectionAssert.AreEqual(collection1, collection2); + action.Should().Throw(); } public void CollectionAssertAreNotEqual_NotEqualNestedLists_Passes() @@ -284,7 +290,8 @@ public void CollectionAssertAreNotEqual_WithIgnoreCaseComparer_Fails() { List expected = ["one", "two"]; List actual = ["ONE", "tWo"]; - VerifyThrows(() => CollectionAssert.AreNotEqual(expected, actual, StringComparer.OrdinalIgnoreCase)); + Action action = () => CollectionAssert.AreNotEqual(expected, actual, StringComparer.OrdinalIgnoreCase); + action.Should().Throw(); } public void CollectionAssertAreNotEqual_WithCaseSensitiveComparer_Passes() @@ -299,7 +306,8 @@ public void CollectionAssertAreNotEqual_EqualNestedLists_Fails() ICollection? collection1 = GetNestedLists(); ICollection? collection2 = GetNestedLists(); - VerifyThrows(() => CollectionAssert.AreNotEqual(collection1, collection2)); + Action action = () => CollectionAssert.AreNotEqual(collection1, collection2); + action.Should().Throw(); } public void CollectionAssertAreNotEqual_EqualNonICollectionInnerCollection_Fails() @@ -307,7 +315,8 @@ public void CollectionAssertAreNotEqual_EqualNonICollectionInnerCollection_Fails ICollection? collection1 = GetNonICollectionInnerCollection(); ICollection? collection2 = GetNonICollectionInnerCollection(); - VerifyThrows(() => CollectionAssert.AreNotEqual(collection1, collection2)); + Action action = () => CollectionAssert.AreNotEqual(collection1, collection2); + action.Should().Throw(); } public void CollectionAssertAreNotEqual_NotEqualNonICollectionInnerCollection_Passes() @@ -373,16 +382,18 @@ public void CollectionAssertAreEquivalent_FailWhenNotEquivalent_WithMessage() { ICollection? collection1 = GetCollection(); ICollection? collection2 = GetMatchingSuperSet(); - Exception ex = VerifyThrows(() => CollectionAssert.AreEquivalent(collection1, collection2, "message")); - Verify(ex.Message.Contains("message")); + Action action = () => CollectionAssert.AreEquivalent(collection1, collection2, "message"); + action.Should().Throw().And + .Message.Should().Contain("message"); } public void CollectionAssertAreEquivalent_FailWhenNotEquivalent_WithMessageAndParams() { ICollection? collection1 = GetCollection(); ICollection? collection2 = GetMatchingSuperSet(); - Exception ex = VerifyThrows(() => CollectionAssert.AreEquivalent(collection1, collection2, "message format {0} {1}", 1, 2)); - Verify(ex.Message.Contains("message")); + Action action = () => CollectionAssert.AreEquivalent(collection1, collection2, "message format {0} {1}", 1, 2); + action.Should().Throw().And. + Message.Should().Contain("message"); } public void CollectionAssertAreEquivalent_WithInsensitiveCaseComparer_DoesNotThrow() @@ -396,16 +407,18 @@ public void CollectionAssertAreEquivalent_FailsWithInsensitiveCaseComparer_WithM { ICollection? collection1 = GetCollection(); ICollection? collection2 = GetLettersCaseMismatchingSuperSet(); - Exception ex = VerifyThrows(() => CollectionAssert.AreEquivalent(collection1?.Cast(), collection2?.Cast(), new CaseInsensitiveEqualityComparer(), "message")); - Verify(ex.Message.Contains("message")); + Action action = () => CollectionAssert.AreEquivalent(collection1?.Cast(), collection2?.Cast(), new CaseInsensitiveEqualityComparer(), "message"); + action.Should().Throw().And + .Message.Should().Contain("message"); } public void CollectionAssertAreEquivalent_FailsWithInsensitiveCaseComparer_WithMessageAndParams() { ICollection? collection1 = GetCollection(); ICollection? collection2 = GetLettersCaseMismatchingSuperSet(); - Exception ex = VerifyThrows(() => CollectionAssert.AreEquivalent(collection1?.Cast(), collection2?.Cast(), new CaseInsensitiveEqualityComparer(), "message format {0} {1}", 1, 2)); - Verify(ex.Message.Contains("message")); + Action action = () => CollectionAssert.AreEquivalent(collection1?.Cast(), collection2?.Cast(), new CaseInsensitiveEqualityComparer(), "message format {0} {1}", 1, 2); + action.Should().Throw().And + .Message.Should().Contain("message"); } public void CollectionAssertAreNotEquivalent_SameItemsWithDifferentOrder_DoesNotThrow() @@ -419,16 +432,18 @@ public void CollectionAssertAreNotEquivalent_FailWhenNotEquivalent_WithMessage() { ICollection? collection1 = GetReversedMatchingSuperSet(); ICollection? collection2 = GetMatchingSuperSet(); - Exception ex = VerifyThrows(() => CollectionAssert.AreNotEquivalent(collection1, collection2, "message")); - Verify(ex.Message.Contains("message")); + Action action = () => CollectionAssert.AreNotEquivalent(collection1, collection2, "message"); + action.Should().Throw().And + .Message.Should().Contain("message"); } public void CollectionAssertAreNotEquivalent_FailWhenNotEquivalent_WithMessageAndParams() { ICollection? collection1 = GetReversedMatchingSuperSet(); ICollection? collection2 = GetMatchingSuperSet(); - Exception ex = VerifyThrows(() => CollectionAssert.AreNotEquivalent(collection1, collection2, "message format {0} {1}", 1, 2)); - Verify(ex.Message.Contains("message")); + Action action = () => CollectionAssert.AreNotEquivalent(collection1, collection2, "message format {0} {1}", 1, 2); + action.Should().Throw().And + .Message.Should().Contain("message"); } public void CollectionAssertAreNotEquivalent_WithInsensitiveCaseComparer_DoesNotThrow() @@ -442,44 +457,48 @@ public void CollectionAssertAreNotEquivalent_FailsWithInsensitiveCaseComparer_Wi { ICollection? collection1 = GetMatchingSuperSet(); ICollection? collection2 = GetLettersCaseMismatchingSuperSet(); - Exception ex = VerifyThrows(() => CollectionAssert.AreNotEquivalent(collection1?.Cast(), collection2?.Cast(), new CaseInsensitiveNotEqualityComparer(), "message")); - Verify(ex.Message.Contains("message")); + Action action = () => CollectionAssert.AreNotEquivalent(collection1?.Cast(), collection2?.Cast(), new CaseInsensitiveNotEqualityComparer(), "message"); + action.Should().Throw() + .And.Message.Should().Contain("message"); } public void CollectionAssertAreNotEquivalent_FailsWithInsensitiveCaseComparer_WithMessageAndParams() { ICollection? collection1 = GetMatchingSuperSet(); ICollection? collection2 = GetLettersCaseMismatchingSuperSet(); - Exception ex = VerifyThrows(() => CollectionAssert.AreNotEquivalent(collection1?.Cast(), collection2?.Cast(), new CaseInsensitiveNotEqualityComparer(), "message format {0} {1}", 1, 2)); - Verify(ex.Message.Contains("message")); + Action action = () => CollectionAssert.AreNotEquivalent(collection1?.Cast(), collection2?.Cast(), new CaseInsensitiveNotEqualityComparer(), "message format {0} {1}", 1, 2); + action.Should().Throw() + .And.Message.Should().Contain("message"); } public void CollectionAssertAreNotEquivalent_FailsWithTwoNullsAndComparer_WithMessageAndParams() { - Exception ex = VerifyThrows(() => CollectionAssert.AreNotEquivalent(null, null, new CaseInsensitiveNotEqualityComparer(), "message format {0} {1}", 1, 2)); - Verify(ex.Message.Contains("message")); + Action action = () => CollectionAssert.AreNotEquivalent(null, null, new CaseInsensitiveNotEqualityComparer(), "message format {0} {1}", 1, 2); + action.Should().Throw() + .And.Message.Should().Contain("message"); } public void CollectionAssertAreEqualWithoutUserMessage_FailsWithGoodMessage() { - Exception ex = VerifyThrows(() => CollectionAssert.AreEqual(new[] { 1, 2, 3 }, new[] { 1, 5, 3 })); - Assert.AreEqual( - """ + Action action = () => CollectionAssert.AreEqual(new[] { 1, 2, 3 }, new[] { 1, 5, 3 }); + action.Should().Throw() + .And.Message.Should().Be(""" CollectionAssert.AreEqual failed. Element at index 1 do not match. Expected: 2 Actual: 5 - """, ex.Message); + """); } public void CollectionAssertAreEqualWithUserMessage_FailsWithGoodMessage() { - Exception ex = VerifyThrows(() => CollectionAssert.AreEqual(new[] { 1, 2, 3 }, new[] { 1, 5, 3 }, "User-provided message")); - Assert.AreEqual( + Action action = () => CollectionAssert.AreEqual(new[] { 1, 2, 3 }, new[] { 1, 5, 3 }, "User-provided message"); + action.Should().Throw() + .And.Message.Should().Be( """ CollectionAssert.AreEqual failed. User-provided message. Element at index 1 do not match. Expected: 2 Actual: 5 - """, ex.Message); + """); } #pragma warning disable CA1859 // Use concrete types when possible for improved performance @@ -567,20 +586,20 @@ private class CaseInsensitiveNotEqualityComparer : IEqualityComparer public void ObsoleteEqualsMethodThrowsAssertFailedException() { #pragma warning disable CS0618 // Type or member is obsolete - Exception ex = VerifyThrows(() => CollectionAssert.Equals("test", "test")); + Action action = () => CollectionAssert.Equals("test", "test"); #pragma warning restore CS0618 // Type or member is obsolete - Verify(ex is AssertFailedException); - Verify(ex.Message.Contains("CollectionAssert.Equals should not be used for Assertions")); + action.Should().Throw() + .And.Message.Should().Contain("CollectionAssert.Equals should not be used for Assertions"); } public void ObsoleteReferenceEqualsMethodThrowsAssertFailedException() { object obj = new(); #pragma warning disable CS0618 // Type or member is obsolete - Exception ex = VerifyThrows(() => CollectionAssert.ReferenceEquals(obj, obj)); + Action action = () => CollectionAssert.ReferenceEquals(obj, obj); #pragma warning restore CS0618 // Type or member is obsolete - Verify(ex is AssertFailedException); - Verify(ex.Message.Contains("CollectionAssert.ReferenceEquals should not be used for Assertions")); + action.Should().Throw() + .And.Message.Should().Contain("CollectionAssert.ReferenceEquals should not be used for Assertions"); } #endif #endregion diff --git a/test/UnitTests/TestFramework.UnitTests/Assertions/StringAssertTests.cs b/test/UnitTests/TestFramework.UnitTests/Assertions/StringAssertTests.cs index 49002e6b66..9c2e82789a 100644 --- a/test/UnitTests/TestFramework.UnitTests/Assertions/StringAssertTests.cs +++ b/test/UnitTests/TestFramework.UnitTests/Assertions/StringAssertTests.cs @@ -1,46 +1,52 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using AwesomeAssertions; + using TestFramework.ForTestingMSTest; namespace Microsoft.VisualStudio.TestPlatform.TestFramework.UnitTests.Assertions; public class StringAssertTests : TestContainer { - public void InstanceShouldReturnAnInstanceOfStringAssert() => Verify(StringAssert.That is not null); + public void InstanceShouldReturnAnInstanceOfStringAssert() => StringAssert.That.Should().NotBeNull(); - public void InstanceShouldCacheStringAssertInstance() => Verify(StringAssert.That == StringAssert.That); + public void InstanceShouldCacheStringAssertInstance() => StringAssert.That.Should().BeSameAs(StringAssert.That); public void StringAssertContains() { string actual = "The quick brown fox jumps over the lazy dog."; string notInString = "I'm not in the string above"; - Exception ex = VerifyThrows(() => StringAssert.Contains(actual, notInString)); - Verify(ex.Message.Contains("StringAssert.Contains failed")); + Action action = () => StringAssert.Contains(actual, notInString); + action.Should().Throw() + .And.Message.Should().Contain("StringAssert.Contains failed"); } public void StringAssertStartsWith() { string actual = "The quick brown fox jumps over the lazy dog."; string notInString = "I'm not in the string above"; - Exception ex = VerifyThrows(() => StringAssert.StartsWith(actual, notInString)); - Verify(ex.Message.Contains("StringAssert.StartsWith failed")); + Action action = () => StringAssert.StartsWith(actual, notInString); + action.Should().Throw() + .And.Message.Should().Contain("StringAssert.StartsWith failed"); } public void StringAssertEndsWith() { string actual = "The quick brown fox jumps over the lazy dog."; string notInString = "I'm not in the string above"; - Exception ex = VerifyThrows(() => StringAssert.EndsWith(actual, notInString)); - Verify(ex.Message.Contains("StringAssert.EndsWith failed")); + Action action = () => StringAssert.EndsWith(actual, notInString); + action.Should().Throw() + .And.Message.Should().Contain("StringAssert.EndsWith failed"); } public void StringAssertDoesNotMatch() { string actual = "The quick brown fox jumps over the lazy dog."; Regex doesMatch = new("quick brown fox"); - Exception ex = VerifyThrows(() => StringAssert.DoesNotMatch(actual, doesMatch)); - Verify(ex.Message.Contains("StringAssert.DoesNotMatch failed")); + Action action = () => StringAssert.DoesNotMatch(actual, doesMatch); + action.Should().Throw() + .And.Message.Should().Contain("StringAssert.DoesNotMatch failed"); } public void StringAssertContainsIgnoreCase_DoesNotThrow() @@ -67,23 +73,25 @@ public void StringAssertEndsWithIgnoreCase_DoesNotThrow() // See https://github.com/dotnet/sdk/issues/25373 public void StringAssertContainsDoesNotThrowFormatException() { - Exception ex = VerifyThrows(() => StringAssert.Contains(":-{", "x")); - Verify(ex.Message.Contains("StringAssert.Contains failed")); + Action action = () => StringAssert.Contains(":-{", "x"); + action.Should().Throw() + .And.Message.Should().Contain("StringAssert.Contains failed"); } // See https://github.com/dotnet/sdk/issues/25373 public void StringAssertContainsDoesNotThrowFormatExceptionWithArguments() { - Exception ex = VerifyThrows(() => StringAssert.Contains("{", "x", "message {0}", "arg")); - Verify(ex.Message.Contains("StringAssert.Contains failed")); + Action action = () => StringAssert.Contains("{", "x", "message {0}", "arg"); + action.Should().Throw() + .And.Message.Should().Contain("StringAssert.Contains failed"); } // See https://github.com/dotnet/sdk/issues/25373 [SuppressMessage("Usage", "CA2241:Provide correct arguments to formatting methods", Justification = "We want to test invalid format")] public void StringAssertContainsFailsIfMessageIsInvalidStringFormatComposite() { - Exception ex = VerifyThrows(() => StringAssert.Contains("a", "b", "message {{0}", "arg")); - Verify(ex is FormatException); + Action action = () => StringAssert.Contains("a", "b", "message {{0}", "arg"); + action.Should().Throw(); } public void StringAssertContainsNullabilitiesPostConditions() @@ -317,20 +325,20 @@ public void StringAssertDoesNotMatchMessageParametersNullabilitiesPostConditions public void ObsoleteEqualsMethodThrowsAssertFailedException() { #pragma warning disable CS0618 // Type or member is obsolete - Exception ex = VerifyThrows(() => StringAssert.Equals("test", "test")); + Action action = () => StringAssert.Equals("test", "test"); #pragma warning restore CS0618 // Type or member is obsolete - Verify(ex is AssertFailedException); - Verify(ex.Message.Contains("StringAssert.Equals should not be used for Assertions")); + action.Should().Throw() + .And.Message.Should().Contain("StringAssert.Equals should not be used for Assertions"); } public void ObsoleteReferenceEqualsMethodThrowsAssertFailedException() { object obj = new(); #pragma warning disable CS0618 // Type or member is obsolete - Exception ex = VerifyThrows(() => StringAssert.ReferenceEquals(obj, obj)); + Action action = () => StringAssert.ReferenceEquals(obj, obj); #pragma warning restore CS0618 // Type or member is obsolete - Verify(ex is AssertFailedException); - Verify(ex.Message.Contains("StringAssert.ReferenceEquals should not be used for Assertions")); + action.Should().Throw() + .And.Message.Should().Contain("StringAssert.ReferenceEquals should not be used for Assertions"); } #endif #endregion diff --git a/test/UnitTests/TestFramework.UnitTests/Attributes/DataRowAttributeTests.cs b/test/UnitTests/TestFramework.UnitTests/Attributes/DataRowAttributeTests.cs index 176a5d279d..7231b56a82 100644 --- a/test/UnitTests/TestFramework.UnitTests/Attributes/DataRowAttributeTests.cs +++ b/test/UnitTests/TestFramework.UnitTests/Attributes/DataRowAttributeTests.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 AwesomeAssertions; + using Moq; using TestFramework.ForTestingMSTest; @@ -15,42 +17,42 @@ public void DefaultConstructorSetsEmptyArrayPassed() { var dataRow = new DataRowAttribute(); - Verify(Array.Empty().SequenceEqual(dataRow.Data)); + dataRow.Data.Should().BeEquivalentTo(Array.Empty()); } public void ConstructorShouldSetDataPassed() { var dataRow = new DataRowAttribute("mercury"); - Verify(new object[] { "mercury" }.SequenceEqual(dataRow.Data)); + dataRow.Data.Should().BeEquivalentTo(new object[] { "mercury" }); } public void ConstructorShouldSetNullDataPassed() { var dataRow = new DataRowAttribute(null); - Verify(new object?[] { null }.SequenceEqual(dataRow.Data)); + dataRow.Data.Should().BeEquivalentTo(new object?[] { null }); } public void ConstructorShouldSetMultipleDataValuesPassed() { var dataRow = new DataRowAttribute("mercury", "venus", "earth"); - Verify(new object[] { "mercury", "venus", "earth" }.SequenceEqual(dataRow.Data)); + dataRow.Data.Should().BeEquivalentTo(new object[] { "mercury", "venus", "earth" }); } public void ConstructorShouldSetANullDataValuePassedInParams() { var dataRow = new DataRowAttribute("neptune", null); - Verify(new object?[] { "neptune", null }.SequenceEqual(dataRow.Data)); + dataRow.Data.Should().BeEquivalentTo(new object?[] { "neptune", null }); } public void ConstructorShouldSetANullDataValuePassedInAsADataArg() { var dataRow = new DataRowAttribute(null, "logos"); - Verify(new object?[] { null, "logos" }.SequenceEqual(dataRow.Data)); + dataRow.Data.Should().BeEquivalentTo(new object?[] { null, "logos" }); } public void ConstructorShouldSetMultipleDataArrays() @@ -58,16 +60,16 @@ public void ConstructorShouldSetMultipleDataArrays() // Fixes https://github.com/microsoft/testfx/issues/1180 var dataRow = new DataRowAttribute(new[] { "a" }, new[] { "b" }); - Verify(dataRow.Data.Length == 2); - Verify(dataRow.Data[0] is string[] array1 && array1.SequenceEqual(["a"])); - Verify(dataRow.Data[1] is string[] array2 && array2.SequenceEqual(["b"])); + dataRow.Data.Should().HaveCount(2); + dataRow.Data[0].Should().BeOfType().Which.Should().BeEquivalentTo(["a"]); + dataRow.Data[1].Should().BeOfType().Which.Should().BeEquivalentTo(["b"]); } public void GetDataShouldReturnDataPassed() { var dataRow = new DataRowAttribute("mercury"); - Verify(new object[] { "mercury" }.SequenceEqual(dataRow.GetData(null!).Single())); + dataRow.GetData(null!).Single().Should().BeEquivalentTo(new object[] { "mercury" }); } public void GetDisplayNameShouldReturnAppropriateName() @@ -82,13 +84,13 @@ public void GetDisplayNameShouldReturnAppropriateName() string?[] data2 = ["First", null, "Second"]; string? displayName = dataRowAttribute.GetDisplayName(testMethodInfo, data); - Verify(displayName == "DataRowTestMethod (\"First\",\"Second\",null)"); + displayName.Should().Be("DataRowTestMethod (\"First\",\"Second\",null)"); displayName = dataRowAttribute.GetDisplayName(testMethodInfo, data1); - Verify(displayName == "DataRowTestMethod (null,\"First\",\"Second\")"); + displayName.Should().Be("DataRowTestMethod (null,\"First\",\"Second\")"); displayName = dataRowAttribute.GetDisplayName(testMethodInfo, data2); - Verify(displayName == "DataRowTestMethod (\"First\",null,\"Second\")"); + displayName.Should().Be("DataRowTestMethod (\"First\",null,\"Second\")"); } public void GetDisplayNameShouldReturnSpecifiedDisplayName() @@ -104,7 +106,7 @@ public void GetDisplayNameShouldReturnSpecifiedDisplayName() string?[] data = ["First", "Second", null]; string? displayName = dataRowAttribute.GetDisplayName(testMethodInfo, data); - Verify(displayName == "DataRowTestWithDisplayName"); + displayName.Should().Be("DataRowTestWithDisplayName"); } public void GetDisplayNameForArrayOfOneItem() @@ -118,7 +120,7 @@ public void GetDisplayNameForArrayOfOneItem() string? displayName = dataRow.GetDisplayName(methodInfoMock.Object, dataRow.Data); // Assert - Verify(displayName == "MyMethod ([\"a\"])"); + displayName.Should().Be("MyMethod ([\"a\"])"); } public void GetDisplayName_AfterOverriding_GetsTheNewDisplayName() @@ -131,7 +133,7 @@ public void GetDisplayName_AfterOverriding_GetsTheNewDisplayName() string? displayName = dataRow.GetDisplayName(methodInfoMock.Object, dataRow.Data); // Assert - Verify(displayName == "Overridden DisplayName"); + displayName.Should().Be("Overridden DisplayName"); } public void GetDisplayNameForArrayOfMultipleItems() @@ -145,7 +147,7 @@ public void GetDisplayNameForArrayOfMultipleItems() string? displayName = dataRow.GetDisplayName(methodInfoMock.Object, dataRow.Data); // Assert - Verify(displayName == "MyMethod ([\"a\",\"b\",\"c\"])"); + displayName.Should().Be("MyMethod ([\"a\",\"b\",\"c\"])"); } public void GetDisplayNameForMultipleArraysOfOneItem() @@ -159,7 +161,7 @@ public void GetDisplayNameForMultipleArraysOfOneItem() string? displayName = dataRow.GetDisplayName(methodInfoMock.Object, dataRow.Data); // Assert - Verify(displayName == "MyMethod ([\"a\"],[\"1\"])"); + displayName.Should().Be("MyMethod ([\"a\"],[\"1\"])"); } public void GetDisplayNameForMultipleArraysOfMultipleItems() @@ -173,7 +175,7 @@ public void GetDisplayNameForMultipleArraysOfMultipleItems() string? displayName = dataRow.GetDisplayName(methodInfoMock.Object, dataRow.Data); // Assert - Verify(displayName == "MyMethod ([\"a\",\"b\",\"c\"],[\"1\",\"2\",\"3\"])"); + displayName.Should().Be("MyMethod ([\"a\",\"b\",\"c\"],[\"1\",\"2\",\"3\"])"); } public void GetDisplayNameForMultipleArraysOfMultipleItemsValueTypes() @@ -187,7 +189,7 @@ public void GetDisplayNameForMultipleArraysOfMultipleItemsValueTypes() string? displayName = dataRow.GetDisplayName(methodInfoMock.Object, dataRow.Data); // Assert - Verify(displayName == "MyMethod ([1,2,3],[4,5,6])"); + displayName.Should().Be("MyMethod ([1,2,3],[4,5,6])"); } public void GetDisplayNameForMultipleArraysOfArraysOfMultipleItems() @@ -201,7 +203,7 @@ public void GetDisplayNameForMultipleArraysOfArraysOfMultipleItems() string? displayName = dataRow.GetDisplayName(methodInfoMock.Object, dataRow.Data); // Assert - Verify(displayName == "MyMethod ([[\"a\",\"b\",\"c\"],[\"d\",\"e\",\"f\"],[\"gh\",\"ij\",\"kl\"]],['m','n','o'],[[\"1\",\"2\",\"3\"],[\"4\",\"5\",\"6\"],[\"7\",\"8\",\"9\"]])"); + displayName.Should().Be("MyMethod ([[\"a\",\"b\",\"c\"],[\"d\",\"e\",\"f\"],[\"gh\",\"ij\",\"kl\"]],['m','n','o'],[[\"1\",\"2\",\"3\"],[\"4\",\"5\",\"6\"],[\"7\",\"8\",\"9\"]])"); } private class DummyDataRowAttribute : DataRowAttribute diff --git a/test/UnitTests/TestFramework.UnitTests/Attributes/DynamicDataAttributeTests.cs b/test/UnitTests/TestFramework.UnitTests/Attributes/DynamicDataAttributeTests.cs index 4354e252b4..4edfc66c98 100644 --- a/test/UnitTests/TestFramework.UnitTests/Attributes/DynamicDataAttributeTests.cs +++ b/test/UnitTests/TestFramework.UnitTests/Attributes/DynamicDataAttributeTests.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 AwesomeAssertions; + using Microsoft.VisualStudio.TestTools.UnitTesting.Resources; using TestFramework.ForTestingMSTest; @@ -25,8 +27,9 @@ public DynamicDataAttributeTests() public void GetDataShouldThrowExceptionIfInvalidPropertyNameIsSpecifiedOrPropertyDoesNotExist() { _dynamicDataAttribute = new DynamicDataAttribute("ABC"); - InvalidOperationException ex = VerifyThrows(() => _dynamicDataAttribute.GetData(_testMethodInfo)); - Verify(ex.Message == string.Format(CultureInfo.InvariantCulture, FrameworkMessages.DynamicDataSourceShouldExistAndBeValid, "ABC", _testMethodInfo.DeclaringType!.FullName)); + Action action = () => _dynamicDataAttribute.GetData(_testMethodInfo); + action.Should().Throw() + .And.Message.Should().Be(string.Format(CultureInfo.InvariantCulture, FrameworkMessages.DynamicDataSourceShouldExistAndBeValid, "ABC", _testMethodInfo.DeclaringType!.FullName)); } public void GetDataShouldReadDataFromProperty() @@ -34,8 +37,8 @@ public void GetDataShouldReadDataFromProperty() MethodInfo methodInfo = _dummyTestClass.GetType().GetTypeInfo().GetDeclaredMethod("TestMethod1")!; _dynamicDataAttribute = new DynamicDataAttribute("ReusableTestDataProperty"); IEnumerable data = _dynamicDataAttribute.GetData(methodInfo); - Verify(data is not null); - Verify(data.ToList().Count == 2); + data.Should().NotBeNull(); + data.ToList().Should().HaveCount(2); } public void GetDataShouldReadDataFromPropertyInDifferentClass() @@ -43,8 +46,8 @@ public void GetDataShouldReadDataFromPropertyInDifferentClass() MethodInfo methodInfo = _dummyTestClass.GetType().GetTypeInfo().GetDeclaredMethod("TestMethod1")!; _dynamicDataAttribute = new DynamicDataAttribute("ReusableTestDataProperty2", typeof(DummyTestClass2)); IEnumerable data = _dynamicDataAttribute.GetData(methodInfo); - Verify(data is not null); - Verify(data.ToList().Count == 2); + data.Should().NotBeNull(); + data.ToList().Should().HaveCount(2); } public void GetDataShouldReadDataFromMethod() @@ -52,8 +55,8 @@ public void GetDataShouldReadDataFromMethod() MethodInfo methodInfo = _dummyTestClass.GetType().GetTypeInfo().GetDeclaredMethod("TestMethod2")!; _dynamicDataAttribute = new DynamicDataAttribute("ReusableTestDataMethod", DynamicDataSourceType.Method); IEnumerable data = _dynamicDataAttribute.GetData(methodInfo); - Verify(data is not null); - Verify(data.ToList().Count == 2); + data.Should().NotBeNull(); + data.ToList().Should().HaveCount(2); } public void GetDataShouldReadDataFromMethodInDifferentClass() @@ -61,17 +64,20 @@ public void GetDataShouldReadDataFromMethodInDifferentClass() MethodInfo methodInfo = _dummyTestClass.GetType().GetTypeInfo().GetDeclaredMethod("TestMethod2")!; _dynamicDataAttribute = new DynamicDataAttribute("ReusableTestDataMethod2", typeof(DummyTestClass2), DynamicDataSourceType.Method); IEnumerable data = _dynamicDataAttribute.GetData(methodInfo); - Verify(data is not null); - Verify(data.ToList().Count == 2); + data.Should().NotBeNull(); + data.ToList().Should().HaveCount(2); } - public void GetDataShouldThrowExceptionIfPropertyReturnsNull() => - VerifyThrows(() => + public void GetDataShouldThrowExceptionIfPropertyReturnsNull() + { + Action action = () => { MethodInfo methodInfo = _dummyTestClass.GetType().GetTypeInfo().GetDeclaredMethod("TestMethod4")!; _dynamicDataAttribute = new DynamicDataAttribute("NullProperty", typeof(DummyTestClass)); _dynamicDataAttribute.GetData(methodInfo); - }); + }; + action.Should().Throw(); + } public void GetDataShouldNotThrowExceptionIfPropertyReturnsEmpty() { @@ -80,23 +86,26 @@ public void GetDataShouldNotThrowExceptionIfPropertyReturnsEmpty() IEnumerable data = _dynamicDataAttribute.GetData(methodInfo); // The callers in AssemblyEnumerator and TestMethodRunner are responsible // for throwing an exception if data is empty and ConsiderEmptyDataSourceAsInconclusive is false. - Verify(!data.Any()); + data.Should().BeEmpty(); } - public void GetDataShouldThrowExceptionIfPropertyDoesNotReturnCorrectType() => - VerifyThrows(() => + public void GetDataShouldThrowExceptionIfPropertyDoesNotReturnCorrectType() + { + Action action = () => { MethodInfo methodInfo = _dummyTestClass.GetType().GetTypeInfo().GetDeclaredMethod("TestMethod3")!; _dynamicDataAttribute = new DynamicDataAttribute("WrongDataTypeProperty", typeof(DummyTestClass)); _dynamicDataAttribute.GetData(methodInfo); - }); + }; + action.Should().Throw(); + } public void GetDisplayNameShouldReturnDisplayName() { object[] data = [1, 2, 3]; string? displayName = _dynamicDataAttribute.GetDisplayName(_testMethodInfo, data); - Verify("TestMethod1 (1,2,3)".SequenceEqual(displayName!)); + displayName.Should().Be("TestMethod1 (1,2,3)"); } public void GetDisplayNameShouldReturnDisplayNameWithDynamicDataDisplayName() @@ -105,7 +114,7 @@ public void GetDisplayNameShouldReturnDisplayNameWithDynamicDataDisplayName() _dynamicDataAttribute.DynamicDataDisplayName = "GetCustomDynamicDataDisplayName"; string? displayName = _dynamicDataAttribute.GetDisplayName(_testMethodInfo, data); - Verify(displayName == "DynamicDataTestWithDisplayName TestMethod1 with 3 parameters"); + displayName.Should().Be("DynamicDataTestWithDisplayName TestMethod1 with 3 parameters"); } public void GetDisplayNameShouldReturnDisplayNameWithDynamicDataDisplayNameInDifferentClass() @@ -115,76 +124,97 @@ public void GetDisplayNameShouldReturnDisplayNameWithDynamicDataDisplayNameInDif _dynamicDataAttribute.DynamicDataDisplayName = "GetCustomDynamicDataDisplayName2"; _dynamicDataAttribute.DynamicDataDisplayNameDeclaringType = typeof(DummyTestClass2); string? displayName = _dynamicDataAttribute.GetDisplayName(_testMethodInfo, data); - Verify(displayName == "DynamicDataTestWithDisplayName TestMethod1 with 3 parameters"); + displayName.Should().Be("DynamicDataTestWithDisplayName TestMethod1 with 3 parameters"); } - public void GetDisplayNameShouldThrowExceptionWithDynamicDataDisplayNameMethodMissingParameters() => - VerifyThrows(() => + public void GetDisplayNameShouldThrowExceptionWithDynamicDataDisplayNameMethodMissingParameters() + { + Action action = () => { object[] data = [1, 2, 3]; _dynamicDataAttribute.DynamicDataDisplayName = "GetDynamicDataDisplayNameWithMissingParameters"; _dynamicDataAttribute.GetDisplayName(_testMethodInfo, data); - }); + }; + action.Should().Throw(); + } - public void GetDisplayNameShouldThrowExceptionWithDynamicDataDisplayNameMethodInvalidReturnType() => - VerifyThrows(() => + public void GetDisplayNameShouldThrowExceptionWithDynamicDataDisplayNameMethodInvalidReturnType() + { + Action action = () => { object[] data = [1, 2, 3]; _dynamicDataAttribute.DynamicDataDisplayName = "GetDynamicDataDisplayNameWithInvalidReturnType"; _dynamicDataAttribute.GetDisplayName(_testMethodInfo, data); - }); + }; + action.Should().Throw(); + } - public void GetDisplayNameShouldThrowExceptionWithDynamicDataDisplayNameMethodInvalidFirstParameterType() => - VerifyThrows(() => + public void GetDisplayNameShouldThrowExceptionWithDynamicDataDisplayNameMethodInvalidFirstParameterType() + { + Action action = () => { object[] data = [1, 2, 3]; _dynamicDataAttribute.DynamicDataDisplayName = "GetDynamicDataDisplayNameWithInvalidFirstParameterType"; _dynamicDataAttribute.GetDisplayName(_testMethodInfo, data); - }); + }; + action.Should().Throw(); + } - public void GetDisplayNameShouldThrowExceptionWithDynamicDataDisplayNameMethodInvalidSecondParameterType() => - VerifyThrows(() => + public void GetDisplayNameShouldThrowExceptionWithDynamicDataDisplayNameMethodInvalidSecondParameterType() + { + Action action = () => { object[] data = [1, 2, 3]; _dynamicDataAttribute.DynamicDataDisplayName = "GetDynamicDataDisplayNameWithInvalidSecondParameterType"; _dynamicDataAttribute.GetDisplayName(_testMethodInfo, data); - }); + }; + action.Should().Throw(); + } - public void GetDisplayNameShouldThrowExceptionWithDynamicDataDisplayNameMethodNonStatic() => - VerifyThrows(() => + public void GetDisplayNameShouldThrowExceptionWithDynamicDataDisplayNameMethodNonStatic() + { + Action action = () => { object[] data = [1, 2, 3]; _dynamicDataAttribute.DynamicDataDisplayName = "GetDynamicDataDisplayNameNonStatic"; _dynamicDataAttribute.GetDisplayName(_testMethodInfo, data); - }); + }; + action.Should().Throw(); + } - public void GetDisplayNameShouldThrowExceptionWithDynamicDataDisplayNameMethodPrivate() => - VerifyThrows(() => + public void GetDisplayNameShouldThrowExceptionWithDynamicDataDisplayNameMethodPrivate() + { + Action action = () => { object[] data = [1, 2, 3]; _dynamicDataAttribute.DynamicDataDisplayName = "GetDynamicDataDisplayNamePrivate"; _dynamicDataAttribute.GetDisplayName(_testMethodInfo, data); - }); + }; + action.Should().Throw(); + } - public void GetDisplayNameShouldThrowExceptionWithMissingDynamicDataDisplayNameMethod() => - VerifyThrows(() => + public void GetDisplayNameShouldThrowExceptionWithMissingDynamicDataDisplayNameMethod() + { + Action action = () => { object[] data = [1, 2, 3]; _dynamicDataAttribute.DynamicDataDisplayName = "MissingCustomDynamicDataDisplayName"; _dynamicDataAttribute.GetDisplayName(_testMethodInfo, data); - }); + }; + action.Should().Throw(); + } public void GetDisplayNameShouldReturnEmptyStringIfDataIsNull() { string? displayName = _dynamicDataAttribute.GetDisplayName(_testMethodInfo, null); - Verify(displayName is null); + displayName.Should().BeNull(); } public void GetDisplayNameHandlesNullValues() @@ -194,43 +224,43 @@ public void GetDisplayNameHandlesNullValues() string?[] data2 = ["value1", null, "value2"]; string? displayName = _dynamicDataAttribute.GetDisplayName(_testMethodInfo, data); - Verify(displayName == "TestMethod1 (\"value1\",\"value2\",null)"); + displayName.Should().Be("TestMethod1 (\"value1\",\"value2\",null)"); displayName = _dynamicDataAttribute.GetDisplayName(_testMethodInfo, data1); - Verify(displayName == "TestMethod1 (null,\"value1\",\"value2\")"); + displayName.Should().Be("TestMethod1 (null,\"value1\",\"value2\")"); displayName = _dynamicDataAttribute.GetDisplayName(_testMethodInfo, data2); - Verify(displayName == "TestMethod1 (\"value1\",null,\"value2\")"); + displayName.Should().Be("TestMethod1 (\"value1\",null,\"value2\")"); } public void GetDisplayNameForArrayOfMultipleItems() { string? displayName = _dynamicDataAttribute.GetDisplayName(_testMethodInfo, [new[] { "a", "b", "c" }]); - Verify(displayName == "TestMethod1 ([\"a\",\"b\",\"c\"])"); + displayName.Should().Be("TestMethod1 ([\"a\",\"b\",\"c\"])"); } public void GetDisplayNameForMultipleArraysOfOneItem() { string? displayName = _dynamicDataAttribute.GetDisplayName(_testMethodInfo, [new[] { "a" }, new[] { "1" }]); - Verify(displayName == "TestMethod1 ([\"a\"],[\"1\"])"); + displayName.Should().Be("TestMethod1 ([\"a\"],[\"1\"])"); } public void GetDisplayNameForMultipleArraysOfMultipleItems() { string? displayName = _dynamicDataAttribute.GetDisplayName(_testMethodInfo, [new[] { "a", "b", "c" }, new[] { "1", "2", "3" }]); - Verify(displayName == "TestMethod1 ([\"a\",\"b\",\"c\"],[\"1\",\"2\",\"3\"])"); + displayName.Should().Be("TestMethod1 ([\"a\",\"b\",\"c\"],[\"1\",\"2\",\"3\"])"); } public void GetDisplayNameForMultipleArraysOfMultipleItemsValueTypes() { string? displayName = _dynamicDataAttribute.GetDisplayName(_testMethodInfo, [new[] { 1, 2, 3 }, new[] { 4, 5, 6 }]); - Verify(displayName == "TestMethod1 ([1,2,3],[4,5,6])"); + displayName.Should().Be("TestMethod1 ([1,2,3],[4,5,6])"); } public void GetDisplayNameForMultipleArraysOfArraysOfMultipleItems() { string? displayName = _dynamicDataAttribute.GetDisplayName(_testMethodInfo, [new[] { ["a", "b", "c"], ["d", "e", "f"], new[] { "gh", "ij", "kl" } }, new[] { 'm', 'n', 'o' }, new[] { ["1", "2", "3"], ["4", "5", "6"], new[] { "7", "8", "9" } }]); - Verify(displayName == "TestMethod1 ([[\"a\",\"b\",\"c\"],[\"d\",\"e\",\"f\"],[\"gh\",\"ij\",\"kl\"]],['m','n','o'],[[\"1\",\"2\",\"3\"],[\"4\",\"5\",\"6\"],[\"7\",\"8\",\"9\"]])"); + displayName.Should().Be("TestMethod1 ([[\"a\",\"b\",\"c\"],[\"d\",\"e\",\"f\"],[\"gh\",\"ij\",\"kl\"]],['m','n','o'],[[\"1\",\"2\",\"3\"],[\"4\",\"5\",\"6\"],[\"7\",\"8\",\"9\"]])"); } public void DynamicDataSource_WithTuple_Works() @@ -268,8 +298,8 @@ public void GetDataShouldReadDataFromField() MethodInfo methodInfo = _dummyTestClass.GetType().GetTypeInfo().GetDeclaredMethod("TestMethod1")!; _dynamicDataAttribute = new DynamicDataAttribute("ReusableTestDataField", DynamicDataSourceType.Field); IEnumerable data = _dynamicDataAttribute.GetData(methodInfo); - Verify(data is not null); - Verify(data.ToList().Count == 2); + data.Should().NotBeNull(); + data.ToList().Should().HaveCount(2); } public void GetDataShouldReadDataFromFieldInDifferentClass() @@ -277,8 +307,8 @@ public void GetDataShouldReadDataFromFieldInDifferentClass() MethodInfo methodInfo = _dummyTestClass.GetType().GetTypeInfo().GetDeclaredMethod("TestMethod1")!; _dynamicDataAttribute = new DynamicDataAttribute("ReusableTestDataField2", typeof(DummyTestClass2), DynamicDataSourceType.Field); IEnumerable data = _dynamicDataAttribute.GetData(methodInfo); - Verify(data is not null); - Verify(data.ToList().Count == 2); + data.Should().NotBeNull(); + data.ToList().Should().HaveCount(2); } public void GetDataShouldReadDataFromFieldInAutoDetectMode() @@ -286,17 +316,20 @@ public void GetDataShouldReadDataFromFieldInAutoDetectMode() MethodInfo methodInfo = _dummyTestClass.GetType().GetTypeInfo().GetDeclaredMethod("TestMethod1")!; _dynamicDataAttribute = new DynamicDataAttribute("ReusableTestDataField"); IEnumerable data = _dynamicDataAttribute.GetData(methodInfo); - Verify(data is not null); - Verify(data.ToList().Count == 2); + data.Should().NotBeNull(); + data.ToList().Should().HaveCount(2); } - public void GetDataShouldThrowExceptionIfFieldReturnsNull() => - VerifyThrows(() => + public void GetDataShouldThrowExceptionIfFieldReturnsNull() + { + Action action = () => { MethodInfo methodInfo = _dummyTestClass.GetType().GetTypeInfo().GetDeclaredMethod("TestMethod1")!; _dynamicDataAttribute = new DynamicDataAttribute("NullField", typeof(DummyTestClass), DynamicDataSourceType.Field); _dynamicDataAttribute.GetData(methodInfo); - }); + }; + action.Should().Throw(); + } public void GetDataShouldNotThrowExceptionIfFieldReturnsEmpty() { @@ -305,24 +338,30 @@ public void GetDataShouldNotThrowExceptionIfFieldReturnsEmpty() IEnumerable data = _dynamicDataAttribute.GetData(methodInfo); // The callers in AssemblyEnumerator and TestMethodRunner are responsible // for throwing an exception if data is empty and ConsiderEmptyDataSourceAsInconclusive is false. - Verify(!data.Any()); + data.Should().BeEmpty(); } - public void GetDataShouldThrowExceptionIfFieldDoesNotReturnCorrectType() => - VerifyThrows(() => + public void GetDataShouldThrowExceptionIfFieldDoesNotReturnCorrectType() + { + Action action = () => { MethodInfo methodInfo = _dummyTestClass.GetType().GetTypeInfo().GetDeclaredMethod("TestMethod1")!; _dynamicDataAttribute = new DynamicDataAttribute("WrongDataTypeField", typeof(DummyTestClass), DynamicDataSourceType.Field); _dynamicDataAttribute.GetData(methodInfo); - }); + }; + action.Should().Throw(); + } - public void GetDataShouldThrowExceptionIfFieldIsNotStatic() => - VerifyThrows(() => + public void GetDataShouldThrowExceptionIfFieldIsNotStatic() + { + Action action = () => { MethodInfo methodInfo = _dummyTestClass.GetType().GetTypeInfo().GetDeclaredMethod("TestMethod1")!; _dynamicDataAttribute = new DynamicDataAttribute("NonStaticField", typeof(DummyTestClass), DynamicDataSourceType.Field); _dynamicDataAttribute.GetData(methodInfo); - }); + }; + action.Should().Throw(); + } /// /// The dummy test class. diff --git a/test/UnitTests/TestFramework.UnitTests/Attributes/ExpectedExceptionAttributeTests.cs b/test/UnitTests/TestFramework.UnitTests/Attributes/ExpectedExceptionAttributeTests.cs index 30d558a0c7..dab8025581 100644 --- a/test/UnitTests/TestFramework.UnitTests/Attributes/ExpectedExceptionAttributeTests.cs +++ b/test/UnitTests/TestFramework.UnitTests/Attributes/ExpectedExceptionAttributeTests.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 AwesomeAssertions; + using TestFramework.ForTestingMSTest; namespace UnitTestFramework.Tests; @@ -15,17 +17,19 @@ public class ExpectedExceptionAttributeTests : TestContainer /// public void ExpectedExceptionAttributeConstructorShouldThrowArgumentNullExceptionWhenExceptionTypeIsNull() { - static void A() => _ = new ExpectedExceptionAttribute(null!, "Dummy"); + Action action = () => _ = new ExpectedExceptionAttribute(null!, "Dummy"); - Exception ex = VerifyThrows(A); - Verify(ex is ArgumentNullException); + action.Should().Throw(); } /// /// ExpectedExceptionAttribute constructor should throw ArgumentNullException when parameter exceptionType = typeof(AnyClassNotDerivedFromExceptionClass). /// - public void ExpectedExceptionAttributeConstructerShouldThrowArgumentException() => - VerifyThrows(() => _ = new ExpectedExceptionAttribute(typeof(ExpectedExceptionAttributeTests), "Dummy")); + public void ExpectedExceptionAttributeConstructerShouldThrowArgumentException() + { + Action action = () => _ = new ExpectedExceptionAttribute(typeof(ExpectedExceptionAttributeTests), "Dummy"); + action.Should().Throw(); + } /// /// ExpectedExceptionAttribute constructor should not throw exception when parameter exceptionType = typeof(AnyClassDerivedFromExceptionClass). @@ -38,7 +42,7 @@ public void GetExceptionMsgShouldReturnExceptionMessage() Exception ex = new("Dummy Exception"); string actualMessage = UtfHelper.GetExceptionMsg(ex); string expectedMessage = "System.Exception: Dummy Exception"; - Verify(expectedMessage == actualMessage); + actualMessage.Should().Be(expectedMessage); } public void GetExceptionMsgShouldReturnInnerExceptionMessageAsWellIfPresent() @@ -47,7 +51,7 @@ public void GetExceptionMsgShouldReturnInnerExceptionMessageAsWellIfPresent() Exception ex = new("Dummy Exception", innerException); string actualMessage = UtfHelper.GetExceptionMsg(ex); string expectedMessage = "System.Exception: Dummy Exception ---> System.DivideByZeroException: Attempted to divide by zero."; - Verify(expectedMessage == actualMessage); + actualMessage.Should().Be(expectedMessage); } public void GetExceptionMsgShouldReturnInnerExceptionMessageRecursivelyIfPresent() @@ -57,7 +61,7 @@ public void GetExceptionMsgShouldReturnInnerExceptionMessageRecursivelyIfPresent Exception ex = new("FirstLevelException", innerException); string actualMessage = UtfHelper.GetExceptionMsg(ex); string expectedMessage = "System.Exception: FirstLevelException ---> System.DivideByZeroException: SecondLevel Exception ---> System.IndexOutOfRangeException: ThirdLevelException"; - Verify(expectedMessage == actualMessage); + actualMessage.Should().Be(expectedMessage); } } diff --git a/test/UnitTests/TestFramework.UnitTests/Attributes/ExpectedExceptionBaseAttributeTests.cs b/test/UnitTests/TestFramework.UnitTests/Attributes/ExpectedExceptionBaseAttributeTests.cs index 73da72f21a..6f85d99b5a 100644 --- a/test/UnitTests/TestFramework.UnitTests/Attributes/ExpectedExceptionBaseAttributeTests.cs +++ b/test/UnitTests/TestFramework.UnitTests/Attributes/ExpectedExceptionBaseAttributeTests.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 AwesomeAssertions; + using TestFramework.ForTestingMSTest; namespace UnitTestFramework.Tests; @@ -19,17 +21,18 @@ public class ExpectedExceptionBaseAttributeTests : TestContainer /// public void RethrowIfAssertExceptionThrowsExceptionOnAssertFailure() { - void A() => _sut.RethrowIfAssertException(new AssertFailedException()); - - Exception ex = VerifyThrows(A); - Verify(ex is AssertFailedException); + Action action = () => _sut.RethrowIfAssertException(new AssertFailedException()); + action.Should().Throw(); } /// /// RethrowIfAssertException function will throw AssertFailedException if we pass AssertInconclusiveException as parameter in it. /// - public void RethrowIfAssertExceptionThrowsExceptionOnAssertInconclusive() => - VerifyThrows(() => _sut.RethrowIfAssertException(new AssertInconclusiveException())); + public void RethrowIfAssertExceptionThrowsExceptionOnAssertInconclusive() + { + Action action = () => _sut.RethrowIfAssertException(new AssertInconclusiveException()); + action.Should().Throw(); + } public void VerifyCorrectMessageIsGettingSetInVariableNoExceptionMessage() { @@ -38,7 +41,7 @@ public void VerifyCorrectMessageIsGettingSetInVariableNoExceptionMessage() string result = _sut.GetNoExceptionMessage(); - Verify(expected == result); + result.Should().Be(expected); } public void VerifyEmptyMessageIsGettingSetInVariableNoExceptionMessage() @@ -47,7 +50,7 @@ public void VerifyEmptyMessageIsGettingSetInVariableNoExceptionMessage() string result = _sut.GetNoExceptionMessage(); - Verify(string.IsNullOrEmpty(result)); + result.Should().BeNullOrEmpty(); } } diff --git a/test/UnitTests/TestFramework.UnitTests/GitHubWorkItemTests.cs b/test/UnitTests/TestFramework.UnitTests/GitHubWorkItemTests.cs index 35d607797c..39a5621502 100644 --- a/test/UnitTests/TestFramework.UnitTests/GitHubWorkItemTests.cs +++ b/test/UnitTests/TestFramework.UnitTests/GitHubWorkItemTests.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. +using AwesomeAssertions; + using TestFramework.ForTestingMSTest; namespace Microsoft.VisualStudio.TestPlatform.TestFramework.UnitTests; @@ -11,71 +13,71 @@ public void GitHubWorkItemAttributeShouldExtractIdFromUrl_IssueUrl() { string url = "https://github.com/microsoft/testfx/issues/1234"; GitHubWorkItemAttribute attribute = new(url); - Verify(attribute.Url == url); - Verify(attribute.Id == 1234); + attribute.Url.Should().Be(url); + attribute.Id.Should().Be(1234); } public void GitHubWorkItemAttributeShouldExtractIdFromUrl_IssueUrlWithEndingSlash() { string url = "https://github.com/microsoft/testfx/issues/1234/"; GitHubWorkItemAttribute attribute = new(url); - Verify(attribute.Url == url); - Verify(attribute.Id == 1234); + attribute.Url.Should().Be(url); + attribute.Id.Should().Be(1234); } public void GitHubWorkItemAttributeShouldExtractIdFromUrl_IssueUrlWithComment() { string url = "https://github.com/microsoft/testfx/issues/1234#issuecomment-2581012838"; GitHubWorkItemAttribute attribute = new(url); - Verify(attribute.Url == url); - Verify(attribute.Id == 1234); + attribute.Url.Should().Be(url); + attribute.Id.Should().Be(1234); } public void GitHubWorkItemAttributeShouldExtractIdFromUrl_PRUrl() { string url = "https://github.com/microsoft/testfx/pull/1234"; GitHubWorkItemAttribute attribute = new(url); - Verify(attribute.Url == url); - Verify(attribute.Id == 1234); + attribute.Url.Should().Be(url); + attribute.Id.Should().Be(1234); } public void GitHubWorkItemAttributeShouldExtractIdFromUrl_PRUrlWithEndingSlash() { string url = "https://github.com/microsoft/testfx/pull/1234/"; GitHubWorkItemAttribute attribute = new(url); - Verify(attribute.Url == url); - Verify(attribute.Id == 1234); + attribute.Url.Should().Be(url); + attribute.Id.Should().Be(1234); } public void GitHubWorkItemAttributeShouldExtractIdFromUrl_PRUrlWithComment() { string url = "https://github.com/microsoft/testfx/pull/1234#discussion_r1932733213"; GitHubWorkItemAttribute attribute = new(url); - Verify(attribute.Url == url); - Verify(attribute.Id == 1234); + attribute.Url.Should().Be(url); + attribute.Id.Should().Be(1234); } public void GitHubWorkItemAttributeShouldExtractIdFromUrl_DiscussionUrl() { string url = "https://github.com/microsoft/testfx/discussions/1234"; GitHubWorkItemAttribute attribute = new(url); - Verify(attribute.Url == url); - Verify(attribute.Id == 1234); + attribute.Url.Should().Be(url); + attribute.Id.Should().Be(1234); } public void GitHubWorkItemAttributeShouldExtractIdFromUrl_DiscussionUrlWithEndingSlash() { string url = "https://github.com/microsoft/testfx/discussions/1234/"; GitHubWorkItemAttribute attribute = new(url); - Verify(attribute.Url == url); - Verify(attribute.Id == 1234); + attribute.Url.Should().Be(url); + attribute.Id.Should().Be(1234); } public void GitHubWorkItemAttributeShouldExtractIdFromUrl_DiscussionUrlWithComment() { string url = "https://github.com/microsoft/testfx/discussions/1234#discussioncomment-11865020"; GitHubWorkItemAttribute attribute = new(url); - Verify(attribute.Url == url); - Verify(attribute.Id == 1234); + attribute.Url.Should().Be(url); + attribute.Id.Should().Be(1234); } } diff --git a/test/UnitTests/TestFramework.UnitTests/LoggerTests.cs b/test/UnitTests/TestFramework.UnitTests/LoggerTests.cs index b0e62e3c04..8ad336959b 100644 --- a/test/UnitTests/TestFramework.UnitTests/LoggerTests.cs +++ b/test/UnitTests/TestFramework.UnitTests/LoggerTests.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 AwesomeAssertions; + using Microsoft.VisualStudio.TestTools.UnitTesting.Logging; using TestFramework.ForTestingMSTest; @@ -12,15 +14,15 @@ public sealed class LoggerTests : TestContainer public void LogMessageWhenFormatIsNullShouldThrow() { Logger.OnLogMessage += message => { }; - ArgumentNullException ex = VerifyThrows(() => Logger.LogMessage(null!, "arg1")); - Verify(ex.Message.Contains("format")); + Action act = () => Logger.LogMessage(null!, "arg1"); + act.Should().Throw().WithMessage("*format*"); } public void LogMessageWhenArgsIsNullShouldThrow() { Logger.OnLogMessage += message => { }; - ArgumentNullException ex = VerifyThrows(() => Logger.LogMessage("foo", null!)); - Verify(ex.Message.Contains("args")); + Action act = () => Logger.LogMessage("foo", null!); + act.Should().Throw().WithMessage("*args*"); } public void LogMessageWhenFormatIsSimpleMessageAndNoArgsShouldCallEvent() @@ -28,7 +30,7 @@ public void LogMessageWhenFormatIsSimpleMessageAndNoArgsShouldCallEvent() string? calledWith = null; Logger.OnLogMessage += message => calledWith = message; Logger.LogMessage("message"); - Verify(calledWith == "message"); + calledWith.Should().Be("message"); } public void LogMessageWhenFormatIsFormateMessageWithArgsShouldCallEvent() @@ -36,7 +38,7 @@ public void LogMessageWhenFormatIsFormateMessageWithArgsShouldCallEvent() string? calledWith = null; Logger.OnLogMessage += message => calledWith = message; Logger.LogMessage("message {0}", 1); - Verify(calledWith == "message 1"); + calledWith.Should().Be("message 1"); } public void LogMessageWhenFormatContainsCurlyBrace() @@ -44,6 +46,6 @@ public void LogMessageWhenFormatContainsCurlyBrace() string? calledWith = null; Logger.OnLogMessage += message => calledWith = message; Logger.LogMessage("{ A"); - Verify(calledWith == "{ A"); + calledWith.Should().Be("{ A"); } } diff --git a/test/UnitTests/TestFramework.UnitTests/TestDataRowTests.cs b/test/UnitTests/TestFramework.UnitTests/TestDataRowTests.cs index 44f6138dec..e2a6ea8dd2 100644 --- a/test/UnitTests/TestFramework.UnitTests/TestDataRowTests.cs +++ b/test/UnitTests/TestFramework.UnitTests/TestDataRowTests.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 AwesomeAssertions; + using TestFramework.ForTestingMSTest; namespace Microsoft.VisualStudio.TestPlatform.TestFramework.UnitTests; @@ -12,10 +14,10 @@ public void TestDataRowShouldInitializeWithValue() string value = "test_value"; var testDataRow = new TestDataRow(value); - Verify(testDataRow.Value == value); - Verify(testDataRow.IgnoreMessage == null); - Verify(testDataRow.DisplayName == null); - Verify(testDataRow.TestCategories == null); + testDataRow.Value.Should().Be(value); + testDataRow.IgnoreMessage.Should().BeNull(); + testDataRow.DisplayName.Should().BeNull(); + testDataRow.TestCategories.Should().BeNull(); } public void TestDataRowShouldAllowSettingTestCategories() @@ -26,10 +28,10 @@ public void TestDataRowShouldAllowSettingTestCategories() testDataRow.TestCategories = testCategories; - Verify(testDataRow.TestCategories == testCategories); - Verify(testDataRow.TestCategories.Count == 2); - Verify(testDataRow.TestCategories.Contains("Category1")); - Verify(testDataRow.TestCategories.Contains("Category2")); + testDataRow.TestCategories.Should().BeSameAs(testCategories); + testDataRow.TestCategories.Should().HaveCount(2); + testDataRow.TestCategories.Should().Contain("Category1"); + testDataRow.TestCategories.Should().Contain("Category2"); } public void TestDataRowShouldImplementITestDataRowForTestCategories() @@ -41,10 +43,10 @@ public void TestDataRowShouldImplementITestDataRowForTestCategories() ITestDataRow dataRow = testDataRow; - Verify(dataRow.TestCategories != null); - Verify(dataRow.TestCategories.Count == 2); - Verify(dataRow.TestCategories.Contains("Integration")); - Verify(dataRow.TestCategories.Contains("Unit")); + dataRow.TestCategories.Should().NotBeNull(); + dataRow.TestCategories.Should().HaveCount(2); + dataRow.TestCategories.Should().Contain("Integration"); + dataRow.TestCategories.Should().Contain("Unit"); } public void TestDataRowShouldAllowNullTestCategories() @@ -55,10 +57,10 @@ public void TestDataRowShouldAllowNullTestCategories() TestCategories = null, }; - Verify(testDataRow.TestCategories == null); + testDataRow.TestCategories.Should().BeNull(); ITestDataRow dataRow = testDataRow; - Verify(dataRow.TestCategories == null); + dataRow.TestCategories.Should().BeNull(); } public void TestDataRowShouldAllowEmptyTestCategories() @@ -69,11 +71,11 @@ public void TestDataRowShouldAllowEmptyTestCategories() testDataRow.TestCategories = emptyCategories; - Verify(testDataRow.TestCategories == emptyCategories); - Verify(testDataRow.TestCategories.Count == 0); + testDataRow.TestCategories.Should().BeSameAs(emptyCategories); + testDataRow.TestCategories.Should().HaveCount(0); ITestDataRow dataRow = testDataRow; - Verify(dataRow.TestCategories != null); - Verify(dataRow.TestCategories.Count == 0); + dataRow.TestCategories.Should().NotBeNull(); + dataRow.TestCategories.Should().HaveCount(0); } } diff --git a/test/UnitTests/TestFramework.UnitTests/TestResultTests.cs b/test/UnitTests/TestFramework.UnitTests/TestResultTests.cs index 99a9c47079..9dff5b841d 100644 --- a/test/UnitTests/TestFramework.UnitTests/TestResultTests.cs +++ b/test/UnitTests/TestFramework.UnitTests/TestResultTests.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 AwesomeAssertions; + using TestFramework.ForTestingMSTest; namespace Microsoft.VisualStudio.TestPlatform.TestFramework.UnitTests; @@ -18,20 +20,20 @@ public void SettingTestFailureExceptionShouldAggregatePreviouslySetExceptions() }; // We use GetType() == typeof(...) to do a strict type match. - Verify(testResult.TestFailureException.GetType() == typeof(InvalidOperationException)); - Verify(testResult.TestFailureException.Message == "Failure1"); + testResult.TestFailureException.Should().BeOfType(); + testResult.TestFailureException.Message.Should().Be("Failure1"); testResult.TestFailureException = new ArgumentException("Failure2"); var aggregateException = (AggregateException)testResult.TestFailureException; - Verify(aggregateException.InnerExceptions.Count == 2); - Verify(aggregateException.InnerExceptions[0].Message == "Failure1"); - Verify(aggregateException.InnerExceptions[1].Message == "Failure2"); + aggregateException.InnerExceptions.Should().HaveCount(2); + aggregateException.InnerExceptions[0].Message.Should().Be("Failure1"); + aggregateException.InnerExceptions[1].Message.Should().Be("Failure2"); testResult.TestFailureException = new ArgumentException("Failure3"); aggregateException = (AggregateException)testResult.TestFailureException; - Verify(aggregateException.InnerExceptions.Count == 3); - Verify(aggregateException.InnerExceptions[0].Message == "Failure1"); - Verify(aggregateException.InnerExceptions[1].Message == "Failure2"); - Verify(aggregateException.InnerExceptions[2].Message == "Failure3"); + aggregateException.InnerExceptions.Should().HaveCount(3); + aggregateException.InnerExceptions[0].Message.Should().Be("Failure1"); + aggregateException.InnerExceptions[1].Message.Should().Be("Failure2"); + aggregateException.InnerExceptions[2].Message.Should().Be("Failure3"); } } From a40cda8fbb2a6cea333bd4215ee2c7a13fd4a042 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Wed, 3 Sep 2025 09:30:10 +0200 Subject: [PATCH 464/541] More pipe improvements (#6498) --- .../IPC/NamedPipeClient.cs | 8 ++- .../IPC/NamedPipeServer.cs | 54 ++++++++++--------- 2 files changed, 36 insertions(+), 26 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Platform/IPC/NamedPipeClient.cs b/src/Platform/Microsoft.Testing.Platform/IPC/NamedPipeClient.cs index 9ed2f8d971..edcab5d062 100644 --- a/src/Platform/Microsoft.Testing.Platform/IPC/NamedPipeClient.cs +++ b/src/Platform/Microsoft.Testing.Platform/IPC/NamedPipeClient.cs @@ -18,6 +18,12 @@ namespace Microsoft.Testing.Platform.IPC; #pragma warning disable CA1416 // Validate platform compatibility internal sealed class NamedPipeClient : NamedPipeBase, IClient { + private const PipeOptions CurrentUserPipeOptions = PipeOptions.None +#if NET + | PipeOptions.CurrentUserOnly +#endif + ; + private readonly NamedPipeClientStream _namedPipeClientStream; private readonly SemaphoreSlim _lock = new(1, 1); @@ -36,7 +42,7 @@ public NamedPipeClient(string name) public NamedPipeClient(string name, IEnvironment environment) { Guard.NotNull(name); - _namedPipeClientStream = new(".", name, PipeDirection.InOut); + _namedPipeClientStream = new(".", name, PipeDirection.InOut, CurrentUserPipeOptions); PipeName = name; _environment = environment; } diff --git a/src/Platform/Microsoft.Testing.Platform/IPC/NamedPipeServer.cs b/src/Platform/Microsoft.Testing.Platform/IPC/NamedPipeServer.cs index 2d2a8f0aa4..27b578ad8f 100644 --- a/src/Platform/Microsoft.Testing.Platform/IPC/NamedPipeServer.cs +++ b/src/Platform/Microsoft.Testing.Platform/IPC/NamedPipeServer.cs @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. -#if NET -using System.Buffers; -#endif using System.IO.Pipes; using Microsoft.Testing.Platform.Helpers; @@ -17,6 +14,14 @@ namespace Microsoft.Testing.Platform.IPC; internal sealed class NamedPipeServer : NamedPipeBase, IServer { +#pragma warning disable CA1416 // Validate platform compatibility + private const PipeOptions AsyncCurrentUserPipeOptions = PipeOptions.Asynchronous +#if NET + | PipeOptions.CurrentUserOnly +#endif + ; +#pragma warning restore CA1416 // Validate platform compatibility + private readonly Func> _callback; private readonly IEnvironment _environment; private readonly NamedPipeServerStream _namedPipeServerStream; @@ -26,6 +31,9 @@ internal sealed class NamedPipeServer : NamedPipeBase, IServer private readonly MemoryStream _serializationBuffer = new(); private readonly MemoryStream _messageBuffer = new(); private readonly byte[] _readBuffer = new byte[250000]; +#if NET + private readonly byte[] _sizeOfIntArray = new byte[sizeof(int)]; +#endif private Task? _loopTask; private bool _disposed; @@ -62,7 +70,7 @@ public NamedPipeServer( { Guard.NotNull(pipeNameDescription); #pragma warning disable CA1416 // Validate platform compatibility - _namedPipeServerStream = new((PipeName = pipeNameDescription).Name, PipeDirection.InOut, maxNumberOfServerInstances, PipeTransmissionMode.Byte, PipeOptions.Asynchronous); + _namedPipeServerStream = new((PipeName = pipeNameDescription).Name, PipeDirection.InOut, maxNumberOfServerInstances, PipeTransmissionMode.Byte, AsyncCurrentUserPipeOptions); #pragma warning restore CA1416 _callback = callback; _environment = environment; @@ -142,6 +150,11 @@ private async Task InternalLoopAsync(CancellationToken cancellationToken) if (currentMessageSize == 0) { // We need to read the message size, first 4 bytes + if (currentReadBytes < sizeof(int)) + { + throw ApplicationStateGuard.Unreachable(); + } + currentMessageSize = BitConverter.ToInt32(_readBuffer, 0); missingBytesToReadOfCurrentChunk = currentReadBytes - sizeof(int); missingBytesToReadOfWholeMessage = currentMessageSize; @@ -159,6 +172,11 @@ private async Task InternalLoopAsync(CancellationToken cancellationToken) missingBytesToReadOfWholeMessage -= missingBytesToReadOfCurrentChunk; } + if (missingBytesToReadOfWholeMessage < 0) + { + throw ApplicationStateGuard.Unreachable(); + } + // If we have read all the message, we can deserialize it if (missingBytesToReadOfWholeMessage == 0) { @@ -196,34 +214,20 @@ private async Task InternalLoopAsync(CancellationToken cancellationToken) // Write the message size #if NET - byte[] bytes = ArrayPool.Shared.Rent(sizeof(int)); - try - { - ApplicationStateGuard.Ensure(BitConverter.TryWriteBytes(bytes, sizeOfTheWholeMessage), PlatformResources.UnexpectedExceptionDuringByteConversionErrorMessage); - - await _messageBuffer.WriteAsync(bytes.AsMemory(0, sizeof(int)), cancellationToken).ConfigureAwait(false); - } - finally - { - ArrayPool.Shared.Return(bytes); - } + byte[] bytes = _sizeOfIntArray; + ApplicationStateGuard.Ensure(BitConverter.TryWriteBytes(bytes, sizeOfTheWholeMessage), PlatformResources.UnexpectedExceptionDuringByteConversionErrorMessage); + ApplicationStateGuard.Ensure(bytes.Length == sizeof(int)); + await _messageBuffer.WriteAsync(bytes, cancellationToken).ConfigureAwait(false); #else await _messageBuffer.WriteAsync(BitConverter.GetBytes(sizeOfTheWholeMessage), 0, sizeof(int), cancellationToken).ConfigureAwait(false); #endif // Write the serializer id #if NET - bytes = ArrayPool.Shared.Rent(sizeof(int)); - try - { - ApplicationStateGuard.Ensure(BitConverter.TryWriteBytes(bytes, responseNamedPipeSerializer.Id), PlatformResources.UnexpectedExceptionDuringByteConversionErrorMessage); + bytes = _sizeOfIntArray; + ApplicationStateGuard.Ensure(BitConverter.TryWriteBytes(bytes, responseNamedPipeSerializer.Id), PlatformResources.UnexpectedExceptionDuringByteConversionErrorMessage); - await _messageBuffer.WriteAsync(bytes.AsMemory(0, sizeof(int)), cancellationToken).ConfigureAwait(false); - } - finally - { - ArrayPool.Shared.Return(bytes); - } + await _messageBuffer.WriteAsync(bytes.AsMemory(0, sizeof(int)), cancellationToken).ConfigureAwait(false); #else await _messageBuffer.WriteAsync(BitConverter.GetBytes(responseNamedPipeSerializer.Id), 0, sizeof(int), cancellationToken).ConfigureAwait(false); #endif From 7804d20d423f66ebd6d6f968fab4f6be52cada48 Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Wed, 3 Sep 2025 10:16:19 +0200 Subject: [PATCH 465/541] [main] Update dependencies from microsoft/testfx (#6496) Co-authored-by: dotnet-maestro[bot] Co-authored-by: Youssef1313 --- eng/Version.Details.xml | 8 ++++---- eng/Versions.props | 4 ++-- .../MSBuildTests.ConfigurationFile.cs | 3 ++- .../TimeoutTests.cs | 6 +++--- 4 files changed, 11 insertions(+), 10 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index 70373e384f..b9a192b211 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -17,13 +17,13 @@ https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage 55eaeaf5a193df238f4437a9b2889da77056347d - + https://github.com/microsoft/testfx - 8d29291af97543579834e9109768c5ee89f63638 + 0d5aa69d6b2cbeebff30536a22d31f4bd7ecf684 - + https://github.com/microsoft/testfx - 8d29291af97543579834e9109768c5ee89f63638 + 0d5aa69d6b2cbeebff30536a22d31f4bd7ecf684 diff --git a/eng/Versions.props b/eng/Versions.props index 19be8a7fd4..2e5412e4e7 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -10,7 +10,7 @@ 11.0.0-beta.25452.3 18.0.0-preview.25452.1 - 3.11.0-preview.25451.2 - 1.9.0-preview.25451.2 + 3.11.0-preview.25452.4 + 1.9.0-preview.25452.4 diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/MSBuildTests.ConfigurationFile.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/MSBuildTests.ConfigurationFile.cs index 12ea1b40ee..31da865173 100644 --- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/MSBuildTests.ConfigurationFile.cs +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/MSBuildTests.ConfigurationFile.cs @@ -28,7 +28,8 @@ public async Task ConfigFileGeneration_CorrectlyCreateAndCacheAndCleaned(string compilationResult = await DotnetCli.RunAsync($"{(verb == Verb.publish ? $"publish -f {tfm}" : "build")} -v:normal -nodeReuse:false {testAsset.TargetAssetPath} -c {compilationMode}", AcceptanceFixture.NuGetGlobalPackagesFolder.Path); Assert.IsTrue(File.Exists(generatedConfigurationFile)); Assert.AreEqual(ConfigurationContent.Trim(), File.ReadAllText(generatedConfigurationFile).Trim()); - compilationResult.StandardOutput.Contains("Microsoft Testing Platform configuration file written"); + // Assert is failing, probably the MSBuild regression which is being fixed in https://github.com/dotnet/msbuild/pull/12431 ? + // compilationResult.AssertOutputContains("Microsoft Testing Platform configuration file written"); Assert.IsTrue(Regex.IsMatch( compilationResult.StandardOutput, """ diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/TimeoutTests.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/TimeoutTests.cs index 334a4f09e0..b7af7d4a4c 100644 --- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/TimeoutTests.cs +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/TimeoutTests.cs @@ -14,7 +14,7 @@ public async Task TimeoutWithInvalidArg_WithoutLetterSuffix_OutputInvalidMessage TestHostResult testHostResult = await testHost.ExecuteAsync("--timeout 5"); testHostResult.AssertExitCodeIs(ExitCodes.InvalidCommandLine); - testHostResult.StandardError.Contains("'timeout' option should have one argument as string in the format [h|m|s] where 'value' is float"); + testHostResult.AssertOutputContains("'timeout' option should have one argument as string in the format [h|m|s] where 'value' is float"); } [DynamicData(nameof(TargetFrameworks.AllForDynamicData), typeof(TargetFrameworks))] @@ -25,7 +25,7 @@ public async Task TimeoutWithInvalidArg_WithInvalidLetterSuffix_OutputInvalidMes TestHostResult testHostResult = await testHost.ExecuteAsync("--timeout 5y"); testHostResult.AssertExitCodeIs(ExitCodes.InvalidCommandLine); - testHostResult.StandardError.Contains("'timeout' option should have one argument as string in the format [h|m|s] where 'value' is float"); + testHostResult.AssertOutputContains("'timeout' option should have one argument as string in the format [h|m|s] where 'value' is float"); } [DynamicData(nameof(TargetFrameworks.AllForDynamicData), typeof(TargetFrameworks))] @@ -36,7 +36,7 @@ public async Task TimeoutWithInvalidArg_WithInvalidFormat_OutputInvalidMessage(s TestHostResult testHostResult = await testHost.ExecuteAsync("--timeout 5h6m"); testHostResult.AssertExitCodeIs(ExitCodes.InvalidCommandLine); - testHostResult.StandardError.Contains("'timeout' option should have one argument as string in the format [h|m|s] where 'value' is float"); + testHostResult.AssertOutputContains("'timeout' option should have one argument as string in the format [h|m|s] where 'value' is float"); } [DynamicData(nameof(TargetFrameworks.AllForDynamicData), typeof(TargetFrameworks))] From 8cfa946f4b525eed3fc3a6aaac986037bc9a9173 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Wed, 3 Sep 2025 14:17:31 +0200 Subject: [PATCH 466/541] Add --debug-attach option to MTP (#6499) --- .../Builder/TestApplication.cs | 24 +++++++++++++------ .../PlatformCommandLineProvider.cs | 2 ++ .../Resources/PlatformResources.resx | 5 +++- .../Resources/xlf/PlatformResources.cs.xlf | 5 ++++ .../Resources/xlf/PlatformResources.de.xlf | 5 ++++ .../Resources/xlf/PlatformResources.es.xlf | 5 ++++ .../Resources/xlf/PlatformResources.fr.xlf | 5 ++++ .../Resources/xlf/PlatformResources.it.xlf | 5 ++++ .../Resources/xlf/PlatformResources.ja.xlf | 5 ++++ .../Resources/xlf/PlatformResources.ko.xlf | 5 ++++ .../Resources/xlf/PlatformResources.pl.xlf | 5 ++++ .../Resources/xlf/PlatformResources.pt-BR.xlf | 5 ++++ .../Resources/xlf/PlatformResources.ru.xlf | 5 ++++ .../Resources/xlf/PlatformResources.tr.xlf | 5 ++++ .../xlf/PlatformResources.zh-Hans.xlf | 5 ++++ .../xlf/PlatformResources.zh-Hant.xlf | 5 ++++ .../HelpInfoTests.cs | 2 ++ .../HelpInfoTests.cs | 14 ++++++++++- 18 files changed, 103 insertions(+), 9 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Platform/Builder/TestApplication.cs b/src/Platform/Microsoft.Testing.Platform/Builder/TestApplication.cs index fc8c2870ef..4ee303edd6 100644 --- a/src/Platform/Microsoft.Testing.Platform/Builder/TestApplication.cs +++ b/src/Platform/Microsoft.Testing.Platform/Builder/TestApplication.cs @@ -78,6 +78,11 @@ public static async Task CreateBuilderAsync(string[] ar // First step is to parse the command line from where we get the second input layer. // The first one should be the env vars handled autonomously by extensions and part of the test platform. CommandLineParseResult parseResult = CommandLineParser.Parse(args, systemEnvironment); + if (parseResult.IsOptionSet(PlatformCommandLineProvider.DebugAttachOptionKey)) + { + WaitForDebuggerToAttach(systemEnvironment, systemConsole, systemProcess); + } + TestHostControllerInfo testHostControllerInfo = new(parseResult); CurrentTestApplicationModuleInfo testApplicationModuleInfo = new(systemEnvironment, systemProcess); @@ -230,16 +235,21 @@ private static void AttachDebuggerIfNeeded(SystemEnvironment environment, System if (environment.GetEnvironmentVariable(EnvironmentVariableConstants.TESTINGPLATFORM_WAIT_ATTACH_DEBUGGER) == "1") { - using IProcess currentProcess = systemProcess.GetCurrentProcess(); - console.WriteLine($"Waiting for debugger to attach... Process Id: {environment.ProcessId}, Name: {currentProcess.Name}"); + WaitForDebuggerToAttach(environment, console, systemProcess); + } + } - while (!Debugger.IsAttached) - { - Thread.Sleep(1000); - } + private static void WaitForDebuggerToAttach(SystemEnvironment environment, SystemConsole console, SystemProcessHandler systemProcess) + { + using IProcess currentProcess = systemProcess.GetCurrentProcess(); + console.WriteLine($"Waiting for debugger to attach... Process Id: {environment.ProcessId}, Name: {currentProcess.Name}"); - Debugger.Break(); + while (!Debugger.IsAttached) + { + Thread.Sleep(1000); } + + Debugger.Break(); } /* diff --git a/src/Platform/Microsoft.Testing.Platform/CommandLine/PlatformCommandLineProvider.cs b/src/Platform/Microsoft.Testing.Platform/CommandLine/PlatformCommandLineProvider.cs index 5f1b3f192b..777497f217 100644 --- a/src/Platform/Microsoft.Testing.Platform/CommandLine/PlatformCommandLineProvider.cs +++ b/src/Platform/Microsoft.Testing.Platform/CommandLine/PlatformCommandLineProvider.cs @@ -29,6 +29,7 @@ internal sealed class PlatformCommandLineProvider : ICommandLineOptionsProvider public const string ExitOnProcessExitOptionKey = "exit-on-process-exit"; public const string ConfigFileOptionKey = "config-file"; public const string FilterUidOptionKey = "filter-uid"; + public const string DebugAttachOptionKey = "debug-wait-attach"; public const string ServerOptionKey = "server"; public const string ClientPortOptionKey = "client-port"; @@ -59,6 +60,7 @@ internal sealed class PlatformCommandLineProvider : ICommandLineOptionsProvider new(ExitOnProcessExitOptionKey, PlatformResources.PlatformCommandLineExitOnProcessExitOptionDescription, ArgumentArity.ExactlyOne, false, isBuiltIn: true), new(ConfigFileOptionKey, PlatformResources.PlatformCommandLineConfigFileOptionDescription, ArgumentArity.ExactlyOne, false, isBuiltIn: true), new(FilterUidOptionKey, PlatformResources.PlatformCommandLineFilterUidOptionDescription, ArgumentArity.OneOrMore, false, isBuiltIn: true), + new(DebugAttachOptionKey, PlatformResources.PlatformCommandLineDebugAttachOptionDescription, ArgumentArity.Zero, false, isBuiltIn: true), // Hidden options new(HelpOptionQuestionMark, PlatformResources.PlatformCommandLineHelpOptionDescription, ArgumentArity.Zero, true, isBuiltIn: true), diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/PlatformResources.resx b/src/Platform/Microsoft.Testing.Platform/Resources/PlatformResources.resx index 9ca55934cd..a3c8767c8f 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/PlatformResources.resx +++ b/src/Platform/Microsoft.Testing.Platform/Resources/PlatformResources.resx @@ -713,4 +713,7 @@ Takes one argument as string in the format <value>[h|m|s] where 'value' is Passing both '--treenode-filter' and '--filter-uid' is unsupported. - + + Allows to pause execution in order to attach to the process for debug purposes. + + \ No newline at end of file diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.cs.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.cs.xlf index 2dd7c37384..d7788c81b0 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.cs.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.cs.xlf @@ -466,6 +466,11 @@ Určuje soubor testconfig.json. + + Allows to pause execution in order to attach to the process for debug purposes. + Allows to pause execution in order to attach to the process for debug purposes. + + Force the built-in file logger to write the log synchronously. Useful for scenario where you don't want to lose any log (i.e. in case of crash). diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.de.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.de.xlf index 2901eea04a..a739f627ef 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.de.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.de.xlf @@ -466,6 +466,11 @@ Gibt eine testconfig.json-Datei an. + + Allows to pause execution in order to attach to the process for debug purposes. + Allows to pause execution in order to attach to the process for debug purposes. + + Force the built-in file logger to write the log synchronously. Useful for scenario where you don't want to lose any log (i.e. in case of crash). diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.es.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.es.xlf index 613ea681c3..5d78b736ff 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.es.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.es.xlf @@ -466,6 +466,11 @@ Especifica un archivo testconfig.json. + + Allows to pause execution in order to attach to the process for debug purposes. + Allows to pause execution in order to attach to the process for debug purposes. + + Force the built-in file logger to write the log synchronously. Useful for scenario where you don't want to lose any log (i.e. in case of crash). diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.fr.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.fr.xlf index 6ac9dfb271..5460814520 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.fr.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.fr.xlf @@ -466,6 +466,11 @@ Spécifie un fichier testconfig.json. + + Allows to pause execution in order to attach to the process for debug purposes. + Allows to pause execution in order to attach to the process for debug purposes. + + Force the built-in file logger to write the log synchronously. Useful for scenario where you don't want to lose any log (i.e. in case of crash). diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.it.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.it.xlf index e2b61cae0c..f810f98b81 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.it.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.it.xlf @@ -466,6 +466,11 @@ Specifica un file testconfig.json. + + Allows to pause execution in order to attach to the process for debug purposes. + Allows to pause execution in order to attach to the process for debug purposes. + + Force the built-in file logger to write the log synchronously. Useful for scenario where you don't want to lose any log (i.e. in case of crash). diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ja.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ja.xlf index 1998a73c03..e08f96a303 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ja.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ja.xlf @@ -466,6 +466,11 @@ testconfig.json ファイルを指定します。 + + Allows to pause execution in order to attach to the process for debug purposes. + Allows to pause execution in order to attach to the process for debug purposes. + + Force the built-in file logger to write the log synchronously. Useful for scenario where you don't want to lose any log (i.e. in case of crash). diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ko.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ko.xlf index e2d0097ada..3b7c2d118a 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ko.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ko.xlf @@ -466,6 +466,11 @@ testconfig.json 파일을 지정합니다. + + Allows to pause execution in order to attach to the process for debug purposes. + Allows to pause execution in order to attach to the process for debug purposes. + + Force the built-in file logger to write the log synchronously. Useful for scenario where you don't want to lose any log (i.e. in case of crash). diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pl.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pl.xlf index 9f96ada5b5..b22b0c5fad 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pl.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pl.xlf @@ -466,6 +466,11 @@ Określa plik testconfig.json. + + Allows to pause execution in order to attach to the process for debug purposes. + Allows to pause execution in order to attach to the process for debug purposes. + + Force the built-in file logger to write the log synchronously. Useful for scenario where you don't want to lose any log (i.e. in case of crash). diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pt-BR.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pt-BR.xlf index a0884e336d..25cef70f6d 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pt-BR.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pt-BR.xlf @@ -466,6 +466,11 @@ Especifica um arquivo testconfig.json. + + Allows to pause execution in order to attach to the process for debug purposes. + Allows to pause execution in order to attach to the process for debug purposes. + + Force the built-in file logger to write the log synchronously. Useful for scenario where you don't want to lose any log (i.e. in case of crash). diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ru.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ru.xlf index e57b6d1544..0c59bd9def 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ru.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ru.xlf @@ -466,6 +466,11 @@ Указывает файл testconfig.json. + + Allows to pause execution in order to attach to the process for debug purposes. + Allows to pause execution in order to attach to the process for debug purposes. + + Force the built-in file logger to write the log synchronously. Useful for scenario where you don't want to lose any log (i.e. in case of crash). diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.tr.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.tr.xlf index 4008f64005..0837ca3b32 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.tr.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.tr.xlf @@ -466,6 +466,11 @@ testconfig.json dosyası belirtir. + + Allows to pause execution in order to attach to the process for debug purposes. + Allows to pause execution in order to attach to the process for debug purposes. + + Force the built-in file logger to write the log synchronously. Useful for scenario where you don't want to lose any log (i.e. in case of crash). diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hans.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hans.xlf index 5fdcc9180a..4f4cf7fd1f 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hans.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hans.xlf @@ -466,6 +466,11 @@ 指定 testconfig.json 文件。 + + Allows to pause execution in order to attach to the process for debug purposes. + Allows to pause execution in order to attach to the process for debug purposes. + + Force the built-in file logger to write the log synchronously. Useful for scenario where you don't want to lose any log (i.e. in case of crash). diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hant.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hant.xlf index 60fd30786c..55cb5acaab 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hant.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hant.xlf @@ -466,6 +466,11 @@ 指定 testconfig.json 檔案。 + + Allows to pause execution in order to attach to the process for debug purposes. + Allows to pause execution in order to attach to the process for debug purposes. + + Force the built-in file logger to write the log synchronously. Useful for scenario where you don't want to lose any log (i.e. in case of crash). diff --git a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/HelpInfoTests.cs b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/HelpInfoTests.cs index f65ad6d7c4..ac09977edf 100644 --- a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/HelpInfoTests.cs +++ b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/HelpInfoTests.cs @@ -28,6 +28,8 @@ Execute a .NET Test Application. Options: --config-file Specifies a testconfig.json file. + --debug-wait-attach + Allows to pause execution in order to attach to the process for debug purposes. --diagnostic Enable the diagnostic logging. The default log level is 'Trace'. The file will be written in the output directory with the name log_[yyMMddHHmmssfff].diag diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/HelpInfoTests.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/HelpInfoTests.cs index 1956c917fc..0cf5d33aa6 100644 --- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/HelpInfoTests.cs +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/HelpInfoTests.cs @@ -22,6 +22,8 @@ Execute a .NET Test Application. Options: --config-file Specifies a testconfig.json file. + --debug-wait-attach + Allows to pause execution in order to attach to the process for debug purposes. --diagnostic Enable the diagnostic logging. The default log level is 'Trace'. The file will be written in the output directory with the name log_[yyMMddHHmmssfff].diag @@ -148,10 +150,14 @@ Microsoft.Testing.Platform v.+ \[.+\] Arity: 1 Hidden: True Description: Specify the port of the client\. - --config-file + --config-file Arity: 1 Hidden: False Description: Specifies a testconfig\.json file\. + --debug-wait-attach + Arity: 0 + Hidden: False + Description: Allows to pause execution in order to attach to the process for debug purposes. --diagnostic Arity: 0 Hidden: False @@ -279,6 +285,8 @@ Execute a .NET Test Application. Options: --config-file Specifies a testconfig.json file. + --debug-wait-attach + Allows to pause execution in order to attach to the process for debug purposes. --diagnostic Enable the diagnostic logging. The default log level is 'Trace'. The file will be written in the output directory with the name log_[yyMMddHHmmssfff].diag @@ -420,6 +428,10 @@ Microsoft.Testing.Platform v* [*] Arity: 1 Hidden: False Description: Specifies a testconfig.json file. + --debug-wait-attach + Arity: 0 + Hidden: False + Description: Allows to pause execution in order to attach to the process for debug purposes. --diagnostic Arity: 0 Hidden: False From f38a9df1d11121edc4cd713264eee32bf87bbd27 Mon Sep 17 00:00:00 2001 From: dotnet bot Date: Wed, 3 Sep 2025 05:21:51 -0700 Subject: [PATCH 467/541] Localized file check-in by OneLocBuild Task: Build definition ID 1218: Build ID 2785442 --- .../Resources/xlf/Resource.cs.xlf | 8 ++++---- .../Resources/xlf/Resource.de.xlf | 2 +- .../Resources/xlf/Resource.es.xlf | 6 +++--- .../Resources/xlf/Resource.fr.xlf | 4 ++-- .../Resources/xlf/Resource.it.xlf | 2 +- .../Resources/xlf/Resource.pl.xlf | 2 +- .../Resources/xlf/Resource.pt-BR.xlf | 2 +- .../Resources/xlf/Resource.ru.xlf | 6 +++--- .../Resources/xlf/Resource.tr.xlf | 2 +- .../Resources/xlf/Resource.zh-Hans.xlf | 6 +++--- .../Resources/xlf/Resource.zh-Hant.xlf | 2 +- .../xlf/CodeFixResources.tr.xlf | 8 ++++---- .../MSTest.Analyzers/xlf/Resources.cs.xlf | 14 +++++++------- .../MSTest.Analyzers/xlf/Resources.tr.xlf | 14 +++++++------- .../Resources/xlf/AzureDevOpsResources.cs.xlf | 2 +- .../Resources/xlf/AzureDevOpsResources.de.xlf | 2 +- .../Resources/xlf/AzureDevOpsResources.es.xlf | 2 +- .../Resources/xlf/AzureDevOpsResources.fr.xlf | 2 +- .../Resources/xlf/AzureDevOpsResources.it.xlf | 2 +- .../Resources/xlf/AzureDevOpsResources.ja.xlf | 2 +- .../Resources/xlf/AzureDevOpsResources.ko.xlf | 2 +- .../Resources/xlf/AzureDevOpsResources.pl.xlf | 2 +- .../Resources/xlf/AzureDevOpsResources.pt-BR.xlf | 2 +- .../Resources/xlf/AzureDevOpsResources.tr.xlf | 2 +- 24 files changed, 49 insertions(+), 49 deletions(-) diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.cs.xlf b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.cs.xlf index ef564b606c..b8b854815b 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.cs.xlf +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.cs.xlf @@ -236,17 +236,17 @@ byl však přijat tento počet argumentů: {4} s typy {5}. Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. - Invalid value '{0}' specified for 'ClassCleanupLifecycle'. Supported scopes are {1}. + Pro 'ClassCleanupLifecycle' byla zadána neplatná hodnota {0}. Podporované obory jsou {1}. {Locked="ClassCleanupLifecycle"} Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. - Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. + Pro procesy 'Scope' je zadaná neplatná hodnota {0}. Podporované obory jsou {1}. {Locked="Scope"} Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. - Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. + Pro procesy 'Workers' je zadaná neplatná hodnota {0}. Hodnota by měla být nezáporné celé číslo. {Locked="Workers"} @@ -351,7 +351,7 @@ byl však přijat tento počet argumentů: {4} s typy {5}. Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) - Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) + Je povolená paralelizace testu pro {0} (Workers: {1}, Scope: {2}) {Locked="Workers"}{Locked="Scope"} diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.de.xlf b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.de.xlf index 0a48f74904..34d0461b6d 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.de.xlf +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.de.xlf @@ -351,7 +351,7 @@ aber empfing {4} Argument(e) mit den Typen „{5}“. Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) - Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) + Testparallelisierung aktiviert für {0} (Workers: {1}, Scope: {2}) {Locked="Workers"}{Locked="Scope"} diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.es.xlf b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.es.xlf index a7034ac99b..022571fcca 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.es.xlf +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.es.xlf @@ -241,12 +241,12 @@ pero recibió {4} argumentos, con los tipos '{5}'. Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. - Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. + Valor no válido "{0}" especificado para "Scope". Los ámbitos admitidos son {1}. {Locked="Scope"} Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. - Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. + Valor no válido "{0}" especificado para "Workers". El valor debe ser un entero no negativo. {Locked="Workers"} @@ -351,7 +351,7 @@ pero recibió {4} argumentos, con los tipos '{5}'. Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) - Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) + Probar paralelización habilitada para {0} (Workers: {1}, Scope: {2}) {Locked="Workers"}{Locked="Scope"} diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.fr.xlf b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.fr.xlf index 088a6d86db..fe1c9768e3 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.fr.xlf +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.fr.xlf @@ -241,7 +241,7 @@ mais a reçu {4} argument(s), avec les types « {5} ». Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. - Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. + Valeur non valide « {0} » spécifiée pour « Scope ». Les étendues prises en charge sont {1}. {Locked="Scope"} @@ -351,7 +351,7 @@ mais a reçu {4} argument(s), avec les types « {5} ». Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) - Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) + Parallélisation des tests activée pour {0} (Workers : {1}, Scope : {2}) {Locked="Workers"}{Locked="Scope"} diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.it.xlf b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.it.xlf index c76d8e8512..01041f4d35 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.it.xlf +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.it.xlf @@ -351,7 +351,7 @@ ma ha ricevuto {4} argomenti, con tipi '{5}'. Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) - Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) + Parallelizzazione test abilitata per {0} (Workers: {1}. Scope: {2}) {Locked="Workers"}{Locked="Scope"} diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.pl.xlf b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.pl.xlf index 032a52c0eb..431f757dd8 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.pl.xlf +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.pl.xlf @@ -351,7 +351,7 @@ ale odebrał argumenty {4} z typami „{5}”. Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) - Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) + Przetwarzanie równoległe testów włączono dla {0} (Workers: {1}, Scope: {2}) {Locked="Workers"}{Locked="Scope"} diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.pt-BR.xlf b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.pt-BR.xlf index 783f6f91f5..775566e3b6 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.pt-BR.xlf +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.pt-BR.xlf @@ -351,7 +351,7 @@ mas {4} argumentos recebidos, com tipos '{5}'. Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) - Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) + Paralelização de Teste habilitada para {0} (Workers: {1}, Scope: {2}) {Locked="Workers"}{Locked="Scope"} diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.ru.xlf b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.ru.xlf index a8c3ef08f6..5196050592 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.ru.xlf +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.ru.xlf @@ -241,12 +241,12 @@ but received {4} argument(s), with types '{5}'. Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. - Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. + В поле "Scope" указано недопустимое значение "{0}". Поддерживаемые области: {1}. {Locked="Scope"} Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. - Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. + В поле "Workers" указано недопустимое значение "{0}". Оно должно быть неотрицательным целым числом. {Locked="Workers"} @@ -351,7 +351,7 @@ but received {4} argument(s), with types '{5}'. Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) - Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) + Включена параллелизация тестов для {0} (Workers: {1}, Scope: {2}) {Locked="Workers"}{Locked="Scope"} diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.tr.xlf b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.tr.xlf index 0f36222ea6..1ba2e803d3 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.tr.xlf +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.tr.xlf @@ -351,7 +351,7 @@ ancak, '{5}' türünde {4} bağımsız değişken aldı. Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) - Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) + {0} için Test Paralelleştirme etkin (Workers: {1}, Scope: {2}) {Locked="Workers"}{Locked="Scope"} diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.zh-Hans.xlf b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.zh-Hans.xlf index 60889681fd..5cc1e12a73 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.zh-Hans.xlf +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.zh-Hans.xlf @@ -241,12 +241,12 @@ but received {4} argument(s), with types '{5}'. Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. - Invalid value '{0}' specified for 'Scope'. Supported scopes are {1}. + 为 ‘Scope’ 指定的值 ‘{0}’ 无效。受支持的范围为 {1}。 {Locked="Scope"} Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. - Invalid value '{0}' specified for 'Workers'. The value should be a non-negative integer. + 为 ‘Workers’ 指定的值 ‘{0}’ 无效。该值应为非负整数。 {Locked="Workers"} @@ -351,7 +351,7 @@ but received {4} argument(s), with types '{5}'. Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) - Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) + 已为 {0} 启用测试并行化(Workers: {1},Scope: {2}) {Locked="Workers"}{Locked="Scope"} diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.zh-Hant.xlf b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.zh-Hant.xlf index 9aa7014cf1..d5a3738734 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.zh-Hant.xlf +++ b/src/Adapter/MSTestAdapter.PlatformServices/Resources/xlf/Resource.zh-Hant.xlf @@ -351,7 +351,7 @@ but received {4} argument(s), with types '{5}'. Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) - Test Parallelization enabled for {0} (Workers: {1}, Scope: {2}) + 已為 {0} 啟用平行測試 (Workers: {1}, Scope: {2}) {Locked="Workers"}{Locked="Scope"} diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.tr.xlf b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.tr.xlf index 2ffc424368..9d31daafe5 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.tr.xlf +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/xlf/CodeFixResources.tr.xlf @@ -24,12 +24,12 @@ Use interpolated string instead of format parameters - Use interpolated string instead of format parameters + Biçim parametreleri yerine düz metin arasına kod eklenmiş dize kullanın Use 'string.Format' instead of format parameters - Use 'string.Format' instead of format parameters + Biçim parametreleri yerine 'string.Format' kullanın @@ -59,7 +59,7 @@ Pass 'TestContext.CancellationToken' argument to method call - Pass 'TestContext.CancellationToken' argument to method call + 'TestContext.CancellationToken' bağımsız değişkenini metot çağrısına aktarın @@ -129,7 +129,7 @@ Use 'TestContext.CancellationToken' instead - Use 'TestContext.CancellationToken' instead + Bunun yerine 'TestContext.CancellationToken' kullanın diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf index 2a91135472..e304d57594 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf @@ -134,12 +134,12 @@ Typ deklarující tyto metody by měl také respektovat následující pravidla: Replace '{0}' with format parameters with string.Format or string interpolation - Replace '{0}' with format parameters with string.Format or string interpolation + Nahraďte {0} parametry formátu pomocí string.Format nebo interpolace řetězce. Avoid using Assert methods with format parameters - Avoid using Assert methods with format parameters + Vyhněte se použití metod Assert s parametry formátu @@ -464,12 +464,12 @@ Typ deklarující tyto metody by měl také respektovat následující pravidla: When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationToken to enable cooperative cancellation and respect test timeouts. - When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationToken to enable cooperative cancellation and respect test timeouts. + Při volání asynchronních metod, které mají přetížení akceptující parametr CancellationToken, upřednostňujte použití přetížení s TestContext.CancellationToken, aby se umožnilo kooperativní rušení a dodržování časových limitů testů. Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationToken' - Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationToken' + Zvažte použití přetížení, které přijímá CancellationToken a předejte TestContext.CancellationToken. @@ -669,17 +669,17 @@ Typ deklarující tyto metody by měl také respektovat následující pravidla: TestContext.CancellationToken provides a more direct way to access the cancellation token compared to TestContext.CancellationTokenSource.Token. - TestContext.CancellationToken provides a more direct way to access the cancellation token compared to TestContext.CancellationTokenSource.Token. + TestContext.CancellationToken poskytuje přímější způsob přístupu k tokenu zrušení v porovnání s TestContext.CancellationTokenSource.Token. Use 'TestContext.CancellationToken' instead of 'TestContext.CancellationTokenSource.Token' - Use 'TestContext.CancellationToken' instead of 'TestContext.CancellationTokenSource.Token' + Místo TestContext.CancellationTokenSource.Token použijte TestContext.CancellationToken. Use TestContext.CancellationToken instead of TestContext.CancellationTokenSource.Token - Use TestContext.CancellationToken instead of TestContext.CancellationTokenSource.Token + Místo TestContext.CancellationTokenSource.Token použijte TestContext.CancellationToken. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf index 9f51785e1c..a99c8212de 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf @@ -134,12 +134,12 @@ Bu yöntemleri bildiren tipin ayrıca aşağıdaki kurallara uyması gerekir: Replace '{0}' with format parameters with string.Format or string interpolation - Replace '{0}' with format parameters with string.Format or string interpolation + '{0}' ifadesini string.Format veya string interpolation format parametreleriyle değiştirin Avoid using Assert methods with format parameters - Avoid using Assert methods with format parameters + Biçim parametreleri ile Assert yöntemlerini kullanmaktan kaçının @@ -464,12 +464,12 @@ Bu yöntemleri bildiren tipin ayrıca aşağıdaki kurallara uyması gerekir: When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationToken to enable cooperative cancellation and respect test timeouts. - When calling async methods that have overloads accepting a CancellationToken parameter, prefer using the overload with TestContext.CancellationToken to enable cooperative cancellation and respect test timeouts. + CancellationToken parametresini kabul eden aşırı yüklemeleri olan asenkron yöntemleri çağırırken, işbirliğine dayalı iptal işlemini etkinleştirmek ve test zaman aşımlarını dikkate almak için TestContext.CancellationToken ile aşırı yüklemeyi kullanmayı tercih edin. Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationToken' - Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationToken' + CancellationToken'ı kabul eden aşırı yüklemeyi kullanmayı düşünün ve 'TestContext.CancellationToken'i geçirin @@ -669,17 +669,17 @@ Bu metotları bildiren türün ayrıca aşağıdaki kurallara uyması gerekir: TestContext.CancellationToken provides a more direct way to access the cancellation token compared to TestContext.CancellationTokenSource.Token. - TestContext.CancellationToken provides a more direct way to access the cancellation token compared to TestContext.CancellationTokenSource.Token. + TestContext.CancellationToken, TestContext.CancellationTokenSource.Token'a kıyasla iptal belirtecine erişmek için daha doğrudan bir yol sağlar. Use 'TestContext.CancellationToken' instead of 'TestContext.CancellationTokenSource.Token' - Use 'TestContext.CancellationToken' instead of 'TestContext.CancellationTokenSource.Token' + 'TestContext.CancellationTokenSource.Token' yerine ‘TestContext.CancellationToken’ kullanın Use TestContext.CancellationToken instead of TestContext.CancellationTokenSource.Token - Use TestContext.CancellationToken instead of TestContext.CancellationTokenSource.Token + TestContext.CancellationTokenSource.Token yerine TestContext.CancellationToken kullanın diff --git a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.cs.xlf b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.cs.xlf index 501985e4ec..076a3037b9 100644 --- a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.cs.xlf +++ b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.cs.xlf @@ -29,7 +29,7 @@ Severity to use for the reported event. Options are: error (default) and warning. - Severity to use for the reported event. Options are: error (default) and warning. + Závažnost, která se má použít pro hlášenou událost. Možnosti: error (výchozí) a warning. {Locked="error"}{Locked="warning"} diff --git a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.de.xlf b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.de.xlf index 25865f91a1..87be6a6ce5 100644 --- a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.de.xlf +++ b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.de.xlf @@ -29,7 +29,7 @@ Severity to use for the reported event. Options are: error (default) and warning. - Severity to use for the reported event. Options are: error (default) and warning. + Schweregrad, der für das gemeldete Ereignis verwendet werden soll. Optionen sind: error (Standard) und warning. {Locked="error"}{Locked="warning"} diff --git a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.es.xlf b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.es.xlf index b3cfd14eaf..c4a61c952f 100644 --- a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.es.xlf +++ b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.es.xlf @@ -29,7 +29,7 @@ Severity to use for the reported event. Options are: error (default) and warning. - Severity to use for the reported event. Options are: error (default) and warning. + Gravedad que se va a usar para el evento notificado. Las opciones son: error (valor predeterminado) y warning. {Locked="error"}{Locked="warning"} diff --git a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.fr.xlf b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.fr.xlf index 9506e61cee..4feb6d0ab7 100644 --- a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.fr.xlf +++ b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.fr.xlf @@ -29,7 +29,7 @@ Severity to use for the reported event. Options are: error (default) and warning. - Severity to use for the reported event. Options are: error (default) and warning. + Gravité à utiliser pour l’événement signalé. Les options sont : error (par défaut) et warning. {Locked="error"}{Locked="warning"} diff --git a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.it.xlf b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.it.xlf index d777478ae0..d9756f675c 100644 --- a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.it.xlf +++ b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.it.xlf @@ -29,7 +29,7 @@ Severity to use for the reported event. Options are: error (default) and warning. - Severity to use for the reported event. Options are: error (default) and warning. + Gravità da usare per l'evento segnalato. Le opzioni sono: error (impostazione predefinita) e warning. {Locked="error"}{Locked="warning"} diff --git a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.ja.xlf b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.ja.xlf index 2aded0feb3..ea3529945b 100644 --- a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.ja.xlf +++ b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.ja.xlf @@ -29,7 +29,7 @@ Severity to use for the reported event. Options are: error (default) and warning. - Severity to use for the reported event. Options are: error (default) and warning. + 報告されたイベントに使用する重大度。オプションは、error (既定) と warning です。 {Locked="error"}{Locked="warning"} diff --git a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.ko.xlf b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.ko.xlf index 60c865fe75..f74caa7f6e 100644 --- a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.ko.xlf +++ b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.ko.xlf @@ -29,7 +29,7 @@ Severity to use for the reported event. Options are: error (default) and warning. - Severity to use for the reported event. Options are: error (default) and warning. + 보고된 이벤트에 사용할 심각도입니다. 옵션은 error(기본값)와 warning, 두 가지입니다. {Locked="error"}{Locked="warning"} diff --git a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.pl.xlf b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.pl.xlf index a020d2abe7..8890f27f70 100644 --- a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.pl.xlf +++ b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.pl.xlf @@ -29,7 +29,7 @@ Severity to use for the reported event. Options are: error (default) and warning. - Severity to use for the reported event. Options are: error (default) and warning. + Ważność do użycia dla zgłoszonego zdarzenia. Dostępne opcje to: error (domyślny) i warning. {Locked="error"}{Locked="warning"} diff --git a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.pt-BR.xlf b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.pt-BR.xlf index 792910812b..d660d0e56a 100644 --- a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.pt-BR.xlf +++ b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.pt-BR.xlf @@ -29,7 +29,7 @@ Severity to use for the reported event. Options are: error (default) and warning. - Severity to use for the reported event. Options are: error (default) and warning. + A gravidade que será usada para o evento relatado. As opções são: error (padrão) e warning. {Locked="error"}{Locked="warning"} diff --git a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.tr.xlf b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.tr.xlf index 4abfbda1c5..69207860a2 100644 --- a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.tr.xlf +++ b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.tr.xlf @@ -29,7 +29,7 @@ Severity to use for the reported event. Options are: error (default) and warning. - Severity to use for the reported event. Options are: error (default) and warning. + Raporlanan olay için kullanılacak önem derecesi. Seçenekler şunlardır: error (varsayılan) ve warning. {Locked="error"}{Locked="warning"} From b180b6bcdc608def7b2bad5cb3a01d87deb0a17d Mon Sep 17 00:00:00 2001 From: dotnet bot Date: Wed, 3 Sep 2025 05:23:20 -0700 Subject: [PATCH 468/541] Localized file check-in by OneLocBuild Task: Build definition ID 1218: Build ID 2785442 --- .../Resources/xlf/AzureDevOpsResources.zh-Hant.xlf | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.zh-Hant.xlf b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.zh-Hant.xlf index 9067fe5cc4..6c61f0fb8f 100644 --- a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.zh-Hant.xlf +++ b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/Resources/xlf/AzureDevOpsResources.zh-Hant.xlf @@ -29,7 +29,7 @@ Severity to use for the reported event. Options are: error (default) and warning. - Severity to use for the reported event. Options are: error (default) and warning. + 要用於所報告事件的嚴重性。選項為: error (預設) warning。 {Locked="error"}{Locked="warning"} From de8bf9dc0786c2a852ef4b78d6789314e79d0ab1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Wed, 3 Sep 2025 15:03:08 +0200 Subject: [PATCH 469/541] Make acceptance tests cancellable quickly (#6502) --- .../AbortionTests.cs | 12 +- .../AnalyzersTests.cs | 37 +++-- .../AssemblyResolutionTests.cs | 10 +- .../AssemblyResolverTests.cs | 4 +- .../CancellationTests.cs | 72 +++++---- .../ConfigurationSettingsTests.cs | 43 ++++-- .../DataSourceTests.cs | 7 +- .../DotnetTestCliTests.cs | 4 +- .../DynamicDataMethodTests.cs | 4 +- .../FrameworkOnlyTests.cs | 4 +- .../GenericTestMethodTests.cs | 4 +- .../HelpInfoTests.cs | 6 +- .../IgnoreTests.cs | 8 +- .../InconclusiveTests.cs | 5 +- .../LeakTests.cs | 4 +- .../LifecycleTests.cs | 4 +- .../MSBuildRunnerTests.cs | 6 +- .../MaxFailedTestsExtensionTests.cs | 6 +- .../NativeAotTests.cs | 10 +- .../OutputTests.cs | 4 +- .../ParameterizedTestTests.cs | 6 +- .../PublishAotNonNativeTests.cs | 4 +- .../RetryTests.cs | 4 +- .../RunnerTests.cs | 24 +-- .../RunsettingsTests.cs | 19 ++- .../STATestClassTests.cs | 16 +- .../STATestMethodTests.cs | 20 +-- .../SdkTests.cs | 46 +++--- .../ServerModeTests.cs | 6 +- .../TestContextTests.cs | 12 +- .../TestDiscoveryTests.cs | 6 +- .../TestDiscoveryWarningsTests.cs | 6 +- .../TestFilterTests.cs | 22 +-- .../TestRunParametersTests.cs | 6 +- .../ThreadContextTests.cs | 20 +-- .../ThreadingTests.cs | 41 +++--- .../TimeoutTests.cs | 139 +++++++++++------- .../TupleDynamicDataTests.cs | 6 +- .../ValueTaskTests.cs | 4 +- .../WinUITests.cs | 4 +- .../ParallelExecutionTests.cs | 4 +- .../AbortionTests.cs | 4 +- .../CrashDumpTests.cs | 10 +- .../CrashPlusHangDumpTests.cs | 8 +- .../CustomBannerTests.cs | 12 +- .../DiagnosticTests.cs | 32 ++-- ...mentVariablesConfigurationProviderTests.cs | 4 +- .../ExecutionTests.cs | 34 +++-- .../ExitOnProcessExitTests.cs | 4 +- .../HangDumpOutputTests.cs | 5 +- .../HangDumpTests.cs | 20 ++- .../HelpInfoTests.cs | 22 +-- .../Helpers/AcceptanceTestBase.cs | 8 +- .../IgnoreExitCodeTests.cs | 9 +- .../MSBuild.KnownExtensionRegistration.cs | 8 +- .../MSBuildTests.ConfigurationFile.cs | 10 +- .../MSBuildTests.GenerateEntryPoint.cs | 20 ++- .../MSBuildTests.Solution.cs | 6 +- .../MSBuildTests.Test.cs | 36 +++-- .../MaxFailedTestsExtensionTests.cs | 15 +- .../NoBannerTests.cs | 12 +- .../RetryFailedTestsTests.cs | 15 +- .../v1.0.0/TestingPlatformClient.cs | 4 +- .../TelemetryTests.cs | 10 +- .../TestHostProcessLifetimeHandlerTests.cs | 4 +- .../TimeoutTests.cs | 16 +- .../TrxTests.cs | 26 ++-- .../TypeForwardingTests.cs | 6 +- .../UnhandledExceptionPolicyTests.cs | 64 ++++---- .../CommandLine.cs | 13 +- .../DotnetCli.cs | 17 ++- .../DotnetMuxer.cs | 10 +- .../IProcessHandle.cs | 4 +- .../ProcessHandle.cs | 8 +- .../TestAssetFixtureBase.cs | 10 +- .../TestHost.cs | 34 +++-- 76 files changed, 731 insertions(+), 458 deletions(-) diff --git a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/AbortionTests.cs b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/AbortionTests.cs index d2fd2c24e5..15bd3a545f 100644 --- a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/AbortionTests.cs +++ b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/AbortionTests.cs @@ -28,10 +28,12 @@ public async Task AbortWithCTRLPlusC_CancellingTests(string tfm) string fileCreationPath = Path.Combine(testHost.DirectoryName, "fileCreation"); File.WriteAllText(fileCreationPath, string.Empty); - TestHostResult testHostResult = await testHost.ExecuteAsync(environmentVariables: new() - { - ["FILE_DIRECTORY"] = fileCreationPath, - }); + TestHostResult testHostResult = await testHost.ExecuteAsync( + environmentVariables: new() + { + ["FILE_DIRECTORY"] = fileCreationPath, + }, + cancellationToken: TestContext.CancellationToken); testHostResult.AssertExitCodeIs(ExitCodes.TestSessionAborted); @@ -159,4 +161,6 @@ public async Task TestA() .PatchCodeWithReplace("$MSTestVersion$", MSTestVersion)); } } + + public TestContext TestContext { get; set; } } diff --git a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/AnalyzersTests.cs b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/AnalyzersTests.cs index 702b6b4d80..f88e6afbda 100644 --- a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/AnalyzersTests.cs +++ b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/AnalyzersTests.cs @@ -54,7 +54,11 @@ public void TestMethod() .PatchCodeWithReplace("$MicrosoftNETTestSdkVersion$", MicrosoftNETTestSdkVersion); using TestAsset testAsset = await TestAsset.GenerateAssetAsync("TestForMSTEST0001", code); - DotnetMuxerResult result = await DotnetCli.RunAsync($"build {testAsset.TargetAssetPath}", AcceptanceFixture.NuGetGlobalPackagesFolder.Path, warnAsError: false); + DotnetMuxerResult result = await DotnetCli.RunAsync( + $"build {testAsset.TargetAssetPath}", + AcceptanceFixture.NuGetGlobalPackagesFolder.Path, + warnAsError: false, + cancellationToken: TestContext.CancellationToken); if (isAdapterReferenced) { result.AssertOutputContains("warning MSTEST0001"); @@ -107,7 +111,11 @@ public void TestMethod() .PatchCodeWithReplace("$MSTestVersion$", MSTestVersion); using TestAsset testAsset = await TestAsset.GenerateAssetAsync("AnalyzersMetapackage", code); - DotnetMuxerResult result = await DotnetCli.RunAsync($"build {testAsset.TargetAssetPath}", AcceptanceFixture.NuGetGlobalPackagesFolder.Path, warnAsError: false); + DotnetMuxerResult result = await DotnetCli.RunAsync( + $"build {testAsset.TargetAssetPath}", + AcceptanceFixture.NuGetGlobalPackagesFolder.Path, + warnAsError: false, + cancellationToken: TestContext.CancellationToken); result.AssertOutputContains("MSTEST0014"); } @@ -143,7 +151,11 @@ public void TestMethod() .PatchCodeWithReplace("$MSTestVersion$", MSTestVersion); using TestAsset testAsset = await TestAsset.GenerateAssetAsync("AnalyzersTestFrameworkPackage", code); - DotnetMuxerResult result = await DotnetCli.RunAsync($"build {testAsset.TargetAssetPath}", AcceptanceFixture.NuGetGlobalPackagesFolder.Path, warnAsError: false); + DotnetMuxerResult result = await DotnetCli.RunAsync( + $"build {testAsset.TargetAssetPath}", + AcceptanceFixture.NuGetGlobalPackagesFolder.Path, + warnAsError: false, + cancellationToken: TestContext.CancellationToken); result.AssertOutputContains("MSTEST0014"); } @@ -182,12 +194,17 @@ public void TestMethod() .PatchCodeWithReplace("$MSTestVersion$", MSTestVersion); using TestAsset testAsset = await TestAsset.GenerateAssetAsync("Analyzers", code); - DotnetMuxerResult result = await DotnetCli.RunAsync($"build {testAsset.TargetAssetPath}", AcceptanceFixture.NuGetGlobalPackagesFolder.Path, environmentVariables: new() - { - ["DOTNET_CLI_UI_LANGUAGE"] = "it-IT", - ["PreferredUILang"] = "it-IT", - ["VSLang"] = "1040", - }, warnAsError: false); + DotnetMuxerResult result = await DotnetCli.RunAsync( + $"build {testAsset.TargetAssetPath}", + AcceptanceFixture.NuGetGlobalPackagesFolder.Path, + environmentVariables: new() + { + ["DOTNET_CLI_UI_LANGUAGE"] = "it-IT", + ["PreferredUILang"] = "it-IT", + ["VSLang"] = "1040", + }, + warnAsError: false, + cancellationToken: TestContext.CancellationToken); result.AssertOutputContains("DataRow deve essere impostato solo su un metodo di test"); } @@ -297,4 +314,6 @@ private static async Task AssertAnalysisModeAsync(string mode, string[] contains Assert.DoesNotContain(doesNotContainElement, output, $"Expected to not find '{doesNotContainElement}' for analysisMode {mode}"); } } + + public TestContext TestContext { get; set; } } diff --git a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/AssemblyResolutionTests.cs b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/AssemblyResolutionTests.cs index a96f5ddca5..304100de45 100644 --- a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/AssemblyResolutionTests.cs +++ b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/AssemblyResolutionTests.cs @@ -12,7 +12,7 @@ public sealed class AssemblyResolutionTests : AcceptanceTestBase GetDataParams(params int[] i) """; } + + public TestContext TestContext { get; set; } } diff --git a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/FrameworkOnlyTests.cs b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/FrameworkOnlyTests.cs index 12c1448218..f191ad5c46 100644 --- a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/FrameworkOnlyTests.cs +++ b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/FrameworkOnlyTests.cs @@ -19,7 +19,7 @@ public async Task DynamicDataAttributeGetDataShouldWorkWithoutAdapter() // Users shouldn't need to reference adapter, nor do anything // special, to be able to call DynamicData.GetData. var testHost = TestHost.LocateFrom(AssetFixture.TargetAssetPath, AssetName, TargetFrameworks.NetCurrent); - TestHostResult testHostResult = await testHost.ExecuteAsync(); + TestHostResult testHostResult = await testHost.ExecuteAsync(cancellationToken: TestContext.CancellationToken); testHostResult.AssertOutputContains(""" 1,2 3,4 @@ -93,4 +93,6 @@ public void TestMethod1() .PatchCodeWithReplace("$MSTestVersion$", MSTestVersion)); } } + + public TestContext TestContext { get; set; } } diff --git a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/GenericTestMethodTests.cs b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/GenericTestMethodTests.cs index 99ee91910a..0222401ac1 100644 --- a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/GenericTestMethodTests.cs +++ b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/GenericTestMethodTests.cs @@ -15,7 +15,7 @@ public async Task TestDifferentGenericMethodTestCases() { var testHost = TestHost.LocateFrom(AssetFixture.GetAssetPath("GenericTestMethodTests"), "GenericTestMethodTests", TargetFrameworks.NetCurrent); - TestHostResult testHostResult = await testHost.ExecuteAsync(); + TestHostResult testHostResult = await testHost.ExecuteAsync(cancellationToken: TestContext.CancellationToken); testHostResult.AssertExitCodeIs(ExitCodes.AtLeastOneTestFailed); testHostResult.AssertOutputMatchesRegex( @@ -170,4 +170,6 @@ public static IEnumerable Data } """; } + + public TestContext TestContext { get; set; } } diff --git a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/HelpInfoTests.cs b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/HelpInfoTests.cs index ac09977edf..2f5bb7d2df 100644 --- a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/HelpInfoTests.cs +++ b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/HelpInfoTests.cs @@ -17,7 +17,7 @@ public class HelpInfoTests : AcceptanceTestBase public async Task Help_WhenMSTestExtensionRegistered_OutputHelpContentOfRegisteredExtension(string tfm) { var testHost = TestHost.LocateFrom(AssetFixture.TargetAssetPath, AssetName, tfm); - TestHostResult testHostResult = await testHost.ExecuteAsync("--help"); + TestHostResult testHostResult = await testHost.ExecuteAsync("--help", cancellationToken: TestContext.CancellationToken); testHostResult.AssertExitCodeIs(ExitCodes.Success); @@ -93,7 +93,7 @@ Output verbosity when reporting tests. public async Task Info_WhenMSTestExtensionRegistered_OutputInfoContentOfRegisteredExtension(string tfm) { var testHost = TestHost.LocateFrom(AssetFixture.TargetAssetPath, AssetName, tfm); - TestHostResult testHostResult = await testHost.ExecuteAsync("--info"); + TestHostResult testHostResult = await testHost.ExecuteAsync("--info", cancellationToken: TestContext.CancellationToken); testHostResult.AssertExitCodeIs(ExitCodes.Success); @@ -166,4 +166,6 @@ public void Test() {} } """; } + + public TestContext TestContext { get; set; } } diff --git a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/IgnoreTests.cs b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/IgnoreTests.cs index e173269e32..615f7748fe 100644 --- a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/IgnoreTests.cs +++ b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/IgnoreTests.cs @@ -14,7 +14,7 @@ public sealed class IgnoreTests : AcceptanceTestBase Data2 } """; } + + public TestContext TestContext { get; set; } } diff --git a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/InconclusiveTests.cs b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/InconclusiveTests.cs index 4e6678c47b..26b4cc714e 100644 --- a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/InconclusiveTests.cs +++ b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/InconclusiveTests.cs @@ -37,7 +37,8 @@ public async Task TestOutcomeShouldBeRespectedCorrectly(Lifecycle inconclusiveSt environmentVariables: new Dictionary { [$"{inconclusiveStep}Inconclusive"] = "1", - }); + }, + cancellationToken: TestContext.CancellationToken); if (inconclusiveStep >= Lifecycle.ClassCleanup) { @@ -232,4 +233,6 @@ public static void AsmCleanup(TestContext _) } """; } + + public TestContext TestContext { get; set; } } diff --git a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/LeakTests.cs b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/LeakTests.cs index fff4190e48..ddfe696468 100644 --- a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/LeakTests.cs +++ b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/LeakTests.cs @@ -14,7 +14,7 @@ public sealed class LeakTests : AcceptanceTestBase public async Task TestContextInstancesShouldNotLeak(string tfm) { var testHost = TestHost.LocateFrom(AssetFixture.ProjectPath, TestAssetFixture.ProjectName, tfm); - TestHostResult testHostResult = await testHost.ExecuteAsync(); + TestHostResult testHostResult = await testHost.ExecuteAsync(cancellationToken: TestContext.CancellationToken); testHostResult.AssertExitCodeIs(0); testHostResult.AssertOutputContainsSummary(failed: 0, passed: 100, skipped: 0); @@ -130,4 +130,6 @@ public static IEnumerable Data """; } + + public TestContext TestContext { get; set; } } diff --git a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/LifecycleTests.cs b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/LifecycleTests.cs index 98ceefdc11..3e233f13e3 100644 --- a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/LifecycleTests.cs +++ b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/LifecycleTests.cs @@ -15,7 +15,7 @@ public sealed class LifecycleTests : AcceptanceTestBase """; } + + public TestContext TestContext { get; set; } } diff --git a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/MSBuildRunnerTests.cs b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/MSBuildRunnerTests.cs index a65f29602d..61b0aa0643 100644 --- a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/MSBuildRunnerTests.cs +++ b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/MSBuildRunnerTests.cs @@ -64,10 +64,10 @@ public async Task MSBuildTestTarget_SingleAndMultiTfm_Should_Run_Solution_Tests( } // Build the solution - DotnetMuxerResult restoreResult = await DotnetCli.RunAsync($"restore -m:1 -nodeReuse:false {solution.SolutionFile} --configfile {nugetFile}", AcceptanceFixture.NuGetGlobalPackagesFolder.Path); + DotnetMuxerResult restoreResult = await DotnetCli.RunAsync($"restore -m:1 -nodeReuse:false {solution.SolutionFile} --configfile {nugetFile}", AcceptanceFixture.NuGetGlobalPackagesFolder.Path, cancellationToken: TestContext.CancellationToken); restoreResult.AssertOutputDoesNotContain("An approximate best match of"); - DotnetMuxerResult testResult = await DotnetCli.RunAsync($"{command} -m:1 -nodeReuse:false {solution.SolutionFile}", AcceptanceFixture.NuGetGlobalPackagesFolder.Path, workingDirectory: generator.TargetAssetPath); + DotnetMuxerResult testResult = await DotnetCli.RunAsync($"{command} -m:1 -nodeReuse:false {solution.SolutionFile}", AcceptanceFixture.NuGetGlobalPackagesFolder.Path, workingDirectory: generator.TargetAssetPath, cancellationToken: TestContext.CancellationToken); if (isMultiTfm) { @@ -85,4 +85,6 @@ public async Task MSBuildTestTarget_SingleAndMultiTfm_Should_Run_Solution_Tests( testResult.AssertOutputMatchesRegex($@"Tests succeeded: '.*TestProject2\..*' \[{singleTfmOrMultiTfm}\|x64\]"); } } + + public TestContext TestContext { get; set; } } diff --git a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/MaxFailedTestsExtensionTests.cs b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/MaxFailedTestsExtensionTests.cs index 0df04d170a..49ddd4443c 100644 --- a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/MaxFailedTestsExtensionTests.cs +++ b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/MaxFailedTestsExtensionTests.cs @@ -18,7 +18,7 @@ public async Task SimpleMaxFailedTestsScenario(string tfm) { var testHost = TestHost.LocateFrom(AssetFixture.TargetAssetPath, AssetName, tfm); - TestHostResult testHostResult = await testHost.ExecuteAsync("--maximum-failed-tests 3"); + TestHostResult testHostResult = await testHost.ExecuteAsync("--maximum-failed-tests 3", cancellationToken: TestContext.CancellationToken); testHostResult.AssertExitCodeIs(ExitCodes.TestExecutionStoppedForMaxFailedTests); int total = int.Parse(Regex.Match(testHostResult.StandardOutput, @"total: (\d+)").Groups[1].Value, CultureInfo.InvariantCulture); @@ -29,7 +29,7 @@ public async Task SimpleMaxFailedTestsScenario(string tfm) Assert.IsLessThan(12, total); Assert.IsGreaterThanOrEqualTo(5, total); - testHostResult = await testHost.ExecuteAsync(); + testHostResult = await testHost.ExecuteAsync(cancellationToken: TestContext.CancellationToken); testHostResult.AssertExitCodeIs(ExitCodes.AtLeastOneTestFailed); total = int.Parse(Regex.Match(testHostResult.StandardOutput, @"total: (\d+)").Groups[1].Value, CultureInfo.InvariantCulture); @@ -144,4 +144,6 @@ public async Task Test12() .PatchCodeWithReplace("$MSTestVersion$", MSTestVersion)); } } + + public TestContext TestContext { get; set; } } diff --git a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/NativeAotTests.cs b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/NativeAotTests.cs index 785fe47106..c867b34df3 100644 --- a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/NativeAotTests.cs +++ b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/NativeAotTests.cs @@ -108,18 +108,22 @@ await RetryHelper.RetryAsync( await DotnetCli.RunAsync( $"restore -m:1 -nodeReuse:false {generator.TargetAssetPath} -r {RID}", AcceptanceFixture.NuGetGlobalPackagesFolder.Path, - retryCount: 0); + retryCount: 0, + cancellationToken: TestContext.CancellationToken); DotnetMuxerResult compilationResult = await DotnetCli.RunAsync( $"publish -m:1 -nodeReuse:false {generator.TargetAssetPath} -r {RID}", AcceptanceFixture.NuGetGlobalPackagesFolder.Path, - retryCount: 0); + retryCount: 0, + cancellationToken: TestContext.CancellationToken); compilationResult.AssertOutputContains("Generating native code"); var testHost = TestHost.LocateFrom(generator.TargetAssetPath, "NativeAotTests", TargetFrameworks.NetCurrent, RID, Verb.publish); - TestHostResult result = await testHost.ExecuteAsync(); + TestHostResult result = await testHost.ExecuteAsync(cancellationToken: TestContext.CancellationToken); result.AssertOutputContains($"MSTest.Engine v{MSTestEngineVersion}"); result.AssertExitCodeIs(0); }, times: 15, every: TimeSpan.FromSeconds(5)); } + + public TestContext TestContext { get; set; } } diff --git a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/OutputTests.cs b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/OutputTests.cs index a52aaf0899..0a2f3d678e 100644 --- a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/OutputTests.cs +++ b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/OutputTests.cs @@ -14,7 +14,7 @@ public sealed class OutputTests : AcceptanceTestBase. Actual:<2>."); @@ -80,4 +80,6 @@ public void TestMethod() } """; } + + public TestContext TestContext { get; set; } } diff --git a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/ParameterizedTestTests.cs b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/ParameterizedTestTests.cs index 1783bf3843..92e1240e2f 100644 --- a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/ParameterizedTestTests.cs +++ b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/ParameterizedTestTests.cs @@ -50,7 +50,7 @@ public async Task UsingTestDataRowVariousCases(string currentTfm) { var testHost = TestHost.LocateFrom(AssetFixture.GetAssetPath(DynamicDataAssetName), DynamicDataAssetName, currentTfm); - TestHostResult testHostResult = await testHost.ExecuteAsync("--settings AppDomainEnabled.runsettings --filter ClassName=TestDataRowTests --list-tests"); + TestHostResult testHostResult = await testHost.ExecuteAsync("--settings AppDomainEnabled.runsettings --filter ClassName=TestDataRowTests --list-tests", cancellationToken: TestContext.CancellationToken); testHostResult.AssertOutputMatchesRegexLines(""" MSTest * TestDataRowSingleParameterFolded @@ -73,7 +73,7 @@ public async Task UsingTestDataRowVariousCases(string currentTfm) """); // progress causes flakiness. See https://github.com/microsoft/testfx/pull/4930#issuecomment-2648506466 - testHostResult = await testHost.ExecuteAsync("--filter ClassName=TestDataRowTests --no-progress"); + testHostResult = await testHost.ExecuteAsync("--filter ClassName=TestDataRowTests --no-progress", cancellationToken: TestContext.CancellationToken); testHostResult.AssertExitCodeIs(ExitCodes.Success); testHostResult.AssertOutputContainsSummary(failed: 0, passed: 9, skipped: 15); @@ -460,4 +460,6 @@ public class CustomEmptyTestDataSourceAttribute : Attribute, ITestDataSource } """; } + + public TestContext TestContext { get; set; } } diff --git a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/PublishAotNonNativeTests.cs b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/PublishAotNonNativeTests.cs index e2bdeecdad..2a148aac69 100644 --- a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/PublishAotNonNativeTests.cs +++ b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/PublishAotNonNativeTests.cs @@ -24,7 +24,7 @@ public async Task RunTests_ThatEnablePublishAOT_ButDontBuildToNative() .PatchCodeWithReplace("$TargetFramework$", $"{TargetFrameworks.NetCurrent}") .PatchCodeWithReplace("$MSTestVersion$", MSTestVersion)); - DotnetMuxerResult compilationResult = await DotnetCli.RunAsync($"test -c Debug {generator.TargetAssetPath}", AcceptanceFixture.NuGetGlobalPackagesFolder.Path, workingDirectory: generator.TargetAssetPath, failIfReturnValueIsNotZero: false); + DotnetMuxerResult compilationResult = await DotnetCli.RunAsync($"test -c Debug {generator.TargetAssetPath}", AcceptanceFixture.NuGetGlobalPackagesFolder.Path, workingDirectory: generator.TargetAssetPath, failIfReturnValueIsNotZero: false, cancellationToken: TestContext.CancellationToken); // In the real-world issue, access to path C:\Program Files\dotnet\ is denied, but we run this from a local .dotnet folder, where we have write access. // So instead of relying on the test run failing because of AccessDenied, we check the output, and see where TestResults were placed. @@ -89,4 +89,6 @@ public void TestMethod1() } } """; + + public TestContext TestContext { get; set; } } diff --git a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/RetryTests.cs b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/RetryTests.cs index 47172caaa4..54405e8e69 100644 --- a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/RetryTests.cs +++ b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/RetryTests.cs @@ -14,7 +14,7 @@ public sealed class RetryTests : AcceptanceTestBase public async Task BasicRetryScenarioTest() { var testHost = TestHost.LocateFrom(AssetFixture.ProjectPath, TestAssetFixture.ProjectName, TargetFrameworks.NetCurrent); - TestHostResult testHostResult = await testHost.ExecuteAsync("--settings my.runsettings"); + TestHostResult testHostResult = await testHost.ExecuteAsync("--settings my.runsettings", cancellationToken: TestContext.CancellationToken); testHostResult.AssertExitCodeIs(ExitCodes.AtLeastOneTestFailed); testHostResult.AssertOutputContains(""" @@ -145,4 +145,6 @@ public static void ClassCleanup() """; } + + public TestContext TestContext { get; set; } } diff --git a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/RunnerTests.cs b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/RunnerTests.cs index 977aa8e1ce..83035ada19 100644 --- a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/RunnerTests.cs +++ b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/RunnerTests.cs @@ -29,17 +29,17 @@ public async SystemTask EnableMSTestRunner_True_Will_Run_Standalone(string tfm, .PatchCodeWithReplace("$Extra$", string.Empty)); DotnetMuxerResult compilationResult = await DotnetCli.RunAsync( $"restore -m:1 -nodeReuse:false {generator.TargetAssetPath} -r {RID}", - AcceptanceFixture.NuGetGlobalPackagesFolder.Path); + AcceptanceFixture.NuGetGlobalPackagesFolder.Path, cancellationToken: TestContext.CancellationToken); compilationResult = await DotnetCli.RunAsync( $"{verb} -m:1 -nodeReuse:false {generator.TargetAssetPath} -c {buildConfiguration} -r {RID}", - AcceptanceFixture.NuGetGlobalPackagesFolder.Path); + AcceptanceFixture.NuGetGlobalPackagesFolder.Path, cancellationToken: TestContext.CancellationToken); Build binLog = Serialization.Read(compilationResult.BinlogPath); Assert.AreNotEqual(0, binLog.FindChildrenRecursive() .Count(x => x.Title.Contains("ProjectCapability") && x.Children.Any(c => ((Item)c).Name == "TestingPlatformServer"))); var testHost = TestHost.LocateFrom(generator.TargetAssetPath, AssetName, tfm, buildConfiguration: buildConfiguration, verb: verb); - TestHostResult testHostResult = await testHost.ExecuteAsync(); + TestHostResult testHostResult = await testHost.ExecuteAsync(cancellationToken: TestContext.CancellationToken); testHostResult.AssertOutputContainsSummary(failed: 0, passed: 1, skipped: 0); } @@ -68,12 +68,12 @@ public async SystemTask EnableMSTestRunner_True_WithCustomEntryPoint_Will_Run_St False preview """)); - await DotnetCli.RunAsync($"restore -m:1 -nodeReuse:false {generator.TargetAssetPath} -r {RID}", AcceptanceFixture.NuGetGlobalPackagesFolder.Path); + await DotnetCli.RunAsync($"restore -m:1 -nodeReuse:false {generator.TargetAssetPath} -r {RID}", AcceptanceFixture.NuGetGlobalPackagesFolder.Path, cancellationToken: TestContext.CancellationToken); await DotnetCli.RunAsync( $"{verb} -m:1 -nodeReuse:false {generator.TargetAssetPath} -c {buildConfiguration} -r {RID}", - AcceptanceFixture.NuGetGlobalPackagesFolder.Path); + AcceptanceFixture.NuGetGlobalPackagesFolder.Path, cancellationToken: TestContext.CancellationToken); var testHost = TestHost.LocateFrom(generator.TargetAssetPath, AssetName, tfm, buildConfiguration: buildConfiguration, verb: verb); - TestHostResult testHostResult = await testHost.ExecuteAsync(); + TestHostResult testHostResult = await testHost.ExecuteAsync(cancellationToken: TestContext.CancellationToken); testHostResult.AssertOutputContainsSummary(failed: 0, passed: 1, skipped: 0); } @@ -90,12 +90,12 @@ public async SystemTask EnableMSTestRunner_False_Will_Run_Empty_Program_EntryPoi .PatchCodeWithReplace("$EnableMSTestRunner$", "false") .PatchCodeWithReplace("$OutputType$", "Exe") .PatchCodeWithReplace("$Extra$", string.Empty)); - await DotnetCli.RunAsync($"restore -m:1 -nodeReuse:false {generator.TargetAssetPath} -r {RID}", AcceptanceFixture.NuGetGlobalPackagesFolder.Path); + await DotnetCli.RunAsync($"restore -m:1 -nodeReuse:false {generator.TargetAssetPath} -r {RID}", AcceptanceFixture.NuGetGlobalPackagesFolder.Path, cancellationToken: TestContext.CancellationToken); try { - await DotnetCli.RunAsync($"{verb} -m:1 -nodeReuse:false {generator.TargetAssetPath} -c {buildConfiguration} -r {RID}", AcceptanceFixture.NuGetGlobalPackagesFolder.Path); + await DotnetCli.RunAsync($"{verb} -m:1 -nodeReuse:false {generator.TargetAssetPath} -c {buildConfiguration} -r {RID}", AcceptanceFixture.NuGetGlobalPackagesFolder.Path, cancellationToken: TestContext.CancellationToken); var testHost = TestHost.LocateFrom(generator.TargetAssetPath, AssetName, tfm, buildConfiguration: buildConfiguration, verb: verb); - TestHostResult testHostResult = await testHost.ExecuteAsync(); + TestHostResult testHostResult = await testHost.ExecuteAsync(cancellationToken: TestContext.CancellationToken); Assert.AreEqual(string.Empty, testHostResult.StandardOutput); } catch (Exception ex) @@ -122,11 +122,13 @@ public async SystemTask EnableMSTestRunner_False_Wont_Flow_TestingPlatformServer .PatchCodeWithReplace("$OutputType$", string.Empty) .PatchCodeWithReplace("$Extra$", string.Empty)); - await DotnetCli.RunAsync($"restore -m:1 -nodeReuse:false {generator.TargetAssetPath} -r {RID}", AcceptanceFixture.NuGetGlobalPackagesFolder.Path); - DotnetMuxerResult result = await DotnetCli.RunAsync($"{verb} -m:1 -nodeReuse:false {generator.TargetAssetPath} -c {buildConfiguration} -r {RID} ", AcceptanceFixture.NuGetGlobalPackagesFolder.Path); + await DotnetCli.RunAsync($"restore -m:1 -nodeReuse:false {generator.TargetAssetPath} -r {RID}", AcceptanceFixture.NuGetGlobalPackagesFolder.Path, cancellationToken: TestContext.CancellationToken); + DotnetMuxerResult result = await DotnetCli.RunAsync($"{verb} -m:1 -nodeReuse:false {generator.TargetAssetPath} -c {buildConfiguration} -r {RID} ", AcceptanceFixture.NuGetGlobalPackagesFolder.Path, cancellationToken: TestContext.CancellationToken); Build binLog = Serialization.Read(result.BinlogPath); Assert.IsFalse(binLog.FindChildrenRecursive() .Any(x => x.Title.Contains("ProjectCapability") && x.Children.Any(c => ((Item)c).Name == "TestingPlatformServer"))); } + + public TestContext TestContext { get; set; } } diff --git a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/RunsettingsTests.cs b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/RunsettingsTests.cs index c2e213c7e7..2d484914f0 100644 --- a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/RunsettingsTests.cs +++ b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/RunsettingsTests.cs @@ -36,7 +36,7 @@ public sealed class RunSettingsTests : AcceptanceTestBasetrue")); - DotnetMuxerResult compilationResult = await DotnetCli.RunAsync($"test -c {buildConfiguration} {testAsset.TargetAssetPath}", AcceptanceFixture.NuGetGlobalPackagesFolder.Path, workingDirectory: testAsset.TargetAssetPath); + DotnetMuxerResult compilationResult = await DotnetCli.RunAsync($"test -c {buildConfiguration} {testAsset.TargetAssetPath}", AcceptanceFixture.NuGetGlobalPackagesFolder.Path, workingDirectory: testAsset.TargetAssetPath, cancellationToken: TestContext.CancellationToken); compilationResult.AssertExitCodeIs(0); compilationResult.AssertOutputMatchesRegex(@"Passed! - Failed: 0, Passed: 1, Skipped: 0, Total: 1, Duration: .* [m]?s - MSTestSdk.dll \(net9\.0\)"); @@ -91,7 +91,7 @@ public async Task RunTests_With_MSTestRunner_DotnetTest(string multiTfm, BuildCo .PatchCodeWithReplace("$TargetFramework$", multiTfm) .PatchCodeWithReplace("$ExtraProperties$", string.Empty)); - DotnetMuxerResult compilationResult = await DotnetCli.RunAsync($"test -c {buildConfiguration} {testAsset.TargetAssetPath}", AcceptanceFixture.NuGetGlobalPackagesFolder.Path, workingDirectory: testAsset.TargetAssetPath); + DotnetMuxerResult compilationResult = await DotnetCli.RunAsync($"test -c {buildConfiguration} {testAsset.TargetAssetPath}", AcceptanceFixture.NuGetGlobalPackagesFolder.Path, workingDirectory: testAsset.TargetAssetPath, cancellationToken: TestContext.CancellationToken); compilationResult.AssertExitCodeIs(0); compilationResult.AssertOutputMatchesRegex(@"Tests succeeded: .* \[net9\.0|x64\]"); @@ -118,12 +118,12 @@ public async Task RunTests_With_MSTestRunner_Standalone(string multiTfm, BuildCo .PatchCodeWithReplace("$TargetFramework$", multiTfm) .PatchCodeWithReplace("$ExtraProperties$", string.Empty)); - DotnetMuxerResult compilationResult = await DotnetCli.RunAsync($"build -c {buildConfiguration} {testAsset.TargetAssetPath}", AcceptanceFixture.NuGetGlobalPackagesFolder.Path); + DotnetMuxerResult compilationResult = await DotnetCli.RunAsync($"build -c {buildConfiguration} {testAsset.TargetAssetPath}", AcceptanceFixture.NuGetGlobalPackagesFolder.Path, cancellationToken: TestContext.CancellationToken); compilationResult.AssertExitCodeIs(0); foreach (string tfm in multiTfm.Split(";")) { var testHost = TestHost.LocateFrom(testAsset.TargetAssetPath, AssetName, tfm, buildConfiguration: buildConfiguration); - TestHostResult testHostResult = await testHost.ExecuteAsync(); + TestHostResult testHostResult = await testHost.ExecuteAsync(cancellationToken: TestContext.CancellationToken); testHostResult.AssertOutputContainsSummary(0, 1, 0); } } @@ -139,12 +139,12 @@ public async Task RunTests_With_CentralPackageManagement_Standalone(string multi .PatchCodeWithReplace("$TargetFramework$", multiTfm) .PatchCodeWithReplace("$ExtraProperties$", string.Empty)); - DotnetMuxerResult compilationResult = await DotnetCli.RunAsync($"build -c {buildConfiguration} {testAsset.TargetAssetPath}", AcceptanceFixture.NuGetGlobalPackagesFolder.Path); + DotnetMuxerResult compilationResult = await DotnetCli.RunAsync($"build -c {buildConfiguration} {testAsset.TargetAssetPath}", AcceptanceFixture.NuGetGlobalPackagesFolder.Path, cancellationToken: TestContext.CancellationToken); compilationResult.AssertExitCodeIs(0); foreach (string tfm in multiTfm.Split(";")) { var testHost = TestHost.LocateFrom(testAsset.TargetAssetPath, AssetName, tfm, buildConfiguration: buildConfiguration); - TestHostResult testHostResult = await testHost.ExecuteAsync(); + TestHostResult testHostResult = await testHost.ExecuteAsync(cancellationToken: TestContext.CancellationToken); testHostResult.AssertOutputContainsSummary(0, 1, 0); } } @@ -199,15 +199,15 @@ public async Task RunTests_With_MSTestRunner_Standalone_Selectively_Enabled_Exte .PatchCodeWithReplace("$TargetFramework$", multiTfm) .PatchCodeWithReplace("$ExtraProperties$", msbuildExtensionEnableFragment)); - DotnetMuxerResult compilationResult = await DotnetCli.RunAsync($"build -c {buildConfiguration} {testAsset.TargetAssetPath}", AcceptanceFixture.NuGetGlobalPackagesFolder.Path); + DotnetMuxerResult compilationResult = await DotnetCli.RunAsync($"build -c {buildConfiguration} {testAsset.TargetAssetPath}", AcceptanceFixture.NuGetGlobalPackagesFolder.Path, cancellationToken: TestContext.CancellationToken); compilationResult.AssertExitCodeIs(0); foreach (string tfm in multiTfm.Split(";")) { var testHost = TestHost.LocateFrom(testAsset.TargetAssetPath, AssetName, tfm, buildConfiguration: buildConfiguration); - TestHostResult testHostResult = await testHost.ExecuteAsync(command: enableCommandLineArg); + TestHostResult testHostResult = await testHost.ExecuteAsync(command: enableCommandLineArg, cancellationToken: TestContext.CancellationToken); testHostResult.AssertOutputContainsSummary(0, 1, 0); - testHostResult = await testHost.ExecuteAsync(command: invalidCommandLineArg); + testHostResult = await testHost.ExecuteAsync(command: invalidCommandLineArg, cancellationToken: TestContext.CancellationToken); Assert.AreEqual(ExitCodes.InvalidCommandLine, testHostResult.ExitCode); } } @@ -223,12 +223,12 @@ public async Task RunTests_With_MSTestRunner_Standalone_EnableAll_Extensions(str .PatchCodeWithReplace("$TargetFramework$", multiTfm) .PatchCodeWithReplace("$ExtraProperties$", "AllMicrosoft")); - DotnetMuxerResult compilationResult = await DotnetCli.RunAsync($"build -c {buildConfiguration} {testAsset.TargetAssetPath}", AcceptanceFixture.NuGetGlobalPackagesFolder.Path); + DotnetMuxerResult compilationResult = await DotnetCli.RunAsync($"build -c {buildConfiguration} {testAsset.TargetAssetPath}", AcceptanceFixture.NuGetGlobalPackagesFolder.Path, cancellationToken: TestContext.CancellationToken); compilationResult.AssertExitCodeIs(0); foreach (string tfm in multiTfm.Split(";")) { var testHost = TestHost.LocateFrom(testAsset.TargetAssetPath, AssetName, tfm, buildConfiguration: buildConfiguration); - TestHostResult testHostResult = await testHost.ExecuteAsync(command: "--coverage --retry-failed-tests 3 --report-trx --crashdump --hangdump --report-azdo"); + TestHostResult testHostResult = await testHost.ExecuteAsync(command: "--coverage --retry-failed-tests 3 --report-trx --crashdump --hangdump --report-azdo", cancellationToken: TestContext.CancellationToken); testHostResult.AssertOutputContainsSummary(0, 1, 0); } } @@ -253,12 +253,12 @@ public async Task RunTests_With_MSTestRunner_Standalone_Enable_Default_Extension .PatchCodeWithReplace("$TargetFramework$", multiTfm) .PatchCodeWithReplace("$ExtraProperties$", enableDefaultExtensions ? string.Empty : "None")); - DotnetMuxerResult compilationResult = await DotnetCli.RunAsync($"build -c {buildConfiguration} {testAsset.TargetAssetPath}", AcceptanceFixture.NuGetGlobalPackagesFolder.Path); + DotnetMuxerResult compilationResult = await DotnetCli.RunAsync($"build -c {buildConfiguration} {testAsset.TargetAssetPath}", AcceptanceFixture.NuGetGlobalPackagesFolder.Path, cancellationToken: TestContext.CancellationToken); compilationResult.AssertExitCodeIs(0); foreach (string tfm in multiTfm.Split(";")) { var testHost = TestHost.LocateFrom(testAsset.TargetAssetPath, AssetName, tfm, buildConfiguration: buildConfiguration); - TestHostResult testHostResult = await testHost.ExecuteAsync(command: "--coverage --report-trx"); + TestHostResult testHostResult = await testHost.ExecuteAsync(command: "--coverage --report-trx", cancellationToken: TestContext.CancellationToken); if (enableDefaultExtensions) { testHostResult.AssertOutputContainsSummary(0, 1, 0); @@ -281,7 +281,7 @@ public async Task Invalid_TestingProfile_Name_Should_Fail(string multiTfm, Build .PatchCodeWithReplace("$TargetFramework$", multiTfm) .PatchCodeWithReplace("$ExtraProperties$", "WrongName")); - DotnetMuxerResult compilationResult = await DotnetCli.RunAsync($"build -c {buildConfiguration} {testAsset.TargetAssetPath}", AcceptanceFixture.NuGetGlobalPackagesFolder.Path, failIfReturnValueIsNotZero: false); + DotnetMuxerResult compilationResult = await DotnetCli.RunAsync($"build -c {buildConfiguration} {testAsset.TargetAssetPath}", AcceptanceFixture.NuGetGlobalPackagesFolder.Path, failIfReturnValueIsNotZero: false, cancellationToken: TestContext.CancellationToken); compilationResult.AssertExitCodeIs(1); compilationResult.AssertOutputContains("Invalid value for property TestingExtensionsProfile. Valid values are 'Default', 'AllMicrosoft' and 'None'."); } @@ -316,12 +316,12 @@ public async Task NativeAot_Smoke_Test_Windows() $"publish -r {RID} -f net9.0 {testAsset.TargetAssetPath}", AcceptanceFixture.NuGetGlobalPackagesFolder.Path, // We prefer to use the outer retry mechanism as we need some extra checks - retryCount: 0); + retryCount: 0, cancellationToken: TestContext.CancellationToken); compilationResult.AssertOutputContains("Generating native code"); compilationResult.AssertOutputDoesNotContain("warning"); var testHost = TestHost.LocateFrom(testAsset.TargetAssetPath, AssetName, "net9.0", verb: Verb.publish); - TestHostResult testHostResult = await testHost.ExecuteAsync(); + TestHostResult testHostResult = await testHost.ExecuteAsync(cancellationToken: TestContext.CancellationToken); testHostResult.AssertExitCodeIs(ExitCodes.Success); testHostResult.AssertOutputContainsSummary(0, 1, 0); @@ -332,7 +332,7 @@ public async Task NativeAot_Smoke_Test_Windows() public async Task EnablePlaywrightProperty_WhenUsingRunner_AllowsToRunPlaywrightTests(string tfm) { var testHost = TestHost.LocateFrom(AssetFixture.PlaywrightProjectPath, TestAssetFixture.PlaywrightProjectName, tfm); - TestHostResult testHostResult = await testHost.ExecuteAsync(); + TestHostResult testHostResult = await testHost.ExecuteAsync(cancellationToken: TestContext.CancellationToken); // Depending on the machine, the test might fail due to the browser not being installed. // To avoid slowing down the tests, we will not run the installation so depending on machines we have different results. @@ -366,7 +366,8 @@ public async Task EnablePlaywrightProperty_WhenUsingVSTest_AllowsToRunPlaywright workingDirectory: AssetFixture.PlaywrightProjectPath, failIfReturnValueIsNotZero: false, warnAsError: false, - suppressPreviewDotNetMessage: false); + suppressPreviewDotNetMessage: false, + cancellationToken: TestContext.CancellationToken); // Ensure output contains the right platform banner dotnetTestResult.AssertOutputContains("VSTest version"); @@ -393,7 +394,7 @@ public async Task EnablePlaywrightProperty_WhenUsingVSTest_AllowsToRunPlaywright public async Task EnableAspireProperty_WhenUsingRunner_AllowsToRunAspireTests() { var testHost = TestHost.LocateFrom(AssetFixture.AspireProjectPath, TestAssetFixture.AspireProjectName, TargetFrameworks.NetCurrent); - TestHostResult testHostResult = await testHost.ExecuteAsync(); + TestHostResult testHostResult = await testHost.ExecuteAsync(cancellationToken: TestContext.CancellationToken); testHostResult.AssertOutputContainsSummary(0, 1, 0); } @@ -409,7 +410,8 @@ public async Task EnableAspireProperty_WhenUsingVSTest_AllowsToRunAspireTests() AcceptanceFixture.NuGetGlobalPackagesFolder.Path, workingDirectory: AssetFixture.AspireProjectPath, warnAsError: false, - suppressPreviewDotNetMessage: false); + suppressPreviewDotNetMessage: false, + cancellationToken: TestContext.CancellationToken); dotnetTestResult.AssertExitCodeIs(0); // Ensure output contains the right platform banner dotnetTestResult.AssertOutputContains("VSTest version"); @@ -426,7 +428,7 @@ public async Task SettingIsTestApplicationToFalseReducesAddedExtensionsAndMakesP .PatchCodeWithReplace("$TargetFramework$", TargetFrameworks.NetCurrent) .PatchCodeWithReplace("$ExtraProperties$", "false")); - DotnetMuxerResult compilationResult = await DotnetCli.RunAsync($"test {testAsset.TargetAssetPath}", AcceptanceFixture.NuGetGlobalPackagesFolder.Path, workingDirectory: testAsset.TargetAssetPath); + DotnetMuxerResult compilationResult = await DotnetCli.RunAsync($"test {testAsset.TargetAssetPath}", AcceptanceFixture.NuGetGlobalPackagesFolder.Path, workingDirectory: testAsset.TargetAssetPath, cancellationToken: TestContext.CancellationToken); compilationResult.AssertExitCodeIs(0); @@ -560,4 +562,6 @@ public async Task HomepageHasPlaywrightInTitleAndGetStartedLinkLinkingToTheIntro .PatchCodeWithReplace("$MSTestVersion$", MSTestVersion)); } } + + public TestContext TestContext { get; set; } } diff --git a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/ServerModeTests.cs b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/ServerModeTests.cs index a4975ed3da..d6ce030865 100644 --- a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/ServerModeTests.cs +++ b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/ServerModeTests.cs @@ -11,6 +11,8 @@ namespace MSTest.Acceptance.IntegrationTests; [TestClass] public sealed class ServerModeTests : ServerModeTestsBase { + public TestContext TestContext { get; set; } + [TestMethod] [DynamicData(nameof(TargetFrameworks.AllForDynamicData), typeof(TargetFrameworks))] public async Task DiscoverAndRun(string tfm) @@ -39,7 +41,7 @@ public async Task DiscoverAndRun(string tfm) Assert.AreNotEqual(0, logs.Count, "Logs are empty"); Assert.IsFalse(telemetry.IsEmpty, "telemetry is empty"); await jsonClient.Exit(); - Assert.AreEqual(0, await jsonClient.WaitServerProcessExit()); + Assert.AreEqual(0, await jsonClient.WaitServerProcessExit(TestContext.CancellationToken)); Assert.AreEqual(0, jsonClient.ExitCode); } @@ -63,7 +65,7 @@ public async Task WhenClientDies_Server_ShouldClose_Gracefully(string tfm) _ = jsonClient.DiscoverTests(Guid.NewGuid(), discoveryCollector.CollectNodeUpdates, @checked: false); await jsonClient.Exit(gracefully: false); - int exitCode = await jsonClient.WaitServerProcessExit(); + int exitCode = await jsonClient.WaitServerProcessExit(TestContext.CancellationToken); Assert.AreEqual(3, exitCode); } diff --git a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/TestContextTests.cs b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/TestContextTests.cs index 06b1624ef7..2da2326fd3 100644 --- a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/TestContextTests.cs +++ b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/TestContextTests.cs @@ -14,7 +14,7 @@ public sealed class TestContextTests : AcceptanceTestBase[h|m|s] where 'value' is float"); @@ -534,7 +549,7 @@ public async Task TimeoutWithInvalidArg_WithoutLetterSuffix_OutputInvalidMessage public async Task TimeoutWithInvalidArg_WithInvalidLetterSuffix_OutputInvalidMessage(string tfm) { var testHost = TestHost.LocateFrom(AssetFixture.NoExtensionTargetAssetPath, TestAssetFixture.AssetName, tfm); - TestHostResult testHostResult = await testHost.ExecuteAsync("--timeout 5y"); + TestHostResult testHostResult = await testHost.ExecuteAsync("--timeout 5y", cancellationToken: TestContext.CancellationToken); testHostResult.AssertExitCodeIs(ExitCodes.InvalidCommandLine); testHostResult.AssertOutputContains("'timeout' option should have one argument as string in the format [h|m|s] where 'value' is float"); @@ -545,7 +560,7 @@ public async Task TimeoutWithInvalidArg_WithInvalidLetterSuffix_OutputInvalidMes public async Task TimeoutWithInvalidArg_WithInvalidFormat_OutputInvalidMessage(string tfm) { var testHost = TestHost.LocateFrom(AssetFixture.NoExtensionTargetAssetPath, TestAssetFixture.AssetName, tfm); - TestHostResult testHostResult = await testHost.ExecuteAsync("--timeout 5h6m"); + TestHostResult testHostResult = await testHost.ExecuteAsync("--timeout 5h6m", cancellationToken: TestContext.CancellationToken); testHostResult.AssertExitCodeIs(ExitCodes.InvalidCommandLine); testHostResult.AssertOutputContains("'timeout' option should have one argument as string in the format [h|m|s] where 'value' is float"); @@ -556,7 +571,7 @@ public async Task TimeoutWithInvalidArg_WithInvalidFormat_OutputInvalidMessage(s public async Task Timeout_WhenTimeoutValueSmallerThanTestDuration_OutputContainsCancelingMessage(string tfm) { var testHost = TestHost.LocateFrom(AssetFixture.NoExtensionTargetAssetPath, TestAssetFixture.AssetName, tfm); - TestHostResult testHostResult = await testHost.ExecuteAsync("--timeout 1s"); + TestHostResult testHostResult = await testHost.ExecuteAsync("--timeout 1s", cancellationToken: TestContext.CancellationToken); testHostResult.AssertExitCodeIsNot(ExitCodes.Success); testHostResult.AssertOutputContains("Canceling the test session"); @@ -567,7 +582,7 @@ public async Task Timeout_WhenTimeoutValueSmallerThanTestDuration_OutputContains public async Task Timeout_WhenTimeoutValueGreaterThanTestDuration_OutputDoesNotContainCancelingMessage(string tfm) { var testHost = TestHost.LocateFrom(AssetFixture.NoExtensionTargetAssetPath, TestAssetFixture.AssetName, tfm); - TestHostResult testHostResult = await testHost.ExecuteAsync("--timeout 30s"); + TestHostResult testHostResult = await testHost.ExecuteAsync("--timeout 30s", cancellationToken: TestContext.CancellationToken); testHostResult.AssertExitCodeIs(ExitCodes.Success); @@ -579,10 +594,12 @@ public async Task Timeout_WhenTimeoutValueGreaterThanTestDuration_OutputDoesNotC public async Task Timeout_WhenMethodTimeoutAndWaitInCtor_TestGetsCanceled(string tfm) { var testHost = TestHost.LocateFrom(AssetFixture.TestMethodTimeoutAssetPath, TestAssetFixture.TestMethodTimeout, tfm); - TestHostResult testHostResult = await testHost.ExecuteAsync(environmentVariables: new() - { - ["LONG_WAIT_CTOR"] = "1", - }); + TestHostResult testHostResult = await testHost.ExecuteAsync( + environmentVariables: new() + { + ["LONG_WAIT_CTOR"] = "1", + }, + cancellationToken: TestContext.CancellationToken); testHostResult.AssertExitCodeIs(ExitCodes.AtLeastOneTestFailed); testHostResult.AssertOutputContains("Test 'TestMethod' timed out after 1000ms"); @@ -593,10 +610,12 @@ public async Task Timeout_WhenMethodTimeoutAndWaitInCtor_TestGetsCanceled(string public async Task Timeout_WhenMethodTimeoutAndWaitInTestInit_TestGetsCanceled(string tfm) { var testHost = TestHost.LocateFrom(AssetFixture.TestMethodTimeoutAssetPath, TestAssetFixture.TestMethodTimeout, tfm); - TestHostResult testHostResult = await testHost.ExecuteAsync(environmentVariables: new() - { - ["LONG_WAIT_TESTINIT"] = "1", - }); + TestHostResult testHostResult = await testHost.ExecuteAsync( + environmentVariables: new() + { + ["LONG_WAIT_TESTINIT"] = "1", + }, + cancellationToken: TestContext.CancellationToken); testHostResult.AssertExitCodeIs(ExitCodes.AtLeastOneTestFailed); testHostResult.AssertOutputContains("Test 'TestMethod' timed out after 1000ms"); @@ -607,10 +626,12 @@ public async Task Timeout_WhenMethodTimeoutAndWaitInTestInit_TestGetsCanceled(st public async Task Timeout_WhenMethodTimeoutAndWaitInTestCleanup_TestGetsCanceled(string tfm) { var testHost = TestHost.LocateFrom(AssetFixture.TestMethodTimeoutAssetPath, TestAssetFixture.TestMethodTimeout, tfm); - TestHostResult testHostResult = await testHost.ExecuteAsync(environmentVariables: new() - { - ["LONG_WAIT_TESTCLEANUP"] = "1", - }); + TestHostResult testHostResult = await testHost.ExecuteAsync( + environmentVariables: new() + { + ["LONG_WAIT_TESTCLEANUP"] = "1", + }, + cancellationToken: TestContext.CancellationToken); testHostResult.AssertExitCodeIs(ExitCodes.AtLeastOneTestFailed); testHostResult.AssertOutputContains("Test 'TestMethod' timed out after 1000ms"); @@ -621,10 +642,12 @@ public async Task Timeout_WhenMethodTimeoutAndWaitInTestCleanup_TestGetsCanceled public async Task Timeout_WhenMethodTimeoutAndWaitInTestMethod_TestGetsCanceled(string tfm) { var testHost = TestHost.LocateFrom(AssetFixture.TestMethodTimeoutAssetPath, TestAssetFixture.TestMethodTimeout, tfm); - TestHostResult testHostResult = await testHost.ExecuteAsync(environmentVariables: new() - { - ["LONG_WAIT_TEST"] = "1", - }); + TestHostResult testHostResult = await testHost.ExecuteAsync( + environmentVariables: new() + { + ["LONG_WAIT_TEST"] = "1", + }, + cancellationToken: TestContext.CancellationToken); testHostResult.AssertExitCodeIs(ExitCodes.AtLeastOneTestFailed); testHostResult.AssertOutputContains("Test 'TestMethod' timed out after 1000ms"); @@ -635,10 +658,12 @@ public async Task Timeout_WhenMethodTimeoutAndWaitInTestMethod_TestGetsCanceled( public async Task CooperativeTimeout_WhenMethodTimeoutAndWaitInCtor_TestGetsCanceled(string tfm) { var testHost = TestHost.LocateFrom(AssetFixture.CooperativeTestMethodTimeoutAssetPath, TestAssetFixture.CooperativeTestMethodTimeout, tfm); - TestHostResult testHostResult = await testHost.ExecuteAsync(environmentVariables: new() - { - ["LONG_WAIT_CTOR"] = "1", - }); + TestHostResult testHostResult = await testHost.ExecuteAsync( + environmentVariables: new() + { + ["LONG_WAIT_CTOR"] = "1", + }, + cancellationToken: TestContext.CancellationToken); testHostResult.AssertExitCodeIs(ExitCodes.AtLeastOneTestFailed); testHostResult.AssertOutputContains("Test 'TestMethod' timed out after 1000ms"); @@ -649,10 +674,12 @@ public async Task CooperativeTimeout_WhenMethodTimeoutAndWaitInCtor_TestGetsCanc public async Task CooperativeTimeout_WhenMethodTimeoutAndWaitInTestInit_TestGetsCanceled(string tfm) { var testHost = TestHost.LocateFrom(AssetFixture.CooperativeTestMethodTimeoutAssetPath, TestAssetFixture.CooperativeTestMethodTimeout, tfm); - TestHostResult testHostResult = await testHost.ExecuteAsync(environmentVariables: new() - { - ["LONG_WAIT_TESTINIT"] = "1", - }); + TestHostResult testHostResult = await testHost.ExecuteAsync( + environmentVariables: new() + { + ["LONG_WAIT_TESTINIT"] = "1", + }, + cancellationToken: TestContext.CancellationToken); testHostResult.AssertExitCodeIs(ExitCodes.AtLeastOneTestFailed); testHostResult.AssertOutputContains("Test initialize method 'TimeoutTest.UnitTest1.TestInit' timed out after 1000ms"); @@ -663,10 +690,12 @@ public async Task CooperativeTimeout_WhenMethodTimeoutAndWaitInTestInit_TestGets public async Task CooperativeTimeout_WhenMethodTimeoutAndWaitInTestCleanup_TestGetsCanceled(string tfm) { var testHost = TestHost.LocateFrom(AssetFixture.CooperativeTestMethodTimeoutAssetPath, TestAssetFixture.CooperativeTestMethodTimeout, tfm); - TestHostResult testHostResult = await testHost.ExecuteAsync(environmentVariables: new() - { - ["LONG_WAIT_TESTCLEANUP"] = "1", - }); + TestHostResult testHostResult = await testHost.ExecuteAsync( + environmentVariables: new() + { + ["LONG_WAIT_TESTCLEANUP"] = "1", + }, + cancellationToken: TestContext.CancellationToken); testHostResult.AssertExitCodeIs(ExitCodes.AtLeastOneTestFailed); testHostResult.AssertOutputContains("Test cleanup method 'TimeoutTest.UnitTest1.TestCleanup' timed out after 1000ms"); @@ -677,10 +706,12 @@ public async Task CooperativeTimeout_WhenMethodTimeoutAndWaitInTestCleanup_TestG public async Task CooperativeTimeout_WhenMethodTimeoutAndWaitInTestMethod_TestGetsCanceled(string tfm) { var testHost = TestHost.LocateFrom(AssetFixture.CooperativeTestMethodTimeoutAssetPath, TestAssetFixture.CooperativeTestMethodTimeout, tfm); - TestHostResult testHostResult = await testHost.ExecuteAsync(environmentVariables: new() - { - ["LONG_WAIT_TEST"] = "1", - }); + TestHostResult testHostResult = await testHost.ExecuteAsync( + environmentVariables: new() + { + ["LONG_WAIT_TEST"] = "1", + }, + cancellationToken: TestContext.CancellationToken); testHostResult.AssertExitCodeIs(ExitCodes.AtLeastOneTestFailed); testHostResult.AssertOutputContains("Test 'TestMethod' timed out after 1000ms"); @@ -1193,4 +1224,6 @@ public async Task TestMethod() .PatchCodeWithReplace("$MSTestVersion$", MSTestVersion)); } } + + public TestContext TestContext { get; set; } } diff --git a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/TupleDynamicDataTests.cs b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/TupleDynamicDataTests.cs index 2ba790b710..fd87953f65 100644 --- a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/TupleDynamicDataTests.cs +++ b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/TupleDynamicDataTests.cs @@ -15,7 +15,7 @@ public sealed class TupleDynamicDataTests : AcceptanceTestBase GetData() """; } + + public TestContext TestContext { get; set; } } diff --git a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/ValueTaskTests.cs b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/ValueTaskTests.cs index acaed7964b..54ecbb6a4e 100644 --- a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/ValueTaskTests.cs +++ b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/ValueTaskTests.cs @@ -14,7 +14,7 @@ public sealed class ValueTaskTests : AcceptanceTestBase { { "TESTINGPLATFORM_NOBANNER", "true" }, - }); + }, + cancellationToken: TestContext.CancellationToken); testHostResult.AssertExitCodeIs(ExitCodes.ZeroTests); testHostResult.AssertOutputDoesNotContain(TestAssetFixture.CustomBannerPrefix); @@ -45,7 +46,8 @@ public async Task UsingDotnetNoLogo_InTheEnvironmentVars_TheBannerDoesNotAppear( new Dictionary { { "DOTNET_NOLOGO", "true" }, - }); + }, + cancellationToken: TestContext.CancellationToken); testHostResult.AssertExitCodeIs(ExitCodes.ZeroTests); testHostResult.AssertOutputDoesNotContain(TestAssetFixture.CustomBannerPrefix); @@ -56,7 +58,7 @@ public async Task UsingDotnetNoLogo_InTheEnvironmentVars_TheBannerDoesNotAppear( public async Task WithoutUsingNoBanner_TheBannerAppears(string tfm) { var testHost = TestInfrastructure.TestHost.LocateFrom(AssetFixture.TargetAssetPath, AssetName, tfm); - TestHostResult testHostResult = await testHost.ExecuteAsync(); + TestHostResult testHostResult = await testHost.ExecuteAsync(cancellationToken: TestContext.CancellationToken); testHostResult.AssertExitCodeIs(ExitCodes.ZeroTests); testHostResult.AssertOutputMatchesRegex($"{TestAssetFixture.CustomBannerPrefix} Platform info: Name: Microsoft.Testing.Platform, Version: .+?, Hash: .*?, Date: .+?"); @@ -162,4 +164,6 @@ public Task ExecuteRequestAsync(ExecuteRequestContext context) .PatchCodeWithReplace("$MicrosoftTestingPlatformVersion$", MicrosoftTestingPlatformVersion)); } } + + public TestContext TestContext { get; set; } } diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/DiagnosticTests.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/DiagnosticTests.cs index d0dae9f7c3..a6dceec769 100644 --- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/DiagnosticTests.cs +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/DiagnosticTests.cs @@ -18,7 +18,7 @@ public async Task Diag_WhenDiagnosticIsSpecified_ReportIsGeneratedInDefaultLocat string diagPathPattern = Path.Combine(diagPath, @"log_.*.diag").Replace(@"\", @"\\"); var testHost = TestInfrastructure.TestHost.LocateFrom(AssetFixture.TargetAssetPath, AssetName, tfm); - TestHostResult testHostResult = await testHost.ExecuteAsync("--diagnostic"); + TestHostResult testHostResult = await testHost.ExecuteAsync("--diagnostic", cancellationToken: TestContext.CancellationToken); await AssertDiagnosticReportWasGeneratedAsync(testHostResult, diagPathPattern); } @@ -31,7 +31,7 @@ public async Task Diag_WhenDiagnosticAndOutputFilePrefixAreSpecified_ReportIsGen string diagPathPattern = Path.Combine(diagPath, @"abcd_.*.diag").Replace(@"\", @"\\"); var testHost = TestInfrastructure.TestHost.LocateFrom(AssetFixture.TargetAssetPath, AssetName, tfm); - TestHostResult testHostResult = await testHost.ExecuteAsync("--diagnostic --diagnostic-output-fileprefix abcd"); + TestHostResult testHostResult = await testHost.ExecuteAsync("--diagnostic --diagnostic-output-fileprefix abcd", cancellationToken: TestContext.CancellationToken); await AssertDiagnosticReportWasGeneratedAsync(testHostResult, diagPathPattern); } @@ -46,7 +46,7 @@ public async Task Diag_WhenDiagnosticAndOutputDirectoryAreSpecified_ReportIsGene Assert.IsTrue(Directory.CreateDirectory(diagPath).Exists); var testHost = TestInfrastructure.TestHost.LocateFrom(AssetFixture.TargetAssetPath, AssetName, tfm); - TestHostResult testHostResult = await testHost.ExecuteAsync($"--diagnostic --diagnostic-output-directory {diagPath}"); + TestHostResult testHostResult = await testHost.ExecuteAsync($"--diagnostic --diagnostic-output-directory {diagPath}", cancellationToken: TestContext.CancellationToken); await AssertDiagnosticReportWasGeneratedAsync(testHostResult, diagPathPattern); } @@ -61,7 +61,7 @@ public async Task Diag_WhenDiagnosticAndOutputFilePrefixAndOutputDirectoryAreSpe Assert.IsTrue(Directory.CreateDirectory(diagPath).Exists); var testHost = TestInfrastructure.TestHost.LocateFrom(AssetFixture.TargetAssetPath, AssetName, tfm); - TestHostResult testHostResult = await testHost.ExecuteAsync($"--diagnostic --diagnostic-output-fileprefix abcde --diagnostic-output-directory {diagPath}"); + TestHostResult testHostResult = await testHost.ExecuteAsync($"--diagnostic --diagnostic-output-fileprefix abcde --diagnostic-output-directory {diagPath}", cancellationToken: TestContext.CancellationToken); await AssertDiagnosticReportWasGeneratedAsync(testHostResult, diagPathPattern); } @@ -71,7 +71,7 @@ public async Task Diag_WhenDiagnosticAndOutputFilePrefixAndOutputDirectoryAreSpe public async Task Diag_WhenDiagnosticOutputFilePrefixButNotDiagnosticIsSpecified_ReportGenerationFails(string tfm) { var testHost = TestInfrastructure.TestHost.LocateFrom(AssetFixture.TargetAssetPath, AssetName, tfm); - TestHostResult testHostResult = await testHost.ExecuteAsync("--diagnostic-output-fileprefix cccc"); + TestHostResult testHostResult = await testHost.ExecuteAsync("--diagnostic-output-fileprefix cccc", cancellationToken: TestContext.CancellationToken); testHostResult.AssertExitCodeIs(ExitCodes.InvalidCommandLine); testHostResult.AssertOutputContains("'--diagnostic-output-fileprefix' requires '--diagnostic' to be provided"); @@ -82,7 +82,7 @@ public async Task Diag_WhenDiagnosticOutputFilePrefixButNotDiagnosticIsSpecified public async Task Diag_WhenDiagnosticOutputDirectoryButNotDiagnosticIsSpecified_ReportGenerationFails(string tfm) { var testHost = TestInfrastructure.TestHost.LocateFrom(AssetFixture.TargetAssetPath, AssetName, tfm); - TestHostResult testHostResult = await testHost.ExecuteAsync("--diagnostic-output-directory cccc"); + TestHostResult testHostResult = await testHost.ExecuteAsync("--diagnostic-output-directory cccc", cancellationToken: TestContext.CancellationToken); testHostResult.AssertExitCodeIs(ExitCodes.InvalidCommandLine); testHostResult.AssertOutputContains("'--diagnostic-output-directory' requires '--diagnostic' to be provided"); @@ -93,7 +93,7 @@ public async Task Diag_WhenDiagnosticOutputDirectoryButNotDiagnosticIsSpecified_ public async Task Diag_WhenDiagnosticFilePrefixAndDiagnosticOutputDirectoryButNotDiagnosticAreSpecified_ReportGenerationFails(string tfm) { var testHost = TestInfrastructure.TestHost.LocateFrom(AssetFixture.TargetAssetPath, AssetName, tfm); - TestHostResult testHostResult = await testHost.ExecuteAsync("--diagnostic-output-fileprefix aaaa --diagnostic-output-directory cccc"); + TestHostResult testHostResult = await testHost.ExecuteAsync("--diagnostic-output-fileprefix aaaa --diagnostic-output-directory cccc", cancellationToken: TestContext.CancellationToken); testHostResult.AssertExitCodeIs(ExitCodes.InvalidCommandLine); testHostResult.AssertOutputContains("'--diagnostic-output-directory' requires '--diagnostic' to be provided"); @@ -112,7 +112,7 @@ public async Task Diag_EnableWithEnvironmentVariables_Succeeded(string tfm) new Dictionary { { EnvironmentVariableConstants.TESTINGPLATFORM_DIAGNOSTIC, "1" }, - }); + }, cancellationToken: TestContext.CancellationToken); await AssertDiagnosticReportWasGeneratedAsync(testHostResult, diagPathPattern); } @@ -131,7 +131,8 @@ public async Task Diag_EnableWithEnvironmentVariables_Verbosity_Succeeded(string { { EnvironmentVariableConstants.TESTINGPLATFORM_DIAGNOSTIC, "1" }, { EnvironmentVariableConstants.TESTINGPLATFORM_DIAGNOSTIC_VERBOSITY, "Trace" }, - }); + }, + cancellationToken: TestContext.CancellationToken); await AssertDiagnosticReportWasGeneratedAsync(testHostResult, diagPathPattern); } @@ -150,7 +151,8 @@ public async Task Diag_EnableWithEnvironmentVariables_CustomPrefix_Succeeded(str { { EnvironmentVariableConstants.TESTINGPLATFORM_DIAGNOSTIC, "1" }, { EnvironmentVariableConstants.TESTINGPLATFORM_DIAGNOSTIC_OUTPUT_FILEPREFIX, "MyPrefix" }, - }); + }, + cancellationToken: TestContext.CancellationToken); await AssertDiagnosticReportWasGeneratedAsync(testHostResult, diagPathPattern); } @@ -169,7 +171,8 @@ public async Task Diag_EnableWithEnvironmentVariables_SynchronousWrite_Succeeded { { EnvironmentVariableConstants.TESTINGPLATFORM_DIAGNOSTIC, "1" }, { EnvironmentVariableConstants.TESTINGPLATFORM_DIAGNOSTIC_FILELOGGER_SYNCHRONOUSWRITE, "1" }, - }); + }, + cancellationToken: TestContext.CancellationToken); await AssertDiagnosticReportWasGeneratedAsync(testHostResult, diagPathPattern, flushType: "sync"); } @@ -185,11 +188,12 @@ public async Task Diag_EnableWithEnvironmentVariables_Disable_Succeeded(string t new Dictionary { { EnvironmentVariableConstants.TESTINGPLATFORM_DIAGNOSTIC, "0" }, - }); + }, + cancellationToken: TestContext.CancellationToken); testHostResult.AssertExitCodeIs(ExitCodes.ZeroTests); testHostResult.AssertOutputDoesNotContain("Diagnostic file"); - testHostResult = await testHost.ExecuteAsync("--diagnostic"); + testHostResult = await testHost.ExecuteAsync("--diagnostic", cancellationToken: TestContext.CancellationToken); testHostResult.AssertExitCodeIs(ExitCodes.ZeroTests); testHostResult.AssertOutputContains("Diagnostic file"); } @@ -296,4 +300,6 @@ public Task ExecuteRequestAsync(ExecuteRequestContext context) .PatchCodeWithReplace("$MicrosoftTestingPlatformVersion$", MicrosoftTestingPlatformVersion)); } } + + public TestContext TestContext { get; set; } } diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/EnvironmentVariablesConfigurationProviderTests.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/EnvironmentVariablesConfigurationProviderTests.cs index a3c16669da..a715df1c6f 100644 --- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/EnvironmentVariablesConfigurationProviderTests.cs +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/EnvironmentVariablesConfigurationProviderTests.cs @@ -13,7 +13,7 @@ public sealed class EnvironmentVariablesConfigurationProviderTests : AcceptanceT public async Task SetEnvironmentVariable_ShouldSucceed(string currentTfm) { var testHost = TestInfrastructure.TestHost.LocateFrom(AssetFixture.TargetAssetPath, AssetName, currentTfm); - TestHostResult testHostResult = await testHost.ExecuteAsync(); + TestHostResult testHostResult = await testHost.ExecuteAsync(cancellationToken: TestContext.CancellationToken); testHostResult.AssertExitCodeIs(ExitCodes.Success); } @@ -136,4 +136,6 @@ public async Task ExecuteRequestAsync(ExecuteRequestContext context) .PatchCodeWithReplace("$MicrosoftTestingPlatformVersion$", MicrosoftTestingPlatformVersion)); } } + + public TestContext TestContext { get; set; } } diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/ExecutionTests.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/ExecutionTests.cs index ece6d5b0fe..b80efbe3e1 100644 --- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/ExecutionTests.cs +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/ExecutionTests.cs @@ -14,7 +14,7 @@ public class ExecutionTests : AcceptanceTestBase\""); + TestHostResult testHostResult = await testHost.ExecuteAsync("--list-tests --treenode-filter \"\"", cancellationToken: TestContext.CancellationToken); testHostResult.AssertExitCodeIs(ExitCodes.Success); @@ -116,7 +116,7 @@ public async Task Exec_WhenListTestsAndFilterAreSpecified_OnlyFilteredTestsAreFo public async Task Exec_WhenFilterIsSpecified_OnlyFilteredTestsAreRun(string tfm) { var testHost = TestInfrastructure.TestHost.LocateFrom(AssetFixture.TargetAssetPath, AssetName, tfm); - TestHostResult testHostResult = await testHost.ExecuteAsync("--treenode-filter \"\""); + TestHostResult testHostResult = await testHost.ExecuteAsync("--treenode-filter \"\"", cancellationToken: TestContext.CancellationToken); testHostResult.AssertExitCodeIs(ExitCodes.Success); @@ -129,7 +129,7 @@ public async Task Exec_WhenFilterIsSpecified_OnlyFilteredTestsAreRun(string tfm) public async Task Exec_WhenMinimumExpectedTestsIsSpecifiedAndEnoughTestsRun_ResultIsOk(string tfm) { var testHost = TestInfrastructure.TestHost.LocateFrom(AssetFixture.TargetAssetPath, AssetName, tfm); - TestHostResult testHostResult = await testHost.ExecuteAsync("--minimum-expected-tests 2"); + TestHostResult testHostResult = await testHost.ExecuteAsync("--minimum-expected-tests 2", cancellationToken: TestContext.CancellationToken); testHostResult.AssertExitCodeIs(ExitCodes.Success); @@ -142,7 +142,7 @@ public async Task Exec_WhenMinimumExpectedTestsIsSpecifiedAndEnoughTestsRun_Resu public async Task Exec_WhenMinimumExpectedTestsIsSpecifiedAndNotEnoughTestsRun_ResultIsNotOk(string tfm) { var testHost = TestInfrastructure.TestHost.LocateFrom(AssetFixture.TargetAssetPath, AssetName, tfm); - TestHostResult testHostResult = await testHost.ExecuteAsync("--minimum-expected-tests 3"); + TestHostResult testHostResult = await testHost.ExecuteAsync("--minimum-expected-tests 3", cancellationToken: TestContext.CancellationToken); testHostResult.AssertExitCodeIs(ExitCodes.MinimumExpectedTestsPolicyViolation); @@ -155,7 +155,7 @@ public async Task Exec_WhenMinimumExpectedTestsIsSpecifiedAndNotEnoughTestsRun_R public async Task Exec_WhenListTestsAndMinimumExpectedTestsAreSpecified_DiscoveryFails(string tfm) { var testHost = TestInfrastructure.TestHost.LocateFrom(AssetFixture.TargetAssetPath, AssetName, tfm); - TestHostResult testHostResult = await testHost.ExecuteAsync("--list-tests --minimum-expected-tests 2"); + TestHostResult testHostResult = await testHost.ExecuteAsync("--list-tests --minimum-expected-tests 2", cancellationToken: TestContext.CancellationToken); testHostResult.AssertExitCodeIs(ExitCodes.InvalidCommandLine); testHostResult.AssertOutputContains("Error: '--list-tests' and '--minimum-expected-tests' are incompatible options"); @@ -167,7 +167,7 @@ public async Task Exec_Honor_Request_Complete(string tfm) { var testHost = TestInfrastructure.TestHost.LocateFrom(AssetFixture.TargetAssetPath2, AssetName2, tfm); var stopwatch = Stopwatch.StartNew(); - TestHostResult testHostResult = await testHost.ExecuteAsync(); + TestHostResult testHostResult = await testHost.ExecuteAsync(cancellationToken: TestContext.CancellationToken); stopwatch.Stop(); Assert.AreEqual(ExitCodes.Success, testHostResult.ExitCode); Assert.IsGreaterThan(3, stopwatch.Elapsed.TotalSeconds); @@ -386,4 +386,6 @@ internal class Capabilities : ITestFrameworkCapabilities .PatchCodeWithReplace("$MicrosoftTestingPlatformVersion$", MicrosoftTestingPlatformVersion)); } } + + public TestContext TestContext { get; set; } } diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/ExitOnProcessExitTests.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/ExitOnProcessExitTests.cs index ad3137f788..b14ea8c35f 100644 --- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/ExitOnProcessExitTests.cs +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/ExitOnProcessExitTests.cs @@ -16,7 +16,7 @@ public void ExitOnProcessExit_Succeed(string tfm) // Create the mutex name used to wait for the PID file created by the test host. string waitPid = Guid.NewGuid().ToString("N"); - _ = testHost.ExecuteAsync(environmentVariables: new Dictionary { { "WaitPid", waitPid } }); + _ = testHost.ExecuteAsync(environmentVariables: new Dictionary { { "WaitPid", waitPid } }, cancellationToken: TestContext.CancellationToken); Process? process; var startTime = Stopwatch.StartNew(); @@ -169,4 +169,6 @@ public async Task ExecuteRequestAsync(ExecuteRequestContext context) .PatchCodeWithReplace("$MicrosoftTestingPlatformVersion$", MicrosoftTestingPlatformVersion)); } } + + public TestContext TestContext { get; set; } } diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/HangDumpOutputTests.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/HangDumpOutputTests.cs index aabb30647e..8992c66746 100644 --- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/HangDumpOutputTests.cs +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/HangDumpOutputTests.cs @@ -29,7 +29,8 @@ public async Task HangDump_Outputs_HangingTests_EvenWhenHangingTestsHaveTheSameD { { "SLEEPTIMEMS1", "100" }, { "SLEEPTIMEMS2", "600000" }, - }); + }, + cancellationToken: TestContext.CancellationToken); testHostResult.AssertExitCodeIs(ExitCodes.TestHostProcessExitedNonGracefully); testHostResult.AssertOutputContains("Test1"); } @@ -150,4 +151,6 @@ public async Task ExecuteRequestAsync(ExecuteRequestContext context) } """; } + + public TestContext TestContext { get; set; } } diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/HangDumpTests.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/HangDumpTests.cs index cfd501c18c..8e113826ef 100644 --- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/HangDumpTests.cs +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/HangDumpTests.cs @@ -24,7 +24,8 @@ public async Task HangDump_DefaultSetting_CreateDump(string tfm) { { "SLEEPTIMEMS1", "4000" }, { "SLEEPTIMEMS2", "600000" }, - }); + }, + cancellationToken: TestContext.CancellationToken); testHostResult.AssertExitCodeIs(ExitCodes.TestHostProcessExitedNonGracefully); string? dumpFile = Directory.GetFiles(resultDirectory, "HangDump*.dmp", SearchOption.AllDirectories).SingleOrDefault(); Assert.IsNotNull(dumpFile, $"Dump file not found '{tfm}'\n{testHostResult}'"); @@ -47,7 +48,7 @@ public async Task HangDump_CustomFileName_CreateDump() { { "SLEEPTIMEMS1", "4000" }, { "SLEEPTIMEMS2", "600000" }, - }); + }, cancellationToken: TestContext.CancellationToken); testHostResult.AssertExitCodeIs(ExitCodes.TestHostProcessExitedNonGracefully); string? dumpFile = Directory.GetFiles(resultDirectory, "myhungdumpfile_*.dmp", SearchOption.AllDirectories).SingleOrDefault(); Assert.IsNotNull(dumpFile, $"Dump file not found '{TargetFrameworks.NetCurrent}'\n{testHostResult}'"); @@ -72,7 +73,8 @@ public async Task HangDump_PathWithSpaces_CreateDump() { { "SLEEPTIMEMS1", "4000" }, { "SLEEPTIMEMS2", "20000" }, - }); + }, + cancellationToken: TestContext.CancellationToken); testHostResult.AssertExitCodeIs(ExitCodes.TestHostProcessExitedNonGracefully); string? dumpFile = Directory.GetFiles(resultDirectory, "myhungdumpfile_*.dmp", SearchOption.AllDirectories).SingleOrDefault(); Assert.IsNotNull(dumpFile, $"Dump file not found '{TargetFrameworks.NetCurrent}'\n{testHostResult}'"); @@ -97,9 +99,10 @@ public async Task HangDump_Formats_CreateDump(string format) $"--hangdump --hangdump-timeout 8s --hangdump-type {format} --results-directory {resultDirectory}", new Dictionary { - { "SLEEPTIMEMS1", "4000" }, - { "SLEEPTIMEMS2", "600000" }, - }); + { "SLEEPTIMEMS1", "4000" }, + { "SLEEPTIMEMS2", "600000" }, + }, + cancellationToken: TestContext.CancellationToken); testHostResult.AssertExitCodeIs(ExitCodes.TestHostProcessExitedNonGracefully); string? dumpFile = Directory.GetFiles(resultDirectory, "HangDump*.dmp", SearchOption.AllDirectories).SingleOrDefault(); Assert.IsNotNull(dumpFile, $"Dump file not found '{format}'\n{testHostResult}'"); @@ -116,7 +119,8 @@ public async Task HangDump_InvalidFormat_ShouldFail() { { "SLEEPTIMEMS1", "4000" }, { "SLEEPTIMEMS2", "600000" }, - }); + }, + cancellationToken: TestContext.CancellationToken); testHostResult.AssertExitCodeIs(ExitCodes.InvalidCommandLine); testHostResult.AssertOutputContains(""" Option '--hangdump-type' has invalid arguments: 'invalid' is not a valid dump type. @@ -227,4 +231,6 @@ public async Task ExecuteRequestAsync(ExecuteRequestContext context) } """; } + + public TestContext TestContext { get; set; } } diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/HelpInfoTests.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/HelpInfoTests.cs index 0cf5d33aa6..e83879a61c 100644 --- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/HelpInfoTests.cs +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/HelpInfoTests.cs @@ -11,7 +11,7 @@ public class HelpInfoTests : AcceptanceTestBase public async Task Help_WhenNoExtensionRegistered_OutputDefaultHelpContent(string tfm) { var testHost = TestInfrastructure.TestHost.LocateFrom(AssetFixture.NoExtensionTargetAssetPath, TestAssetFixture.NoExtensionAssetName, tfm); - TestHostResult testHostResult = await testHost.ExecuteAsync("--help"); + TestHostResult testHostResult = await testHost.ExecuteAsync("--help", cancellationToken: TestContext.CancellationToken); testHostResult.AssertExitCodeIs(ExitCodes.Success); @@ -79,7 +79,7 @@ Output verbosity when reporting tests. public async Task HelpShortName_WhenNoExtensionRegistered_OutputDefaultHelpContent(string tfm) { var testHost = TestInfrastructure.TestHost.LocateFrom(AssetFixture.NoExtensionTargetAssetPath, TestAssetFixture.NoExtensionAssetName, tfm); - TestHostResult testHostResult = await testHost.ExecuteAsync("--?"); + TestHostResult testHostResult = await testHost.ExecuteAsync("--?", cancellationToken: TestContext.CancellationToken); testHostResult.AssertExitCodeIs(ExitCodes.Success); @@ -100,7 +100,7 @@ public async Task Help_WhenNoExtensionRegisteredAndUnknownOptionIsSpecified_Outp const string UnknownOption = "aaa"; var testHost = TestInfrastructure.TestHost.LocateFrom(AssetFixture.NoExtensionTargetAssetPath, TestAssetFixture.NoExtensionAssetName, tfm); - TestHostResult testHostResult = await testHost.ExecuteAsync($"-{UnknownOption}"); + TestHostResult testHostResult = await testHost.ExecuteAsync($"-{UnknownOption}", cancellationToken: TestContext.CancellationToken); testHostResult.AssertExitCodeIs(ExitCodes.InvalidCommandLine); @@ -120,7 +120,7 @@ Execute a .NET Test Application. public async Task Info_WhenNoExtensionRegistered_OutputDefaultInfoContent(string tfm) { var testHost = TestInfrastructure.TestHost.LocateFrom(AssetFixture.NoExtensionTargetAssetPath, TestAssetFixture.NoExtensionAssetName, tfm); - TestHostResult testHostResult = await testHost.ExecuteAsync("--info"); + TestHostResult testHostResult = await testHost.ExecuteAsync("--info", cancellationToken: TestContext.CancellationToken); testHostResult.AssertExitCodeIs(ExitCodes.Success); @@ -274,7 +274,7 @@ There are no registered tools\. public async Task Help_WithAllExtensionsRegistered_OutputFullHelpContent(string tfm) { var testHost = TestInfrastructure.TestHost.LocateFrom(AssetFixture.AllExtensionsTargetAssetPath, TestAssetFixture.AllExtensionsAssetName, tfm); - TestHostResult testHostResult = await testHost.ExecuteAsync("--help"); + TestHostResult testHostResult = await testHost.ExecuteAsync("--help", cancellationToken: TestContext.CancellationToken); testHostResult.AssertExitCodeIs(ExitCodes.Success); @@ -375,7 +375,7 @@ The name of the generated TRX report public async Task HelpShortName_WithAllExtensionsRegistered_OutputFullHelpContent(string tfm) { var testHost = TestInfrastructure.TestHost.LocateFrom(AssetFixture.AllExtensionsTargetAssetPath, TestAssetFixture.AllExtensionsAssetName, tfm); - TestHostResult testHostResult = await testHost.ExecuteAsync("-?"); + TestHostResult testHostResult = await testHost.ExecuteAsync("-?", cancellationToken: TestContext.CancellationToken); testHostResult.AssertExitCodeIs(ExitCodes.Success); @@ -394,7 +394,7 @@ Execute a .NET Test Application. public async Task Info_WithAllExtensionsRegistered_OutputFullInfoContent(string tfm) { var testHost = TestInfrastructure.TestHost.LocateFrom(AssetFixture.AllExtensionsTargetAssetPath, TestAssetFixture.AllExtensionsAssetName, tfm); - TestHostResult testHostResult = await testHost.ExecuteAsync("--info"); + TestHostResult testHostResult = await testHost.ExecuteAsync("--info", cancellationToken: TestContext.CancellationToken); testHostResult.AssertExitCodeIs(ExitCodes.Success); @@ -665,7 +665,7 @@ public async Task Help_DoesNotCreateTestResultsFolder(string tfm) Directory.Delete(testResultsPath, recursive: true); } - TestHostResult testHostResult = await testHost.ExecuteAsync("--help"); + TestHostResult testHostResult = await testHost.ExecuteAsync("--help", cancellationToken: TestContext.CancellationToken); testHostResult.AssertExitCodeIs(ExitCodes.Success); @@ -687,7 +687,7 @@ public async Task HelpShortName_DoesNotCreateTestResultsFolder(string tfm) Directory.Delete(testResultsPath, recursive: true); } - TestHostResult testHostResult = await testHost.ExecuteAsync("--?"); + TestHostResult testHostResult = await testHost.ExecuteAsync("--?", cancellationToken: TestContext.CancellationToken); testHostResult.AssertExitCodeIs(ExitCodes.Success); @@ -709,7 +709,7 @@ public async Task Info_DoesNotCreateTestResultsFolder(string tfm) Directory.Delete(testResultsPath, recursive: true); } - TestHostResult testHostResult = await testHost.ExecuteAsync("--info"); + TestHostResult testHostResult = await testHost.ExecuteAsync("--info", cancellationToken: TestContext.CancellationToken); testHostResult.AssertExitCodeIs(ExitCodes.Success); @@ -863,4 +863,6 @@ public Task ExecuteRequestAsync(ExecuteRequestContext context) .PatchCodeWithReplace("$MicrosoftTestingPlatformVersion$", MicrosoftTestingPlatformVersion)); } } + + public TestContext TestContext { get; set; } } diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/Helpers/AcceptanceTestBase.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/Helpers/AcceptanceTestBase.cs index ee62060cb3..17e7811f01 100644 --- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/Helpers/AcceptanceTestBase.cs +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/Helpers/AcceptanceTestBase.cs @@ -82,7 +82,7 @@ static AcceptanceTestBase() public static async Task ClassInitialize(TestContext testContext) { AssetFixture = new(); - await AssetFixture.InitializeAsync(); + await AssetFixture.InitializeAsync(testContext.CancellationToken); } [ClassCleanup(InheritanceBehavior.BeforeEachDerivedClass)] @@ -145,17 +145,17 @@ public static void ClassCleanup() } // https://github.com/NuGet/NuGet.Client/blob/c5934bdcbc578eec1e2921f49e6a5d53481c5099/test/NuGet.Core.FuncTests/Msbuild.Integration.Test/MsbuildIntegrationTestFixture.cs#L65-L94 - private protected static async Task FindMsbuildWithVsWhereAsync() + private protected static async Task FindMsbuildWithVsWhereAsync(CancellationToken cancellationToken) { string vswherePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86), "Microsoft Visual Studio", "Installer", "vswhere.exe"); var commandLine = new TestInfrastructure.CommandLine(); - await commandLine.RunAsync($"\"{vswherePath}\" -latest -prerelease -requires Microsoft.Component.MSBuild -find MSBuild\\**\\Bin\\MSBuild.exe"); + await commandLine.RunAsync($"\"{vswherePath}\" -latest -prerelease -requires Microsoft.Component.MSBuild -find MSBuild\\**\\Bin\\MSBuild.exe", cancellationToken: cancellationToken); string? path = null; using (var stringReader = new StringReader(commandLine.StandardOutput)) { string? line; - while ((line = await stringReader.ReadLineAsync()) != null) + while ((line = await stringReader.ReadLineAsync(cancellationToken)) != null) { if (path != null) { diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/IgnoreExitCodeTests.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/IgnoreExitCodeTests.cs index 56551db7b1..17ca19b00d 100644 --- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/IgnoreExitCodeTests.cs +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/IgnoreExitCodeTests.cs @@ -100,16 +100,19 @@ public async Task If_IgnoreExitCode_Specified_Should_Return_Success_ExitCode(str string assetPath = generator.TargetAssetPath; string globalPackagesPath = AcceptanceFixture.NuGetGlobalPackagesFolder.Path; - await DotnetCli.RunAsync($"restore -m:1 -nodeReuse:false {assetPath} -r {RID}", globalPackagesPath); - await DotnetCli.RunAsync($"build -m:1 -nodeReuse:false {assetPath} -c {buildConfiguration} -r {RID}", globalPackagesPath); + await DotnetCli.RunAsync($"restore -m:1 -nodeReuse:false {assetPath} -r {RID}", globalPackagesPath, cancellationToken: TestContext.CancellationToken); + await DotnetCli.RunAsync($"build -m:1 -nodeReuse:false {assetPath} -c {buildConfiguration} -r {RID}", globalPackagesPath, cancellationToken: TestContext.CancellationToken); var host = TestInfrastructure.TestHost.LocateFrom(assetPath, AssetName, tfm, buildConfiguration: buildConfiguration); TestHostResult hostResult = await host.ExecuteAsync( command: commandLine, environmentVariables: new Dictionary { { EnvironmentVariableConstants.TESTINGPLATFORM_EXITCODE_IGNORE, environmentVariable }, - }); + }, + cancellationToken: TestContext.CancellationToken); hostResult.AssertOutputContainsSummary(failed: 1, passed: 0, skipped: 0); Assert.AreEqual(0, hostResult.ExitCode); } + + public TestContext TestContext { get; set; } } diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/MSBuild.KnownExtensionRegistration.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/MSBuild.KnownExtensionRegistration.cs index 717e6bbe24..597776a966 100644 --- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/MSBuild.KnownExtensionRegistration.cs +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/MSBuild.KnownExtensionRegistration.cs @@ -19,12 +19,12 @@ public async Task Microsoft_Testing_Platform_Extensions_ShouldBe_Correctly_Regis SourceCode .PatchCodeWithReplace("$TargetFrameworks$", tfm) .PatchCodeWithReplace("$MicrosoftTestingPlatformVersion$", MicrosoftTestingPlatformVersion)); - await DotnetCli.RunAsync($"restore -r {RID} {testAsset.TargetAssetPath}{Path.DirectorySeparatorChar}MSBuildTests.csproj", AcceptanceFixture.NuGetGlobalPackagesFolder.Path); - DotnetMuxerResult result = await DotnetCli.RunAsync($"{(verb == Verb.publish ? $"publish -f {tfm}" : "build")} -c {compilationMode} -r {RID} -nodeReuse:false {testAsset.TargetAssetPath} -v:n", AcceptanceFixture.NuGetGlobalPackagesFolder.Path); + await DotnetCli.RunAsync($"restore -r {RID} {testAsset.TargetAssetPath}{Path.DirectorySeparatorChar}MSBuildTests.csproj", AcceptanceFixture.NuGetGlobalPackagesFolder.Path, cancellationToken: TestContext.CancellationToken); + DotnetMuxerResult result = await DotnetCli.RunAsync($"{(verb == Verb.publish ? $"publish -f {tfm}" : "build")} -c {compilationMode} -r {RID} -nodeReuse:false {testAsset.TargetAssetPath} -v:n", AcceptanceFixture.NuGetGlobalPackagesFolder.Path, cancellationToken: TestContext.CancellationToken); string binlogFile = result.BinlogPath!; var testHost = TestInfrastructure.TestHost.LocateFrom(testAsset.TargetAssetPath, AssetName, tfm, rid: RID, verb: verb, buildConfiguration: compilationMode); - TestHostResult testHostResult = await testHost.ExecuteAsync("--help"); + TestHostResult testHostResult = await testHost.ExecuteAsync("--help", cancellationToken: TestContext.CancellationToken); testHostResult.AssertOutputContains("--crashdump"); testHostResult.AssertOutputContains("--report-trx"); testHostResult.AssertOutputContains("--retry-failed-tests"); @@ -136,4 +136,6 @@ namespace MSBuildTests.Microsoft; // Then, without global::, Microsoft will be referring to MSBuildTests.Microsoft namespace and will fail to compile public static class DummyClass { } """; + + public TestContext TestContext { get; set; } } diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/MSBuildTests.ConfigurationFile.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/MSBuildTests.ConfigurationFile.cs index 31da865173..1e84560bcb 100644 --- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/MSBuildTests.ConfigurationFile.cs +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/MSBuildTests.ConfigurationFile.cs @@ -17,7 +17,7 @@ public async Task ConfigFileGeneration_CorrectlyCreateAndCacheAndCleaned(string .PatchCodeWithReplace("$JsonContent$", ConfigurationContent) .PatchCodeWithReplace("$MicrosoftTestingPlatformVersion$", MicrosoftTestingPlatformVersion)); - DotnetMuxerResult compilationResult = await DotnetCli.RunAsync($"{(verb == Verb.publish ? $"publish -f {tfm}" : "build")} -v:normal -nodeReuse:false {testAsset.TargetAssetPath} -c {compilationMode}", AcceptanceFixture.NuGetGlobalPackagesFolder.Path); + DotnetMuxerResult compilationResult = await DotnetCli.RunAsync($"{(verb == Verb.publish ? $"publish -f {tfm}" : "build")} -v:normal -nodeReuse:false {testAsset.TargetAssetPath} -c {compilationMode}", AcceptanceFixture.NuGetGlobalPackagesFolder.Path, cancellationToken: TestContext.CancellationToken); var testHost = TestInfrastructure.TestHost.LocateFrom(testAsset.TargetAssetPath, "MSBuildTests", tfm, verb: verb, buildConfiguration: compilationMode); string generatedConfigurationFile = Path.Combine(testHost.DirectoryName, "MSBuildTests.testconfig.json"); @@ -25,7 +25,7 @@ public async Task ConfigFileGeneration_CorrectlyCreateAndCacheAndCleaned(string Assert.AreEqual(ConfigurationContent.Trim(), File.ReadAllText(generatedConfigurationFile).Trim()); Assert.Contains("Microsoft Testing Platform configuration file written", compilationResult.StandardOutput); - compilationResult = await DotnetCli.RunAsync($"{(verb == Verb.publish ? $"publish -f {tfm}" : "build")} -v:normal -nodeReuse:false {testAsset.TargetAssetPath} -c {compilationMode}", AcceptanceFixture.NuGetGlobalPackagesFolder.Path); + compilationResult = await DotnetCli.RunAsync($"{(verb == Verb.publish ? $"publish -f {tfm}" : "build")} -v:normal -nodeReuse:false {testAsset.TargetAssetPath} -c {compilationMode}", AcceptanceFixture.NuGetGlobalPackagesFolder.Path, cancellationToken: TestContext.CancellationToken); Assert.IsTrue(File.Exists(generatedConfigurationFile)); Assert.AreEqual(ConfigurationContent.Trim(), File.ReadAllText(generatedConfigurationFile).Trim()); // Assert is failing, probably the MSBuild regression which is being fixed in https://github.com/dotnet/msbuild/pull/12431 ? @@ -36,7 +36,7 @@ public async Task ConfigFileGeneration_CorrectlyCreateAndCacheAndCleaned(string \s*_GenerateTestingPlatformConfigurationFileCore: \s*Skipping target "_GenerateTestingPlatformConfigurationFileCore" because all output files are up\-to\-date with respect to the input files\. """)); - await DotnetCli.RunAsync($"clean -c {compilationMode} -v:normal {testAsset.TargetAssetPath}", AcceptanceFixture.NuGetGlobalPackagesFolder.Path); + await DotnetCli.RunAsync($"clean -c {compilationMode} -v:normal {testAsset.TargetAssetPath}", AcceptanceFixture.NuGetGlobalPackagesFolder.Path, cancellationToken: TestContext.CancellationToken); // dotnet clean doesn't clean the publish output folder if (verb == Verb.build) @@ -58,7 +58,7 @@ public async Task ConfigFileGeneration_NoConfigurationFile_TaskWontRun(string tf File.Delete(Path.Combine(testAsset.TargetAssetPath, "testconfig.json")); - DotnetMuxerResult compilationResult = await DotnetCli.RunAsync($"{(verb == Verb.publish ? $"publish -f {tfm}" : "build")} -v:diagnostic -nodeReuse:false {testAsset.TargetAssetPath} -c {compilationMode}", AcceptanceFixture.NuGetGlobalPackagesFolder.Path); + DotnetMuxerResult compilationResult = await DotnetCli.RunAsync($"{(verb == Verb.publish ? $"publish -f {tfm}" : "build")} -v:diagnostic -nodeReuse:false {testAsset.TargetAssetPath} -c {compilationMode}", AcceptanceFixture.NuGetGlobalPackagesFolder.Path, cancellationToken: TestContext.CancellationToken); var testHost = TestInfrastructure.TestHost.LocateFrom(testAsset.TargetAssetPath, "MSBuildTests", tfm, verb: verb, buildConfiguration: compilationMode); @@ -142,4 +142,6 @@ public Task ExecuteRequestAsync(ExecuteRequestContext context) } } """; + + public TestContext TestContext { get; set; } } diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/MSBuildTests.GenerateEntryPoint.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/MSBuildTests.GenerateEntryPoint.cs index 6818dca991..3f86e9ea09 100644 --- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/MSBuildTests.GenerateEntryPoint.cs +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/MSBuildTests.GenerateEntryPoint.cs @@ -19,8 +19,12 @@ public async Task When_GenerateTestingPlatformEntryPoint_IsFalse_NoEntryPointInj CSharpSourceCode .PatchCodeWithReplace("$TargetFrameworks$", tfm) .PatchCodeWithReplace("$MicrosoftTestingPlatformVersion$", MicrosoftTestingPlatformVersion)); - DotnetMuxerResult compilationResult = await DotnetCli.RunAsync($"restore -r {RID} {testAsset.TargetAssetPath}{Path.DirectorySeparatorChar}MSBuildTests.csproj ", AcceptanceFixture.NuGetGlobalPackagesFolder.Path); - compilationResult = await DotnetCli.RunAsync($"{(verb == Verb.publish ? $"publish -f {tfm}" : "build")} -c {compilationMode} -r {RID} -nodeReuse:false -p:GenerateTestingPlatformEntryPoint=False {testAsset.TargetAssetPath} -v:n", AcceptanceFixture.NuGetGlobalPackagesFolder.Path, failIfReturnValueIsNotZero: false); + DotnetMuxerResult compilationResult = await DotnetCli.RunAsync($"restore -r {RID} {testAsset.TargetAssetPath}{Path.DirectorySeparatorChar}MSBuildTests.csproj ", AcceptanceFixture.NuGetGlobalPackagesFolder.Path, cancellationToken: TestContext.CancellationToken); + compilationResult = await DotnetCli.RunAsync( + $"{(verb == Verb.publish ? $"publish -f {tfm}" : "build")} -c {compilationMode} -r {RID} -nodeReuse:false -p:GenerateTestingPlatformEntryPoint=False {testAsset.TargetAssetPath} -v:n", + AcceptanceFixture.NuGetGlobalPackagesFolder.Path, + failIfReturnValueIsNotZero: false, + cancellationToken: TestContext.CancellationToken); SL.Build binLog = SL.Serialization.Read(compilationResult.BinlogPath!); IEnumerable generateTestingPlatformEntryPointTargets = binLog.FindChildrenRecursive().Where(t => t.Name == "_GenerateTestingPlatformEntryPoint"); @@ -129,8 +133,8 @@ private async Task GenerateAndVerifyLanguageSpecificEntryPointAsync(string asset .PatchCodeWithReplace("$TargetFrameworks$", tfm) .PatchCodeWithReplace("$MicrosoftTestingPlatformVersion$", MicrosoftTestingPlatformVersion); using TestAsset testAsset = await TestAsset.GenerateAssetAsync(assetName, finalSourceCode); - await DotnetCli.RunAsync($"restore -r {RID} {testAsset.TargetAssetPath}{Path.DirectorySeparatorChar}MSBuildTests.{languageFileExtension}proj", AcceptanceFixture.NuGetGlobalPackagesFolder.Path); - DotnetMuxerResult buildResult = await DotnetCli.RunAsync($"{(verb == Verb.publish ? $"publish -f {tfm}" : "build")} -c {compilationMode} -r {RID} -nodeReuse:false {testAsset.TargetAssetPath} -v:n", AcceptanceFixture.NuGetGlobalPackagesFolder.Path); + await DotnetCli.RunAsync($"restore -r {RID} {testAsset.TargetAssetPath}{Path.DirectorySeparatorChar}MSBuildTests.{languageFileExtension}proj", AcceptanceFixture.NuGetGlobalPackagesFolder.Path, cancellationToken: TestContext.CancellationToken); + DotnetMuxerResult buildResult = await DotnetCli.RunAsync($"{(verb == Verb.publish ? $"publish -f {tfm}" : "build")} -c {compilationMode} -r {RID} -nodeReuse:false {testAsset.TargetAssetPath} -v:n", AcceptanceFixture.NuGetGlobalPackagesFolder.Path, cancellationToken: TestContext.CancellationToken); SL.Build binLog = SL.Serialization.Read(buildResult.BinlogPath!); SL.Target generateTestingPlatformEntryPoint = binLog.FindChildrenRecursive().Single(t => t.Name == "_GenerateTestingPlatformEntryPoint"); SL.Task testingPlatformEntryPoint = generateTestingPlatformEntryPoint.FindChildrenRecursive().Single(t => t.Name == "TestingPlatformEntryPointTask"); @@ -138,7 +142,7 @@ private async Task GenerateAndVerifyLanguageSpecificEntryPointAsync(string asset Assert.AreEqual(expectedEntryPoint.ReplaceLineEndings(), generatedSource.Text.ReplaceLineEndings()); var testHost = TestInfrastructure.TestHost.LocateFrom(testAsset.TargetAssetPath, AssetName, tfm, rid: RID, verb: verb, buildConfiguration: compilationMode); - TestHostResult testHostResult = await testHost.ExecuteAsync(); + TestHostResult testHostResult = await testHost.ExecuteAsync(cancellationToken: TestContext.CancellationToken); testHostResult.AssertExitCodeIs(ExitCodes.Success); Assert.Contains("Passed!", testHostResult.StandardOutput); @@ -149,13 +153,13 @@ private async Task GenerateAndVerifyLanguageSpecificEntryPointAsync(string asset Assert.IsNotNull(sourceFilePathInObj); File.Delete(buildResult.BinlogPath!); - buildResult = await DotnetCli.RunAsync($"{(verb == Verb.publish ? $"publish -f {tfm}" : "build")} -c {compilationMode} -r {RID} -nodeReuse:false {testAsset.TargetAssetPath} -v:n", AcceptanceFixture.NuGetGlobalPackagesFolder.Path); + buildResult = await DotnetCli.RunAsync($"{(verb == Verb.publish ? $"publish -f {tfm}" : "build")} -c {compilationMode} -r {RID} -nodeReuse:false {testAsset.TargetAssetPath} -v:n", AcceptanceFixture.NuGetGlobalPackagesFolder.Path, cancellationToken: TestContext.CancellationToken); binLog = SL.Serialization.Read(buildResult.BinlogPath!); generateTestingPlatformEntryPoint = binLog.FindChildrenRecursive(t => t.Name == "_GenerateTestingPlatformEntryPoint" && t.Children.Count > 0).Single(); Assert.IsNotNull(generateTestingPlatformEntryPoint.FindChildrenRecursive(m => m.Text.Contains("Skipping target \"_GenerateTestingPlatformEntryPoint\" because all output files are up-to-date with respect to the input files.", StringComparison.OrdinalIgnoreCase)).Single()); testHost = TestInfrastructure.TestHost.LocateFrom(testAsset.TargetAssetPath, AssetName, tfm, rid: RID, verb: verb, buildConfiguration: compilationMode); - testHostResult = await testHost.ExecuteAsync(); + testHostResult = await testHost.ExecuteAsync(cancellationToken: TestContext.CancellationToken); Assert.AreEqual(ExitCodes.Success, testHostResult.ExitCode); Assert.Contains("Passed!", testHostResult.StandardOutput); } @@ -463,4 +467,6 @@ let AddExtensions (testApplicationBuilder : ITestApplicationBuilder, args: strin let AddExtensions (_, _) = () """; + + public TestContext TestContext { get; set; } } diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/MSBuildTests.Solution.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/MSBuildTests.Solution.cs index 834abfb43e..769e8f5378 100644 --- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/MSBuildTests.Solution.cs +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/MSBuildTests.Solution.cs @@ -57,9 +57,9 @@ public async Task MSBuildTests_UseMSBuildTestInfrastructure_Should_Run_Solution_ } // Build the solution - DotnetMuxerResult restoreResult = await DotnetCli.RunAsync($"restore -nodeReuse:false {solution.SolutionFile} --configfile {nugetFile}", AcceptanceFixture.NuGetGlobalPackagesFolder.Path); + DotnetMuxerResult restoreResult = await DotnetCli.RunAsync($"restore -nodeReuse:false {solution.SolutionFile} --configfile {nugetFile}", AcceptanceFixture.NuGetGlobalPackagesFolder.Path, cancellationToken: TestContext.CancellationToken); restoreResult.AssertOutputDoesNotContain("An approximate best match of"); - DotnetMuxerResult testResult = await DotnetCli.RunAsync($"{command} -nodeReuse:false {solution.SolutionFile}", AcceptanceFixture.NuGetGlobalPackagesFolder.Path, workingDirectory: solution.FolderPath); + DotnetMuxerResult testResult = await DotnetCli.RunAsync($"{command} -nodeReuse:false {solution.SolutionFile}", AcceptanceFixture.NuGetGlobalPackagesFolder.Path, workingDirectory: solution.FolderPath, cancellationToken: TestContext.CancellationToken); if (isMultiTfm) { @@ -151,4 +151,6 @@ public async Task ExecuteRequestAsync(ExecuteRequestContext context) } } """; + + public TestContext TestContext { get; set; } } diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/MSBuildTests.Test.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/MSBuildTests.Test.cs index 8b857d9aba..a23c552afd 100644 --- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/MSBuildTests.Test.cs +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/MSBuildTests.Test.cs @@ -54,7 +54,7 @@ private async Task InvokeTestingPlatform_Target_Should_Execute_Tests_Without_Sho .PatchCodeWithReplace("$AssertValue$", testSucceeded.ToString().ToLowerInvariant()) .PatchCodeWithReplace("$MicrosoftTestingPlatformVersion$", MicrosoftTestingPlatformVersion)); string testResultFolder = Path.Combine(testAsset.TargetAssetPath, Guid.NewGuid().ToString("N")); - DotnetMuxerResult compilationResult = await DotnetCli.RunAsync($"{testCommand} -p:TestingPlatformCommandLineArguments=\"--results-directory %22{testResultFolder}%22\" -p:Configuration={compilationMode} -p:nodeReuse=false \"{testAsset.TargetAssetPath}\"", AcceptanceFixture.NuGetGlobalPackagesFolder.Path, workingDirectory: testAsset.TargetAssetPath, failIfReturnValueIsNotZero: false); + DotnetMuxerResult compilationResult = await DotnetCli.RunAsync($"{testCommand} -p:TestingPlatformCommandLineArguments=\"--results-directory %22{testResultFolder}%22\" -p:Configuration={compilationMode} -p:nodeReuse=false \"{testAsset.TargetAssetPath}\"", AcceptanceFixture.NuGetGlobalPackagesFolder.Path, workingDirectory: testAsset.TargetAssetPath, failIfReturnValueIsNotZero: false, cancellationToken: TestContext.CancellationToken); foreach (string tfmToAssert in tfmsToAssert) { @@ -87,11 +87,11 @@ private async Task InvokeTestingPlatform_Target_Should_Build_Without_Warnings_An ? await DotnetCli.RunAsync( $"{testCommand} -p:Configuration={compilationMode} -p:nodeReuse=false \"{testAsset.TargetAssetPath}\" -- --treenode-filter --results-directory \"{testResultFolder}\"", AcceptanceFixture.NuGetGlobalPackagesFolder.Path, - workingDirectory: testAsset.TargetAssetPath) + workingDirectory: testAsset.TargetAssetPath, cancellationToken: TestContext.CancellationToken) : await DotnetCli.RunAsync( $"{testCommand} -p:TestingPlatformCommandLineArguments=\"--treenode-filter --results-directory \"{testResultFolder}\"\" -p:Configuration={compilationMode} -p:nodeReuse=false \"{testAsset.TargetAssetPath}\"", AcceptanceFixture.NuGetGlobalPackagesFolder.Path, - workingDirectory: testAsset.TargetAssetPath); + workingDirectory: testAsset.TargetAssetPath, cancellationToken: TestContext.CancellationToken); foreach (string tfmToAssert in tfmsToAssert) { @@ -111,14 +111,17 @@ public async Task RunUsingTestTargetWithNetfxMSBuild() .PatchCodeWithReplace("$AssertValue$", bool.TrueString.ToLowerInvariant()) .PatchCodeWithReplace("$MicrosoftTestingPlatformVersion$", MicrosoftTestingPlatformVersion)); - string msbuildExe = await FindMsbuildWithVsWhereAsync(); + string msbuildExe = await FindMsbuildWithVsWhereAsync(TestContext.CancellationToken); var commandLine = new TestInfrastructure.CommandLine(); string binlogFile = Path.Combine(TempDirectory.TestSuiteDirectory, $"{nameof(RunUsingTestTargetWithNetfxMSBuild)}.binlog"); - await commandLine.RunAsync($"\"{msbuildExe}\" {testAsset.TargetAssetPath} /t:Restore"); - await commandLine.RunAsync($"\"{msbuildExe}\" {testAsset.TargetAssetPath} /t:\"Build;Test\" /bl:\"{binlogFile}\"", environmentVariables: new Dictionary - { - ["DOTNET_ROOT"] = Path.Combine(RootFinder.Find(), ".dotnet"), - }); + await commandLine.RunAsync($"\"{msbuildExe}\" {testAsset.TargetAssetPath} /t:Restore", cancellationToken: TestContext.CancellationToken); + await commandLine.RunAsync( + $"\"{msbuildExe}\" {testAsset.TargetAssetPath} /t:\"Build;Test\" /bl:\"{binlogFile}\"", + environmentVariables: new Dictionary + { + ["DOTNET_ROOT"] = Path.Combine(RootFinder.Find(), ".dotnet"), + }, + cancellationToken: TestContext.CancellationToken); Assert.Contains("Tests succeeded", commandLine.StandardOutput); } @@ -149,7 +152,8 @@ await DotnetCli.RunAsync( AcceptanceFixture.NuGetGlobalPackagesFolder.Path, workingDirectory: testAsset.TargetAssetPath, environmentVariables: dotnetRootX86, - failIfReturnValueIsNotZero: false); + failIfReturnValueIsNotZero: false, + cancellationToken: TestContext.CancellationToken); string outputFileLog = Directory.GetFiles(testAsset.TargetAssetPath, "MSBuild Tests_net9.0_x86.log", SearchOption.AllDirectories).Single(); Assert.IsTrue(File.Exists(outputFileLog), $"Expected file '{outputFileLog}'"); @@ -182,7 +186,8 @@ public async Task Invoke_DotnetTest_With_Incompatible_Arch() $"test --arch {incompatibleArchitecture} -p:TestingPlatformDotnetTestSupport=True \"{testAsset.TargetAssetPath}\"", AcceptanceFixture.NuGetGlobalPackagesFolder.Path, workingDirectory: testAsset.TargetAssetPath, - failIfReturnValueIsNotZero: false); + failIfReturnValueIsNotZero: false, + cancellationToken: TestContext.CancellationToken); // On Windows, we run the exe directly. // On other OSes, we run with dotnet exec. @@ -238,7 +243,8 @@ await DotnetCli.RunAsync( AcceptanceFixture.NuGetGlobalPackagesFolder.Path, workingDirectory: testAsset.TargetAssetPath, environmentVariables: dotnetHostPathEnvVar, - failIfReturnValueIsNotZero: false); + failIfReturnValueIsNotZero: false, + cancellationToken: TestContext.CancellationToken); string outputFileLog = Directory.GetFiles(testAsset.TargetAssetPath, "MSBuild Tests_net9.0_x64.log", SearchOption.AllDirectories).Single(); Assert.IsTrue(File.Exists(outputFileLog), $"Expected file '{outputFileLog}'"); @@ -284,7 +290,7 @@ public async Task InvokeTestingPlatform_Target_Showing_Error_And_Do_Not_Capture_ .PatchCodeWithReplace("$TargetFrameworks$", $"{tfm}") .PatchCodeWithReplace("$AssertValue$", testSucceeded.ToString().ToLowerInvariant()) .PatchCodeWithReplace("$MicrosoftTestingPlatformVersion$", MicrosoftTestingPlatformVersion)); - DotnetMuxerResult compilationResult = await DotnetCli.RunAsync($"{testCommand} -p:TestingPlatformShowTestsFailure=True -p:TestingPlatformCaptureOutput=False -p:Configuration={compilationMode} -p:nodeReuse=false {testAsset.TargetAssetPath}", AcceptanceFixture.NuGetGlobalPackagesFolder.Path, workingDirectory: testAsset.TargetAssetPath, failIfReturnValueIsNotZero: false); + DotnetMuxerResult compilationResult = await DotnetCli.RunAsync($"{testCommand} -p:TestingPlatformShowTestsFailure=True -p:TestingPlatformCaptureOutput=False -p:Configuration={compilationMode} -p:nodeReuse=false {testAsset.TargetAssetPath}", AcceptanceFixture.NuGetGlobalPackagesFolder.Path, workingDirectory: testAsset.TargetAssetPath, failIfReturnValueIsNotZero: false, cancellationToken: TestContext.CancellationToken); compilationResult.AssertOutputContains("error test failed: Test2 ("); compilationResult.AssertOutputContains("FAILED: Expected 'true', but got 'false'."); @@ -301,7 +307,7 @@ public async Task TestingPlatformDisableCustomTestTarget_Should_Cause_UserDefine .PatchCodeWithReplace("$TargetFrameworks$", $"{TargetFrameworks.NetCurrent}") .PatchCodeWithReplace("$AssertValue$", "true") .PatchCodeWithReplace("$MicrosoftTestingPlatformVersion$", MicrosoftTestingPlatformVersion)); - DotnetMuxerResult compilationResult = await DotnetCli.RunAsync($"build {testAsset.TargetAssetPath} -p:TestingPlatformDisableCustomTestTarget=true -p:ImportUserDefinedTestTarget=true -t:\"Build;Test\"", AcceptanceFixture.NuGetGlobalPackagesFolder.Path, failIfReturnValueIsNotZero: false); + DotnetMuxerResult compilationResult = await DotnetCli.RunAsync($"build {testAsset.TargetAssetPath} -p:TestingPlatformDisableCustomTestTarget=true -p:ImportUserDefinedTestTarget=true -t:\"Build;Test\"", AcceptanceFixture.NuGetGlobalPackagesFolder.Path, failIfReturnValueIsNotZero: false, cancellationToken: TestContext.CancellationToken); compilationResult.AssertOutputContains("Error from UserDefinedTestTarget.targets"); } @@ -424,4 +430,6 @@ public async Task ExecuteRequestAsync(ExecuteRequestContext context) } } """; + + public TestContext TestContext { get; set; } } diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/MaxFailedTestsExtensionTests.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/MaxFailedTestsExtensionTests.cs index 44ebf81d34..528de217d2 100644 --- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/MaxFailedTestsExtensionTests.cs +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/MaxFailedTestsExtensionTests.cs @@ -12,7 +12,7 @@ public class MaxFailedTestsExtensionTests : AcceptanceTestBase public async Task UsingNoBanner_TheBannerDoesNotAppear(string tfm) { var testHost = TestInfrastructure.TestHost.LocateFrom(AssetFixture.TargetAssetPath, AssetName, tfm); - TestHostResult testHostResult = await testHost.ExecuteAsync("--no-banner"); + TestHostResult testHostResult = await testHost.ExecuteAsync("--no-banner", cancellationToken: TestContext.CancellationToken); testHostResult.AssertExitCodeIs(ExitCodes.ZeroTests); testHostResult.AssertOutputDoesNotMatchRegex(_bannerRegexMatchPattern); @@ -30,7 +30,8 @@ public async Task UsingNoBanner_InTheEnvironmentVars_TheBannerDoesNotAppear(stri new Dictionary { { "TESTINGPLATFORM_NOBANNER", "true" }, - }); + }, + cancellationToken: TestContext.CancellationToken); testHostResult.AssertExitCodeIs(ExitCodes.ZeroTests); testHostResult.AssertOutputDoesNotMatchRegex(_bannerRegexMatchPattern); @@ -46,7 +47,8 @@ public async Task UsingDotnetNoLogo_InTheEnvironmentVars_TheBannerDoesNotAppear( new Dictionary { { "DOTNET_NOLOGO", "true" }, - }); + }, + cancellationToken: TestContext.CancellationToken); testHostResult.AssertExitCodeIs(ExitCodes.ZeroTests); testHostResult.AssertOutputDoesNotMatchRegex(_bannerRegexMatchPattern); @@ -57,7 +59,7 @@ public async Task UsingDotnetNoLogo_InTheEnvironmentVars_TheBannerDoesNotAppear( public async Task WithoutUsingNoBanner_TheBannerAppears(string tfm) { var testHost = TestInfrastructure.TestHost.LocateFrom(AssetFixture.TargetAssetPath, AssetName, tfm); - TestHostResult testHostResult = await testHost.ExecuteAsync(); + TestHostResult testHostResult = await testHost.ExecuteAsync(cancellationToken: TestContext.CancellationToken); testHostResult.AssertExitCodeIs(ExitCodes.ZeroTests); testHostResult.AssertOutputMatchesRegex(_bannerRegexMatchPattern); @@ -132,4 +134,6 @@ public Task ExecuteRequestAsync(ExecuteRequestContext context) .PatchCodeWithReplace("$MicrosoftTestingPlatformVersion$", MicrosoftTestingPlatformVersion)); } } + + public TestContext TestContext { get; set; } } diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/RetryFailedTestsTests.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/RetryFailedTestsTests.cs index 86a1f1476c..c6f05b18d4 100644 --- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/RetryFailedTestsTests.cs +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/RetryFailedTestsTests.cs @@ -35,7 +35,8 @@ public async Task RetryFailedTests_OnlyRetryTimes_Succeeds(string tfm, bool fail { "METHOD1", "1" }, { "FAIL", failOnly ? "1" : "0" }, { "RESULTDIR", resultDirectory }, - }); + }, + cancellationToken: TestContext.CancellationToken); if (!failOnly) { @@ -80,7 +81,8 @@ public async Task RetryFailedTests_MaxPercentage_Succeeds(string tfm, bool fail) { "RESULTDIR", resultDirectory }, { "METHOD1", "1" }, { fail ? "METHOD2" : "UNUSED", "1" }, - }); + }, + cancellationToken: TestContext.CancellationToken); string retriesPath = Path.Combine(resultDirectory, "Retries"); Assert.IsTrue(Directory.Exists(retriesPath)); @@ -122,7 +124,7 @@ public async Task RetryFailedTests_MaxTestsCount_Succeeds(string tfm, bool fail) { "RESULTDIR", resultDirectory }, { "METHOD1", "1" }, { fail ? "METHOD2" : "UNUSED", "1" }, - }); + }, cancellationToken: TestContext.CancellationToken); if (fail) { @@ -163,7 +165,8 @@ await RetryHelper.RetryAsync( { EnvironmentVariableConstants.TESTINGPLATFORM_TELEMETRY_OPTOUT, "1" }, { "RESULTDIR", resultDirectory }, { "CRASH", "1" }, - }); + }, + cancellationToken: TestContext.CancellationToken); testHostResult.AssertExitCodeIs(ExitCodes.TestHostProcessExitedNonGracefully); @@ -195,7 +198,7 @@ public async Task RetryFailedTests_PassingFromFirstTime_UsingOldDotnetTest_MoveF DotnetMuxerResult result = await DotnetCli.RunAsync( $"test \"{AssetFixture.TargetAssetPath}\" -- --retry-failed-tests 1 --results-directory \"{resultDirectory}\"", AcceptanceFixture.NuGetGlobalPackagesFolder.Path, - workingDirectory: AssetFixture.TargetAssetPath); + workingDirectory: AssetFixture.TargetAssetPath, cancellationToken: TestContext.CancellationToken); result.AssertExitCodeIs(ExitCodes.Success); @@ -413,4 +416,6 @@ private bool TestMethod3(bool fail, string resultDir) } """; } + + public TestContext TestContext { get; set; } } diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/ServerMode/v1.0.0/TestingPlatformClient.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/ServerMode/v1.0.0/TestingPlatformClient.cs index 43c86c3cb3..16504cd25d 100644 --- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/ServerMode/v1.0.0/TestingPlatformClient.cs +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/ServerMode/v1.0.0/TestingPlatformClient.cs @@ -50,9 +50,9 @@ private void JsonRpcClient_Disconnected(object? sender, JsonRpcDisconnectedEvent public int ExitCode => _processHandler.ExitCode; - public async Task WaitServerProcessExit() + public async Task WaitServerProcessExit(CancellationToken cancellationToken) { - await _processHandler.WaitForExitAsync(); + await _processHandler.WaitForExitAsync(cancellationToken); return _processHandler.ExitCode; } diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/TelemetryTests.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/TelemetryTests.cs index 53abc787a6..c3916ceab6 100644 --- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/TelemetryTests.cs +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/TelemetryTests.cs @@ -18,7 +18,7 @@ public async Task Telemetry_ByDefault_TelemetryIsEnabled(string tfm) string diagPathPattern = Path.Combine(diagPath, @"log_.*.diag").Replace(@"\", @"\\"); var testHost = TestInfrastructure.TestHost.LocateFrom(AssetFixture.TargetAssetPath, AssetName, tfm); - TestHostResult testHostResult = await testHost.ExecuteAsync("--diagnostic", disableTelemetry: false); + TestHostResult testHostResult = await testHost.ExecuteAsync("--diagnostic", disableTelemetry: false, cancellationToken: TestContext.CancellationToken); testHostResult.AssertExitCodeIs(ExitCodes.ZeroTests); @@ -46,7 +46,7 @@ public async Task Telemetry_WhenOptingOutTelemetry_WithEnvironmentVariable_Telem { { EnvironmentVariableConstants.TESTINGPLATFORM_TELEMETRY_OPTOUT, "1" }, }, - disableTelemetry: false); + disableTelemetry: false, TestContext.CancellationToken); testHostResult.AssertExitCodeIs(ExitCodes.ZeroTests); @@ -74,7 +74,7 @@ public async Task Telemetry_WhenOptingOutTelemetry_With_DOTNET_CLI_EnvironmentVa { { EnvironmentVariableConstants.DOTNET_CLI_TELEMETRY_OPTOUT, "1" }, }, - disableTelemetry: false); + disableTelemetry: false, TestContext.CancellationToken); testHostResult.AssertExitCodeIs(ExitCodes.ZeroTests); @@ -96,7 +96,7 @@ public async Task Telemetry_WhenEnableTelemetryIsFalse_WithTestApplicationOption string diagPathPattern = Path.Combine(diagPath, @"log_.*.diag").Replace(@"\", @"\\"); var testHost = TestInfrastructure.TestHost.LocateFrom(AssetFixture.TargetAssetPathWithDisableTelemetry, AssetName, tfm); - TestHostResult testHostResult = await testHost.ExecuteAsync("--diagnostic", disableTelemetry: false); + TestHostResult testHostResult = await testHost.ExecuteAsync("--diagnostic", disableTelemetry: false, cancellationToken: TestContext.CancellationToken); testHostResult.AssertExitCodeIs(ExitCodes.ZeroTests); @@ -212,4 +212,6 @@ public Task ExecuteRequestAsync(ExecuteRequestContext context) .PatchCodeWithReplace("$TelemetryArg$", ", new TestApplicationOptions() { EnableTelemetry = false }")); } } + + public TestContext TestContext { get; set; } } diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/TestHostProcessLifetimeHandlerTests.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/TestHostProcessLifetimeHandlerTests.cs index cd3452d3df..c0327972fa 100644 --- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/TestHostProcessLifetimeHandlerTests.cs +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/TestHostProcessLifetimeHandlerTests.cs @@ -13,7 +13,7 @@ public sealed class TestHostProcessLifetimeHandlerTests : AcceptanceTestBase public async Task TimeoutWithInvalidArg_WithoutLetterSuffix_OutputInvalidMessage(string tfm) { var testHost = TestInfrastructure.TestHost.LocateFrom(AssetFixture.NoExtensionTargetAssetPath, TestAssetFixture.AssetName, tfm); - TestHostResult testHostResult = await testHost.ExecuteAsync("--timeout 5"); + TestHostResult testHostResult = await testHost.ExecuteAsync("--timeout 5", cancellationToken: TestContext.CancellationToken); testHostResult.AssertExitCodeIs(ExitCodes.InvalidCommandLine); testHostResult.AssertOutputContains("'timeout' option should have one argument as string in the format [h|m|s] where 'value' is float"); @@ -22,7 +22,7 @@ public async Task TimeoutWithInvalidArg_WithoutLetterSuffix_OutputInvalidMessage public async Task TimeoutWithInvalidArg_WithInvalidLetterSuffix_OutputInvalidMessage(string tfm) { var testHost = TestInfrastructure.TestHost.LocateFrom(AssetFixture.NoExtensionTargetAssetPath, TestAssetFixture.AssetName, tfm); - TestHostResult testHostResult = await testHost.ExecuteAsync("--timeout 5y"); + TestHostResult testHostResult = await testHost.ExecuteAsync("--timeout 5y", cancellationToken: TestContext.CancellationToken); testHostResult.AssertExitCodeIs(ExitCodes.InvalidCommandLine); testHostResult.AssertOutputContains("'timeout' option should have one argument as string in the format [h|m|s] where 'value' is float"); @@ -33,7 +33,7 @@ public async Task TimeoutWithInvalidArg_WithInvalidLetterSuffix_OutputInvalidMes public async Task TimeoutWithInvalidArg_WithInvalidFormat_OutputInvalidMessage(string tfm) { var testHost = TestInfrastructure.TestHost.LocateFrom(AssetFixture.NoExtensionTargetAssetPath, TestAssetFixture.AssetName, tfm); - TestHostResult testHostResult = await testHost.ExecuteAsync("--timeout 5h6m"); + TestHostResult testHostResult = await testHost.ExecuteAsync("--timeout 5h6m", cancellationToken: TestContext.CancellationToken); testHostResult.AssertExitCodeIs(ExitCodes.InvalidCommandLine); testHostResult.AssertOutputContains("'timeout' option should have one argument as string in the format [h|m|s] where 'value' is float"); @@ -44,7 +44,7 @@ public async Task TimeoutWithInvalidArg_WithInvalidFormat_OutputInvalidMessage(s public async Task TimeoutWithValidArg_WithTestTimeOut_OutputContainsCancelingMessage(string tfm) { var testHost = TestInfrastructure.TestHost.LocateFrom(AssetFixture.NoExtensionTargetAssetPath, TestAssetFixture.AssetName, tfm); - TestHostResult testHostResult = await testHost.ExecuteAsync("--timeout 1s"); + TestHostResult testHostResult = await testHost.ExecuteAsync("--timeout 1s", cancellationToken: TestContext.CancellationToken); testHostResult.AssertExitCodeIsNot(ExitCodes.Success); testHostResult.AssertOutputContains("Canceling the test session"); @@ -55,7 +55,7 @@ public async Task TimeoutWithValidArg_WithTestTimeOut_OutputContainsCancelingMes public async Task TimeoutWithValidArg_WithSecondAsSuffix_WithTestNotTimeOut_OutputDoesNotContainCancelingMessage(string tfm) { var testHost = TestInfrastructure.TestHost.LocateFrom(AssetFixture.NoExtensionTargetAssetPath, TestAssetFixture.AssetName, tfm); - TestHostResult testHostResult = await testHost.ExecuteAsync("--timeout 12.5s"); + TestHostResult testHostResult = await testHost.ExecuteAsync("--timeout 12.5s", cancellationToken: TestContext.CancellationToken); testHostResult.AssertExitCodeIs(ExitCodes.ZeroTests); testHostResult.AssertOutputDoesNotContain("Canceling the test session"); @@ -66,7 +66,7 @@ public async Task TimeoutWithValidArg_WithSecondAsSuffix_WithTestNotTimeOut_Outp public async Task TimeoutWithValidArg_WithMinuteAsSuffix_WithTestNotTimeOut_OutputDoesNotContainCancelingMessage(string tfm) { var testHost = TestInfrastructure.TestHost.LocateFrom(AssetFixture.NoExtensionTargetAssetPath, TestAssetFixture.AssetName, tfm); - TestHostResult testHostResult = await testHost.ExecuteAsync("--timeout 1m"); + TestHostResult testHostResult = await testHost.ExecuteAsync("--timeout 1m", cancellationToken: TestContext.CancellationToken); testHostResult.AssertExitCodeIs(ExitCodes.ZeroTests); testHostResult.AssertOutputDoesNotContain("Canceling the test session"); @@ -77,7 +77,7 @@ public async Task TimeoutWithValidArg_WithMinuteAsSuffix_WithTestNotTimeOut_Outp public async Task TimeoutWithValidArg_WithHourAsSuffix_WithTestNotTimeOut_OutputDoesNotContainCancelingMessage(string tfm) { var testHost = TestInfrastructure.TestHost.LocateFrom(AssetFixture.NoExtensionTargetAssetPath, TestAssetFixture.AssetName, tfm); - TestHostResult testHostResult = await testHost.ExecuteAsync("--timeout 1h"); + TestHostResult testHostResult = await testHost.ExecuteAsync("--timeout 1h", cancellationToken: TestContext.CancellationToken); testHostResult.AssertExitCodeIs(ExitCodes.ZeroTests); testHostResult.AssertOutputDoesNotContain("Canceling the test session"); @@ -157,4 +157,6 @@ public Task ExecuteRequestAsync(ExecuteRequestContext context) .PatchCodeWithReplace("$MicrosoftTestingPlatformVersion$", MicrosoftTestingPlatformVersion)); } } + + public TestContext TestContext { get; set; } } diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/TrxTests.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/TrxTests.cs index 90b89e9b90..26fbd380b1 100644 --- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/TrxTests.cs +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/TrxTests.cs @@ -11,7 +11,7 @@ public class TrxTests : AcceptanceTestBase public async Task Trx_WhenReportTrxIsNotSpecified_TrxReportIsNotGenerated(string tfm) { var testHost = TestInfrastructure.TestHost.LocateFrom(AssetFixture.TargetAssetPath, TestAssetFixture.AssetName, tfm); - TestHostResult testHostResult = await testHost.ExecuteAsync(); + TestHostResult testHostResult = await testHost.ExecuteAsync(cancellationToken: TestContext.CancellationToken); testHostResult.AssertExitCodeIs(ExitCodes.Success); @@ -30,7 +30,7 @@ public async Task Trx_WhenReportTrxIsSpecified_TrxReportIsGeneratedInDefaultLoca string trxPathPattern = Path.Combine(testResultsPath, ".*.trx").Replace(@"\", @"\\"); var testHost = TestInfrastructure.TestHost.LocateFrom(AssetFixture.TargetAssetPath, TestAssetFixture.AssetName, tfm); - TestHostResult testHostResult = await testHost.ExecuteAsync("--report-trx"); + TestHostResult testHostResult = await testHost.ExecuteAsync("--report-trx", cancellationToken: TestContext.CancellationToken); // number of test is the third param because we have two different test code with different number of tests. await AssertTrxReportWasGeneratedAsync(testHostResult, trxPathPattern, 1); @@ -50,7 +50,7 @@ public async Task Trx_WhenTestHostCrash_ErrorIsDisplayedInsideTheTrx(string tfm) var testHost = TestInfrastructure.TestHost.LocateFrom(AssetFixture.TargetAssetPath, TestAssetFixture.AssetName, tfm); TestHostResult testHostResult = await testHost.ExecuteAsync( $"--crashdump --report-trx --report-trx-filename {fileName}.trx", - new() { { "CRASHPROCESS", "1" } }); + new() { { "CRASHPROCESS", "1" } }, cancellationToken: TestContext.CancellationToken); testHostResult.AssertExitCodeIs(ExitCodes.TestHostProcessExitedNonGracefully); @@ -66,7 +66,7 @@ public async Task Trx_WhenSkipTest_ItAppearsAsExpectedInsideTheTrx(string tfm) { string fileName = Guid.NewGuid().ToString("N"); var testHost = TestInfrastructure.TestHost.LocateFrom(AssetFixture.TargetAssetPathWithSkippedTest, TestAssetFixture.AssetNameUsingMSTest, tfm); - TestHostResult testHostResult = await testHost.ExecuteAsync($"--report-trx --report-trx-filename {fileName}.trx"); + TestHostResult testHostResult = await testHost.ExecuteAsync($"--report-trx --report-trx-filename {fileName}.trx", cancellationToken: TestContext.CancellationToken); testHostResult.AssertExitCodeIs(ExitCodes.ZeroTests); @@ -89,7 +89,7 @@ public async Task Trx_WhenTheTestNameHasInvalidXmlChar_TheTrxCreatedSuccessfully string trxPathPattern = Path.Combine(testResultsPath, ".*.trx").Replace(@"\", @"\\"); var testHost = TestInfrastructure.TestHost.LocateFrom(AssetFixture.TargetAssetPathWithDataRow, TestAssetFixture.AssetNameUsingMSTest, tfm); - TestHostResult testHostResult = await testHost.ExecuteAsync("--report-trx"); + TestHostResult testHostResult = await testHost.ExecuteAsync("--report-trx", cancellationToken: TestContext.CancellationToken); // number of test is the third param because we have two different test code with different number of tests. await AssertTrxReportWasGeneratedAsync(testHostResult, trxPathPattern, 2); @@ -101,7 +101,7 @@ public async Task Trx_UsingDataDriven_CreatesUnitTestTagForEachOneInsideTheTrx(s { string fileName = Guid.NewGuid().ToString("N"); var testHost = TestInfrastructure.TestHost.LocateFrom(AssetFixture.TargetAssetPathWithSkippedTest, TestAssetFixture.AssetNameUsingMSTest, tfm); - TestHostResult testHostResult = await testHost.ExecuteAsync($"--report-trx --report-trx-filename {fileName}.trx"); + TestHostResult testHostResult = await testHost.ExecuteAsync($"--report-trx --report-trx-filename {fileName}.trx", cancellationToken: TestContext.CancellationToken); testHostResult.AssertExitCodeIs(ExitCodes.ZeroTests); @@ -126,7 +126,7 @@ public async Task Trx_WhenReportTrxIsSpecifiedWithFullPath_TrxReportShouldFail(s Assert.IsFalse(Directory.Exists(testResultsPath)); var testHost = TestInfrastructure.TestHost.LocateFrom(AssetFixture.TargetAssetPath, TestAssetFixture.AssetName, tfm); - TestHostResult testHostResult = await testHost.ExecuteAsync($"--report-trx --report-trx-filename {Path.Combine(testResultsPath, "report.trx")}"); + TestHostResult testHostResult = await testHost.ExecuteAsync($"--report-trx --report-trx-filename {Path.Combine(testResultsPath, "report.trx")}", cancellationToken: TestContext.CancellationToken); testHostResult.AssertExitCodeIs(ExitCodes.InvalidCommandLine); testHostResult.AssertOutputContains("Option '--report-trx-filename' has invalid arguments: file name argument must not contain path (e.g. --report-trx-filename myreport.trx)"); @@ -137,7 +137,7 @@ public async Task Trx_WhenReportTrxIsSpecifiedWithFullPath_TrxReportShouldFail(s public async Task Trx_WhenReportTrxIsSpecifiedWithRelativePath_TrxReportShouldFail(string tfm) { var testHost = TestInfrastructure.TestHost.LocateFrom(AssetFixture.TargetAssetPath, TestAssetFixture.AssetName, tfm); - TestHostResult testHostResult = await testHost.ExecuteAsync($"--report-trx --report-trx-filename {Path.Combine("aaa", "report.trx")}"); + TestHostResult testHostResult = await testHost.ExecuteAsync($"--report-trx --report-trx-filename {Path.Combine("aaa", "report.trx")}", cancellationToken: TestContext.CancellationToken); testHostResult.AssertExitCodeIs(ExitCodes.InvalidCommandLine); testHostResult.AssertOutputContains("Option '--report-trx-filename' has invalid arguments: file name argument must not contain path (e.g. --report-trx-filename myreport.trx)"); @@ -148,7 +148,7 @@ public async Task Trx_WhenReportTrxIsSpecifiedWithRelativePath_TrxReportShouldFa public async Task Trx_WhenReportTrxIsNotSpecifiedAndReportTrxPathIsSpecified_ErrorIsDisplayed(string tfm) { var testHost = TestInfrastructure.TestHost.LocateFrom(AssetFixture.TargetAssetPath, TestAssetFixture.AssetName, tfm); - TestHostResult testHostResult = await testHost.ExecuteAsync("--report-trx-filename report.trx"); + TestHostResult testHostResult = await testHost.ExecuteAsync("--report-trx-filename report.trx", cancellationToken: TestContext.CancellationToken); testHostResult.AssertExitCodeIs(ExitCodes.InvalidCommandLine); testHostResult.AssertOutputContains("Error: '--report-trx-filename' requires '--report-trx' to be enabled"); @@ -160,13 +160,13 @@ public async Task Trx_WhenReportTrxIsSpecifiedAndReportTrxPathIsSpecified_Overwr { var testHost = TestInfrastructure.TestHost.LocateFrom(AssetFixture.TargetAssetPath, TestAssetFixture.AssetName, tfm); string reportFileName = $"report-{tfm}.trx"; - TestHostResult testHostResult = await testHost.ExecuteAsync($"--report-trx --report-trx-filename {reportFileName}"); + TestHostResult testHostResult = await testHost.ExecuteAsync($"--report-trx --report-trx-filename {reportFileName}", cancellationToken: TestContext.CancellationToken); testHostResult.AssertExitCodeIs(ExitCodes.Success); string warningMessage = $"Warning: Trx file '{Path.Combine(testHost.DirectoryName, "TestResults", reportFileName)}' already exists and will be overwritten."; testHostResult.AssertOutputDoesNotContain(warningMessage); - testHostResult = await testHost.ExecuteAsync($"--report-trx --report-trx-filename {reportFileName}"); + testHostResult = await testHost.ExecuteAsync($"--report-trx --report-trx-filename {reportFileName}", cancellationToken: TestContext.CancellationToken); testHostResult.AssertExitCodeIs(ExitCodes.Success); testHostResult.AssertOutputContains(warningMessage); @@ -177,7 +177,7 @@ public async Task Trx_WhenReportTrxIsSpecifiedAndReportTrxPathIsSpecified_Overwr public async Task Trx_WhenReportTrxIsSpecifiedAndListTestsIsSpecified_ErrorIsDisplayed(string tfm) { var testHost = TestInfrastructure.TestHost.LocateFrom(AssetFixture.TargetAssetPath, TestAssetFixture.AssetName, tfm); - TestHostResult testHostResult = await testHost.ExecuteAsync("--report-trx --list-tests"); + TestHostResult testHostResult = await testHost.ExecuteAsync("--report-trx --list-tests", cancellationToken: TestContext.CancellationToken); testHostResult.AssertExitCodeIs(ExitCodes.InvalidCommandLine); testHostResult.AssertOutputContains("Error: '--report-trx' cannot be enabled when using '--list-tests'"); @@ -382,4 +382,6 @@ public void TestMethod1(string s) .PatchCodeWithReplace("$IgnoreTestAttributeOrNothing$", string.Empty)); } } + + public TestContext TestContext { get; set; } } diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/TypeForwardingTests.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/TypeForwardingTests.cs index 4a8e77822b..b39ea87d09 100644 --- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/TypeForwardingTests.cs +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/TypeForwardingTests.cs @@ -68,12 +68,14 @@ public async Task SettingDisplayNameFromNetStandardLibraryDuringNetCurrentRuntim .PatchCodeWithReplace("$MicrosoftTestingPlatformVersion$", MicrosoftTestingPlatformVersion); using TestAsset testAsset = await TestAsset.GenerateAssetAsync(AssetName, patchedSources); - await DotnetCli.RunAsync($"build -m:1 -nodeReuse:false {testAsset.TargetAssetPath}/ConsoleApp -c Release", AcceptanceFixture.NuGetGlobalPackagesFolder.Path); + await DotnetCli.RunAsync($"build -m:1 -nodeReuse:false {testAsset.TargetAssetPath}/ConsoleApp -c Release", AcceptanceFixture.NuGetGlobalPackagesFolder.Path, cancellationToken: TestContext.CancellationToken); var testHost = TestInfrastructure.TestHost.LocateFrom($"{testAsset.TargetAssetPath}/ConsoleApp", "ConsoleApp", TargetFrameworks.NetCurrent); - TestHostResult testHostResult = await testHost.ExecuteAsync(); + TestHostResult testHostResult = await testHost.ExecuteAsync(cancellationToken: TestContext.CancellationToken); testHostResult.AssertExitCodeIs(ExitCodes.Success); testHostResult.AssertOutputContains("MyDisplayName"); } + + public TestContext TestContext { get; set; } } diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/UnhandledExceptionPolicyTests.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/UnhandledExceptionPolicyTests.cs index 69ec64519f..b1675e268f 100644 --- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/UnhandledExceptionPolicyTests.cs +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/UnhandledExceptionPolicyTests.cs @@ -45,39 +45,45 @@ public async Task UnhandledExceptionPolicy_ConfigFile_UnobservedTaskException_Sh { case Mode.Enabled: File.WriteAllText(configFileName, contentFile.Replace("\"exitProcessOnUnhandledException\": false", "\"exitProcessOnUnhandledException\": true")); - testHostResult = await testHost.ExecuteAsync(null, new() { { "UNOBSERVEDTASKEXCEPTION", "1" } }); + testHostResult = await testHost.ExecuteAsync(null, new() { { "UNOBSERVEDTASKEXCEPTION", "1" } }, cancellationToken: TestContext.CancellationToken); testHostResult.AssertExitCodeIsNot(ExitCodes.Success); testHostResult.AssertOutputContains("[UnhandledExceptionHandler.OnTaskSchedulerUnobservedTaskException(testhost controller workflow)]"); break; case Mode.Disabled: File.WriteAllText(configFileName, contentFile.Replace("\"exitProcessOnUnhandledException\": false", "\"exitProcessOnUnhandledException\": false")); - testHostResult = await testHost.ExecuteAsync(null, new() { { "UNOBSERVEDTASKEXCEPTION", "1" } }); + testHostResult = await testHost.ExecuteAsync(null, new() { { "UNOBSERVEDTASKEXCEPTION", "1" } }, cancellationToken: TestContext.CancellationToken); testHostResult.AssertExitCodeIs(ExitCodes.Success); testHostResult.AssertOutputDoesNotContain("[UnhandledExceptionHandler.OnTaskSchedulerUnobservedTaskException]"); break; case Mode.Default: File.Delete(configFileName); - testHostResult = await testHost.ExecuteAsync(null, new() { { "UNOBSERVEDTASKEXCEPTION", "1" } }); + testHostResult = await testHost.ExecuteAsync(null, new() { { "UNOBSERVEDTASKEXCEPTION", "1" } }, cancellationToken: TestContext.CancellationToken); testHostResult.AssertExitCodeIs(ExitCodes.Success); testHostResult.AssertOutputDoesNotContain("[UnhandledExceptionHandler.OnTaskSchedulerUnobservedTaskException]"); break; case Mode.DisabledByEnvironmentVariable: File.WriteAllText(configFileName, contentFile.Replace("\"exitProcessOnUnhandledException\": false", "\"exitProcessOnUnhandledException\": true")); - testHostResult = await testHost.ExecuteAsync(null, new() - { - { "UNOBSERVEDTASKEXCEPTION", "1" }, - { EnvironmentVariableConstants.TESTINGPLATFORM_EXIT_PROCESS_ON_UNHANDLED_EXCEPTION, "0" }, - }); + testHostResult = await testHost.ExecuteAsync( + null, + new() + { + { "UNOBSERVEDTASKEXCEPTION", "1" }, + { EnvironmentVariableConstants.TESTINGPLATFORM_EXIT_PROCESS_ON_UNHANDLED_EXCEPTION, "0" }, + }, + cancellationToken: TestContext.CancellationToken); testHostResult.AssertExitCodeIs(ExitCodes.Success); testHostResult.AssertOutputDoesNotContain("[UnhandledExceptionHandler.OnTaskSchedulerUnobservedTaskException]"); break; case Mode.EnabledByEnvironmentVariable: File.WriteAllText(configFileName, contentFile.Replace("\"exitProcessOnUnhandledException\": false", "\"exitProcessOnUnhandledException\": false")); - testHostResult = await testHost.ExecuteAsync(null, new() - { - { "UNOBSERVEDTASKEXCEPTION", "1" }, - { EnvironmentVariableConstants.TESTINGPLATFORM_EXIT_PROCESS_ON_UNHANDLED_EXCEPTION, "1" }, - }); + testHostResult = await testHost.ExecuteAsync( + null, + new() + { + { "UNOBSERVEDTASKEXCEPTION", "1" }, + { EnvironmentVariableConstants.TESTINGPLATFORM_EXIT_PROCESS_ON_UNHANDLED_EXCEPTION, "1" }, + }, + cancellationToken: TestContext.CancellationToken); testHostResult.AssertExitCodeIsNot(ExitCodes.Success); testHostResult.AssertOutputContains("[UnhandledExceptionHandler.OnTaskSchedulerUnobservedTaskException(testhost controller workflow)]"); break; @@ -102,40 +108,46 @@ public async Task UnhandledExceptionPolicy_EnvironmentVariable_UnhandledExceptio { case Mode.Enabled: File.WriteAllText(configFileName, contentFile.Replace("\"exitProcessOnUnhandledException\": false", "\"exitProcessOnUnhandledException\": true")); - testHostResult = await testHost.ExecuteAsync(null, new() { { "UNHANDLEDEXCEPTION", "1" } }); + testHostResult = await testHost.ExecuteAsync(null, new() { { "UNHANDLEDEXCEPTION", "1" } }, cancellationToken: TestContext.CancellationToken); testHostResult.AssertOutputContains("[UnhandledExceptionHandler.OnCurrentDomainUnhandledException(testhost controller workflow)]"); testHostResult.AssertOutputContains("IsTerminating: True"); testHostResult.AssertExitCodeIsNot(ExitCodes.Success); break; case Mode.Disabled: File.WriteAllText(configFileName, contentFile.Replace("\"exitProcessOnUnhandledException\": false", "\"exitProcessOnUnhandledException\": false")); - testHostResult = await testHost.ExecuteAsync(null, new() { { "UNHANDLEDEXCEPTION", "1" } }); + testHostResult = await testHost.ExecuteAsync(null, new() { { "UNHANDLEDEXCEPTION", "1" } }, cancellationToken: TestContext.CancellationToken); Assert.IsTrue(testHostResult.StandardError.Contains("Unhandled exception", StringComparison.OrdinalIgnoreCase), testHostResult.ToString()); testHostResult.AssertExitCodeIsNot(ExitCodes.Success); break; case Mode.Default: File.Delete(configFileName); - testHostResult = await testHost.ExecuteAsync(null, new() { { "UNHANDLEDEXCEPTION", "1" } }); + testHostResult = await testHost.ExecuteAsync(null, new() { { "UNHANDLEDEXCEPTION", "1" } }, cancellationToken: TestContext.CancellationToken); testHostResult.AssertExitCodeIsNot(ExitCodes.Success); break; case Mode.DisabledByEnvironmentVariable: File.WriteAllText(configFileName, contentFile.Replace("\"exitProcessOnUnhandledException\": false", "\"exitProcessOnUnhandledException\": true")); - testHostResult = await testHost.ExecuteAsync(null, new() - { - { "UNHANDLEDEXCEPTION", "1" }, - { EnvironmentVariableConstants.TESTINGPLATFORM_EXIT_PROCESS_ON_UNHANDLED_EXCEPTION, "0" }, - }); + testHostResult = await testHost.ExecuteAsync( + null, + new() + { + { "UNHANDLEDEXCEPTION", "1" }, + { EnvironmentVariableConstants.TESTINGPLATFORM_EXIT_PROCESS_ON_UNHANDLED_EXCEPTION, "0" }, + }, + cancellationToken: TestContext.CancellationToken); Assert.IsTrue(testHostResult.StandardError.Contains("Unhandled exception", StringComparison.OrdinalIgnoreCase), testHostResult.ToString()); testHostResult.AssertOutputDoesNotContain("IsTerminating: True"); testHostResult.AssertExitCodeIsNot(ExitCodes.Success); break; case Mode.EnabledByEnvironmentVariable: File.WriteAllText(configFileName, contentFile.Replace("\"exitProcessOnUnhandledException\": false", "\"exitProcessOnUnhandledException\": false")); - testHostResult = await testHost.ExecuteAsync(null, new() - { - { "UNHANDLEDEXCEPTION", "1" }, - { EnvironmentVariableConstants.TESTINGPLATFORM_EXIT_PROCESS_ON_UNHANDLED_EXCEPTION, "1" }, - }); + testHostResult = await testHost.ExecuteAsync( + null, + new() + { + { "UNHANDLEDEXCEPTION", "1" }, + { EnvironmentVariableConstants.TESTINGPLATFORM_EXIT_PROCESS_ON_UNHANDLED_EXCEPTION, "1" }, + }, + cancellationToken: TestContext.CancellationToken); testHostResult.AssertOutputContains("[UnhandledExceptionHandler.OnCurrentDomainUnhandledException(testhost controller workflow)]"); testHostResult.AssertOutputContains("IsTerminating: True"); testHostResult.AssertExitCodeIsNot(ExitCodes.Success); diff --git a/test/Utilities/Microsoft.Testing.TestInfrastructure/CommandLine.cs b/test/Utilities/Microsoft.Testing.TestInfrastructure/CommandLine.cs index 52059a16b5..51bf29848b 100644 --- a/test/Utilities/Microsoft.Testing.TestInfrastructure/CommandLine.cs +++ b/test/Utilities/Microsoft.Testing.TestInfrastructure/CommandLine.cs @@ -40,9 +40,10 @@ public static int MaxOutstandingCommands public async Task RunAsync( string commandLine, - IDictionary? environmentVariables = null) + IDictionary? environmentVariables = null, + CancellationToken cancellationToken = default) { - int exitCode = await RunAsyncAndReturnExitCodeAsync(commandLine, environmentVariables); + int exitCode = await RunAsyncAndReturnExitCodeAsync(commandLine, environmentVariables, cancellationToken: cancellationToken); if (exitCode != 0) { throw new InvalidOperationException( @@ -71,9 +72,10 @@ public async Task RunAsyncAndReturnExitCodeAsync( string commandLine, IDictionary? environmentVariables = null, string? workingDirectory = null, - bool cleanDefaultEnvironmentVariableIfCustomAreProvided = false) + bool cleanDefaultEnvironmentVariableIfCustomAreProvided = false, + CancellationToken cancellationToken = default) { - await s_maxOutstandingCommands_semaphore.WaitAsync(); + await s_maxOutstandingCommands_semaphore.WaitAsync(cancellationToken); try { Interlocked.Increment(ref s_totalProcessesAttempt); @@ -90,7 +92,8 @@ public async Task RunAsyncAndReturnExitCodeAsync( }; _process = ProcessFactory.Start(startInfo, cleanDefaultEnvironmentVariableIfCustomAreProvided); - return await _process.WaitForExitAsync(); + using CancellationTokenRegistration registration = cancellationToken.Register(() => _process.Kill()); + return await _process.WaitForExitAsync(cancellationToken); } finally { diff --git a/test/Utilities/Microsoft.Testing.TestInfrastructure/DotnetCli.cs b/test/Utilities/Microsoft.Testing.TestInfrastructure/DotnetCli.cs index a7fc3a6784..961b396e17 100644 --- a/test/Utilities/Microsoft.Testing.TestInfrastructure/DotnetCli.cs +++ b/test/Utilities/Microsoft.Testing.TestInfrastructure/DotnetCli.cs @@ -58,9 +58,10 @@ public static async Task RunAsync( bool disableCodeCoverage = true, bool warnAsError = true, bool suppressPreviewDotNetMessage = true, - [CallerMemberName] string callerMemberName = "") + [CallerMemberName] string callerMemberName = "", + CancellationToken cancellationToken = default) { - await s_maxOutstandingCommands_semaphore.WaitAsync(); + await s_maxOutstandingCommands_semaphore.WaitAsync(cancellationToken); try { environmentVariables ??= []; @@ -109,7 +110,7 @@ public static async Task RunAsync( if (DoNotRetry) { - return await CallTheMuxerAsync(args, environmentVariables, workingDirectory, failIfReturnValueIsNotZero, callerMemberName); + return await CallTheMuxerAsync(args, environmentVariables, workingDirectory, failIfReturnValueIsNotZero, callerMemberName, cancellationToken); } else { @@ -117,7 +118,7 @@ public static async Task RunAsync( return await Policy .Handle() .WaitAndRetryAsync(delay) - .ExecuteAsync(async () => await CallTheMuxerAsync(args, environmentVariables, workingDirectory, failIfReturnValueIsNotZero, callerMemberName)); + .ExecuteAsync(async ct => await CallTheMuxerAsync(args, environmentVariables, workingDirectory, failIfReturnValueIsNotZero, callerMemberName, ct), cancellationToken); } } finally @@ -130,13 +131,13 @@ private static bool IsDotNetTestWithExeOrDll(string args) => args.StartsWith("test ", StringComparison.Ordinal) && (args.Contains(".dll") || args.Contains(".exe")); // Workaround NuGet issue https://github.com/NuGet/Home/issues/14064 - private static async Task CallTheMuxerAsync(string args, Dictionary environmentVariables, string? workingDirectory, bool failIfReturnValueIsNotZero, string binlogBaseFileName) + private static async Task CallTheMuxerAsync(string args, Dictionary environmentVariables, string? workingDirectory, bool failIfReturnValueIsNotZero, string binlogBaseFileName, CancellationToken cancellationToken) => await Policy .Handle(ex => ex.Message.Contains("MSB4236")) .WaitAndRetryAsync(retryCount: 3, sleepDurationProvider: static _ => TimeSpan.FromSeconds(2)) - .ExecuteAsync(async () => await CallTheMuxerCoreAsync(args, environmentVariables, workingDirectory, failIfReturnValueIsNotZero, binlogBaseFileName)); + .ExecuteAsync(async ct => await CallTheMuxerCoreAsync(args, environmentVariables, workingDirectory, failIfReturnValueIsNotZero, binlogBaseFileName, ct), cancellationToken); - private static async Task CallTheMuxerCoreAsync(string args, Dictionary environmentVariables, string? workingDirectory, bool failIfReturnValueIsNotZero, string binlogBaseFileName) + private static async Task CallTheMuxerCoreAsync(string args, Dictionary environmentVariables, string? workingDirectory, bool failIfReturnValueIsNotZero, string binlogBaseFileName, CancellationToken cancellationToken) { if (args.StartsWith("dotnet ", StringComparison.OrdinalIgnoreCase)) { @@ -160,7 +161,7 @@ private static async Task CallTheMuxerCoreAsync(string args, } using DotnetMuxer dotnet = new(environmentVariables); - int exitCode = await dotnet.ExecuteAsync(args, workingDirectory); + int exitCode = await dotnet.ExecuteAsync(args, workingDirectory, cancellationToken); if (dotnet.StandardError.Contains("Invalid runtimeconfig.json")) { diff --git a/test/Utilities/Microsoft.Testing.TestInfrastructure/DotnetMuxer.cs b/test/Utilities/Microsoft.Testing.TestInfrastructure/DotnetMuxer.cs index d25c5b96e8..d0dee689b9 100644 --- a/test/Utilities/Microsoft.Testing.TestInfrastructure/DotnetMuxer.cs +++ b/test/Utilities/Microsoft.Testing.TestInfrastructure/DotnetMuxer.cs @@ -92,18 +92,20 @@ protected virtual void Dispose(bool disposing) _isDisposed = true; } - public async Task ExecuteAsync(string arguments, string? workingDirectory = null) - => await ExecuteAsync(arguments, workingDirectory, _environmentVariables); + public async Task ExecuteAsync(string arguments, string? workingDirectory = null, CancellationToken cancellationToken = default) + => await ExecuteAsync(arguments, workingDirectory, _environmentVariables, cancellationToken); public async Task ExecuteAsync( string arguments, string? workingDirectory, - IDictionary environmentVariables) + IDictionary environmentVariables, + CancellationToken cancellationToken) => await _commandLine.RunAsyncAndReturnExitCodeAsync( $"{_dotnet} {arguments}", environmentVariables, workingDirectory: workingDirectory, - cleanDefaultEnvironmentVariableIfCustomAreProvided: true); + cleanDefaultEnvironmentVariableIfCustomAreProvided: true, + cancellationToken); private static IDictionary MergeEnvironmentVariables( IDictionary environmentVariables1, diff --git a/test/Utilities/Microsoft.Testing.TestInfrastructure/IProcessHandle.cs b/test/Utilities/Microsoft.Testing.TestInfrastructure/IProcessHandle.cs index f9f3a43cc5..9307e6fdcc 100644 --- a/test/Utilities/Microsoft.Testing.TestInfrastructure/IProcessHandle.cs +++ b/test/Utilities/Microsoft.Testing.TestInfrastructure/IProcessHandle.cs @@ -19,9 +19,9 @@ public interface IProcessHandle void Kill(); - Task StopAsync(); + Task StopAsync(CancellationToken cancellationToken = default); - Task WaitForExitAsync(); + Task WaitForExitAsync(CancellationToken cancellationToken = default); Task WriteInputAsync(string input); } diff --git a/test/Utilities/Microsoft.Testing.TestInfrastructure/ProcessHandle.cs b/test/Utilities/Microsoft.Testing.TestInfrastructure/ProcessHandle.cs index fb32b027b3..31d4fc729c 100644 --- a/test/Utilities/Microsoft.Testing.TestInfrastructure/ProcessHandle.cs +++ b/test/Utilities/Microsoft.Testing.TestInfrastructure/ProcessHandle.cs @@ -26,18 +26,18 @@ internal ProcessHandle(Process process, ProcessHandleInfo processHandleInfo) public int ExitCode => _process.ExitCode; - public async Task WaitForExitAsync() + public async Task WaitForExitAsync(CancellationToken cancellationToken = default) { if (_disposed) { return _exitCode; } - await _process.WaitForExitAsync(); + await _process.WaitForExitAsync(cancellationToken); return _process.ExitCode; } - public async Task StopAsync() + public async Task StopAsync(CancellationToken cancellationToken = default) { if (_disposed) { @@ -45,7 +45,7 @@ public async Task StopAsync() } KillSafe(_process); - return await WaitForExitAsync(); + return await WaitForExitAsync(cancellationToken); } public void Kill() diff --git a/test/Utilities/Microsoft.Testing.TestInfrastructure/TestAssetFixtureBase.cs b/test/Utilities/Microsoft.Testing.TestInfrastructure/TestAssetFixtureBase.cs index 343e98d000..5178272cca 100644 --- a/test/Utilities/Microsoft.Testing.TestInfrastructure/TestAssetFixtureBase.cs +++ b/test/Utilities/Microsoft.Testing.TestInfrastructure/TestAssetFixtureBase.cs @@ -5,12 +5,12 @@ namespace Microsoft.Testing.TestInfrastructure; public interface ITestAssetFixture : IDisposable { - Task InitializeAsync(); + Task InitializeAsync(CancellationToken cancellationToken); } public sealed class NopAssetFixture : ITestAssetFixture { - public Task InitializeAsync() => Task.CompletedTask; + public Task InitializeAsync(CancellationToken cancellationToken) => Task.CompletedTask; public void Dispose() { @@ -32,13 +32,13 @@ public string GetAssetPath(string assetID) ? throw new ArgumentNullException(nameof(assetID), $"Cannot find target path for test asset '{assetID}'") : testAsset.TargetAssetPath; - public async Task InitializeAsync() => + public async Task InitializeAsync(CancellationToken cancellationToken) => // Generate all projects into the same temporary base folder, but separate subdirectories, so we can reference one from other. #if NET await Parallel.ForEachAsync(GetAssetsToGenerate(), async (asset, _) => { TestAsset testAsset = await TestAsset.GenerateAssetAsync(asset.ID, asset.Code, _tempDirectory); - DotnetMuxerResult result = await DotnetCli.RunAsync($"build {testAsset.TargetAssetPath} -c Release", _nugetGlobalPackagesDirectory.Path, callerMemberName: asset.Name); + DotnetMuxerResult result = await DotnetCli.RunAsync($"build {testAsset.TargetAssetPath} -c Release", _nugetGlobalPackagesDirectory.Path, callerMemberName: asset.Name, cancellationToken: cancellationToken); testAsset.DotnetResult = result; _testAssets.TryAdd(asset.ID, testAsset); }); @@ -46,7 +46,7 @@ await Parallel.ForEachAsync(GetAssetsToGenerate(), async (asset, _) => await Task.WhenAll(GetAssetsToGenerate().Select(async asset => { TestAsset testAsset = await TestAsset.GenerateAssetAsync(asset.Name, asset.Code, _tempDirectory); - DotnetMuxerResult result = await DotnetCli.RunAsync($"build {testAsset.TargetAssetPath} -c Release", _nugetGlobalPackagesDirectory.Path, callerMemberName: asset.Name); + DotnetMuxerResult result = await DotnetCli.RunAsync($"build {testAsset.TargetAssetPath} -c Release", _nugetGlobalPackagesDirectory.Path, callerMemberName: asset.Name, cancellationToken: cancellationToken); testAsset.DotnetResult = result; _testAssets.TryAdd(asset.ID, testAsset); })); diff --git a/test/Utilities/Microsoft.Testing.TestInfrastructure/TestHost.cs b/test/Utilities/Microsoft.Testing.TestInfrastructure/TestHost.cs index a490fab4f1..91f9c992db 100644 --- a/test/Utilities/Microsoft.Testing.TestInfrastructure/TestHost.cs +++ b/test/Utilities/Microsoft.Testing.TestInfrastructure/TestHost.cs @@ -40,9 +40,10 @@ public static int MaxOutstandingExecutions public async Task ExecuteAsync( string? command = null, Dictionary? environmentVariables = null, - bool disableTelemetry = true) + bool disableTelemetry = true, + CancellationToken cancellationToken = default) { - await s_maxOutstandingExecutions_semaphore.WaitAsync(); + await s_maxOutstandingExecutions_semaphore.WaitAsync(cancellationToken); try { if (command?.StartsWith(_testHostModuleName, StringComparison.OrdinalIgnoreCase) ?? false) @@ -83,19 +84,22 @@ public async Task ExecuteAsync( return await Policy .Handle() .WaitAndRetryAsync(delay) - .ExecuteAsync(async () => - { - CommandLine commandLine = new(); - // Disable ANSI rendering so tests have easier time parsing the output. - // Disable progress so tests don't mix progress with overall progress, and with test process output. - int exitCode = await commandLine.RunAsyncAndReturnExitCodeAsync( - $"{FullName} --no-ansi --no-progress {finalArguments}", - environmentVariables: environmentVariables, - workingDirectory: null, - cleanDefaultEnvironmentVariableIfCustomAreProvided: true); - string fullCommand = command is not null ? $"{FullName} {command}" : FullName; - return new TestHostResult(fullCommand, exitCode, commandLine.StandardOutput, commandLine.StandardOutputLines, commandLine.ErrorOutput, commandLine.ErrorOutputLines); - }); + .ExecuteAsync( + async ct => + { + CommandLine commandLine = new(); + // Disable ANSI rendering so tests have easier time parsing the output. + // Disable progress so tests don't mix progress with overall progress, and with test process output. + int exitCode = await commandLine.RunAsyncAndReturnExitCodeAsync( + $"{FullName} --no-ansi --no-progress {finalArguments}", + environmentVariables: environmentVariables, + workingDirectory: null, + cleanDefaultEnvironmentVariableIfCustomAreProvided: true, + cancellationToken: ct); + string fullCommand = command is not null ? $"{FullName} {command}" : FullName; + return new TestHostResult(fullCommand, exitCode, commandLine.StandardOutput, commandLine.StandardOutputLines, commandLine.ErrorOutput, commandLine.ErrorOutputLines); + }, + cancellationToken); } finally { From 62023bcace45557fce8d84d817181b37d707c384 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Wed, 3 Sep 2025 15:53:11 +0200 Subject: [PATCH 470/541] Clean TestProgressState on TestExecutionCompleted (#6505) --- .../OutputDevice/Terminal/TerminalTestReporter.cs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporter.cs b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporter.cs index db8c1a05f7..5bc9f7daa7 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporter.cs +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporter.cs @@ -159,6 +159,11 @@ public void TestExecutionCompleted(DateTimeOffset endTime) _terminalWithProgress.WriteToTerminal(_isDiscovery ? AppendTestDiscoverySummary : AppendTestRunSummary); NativeMethods.RestoreConsoleMode(_originalConsoleMode); + + // This is relevant for HotReload scenarios. We want the next test sessions to start + // on a new TestProgressState + _testProgressState = null; + _buildErrorsCount = 0; _testExecutionStartTime = null; _testExecutionEndTime = null; From 684f40affad7afc91e8a960cc64ebf12bc25a3d1 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Wed, 3 Sep 2025 19:01:10 +0200 Subject: [PATCH 471/541] Cleanup unused class (#6508) --- .../ServerMode/DotnetTest/IPC/Models/TestResultMessages.cs | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Models/TestResultMessages.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Models/TestResultMessages.cs index fac3cb9f44..a1ebc94504 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Models/TestResultMessages.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Models/TestResultMessages.cs @@ -7,8 +7,6 @@ internal sealed record SuccessfulTestResultMessage(string? Uid, string? DisplayN internal sealed record FailedTestResultMessage(string? Uid, string? DisplayName, byte? State, long? Duration, string? Reason, ExceptionMessage[]? Exceptions, string? StandardOutput, string? ErrorOutput, string? SessionUid); -internal sealed record InProgressTestResultMessage(string? Uid, string? DisplayName, string? SessionUid); - internal sealed record ExceptionMessage(string? ErrorMessage, string? ErrorType, string? StackTrace); internal sealed record TestResultMessages(string? ExecutionId, string? InstanceId, SuccessfulTestResultMessage[] SuccessfulTestMessages, FailedTestResultMessage[] FailedTestMessages) : IRequest; From adeb129055b993665fb1a6b2641fe543aaf4f9de Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Thu, 4 Sep 2025 07:28:27 +0200 Subject: [PATCH 472/541] [main] Update dependencies from microsoft/testfx (#6515) Co-authored-by: dotnet-maestro[bot] --- eng/Version.Details.xml | 8 ++++---- eng/Versions.props | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index b9a192b211..b9b1ce5256 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -17,13 +17,13 @@ https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage 55eaeaf5a193df238f4437a9b2889da77056347d - + https://github.com/microsoft/testfx - 0d5aa69d6b2cbeebff30536a22d31f4bd7ecf684 + 684f40affad7afc91e8a960cc64ebf12bc25a3d1 - + https://github.com/microsoft/testfx - 0d5aa69d6b2cbeebff30536a22d31f4bd7ecf684 + 684f40affad7afc91e8a960cc64ebf12bc25a3d1 diff --git a/eng/Versions.props b/eng/Versions.props index 2e5412e4e7..4532056d97 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -10,7 +10,7 @@ 11.0.0-beta.25452.3 18.0.0-preview.25452.1 - 3.11.0-preview.25452.4 - 1.9.0-preview.25452.4 + 3.11.0-preview.25453.10 + 1.9.0-preview.25453.10 From 4e95278f065e77bbf5ed589b7540ed765a330ee0 Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Thu, 4 Sep 2025 06:08:02 +0000 Subject: [PATCH 473/541] [main] Update dependencies from dotnet/arcade (#6514) Co-authored-by: dotnet-maestro[bot] --- eng/Version.Details.xml | 12 ++++++------ eng/Versions.props | 2 +- global.json | 2 +- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index b9b1ce5256..36d0611901 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -1,17 +1,17 @@ - + https://github.com/dotnet/arcade - 19b800616b55f3fae5098eb0dad0a63a15747a00 + f614a5074484f409b8dd60a98a2a9f7abf571970 - + https://github.com/dotnet/arcade - 19b800616b55f3fae5098eb0dad0a63a15747a00 + f614a5074484f409b8dd60a98a2a9f7abf571970 - + https://github.com/dotnet/arcade - 19b800616b55f3fae5098eb0dad0a63a15747a00 + f614a5074484f409b8dd60a98a2a9f7abf571970 https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage diff --git a/eng/Versions.props b/eng/Versions.props index 4532056d97..dab221633e 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -7,7 +7,7 @@ preview - 11.0.0-beta.25452.3 + 11.0.0-beta.25453.1 18.0.0-preview.25452.1 3.11.0-preview.25453.10 diff --git a/global.json b/global.json index 03bd9c8f95..0c9e5cb2f3 100644 --- a/global.json +++ b/global.json @@ -33,7 +33,7 @@ "rollForward": "latestFeature" }, "msbuild-sdks": { - "Microsoft.DotNet.Arcade.Sdk": "11.0.0-beta.25452.3", + "Microsoft.DotNet.Arcade.Sdk": "11.0.0-beta.25453.1", "MSBuild.Sdk.Extras": "3.0.44" } } From 4efd6272d4157c64f4839bca5bbaa3c48007213c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Thu, 4 Sep 2025 10:54:42 +0200 Subject: [PATCH 474/541] Rename --debug-wait-attach to --debug (#6516) --- .../CommandLine/PlatformCommandLineProvider.cs | 2 +- .../MSTest.Acceptance.IntegrationTests/HelpInfoTests.cs | 2 +- .../HelpInfoTests.cs | 8 ++++---- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Platform/CommandLine/PlatformCommandLineProvider.cs b/src/Platform/Microsoft.Testing.Platform/CommandLine/PlatformCommandLineProvider.cs index 777497f217..2d5b375879 100644 --- a/src/Platform/Microsoft.Testing.Platform/CommandLine/PlatformCommandLineProvider.cs +++ b/src/Platform/Microsoft.Testing.Platform/CommandLine/PlatformCommandLineProvider.cs @@ -29,7 +29,7 @@ internal sealed class PlatformCommandLineProvider : ICommandLineOptionsProvider public const string ExitOnProcessExitOptionKey = "exit-on-process-exit"; public const string ConfigFileOptionKey = "config-file"; public const string FilterUidOptionKey = "filter-uid"; - public const string DebugAttachOptionKey = "debug-wait-attach"; + public const string DebugAttachOptionKey = "debug"; public const string ServerOptionKey = "server"; public const string ClientPortOptionKey = "client-port"; diff --git a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/HelpInfoTests.cs b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/HelpInfoTests.cs index 2f5bb7d2df..5a74f90618 100644 --- a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/HelpInfoTests.cs +++ b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/HelpInfoTests.cs @@ -28,7 +28,7 @@ Execute a .NET Test Application. Options: --config-file Specifies a testconfig.json file. - --debug-wait-attach + --debug Allows to pause execution in order to attach to the process for debug purposes. --diagnostic Enable the diagnostic logging. The default log level is 'Trace'. diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/HelpInfoTests.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/HelpInfoTests.cs index e83879a61c..20a68cbf65 100644 --- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/HelpInfoTests.cs +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/HelpInfoTests.cs @@ -22,7 +22,7 @@ Execute a .NET Test Application. Options: --config-file Specifies a testconfig.json file. - --debug-wait-attach + --debug Allows to pause execution in order to attach to the process for debug purposes. --diagnostic Enable the diagnostic logging. The default log level is 'Trace'. @@ -154,7 +154,7 @@ Microsoft.Testing.Platform v.+ \[.+\] Arity: 1 Hidden: False Description: Specifies a testconfig\.json file\. - --debug-wait-attach + --debug Arity: 0 Hidden: False Description: Allows to pause execution in order to attach to the process for debug purposes. @@ -285,7 +285,7 @@ Execute a .NET Test Application. Options: --config-file Specifies a testconfig.json file. - --debug-wait-attach + --debug Allows to pause execution in order to attach to the process for debug purposes. --diagnostic Enable the diagnostic logging. The default log level is 'Trace'. @@ -428,7 +428,7 @@ Microsoft.Testing.Platform v* [*] Arity: 1 Hidden: False Description: Specifies a testconfig.json file. - --debug-wait-attach + --debug Arity: 0 Hidden: False Description: Allows to pause execution in order to attach to the process for debug purposes. From cc2b565e2a01b4cc9668114905116100ff52c24b Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Fri, 5 Sep 2025 07:54:43 +0200 Subject: [PATCH 475/541] [main] Update dependencies from microsoft/testfx (#6521) Co-authored-by: dotnet-maestro[bot] --- eng/Version.Details.xml | 8 ++++---- eng/Versions.props | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index 36d0611901..6d70b71395 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -17,13 +17,13 @@ https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage 55eaeaf5a193df238f4437a9b2889da77056347d - + https://github.com/microsoft/testfx - 684f40affad7afc91e8a960cc64ebf12bc25a3d1 + 4efd6272d4157c64f4839bca5bbaa3c48007213c - + https://github.com/microsoft/testfx - 684f40affad7afc91e8a960cc64ebf12bc25a3d1 + 4efd6272d4157c64f4839bca5bbaa3c48007213c diff --git a/eng/Versions.props b/eng/Versions.props index dab221633e..5ad47e6b3b 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -10,7 +10,7 @@ 11.0.0-beta.25453.1 18.0.0-preview.25452.1 - 3.11.0-preview.25453.10 - 1.9.0-preview.25453.10 + 3.11.0-preview.25454.3 + 1.9.0-preview.25454.3 From 661b0515cdfdac2656ed9232e2ca086ead951435 Mon Sep 17 00:00:00 2001 From: dotnet bot Date: Thu, 4 Sep 2025 23:02:51 -0700 Subject: [PATCH 476/541] Localized file check-in by OneLocBuild Task: Build definition ID 1218: Build ID 2786796 --- src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf | 6 +++--- src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf | 6 +++--- src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf | 6 +++--- src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf | 6 +++--- src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf | 6 +++--- src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf | 6 +++--- 6 files changed, 18 insertions(+), 18 deletions(-) diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf index afb54134df..ec569abfd5 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.de.xlf @@ -525,17 +525,17 @@ Der Typ, der diese Methoden deklariert, sollte auch die folgenden Regeln beachte Methods like Contains, StartsWith, and EndsWith return boolean values that indicate whether the condition was met. Ignoring these return values is likely a mistake. - Methods like Contains, StartsWith, and EndsWith return boolean values that indicate whether the condition was met. Ignoring these return values is likely a mistake. + Methoden wie Contains, StartsWith und EndsWith geben boolesche Werte zurück, die angeben, ob die Bedingung erfüllt wurde. Das Ignorieren dieser Rückgabewerte ist wahrscheinlich ein Fehler. The return value of '{0}' should not be ignored - The return value of '{0}' should not be ignored + Der Rückgabewert von „{0}“ darf nicht ignoriert werden Do not ignore the return value of string methods - Do not ignore the return value of string methods + Rückgabewert von Zeichenfolgenmethoden nicht ignorieren diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf index 068f5ac31e..8509932845 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.es.xlf @@ -524,17 +524,17 @@ El tipo que declara estos métodos también debe respetar las reglas siguientes: Methods like Contains, StartsWith, and EndsWith return boolean values that indicate whether the condition was met. Ignoring these return values is likely a mistake. - Methods like Contains, StartsWith, and EndsWith return boolean values that indicate whether the condition was met. Ignoring these return values is likely a mistake. + Los métodos como Contains, StartsWith y EndsWith devuelven valores booleanos que indican si se cumplió la condición. Ignorar estos valores devueltos probablemente sea un error. The return value of '{0}' should not be ignored - The return value of '{0}' should not be ignored + No se debe ignorar el valor devuelto de '{0}' Do not ignore the return value of string methods - Do not ignore the return value of string methods + No ignore el valor devuelto de los métodos de cadena diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf index 3623788b03..3c029d6838 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.it.xlf @@ -524,17 +524,17 @@ Anche il tipo che dichiara questi metodi deve rispettare le regole seguenti: Methods like Contains, StartsWith, and EndsWith return boolean values that indicate whether the condition was met. Ignoring these return values is likely a mistake. - Methods like Contains, StartsWith, and EndsWith return boolean values that indicate whether the condition was met. Ignoring these return values is likely a mistake. + Metodi come Contains, StartsWith e EndsWith restituiscono valori booleani che indicano se la condizione è stata soddisfatta. Ignorare questi valori restituiti è probabilmente un errore. The return value of '{0}' should not be ignored - The return value of '{0}' should not be ignored + Il valore restituito di '{0}' non deve essere ignorato Do not ignore the return value of string methods - Do not ignore the return value of string methods + Non ignorare il valore restituito dei metodi stringa diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf index ed8349acf3..9ec21cbef5 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ru.xlf @@ -530,17 +530,17 @@ The type declaring these methods should also respect the following rules: Methods like Contains, StartsWith, and EndsWith return boolean values that indicate whether the condition was met. Ignoring these return values is likely a mistake. - Methods like Contains, StartsWith, and EndsWith return boolean values that indicate whether the condition was met. Ignoring these return values is likely a mistake. + Такие методы, как Contains, StartsWith и EndsWith, возвращают логические значения, указывающие, выполнено ли условие. Игнорирование этих возвращаемых значений, скорее всего, является ошибкой. The return value of '{0}' should not be ignored - The return value of '{0}' should not be ignored + Возвращаемое значение "{0}" не должно игнорироваться Do not ignore the return value of string methods - Do not ignore the return value of string methods + Не игнорируйте возвращаемое значение строковых методов diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf index a99c8212de..e30a584b2a 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.tr.xlf @@ -524,17 +524,17 @@ Bu metotları bildiren türün ayrıca aşağıdaki kurallara uyması gerekir: Methods like Contains, StartsWith, and EndsWith return boolean values that indicate whether the condition was met. Ignoring these return values is likely a mistake. - Methods like Contains, StartsWith, and EndsWith return boolean values that indicate whether the condition was met. Ignoring these return values is likely a mistake. + Contains, StartsWith ve EndsWith gibi yöntemler, koşulun karşılanıp karşılanmadığını belirten boole değerleri döndürür. Bu dönüş değerlerini yok saymak büyük olasılıkla bir hataya yol açar. The return value of '{0}' should not be ignored - The return value of '{0}' should not be ignored + '{0}' değerinin dönüş değeri yok sayılmamalıdır Do not ignore the return value of string methods - Do not ignore the return value of string methods + Dize yöntemlerinin dönüş değerini yok saymayın diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf index b9044763d8..3b1c94232d 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hant.xlf @@ -524,17 +524,17 @@ The type declaring these methods should also respect the following rules: Methods like Contains, StartsWith, and EndsWith return boolean values that indicate whether the condition was met. Ignoring these return values is likely a mistake. - Methods like Contains, StartsWith, and EndsWith return boolean values that indicate whether the condition was met. Ignoring these return values is likely a mistake. + Contains、StartsWith 和 EndsWith 等方法會傳回布林值,指出是否已符合條件。忽略這些傳回值可能導致錯誤。 The return value of '{0}' should not be ignored - The return value of '{0}' should not be ignored + 不應忽略傳回值 '{0}' Do not ignore the return value of string methods - Do not ignore the return value of string methods + 請勿忽略字串方法的傳回值 From e36936ba7d95b0f6bcdac9b5a3e6866c3fa0452d Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Fri, 5 Sep 2025 11:37:06 +0000 Subject: [PATCH 477/541] [main] Update dependencies from devdiv/DevDiv/vs-code-coverage, dotnet/arcade (#6520) Co-authored-by: dotnet-maestro[bot] Co-authored-by: Youssef Victor --- eng/Version.Details.xml | 16 ++++++++-------- eng/Versions.props | 4 ++-- global.json | 6 +++--- .../Deployment/TestRunDirectories.cs | 2 +- .../ObjectModel/TestMethod.cs | 4 ++-- .../Terminal/TerminalTestReporter.cs | 2 +- .../Attributes/TestMethod/RetryAttribute.cs | 2 +- 7 files changed, 18 insertions(+), 18 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index 6d70b71395..3567f60719 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -1,21 +1,21 @@ - + https://github.com/dotnet/arcade - f614a5074484f409b8dd60a98a2a9f7abf571970 + 6aa173793e862e03b509406b2a554a2d8bedaf34 - + https://github.com/dotnet/arcade - f614a5074484f409b8dd60a98a2a9f7abf571970 + 6aa173793e862e03b509406b2a554a2d8bedaf34 - + https://github.com/dotnet/arcade - f614a5074484f409b8dd60a98a2a9f7abf571970 + 6aa173793e862e03b509406b2a554a2d8bedaf34 - + https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage - 55eaeaf5a193df238f4437a9b2889da77056347d + e47e677c358805815914ac475d646c90fd28a1ec https://github.com/microsoft/testfx diff --git a/eng/Versions.props b/eng/Versions.props index 5ad47e6b3b..90b468a493 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -7,8 +7,8 @@ preview - 11.0.0-beta.25453.1 - 18.0.0-preview.25452.1 + 11.0.0-beta.25454.5 + 18.0.0-preview.25453.1 3.11.0-preview.25454.3 1.9.0-preview.25454.3 diff --git a/global.json b/global.json index 0c9e5cb2f3..517636cc61 100644 --- a/global.json +++ b/global.json @@ -1,6 +1,6 @@ { "tools": { - "dotnet": "10.0.100-rc.1.25411.109", + "dotnet": "10.0.100-rc.1.25420.111", "runtimes": { "dotnet": [ "3.1.32", @@ -23,7 +23,7 @@ } }, "sdk": { - "version": "10.0.100-rc.1.25411.109", + "version": "10.0.100-rc.1.25420.111", "paths": [ ".dotnet", "$host$" @@ -33,7 +33,7 @@ "rollForward": "latestFeature" }, "msbuild-sdks": { - "Microsoft.DotNet.Arcade.Sdk": "11.0.0-beta.25453.1", + "Microsoft.DotNet.Arcade.Sdk": "11.0.0-beta.25454.5", "MSBuild.Sdk.Extras": "3.0.44" } } diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Deployment/TestRunDirectories.cs b/src/Adapter/MSTestAdapter.PlatformServices/Deployment/TestRunDirectories.cs index c2c085bb46..03ebb19b0b 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Deployment/TestRunDirectories.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Deployment/TestRunDirectories.cs @@ -57,7 +57,7 @@ private void OnRootDeploymentDirectoryUpdated() /// public string RootDeploymentDirectory { - get => field; + get; // TODO: Remove the setter as a breaking change and simplify the code. [MemberNotNull(nameof(InDirectory), nameof(OutDirectory), nameof(InMachineNameDirectory))] set diff --git a/src/Adapter/MSTestAdapter.PlatformServices/ObjectModel/TestMethod.cs b/src/Adapter/MSTestAdapter.PlatformServices/ObjectModel/TestMethod.cs index 5ac8e29b26..a9c0f1e450 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/ObjectModel/TestMethod.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/ObjectModel/TestMethod.cs @@ -89,7 +89,7 @@ internal TestMethod(string? managedTypeName, string? managedMethodName, string?[ /// public string? DeclaringAssemblyName { - get => field; + get; set { @@ -106,7 +106,7 @@ public string? DeclaringAssemblyName /// public string? DeclaringClassFullName { - get => field; + get; set { diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporter.cs b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporter.cs index 5bc9f7daa7..c70b141823 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporter.cs +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporter.cs @@ -62,7 +62,7 @@ internal event EventHandler OnProgressStopUpdate private bool WasCancelled { get => field || _testApplicationCancellationTokenSource.CancellationToken.IsCancellationRequested; - set => field = value; + set; } private bool? _shouldShowPassedTests; diff --git a/src/TestFramework/TestFramework/Attributes/TestMethod/RetryAttribute.cs b/src/TestFramework/TestFramework/Attributes/TestMethod/RetryAttribute.cs index 811a7b0e37..ce0ef338d7 100644 --- a/src/TestFramework/TestFramework/Attributes/TestMethod/RetryAttribute.cs +++ b/src/TestFramework/TestFramework/Attributes/TestMethod/RetryAttribute.cs @@ -43,7 +43,7 @@ public RetryAttribute(int maxRetryAttempts) /// public DelayBackoffType BackoffType { - get => field; + get; set { if (value is < DelayBackoffType.Constant or > DelayBackoffType.Exponential) From b9267f346a3c7f51b5ce8f78a9e05a351af6bf08 Mon Sep 17 00:00:00 2001 From: dotnet bot Date: Fri, 5 Sep 2025 04:45:34 -0700 Subject: [PATCH 478/541] Localized file check-in by OneLocBuild Task: Build definition ID 1218: Build ID 2786952 --- src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf | 6 +++--- src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf | 6 +++--- src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf | 6 +++--- src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf | 6 +++--- src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf | 6 +++--- src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf | 6 +++--- src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf | 6 +++--- 7 files changed, 21 insertions(+), 21 deletions(-) diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf index e304d57594..e6328c19f1 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.cs.xlf @@ -524,17 +524,17 @@ Typ deklarující tyto metody by měl také respektovat následující pravidla: Methods like Contains, StartsWith, and EndsWith return boolean values that indicate whether the condition was met. Ignoring these return values is likely a mistake. - Methods like Contains, StartsWith, and EndsWith return boolean values that indicate whether the condition was met. Ignoring these return values is likely a mistake. + Metody jako Contains, StartsWith a EndsWith vracejí logické hodnoty, které označují, jestli byla podmínka splněna. Ignorování těchto vrácených hodnot je pravděpodobně chyba. The return value of '{0}' should not be ignored - The return value of '{0}' should not be ignored + Návratová hodnota {0} by neměla být ignorována Do not ignore the return value of string methods - Do not ignore the return value of string methods + Neignorovat návratovou hodnotu řetězcových metod diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf index 681bd20803..8a75b123d9 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.fr.xlf @@ -524,17 +524,17 @@ Le type déclarant ces méthodes doit également respecter les règles suivantes Methods like Contains, StartsWith, and EndsWith return boolean values that indicate whether the condition was met. Ignoring these return values is likely a mistake. - Methods like Contains, StartsWith, and EndsWith return boolean values that indicate whether the condition was met. Ignoring these return values is likely a mistake. + Les méthodes telles que Contains, StartsWith et EndsWith retournent des valeurs booléennes qui indiquent si la condition a été remplie. Ignorer ces valeurs de retour est certainement une erreur. The return value of '{0}' should not be ignored - The return value of '{0}' should not be ignored + La valeur de retour « {0} » ne doit pas être ignorée Do not ignore the return value of string methods - Do not ignore the return value of string methods + Ne négligez pas la valeur de retour des méthodes de chaîne diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf index c66487cf18..5d80076bd1 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ja.xlf @@ -524,17 +524,17 @@ The type declaring these methods should also respect the following rules: Methods like Contains, StartsWith, and EndsWith return boolean values that indicate whether the condition was met. Ignoring these return values is likely a mistake. - Methods like Contains, StartsWith, and EndsWith return boolean values that indicate whether the condition was met. Ignoring these return values is likely a mistake. + Contains、StartsWith、EndsWith などのメソッドは、条件が満たされたかどうかを示すブール値を返します。これらの戻り値を無視するのは間違いである可能性が高いです。 The return value of '{0}' should not be ignored - The return value of '{0}' should not be ignored + '{0}' の戻り値は無視しないでください Do not ignore the return value of string methods - Do not ignore the return value of string methods + 文字列メソッドの戻り値を無視しない diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf index 517aa1c614..0a46f0e065 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.ko.xlf @@ -524,17 +524,17 @@ The type declaring these methods should also respect the following rules: Methods like Contains, StartsWith, and EndsWith return boolean values that indicate whether the condition was met. Ignoring these return values is likely a mistake. - Methods like Contains, StartsWith, and EndsWith return boolean values that indicate whether the condition was met. Ignoring these return values is likely a mistake. + Contains, StartsWith 및 EndsWith와 같은 메서드는 조건이 충족되었는지 여부를 나타내는 부울 값을 반환합니다. 이 반환 값을 무시하는 것은 아마 실수일 것입니다. The return value of '{0}' should not be ignored - The return value of '{0}' should not be ignored + '{0}'의 반환 값은 무시하면 안 됩니다. Do not ignore the return value of string methods - Do not ignore the return value of string methods + 문자열 메서드의 반환 값을 무시하지 마세요. diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf index 0d243b12e1..436d3c6be8 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pl.xlf @@ -524,17 +524,17 @@ Typ deklarujący te metody powinien również przestrzegać następujących regu Methods like Contains, StartsWith, and EndsWith return boolean values that indicate whether the condition was met. Ignoring these return values is likely a mistake. - Methods like Contains, StartsWith, and EndsWith return boolean values that indicate whether the condition was met. Ignoring these return values is likely a mistake. + Metody takie jak Contains, StartsWith i EndsWith zwracają wartości logiczne wskazujące, czy warunek został spełniony. Ignorowanie tych wartości zwrotnych jest prawdopodobnie błędem. The return value of '{0}' should not be ignored - The return value of '{0}' should not be ignored + Zwracana wartość „{0}” nie powinna być ignorowana Do not ignore the return value of string methods - Do not ignore the return value of string methods + Nie ignoruj zwracanej wartości metod ciągu diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf index e56848fd43..232924c5a6 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.pt-BR.xlf @@ -524,17 +524,17 @@ O tipo que declara esses métodos também deve respeitar as seguintes regras: Methods like Contains, StartsWith, and EndsWith return boolean values that indicate whether the condition was met. Ignoring these return values is likely a mistake. - Methods like Contains, StartsWith, and EndsWith return boolean values that indicate whether the condition was met. Ignoring these return values is likely a mistake. + Métodos como Contains, StartsWith e EndsWith retornam valores boolianos que indicam se a condição foi atendida. Ignorar esses valores retornados provavelmente é um erro. The return value of '{0}' should not be ignored - The return value of '{0}' should not be ignored + O valor retornado de "{0}" não deve ser ignorado Do not ignore the return value of string methods - Do not ignore the return value of string methods + Não ignore o valor retornado dos métodos de cadeia de caracteres diff --git a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf index 8074f39d6c..329c91d36f 100644 --- a/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf +++ b/src/Analyzers/MSTest.Analyzers/xlf/Resources.zh-Hans.xlf @@ -524,17 +524,17 @@ The type declaring these methods should also respect the following rules: Methods like Contains, StartsWith, and EndsWith return boolean values that indicate whether the condition was met. Ignoring these return values is likely a mistake. - Methods like Contains, StartsWith, and EndsWith return boolean values that indicate whether the condition was met. Ignoring these return values is likely a mistake. + Contains、StartsWith 和 EndsWith 等方法会返回指示是否满足条件的布尔值。忽略这些返回值可能是一个错误。 The return value of '{0}' should not be ignored - The return value of '{0}' should not be ignored + 不应忽略 ‘{0}’ 的返回值 Do not ignore the return value of string methods - Do not ignore the return value of string methods + 不要忽略字符串方法的返回值 From 3897e0b338d9327020a03b66246c073cb9b0bf3f Mon Sep 17 00:00:00 2001 From: dotnet bot Date: Fri, 5 Sep 2025 04:50:09 -0700 Subject: [PATCH 479/541] Localized file check-in by OneLocBuild Task: Build definition ID 1218: Build ID 2786952 --- .../Resources/xlf/PlatformResources.cs.xlf | 2 +- .../Resources/xlf/PlatformResources.de.xlf | 2 +- .../Resources/xlf/PlatformResources.es.xlf | 2 +- .../Resources/xlf/PlatformResources.fr.xlf | 2 +- .../Resources/xlf/PlatformResources.it.xlf | 2 +- .../Resources/xlf/PlatformResources.ja.xlf | 2 +- .../Resources/xlf/PlatformResources.ko.xlf | 2 +- .../Resources/xlf/PlatformResources.pl.xlf | 2 +- .../Resources/xlf/PlatformResources.pt-BR.xlf | 2 +- .../Resources/xlf/PlatformResources.ru.xlf | 2 +- .../Resources/xlf/PlatformResources.tr.xlf | 2 +- .../Resources/xlf/PlatformResources.zh-Hans.xlf | 2 +- .../Resources/xlf/PlatformResources.zh-Hant.xlf | 2 +- 13 files changed, 13 insertions(+), 13 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.cs.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.cs.xlf index d7788c81b0..774a24e2b1 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.cs.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.cs.xlf @@ -468,7 +468,7 @@ Allows to pause execution in order to attach to the process for debug purposes. - Allows to pause execution in order to attach to the process for debug purposes. + Umožňuje pozastavit provádění, aby se mohlo připojit k procesu pro účely ladění. diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.de.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.de.xlf index a739f627ef..97ae7e4f03 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.de.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.de.xlf @@ -468,7 +468,7 @@ Allows to pause execution in order to attach to the process for debug purposes. - Allows to pause execution in order to attach to the process for debug purposes. + Ermöglicht das Anhalten der Ausführung zum Anfügen an den Prozess zum Debuggen. diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.es.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.es.xlf index 5d78b736ff..d1a6c71998 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.es.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.es.xlf @@ -468,7 +468,7 @@ Allows to pause execution in order to attach to the process for debug purposes. - Allows to pause execution in order to attach to the process for debug purposes. + Permite pausar la ejecución para asociarla al proceso con fines de depuración. diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.fr.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.fr.xlf index 5460814520..39b10aa4e2 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.fr.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.fr.xlf @@ -468,7 +468,7 @@ Allows to pause execution in order to attach to the process for debug purposes. - Allows to pause execution in order to attach to the process for debug purposes. + Permet de suspendre l’exécution afin de s’attacher au processus à des fins de débogage. diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.it.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.it.xlf index f810f98b81..fe36f4c234 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.it.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.it.xlf @@ -468,7 +468,7 @@ Allows to pause execution in order to attach to the process for debug purposes. - Allows to pause execution in order to attach to the process for debug purposes. + Consente di sospendere l'esecuzione per connettersi al processo a scopo di debug. diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ja.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ja.xlf index e08f96a303..4a0d6dbfaa 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ja.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ja.xlf @@ -468,7 +468,7 @@ Allows to pause execution in order to attach to the process for debug purposes. - Allows to pause execution in order to attach to the process for debug purposes. + デバッグ目的でプロセスにアタッチするために、実行を一時停止することができます。 diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ko.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ko.xlf index 3b7c2d118a..dfce73d2e4 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ko.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ko.xlf @@ -468,7 +468,7 @@ Allows to pause execution in order to attach to the process for debug purposes. - Allows to pause execution in order to attach to the process for debug purposes. + 디버그 목적으로 프로세스에 연결하기 위해 실행을 일시 중지할 수 있습니다. diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pl.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pl.xlf index b22b0c5fad..36aa4297ba 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pl.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pl.xlf @@ -468,7 +468,7 @@ Allows to pause execution in order to attach to the process for debug purposes. - Allows to pause execution in order to attach to the process for debug purposes. + Umożliwia wstrzymanie wykonywania w celu dołączenia do procesu na potrzeby debugowania. diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pt-BR.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pt-BR.xlf index 25cef70f6d..3927d947cf 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pt-BR.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pt-BR.xlf @@ -468,7 +468,7 @@ Allows to pause execution in order to attach to the process for debug purposes. - Allows to pause execution in order to attach to the process for debug purposes. + Permite pausar a execução a fim de anexar ao processo para fins de depuração. diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ru.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ru.xlf index 0c59bd9def..29c8f07c1a 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ru.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ru.xlf @@ -468,7 +468,7 @@ Allows to pause execution in order to attach to the process for debug purposes. - Allows to pause execution in order to attach to the process for debug purposes. + Позволяет приостановить выполнение, чтобы подключиться к процессу для отладки. diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.tr.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.tr.xlf index 0837ca3b32..618e7b4c8f 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.tr.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.tr.xlf @@ -468,7 +468,7 @@ Allows to pause execution in order to attach to the process for debug purposes. - Allows to pause execution in order to attach to the process for debug purposes. + Hata ayıklama amacıyla işleme eklemek için yürütmeyi duraklatmayı sağlar. diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hans.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hans.xlf index 4f4cf7fd1f..17a1097a91 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hans.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hans.xlf @@ -468,7 +468,7 @@ Allows to pause execution in order to attach to the process for debug purposes. - Allows to pause execution in order to attach to the process for debug purposes. + 允许暂停执行,以便附加到进程以进行调试。 diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hant.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hant.xlf index 55cb5acaab..7a913b5b2c 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hant.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hant.xlf @@ -468,7 +468,7 @@ Allows to pause execution in order to attach to the process for debug purposes. - Allows to pause execution in order to attach to the process for debug purposes. + 允許暫停執行,以便附加至處理常式以供偵錯之用。 From c61781cbee0d3ccd451f144e398e68751abd31cd Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Sat, 6 Sep 2025 09:29:46 +0200 Subject: [PATCH 480/541] [main] Update dependencies from dotnet/arcade (#6528) Co-authored-by: dotnet-maestro[bot] --- eng/Version.Details.xml | 12 ++++++------ eng/Versions.props | 2 +- global.json | 2 +- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index 3567f60719..38129d3446 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -1,17 +1,17 @@ - + https://github.com/dotnet/arcade - 6aa173793e862e03b509406b2a554a2d8bedaf34 + 0a31c47ca9260204693307c442ff13e3f4d2aeb5 - + https://github.com/dotnet/arcade - 6aa173793e862e03b509406b2a554a2d8bedaf34 + 0a31c47ca9260204693307c442ff13e3f4d2aeb5 - + https://github.com/dotnet/arcade - 6aa173793e862e03b509406b2a554a2d8bedaf34 + 0a31c47ca9260204693307c442ff13e3f4d2aeb5 https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage diff --git a/eng/Versions.props b/eng/Versions.props index 90b468a493..0da33b2737 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -7,7 +7,7 @@ preview - 11.0.0-beta.25454.5 + 11.0.0-beta.25455.5 18.0.0-preview.25453.1 3.11.0-preview.25454.3 diff --git a/global.json b/global.json index 517636cc61..2b6f0cb995 100644 --- a/global.json +++ b/global.json @@ -33,7 +33,7 @@ "rollForward": "latestFeature" }, "msbuild-sdks": { - "Microsoft.DotNet.Arcade.Sdk": "11.0.0-beta.25454.5", + "Microsoft.DotNet.Arcade.Sdk": "11.0.0-beta.25455.5", "MSBuild.Sdk.Extras": "3.0.44" } } From db43d4e2dedc776e37717853805b0fce30b1ccff Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Sun, 7 Sep 2025 22:15:52 +0200 Subject: [PATCH 481/541] Rename ReadShort and WriteShort to ReadUShort and WriteUShort (#6530) --- .../IPC/Serializers/BaseSerializer.cs | 18 +++++------ .../CommandLineOptionMessagesSerializer.cs | 14 ++++----- .../DiscoveredTestMessagesSerializer.cs | 22 +++++++------- .../FileArtifactMessagesSerializer.cs | 14 ++++----- .../Serializers/HandshakeMessageSerializer.cs | 4 +-- .../TestResultMessagesSerializer.cs | 30 +++++++++---------- .../Serializers/TestSessionEventSerializer.cs | 6 ++-- 7 files changed, 54 insertions(+), 54 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Platform/IPC/Serializers/BaseSerializer.cs b/src/Platform/Microsoft.Testing.Platform/IPC/Serializers/BaseSerializer.cs index 7625d3a39e..4089c4cc84 100644 --- a/src/Platform/Microsoft.Testing.Platform/IPC/Serializers/BaseSerializer.cs +++ b/src/Platform/Microsoft.Testing.Platform/IPC/Serializers/BaseSerializer.cs @@ -117,7 +117,7 @@ protected static void WriteLong(Stream stream, long value) stream.Write(bytes); } - protected static void WriteShort(Stream stream, ushort value) + protected static void WriteUShort(Stream stream, ushort value) { Span bytes = stackalloc byte[sizeof(ushort)]; ApplicationStateGuard.Ensure(BitConverter.TryWriteBytes(bytes, value), PlatformResources.UnexpectedExceptionDuringByteConversionErrorMessage); @@ -147,7 +147,7 @@ protected static long ReadLong(Stream stream) return BitConverter.ToInt64(bytes); } - protected static ushort ReadShort(Stream stream) + protected static ushort ReadUShort(Stream stream) { Span bytes = stackalloc byte[sizeof(ushort)]; stream.ReadExactly(bytes); @@ -229,7 +229,7 @@ protected static void WriteLong(Stream stream, long value) stream.Write(bytes, 0, bytes.Length); } - protected static void WriteShort(Stream stream, ushort value) + protected static void WriteUShort(Stream stream, ushort value) { byte[] bytes = BitConverter.GetBytes(value); stream.Write(bytes, 0, bytes.Length); @@ -242,7 +242,7 @@ protected static long ReadLong(Stream stream) return BitConverter.ToInt64(bytes, 0); } - protected static ushort ReadShort(Stream stream) + protected static ushort ReadUShort(Stream stream) { byte[] bytes = new byte[sizeof(ushort)]; _ = stream.Read(bytes, 0, bytes.Length); @@ -274,7 +274,7 @@ protected static void WriteField(Stream stream, ushort id, string? value) return; } - WriteShort(stream, id); + WriteUShort(stream, id); WriteStringSize(stream, value); WriteStringValue(stream, value); } @@ -286,7 +286,7 @@ protected static void WriteField(Stream stream, ushort id, long? value) return; } - WriteShort(stream, id); + WriteUShort(stream, id); WriteSize(stream); WriteLong(stream, value.Value); } @@ -298,7 +298,7 @@ protected static void WriteField(Stream stream, ushort id, int? value) return; } - WriteShort(stream, id); + WriteUShort(stream, id); WriteSize(stream); WriteInt(stream, value.Value); } @@ -330,7 +330,7 @@ protected static void WriteField(Stream stream, ushort id, bool? value) return; } - WriteShort(stream, id); + WriteUShort(stream, id); WriteSize(stream); WriteBool(stream, value.Value); } @@ -342,7 +342,7 @@ protected static void WriteField(Stream stream, ushort id, byte? value) return; } - WriteShort(stream, id); + WriteUShort(stream, id); WriteSize(stream); WriteByte(stream, value.Value); } diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Serializers/CommandLineOptionMessagesSerializer.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Serializers/CommandLineOptionMessagesSerializer.cs index a96255e664..0e75677bd1 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Serializers/CommandLineOptionMessagesSerializer.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Serializers/CommandLineOptionMessagesSerializer.cs @@ -45,11 +45,11 @@ public object Deserialize(Stream stream) string? moduleName = null; List? commandLineOptionMessages = null; - ushort fieldCount = ReadShort(stream); + ushort fieldCount = ReadUShort(stream); for (int i = 0; i < fieldCount; i++) { - int fieldId = ReadShort(stream); + int fieldId = ReadUShort(stream); int fieldSize = ReadInt(stream); switch (fieldId) @@ -82,11 +82,11 @@ private static List ReadCommandLineOptionMessagesPaylo string? name = null, description = null; bool? isHidden = null, isBuiltIn = null; - int fieldCount = ReadShort(stream); + int fieldCount = ReadUShort(stream); for (int j = 0; j < fieldCount; j++) { - int fieldId = ReadShort(stream); + int fieldId = ReadUShort(stream); int fieldSize = ReadInt(stream); switch (fieldId) @@ -125,7 +125,7 @@ public void Serialize(object objectToSerialize, Stream stream) var commandLineOptionMessages = (CommandLineOptionMessages)objectToSerialize; - WriteShort(stream, GetFieldCount(commandLineOptionMessages)); + WriteUShort(stream, GetFieldCount(commandLineOptionMessages)); WriteField(stream, CommandLineOptionMessagesFieldsId.ModulePath, commandLineOptionMessages.ModulePath); WriteCommandLineOptionMessagesPayload(stream, commandLineOptionMessages.CommandLineOptionMessageList); @@ -138,7 +138,7 @@ private static void WriteCommandLineOptionMessagesPayload(Stream stream, Command return; } - WriteShort(stream, CommandLineOptionMessagesFieldsId.CommandLineOptionMessageList); + WriteUShort(stream, CommandLineOptionMessagesFieldsId.CommandLineOptionMessageList); // We will reserve an int (4 bytes) // so that we fill the size later, once we write the payload @@ -148,7 +148,7 @@ private static void WriteCommandLineOptionMessagesPayload(Stream stream, Command WriteInt(stream, commandLineOptionMessageList.Length); foreach (CommandLineOptionMessage commandLineOptionMessage in commandLineOptionMessageList) { - WriteShort(stream, GetFieldCount(commandLineOptionMessage)); + WriteUShort(stream, GetFieldCount(commandLineOptionMessage)); WriteField(stream, CommandLineOptionMessageFieldsId.Name, commandLineOptionMessage.Name); WriteField(stream, CommandLineOptionMessageFieldsId.Description, commandLineOptionMessage.Description); diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Serializers/DiscoveredTestMessagesSerializer.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Serializers/DiscoveredTestMessagesSerializer.cs index 67c35e5417..ff8482ff6c 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Serializers/DiscoveredTestMessagesSerializer.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Serializers/DiscoveredTestMessagesSerializer.cs @@ -78,11 +78,11 @@ public object Deserialize(Stream stream) string? instanceId = null; DiscoveredTestMessage[]? discoveredTestMessages = []; - ushort fieldCount = ReadShort(stream); + ushort fieldCount = ReadUShort(stream); for (int i = 0; i < fieldCount; i++) { - int fieldId = ReadShort(stream); + int fieldId = ReadUShort(stream); int fieldSize = ReadInt(stream); switch (fieldId) @@ -124,11 +124,11 @@ private static DiscoveredTestMessage[] ReadDiscoveredTestMessagesPayload(Stream string? methodName = null; TestMetadataProperty[] traits = []; - int fieldCount = ReadShort(stream); + int fieldCount = ReadUShort(stream); for (int j = 0; j < fieldCount; j++) { - int fieldId = ReadShort(stream); + int fieldId = ReadUShort(stream); int fieldSize = ReadInt(stream); switch (fieldId) @@ -185,11 +185,11 @@ private static TestMetadataProperty[] ReadTraitsPayload(Stream stream) { string? key = null; string? value = null; - int fieldCount = ReadShort(stream); + int fieldCount = ReadUShort(stream); for (int j = 0; j < fieldCount; j++) { - int fieldId = ReadShort(stream); + int fieldId = ReadUShort(stream); int fieldSize = ReadInt(stream); switch (fieldId) @@ -222,7 +222,7 @@ public void Serialize(object objectToSerialize, Stream stream) var discoveredTestMessages = (DiscoveredTestMessages)objectToSerialize; - WriteShort(stream, GetFieldCount(discoveredTestMessages)); + WriteUShort(stream, GetFieldCount(discoveredTestMessages)); WriteField(stream, DiscoveredTestMessagesFieldsId.ExecutionId, discoveredTestMessages.ExecutionId); WriteField(stream, DiscoveredTestMessagesFieldsId.InstanceId, discoveredTestMessages.InstanceId); @@ -236,7 +236,7 @@ private static void WriteDiscoveredTestMessagesPayload(Stream stream, Discovered return; } - WriteShort(stream, DiscoveredTestMessagesFieldsId.DiscoveredTestMessageList); + WriteUShort(stream, DiscoveredTestMessagesFieldsId.DiscoveredTestMessageList); // We will reserve an int (4 bytes) // so that we fill the size later, once we write the payload @@ -246,7 +246,7 @@ private static void WriteDiscoveredTestMessagesPayload(Stream stream, Discovered WriteInt(stream, discoveredTestMessageList.Length); foreach (DiscoveredTestMessage discoveredTestMessage in discoveredTestMessageList) { - WriteShort(stream, GetFieldCount(discoveredTestMessage)); + WriteUShort(stream, GetFieldCount(discoveredTestMessage)); WriteField(stream, DiscoveredTestMessageFieldsId.Uid, discoveredTestMessage.Uid); WriteField(stream, DiscoveredTestMessageFieldsId.DisplayName, discoveredTestMessage.DisplayName); @@ -271,7 +271,7 @@ private static void WriteTraitsPayload(Stream stream, TestMetadataProperty[]? tr return; } - WriteShort(stream, DiscoveredTestMessageFieldsId.Traits); + WriteUShort(stream, DiscoveredTestMessageFieldsId.Traits); // We will reserve an int (4 bytes) // so that we fill the size later, once we write the payload @@ -281,7 +281,7 @@ private static void WriteTraitsPayload(Stream stream, TestMetadataProperty[]? tr WriteInt(stream, traits.Length); foreach (TestMetadataProperty trait in traits) { - WriteShort(stream, GetFieldCount(trait)); + WriteUShort(stream, GetFieldCount(trait)); WriteField(stream, TraitMessageFieldsId.Key, trait.Key); WriteField(stream, TraitMessageFieldsId.Value, trait.Value); diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Serializers/FileArtifactMessagesSerializer.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Serializers/FileArtifactMessagesSerializer.cs index 203b295ef8..614fe806bc 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Serializers/FileArtifactMessagesSerializer.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Serializers/FileArtifactMessagesSerializer.cs @@ -58,11 +58,11 @@ public object Deserialize(Stream stream) string? instanceId = null; List? fileArtifactMessages = null; - ushort fieldCount = ReadShort(stream); + ushort fieldCount = ReadUShort(stream); for (int i = 0; i < fieldCount; i++) { - int fieldId = ReadShort(stream); + int fieldId = ReadUShort(stream); int fieldSize = ReadInt(stream); switch (fieldId) @@ -98,11 +98,11 @@ private static List ReadFileArtifactMessagesPayload(Stream { string? fullPath = null, displayName = null, description = null, testUid = null, testDisplayName = null, sessionUid = null; - int fieldCount = ReadShort(stream); + int fieldCount = ReadUShort(stream); for (int j = 0; j < fieldCount; j++) { - int fieldId = ReadShort(stream); + int fieldId = ReadUShort(stream); int fieldSize = ReadInt(stream); switch (fieldId) @@ -149,7 +149,7 @@ public void Serialize(object objectToSerialize, Stream stream) var fileArtifactMessages = (FileArtifactMessages)objectToSerialize; - WriteShort(stream, GetFieldCount(fileArtifactMessages)); + WriteUShort(stream, GetFieldCount(fileArtifactMessages)); WriteField(stream, FileArtifactMessagesFieldsId.ExecutionId, fileArtifactMessages.ExecutionId); WriteField(stream, FileArtifactMessagesFieldsId.InstanceId, fileArtifactMessages.InstanceId); @@ -163,7 +163,7 @@ private static void WriteFileArtifactMessagesPayload(Stream stream, FileArtifact return; } - WriteShort(stream, FileArtifactMessagesFieldsId.FileArtifactMessageList); + WriteUShort(stream, FileArtifactMessagesFieldsId.FileArtifactMessageList); // We will reserve an int (4 bytes) // so that we fill the size later, once we write the payload @@ -173,7 +173,7 @@ private static void WriteFileArtifactMessagesPayload(Stream stream, FileArtifact WriteInt(stream, fileArtifactMessageList.Length); foreach (FileArtifactMessage fileArtifactMessage in fileArtifactMessageList) { - WriteShort(stream, GetFieldCount(fileArtifactMessage)); + WriteUShort(stream, GetFieldCount(fileArtifactMessage)); WriteField(stream, FileArtifactMessageFieldsId.FullPath, fileArtifactMessage.FullPath); WriteField(stream, FileArtifactMessageFieldsId.DisplayName, fileArtifactMessage.DisplayName); diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Serializers/HandshakeMessageSerializer.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Serializers/HandshakeMessageSerializer.cs index 9571f8f7a4..403337e701 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Serializers/HandshakeMessageSerializer.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Serializers/HandshakeMessageSerializer.cs @@ -13,7 +13,7 @@ public object Deserialize(Stream stream) { Dictionary properties = []; - ushort fieldCount = ReadShort(stream); + ushort fieldCount = ReadUShort(stream); for (int i = 0; i < fieldCount; i++) { @@ -34,7 +34,7 @@ public void Serialize(object objectToSerialize, Stream stream) return; } - WriteShort(stream, (ushort)handshakeMessage.Properties.Count); + WriteUShort(stream, (ushort)handshakeMessage.Properties.Count); foreach ((byte key, string value) in handshakeMessage.Properties) { WriteField(stream, key); diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Serializers/TestResultMessagesSerializer.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Serializers/TestResultMessagesSerializer.cs index 3bc7cc8965..6535d43e12 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Serializers/TestResultMessagesSerializer.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Serializers/TestResultMessagesSerializer.cs @@ -114,11 +114,11 @@ public object Deserialize(Stream stream) List? successfulTestResultMessages = null; List? failedTestResultMessages = null; - ushort fieldCount = ReadShort(stream); + ushort fieldCount = ReadUShort(stream); for (int i = 0; i < fieldCount; i++) { - int fieldId = ReadShort(stream); + int fieldId = ReadUShort(stream); int fieldSize = ReadInt(stream); switch (fieldId) @@ -164,11 +164,11 @@ private static List ReadSuccessfulTestMessagesPaylo byte? state = null; long? duration = null; - int fieldCount = ReadShort(stream); + int fieldCount = ReadUShort(stream); for (int j = 0; j < fieldCount; j++) { - int fieldId = ReadShort(stream); + int fieldId = ReadUShort(stream); int fieldSize = ReadInt(stream); switch (fieldId) @@ -229,11 +229,11 @@ private static List ReadFailedTestMessagesPayload(Strea byte? state = null; long? duration = null; - int fieldCount = ReadShort(stream); + int fieldCount = ReadUShort(stream); for (int j = 0; j < fieldCount; j++) { - int fieldId = ReadShort(stream); + int fieldId = ReadUShort(stream); int fieldSize = ReadInt(stream); switch (fieldId) @@ -293,7 +293,7 @@ private static ExceptionMessage[] ReadExceptionMessagesPayload(Stream stream) int length = ReadInt(stream); for (int i = 0; i < length; i++) { - int fieldCount = ReadShort(stream); + int fieldCount = ReadUShort(stream); string? errorMessage = null; string? errorType = null; @@ -301,7 +301,7 @@ private static ExceptionMessage[] ReadExceptionMessagesPayload(Stream stream) for (int j = 0; j < fieldCount; j++) { - int fieldId = ReadShort(stream); + int fieldId = ReadUShort(stream); int fieldSize = ReadInt(stream); switch (fieldId) @@ -332,7 +332,7 @@ public void Serialize(object objectToSerialize, Stream stream) var testResultMessages = (TestResultMessages)objectToSerialize; - WriteShort(stream, GetFieldCount(testResultMessages)); + WriteUShort(stream, GetFieldCount(testResultMessages)); WriteField(stream, TestResultMessagesFieldsId.ExecutionId, testResultMessages.ExecutionId); WriteField(stream, TestResultMessagesFieldsId.InstanceId, testResultMessages.InstanceId); @@ -347,7 +347,7 @@ private static void WriteSuccessfulTestMessagesPayload(Stream stream, Successful return; } - WriteShort(stream, TestResultMessagesFieldsId.SuccessfulTestMessageList); + WriteUShort(stream, TestResultMessagesFieldsId.SuccessfulTestMessageList); // We will reserve an int (4 bytes) // so that we fill the size later, once we write the payload @@ -357,7 +357,7 @@ private static void WriteSuccessfulTestMessagesPayload(Stream stream, Successful WriteInt(stream, successfulTestResultMessages.Length); foreach (SuccessfulTestResultMessage successfulTestResultMessage in successfulTestResultMessages) { - WriteShort(stream, GetFieldCount(successfulTestResultMessage)); + WriteUShort(stream, GetFieldCount(successfulTestResultMessage)); WriteField(stream, SuccessfulTestResultMessageFieldsId.Uid, successfulTestResultMessage.Uid); WriteField(stream, SuccessfulTestResultMessageFieldsId.DisplayName, successfulTestResultMessage.DisplayName); @@ -381,7 +381,7 @@ private static void WriteFailedTestMessagesPayload(Stream stream, FailedTestResu return; } - WriteShort(stream, TestResultMessagesFieldsId.FailedTestMessageList); + WriteUShort(stream, TestResultMessagesFieldsId.FailedTestMessageList); // We will reserve an int (4 bytes) // so that we fill the size later, once we write the payload @@ -391,7 +391,7 @@ private static void WriteFailedTestMessagesPayload(Stream stream, FailedTestResu WriteInt(stream, failedTestResultMessages.Length); foreach (FailedTestResultMessage failedTestResultMessage in failedTestResultMessages) { - WriteShort(stream, GetFieldCount(failedTestResultMessage)); + WriteUShort(stream, GetFieldCount(failedTestResultMessage)); WriteField(stream, FailedTestResultMessageFieldsId.Uid, failedTestResultMessage.Uid); WriteField(stream, FailedTestResultMessageFieldsId.DisplayName, failedTestResultMessage.DisplayName); @@ -416,7 +416,7 @@ private static void WriteExceptionMessagesPayload(Stream stream, ExceptionMessag return; } - WriteShort(stream, FailedTestResultMessageFieldsId.ExceptionMessageList); + WriteUShort(stream, FailedTestResultMessageFieldsId.ExceptionMessageList); // We will reserve an int (4 bytes) // so that we fill the size later, once we write the payload @@ -426,7 +426,7 @@ private static void WriteExceptionMessagesPayload(Stream stream, ExceptionMessag WriteInt(stream, exceptionMessages.Length); foreach (ExceptionMessage exceptionMessage in exceptionMessages) { - WriteShort(stream, GetFieldCount(exceptionMessage)); + WriteUShort(stream, GetFieldCount(exceptionMessage)); WriteField(stream, ExceptionMessageFieldsId.ErrorMessage, exceptionMessage.ErrorMessage); WriteField(stream, ExceptionMessageFieldsId.ErrorType, exceptionMessage.ErrorType); diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Serializers/TestSessionEventSerializer.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Serializers/TestSessionEventSerializer.cs index 2c5afdefa1..0862b3f69f 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Serializers/TestSessionEventSerializer.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Serializers/TestSessionEventSerializer.cs @@ -31,11 +31,11 @@ public object Deserialize(Stream stream) string? sessionUid = null; string? executionId = null; - ushort fieldCount = ReadShort(stream); + ushort fieldCount = ReadUShort(stream); for (int i = 0; i < fieldCount; i++) { - ushort fieldId = ReadShort(stream); + ushort fieldId = ReadUShort(stream); int fieldSize = ReadInt(stream); switch (fieldId) @@ -68,7 +68,7 @@ public void Serialize(object objectToSerialize, Stream stream) var testSessionEvent = (TestSessionEvent)objectToSerialize; - WriteShort(stream, GetFieldCount(testSessionEvent)); + WriteUShort(stream, GetFieldCount(testSessionEvent)); WriteField(stream, TestSessionEventFieldsId.SessionType, testSessionEvent.SessionType); WriteField(stream, TestSessionEventFieldsId.SessionUid, testSessionEvent.SessionUid); From 2f8232d10acd32201d7b8f8fc5383f0e2e5e2cde Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Mon, 8 Sep 2025 07:38:02 +0200 Subject: [PATCH 482/541] [main] Update dependencies from dotnet/arcade (#6534) Co-authored-by: dotnet-maestro[bot] --- eng/Version.Details.xml | 12 ++++++------ eng/Versions.props | 2 +- global.json | 2 +- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index 38129d3446..fb7cbbcf90 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -1,17 +1,17 @@ - + https://github.com/dotnet/arcade - 0a31c47ca9260204693307c442ff13e3f4d2aeb5 + d7585e79b1397fe8783ac30c81bf5be4d250bcb1 - + https://github.com/dotnet/arcade - 0a31c47ca9260204693307c442ff13e3f4d2aeb5 + d7585e79b1397fe8783ac30c81bf5be4d250bcb1 - + https://github.com/dotnet/arcade - 0a31c47ca9260204693307c442ff13e3f4d2aeb5 + d7585e79b1397fe8783ac30c81bf5be4d250bcb1 https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage diff --git a/eng/Versions.props b/eng/Versions.props index 0da33b2737..827991981d 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -7,7 +7,7 @@ preview - 11.0.0-beta.25455.5 + 11.0.0-beta.25457.1 18.0.0-preview.25453.1 3.11.0-preview.25454.3 diff --git a/global.json b/global.json index 2b6f0cb995..77065596cc 100644 --- a/global.json +++ b/global.json @@ -33,7 +33,7 @@ "rollForward": "latestFeature" }, "msbuild-sdks": { - "Microsoft.DotNet.Arcade.Sdk": "11.0.0-beta.25455.5", + "Microsoft.DotNet.Arcade.Sdk": "11.0.0-beta.25457.1", "MSBuild.Sdk.Extras": "3.0.44" } } From 534a33a00a02234f9d9930c0fd149c904ae39f0c Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Mon, 8 Sep 2025 07:38:33 +0200 Subject: [PATCH 483/541] [main] Update dependencies from microsoft/testfx (#6533) Co-authored-by: dotnet-maestro[bot] --- eng/Version.Details.xml | 8 ++++---- eng/Versions.props | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index fb7cbbcf90..d8e2ebad62 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -17,13 +17,13 @@ https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage e47e677c358805815914ac475d646c90fd28a1ec - + https://github.com/microsoft/testfx - 4efd6272d4157c64f4839bca5bbaa3c48007213c + db43d4e2dedc776e37717853805b0fce30b1ccff - + https://github.com/microsoft/testfx - 4efd6272d4157c64f4839bca5bbaa3c48007213c + db43d4e2dedc776e37717853805b0fce30b1ccff diff --git a/eng/Versions.props b/eng/Versions.props index 827991981d..f0369eab1d 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -10,7 +10,7 @@ 11.0.0-beta.25457.1 18.0.0-preview.25453.1 - 3.11.0-preview.25454.3 - 1.9.0-preview.25454.3 + 3.11.0-preview.25457.1 + 1.9.0-preview.25457.1 From eb3da3b20623d0efb33d865abe9701f0229a725c Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Mon, 8 Sep 2025 09:45:27 +0200 Subject: [PATCH 484/541] Fix handshake serialization if properties dictionary is null or empty (#6532) --- .../Serializers/HandshakeMessageSerializer.cs | 7 +- .../IPC/ProtocolTests.cs | 64 +++++++++++++++++++ 2 files changed, 69 insertions(+), 2 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Serializers/HandshakeMessageSerializer.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Serializers/HandshakeMessageSerializer.cs index 403337e701..554ae3b12d 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Serializers/HandshakeMessageSerializer.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Serializers/HandshakeMessageSerializer.cs @@ -29,12 +29,15 @@ public void Serialize(object objectToSerialize, Stream stream) var handshakeMessage = (HandshakeMessage)objectToSerialize; - if (handshakeMessage.Properties is null || handshakeMessage.Properties.Count == 0) + // Deserializer always expected fieldCount to be present. + // We must write the count even if Properties is null or empty. + WriteUShort(stream, (ushort)(handshakeMessage.Properties?.Count ?? 0)); + + if (handshakeMessage.Properties is null) { return; } - WriteUShort(stream, (ushort)handshakeMessage.Properties.Count); foreach ((byte key, string value) in handshakeMessage.Properties) { WriteField(stream, key); diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/ProtocolTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/ProtocolTests.cs index 4343493322..192f43b6d7 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/ProtocolTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/ProtocolTests.cs @@ -69,4 +69,68 @@ public void DiscoveredTestMessagesSerializeDeserialize() } } } + + [TestMethod] + public void HandshakeMessageWithProperties() + { + var message = new HandshakeMessage(new Dictionary + { + { 10, "Ten" }, + { 35, "ThirtyFive" }, + { 48, "FortyEight" }, + }); + + var stream = new MemoryStream(); + new HandshakeMessageSerializer().Serialize(message, stream); + stream.Seek(0, SeekOrigin.Begin); + var actual = (HandshakeMessage)new HandshakeMessageSerializer().Deserialize(stream); + + Assert.IsNotNull(actual.Properties); + Assert.IsNotNull(message.Properties); + + Assert.HasCount(3, actual.Properties); + Assert.HasCount(3, message.Properties); + + Assert.AreEqual("Ten", actual.Properties[10]); + Assert.AreEqual("Ten", message.Properties[10]); + + Assert.AreEqual("ThirtyFive", actual.Properties[35]); + Assert.AreEqual("ThirtyFive", message.Properties[35]); + + Assert.AreEqual("FortyEight", actual.Properties[48]); + Assert.AreEqual("FortyEight", message.Properties[48]); + } + + [TestMethod] + public void HandshakeMessageWithEmptyProperties() + { + var message = new HandshakeMessage([]); + + var stream = new MemoryStream(); + new HandshakeMessageSerializer().Serialize(message, stream); + stream.Seek(0, SeekOrigin.Begin); + var actual = (HandshakeMessage)new HandshakeMessageSerializer().Deserialize(stream); + + Assert.IsNotNull(actual.Properties); + Assert.IsNotNull(message.Properties); + + Assert.IsEmpty(actual.Properties); + Assert.IsEmpty(message.Properties); + } + + [TestMethod] + public void HandshakeMessageWithNullProperties() + { + var message = new HandshakeMessage(null); + + var stream = new MemoryStream(); + new HandshakeMessageSerializer().Serialize(message, stream); + stream.Seek(0, SeekOrigin.Begin); + var actual = (HandshakeMessage)new HandshakeMessageSerializer().Deserialize(stream); + + Assert.IsNotNull(actual.Properties); + Assert.IsNull(message.Properties); + + Assert.IsEmpty(actual.Properties); + } } From 5ced872f97f0e7dd5e4bc72e7320f319bf0e850a Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Tue, 9 Sep 2025 08:20:00 +0200 Subject: [PATCH 485/541] [main] Update dependencies from microsoft/testfx (#6541) Co-authored-by: dotnet-maestro[bot] --- eng/Version.Details.xml | 8 ++++---- eng/Versions.props | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index d8e2ebad62..f854c52e93 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -17,13 +17,13 @@ https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage e47e677c358805815914ac475d646c90fd28a1ec - + https://github.com/microsoft/testfx - db43d4e2dedc776e37717853805b0fce30b1ccff + 534a33a00a02234f9d9930c0fd149c904ae39f0c - + https://github.com/microsoft/testfx - db43d4e2dedc776e37717853805b0fce30b1ccff + 534a33a00a02234f9d9930c0fd149c904ae39f0c diff --git a/eng/Versions.props b/eng/Versions.props index f0369eab1d..7a4422c30d 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -10,7 +10,7 @@ 11.0.0-beta.25457.1 18.0.0-preview.25453.1 - 3.11.0-preview.25457.1 - 1.9.0-preview.25457.1 + 3.11.0-preview.25457.2 + 1.9.0-preview.25457.2 From 2d358c37892b720c0f23d7851712cf3247293328 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Tue, 9 Sep 2025 11:17:36 +0200 Subject: [PATCH 486/541] Avoid long path issues for pipes (#6536) --- .../IPC/NamedPipeServer.cs | 34 ++++++++----------- .../IPC/PipeNameDescription.cs | 25 ++------------ 2 files changed, 17 insertions(+), 42 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Platform/IPC/NamedPipeServer.cs b/src/Platform/Microsoft.Testing.Platform/IPC/NamedPipeServer.cs index 27b578ad8f..f9ba102c10 100644 --- a/src/Platform/Microsoft.Testing.Platform/IPC/NamedPipeServer.cs +++ b/src/Platform/Microsoft.Testing.Platform/IPC/NamedPipeServer.cs @@ -22,6 +22,8 @@ internal sealed class NamedPipeServer : NamedPipeBase, IServer ; #pragma warning restore CA1416 // Validate platform compatibility + private static bool IsUnix => Path.DirectorySeparatorChar == '/'; + private readonly Func> _callback; private readonly IEnvironment _environment; private readonly NamedPipeServerStream _namedPipeServerStream; @@ -277,32 +279,24 @@ private async Task InternalLoopAsync(CancellationToken cancellationToken) // If core MTP is updated, but old version of TRX is still used, it will try to call this overload at runtime. // Without it, MissingMethodException will be thrown at runtime. public static PipeNameDescription GetPipeName(string name) - => GetPipeName(name, new SystemEnvironment()); - - public static PipeNameDescription GetPipeName(string name, IEnvironment environment) { - if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + if (!IsUnix) { - return new PipeNameDescription($"testingplatform.pipe.{name.Replace('\\', '.')}", false); + return new PipeNameDescription($"testingplatform.pipe.{name.Replace('\\', '.')}"); } -#pragma warning disable RS0030 // Do not use banned APIs - We are using IEnvironment, but we still need the enum from the Environment class in BCL. This is safe. - string directoryId = Path.Combine(environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData, Environment.SpecialFolderOption.None), name); -#pragma warning disable RS0030 // Do not use banned APIs - Directory.CreateDirectory(directoryId); - return new PipeNameDescription( - !Directory.Exists(directoryId) - ? throw new DirectoryNotFoundException(string.Format( - CultureInfo.InvariantCulture, -#if PLATFORM_MSBUILD - $"Directory: {directoryId} doesn't exist.", -#else - PlatformResources.CouldNotFindDirectoryErrorMessage, -#endif - directoryId)) - : Path.Combine(directoryId, ".p"), true); + // Similar to https://github.com/dotnet/roslyn/blob/99bf83c7bc52fa1ff27cf792db38755d5767c004/src/Compilers/Shared/NamedPipeUtil.cs#L26-L42 + return new PipeNameDescription(Path.Combine("/tmp", name)); } + // For compatibility only. + // Old versions of MTP used to have this overload without IEnvironment. + // Extensions (e.g, TRX) calls into this overload. + // If core MTP is updated, but old version of TRX is still used, it will try to call this overload at runtime. + // Without it, MissingMethodException will be thrown at runtime. + public static PipeNameDescription GetPipeName(string name, IEnvironment _) + => GetPipeName(name); + public void Dispose() { if (_disposed) diff --git a/src/Platform/Microsoft.Testing.Platform/IPC/PipeNameDescription.cs b/src/Platform/Microsoft.Testing.Platform/IPC/PipeNameDescription.cs index b8b6214612..eebb652d3e 100644 --- a/src/Platform/Microsoft.Testing.Platform/IPC/PipeNameDescription.cs +++ b/src/Platform/Microsoft.Testing.Platform/IPC/PipeNameDescription.cs @@ -3,32 +3,13 @@ namespace Microsoft.Testing.Platform.IPC; -internal sealed class PipeNameDescription(string name, bool isDirectory) : IDisposable +internal sealed class PipeNameDescription(string name) : IDisposable { - private readonly bool _isDirectory = isDirectory; - private bool _disposed; - public string Name { get; } = name; + // This is available via IVT. + // Avoid removing it as it can be seen as a binary breaking change when users use newer version of core MTP but older version of one of the extensions. public void Dispose() { - if (_disposed) - { - return; - } - - if (_isDirectory) - { - try - { - Directory.Delete(Path.GetDirectoryName(Name)!, true); - } - catch (IOException) - { - // This folder is created inside the temp directory and will be cleaned up eventually by the OS - } - } - - _disposed = true; } } From bc9e0f634673e28205bc777027a78af065bed5c2 Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Tue, 9 Sep 2025 09:20:57 +0000 Subject: [PATCH 487/541] [main] Update dependencies from devdiv/DevDiv/vs-code-coverage, dotnet/arcade (#6540) Co-authored-by: dotnet-maestro[bot] --- eng/Version.Details.xml | 16 ++++++++-------- eng/Versions.props | 4 ++-- .../steps/source-index-stage1-publish.yml | 4 ++-- global.json | 2 +- 4 files changed, 13 insertions(+), 13 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index f854c52e93..e2fedef2a4 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -1,21 +1,21 @@ - + https://github.com/dotnet/arcade - d7585e79b1397fe8783ac30c81bf5be4d250bcb1 + e7357d6000fb383b01fd37b972a3b55904267da7 - + https://github.com/dotnet/arcade - d7585e79b1397fe8783ac30c81bf5be4d250bcb1 + e7357d6000fb383b01fd37b972a3b55904267da7 - + https://github.com/dotnet/arcade - d7585e79b1397fe8783ac30c81bf5be4d250bcb1 + e7357d6000fb383b01fd37b972a3b55904267da7 - + https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage - e47e677c358805815914ac475d646c90fd28a1ec + 7f9009a58e7c72137ee1d63105626b3d16dfdf90 https://github.com/microsoft/testfx diff --git a/eng/Versions.props b/eng/Versions.props index 7a4422c30d..8701a0b12c 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -7,8 +7,8 @@ preview - 11.0.0-beta.25457.1 - 18.0.0-preview.25453.1 + 11.0.0-beta.25458.3 + 18.0.0-preview.25458.3 3.11.0-preview.25457.2 1.9.0-preview.25457.2 diff --git a/eng/common/core-templates/steps/source-index-stage1-publish.yml b/eng/common/core-templates/steps/source-index-stage1-publish.yml index e9a694afa5..eff4573c6e 100644 --- a/eng/common/core-templates/steps/source-index-stage1-publish.yml +++ b/eng/common/core-templates/steps/source-index-stage1-publish.yml @@ -1,6 +1,6 @@ parameters: - sourceIndexUploadPackageVersion: 2.0.0-20250818.1 - sourceIndexProcessBinlogPackageVersion: 1.0.1-20250818.1 + sourceIndexUploadPackageVersion: 2.0.0-20250906.1 + sourceIndexProcessBinlogPackageVersion: 1.0.1-20250906.1 sourceIndexPackageSource: https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-tools/nuget/v3/index.json binlogPath: artifacts/log/Debug/Build.binlog diff --git a/global.json b/global.json index 77065596cc..7d28c5c343 100644 --- a/global.json +++ b/global.json @@ -33,7 +33,7 @@ "rollForward": "latestFeature" }, "msbuild-sdks": { - "Microsoft.DotNet.Arcade.Sdk": "11.0.0-beta.25457.1", + "Microsoft.DotNet.Arcade.Sdk": "11.0.0-beta.25458.3", "MSBuild.Sdk.Extras": "3.0.44" } } From e5200a7c8e731f262d5e3cc79268057ad0811f5f Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Wed, 10 Sep 2025 05:02:32 +0200 Subject: [PATCH 488/541] [main] Update dependencies from microsoft/testfx (#6543) Co-authored-by: dotnet-maestro[bot] --- eng/Version.Details.xml | 8 ++++---- eng/Versions.props | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index e2fedef2a4..3c556ad161 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -17,13 +17,13 @@ https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage 7f9009a58e7c72137ee1d63105626b3d16dfdf90 - + https://github.com/microsoft/testfx - 534a33a00a02234f9d9930c0fd149c904ae39f0c + bc9e0f634673e28205bc777027a78af065bed5c2 - + https://github.com/microsoft/testfx - 534a33a00a02234f9d9930c0fd149c904ae39f0c + bc9e0f634673e28205bc777027a78af065bed5c2 diff --git a/eng/Versions.props b/eng/Versions.props index 8701a0b12c..1a15ef2476 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -10,7 +10,7 @@ 11.0.0-beta.25458.3 18.0.0-preview.25458.3 - 3.11.0-preview.25457.2 - 1.9.0-preview.25457.2 + 3.11.0-preview.25459.2 + 1.9.0-preview.25459.2 From a7990cad9cda3619caa8c15c7774fa53ee670f39 Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Wed, 10 Sep 2025 06:29:51 +0000 Subject: [PATCH 489/541] [main] Update dependencies from devdiv/DevDiv/vs-code-coverage, dotnet/arcade (#6542) Co-authored-by: dotnet-maestro[bot] --- eng/Version.Details.xml | 16 ++++++++-------- eng/Versions.props | 4 ++-- global.json | 2 +- 3 files changed, 11 insertions(+), 11 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index 3c556ad161..4a795fca08 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -1,21 +1,21 @@ - + https://github.com/dotnet/arcade - e7357d6000fb383b01fd37b972a3b55904267da7 + 4bb350073ab630245b80473c78b8c9d14d8236c8 - + https://github.com/dotnet/arcade - e7357d6000fb383b01fd37b972a3b55904267da7 + 4bb350073ab630245b80473c78b8c9d14d8236c8 - + https://github.com/dotnet/arcade - e7357d6000fb383b01fd37b972a3b55904267da7 + 4bb350073ab630245b80473c78b8c9d14d8236c8 - + https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage - 7f9009a58e7c72137ee1d63105626b3d16dfdf90 + d71460dce5bbe5fce378c510bddeec7cd50d865f https://github.com/microsoft/testfx diff --git a/eng/Versions.props b/eng/Versions.props index 1a15ef2476..53496aa73a 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -7,8 +7,8 @@ preview - 11.0.0-beta.25458.3 - 18.0.0-preview.25458.3 + 11.0.0-beta.25459.1 + 18.0.0-preview.25459.1 3.11.0-preview.25459.2 1.9.0-preview.25459.2 diff --git a/global.json b/global.json index 7d28c5c343..1273fedc68 100644 --- a/global.json +++ b/global.json @@ -33,7 +33,7 @@ "rollForward": "latestFeature" }, "msbuild-sdks": { - "Microsoft.DotNet.Arcade.Sdk": "11.0.0-beta.25458.3", + "Microsoft.DotNet.Arcade.Sdk": "11.0.0-beta.25459.1", "MSBuild.Sdk.Extras": "3.0.44" } } From c1da2fb788565ccaf9ac9295d42486104d6797cb Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Wed, 10 Sep 2025 14:32:12 +0200 Subject: [PATCH 490/541] Remove extra reference to MSTest.Analyzers (#6548) --- src/Package/MSTest/MSTest.csproj | 1 - 1 file changed, 1 deletion(-) diff --git a/src/Package/MSTest/MSTest.csproj b/src/Package/MSTest/MSTest.csproj index ecbba42c9e..52763d8709 100644 --- a/src/Package/MSTest/MSTest.csproj +++ b/src/Package/MSTest/MSTest.csproj @@ -46,7 +46,6 @@ - From ebc4aef0f4ef7df7eb88ffc371c02b2c76fa51a3 Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Thu, 11 Sep 2025 08:41:00 +0200 Subject: [PATCH 491/541] [main] Update dependencies from microsoft/testfx (#6553) Co-authored-by: dotnet-maestro[bot] --- eng/Version.Details.xml | 8 ++++---- eng/Versions.props | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index 4a795fca08..eb658f5a34 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -17,13 +17,13 @@ https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage d71460dce5bbe5fce378c510bddeec7cd50d865f - + https://github.com/microsoft/testfx - bc9e0f634673e28205bc777027a78af065bed5c2 + c1da2fb788565ccaf9ac9295d42486104d6797cb - + https://github.com/microsoft/testfx - bc9e0f634673e28205bc777027a78af065bed5c2 + c1da2fb788565ccaf9ac9295d42486104d6797cb diff --git a/eng/Versions.props b/eng/Versions.props index 53496aa73a..b458433f83 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -10,7 +10,7 @@ 11.0.0-beta.25459.1 18.0.0-preview.25459.1 - 3.11.0-preview.25459.2 - 1.9.0-preview.25459.2 + 3.11.0-preview.25460.1 + 1.9.0-preview.25460.1 From 23e393474209c2abcbc97b175dd6625d65420ad5 Mon Sep 17 00:00:00 2001 From: Mariam Abdullah <122357303+mariam-abdulla@users.noreply.github.com> Date: Thu, 11 Sep 2025 10:12:31 +0200 Subject: [PATCH 492/541] Remove failfast in named pipe client (#6552) --- src/Platform/Microsoft.Testing.Platform/IPC/NamedPipeClient.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/Platform/Microsoft.Testing.Platform/IPC/NamedPipeClient.cs b/src/Platform/Microsoft.Testing.Platform/IPC/NamedPipeClient.cs index edcab5d062..63c04d3919 100644 --- a/src/Platform/Microsoft.Testing.Platform/IPC/NamedPipeClient.cs +++ b/src/Platform/Microsoft.Testing.Platform/IPC/NamedPipeClient.cs @@ -164,7 +164,8 @@ public async Task RequestReplyAsync(TRequest req // This can happen if the other processes gets killed or crashes while while it's sending the response. // This is especially important for 'dotnet test', where the user can simply kill the dotnet.exe process themselves. // In that case, we want the MTP process to also die. - _environment.FailFast("[NamedPipeClient] Connection lost with the other side."); + // Exit code 1 indicates abnormal termination due to IPC connection loss. + _environment.Exit(ExitCodes.GenericFailure); } // Reset the current chunk size From 585e2790528226dd35afd6e5c3850567ea2fe5e5 Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Fri, 12 Sep 2025 08:28:25 +0000 Subject: [PATCH 493/541] [main] Update dependencies from dotnet/arcade (#6556) Co-authored-by: dotnet-maestro[bot] --- eng/Version.Details.xml | 12 ++++++------ eng/Versions.props | 2 +- global.json | 2 +- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index eb658f5a34..ddad4f0531 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -1,17 +1,17 @@ - + https://github.com/dotnet/arcade - 4bb350073ab630245b80473c78b8c9d14d8236c8 + eaeefbd9f29d54c1543459f7624aecddb06d9c7e - + https://github.com/dotnet/arcade - 4bb350073ab630245b80473c78b8c9d14d8236c8 + eaeefbd9f29d54c1543459f7624aecddb06d9c7e - + https://github.com/dotnet/arcade - 4bb350073ab630245b80473c78b8c9d14d8236c8 + eaeefbd9f29d54c1543459f7624aecddb06d9c7e https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage diff --git a/eng/Versions.props b/eng/Versions.props index b458433f83..0d1cea9734 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -7,7 +7,7 @@ preview - 11.0.0-beta.25459.1 + 11.0.0-beta.25461.3 18.0.0-preview.25459.1 3.11.0-preview.25460.1 diff --git a/global.json b/global.json index 1273fedc68..ea70e7eafd 100644 --- a/global.json +++ b/global.json @@ -33,7 +33,7 @@ "rollForward": "latestFeature" }, "msbuild-sdks": { - "Microsoft.DotNet.Arcade.Sdk": "11.0.0-beta.25459.1", + "Microsoft.DotNet.Arcade.Sdk": "11.0.0-beta.25461.3", "MSBuild.Sdk.Extras": "3.0.44" } } From 4f736ecab3009b248552ddfe9b737b4a297b09ae Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Fri, 12 Sep 2025 14:43:47 +0200 Subject: [PATCH 494/541] Fix broken official build (#6557) --- .../OutputDevice/BrowserOutputDevice.cs | 2 +- .../OutputDevice/TerminalOutputDevice.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/BrowserOutputDevice.cs b/src/Platform/Microsoft.Testing.Platform/OutputDevice/BrowserOutputDevice.cs index 603c8dc38d..87a62f15d4 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/BrowserOutputDevice.cs +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/BrowserOutputDevice.cs @@ -151,7 +151,7 @@ public async Task DisplayBannerAsync(string? bannerMessage) if (_platformInformation.BuildDate is { } buildDate) { - stringBuilder.Append(CultureInfo.InvariantCulture, $" (UTC {buildDate.UtcDateTime.ToShortDateString()})"); + stringBuilder.Append(CultureInfo.InvariantCulture, $" (UTC {buildDate.UtcDateTime:d})"); } if (_runtimeFeature.IsDynamicCodeSupported) diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/TerminalOutputDevice.cs b/src/Platform/Microsoft.Testing.Platform/OutputDevice/TerminalOutputDevice.cs index 2fd1bbb28f..8701f17e0b 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/TerminalOutputDevice.cs +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/TerminalOutputDevice.cs @@ -234,7 +234,7 @@ public async Task DisplayBannerAsync(string? bannerMessage) if (_platformInformation.BuildDate is { } buildDate) { - stringBuilder.Append(CultureInfo.InvariantCulture, $" (UTC {buildDate.UtcDateTime.ToShortDateString()})"); + stringBuilder.Append(CultureInfo.InvariantCulture, $" (UTC {buildDate.UtcDateTime:d})"); } if (_runtimeFeature.IsDynamicCodeSupported) From afba02a7d39a2081784a1c765f9c429ae77568e7 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Fri, 12 Sep 2025 17:37:44 +0200 Subject: [PATCH 495/541] Fix official pipeline build (#6558) --- samples/Playground/Tests.cs | 12 +----------- 1 file changed, 1 insertion(+), 11 deletions(-) diff --git a/samples/Playground/Tests.cs b/samples/Playground/Tests.cs index c3b540e601..b77a79c78b 100644 --- a/samples/Playground/Tests.cs +++ b/samples/Playground/Tests.cs @@ -13,17 +13,7 @@ namespace Playground; public class TestClass { [TestMethod] - [DynamicData(nameof(Data))] - public void Test3(int a, int b) + public void Test1() { } - - public static IEnumerable<(int A, int B)> Data - { - get - { - yield return (1, 2); - yield return (3, 4); - } - } } From db5e262a1483caa653d6fa8e6df54763d0f88f77 Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Sat, 13 Sep 2025 08:31:51 +0000 Subject: [PATCH 496/541] [main] Update dependencies from devdiv/DevDiv/vs-code-coverage, dotnet/arcade (#6561) Co-authored-by: dotnet-maestro[bot] --- eng/Version.Details.xml | 16 ++++++++-------- eng/Versions.props | 4 ++-- .../core-templates/job/publish-build-assets.yml | 9 ++++++++- eng/common/core-templates/jobs/jobs.yml | 2 ++ global.json | 2 +- 5 files changed, 21 insertions(+), 12 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index ddad4f0531..1849319541 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -1,21 +1,21 @@ - + https://github.com/dotnet/arcade - eaeefbd9f29d54c1543459f7624aecddb06d9c7e + c32cd132a730a7b9f947498b2ae75dbdc6785456 - + https://github.com/dotnet/arcade - eaeefbd9f29d54c1543459f7624aecddb06d9c7e + c32cd132a730a7b9f947498b2ae75dbdc6785456 - + https://github.com/dotnet/arcade - eaeefbd9f29d54c1543459f7624aecddb06d9c7e + c32cd132a730a7b9f947498b2ae75dbdc6785456 - + https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage - d71460dce5bbe5fce378c510bddeec7cd50d865f + aeac32704110bf7b363a16815eb51df0d62ae57a https://github.com/microsoft/testfx diff --git a/eng/Versions.props b/eng/Versions.props index 0d1cea9734..84edc926d3 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -7,8 +7,8 @@ preview - 11.0.0-beta.25461.3 - 18.0.0-preview.25459.1 + 11.0.0-beta.25462.2 + 18.0.0-preview.25462.2 3.11.0-preview.25460.1 1.9.0-preview.25460.1 diff --git a/eng/common/core-templates/job/publish-build-assets.yml b/eng/common/core-templates/job/publish-build-assets.yml index 348cd16376..37dff559fc 100644 --- a/eng/common/core-templates/job/publish-build-assets.yml +++ b/eng/common/core-templates/job/publish-build-assets.yml @@ -40,6 +40,8 @@ parameters: repositoryAlias: self + officialBuildId: '' + jobs: - job: Asset_Registry_Publish @@ -62,6 +64,11 @@ jobs: value: false # unconditional - needed for logs publishing (redactor tool version) - template: /eng/common/core-templates/post-build/common-variables.yml + - name: OfficialBuildId + ${{ if ne(parameters.officialBuildId, '') }}: + value: ${{ parameters.officialBuildId }} + ${{ else }}: + value: $(Build.BuildNumber) pool: # We don't use the collection uri here because it might vary (.visualstudio.com vs. dev.azure.com) @@ -124,7 +131,7 @@ jobs: /p:ManifestsPath='$(Build.StagingDirectory)/AssetManifests' /p:IsAssetlessBuild=${{ parameters.isAssetlessBuild }} /p:MaestroApiEndpoint=https://maestro.dot.net - /p:OfficialBuildId=$(Build.BuildNumber) + /p:OfficialBuildId=$(OfficialBuildId) condition: ${{ parameters.condition }} continueOnError: ${{ parameters.continueOnError }} diff --git a/eng/common/core-templates/jobs/jobs.yml b/eng/common/core-templates/jobs/jobs.yml index b637cb6e94..01ada74766 100644 --- a/eng/common/core-templates/jobs/jobs.yml +++ b/eng/common/core-templates/jobs/jobs.yml @@ -44,6 +44,7 @@ parameters: artifacts: {} is1ESPipeline: '' repositoryAlias: self + officialBuildId: '' # Internal resources (telemetry, microbuild) can only be accessed from non-public projects, # and some (Microbuild) should only be applied to non-PR cases for internal builds. @@ -116,3 +117,4 @@ jobs: artifactsPublishingAdditionalParameters: ${{ parameters.artifactsPublishingAdditionalParameters }} signingValidationAdditionalParameters: ${{ parameters.signingValidationAdditionalParameters }} repositoryAlias: ${{ parameters.repositoryAlias }} + officialBuildId: ${{ parameters.officialBuildId }} diff --git a/global.json b/global.json index ea70e7eafd..6fd15b887b 100644 --- a/global.json +++ b/global.json @@ -33,7 +33,7 @@ "rollForward": "latestFeature" }, "msbuild-sdks": { - "Microsoft.DotNet.Arcade.Sdk": "11.0.0-beta.25461.3", + "Microsoft.DotNet.Arcade.Sdk": "11.0.0-beta.25462.2", "MSBuild.Sdk.Extras": "3.0.44" } } From 8ad6a3baf53aa46b74cfd1fdafdfffeba0877936 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Sat, 13 Sep 2025 20:32:27 +0200 Subject: [PATCH 497/541] Add es-metadata.yml (#6560) --- es-metadata.yml | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 es-metadata.yml diff --git a/es-metadata.yml b/es-metadata.yml new file mode 100644 index 0000000000..11af1e321e --- /dev/null +++ b/es-metadata.yml @@ -0,0 +1,8 @@ +schemaVersion: 0.0.1 +isProduction: true +accountableOwners: + service: 88877424-b87d-45a2-8ab8-48321d99a5d2 +routing: + defaultAreaPath: + org: devdiv + path: DevDiv\Testing Platforms From 57270ecc40e5470caac283cf45b4a913115fd982 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Sat, 13 Sep 2025 20:33:20 +0200 Subject: [PATCH 498/541] Bump dotnet-sdk from 10.0.100-rc.1.25420.111 to 10.0.100.pre.rc.1.25451.107 (#6545) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: Youssef Victor --- global.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/global.json b/global.json index 6fd15b887b..7b9480baf1 100644 --- a/global.json +++ b/global.json @@ -1,6 +1,6 @@ { "tools": { - "dotnet": "10.0.100-rc.1.25420.111", + "dotnet": "10.0.100-rc.1.25451.107", "runtimes": { "dotnet": [ "3.1.32", @@ -23,7 +23,7 @@ } }, "sdk": { - "version": "10.0.100-rc.1.25420.111", + "version": "10.0.100-rc.1.25451.107", "paths": [ ".dotnet", "$host$" From b7507dc8a6007e132d8809edc2ddf0065bd0ec4e Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Sun, 14 Sep 2025 09:45:54 +0200 Subject: [PATCH 499/541] [main] Update dependencies from microsoft/testfx (#6563) Co-authored-by: dotnet-maestro[bot] --- eng/Version.Details.xml | 8 ++++---- eng/Versions.props | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index 1849319541..b8aad67434 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -17,13 +17,13 @@ https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage aeac32704110bf7b363a16815eb51df0d62ae57a - + https://github.com/microsoft/testfx - c1da2fb788565ccaf9ac9295d42486104d6797cb + db5e262a1483caa653d6fa8e6df54763d0f88f77 - + https://github.com/microsoft/testfx - c1da2fb788565ccaf9ac9295d42486104d6797cb + db5e262a1483caa653d6fa8e6df54763d0f88f77 diff --git a/eng/Versions.props b/eng/Versions.props index 84edc926d3..69433fe0b3 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -10,7 +10,7 @@ 11.0.0-beta.25462.2 18.0.0-preview.25462.2 - 3.11.0-preview.25460.1 - 1.9.0-preview.25460.1 + 3.11.0-preview.25463.1 + 1.9.0-preview.25463.1 From 090d1d49bf4f7ba375d451ed2b34930856c20e4a Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Mon, 15 Sep 2025 08:54:25 +0200 Subject: [PATCH 500/541] [main] Update dependencies from microsoft/testfx (#6565) Co-authored-by: dotnet-maestro[bot] --- eng/Version.Details.xml | 8 ++++---- eng/Versions.props | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index b8aad67434..9eda64cb51 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -17,13 +17,13 @@ https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage aeac32704110bf7b363a16815eb51df0d62ae57a - + https://github.com/microsoft/testfx - db5e262a1483caa653d6fa8e6df54763d0f88f77 + b7507dc8a6007e132d8809edc2ddf0065bd0ec4e - + https://github.com/microsoft/testfx - db5e262a1483caa653d6fa8e6df54763d0f88f77 + b7507dc8a6007e132d8809edc2ddf0065bd0ec4e diff --git a/eng/Versions.props b/eng/Versions.props index 69433fe0b3..e221c54101 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -10,7 +10,7 @@ 11.0.0-beta.25462.2 18.0.0-preview.25462.2 - 3.11.0-preview.25463.1 - 1.9.0-preview.25463.1 + 3.11.0-preview.25464.1 + 1.9.0-preview.25464.1 From 88b628c119accb687eea15d88fb52aecb7c09e70 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Mon, 15 Sep 2025 12:42:21 +0200 Subject: [PATCH 501/541] Include parameter types in discovered test message (#6564) --- .../DotnetTest/IPC/DotnetTestDataConsumer.cs | 1 + .../IPC/Models/DiscoveredTestMessages.cs | 2 +- .../DotnetTest/IPC/ObjectFieldIds.cs | 1 + .../DiscoveredTestMessagesSerializer.cs | 56 ++++++++++++++++++- .../IPC/ProtocolTests.cs | 18 +++++- 5 files changed, 72 insertions(+), 6 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/DotnetTestDataConsumer.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/DotnetTestDataConsumer.cs index 585e5aff1a..4c0421dea6 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/DotnetTestDataConsumer.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/DotnetTestDataConsumer.cs @@ -78,6 +78,7 @@ public async Task ConsumeAsync(IDataProducer dataProducer, IData value, Cancella testMethodIdentifierProperty?.Namespace, testMethodIdentifierProperty?.TypeName, testMethodIdentifierProperty?.MethodName, + testMethodIdentifierProperty?.ParameterTypeFullNames, traits) ]); diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Models/DiscoveredTestMessages.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Models/DiscoveredTestMessages.cs index 2685de08ef..1f2275d1c9 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Models/DiscoveredTestMessages.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Models/DiscoveredTestMessages.cs @@ -5,6 +5,6 @@ namespace Microsoft.Testing.Platform.IPC.Models; -internal sealed record DiscoveredTestMessage(string? Uid, string? DisplayName, string? FilePath, int? LineNumber, string? Namespace, string? TypeName, string? MethodName, TestMetadataProperty[] Traits); +internal sealed record DiscoveredTestMessage(string? Uid, string? DisplayName, string? FilePath, int? LineNumber, string? Namespace, string? TypeName, string? MethodName, string[]? ParameterTypeFullNames, TestMetadataProperty[] Traits); internal sealed record DiscoveredTestMessages(string? ExecutionId, string? InstanceId, DiscoveredTestMessage[] DiscoveredMessages) : IRequest; diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/ObjectFieldIds.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/ObjectFieldIds.cs index 46c634ebf8..dc61f0c85f 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/ObjectFieldIds.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/ObjectFieldIds.cs @@ -57,6 +57,7 @@ internal static class DiscoveredTestMessageFieldsId public const ushort TypeName = 6; public const ushort MethodName = 7; public const ushort Traits = 8; + public const ushort ParameterTypeFullNames = 9; } internal static class TraitMessageFieldsId diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Serializers/DiscoveredTestMessagesSerializer.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Serializers/DiscoveredTestMessagesSerializer.cs index ff8482ff6c..dd0d4f39ae 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Serializers/DiscoveredTestMessagesSerializer.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Serializers/DiscoveredTestMessagesSerializer.cs @@ -66,6 +66,14 @@ namespace Microsoft.Testing.Platform.IPC.Serializers; |---DiscoveredTestMessageList[0].Trits[0].Value Id---| (2 bytes) |---DiscoveredTestMessageList[0].Trits[0].Value Size---| (4 bytes) |---DiscoveredTestMessageList[0].Trits[0].Value Value---| (n bytes) + + |---DiscoveredTestMessageList[0].ParameterTypeFullNames Id---| (2 bytes) + |---DiscoveredTestMessageList[0].ParameterTypeFullNames Size---| (4 bytes) + |---DiscoveredTestMessageList[0].ParameterTypeFullNames Value---| (n bytes) + |---DiscoveredTestMessageList[0].ParameterTypeFullNames Length---| (4 bytes) + + |---DiscoveredTestMessageList[0].ParameterTypeFullNames[0].Key Size---| (4 bytes) + |---DiscoveredTestMessageList[0].ParameterTypeFullNames[0].Key Value---| (n bytes) */ internal sealed class DiscoveredTestMessagesSerializer : BaseSerializer, INamedPipeSerializer @@ -123,6 +131,7 @@ private static DiscoveredTestMessage[] ReadDiscoveredTestMessagesPayload(Stream string? typeName = null; string? methodName = null; TestMetadataProperty[] traits = []; + string[] parameterTypeFullNames = []; int fieldCount = ReadUShort(stream); @@ -165,18 +174,35 @@ private static DiscoveredTestMessage[] ReadDiscoveredTestMessagesPayload(Stream traits = ReadTraitsPayload(stream); break; + case DiscoveredTestMessageFieldsId.ParameterTypeFullNames: + parameterTypeFullNames = ReadParameterTypeFullNamesPayload(stream); + break; + default: SetPosition(stream, stream.Position + fieldSize); break; } } - discoveredTestMessages[i] = new DiscoveredTestMessage(uid, displayName, filePath, lineNumber, @namespace, typeName, methodName, traits); + discoveredTestMessages[i] = new DiscoveredTestMessage(uid, displayName, filePath, lineNumber, @namespace, typeName, methodName, parameterTypeFullNames, traits); } return discoveredTestMessages; } + private static string[] ReadParameterTypeFullNamesPayload(Stream stream) + { + int length = ReadInt(stream); + string[] parameterTypeFullNames = new string[length]; + + for (int i = 0; i < length; i++) + { + parameterTypeFullNames[i] = ReadString(stream); + } + + return parameterTypeFullNames; + } + private static TestMetadataProperty[] ReadTraitsPayload(Stream stream) { int length = ReadInt(stream); @@ -255,7 +281,7 @@ private static void WriteDiscoveredTestMessagesPayload(Stream stream, Discovered WriteField(stream, DiscoveredTestMessageFieldsId.Namespace, discoveredTestMessage.Namespace); WriteField(stream, DiscoveredTestMessageFieldsId.TypeName, discoveredTestMessage.TypeName); WriteField(stream, DiscoveredTestMessageFieldsId.MethodName, discoveredTestMessage.MethodName); - + WriteParameterTypeFullNamesPayload(stream, discoveredTestMessage.ParameterTypeFullNames); WriteTraitsPayload(stream, discoveredTestMessage.Traits); } @@ -292,6 +318,31 @@ private static void WriteTraitsPayload(Stream stream, TestMetadataProperty[]? tr WriteAtPosition(stream, (int)(stream.Position - before), before - sizeof(int)); } + private static void WriteParameterTypeFullNamesPayload(Stream stream, string[]? parameterTypeFullNames) + { + if (parameterTypeFullNames is null || parameterTypeFullNames.Length == 0) + { + return; + } + + WriteUShort(stream, DiscoveredTestMessageFieldsId.ParameterTypeFullNames); + + // We will reserve an int (4 bytes) + // so that we fill the size later, once we write the payload + WriteInt(stream, 0); + + long before = stream.Position; + WriteInt(stream, parameterTypeFullNames.Length); + foreach (string parameterTypeFullName in parameterTypeFullNames) + { + WriteString(stream, parameterTypeFullName); + } + + // NOTE: We are able to seek only if we are using a MemoryStream + // thus, the seek operation is fast as we are only changing the value of a property + WriteAtPosition(stream, (int)(stream.Position - before), before - sizeof(int)); + } + private static ushort GetFieldCount(DiscoveredTestMessages discoveredTestMessages) => (ushort)((discoveredTestMessages.ExecutionId is null ? 0 : 1) + (discoveredTestMessages.InstanceId is null ? 0 : 1) + @@ -305,6 +356,7 @@ private static ushort GetFieldCount(DiscoveredTestMessage discoveredTestMessage) (discoveredTestMessage.Namespace is null ? 0 : 1) + (discoveredTestMessage.TypeName is null ? 0 : 1) + (discoveredTestMessage.MethodName is null ? 0 : 1) + + (IsNullOrEmpty(discoveredTestMessage.ParameterTypeFullNames) ? 0 : 1) + (IsNullOrEmpty(discoveredTestMessage.Traits) ? 0 : 1)); private static ushort GetFieldCount(TestMetadataProperty trait) => diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/ProtocolTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/ProtocolTests.cs index 192f43b6d7..809a396a18 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/ProtocolTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/ProtocolTests.cs @@ -37,9 +37,12 @@ public void DiscoveredTestMessagesSerializeDeserialize() "MyExecId", "MyInstId", [ - new DiscoveredTestMessage("MyFirstUid", "DispName1", "path/to/file1.cs", 19, "MyNamespace1", "FirstType", "TM1", []), - new DiscoveredTestMessage("My2ndUid", "SecondDisplay", "file2.cs", 21, string.Empty, null, string.Empty, []), - new DiscoveredTestMessage("My3rdUid", "3rdDisplay", null, null, "MyNamespace3", "TestClass3", "TM3", [new("Key1", "Value"), new("Key2", string.Empty)]), + new DiscoveredTestMessage("MyFirstUid", "DispName1", "path/to/file1.cs", 19, "MyNamespace1", "FirstType", "TM1", [], []), + new DiscoveredTestMessage("My2ndUid", "SecondDisplay", "file2.cs", 21, string.Empty, null, string.Empty, [], []), + new DiscoveredTestMessage("My3rdUid", "3rdDisplay", null, null, "MyNamespace3", "TestClass3", "TM3", [], [new("Key1", "Value"), new("Key2", string.Empty)]), + new DiscoveredTestMessage("My4thUid", "DispName1", "path/to/file1.cs", 19, "MyNamespace1", "FirstType", "TM1", ["paramtype1", "paramtype2"], []), + new DiscoveredTestMessage("My5thUid", "SecondDisplay", "file2.cs", 21, string.Empty, null, string.Empty, ["paramtype1", "paramtype2", "paramtype3"], []), + new DiscoveredTestMessage("My5thUid", "3rdDisplay", null, null, "MyNamespace3", "TestClass3", "TM3", ["paramtype1", "paramtype2", "paramtype3"], [new("Key1", "Value"), new("Key2", string.Empty)]), ]); serializer.Serialize(message, stream); @@ -61,6 +64,15 @@ public void DiscoveredTestMessagesSerializeDeserialize() Assert.AreEqual(expected.Namespace, actual.Namespace); Assert.AreEqual(expected.TypeName, actual.TypeName); Assert.AreEqual(expected.MethodName, actual.MethodName); + + Assert.IsNotNull(expected.ParameterTypeFullNames); + Assert.IsNotNull(actual.ParameterTypeFullNames); + Assert.HasCount(expected.ParameterTypeFullNames.Length, actual.ParameterTypeFullNames); + for (int j = 0; j < expected.ParameterTypeFullNames.Length; j++) + { + Assert.AreEqual(expected.ParameterTypeFullNames[j], actual.ParameterTypeFullNames[j]); + } + Assert.HasCount(expected.Traits.Length, actual.Traits); for (int j = 0; j < expected.Traits.Length; j++) { From 1756c7f849409a918a47338b8ae26d939f2a320c Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Tue, 16 Sep 2025 17:01:14 +0200 Subject: [PATCH 502/541] Update SDK in global.json (#6568) --- dotnet.config | 2 -- global.json | 7 +++-- .../PublishAotNonNativeTests.cs | 9 ++++--- .../SdkTests.cs | 27 ++++++++++++------- .../Helpers/AcceptanceTestBase.cs | 9 ++++--- .../MSBuildTests.Solution.cs | 9 ++++--- .../MSBuildTests.Test.cs | 9 ++++--- .../RetryFailedTestsTests.cs | 9 ++++--- 8 files changed, 53 insertions(+), 28 deletions(-) delete mode 100644 dotnet.config diff --git a/dotnet.config b/dotnet.config deleted file mode 100644 index d8d2aab7e5..0000000000 --- a/dotnet.config +++ /dev/null @@ -1,2 +0,0 @@ -[dotnet.test.runner] -name= "Microsoft.Testing.Platform" diff --git a/global.json b/global.json index 7b9480baf1..8fa6e34ad3 100644 --- a/global.json +++ b/global.json @@ -1,6 +1,6 @@ { "tools": { - "dotnet": "10.0.100-rc.1.25451.107", + "dotnet": "10.0.100-rc.2.25464.104", "runtimes": { "dotnet": [ "3.1.32", @@ -23,7 +23,7 @@ } }, "sdk": { - "version": "10.0.100-rc.1.25451.107", + "version": "10.0.100-rc.2.25464.104", "paths": [ ".dotnet", "$host$" @@ -32,6 +32,9 @@ "allowPrerelease": true, "rollForward": "latestFeature" }, + "test": { + "runner": "Microsoft.Testing.Platform" + }, "msbuild-sdks": { "Microsoft.DotNet.Arcade.Sdk": "11.0.0-beta.25462.2", "MSBuild.Sdk.Extras": "3.0.44" diff --git a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/PublishAotNonNativeTests.cs b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/PublishAotNonNativeTests.cs index 2a148aac69..0ab9b4ec83 100644 --- a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/PublishAotNonNativeTests.cs +++ b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/PublishAotNonNativeTests.cs @@ -68,9 +68,12 @@ we end up with a -dev or -ci version which will lose resolution over -preview de -#file dotnet.config -[dotnet.test.runner] -name= "VSTest" +#file global.json +{ + "test": { + "runner": "VSTest" + } +} #file UnitTest1.cs diff --git a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/SdkTests.cs b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/SdkTests.cs index cd4438c398..bfa5bd799e 100644 --- a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/SdkTests.cs +++ b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/SdkTests.cs @@ -33,9 +33,12 @@ we end up with a -dev or -ci version which will lose resolution over -preview de -#file dotnet.config -[dotnet.test.runner] -name= "VSTest" +#file global.json +{ + "test": { + "runner": "VSTest" + } +} #file UnitTest1.cs using Microsoft.VisualStudio.TestTools.UnitTesting; @@ -473,9 +476,12 @@ public sealed class TestAssetFixture() : TestAssetFixtureBase(AcceptanceFixture. -#file dotnet.config -[dotnet.test.runner] -name= "VSTest" +#file global.json +{ + "test": { + "runner": "VSTest" + } +} #file UnitTest1.cs namespace AspireProject; @@ -540,9 +546,12 @@ public async Task HomepageHasPlaywrightInTitleAndGetStartedLinkLinkingToTheIntro } } -#file dotnet.config -[dotnet.test.runner] -name= "VSTest" +#file global.json +{ + "test": { + "runner": "VSTest" + } +} """; public string AspireProjectPath => GetAssetPath(AspireProjectName); diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/Helpers/AcceptanceTestBase.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/Helpers/AcceptanceTestBase.cs index 17e7811f01..1c258e1099 100644 --- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/Helpers/AcceptanceTestBase.cs +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/Helpers/AcceptanceTestBase.cs @@ -43,9 +43,12 @@ public void TestMethod1() } } -#file dotnet.config -[dotnet.test.runner] -name= "VSTest" +#file global.json +{ + "test": { + "runner": "VSTest" + } +} """; static AcceptanceTestBase() diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/MSBuildTests.Solution.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/MSBuildTests.Solution.cs index 769e8f5378..6d000d221b 100644 --- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/MSBuildTests.Solution.cs +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/MSBuildTests.Solution.cs @@ -42,9 +42,12 @@ public async Task MSBuildTests_UseMSBuildTestInfrastructure_Should_Run_Solution_ string solutionFolder = Path.Combine(tempDirectory.Path, "Solution"); VSSolution solution = new(solutionFolder, "MSTestSolution"); string nugetFile = solution.AddOrUpdateFileContent("Nuget.config", nugetConfigContent); - solution.AddOrUpdateFileContent("dotnet.config", """ - [dotnet.test.runner] - name= "VSTest" + solution.AddOrUpdateFileContent("global.json", """ + { + "test": { + "runner": "VSTest" + } + } """); for (int i = 0; i < 3; i++) { diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/MSBuildTests.Test.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/MSBuildTests.Test.cs index a23c552afd..6371a2bfd7 100644 --- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/MSBuildTests.Test.cs +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/MSBuildTests.Test.cs @@ -341,9 +341,12 @@ public async Task TestingPlatformDisableCustomTestTarget_Should_Cause_UserDefine -#file dotnet.config -[dotnet.test.runner] -name= "VSTest" +#file global.json +{ + "test": { + "runner": "VSTest" + } +} #file Program.cs using Microsoft.Testing.Platform.Builder; diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/RetryFailedTestsTests.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/RetryFailedTestsTests.cs index c6f05b18d4..f29b77ee6f 100644 --- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/RetryFailedTestsTests.cs +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/RetryFailedTestsTests.cs @@ -249,9 +249,12 @@ public sealed class TestAssetFixture() : TestAssetFixtureBase(AcceptanceFixture. -#file dotnet.config -[dotnet.test.runner] -name= "VSTest" +#file global.json +{ + "test": { + "runner": "VSTest" + } +} #file Program.cs using Microsoft.Testing.Extensions; From 3f63086ec67feb7f98d964e989ec5d8fdc4a3a01 Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Wed, 17 Sep 2025 05:50:05 +0200 Subject: [PATCH 503/541] [main] Update dependencies from devdiv/DevDiv/vs-code-coverage (#6570) Co-authored-by: dotnet-maestro[bot] --- eng/Version.Details.xml | 4 ++-- eng/Versions.props | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index 9eda64cb51..982747163e 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -13,9 +13,9 @@ https://github.com/dotnet/arcade c32cd132a730a7b9f947498b2ae75dbdc6785456 - + https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage - aeac32704110bf7b363a16815eb51df0d62ae57a + 63a748d711aa7743a17b4dd85f8321dad8f87eed https://github.com/microsoft/testfx diff --git a/eng/Versions.props b/eng/Versions.props index e221c54101..145358b06b 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -8,7 +8,7 @@ 11.0.0-beta.25462.2 - 18.0.0-preview.25462.2 + 18.0.0-preview.25466.1 3.11.0-preview.25464.1 1.9.0-preview.25464.1 From 219c70b33b1f6053c957eddf6e42b526f5e680a9 Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Wed, 17 Sep 2025 04:06:11 +0000 Subject: [PATCH 504/541] [main] Update dependencies from microsoft/testfx (#6571) Co-authored-by: dotnet-maestro[bot] --- eng/Version.Details.xml | 8 ++++---- eng/Versions.props | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index 982747163e..6f1be7bc07 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -17,13 +17,13 @@ https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage 63a748d711aa7743a17b4dd85f8321dad8f87eed - + https://github.com/microsoft/testfx - b7507dc8a6007e132d8809edc2ddf0065bd0ec4e + 1756c7f849409a918a47338b8ae26d939f2a320c - + https://github.com/microsoft/testfx - b7507dc8a6007e132d8809edc2ddf0065bd0ec4e + 1756c7f849409a918a47338b8ae26d939f2a320c diff --git a/eng/Versions.props b/eng/Versions.props index 145358b06b..15f6c3f4fa 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -10,7 +10,7 @@ 11.0.0-beta.25462.2 18.0.0-preview.25466.1 - 3.11.0-preview.25464.1 - 1.9.0-preview.25464.1 + 3.11.0-preview.25466.1 + 1.9.0-preview.25466.1 From bec122572fa9ceff9f31faabb512a080d7aad3e0 Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Thu, 18 Sep 2025 07:55:33 +0200 Subject: [PATCH 505/541] [main] Update dependencies from dotnet/arcade (#6572) Co-authored-by: dotnet-maestro[bot] --- eng/Version.Details.xml | 12 ++++++------ eng/Versions.props | 2 +- eng/common/SetupNugetSources.ps1 | 2 +- eng/common/SetupNugetSources.sh | 2 +- global.json | 2 +- 5 files changed, 10 insertions(+), 10 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index 6f1be7bc07..5a4451e169 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -1,17 +1,17 @@ - + https://github.com/dotnet/arcade - c32cd132a730a7b9f947498b2ae75dbdc6785456 + 06f338fe9a2a14ebb99d23d96818faaf2bccc663 - + https://github.com/dotnet/arcade - c32cd132a730a7b9f947498b2ae75dbdc6785456 + 06f338fe9a2a14ebb99d23d96818faaf2bccc663 - + https://github.com/dotnet/arcade - c32cd132a730a7b9f947498b2ae75dbdc6785456 + 06f338fe9a2a14ebb99d23d96818faaf2bccc663 https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage diff --git a/eng/Versions.props b/eng/Versions.props index 15f6c3f4fa..b4d8529dda 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -7,7 +7,7 @@ preview - 11.0.0-beta.25462.2 + 11.0.0-beta.25467.6 18.0.0-preview.25466.1 3.11.0-preview.25466.1 diff --git a/eng/common/SetupNugetSources.ps1 b/eng/common/SetupNugetSources.ps1 index 792b60b49d..9445c31432 100644 --- a/eng/common/SetupNugetSources.ps1 +++ b/eng/common/SetupNugetSources.ps1 @@ -157,7 +157,7 @@ if ($dotnet31Source -ne $null) { AddPackageSource -Sources $sources -SourceName "dotnet3.1-internal-transport" -SourceEndPoint "https://pkgs.dev.azure.com/dnceng/_packaging/dotnet3.1-internal-transport/nuget/v2" -Creds $creds -Username $userName -pwd $Password } -$dotnetVersions = @('5','6','7','8','9') +$dotnetVersions = @('5','6','7','8','9','10') foreach ($dotnetVersion in $dotnetVersions) { $feedPrefix = "dotnet" + $dotnetVersion; diff --git a/eng/common/SetupNugetSources.sh b/eng/common/SetupNugetSources.sh index facb415ca6..ddf4efc81a 100644 --- a/eng/common/SetupNugetSources.sh +++ b/eng/common/SetupNugetSources.sh @@ -99,7 +99,7 @@ if [ "$?" == "0" ]; then PackageSources+=('dotnet3.1-internal-transport') fi -DotNetVersions=('5' '6' '7' '8' '9') +DotNetVersions=('5' '6' '7' '8' '9' '10') for DotNetVersion in ${DotNetVersions[@]} ; do FeedPrefix="dotnet${DotNetVersion}"; diff --git a/global.json b/global.json index 8fa6e34ad3..363c63d3e2 100644 --- a/global.json +++ b/global.json @@ -36,7 +36,7 @@ "runner": "Microsoft.Testing.Platform" }, "msbuild-sdks": { - "Microsoft.DotNet.Arcade.Sdk": "11.0.0-beta.25462.2", + "Microsoft.DotNet.Arcade.Sdk": "11.0.0-beta.25467.6", "MSBuild.Sdk.Extras": "3.0.44" } } From a65b77ad062d0a16ecd9452b828174d9efa8c89f Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Thu, 18 Sep 2025 07:55:56 +0200 Subject: [PATCH 506/541] [main] Update dependencies from microsoft/testfx (#6573) Co-authored-by: dotnet-maestro[bot] --- eng/Version.Details.xml | 8 ++++---- eng/Versions.props | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index 5a4451e169..3252a0a316 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -17,13 +17,13 @@ https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage 63a748d711aa7743a17b4dd85f8321dad8f87eed - + https://github.com/microsoft/testfx - 1756c7f849409a918a47338b8ae26d939f2a320c + 3f63086ec67feb7f98d964e989ec5d8fdc4a3a01 - + https://github.com/microsoft/testfx - 1756c7f849409a918a47338b8ae26d939f2a320c + 3f63086ec67feb7f98d964e989ec5d8fdc4a3a01 diff --git a/eng/Versions.props b/eng/Versions.props index b4d8529dda..1b4f6a850f 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -10,7 +10,7 @@ 11.0.0-beta.25467.6 18.0.0-preview.25466.1 - 3.11.0-preview.25466.1 - 1.9.0-preview.25466.1 + 3.11.0-preview.25466.2 + 1.9.0-preview.25466.2 From d8aad94414cba8d97aefe39fcc24761d741ed508 Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Fri, 19 Sep 2025 05:43:42 +0200 Subject: [PATCH 507/541] [main] Update dependencies from dotnet/arcade (#6576) Co-authored-by: dotnet-maestro[bot] --- eng/Version.Details.xml | 12 ++++++------ eng/Versions.props | 2 +- global.json | 2 +- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index 3252a0a316..b7506c6b33 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -1,17 +1,17 @@ - + https://github.com/dotnet/arcade - 06f338fe9a2a14ebb99d23d96818faaf2bccc663 + f24bb1036bfd3d8350578f0e805eb17d252e7df8 - + https://github.com/dotnet/arcade - 06f338fe9a2a14ebb99d23d96818faaf2bccc663 + f24bb1036bfd3d8350578f0e805eb17d252e7df8 - + https://github.com/dotnet/arcade - 06f338fe9a2a14ebb99d23d96818faaf2bccc663 + f24bb1036bfd3d8350578f0e805eb17d252e7df8 https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage diff --git a/eng/Versions.props b/eng/Versions.props index 1b4f6a850f..f4c3ff8666 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -7,7 +7,7 @@ preview - 11.0.0-beta.25467.6 + 11.0.0-beta.25468.5 18.0.0-preview.25466.1 3.11.0-preview.25466.2 diff --git a/global.json b/global.json index 363c63d3e2..d1bb2d08d5 100644 --- a/global.json +++ b/global.json @@ -36,7 +36,7 @@ "runner": "Microsoft.Testing.Platform" }, "msbuild-sdks": { - "Microsoft.DotNet.Arcade.Sdk": "11.0.0-beta.25467.6", + "Microsoft.DotNet.Arcade.Sdk": "11.0.0-beta.25468.5", "MSBuild.Sdk.Extras": "3.0.44" } } From 22b0e4a5c81455cc3bf932e447b29d4dadebbec4 Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Fri, 19 Sep 2025 05:43:54 +0200 Subject: [PATCH 508/541] [main] Update dependencies from microsoft/testfx (#6577) Co-authored-by: dotnet-maestro[bot] --- eng/Version.Details.xml | 8 ++++---- eng/Versions.props | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index b7506c6b33..ccbc5811de 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -17,13 +17,13 @@ https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage 63a748d711aa7743a17b4dd85f8321dad8f87eed - + https://github.com/microsoft/testfx - 3f63086ec67feb7f98d964e989ec5d8fdc4a3a01 + a65b77ad062d0a16ecd9452b828174d9efa8c89f - + https://github.com/microsoft/testfx - 3f63086ec67feb7f98d964e989ec5d8fdc4a3a01 + a65b77ad062d0a16ecd9452b828174d9efa8c89f diff --git a/eng/Versions.props b/eng/Versions.props index f4c3ff8666..89a1429676 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -10,7 +10,7 @@ 11.0.0-beta.25468.5 18.0.0-preview.25466.1 - 3.11.0-preview.25466.2 - 1.9.0-preview.25466.2 + 3.11.0-preview.25467.1 + 1.9.0-preview.25467.1 From 7812bf1fe7289e9f528ced8a230502c1e0bfe50f Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Sat, 20 Sep 2025 12:23:55 +0200 Subject: [PATCH 509/541] [main] Update dependencies from devdiv/DevDiv/vs-code-coverage, dotnet/arcade (#6580) Co-authored-by: dotnet-maestro[bot] --- eng/Version.Details.xml | 16 ++++++++-------- eng/Versions.props | 4 ++-- global.json | 2 +- 3 files changed, 11 insertions(+), 11 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index ccbc5811de..8f12522142 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -1,21 +1,21 @@ - + https://github.com/dotnet/arcade - f24bb1036bfd3d8350578f0e805eb17d252e7df8 + dbc4dce57f6a2087f13d86e89dfb0334be3c42e2 - + https://github.com/dotnet/arcade - f24bb1036bfd3d8350578f0e805eb17d252e7df8 + dbc4dce57f6a2087f13d86e89dfb0334be3c42e2 - + https://github.com/dotnet/arcade - f24bb1036bfd3d8350578f0e805eb17d252e7df8 + dbc4dce57f6a2087f13d86e89dfb0334be3c42e2 - + https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage - 63a748d711aa7743a17b4dd85f8321dad8f87eed + 957aa737e42290c129a620df7129f03189743dd1 https://github.com/microsoft/testfx diff --git a/eng/Versions.props b/eng/Versions.props index 89a1429676..525ec45f26 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -7,8 +7,8 @@ preview - 11.0.0-beta.25468.5 - 18.0.0-preview.25466.1 + 11.0.0-beta.25469.3 + 18.0.0-preview.25469.1 3.11.0-preview.25467.1 1.9.0-preview.25467.1 diff --git a/global.json b/global.json index d1bb2d08d5..23153405ba 100644 --- a/global.json +++ b/global.json @@ -36,7 +36,7 @@ "runner": "Microsoft.Testing.Platform" }, "msbuild-sdks": { - "Microsoft.DotNet.Arcade.Sdk": "11.0.0-beta.25468.5", + "Microsoft.DotNet.Arcade.Sdk": "11.0.0-beta.25469.3", "MSBuild.Sdk.Extras": "3.0.44" } } From b3e546bafaf984fb332eda08678e79310c1f11b7 Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Sun, 21 Sep 2025 09:19:46 +0200 Subject: [PATCH 510/541] [main] Update dependencies from microsoft/testfx (#6584) Co-authored-by: dotnet-maestro[bot] --- eng/Version.Details.xml | 8 ++++---- eng/Versions.props | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index 8f12522142..a01da254fa 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -17,13 +17,13 @@ https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage 957aa737e42290c129a620df7129f03189743dd1 - + https://github.com/microsoft/testfx - a65b77ad062d0a16ecd9452b828174d9efa8c89f + 7812bf1fe7289e9f528ced8a230502c1e0bfe50f - + https://github.com/microsoft/testfx - a65b77ad062d0a16ecd9452b828174d9efa8c89f + 7812bf1fe7289e9f528ced8a230502c1e0bfe50f diff --git a/eng/Versions.props b/eng/Versions.props index 525ec45f26..e0dd7d7b27 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -10,7 +10,7 @@ 11.0.0-beta.25469.3 18.0.0-preview.25469.1 - 3.11.0-preview.25467.1 - 1.9.0-preview.25467.1 + 3.11.0-preview.25470.1 + 1.9.0-preview.25470.1 From bd482b45d588e1a8812bd644cd0e1f839fb5edb5 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Mon, 22 Sep 2025 19:52:07 +0200 Subject: [PATCH 511/541] More async usage (#6582) --- .../Execution/ClassCleanupManager.cs | 2 +- .../Execution/TestClassInfo.cs | 100 +++++--- .../Execution/TestMethodInfo.cs | 228 +++++++++--------- .../Execution/UnitTestRunner.cs | 9 +- .../Helpers/ExecutionContextHelpers.cs | 23 ++ .../Helpers/FixtureMethodRunner.cs | 30 ++- .../DeadlockTests.cs | 160 ++++++++++++ .../Execution/TestClassInfoTests.cs | 52 ++-- 8 files changed, 413 insertions(+), 191 deletions(-) create mode 100644 test/IntegrationTests/MSTest.Acceptance.IntegrationTests/DeadlockTests.cs diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Execution/ClassCleanupManager.cs b/src/Adapter/MSTestAdapter.PlatformServices/Execution/ClassCleanupManager.cs index 0fbfdb5bff..6cff6d26bd 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Execution/ClassCleanupManager.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Execution/ClassCleanupManager.cs @@ -104,7 +104,7 @@ internal static void ForceCleanup(TypeCache typeCache, IDictionary classInfoCache = typeCache.ClassInfoListWithExecutableCleanupMethods; foreach (TestClassInfo classInfo in classInfoCache) { - TestFailedException? ex = classInfo.ExecuteClassCleanup(testContext); + TestFailedException? ex = classInfo.ExecuteClassCleanupAsync(testContext).GetAwaiter().GetResult(); if (ex is not null) { throw ex; diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestClassInfo.cs b/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestClassInfo.cs index 8243abc9fb..429233823d 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestClassInfo.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestClassInfo.cs @@ -21,14 +21,16 @@ namespace Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution; #else [Obsolete(FrameworkConstants.PublicTypeObsoleteMessage)] #endif +#pragma warning disable CA1001 // Types that own disposable fields should be disposable - not important to dispose the SemaphoreSlim, we don't access AvailableWaitHandle. public class TestClassInfo +#pragma warning restore CA1001 // Types that own disposable fields should be disposable { /// /// Test context property name. /// private const string TestContextPropertyName = "TestContext"; - private readonly Lock _testClassExecuteSyncObject = new(); + private readonly SemaphoreSlim _testClassExecuteSyncSemaphore = new(1, 1); private TestResult? _classInitializeResult; @@ -244,12 +246,16 @@ internal set /// public Queue BaseTestCleanupMethodsQueue { get; } = new(); + /// + public void RunClassInitialize(TestContext testContext) + => RunClassInitializeAsync(testContext).GetAwaiter().GetResult(); + /// /// Runs the class initialize method. /// /// The test context. /// Throws a test failed exception if the initialization method throws an exception. - public void RunClassInitialize(TestContext testContext) + internal async Task RunClassInitializeAsync(TestContext testContext) { // If no class initialize and no base class initialize, return if (ClassInitializeMethod is null && BaseClassInitMethods.Count == 0) @@ -281,7 +287,7 @@ public void RunClassInitialize(TestContext testContext) for (int i = BaseClassInitMethods.Count - 1; i >= 0; i--) { initializeMethod = BaseClassInitMethods[i]; - ClassInitializationException = InvokeInitializeMethod(initializeMethod, testContext); + ClassInitializationException = await InvokeInitializeMethodAsync(initializeMethod, testContext).ConfigureAwait(false); if (ClassInitializationException is not null) { break; @@ -291,7 +297,7 @@ public void RunClassInitialize(TestContext testContext) if (ClassInitializationException is null) { initializeMethod = ClassInitializeMethod; - ClassInitializationException = InvokeInitializeMethod(ClassInitializeMethod, testContext); + ClassInitializationException = await InvokeInitializeMethodAsync(ClassInitializeMethod, testContext).ConfigureAwait(false); } } catch (Exception ex) @@ -355,7 +361,7 @@ public void RunClassInitialize(TestContext testContext) TestFailureException = _classInitializeResult.TestFailureException, }; - internal TestResult GetResultOrRunClassInitialize(ITestContext testContext, string? initializationLogs, string? initializationErrorLogs, string? initializationTrace, string? initializationTestContextMessages) + internal async Task GetResultOrRunClassInitializeAsync(ITestContext testContext, string? initializationLogs, string? initializationErrorLogs, string? initializationTrace, string? initializationTestContextMessages) { TestResult? clonedInitializeResult = TryGetClonedCachedClassInitializeResult(); @@ -382,8 +388,9 @@ internal TestResult GetResultOrRunClassInitialize(ITestContext testContext, stri // We could keep the logic in lock only and not duplicate, but we don't want to pay // the lock cost unnecessarily for a common case. // We also need to lock to avoid concurrency issues and guarantee that class init is called only once. - lock (_testClassExecuteSyncObject) + try { + await _testClassExecuteSyncSemaphore.WaitAsync().ConfigureAwait(false); clonedInitializeResult = TryGetClonedCachedClassInitializeResult(); // Optimization: If we already ran before and know the result, return it. @@ -407,7 +414,7 @@ internal TestResult GetResultOrRunClassInitialize(ITestContext testContext, stri IgnoreReason = "MSTest STATestClass ClassInitialize didn't complete", }; - Thread entryPointThread = new(() => result = DoRun()) + Thread entryPointThread = new(() => result = DoRunAsync().GetAwaiter().GetResult()) { Name = "MSTest STATestClass ClassInitialize", }; @@ -438,12 +445,16 @@ internal TestResult GetResultOrRunClassInitialize(ITestContext testContext, stri PlatformServiceProvider.Instance.AdapterTraceLogger.LogWarning(Resource.STAIsOnlySupportedOnWindowsWarning); } - return DoRun(); + return await DoRunAsync().ConfigureAwait(false); } } + finally + { + _testClassExecuteSyncSemaphore.Release(); + } // Local functions - TestResult DoRun() + async Task DoRunAsync() { var result = new TestResult { @@ -453,7 +464,7 @@ TestResult DoRun() try { // This runs the ClassInitialize methods only once but saves the - RunClassInitialize(testContext.Context); + await RunClassInitializeAsync(testContext.Context).ConfigureAwait(false); } catch (TestFailedException ex) { @@ -482,7 +493,7 @@ TestResult DoRun() } } - private TestFailedException? InvokeInitializeMethod(MethodInfo? methodInfo, TestContext testContext) + private async Task InvokeInitializeMethodAsync(MethodInfo? methodInfo, TestContext testContext) { if (methodInfo is null) { @@ -495,14 +506,18 @@ TestResult DoRun() timeout = localTimeout; } - TestFailedException? result = FixtureMethodRunner.RunWithTimeoutAndCancellation( - () => + TestFailedException? result = await FixtureMethodRunner.RunWithTimeoutAndCancellationAsync( + async () => { // NOTE: It's unclear what the effect is if we reset the current test context before vs after the capture. // It's safer to reset it before the capture. using (TestContextImplementation.SetCurrentTestContext(testContext as TestContextImplementation)) { - methodInfo.InvokeAsSynchronousTask(null, testContext); + Task? task = methodInfo.GetInvokeResultAsync(null, testContext); + if (task is not null) + { + await task.ConfigureAwait(false); + } } // **After** we have executed the class initialize, we save the current context. @@ -514,7 +529,7 @@ TestResult DoRun() methodInfo, ExecutionContext ?? Parent?.ExecutionContext, Resource.ClassInitializeWasCancelled, - Resource.ClassInitializeTimedOut); + Resource.ClassInitializeTimedOut).ConfigureAwait(false); return result; } @@ -540,8 +555,10 @@ TestResult DoRun() } MethodInfo? classCleanupMethod = null; - lock (_testClassExecuteSyncObject) + try { + _testClassExecuteSyncSemaphore.Wait(); + if (IsClassCleanupExecuted) { return null; @@ -552,12 +569,12 @@ TestResult DoRun() try { classCleanupMethod = ClassCleanupMethod; - ClassCleanupException = classCleanupMethod is not null ? InvokeCleanupMethod(classCleanupMethod, null!) : null; + ClassCleanupException = classCleanupMethod is not null ? InvokeCleanupMethodAsync(classCleanupMethod, null!).GetAwaiter().GetResult() : null; var baseClassCleanupQueue = new Queue(BaseClassCleanupMethods); while (baseClassCleanupQueue.Count > 0 && ClassCleanupException is null) { classCleanupMethod = baseClassCleanupQueue.Dequeue(); - ClassCleanupException = InvokeCleanupMethod(classCleanupMethod, null!); + ClassCleanupException = InvokeCleanupMethodAsync(classCleanupMethod, null!).GetAwaiter().GetResult(); } IsClassCleanupExecuted = ClassCleanupException is null; @@ -568,6 +585,10 @@ TestResult DoRun() } } } + finally + { + _testClassExecuteSyncSemaphore.Release(); + } // If ClassCleanup was successful, then don't do anything if (ClassCleanupException == null) @@ -609,7 +630,7 @@ TestResult DoRun() /// This is a replacement for RunClassCleanup but as we are on a bug fix version, we do not want to change /// the public API, hence this method. /// - internal TestFailedException? ExecuteClassCleanup(TestContext testContext) + internal async Task ExecuteClassCleanupAsync(TestContext testContext) { if ((ClassCleanupMethod is null && BaseClassCleanupMethods.Count == 0) || IsClassCleanupExecuted) @@ -619,8 +640,9 @@ TestResult DoRun() MethodInfo? classCleanupMethod = ClassCleanupMethod; - lock (_testClassExecuteSyncObject) + try { + await _testClassExecuteSyncSemaphore.WaitAsync().ConfigureAwait(false); if (IsClassCleanupExecuted // If ClassInitialize method has not been executed, then we should not execute ClassCleanup // Note that if there is no ClassInitialze method at all, we will still set @@ -637,7 +659,7 @@ TestResult DoRun() { if (!classCleanupMethod.DeclaringType!.IsIgnored(out _)) { - ClassCleanupException = InvokeCleanupMethod(classCleanupMethod, testContext); + ClassCleanupException = await InvokeCleanupMethodAsync(classCleanupMethod, testContext).ConfigureAwait(false); } } @@ -648,7 +670,7 @@ TestResult DoRun() classCleanupMethod = BaseClassCleanupMethods[i]; if (!classCleanupMethod.DeclaringType!.IsIgnored(out _)) { - ClassCleanupException = InvokeCleanupMethod(classCleanupMethod, testContext); + ClassCleanupException = await InvokeCleanupMethodAsync(classCleanupMethod, testContext).ConfigureAwait(false); if (ClassCleanupException is not null) { break; @@ -666,6 +688,10 @@ TestResult DoRun() IsClassCleanupExecuted = true; } } + finally + { + _testClassExecuteSyncSemaphore.Release(); + } // If ClassCleanup was successful, then don't do anything if (ClassCleanupException == null) @@ -704,7 +730,7 @@ TestResult DoRun() return testFailedException; } - internal void RunClassCleanup(ITestContext testContext, ClassCleanupManager classCleanupManager, TestMethodInfo testMethodInfo, TestResult[] results) + internal async Task RunClassCleanupAsync(ITestContext testContext, ClassCleanupManager classCleanupManager, TestMethodInfo testMethodInfo, TestResult[] results) { DebugEx.Assert(testMethodInfo.Parent == this, "Parent of testMethodInfo should be this TestClassInfo."); @@ -729,7 +755,7 @@ internal void RunClassCleanup(ITestContext testContext, ClassCleanupManager clas && isWindowsOS && Thread.CurrentThread.GetApartmentState() != ApartmentState.STA) { - Thread entryPointThread = new(DoRun) + var entryPointThread = new Thread(() => DoRunAsync().GetAwaiter().GetResult()) { Name = "MSTest STATestClass ClassCleanup", }; @@ -754,15 +780,15 @@ internal void RunClassCleanup(ITestContext testContext, ClassCleanupManager clas PlatformServiceProvider.Instance.AdapterTraceLogger.LogWarning(Resource.STAIsOnlySupportedOnWindowsWarning); } - DoRun(); + await DoRunAsync().ConfigureAwait(false); } // Local functions - void DoRun() + async Task DoRunAsync() { try { - TestFailedException? ex = ExecuteClassCleanup(testContext.Context); + TestFailedException? ex = await ExecuteClassCleanupAsync(testContext.Context).ConfigureAwait(false); if (ex is not null && results.Length > 0) { #pragma warning disable IDE0056 // Use index operator @@ -789,7 +815,7 @@ void DoRun() } } - private TestFailedException? InvokeCleanupMethod(MethodInfo methodInfo, TestContext testContext) + private async Task InvokeCleanupMethodAsync(MethodInfo methodInfo, TestContext testContext) { TimeoutInfo? timeout = null; if (ClassCleanupMethodTimeoutMilliseconds.TryGetValue(methodInfo, out TimeoutInfo localTimeout)) @@ -797,20 +823,20 @@ void DoRun() timeout = localTimeout; } - TestFailedException? result = FixtureMethodRunner.RunWithTimeoutAndCancellation( - () => + TestFailedException? result = await FixtureMethodRunner.RunWithTimeoutAndCancellationAsync( + async () => { // NOTE: It's unclear what the effect is if we reset the current test context before vs after the capture. // It's safer to reset it before the capture. using (TestContextImplementation.SetCurrentTestContext(testContext as TestContextImplementation)) { - if (methodInfo.GetParameters().Length == 0) - { - methodInfo.InvokeAsSynchronousTask(null); - } - else + Task? task = methodInfo.GetParameters().Length == 0 + ? methodInfo.GetInvokeResultAsync(null) + : methodInfo.GetInvokeResultAsync(null, testContext); + + if (task is not null) { - methodInfo.InvokeAsSynchronousTask(null, testContext); + await task.ConfigureAwait(false); } } @@ -824,7 +850,7 @@ void DoRun() methodInfo, ExecutionContext ?? Parent.ExecutionContext, Resource.ClassCleanupWasCancelled, - Resource.ClassCleanupTimedOut); + Resource.ClassCleanupTimedOut).ConfigureAwait(false); return result; } diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestMethodInfo.cs b/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestMethodInfo.cs index 8717823504..0f9ceb7d85 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestMethodInfo.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestMethodInfo.cs @@ -1,6 +1,10 @@ // 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 +using System.Runtime.Remoting.Messaging; +#endif + using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Extensions; using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Helpers; using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel; @@ -33,6 +37,12 @@ public class TestMethodInfo : ITestMethod private bool _isTestContextSet; private bool _isTestCleanupInvoked; + private ExecutionContext? _executionContext; + +#if NETFRAMEWORK + private object? _hostContext; +#endif + internal TestMethodInfo( MethodInfo testMethod, TestClassInfo parent, @@ -170,6 +180,12 @@ public virtual async Task InvokeAsync(object?[]? arguments) result.ResultFiles = TestContext?.GetResultFiles(); result.Duration = watch.Elapsed; } + + _executionContext?.Dispose(); + _executionContext = null; +#if NETFRAMEWORK + _hostContext = null; +#endif } return result!; @@ -386,7 +402,6 @@ private async Task ExecuteInternalAsync(object?[]? arguments, Cancel bool hasTestInitializePassed = false; Exception? testRunnerException = null; _isTestCleanupInvoked = false; - ExecutionContext? executionContext = null; try { @@ -398,12 +413,12 @@ private async Task ExecuteInternalAsync(object?[]? arguments, Cancel // After that, we invoke local cleanups (including Dispose) and finally global cleanups at last. foreach ((MethodInfo method, TimeoutInfo? timeoutInfo) in Parent.Parent.GlobalTestInitializations) { - InvokeGlobalInitializeMethod(method, ref executionContext, timeoutInfo, timeoutTokenSource); + await InvokeGlobalInitializeMethodAsync(method, timeoutInfo, timeoutTokenSource).ConfigureAwait(false); } // TODO remove dry violation with TestMethodRunner bool setTestContextSucessful = false; - if (executionContext is null) + if (_executionContext is null) { _classInstance = CreateTestClassInstance(result); setTestContextSucessful = _classInstance != null && SetTestContext(_classInstance, result); @@ -411,13 +426,11 @@ private async Task ExecuteInternalAsync(object?[]? arguments, Cancel else { // The whole ExecuteInternalAsync method is already running on the execution context we got after class init. - // However, if the global test initialize call above is using a non-cooperative timeout, it will - // need to capture the execution context from the thread running it (after it has finished). + // However, after we run global test initialize, it will need to capture the execution context (after it has finished). // This is the case when executionContext is not null (this code path). // In this case, we want to ensure the constructor and setting TestContext are both run on the correct execution context. // Also we re-capture the execution context in case constructor or TestContext setter modifies an async local value. - ExecutionContext updatedExecutionContext = executionContext; - ExecutionContextHelpers.RunOnContext(executionContext, () => + ExecutionContextHelpers.RunOnContext(_executionContext, () => { try { @@ -426,11 +439,12 @@ private async Task ExecuteInternalAsync(object?[]? arguments, Cancel } finally { - updatedExecutionContext = ExecutionContext.Capture() ?? executionContext; + _executionContext = ExecutionContext.Capture() ?? _executionContext; +#if NETFRAMEWORK + _hostContext = CallContext.HostContext; +#endif } }); - - executionContext = updatedExecutionContext; } if (setTestContextSucessful) @@ -438,11 +452,11 @@ private async Task ExecuteInternalAsync(object?[]? arguments, Cancel // For any failure after this point, we must run TestCleanup _isTestContextSet = true; - if (RunTestInitializeMethod(_classInstance!, result, ref executionContext, timeoutTokenSource)) + if (await RunTestInitializeMethodAsync(_classInstance!, result, timeoutTokenSource).ConfigureAwait(false)) { hasTestInitializePassed = true; - if (executionContext is null) + if (_executionContext is null) { Task? invokeResult = MethodInfo.GetInvokeResultAsync(_classInstance, arguments); if (invokeResult is not null) @@ -453,12 +467,14 @@ private async Task ExecuteInternalAsync(object?[]? arguments, Cancel else { var tcs = new TaskCompletionSource(); - ExecutionContext? updatedExecutionContext = executionContext; #pragma warning disable VSTHRD101 // Avoid unsupported async delegates - ExecutionContextHelpers.RunOnContext(executionContext, async () => + ExecutionContextHelpers.RunOnContext(_executionContext, async () => { try { +#if NETFRAMEWORK + CallContext.HostContext = _hostContext; +#endif Task? invokeResult = MethodInfo.GetInvokeResultAsync(_classInstance, arguments); if (invokeResult is not null) { @@ -471,18 +487,16 @@ private async Task ExecuteInternalAsync(object?[]? arguments, Cancel } finally { - updatedExecutionContext = ExecutionContext.Capture(); + _executionContext = ExecutionContext.Capture() ?? _executionContext; +#if NETFRAMEWORK + _hostContext = CallContext.HostContext; +#endif tcs.TrySetResult(null); } }); #pragma warning restore VSTHRD101 // Avoid unsupported async delegates await tcs.Task.ConfigureAwait(false); - - if (updatedExecutionContext is not null) - { - executionContext = updatedExecutionContext; - } } result.Outcome = UTF.UnitTestOutcome.Passed; @@ -562,7 +576,7 @@ private async Task ExecuteInternalAsync(object?[]? arguments, Cancel // Pulling it out so extension writers can abort custom cleanups if need be. Having this in a finally block // does not allow a thread abort exception to be raised within the block but throws one after finally is executed // crashing the process. This was blocking writing an extension for Dynamic Timeout in VSO. - await RunTestCleanupMethodAsync(result, executionContext, timeoutTokenSource).ConfigureAwait(false); + await RunTestCleanupMethodAsync(result, timeoutTokenSource).ConfigureAwait(false); return testRunnerException != null ? throw testRunnerException : result; } @@ -707,15 +721,9 @@ private static TestFailedException HandleMethodException(Exception ex, Exception /// Runs TestCleanup methods of parent TestClass and base classes. /// /// Instance of TestResult. - /// The execution context to run on. /// The timeout token source. [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Requirement is to handle all kinds of user exceptions and message appropriately.")] - private -#if NET6_0_OR_GREATER - async -#endif - Task - RunTestCleanupMethodAsync(TestResult result, ExecutionContext? executionContext, CancellationTokenSource? timeoutTokenSource) + private async Task RunTestCleanupMethodAsync(TestResult result, CancellationTokenSource? timeoutTokenSource) { DebugEx.Assert(result != null, "result != null"); @@ -724,11 +732,7 @@ private static TestFailedException HandleMethodException(Exception ex, Exception // This avoids the code below that allocates CancellationTokenSource !HasCleanupsToInvoke()) { -#if NET6_0_OR_GREATER return; -#else - return Task.CompletedTask; -#endif } _isTestCleanupInvoked = true; @@ -750,13 +754,13 @@ private static TestFailedException HandleMethodException(Exception ex, Exception // Test cleanups are called in the order of discovery // Current TestClass -> Parent -> Grandparent testCleanupException = testCleanupMethod is not null - ? InvokeCleanupMethod(testCleanupMethod, _classInstance, ref executionContext, timeoutTokenSource) + ? await InvokeCleanupMethodAsync(testCleanupMethod, _classInstance, timeoutTokenSource).ConfigureAwait(false) : null; var baseTestCleanupQueue = new Queue(Parent.BaseTestCleanupMethodsQueue); while (baseTestCleanupQueue.Count > 0 && testCleanupException is null) { testCleanupMethod = baseTestCleanupQueue.Dequeue(); - testCleanupException = InvokeCleanupMethod(testCleanupMethod, _classInstance, ref executionContext, timeoutTokenSource); + testCleanupException = await InvokeCleanupMethodAsync(testCleanupMethod, _classInstance, timeoutTokenSource).ConfigureAwait(false); } } finally @@ -775,7 +779,7 @@ private static TestFailedException HandleMethodException(Exception ex, Exception foreach ((MethodInfo method, TimeoutInfo? timeoutInfo) in Parent.Parent.GlobalTestCleanups) { - InvokeGlobalCleanupMethod(method, ref executionContext, timeoutInfo, timeoutTokenSource); + await InvokeGlobalCleanupMethodAsync(method, timeoutInfo, timeoutTokenSource).ConfigureAwait(false); } } } @@ -787,11 +791,7 @@ private static TestFailedException HandleMethodException(Exception ex, Exception // If testCleanup was successful, then don't do anything if (testCleanupException == null) { -#if NET6_0_OR_GREATER return; -#else - return Task.CompletedTask; -#endif } Exception realException = testCleanupException.GetRealException(); @@ -811,10 +811,6 @@ private static TestFailedException HandleMethodException(Exception ex, Exception realException); result.TestFailureException = realException; - -#if !NET6_0_OR_GREATER - return Task.CompletedTask; -#endif } private bool HasCleanupsToInvoke() => @@ -831,11 +827,10 @@ _classInstance is IAsyncDisposable || /// /// Instance of TestClass. /// Instance of TestResult. - /// The execution context to run on. /// The timeout token source. /// True if the TestInitialize method(s) did not throw an exception. [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Requirement is to handle all kinds of user exceptions and message appropriately.")] - private bool RunTestInitializeMethod(object classInstance, TestResult result, ref ExecutionContext? executionContext, CancellationTokenSource? timeoutTokenSource) + private async Task RunTestInitializeMethodAsync(object classInstance, TestResult result, CancellationTokenSource? timeoutTokenSource) { DebugEx.Assert(classInstance != null, "classInstance != null"); DebugEx.Assert(result != null, "result != null"); @@ -852,7 +847,7 @@ private bool RunTestInitializeMethod(object classInstance, TestResult result, re { testInitializeMethod = baseTestInitializeStack.Pop(); testInitializeException = testInitializeMethod is not null - ? InvokeInitializeMethod(testInitializeMethod, classInstance, ref executionContext, timeoutTokenSource) + ? await InvokeInitializeMethodAsync(testInitializeMethod, classInstance, timeoutTokenSource).ConfigureAwait(false) : null; if (testInitializeException is not null) { @@ -864,7 +859,7 @@ private bool RunTestInitializeMethod(object classInstance, TestResult result, re { testInitializeMethod = Parent.TestInitializeMethod; testInitializeException = testInitializeMethod is not null - ? InvokeInitializeMethod(testInitializeMethod, classInstance, ref executionContext, timeoutTokenSource) + ? await InvokeInitializeMethodAsync(testInitializeMethod, classInstance, timeoutTokenSource).ConfigureAwait(false) : null; } } @@ -913,7 +908,7 @@ private bool RunTestInitializeMethod(object classInstance, TestResult result, re return false; } - private TestFailedException? InvokeInitializeMethod(MethodInfo methodInfo, object classInstance, ref ExecutionContext? executionContext, CancellationTokenSource? timeoutTokenSource) + private async Task InvokeInitializeMethodAsync(MethodInfo methodInfo, object classInstance, CancellationTokenSource? timeoutTokenSource) { TimeoutInfo? timeout = null; if (Parent.TestInitializeMethodTimeoutMilliseconds.TryGetValue(methodInfo, out TimeoutInfo localTimeout)) @@ -921,71 +916,71 @@ private bool RunTestInitializeMethod(object classInstance, TestResult result, re timeout = localTimeout; } - int originalThreadId = Environment.CurrentManagedThreadId; - ExecutionContext? updatedExecutionContext = null; - TestFailedException? result = FixtureMethodRunner.RunWithTimeoutAndCancellation( - () => + TestFailedException? result = await FixtureMethodRunner.RunWithTimeoutAndCancellationAsync( + async () => { - methodInfo.InvokeAsSynchronousTask(classInstance, null); - if (originalThreadId != Environment.CurrentManagedThreadId) +#if NETFRAMEWORK + CallContext.HostContext = _hostContext; +#endif + + Task? task = methodInfo.GetInvokeResultAsync(classInstance, null); + if (task is not null) { - // We ended up running on a different thread, because of use of non-cooperative timeout. - // Re-capture the execution context. - updatedExecutionContext = ExecutionContext.Capture(); + await task.ConfigureAwait(false); } + + _executionContext = ExecutionContext.Capture() ?? _executionContext; +#if NETFRAMEWORK + _hostContext = CallContext.HostContext; +#endif }, TestContext!.Context.CancellationTokenSource, timeout, methodInfo, - executionContext, + _executionContext, Resource.TestInitializeWasCancelled, Resource.TestInitializeTimedOut, timeoutTokenSource is null ? null - : (timeoutTokenSource, TimeoutInfo.Timeout)); - - if (updatedExecutionContext != null) - { - executionContext = updatedExecutionContext; - } + : (timeoutTokenSource, TimeoutInfo.Timeout)).ConfigureAwait(false); return result; } - private TestFailedException? InvokeGlobalInitializeMethod(MethodInfo methodInfo, ref ExecutionContext? executionContext, TimeoutInfo? timeoutInfo, CancellationTokenSource? timeoutTokenSource) + private async Task InvokeGlobalInitializeMethodAsync(MethodInfo methodInfo, TimeoutInfo? timeoutInfo, CancellationTokenSource? timeoutTokenSource) { - int originalThreadId = Environment.CurrentManagedThreadId; - ExecutionContext? updatedExecutionContext = null; - TestFailedException? result = FixtureMethodRunner.RunWithTimeoutAndCancellation( - () => + TestFailedException? result = await FixtureMethodRunner.RunWithTimeoutAndCancellationAsync( + async () => { - methodInfo.InvokeAsSynchronousTask(null, [TestContext]); - if (originalThreadId != Environment.CurrentManagedThreadId) +#if NETFRAMEWORK + CallContext.HostContext = _hostContext; +#endif + + Task? task = methodInfo.GetInvokeResultAsync(null, [TestContext]); + if (task is not null) { - // We ended up running on a different thread, because of use of non-cooperative timeout. - // Re-capture the execution context. - updatedExecutionContext = ExecutionContext.Capture(); + await task.ConfigureAwait(false); } + + _executionContext = ExecutionContext.Capture() ?? _executionContext; +#if NETFRAMEWORK + _hostContext = CallContext.HostContext; +#endif }, TestContext!.Context.CancellationTokenSource, timeoutInfo: timeoutInfo, methodInfo, - executionContext, + _executionContext, Resource.TestInitializeWasCancelled, Resource.TestInitializeTimedOut, timeoutTokenSource is null ? null - : (timeoutTokenSource, TimeoutInfo.Timeout)); - - if (updatedExecutionContext != null) - { - executionContext = updatedExecutionContext; - } + : (timeoutTokenSource, TimeoutInfo.Timeout)).ConfigureAwait(false); return result; } - private TestFailedException? InvokeCleanupMethod(MethodInfo methodInfo, object classInstance, ref ExecutionContext? executionContext, CancellationTokenSource? timeoutTokenSource) + private async Task InvokeCleanupMethodAsync(MethodInfo methodInfo, object classInstance, CancellationTokenSource? timeoutTokenSource) { TimeoutInfo? timeout = null; if (Parent.TestCleanupMethodTimeoutMilliseconds.TryGetValue(methodInfo, out TimeoutInfo localTimeout)) @@ -993,66 +988,66 @@ timeoutTokenSource is null timeout = localTimeout; } - int originalThreadId = Environment.CurrentManagedThreadId; - ExecutionContext? updatedExecutionContext = null; - TestFailedException? result = FixtureMethodRunner.RunWithTimeoutAndCancellation( - () => + TestFailedException? result = await FixtureMethodRunner.RunWithTimeoutAndCancellationAsync( + async () => { - methodInfo.InvokeAsSynchronousTask(classInstance, null); - if (originalThreadId != Environment.CurrentManagedThreadId) +#if NETFRAMEWORK + CallContext.HostContext = _hostContext; +#endif + + Task? task = methodInfo.GetInvokeResultAsync(classInstance, null); + if (task is not null) { - // We ended up running on a different thread, because of use of non-cooperative timeout. - // Re-capture the execution context. - updatedExecutionContext = ExecutionContext.Capture(); + await task.ConfigureAwait(false); } + + _executionContext = ExecutionContext.Capture() ?? _executionContext; +#if NETFRAMEWORK + _hostContext = CallContext.HostContext; +#endif }, TestContext!.Context.CancellationTokenSource, timeout, methodInfo, - executionContext, + _executionContext, Resource.TestCleanupWasCancelled, Resource.TestCleanupTimedOut, timeoutTokenSource is null ? null - : (timeoutTokenSource, TimeoutInfo.Timeout)); - - if (updatedExecutionContext != null) - { - executionContext = updatedExecutionContext; - } + : (timeoutTokenSource, TimeoutInfo.Timeout)).ConfigureAwait(false); return result; } - private TestFailedException? InvokeGlobalCleanupMethod(MethodInfo methodInfo, ref ExecutionContext? executionContext, TimeoutInfo? timeoutInfo, CancellationTokenSource? timeoutTokenSource) + private async Task InvokeGlobalCleanupMethodAsync(MethodInfo methodInfo, TimeoutInfo? timeoutInfo, CancellationTokenSource? timeoutTokenSource) { - int originalThreadId = Environment.CurrentManagedThreadId; - ExecutionContext? updatedExecutionContext = null; - TestFailedException? result = FixtureMethodRunner.RunWithTimeoutAndCancellation( - () => + TestFailedException? result = await FixtureMethodRunner.RunWithTimeoutAndCancellationAsync( + async () => { - methodInfo.InvokeAsSynchronousTask(null, [TestContext]); - if (originalThreadId != Environment.CurrentManagedThreadId) +#if NETFRAMEWORK + CallContext.HostContext = _hostContext; +#endif + + Task? task = methodInfo.GetInvokeResultAsync(null, [TestContext]); + if (task is not null) { - // We ended up running on a different thread, because of use of non-cooperative timeout. - // Re-capture the execution context. - updatedExecutionContext = ExecutionContext.Capture(); + await task.ConfigureAwait(false); } + + _executionContext = ExecutionContext.Capture() ?? _executionContext; +#if NETFRAMEWORK + _hostContext = CallContext.HostContext; +#endif }, TestContext!.Context.CancellationTokenSource, timeoutInfo: timeoutInfo, methodInfo, - executionContext, + _executionContext, Resource.TestCleanupWasCancelled, Resource.TestCleanupTimedOut, timeoutTokenSource is null ? null - : (timeoutTokenSource, TimeoutInfo.Timeout)); - - if (updatedExecutionContext != null) - { - executionContext = updatedExecutionContext; - } + : (timeoutTokenSource, TimeoutInfo.Timeout)).ConfigureAwait(false); return result; } @@ -1220,7 +1215,6 @@ private async Task ExecuteInternalWithTimeoutAsync(object?[]? argume TestResult? result = null; Exception? failure = null; - ExecutionContext? executionContext = null; if (PlatformServiceProvider.Instance.ThreadOperations.Execute(ExecuteAsyncAction, TimeoutInfo.Timeout, TestContext!.Context.CancellationTokenSource.Token)) { @@ -1253,7 +1247,7 @@ private async Task ExecuteInternalWithTimeoutAsync(object?[]? argume // We don't know when the cancellation happened so it's possible that the cleanup wasn't executed, so we need to run it here. // The method already checks if the cleanup was already executed. - await RunTestCleanupMethodAsync(timeoutResult, executionContext, null).ConfigureAwait(false); + await RunTestCleanupMethodAsync(timeoutResult, null).ConfigureAwait(false); return timeoutResult; // Local functions diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Execution/UnitTestRunner.cs b/src/Adapter/MSTestAdapter.PlatformServices/Execution/UnitTestRunner.cs index f554851dba..3bd1ec0d2c 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Execution/UnitTestRunner.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Execution/UnitTestRunner.cs @@ -190,7 +190,7 @@ internal async Task RunSingleTestAsync(TestMethod testMethod, IDic { testContextForClassInit = PlatformServiceProvider.Instance.GetTestContext(testMethod, testContextProperties, messageLogger, testContextForAssemblyInit.Context.CurrentTestOutcome); - TestResult classInitializeResult = testMethodInfo.Parent.GetResultOrRunClassInitialize(testContextForClassInit, assemblyInitializeResult.LogOutput, assemblyInitializeResult.LogError, assemblyInitializeResult.DebugTrace, assemblyInitializeResult.TestContextMessages); + TestResult classInitializeResult = await testMethodInfo.Parent.GetResultOrRunClassInitializeAsync(testContextForClassInit, assemblyInitializeResult.LogOutput, assemblyInitializeResult.LogError, assemblyInitializeResult.DebugTrace, assemblyInitializeResult.TestContextMessages).ConfigureAwait(false); DebugEx.Assert(testMethodInfo.Parent.IsClassInitializeExecuted, "IsClassInitializeExecuted should be true after attempting to run it."); if (classInitializeResult.Outcome != UTF.UnitTestOutcome.Passed) { @@ -217,7 +217,10 @@ internal async Task RunSingleTestAsync(TestMethod testMethod, IDic } testContextForClassCleanup = PlatformServiceProvider.Instance.GetTestContext(testMethod, testContextProperties, messageLogger, testContextForTestExecution.Context.CurrentTestOutcome); - testMethodInfo?.Parent.RunClassCleanup(testContextForClassCleanup, _classCleanupManager, testMethodInfo, result); + if (testMethodInfo is not null) + { + await testMethodInfo.Parent.RunClassCleanupAsync(testContextForClassCleanup, _classCleanupManager, testMethodInfo, result).ConfigureAwait(false); + } if (testMethodInfo?.Parent.Parent.IsAssemblyInitializeExecuted == true) { @@ -292,7 +295,7 @@ private static void RunAssemblyCleanupIfNeeded(ITestContext testContext, ClassCl IEnumerable classInfoCache = typeCache.ClassInfoListWithExecutableCleanupMethods; foreach (TestClassInfo classInfo in classInfoCache) { - TestFailedException? ex = classInfo.ExecuteClassCleanup(testContext.Context); + TestFailedException? ex = classInfo.ExecuteClassCleanupAsync(testContext.Context).GetAwaiter().GetResult(); if (results.Length > 0 && ex is not null) { diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Helpers/ExecutionContextHelpers.cs b/src/Adapter/MSTestAdapter.PlatformServices/Helpers/ExecutionContextHelpers.cs index bc45585b18..23a1ff9228 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Helpers/ExecutionContextHelpers.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Helpers/ExecutionContextHelpers.cs @@ -22,4 +22,27 @@ internal static void RunOnContext(ExecutionContext? executionContext, Action act ExecutionContext.Run(executionContext, static action => ((Action)action!).Invoke(), action); } } + + internal static async Task RunOnContextAsync(ExecutionContext? executionContext, Func action) + { + if (executionContext is null) + { + await action().ConfigureAwait(false); + } + else + { + // CreateCopy doesn't do anything on .NET Core as ExecutionContexts are immutable. + // But it's important on .NET Framework. + // On .NET Framework, ExecutionContext.Run cannot be called twice with the same ExecutionContext. + // Otherwise, it will throw InvalidOperationException with message: + // Cannot apply a context that has been marshaled across AppDomains, that was not acquired through a Capture operation or that has already been the argument to a Set call. + executionContext = executionContext.CreateCopy(); + Task? t = null; + ExecutionContext.Run(executionContext, action => t = ((Func)action!).Invoke(), action); + if (t is not null) + { + await t.ConfigureAwait(false); + } + } + } } diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Helpers/FixtureMethodRunner.cs b/src/Adapter/MSTestAdapter.PlatformServices/Helpers/FixtureMethodRunner.cs index 5feb0ce26b..e1c2da9852 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Helpers/FixtureMethodRunner.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Helpers/FixtureMethodRunner.cs @@ -16,6 +16,19 @@ internal static class FixtureMethodRunner ExecutionContext? executionContext, string methodCanceledMessageFormat, string methodTimedOutMessageFormat, // When a test method is marked with [Timeout], this timeout is applied from ctor to destructor, so we need to take // that into account when processing the OCE of the action. + (CancellationTokenSource TokenSource, int Timeout)? testTimeoutInfo = default) + => RunWithTimeoutAndCancellationAsync( + () => + { + action(); + return Task.CompletedTask; + }, cancellationTokenSource, timeoutInfo, methodInfo, executionContext, methodCanceledMessageFormat, methodTimedOutMessageFormat, testTimeoutInfo).GetAwaiter().GetResult(); + + internal static async Task RunWithTimeoutAndCancellationAsync( + Func action, CancellationTokenSource cancellationTokenSource, TimeoutInfo? timeoutInfo, MethodInfo methodInfo, + ExecutionContext? executionContext, string methodCanceledMessageFormat, string methodTimedOutMessageFormat, + // When a test method is marked with [Timeout], this timeout is applied from ctor to destructor, so we need to take + // that into account when processing the OCE of the action. (CancellationTokenSource TokenSource, int Timeout)? testTimeoutInfo = default) { if (cancellationTokenSource.Token.IsCancellationRequested) @@ -31,7 +44,7 @@ internal static class FixtureMethodRunner { try { - ExecutionContextHelpers.RunOnContext(executionContext, action); + await ExecutionContextHelpers.RunOnContextAsync(executionContext, action).ConfigureAwait(false); return null; } catch (Exception ex) @@ -56,7 +69,8 @@ internal static class FixtureMethodRunner if (timeoutInfo.Value.CooperativeCancellation) { - return RunWithCooperativeCancellation(action, executionContext, cancellationTokenSource, timeoutInfo.Value.Timeout, methodInfo, methodCanceledMessageFormat, methodTimedOutMessageFormat); + return await RunWithCooperativeCancellationAsync( + action, executionContext, cancellationTokenSource, timeoutInfo.Value.Timeout, methodInfo, methodCanceledMessageFormat, methodTimedOutMessageFormat).ConfigureAwait(false); } // We need to start a thread to handle "cancellation" and "timeout" scenarios. @@ -65,7 +79,7 @@ internal static class FixtureMethodRunner : RunWithTimeoutAndCancellationWithThreadPool(action, executionContext, cancellationTokenSource, timeoutInfo.Value.Timeout, methodInfo, methodCanceledMessageFormat, methodTimedOutMessageFormat); } - private static TestFailedException? RunWithCooperativeCancellation(Action action, ExecutionContext? executionContext, CancellationTokenSource cancellationTokenSource, int timeout, MethodInfo methodInfo, string methodCanceledMessageFormat, string methodTimedOutMessageFormat) + private static async Task RunWithCooperativeCancellationAsync(Func action, ExecutionContext? executionContext, CancellationTokenSource cancellationTokenSource, int timeout, MethodInfo methodInfo, string methodCanceledMessageFormat, string methodTimedOutMessageFormat) { CancellationTokenSource? timeoutTokenSource = null; try @@ -86,7 +100,7 @@ internal static class FixtureMethodRunner try { - ExecutionContextHelpers.RunOnContext(executionContext, action); + await ExecutionContextHelpers.RunOnContextAsync(executionContext, action).ConfigureAwait(false); return null; } catch (Exception ex) when (ex.IsOperationCanceledExceptionFromToken(cancellationTokenSource.Token)) @@ -116,7 +130,7 @@ internal static class FixtureMethodRunner } private static TestFailedException? RunWithTimeoutAndCancellationWithThreadPool( - Action action, ExecutionContext? executionContext, CancellationTokenSource cancellationTokenSource, int timeout, MethodInfo methodInfo, + Func action, ExecutionContext? executionContext, CancellationTokenSource cancellationTokenSource, int timeout, MethodInfo methodInfo, string methodCanceledMessageFormat, string methodTimedOutMessageFormat) { Exception? realException = null; @@ -128,7 +142,7 @@ internal static class FixtureMethodRunner { try { - ExecutionContextHelpers.RunOnContext(executionContext, action); + ExecutionContextHelpers.RunOnContextAsync(executionContext, action).GetAwaiter().GetResult(); } catch (Exception ex) { @@ -177,7 +191,7 @@ internal static class FixtureMethodRunner [SupportedOSPlatform("windows")] private static TestFailedException? RunWithTimeoutAndCancellationWithSTAThread( - Action action, ExecutionContext? executionContext, CancellationTokenSource cancellationTokenSource, int timeout, MethodInfo methodInfo, + Func action, ExecutionContext? executionContext, CancellationTokenSource cancellationTokenSource, int timeout, MethodInfo methodInfo, string methodCanceledMessageFormat, string methodTimedOutMessageFormat) { TaskCompletionSource tcs = new(); @@ -186,7 +200,7 @@ internal static class FixtureMethodRunner { try { - ExecutionContextHelpers.RunOnContext(executionContext, action); + ExecutionContextHelpers.RunOnContextAsync(executionContext, action).GetAwaiter().GetResult(); tcs.SetResult(0); } catch (Exception ex) diff --git a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/DeadlockTests.cs b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/DeadlockTests.cs new file mode 100644 index 0000000000..acf2d4f64d --- /dev/null +++ b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/DeadlockTests.cs @@ -0,0 +1,160 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using Microsoft.Testing.Platform.Acceptance.IntegrationTests; +using Microsoft.Testing.Platform.Acceptance.IntegrationTests.Helpers; + +namespace MSTest.Acceptance.IntegrationTests; + +[TestClass] +public sealed class DeadlockTests : AcceptanceTestBase +{ + [TestMethod] + [DynamicData(nameof(TargetFrameworks.AllForDynamicData), typeof(TargetFrameworks))] + public async Task DeadlockCaseClassCleanupWaitingOnTestMethod(string tfm) + { + var testHost = TestHost.LocateFrom(AssetFixture.ProjectPath, TestAssetFixture.ProjectName, tfm); + TestHostResult testHostResult = await testHost.ExecuteAsync("--filter FullyQualifiedName~DeadlockCase1", cancellationToken: TestContext.CancellationToken); + + testHostResult.AssertExitCodeIs(0); + testHostResult.AssertOutputContainsSummary(failed: 0, passed: 1, skipped: 0); + } + + [TestMethod] + [DynamicData(nameof(TargetFrameworks.AllForDynamicData), typeof(TargetFrameworks))] + public async Task DeadlockCaseClassInitWaitingOnPreviousTestMethod(string tfm) + { + var testHost = TestHost.LocateFrom(AssetFixture.ProjectPath, TestAssetFixture.ProjectName, tfm); + TestHostResult testHostResult = await testHost.ExecuteAsync("--filter FullyQualifiedName~DeadlockCase2", cancellationToken: TestContext.CancellationToken); + + testHostResult.AssertExitCodeIs(0); + testHostResult.AssertOutputContainsSummary(failed: 0, passed: 2, skipped: 0); + } + + public sealed class TestAssetFixture() : TestAssetFixtureBase(AcceptanceFixture.NuGetGlobalPackagesFolder) + { + public const string ProjectName = "DeadlockTests"; + + public string ProjectPath => GetAssetPath(ProjectName); + + public override IEnumerable<(string ID, string Name, string Code)> GetAssetsToGenerate() + { + yield return (ProjectName, ProjectName, + SourceCode + .PatchTargetFrameworks(TargetFrameworks.All) + .PatchCodeWithReplace("$MSTestVersion$", MSTestVersion)); + } + + private const string SourceCode = """ +#file DeadlockTests.csproj + + + + Exe + true + $TargetFrameworks$ + preview + + + true + + + + + + + + +#file UnitTest1.cs +using System; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +[TestClass] +public class DeadlockCase1 +{ + // This repro is intended to deadlock when Test1 is called asynchronously like await Test1(), but then ClassCleanup is called with GetAwaiter().GetResult(). + // When await Test1() is called, we return a Task that will complete in ~1second on a custom thread we created. + // After that Task completes, the continuation will run on that exact same custom thread. + // If the continuation calls ClassCleanup().GetAwaiter().GetResult(), then we are blocking that custom thread waiting for ClassCleanup to complete. + // But ClassCleanup cannot complete until that custom thread calls _cts.SetResult(), which it cannot do because it is blocked waiting for ClassCleanup to complete. + // So we deadlock. + // This repro is related to https://github.com/microsoft/testfx/issues/6575 + private static TaskCompletionSource _cts = new(); + + [ClassCleanup(ClassCleanupBehavior.EndOfClass)] + public static async Task ClassCleanup() + { + await _cts.Task; + } + + [TestMethod] + public async Task Test1() + { + var cts1 = new TaskCompletionSource(); + var t = new Thread(() => + { + Thread.Sleep(1000); + cts1.SetResult(null); + Thread.Sleep(1000); + _cts.SetResult(null); + }); + t.Start(); + await cts1.Task; + } +} + +[TestClass] +public class DeadlockCase2 +{ + // This repro is intended to deadlock when Test1 is called asynchronously like await Test1(), but then TestInit (the invocation before Test2 and after Test1) is called with GetAwaiter().GetResult(). + // When await Test1() is called, we return a Task that will complete in ~1second on a custom thread we created. + // After that Task completes, the continuation will run on that exact same custom thread. + // If the continuation calls TestInit().GetAwaiter().GetResult(), then we are blocking that custom thread waiting for TestInit to complete. + // But TestInit cannot complete until that custom thread calls _cts.SetResult(), which it cannot do because it is blocked waiting for TestInit to complete. + // So we deadlock. + // This repro is related to https://github.com/microsoft/testfx/issues/6575 + private static TaskCompletionSource _cts = new(); + + public TestContext TestContext { get; set; } + + [TestInitialize] + public async Task TestInit() + { + if (TestContext.TestName == nameof(Test2)) + { + await _cts.Task; + } + } + + [TestMethod] + public async Task Test1() + { + var cts1 = new TaskCompletionSource(); + var t = new Thread(() => + { + Thread.Sleep(1000); + cts1.SetResult(null); + Thread.Sleep(1000); + _cts.SetResult(null); + }); + t.Start(); + await cts1.Task; + } + + [TestMethod] + public void Test2() + { + } +} + +"""; + } + + public TestContext TestContext { get; set; } +} diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestClassInfoTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestClassInfoTests.cs index 9242df3d9f..eaf89b0c38 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestClassInfoTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestClassInfoTests.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.Threading.Tasks; + using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution; using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel; using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; @@ -123,7 +125,7 @@ void Action() VerifyThrows(Action); } - public void TestClassInfoClassCleanupMethodShouldNotInvokeWhenNoTestClassInitializedIsCalled() + public async Task TestClassInfoClassCleanupMethodShouldNotInvokeWhenNoTestClassInitializedIsCalled() { int classCleanupCallCount = 0; DummyTestClass.ClassCleanupMethodBody = () => classCleanupCallCount++; @@ -131,12 +133,12 @@ public void TestClassInfoClassCleanupMethodShouldNotInvokeWhenNoTestClassInitial _testClassInfo.ClassCleanupMethod = typeof(DummyTestClass).GetMethod("ClassCleanupMethod")!; _testClassInfo.ClassInitializeMethod = typeof(DummyTestClass).GetMethod("ClassInitializeMethod")!; - TestFailedException? ex = _testClassInfo.ExecuteClassCleanup(new TestContextImplementation(null, new StringWriter(), new Dictionary())); // call cleanup without calling init + TestFailedException? ex = await _testClassInfo.ExecuteClassCleanupAsync(new TestContextImplementation(null, new StringWriter(), new Dictionary())); // call cleanup without calling init Verify(ex is null); Verify(classCleanupCallCount == 0); } - public void TestClassInfoClassCleanupMethodShouldInvokeWhenTestClassInitializedIsCalled() + public async Task TestClassInfoClassCleanupMethodShouldInvokeWhenTestClassInitializedIsCalled() { int classCleanupCallCount = 0; DummyTestClass.ClassCleanupMethodBody = () => classCleanupCallCount++; @@ -145,13 +147,13 @@ public void TestClassInfoClassCleanupMethodShouldInvokeWhenTestClassInitializedI _testClassInfo.ClassInitializeMethod = typeof(DummyTestClass).GetMethod("ClassInitializeMethod")!; GetResultOrRunClassInitialize(); - TestFailedException? ex = _testClassInfo.ExecuteClassCleanup(new TestContextImplementation(null, new StringWriter(), new Dictionary())); // call cleanup without calling init + TestFailedException? ex = await _testClassInfo.ExecuteClassCleanupAsync(new TestContextImplementation(null, new StringWriter(), new Dictionary())); // call cleanup without calling init Verify(ex is null); Verify(classCleanupCallCount == 1); } - public void TestClassInfoClassCleanupMethodShouldInvokeBaseClassCleanupMethodWhenTestClassInitializedIsCalled() + public async Task TestClassInfoClassCleanupMethodShouldInvokeBaseClassCleanupMethodWhenTestClassInitializedIsCalled() { int classCleanupCallCount = 0; DummyBaseTestClass.ClassCleanupMethodBody = () => classCleanupCallCount++; @@ -160,7 +162,7 @@ public void TestClassInfoClassCleanupMethodShouldInvokeBaseClassCleanupMethodWhe _testClassInfo.BaseClassCleanupMethods.Add(typeof(DummyBaseTestClass).GetMethod("CleanupClassMethod")!); GetResultOrRunClassInitialize(); - TestFailedException? ex = _testClassInfo.ExecuteClassCleanup(new TestContextImplementation(null, new StringWriter(), new Dictionary())); + TestFailedException? ex = await _testClassInfo.ExecuteClassCleanupAsync(new TestContextImplementation(null, new StringWriter(), new Dictionary())); Verify(ex is null); Verify(classCleanupCallCount == 1); @@ -450,12 +452,12 @@ private TestResult GetResultOrRunClassInitialize() => GetResultOrRunClassInitialize(_testContext); private TestResult GetResultOrRunClassInitialize(TestContext? testContext) - => _testClassInfo.GetResultOrRunClassInitialize(new TestTestContextImpl(testContext!), string.Empty, string.Empty, string.Empty, string.Empty); + => _testClassInfo.GetResultOrRunClassInitializeAsync(new TestTestContextImpl(testContext!), string.Empty, string.Empty, string.Empty, string.Empty).GetAwaiter().GetResult(); #endregion #region Run Class Cleanup tests - public void RunClassCleanupShouldInvokeIfClassCleanupMethod() + public async Task RunClassCleanupShouldInvokeIfClassCleanupMethod() { // Arrange int classCleanupCallCount = 0; @@ -464,14 +466,14 @@ public void RunClassCleanupShouldInvokeIfClassCleanupMethod() // Act GetResultOrRunClassInitialize(null); - TestFailedException? ex = _testClassInfo.ExecuteClassCleanup(new TestContextImplementation(null, new StringWriter(), new Dictionary())); + TestFailedException? ex = await _testClassInfo.ExecuteClassCleanupAsync(new TestContextImplementation(null, new StringWriter(), new Dictionary())); // Assert Verify(ex is null); Verify(classCleanupCallCount == 1); } - public void RunClassCleanupShouldNotInvokeIfClassCleanupIsNull() + public async Task RunClassCleanupShouldNotInvokeIfClassCleanupIsNull() { // Arrange int classCleanupCallCount = 0; @@ -479,14 +481,14 @@ public void RunClassCleanupShouldNotInvokeIfClassCleanupIsNull() _testClassInfo.ClassCleanupMethod = null; // Act - TestFailedException? ex = _testClassInfo.ExecuteClassCleanup(new TestContextImplementation(null, new StringWriter(), new Dictionary())); + TestFailedException? ex = await _testClassInfo.ExecuteClassCleanupAsync(new TestContextImplementation(null, new StringWriter(), new Dictionary())); // Assert Verify(ex is null); Verify(classCleanupCallCount == 0); } - public void RunClassCleanupShouldReturnAssertFailureExceptionDetails() + public async Task RunClassCleanupShouldReturnAssertFailureExceptionDetails() { // Arrange DummyTestClass.ClassCleanupMethodBody = () => UTF.Assert.Fail("Test Failure"); @@ -494,7 +496,7 @@ public void RunClassCleanupShouldReturnAssertFailureExceptionDetails() // Act GetResultOrRunClassInitialize(null); - TestFailedException? classCleanupException = _testClassInfo.ExecuteClassCleanup(new TestContextImplementation(null, new StringWriter(), new Dictionary())); + TestFailedException? classCleanupException = await _testClassInfo.ExecuteClassCleanupAsync(new TestContextImplementation(null, new StringWriter(), new Dictionary())); // Assert Verify(classCleanupException is not null); @@ -508,7 +510,7 @@ public void RunClassCleanupShouldReturnAssertFailureExceptionDetails() #endif } - public void RunClassCleanupShouldReturnAssertInconclusiveExceptionDetails() + public async Task RunClassCleanupShouldReturnAssertInconclusiveExceptionDetails() { // Arrange DummyTestClass.ClassCleanupMethodBody = () => UTF.Assert.Inconclusive("Test Inconclusive"); @@ -516,7 +518,7 @@ public void RunClassCleanupShouldReturnAssertInconclusiveExceptionDetails() // Act GetResultOrRunClassInitialize(null); - TestFailedException? classCleanupException = _testClassInfo.ExecuteClassCleanup(new TestContextImplementation(null, new StringWriter(), new Dictionary())); + TestFailedException? classCleanupException = await _testClassInfo.ExecuteClassCleanupAsync(new TestContextImplementation(null, new StringWriter(), new Dictionary())); // Assert Verify(classCleanupException is not null); @@ -529,7 +531,7 @@ public void RunClassCleanupShouldReturnAssertInconclusiveExceptionDetails() #endif } - public void RunClassCleanupShouldReturnExceptionDetailsOfNonAssertExceptions() + public async Task RunClassCleanupShouldReturnExceptionDetailsOfNonAssertExceptions() { // Arrange DummyTestClass.ClassCleanupMethodBody = () => throw new ArgumentException("Argument Exception"); @@ -537,7 +539,7 @@ public void RunClassCleanupShouldReturnExceptionDetailsOfNonAssertExceptions() // Act GetResultOrRunClassInitialize(null); - TestFailedException? classCleanupException = _testClassInfo.ExecuteClassCleanup(new TestContextImplementation(null, new StringWriter(), new Dictionary())); + TestFailedException? classCleanupException = await _testClassInfo.ExecuteClassCleanupAsync(new TestContextImplementation(null, new StringWriter(), new Dictionary())); // Assert Verify(classCleanupException is not null); @@ -546,7 +548,7 @@ public void RunClassCleanupShouldReturnExceptionDetailsOfNonAssertExceptions() Verify(classCleanupException.Message.Contains($"{typeof(TestClassInfoTests).FullName}.<>c.<{nameof(this.RunClassCleanupShouldReturnExceptionDetailsOfNonAssertExceptions)}>")); } - public void RunBaseClassCleanupWithNoDerivedClassCleanupShouldReturnExceptionDetailsOfNonAssertExceptions() + public async Task RunBaseClassCleanupWithNoDerivedClassCleanupShouldReturnExceptionDetailsOfNonAssertExceptions() { // Arrange DummyBaseTestClass.ClassCleanupMethodBody = () => throw new ArgumentException("Argument Exception"); @@ -556,7 +558,7 @@ public void RunBaseClassCleanupWithNoDerivedClassCleanupShouldReturnExceptionDet // Act GetResultOrRunClassInitialize(null); - TestFailedException? classCleanupException = _testClassInfo.ExecuteClassCleanup(new TestContextImplementation(null, new StringWriter(), new Dictionary())); + TestFailedException? classCleanupException = await _testClassInfo.ExecuteClassCleanupAsync(new TestContextImplementation(null, new StringWriter(), new Dictionary())); // Assert Verify(classCleanupException is not null); @@ -565,7 +567,7 @@ public void RunBaseClassCleanupWithNoDerivedClassCleanupShouldReturnExceptionDet Verify(classCleanupException.Message.Contains($"{typeof(TestClassInfoTests).FullName}.<>c.<{nameof(this.RunBaseClassCleanupWithNoDerivedClassCleanupShouldReturnExceptionDetailsOfNonAssertExceptions)}>")); } - public void RunBaseClassCleanupEvenIfThereIsNoDerivedClassCleanup() + public async Task RunBaseClassCleanupEvenIfThereIsNoDerivedClassCleanup() { // Arrange int classCleanupCallCount = 0; @@ -575,7 +577,7 @@ public void RunBaseClassCleanupEvenIfThereIsNoDerivedClassCleanup() _testClassInfo.BaseClassCleanupMethods.Add(baseClassCleanupMethod); // Act - TestFailedException? ex = _testClassInfo.ExecuteClassCleanup(new TestContextImplementation(null, new StringWriter(), new Dictionary())); + TestFailedException? ex = await _testClassInfo.ExecuteClassCleanupAsync(new TestContextImplementation(null, new StringWriter(), new Dictionary())); // Assert Verify(ex is null); @@ -584,7 +586,7 @@ public void RunBaseClassCleanupEvenIfThereIsNoDerivedClassCleanup() // Act 2 GetResultOrRunClassInitialize(null); - ex = _testClassInfo.ExecuteClassCleanup(new TestContextImplementation(null, new StringWriter(), new Dictionary())); + ex = await _testClassInfo.ExecuteClassCleanupAsync(new TestContextImplementation(null, new StringWriter(), new Dictionary())); // Assert 2 Verify(ex is null); @@ -593,7 +595,7 @@ public void RunBaseClassCleanupEvenIfThereIsNoDerivedClassCleanup() Verify(classCleanupCallCount == 1, "DummyBaseTestClass.CleanupClassMethod call count"); // Act 3 - ex = _testClassInfo.ExecuteClassCleanup(new TestContextImplementation(null, new StringWriter(), new Dictionary())); + ex = await _testClassInfo.ExecuteClassCleanupAsync(new TestContextImplementation(null, new StringWriter(), new Dictionary())); // Assert 3 Verify(ex is null); @@ -601,7 +603,7 @@ public void RunBaseClassCleanupEvenIfThereIsNoDerivedClassCleanup() Verify(classCleanupCallCount == 1, "DummyBaseTestClass.CleanupClassMethod call count"); } - public void RunClassCleanupShouldThrowTheInnerMostExceptionWhenThereAreMultipleNestedTypeInitializationExceptions() + public async Task RunClassCleanupShouldThrowTheInnerMostExceptionWhenThereAreMultipleNestedTypeInitializationExceptions() { // This helper calls inner helper, and the inner helper ctor throws. // We want to see the real exception on screen, and not TypeInitializationException @@ -610,7 +612,7 @@ public void RunClassCleanupShouldThrowTheInnerMostExceptionWhenThereAreMultipleN _testClassInfo.ClassCleanupMethod = typeof(DummyTestClass).GetMethod("ClassCleanupMethod")!; GetResultOrRunClassInitialize(null); - TestFailedException? classCleanupException = _testClassInfo.ExecuteClassCleanup(new TestContextImplementation(null, new StringWriter(), new Dictionary())); + TestFailedException? classCleanupException = await _testClassInfo.ExecuteClassCleanupAsync(new TestContextImplementation(null, new StringWriter(), new Dictionary())); Verify(classCleanupException is not null); Verify(classCleanupException.Message.StartsWith("Class Cleanup method DummyTestClass.ClassCleanupMethod failed. Error Message: System.InvalidOperationException: I fail..", StringComparison.Ordinal)); From 60dfd889d726b22e55a70153a4226782d0f0992d Mon Sep 17 00:00:00 2001 From: Copilot <198982749+Copilot@users.noreply.github.com> Date: Tue, 23 Sep 2025 17:40:53 +0200 Subject: [PATCH 512/541] Implement discovery indicator fixes - show neutral progress colors and error for zero tests (#6579) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: nohwnd <5735905+nohwnd@users.noreply.github.com> Co-authored-by: Jakub Jareš --- .../Terminal/AnsiTerminalTestProgressFrame.cs | 84 +++++++++++-------- .../Terminal/SimpleTerminalBase.cs | 60 ++++++++----- .../Terminal/TerminalTestReporter.cs | 11 +-- .../Terminal/TestProgressState.cs | 7 +- .../Terminal/TerminalTestReporterTests.cs | 58 +++++++++++++ 5 files changed, 159 insertions(+), 61 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/AnsiTerminalTestProgressFrame.cs b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/AnsiTerminalTestProgressFrame.cs index 272e73c412..85606f5b0c 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/AnsiTerminalTestProgressFrame.cs +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/AnsiTerminalTestProgressFrame.cs @@ -30,44 +30,62 @@ public void AppendTestWorkerProgress(TestProgressState progress, RenderedProgres int nonReservedWidth = Width - (durationString.Length + 2); + int discovered = progress.DiscoveredTests; int passed = progress.PassedTests; int failed = progress.FailedTests; int skipped = progress.SkippedTests; int charsTaken = 0; - terminal.Append('['); - charsTaken++; - terminal.SetColor(TerminalColor.DarkGreen); - terminal.Append('✓'); - charsTaken++; - string passedText = passed.ToString(CultureInfo.CurrentCulture); - terminal.Append(passedText); - charsTaken += passedText.Length; - terminal.ResetColor(); - - terminal.Append('/'); - charsTaken++; - - terminal.SetColor(TerminalColor.DarkRed); - terminal.Append('x'); - charsTaken++; - string failedText = failed.ToString(CultureInfo.CurrentCulture); - terminal.Append(failedText); - charsTaken += failedText.Length; - terminal.ResetColor(); - - terminal.Append('/'); - charsTaken++; - - terminal.SetColor(TerminalColor.DarkYellow); - terminal.Append('↓'); - charsTaken++; - string skippedText = skipped.ToString(CultureInfo.CurrentCulture); - terminal.Append(skippedText); - charsTaken += skippedText.Length; - terminal.ResetColor(); - terminal.Append(']'); - charsTaken++; + if (!progress.IsDiscovery) + { + terminal.Append('['); + charsTaken++; + terminal.SetColor(TerminalColor.DarkGreen); + terminal.Append('✓'); + charsTaken++; + string passedText = passed.ToString(CultureInfo.CurrentCulture); + terminal.Append(passedText); + charsTaken += passedText.Length; + terminal.ResetColor(); + + terminal.Append('/'); + charsTaken++; + + terminal.SetColor(TerminalColor.DarkRed); + terminal.Append('x'); + charsTaken++; + string failedText = failed.ToString(CultureInfo.CurrentCulture); + terminal.Append(failedText); + charsTaken += failedText.Length; + terminal.ResetColor(); + + terminal.Append('/'); + charsTaken++; + + terminal.SetColor(TerminalColor.DarkYellow); + terminal.Append('↓'); + charsTaken++; + string skippedText = skipped.ToString(CultureInfo.CurrentCulture); + terminal.Append(skippedText); + charsTaken += skippedText.Length; + terminal.ResetColor(); + terminal.Append(']'); + charsTaken++; + } + else + { + string discoveredText = discovered.ToString(CultureInfo.CurrentCulture); + terminal.Append('['); + charsTaken++; + terminal.SetColor(TerminalColor.DarkMagenta); + terminal.Append('+'); + charsTaken++; + terminal.Append(discoveredText); + charsTaken += discoveredText.Length; + terminal.ResetColor(); + terminal.Append(']'); + charsTaken++; + } terminal.Append(' '); charsTaken++; diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/SimpleTerminalBase.cs b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/SimpleTerminalBase.cs index aefad9bc28..a4620f0df4 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/SimpleTerminalBase.cs +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/SimpleTerminalBase.cs @@ -66,32 +66,48 @@ public void RenderProgress(TestProgressState?[] progress) string durationString = HumanReadableDurationFormatter.Render(p.Stopwatch.Elapsed); + int discovered = p.DiscoveredTests; int passed = p.PassedTests; int failed = p.FailedTests; int skipped = p.SkippedTests; - // Use just ascii here, so we don't put too many restrictions on fonts needing to - // properly show unicode, or logs being saved in particular encoding. - Append('['); - SetColor(TerminalColor.DarkGreen); - Append('+'); - Append(passed.ToString(CultureInfo.CurrentCulture)); - ResetColor(); - - Append('/'); - - SetColor(TerminalColor.DarkRed); - Append('x'); - Append(failed.ToString(CultureInfo.CurrentCulture)); - ResetColor(); - - Append('/'); - - SetColor(TerminalColor.DarkYellow); - Append('?'); - Append(skipped.ToString(CultureInfo.CurrentCulture)); - ResetColor(); - Append(']'); + if (!p.IsDiscovery) + { + // Use just ascii here, so we don't put too many restrictions on fonts needing to + // properly show unicode, or logs being saved in particular encoding. + Append('['); + SetColor(TerminalColor.DarkGreen); + Append('+'); + Append(passed.ToString(CultureInfo.CurrentCulture)); + ResetColor(); + + Append('/'); + + SetColor(TerminalColor.DarkRed); + Append('x'); + Append(failed.ToString(CultureInfo.CurrentCulture)); + ResetColor(); + + Append('/'); + + SetColor(TerminalColor.DarkYellow); + Append('?'); + Append(skipped.ToString(CultureInfo.CurrentCulture)); + ResetColor(); + Append(']'); + } + else + { + // Use just ascii here, so we don't put too many restrictions on fonts needing to + // properly show unicode, or logs being saved in particular encoding. + Append('['); + SetColor(TerminalColor.DarkMagenta); + Append('+'); + Append(discovered.ToString(CultureInfo.CurrentCulture)); + ResetColor(); + + Append(']'); + } Append(' '); Append(p.AssemblyName); diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporter.cs b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporter.cs index c70b141823..9432a79e97 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporter.cs +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporter.cs @@ -143,7 +143,7 @@ private TestProgressState GetOrAddAssemblyRun() } IStopwatch sw = CreateStopwatch(); - var assemblyRun = new TestProgressState(Interlocked.Increment(ref _counter), _assembly, _targetFramework, _architecture, sw); + var assemblyRun = new TestProgressState(Interlocked.Increment(ref _counter), _assembly, _targetFramework, _architecture, sw, _isDiscovery); int slotIndex = _terminalWithProgress.AddWorker(assemblyRun); assemblyRun.SlotIndex = slotIndex; _testProgressState = assemblyRun; @@ -840,11 +840,12 @@ internal void TestDiscovered(string displayName) } TestProgressState asm = _testProgressState; + asm.DiscoveredTests++; + if (_isDiscovery) { - // TODO: add mode for discovered tests to the progress bar, to get rid of the hack here that allows updating the - // progress, but also breaks the total counts if not done only in discovery. - asm.PassedTests++; + // In discovery mode we count discovered tests, + // but in execution mode the completion of test will increase the total tests count. asm.TotalTests++; } @@ -859,7 +860,7 @@ public void AppendTestDiscoverySummary(ITerminal terminal) terminal.AppendLine(); int totalTests = assembly?.TotalTests ?? 0; - bool runFailed = WasCancelled; + bool runFailed = WasCancelled || totalTests < 1; if (assembly is not null) { diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TestProgressState.cs b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TestProgressState.cs index 5cccaafa99..489654cc0e 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TestProgressState.cs +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TestProgressState.cs @@ -7,7 +7,7 @@ namespace Microsoft.Testing.Platform.OutputDevice.Terminal; internal sealed class TestProgressState { - public TestProgressState(long id, string assembly, string? targetFramework, string? architecture, IStopwatch stopwatch) + public TestProgressState(long id, string assembly, string? targetFramework, string? architecture, IStopwatch stopwatch, bool isDiscovery) { Id = id; Assembly = assembly; @@ -15,6 +15,7 @@ public TestProgressState(long id, string assembly, string? targetFramework, stri Architecture = architecture; Stopwatch = stopwatch; AssemblyName = Path.GetFileName(assembly)!; + IsDiscovery = isDiscovery; } public string Assembly { get; } @@ -27,6 +28,8 @@ public TestProgressState(long id, string assembly, string? targetFramework, stri public IStopwatch Stopwatch { get; } + public int DiscoveredTests { get; internal set; } + public List Messages { get; } = []; public int FailedTests { get; internal set; } @@ -47,6 +50,8 @@ public TestProgressState(long id, string assembly, string? targetFramework, stri public List DiscoveredTestDisplayNames { get; internal set; } = []; + public bool IsDiscovery { get; } + internal void AddError(string text) => Messages.Add(new ErrorMessage(text)); diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/OutputDevice/Terminal/TerminalTestReporterTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/OutputDevice/Terminal/TerminalTestReporterTests.cs index 05299af231..2ed465160d 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/OutputDevice/Terminal/TerminalTestReporterTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/OutputDevice/Terminal/TerminalTestReporterTests.cs @@ -755,4 +755,62 @@ public void TestDiscovery_WithControlCharacters_AreNormalized(char controlChar, Assert.DoesNotContain(literalDisplayName, output, $"Literal {charName} should not be present in test display name"); } } + + [TestMethod] + public void TestProgressState_WhenCreatedWithDiscoveryTrue_ShouldHaveIsDiscoveryTrue() + { + // Arrange + var stopwatch = new StopwatchFactory.MockStopwatch(new StopwatchFactory(), TimeSpan.Zero); + + // Act + var progressState = new TestProgressState(1, "test.dll", "net8.0", "x64", stopwatch, isDiscovery: true); + + // Assert + Assert.IsTrue(progressState.IsDiscovery); + Assert.AreEqual(0, progressState.DiscoveredTests); + } + + [TestMethod] + public void TestProgressState_WhenCreatedWithFalseIsDiscoveryParameter_ShouldHaveIsDiscoveryFalse() + { + // Arrange + var stopwatch = new StopwatchFactory.MockStopwatch(new StopwatchFactory(), TimeSpan.Zero); + + // Act + var progressState = new TestProgressState(1, "test.dll", "net8.0", "x64", stopwatch, isDiscovery: false); + + // Assert + Assert.IsFalse(progressState.IsDiscovery); + Assert.AreEqual(0, progressState.DiscoveredTests); + } + + [TestMethod] + public void TerminalTestReporter_WhenInDiscoveryMode_ShouldIncrementDiscoveredTests() + { + // Arrange + string assembly = "test.dll"; + var stringBuilderConsole = new StringBuilderConsole(); + var terminalReporter = new TerminalTestReporter(assembly, "net8.0", "x64", stringBuilderConsole, new CTRLPlusCCancellationTokenSource(), new TerminalTestReporterOptions + { + ShowPassedTests = () => false, + UseAnsi = false, + ShowProgress = () => false, + }); + + DateTimeOffset startTime = DateTimeOffset.MinValue; + DateTimeOffset endTime = DateTimeOffset.MaxValue; + + // Act + terminalReporter.TestExecutionStarted(startTime, 1, isDiscovery: true); + terminalReporter.AssemblyRunStarted(); + terminalReporter.TestDiscovered("TestMethod1"); + terminalReporter.TestDiscovered("TestMethod2"); + terminalReporter.AssemblyRunCompleted(); + terminalReporter.TestExecutionCompleted(endTime); + + string output = stringBuilderConsole.Output; + + // Assert - should contain information about 2 tests discovered + Assert.IsTrue(output.Contains('2') || output.Contains("TestMethod1"), "Output should contain information about discovered tests"); + } } From a6a292e65f4ed553236cb1ff028a0bfbfc51944d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Jare=C5=A1?= Date: Wed, 24 Sep 2025 08:48:21 +0200 Subject: [PATCH 513/541] Fix typo in protocol introduction (#6588) --- docs/mstest-runner-protocol/001-protocol-intro.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/mstest-runner-protocol/001-protocol-intro.md b/docs/mstest-runner-protocol/001-protocol-intro.md index 5f2d04539c..071933eb2e 100644 --- a/docs/mstest-runner-protocol/001-protocol-intro.md +++ b/docs/mstest-runner-protocol/001-protocol-intro.md @@ -1,7 +1,7 @@ # 001 - MSTest Runner Protocol MSTest Runner projects builds into a self-contained executable that can be invoked to run tests. -The protocol describes the communication between the client (IDE/CLI/CI) any the MSTest Runner executable (also refered to as the server). +The protocol describes the communication between the client (IDE/CLI/CI) and the MSTest Runner executable (also refered to as the server). The communication is based on JSON-RPC and describes the RPC messages sent in order to support running of tests. From 9086d5ea5fce06fdd36dc44e5c84d282783d79f8 Mon Sep 17 00:00:00 2001 From: Muiz Atolagbe <46275427+AtolagbeMuiz@users.noreply.github.com> Date: Wed, 24 Sep 2025 07:59:41 +0100 Subject: [PATCH 514/541] Is subsetof return non subset values of the superset (relates to #662) (#6292) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Jakub Jareš --- Directory.Packages.props | 1 - .../Assertions/CollectionAssert.cs | 35 ++++-- .../Resources/FrameworkMessages.resx | 3 + .../Resources/xlf/FrameworkMessages.cs.xlf | 5 + .../Resources/xlf/FrameworkMessages.de.xlf | 5 + .../Resources/xlf/FrameworkMessages.es.xlf | 5 + .../Resources/xlf/FrameworkMessages.fr.xlf | 5 + .../Resources/xlf/FrameworkMessages.it.xlf | 5 + .../Resources/xlf/FrameworkMessages.ja.xlf | 5 + .../Resources/xlf/FrameworkMessages.ko.xlf | 5 + .../Resources/xlf/FrameworkMessages.pl.xlf | 5 + .../Resources/xlf/FrameworkMessages.pt-BR.xlf | 5 + .../Resources/xlf/FrameworkMessages.ru.xlf | 5 + .../Resources/xlf/FrameworkMessages.tr.xlf | 5 + .../xlf/FrameworkMessages.zh-Hans.xlf | 5 + .../xlf/FrameworkMessages.zh-Hant.xlf | 5 + .../Assertions/CollectionAssertTests.cs | 105 ++++++++++++------ 17 files changed, 169 insertions(+), 40 deletions(-) diff --git a/Directory.Packages.props b/Directory.Packages.props index bdb6f86c35..b0d823d309 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -65,7 +65,6 @@ - diff --git a/src/TestFramework/TestFramework/Assertions/CollectionAssert.cs b/src/TestFramework/TestFramework/Assertions/CollectionAssert.cs index bc8104a47c..f96ef84443 100644 --- a/src/TestFramework/TestFramework/Assertions/CollectionAssert.cs +++ b/src/TestFramework/TestFramework/Assertions/CollectionAssert.cs @@ -418,9 +418,13 @@ public static void IsSubsetOf([NotNull] ICollection? subset, [NotNull] ICollecti { Assert.CheckParameterNotNull(subset, "CollectionAssert.IsSubsetOf", "subset", string.Empty); Assert.CheckParameterNotNull(superset, "CollectionAssert.IsSubsetOf", "superset", string.Empty); - if (!IsSubsetOfHelper(subset, superset)) + Tuple> isSubsetValue = IsSubsetOfHelper(subset, superset); + if (!isSubsetValue.Item1) { - Assert.ThrowAssertFailed("CollectionAssert.IsSubsetOf", Assert.BuildUserMessage(message, parameters)); + string returnedSubsetValueMessage = string.Join(", ", isSubsetValue.Item2.Select(item => Convert.ToString(item, CultureInfo.InvariantCulture))); + + returnedSubsetValueMessage = string.Format(CultureInfo.InvariantCulture, FrameworkMessages.ReturnedSubsetValueMessage, returnedSubsetValueMessage.Trim()); + Assert.ThrowAssertFailed("CollectionAssert.IsSubsetOf", returnedSubsetValueMessage); } } @@ -493,7 +497,8 @@ public static void IsNotSubsetOf([NotNull] ICollection? subset, [NotNull] IColle { Assert.CheckParameterNotNull(subset, "CollectionAssert.IsNotSubsetOf", "subset", string.Empty); Assert.CheckParameterNotNull(superset, "CollectionAssert.IsNotSubsetOf", "superset", string.Empty); - if (IsSubsetOfHelper(subset, superset)) + Tuple> isSubsetValue = IsSubsetOfHelper(subset, superset); + if (isSubsetValue.Item1) { Assert.ThrowAssertFailed("CollectionAssert.IsNotSubsetOf", Assert.BuildUserMessage(message, parameters)); } @@ -1438,21 +1443,30 @@ public static void AreNotEqual(ICollection? notExpected, ICollection? actual, [N /// True if is a subset of /// , false otherwise. /// - internal static bool IsSubsetOfHelper(ICollection subset, ICollection superset) + internal static Tuple> IsSubsetOfHelper(ICollection subset, ICollection superset) { // $ CONSIDER: The current algorithm counts the number of occurrences of each // $ CONSIDER: element in each collection and then compares the count, resulting // $ CONSIDER: in an algorithm of ~n*log(n) + m*log(m) + n*log(m). It should be // $ CONSIDER: faster to sort both collections and do an element-by-element // $ CONSIDER: comparison, which should result in ~n*log(n) + m*log(m) + n. + var nonSubsetValues = new List(); // Count the occurrences of each object in both collections. Dictionary subsetElements = GetElementCounts(subset.Cast(), EqualityComparer.Default, out int subsetNulls); Dictionary supersetElements = GetElementCounts(superset.Cast(), EqualityComparer.Default, out int supersetNulls); + bool isSubset = true; + + // Check null counts first if (subsetNulls > supersetNulls) { - return false; + isSubset = false; + // Add the excess null values to non-subset collection + for (int i = 0; i < (subsetNulls - supersetNulls); i++) + { + nonSubsetValues.Add(null); + } } // Compare the counts of each object in the subset to the count of that object @@ -1464,12 +1478,17 @@ internal static bool IsSubsetOfHelper(ICollection subset, ICollection superset) if (subsetCount > supersetCount) { - return false; + isSubset = false; + // Add the excess occurrences to non-subset collection + int excessCount = subsetCount - supersetCount; + for (int i = 0; i < excessCount; i++) + { + nonSubsetValues.Add(element); + } } } - // All the elements counts were OK. - return true; + return new Tuple>(isSubset, nonSubsetValues); } #pragma warning disable CS8714 diff --git a/src/TestFramework/TestFramework/Resources/FrameworkMessages.resx b/src/TestFramework/TestFramework/Resources/FrameworkMessages.resx index 6a559ed4a7..b748db7eb1 100644 --- a/src/TestFramework/TestFramework/Resources/FrameworkMessages.resx +++ b/src/TestFramework/TestFramework/Resources/FrameworkMessages.resx @@ -370,4 +370,7 @@ Actual: {2} CollectionAssert.ReferenceEquals should not be used for Assertions. Please use CollectionAssert methods or Assert.AreSame & overloads instead. + + Element(s) <{0}> is/are not present in the collection + \ No newline at end of file diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.cs.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.cs.xlf index eb42733783..8dd3b5763e 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.cs.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.cs.xlf @@ -283,6 +283,11 @@ Skutečnost: {2} Rozdílný počet elementů. + + Element(s) <{0}> is/are not present in the collection + Element(s) <{0}> is/are not present in the collection + + String '{0}' does not start with string '{1}'. {2} Řetězec „{0}“ nezačíná řetězcem „{1}“. {2} diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.de.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.de.xlf index 54f6b8bb30..c8a2b5a22a 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.de.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.de.xlf @@ -283,6 +283,11 @@ Tatsächlich: {2} Unterschiedliche Anzahl von Elementen. + + Element(s) <{0}> is/are not present in the collection + Element(s) <{0}> is/are not present in the collection + + String '{0}' does not start with string '{1}'. {2} Die Zeichenfolge „{0}“ beginnt nicht mit der Zeichenfolge „{1}“. {2} diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.es.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.es.xlf index db1e3c240c..8ac18cf8c0 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.es.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.es.xlf @@ -283,6 +283,11 @@ Real: {2} Número diferente de elementos. + + Element(s) <{0}> is/are not present in the collection + Element(s) <{0}> is/are not present in the collection + + String '{0}' does not start with string '{1}'. {2} La cadena "{0}" no empieza con la cadena "{1}". {2} diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.fr.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.fr.xlf index e6b7647f69..8301bb846d 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.fr.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.fr.xlf @@ -283,6 +283,11 @@ Réel : {2} Nombre d'éléments différent. + + Element(s) <{0}> is/are not present in the collection + Element(s) <{0}> is/are not present in the collection + + String '{0}' does not start with string '{1}'. {2} La chaîne '{0}' ne commence pas par la chaîne '{1}'. {2} diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.it.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.it.xlf index 11ce79e9eb..6ee410aac8 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.it.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.it.xlf @@ -283,6 +283,11 @@ Effettivo: {2} Il numero di elementi è diverso. + + Element(s) <{0}> is/are not present in the collection + Element(s) <{0}> is/are not present in the collection + + String '{0}' does not start with string '{1}'. {2} La stringa '{0}' non inizia con la stringa '{1}'. {2} diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ja.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ja.xlf index 95eccb1dc7..09d2a5859d 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ja.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ja.xlf @@ -283,6 +283,11 @@ Actual: {2} 要素数が異なります。 + + Element(s) <{0}> is/are not present in the collection + Element(s) <{0}> is/are not present in the collection + + String '{0}' does not start with string '{1}'. {2} 文字列 '{0}' は文字列 '{1}' で始まりません。{2} diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ko.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ko.xlf index 677e3d8784..37eb133061 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ko.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ko.xlf @@ -283,6 +283,11 @@ Actual: {2} 요소 수가 다릅니다. + + Element(s) <{0}> is/are not present in the collection + Element(s) <{0}> is/are not present in the collection + + String '{0}' does not start with string '{1}'. {2} '{0}' 문자열이 '{1}' 문자열로 시작되지 않습니다. {2} diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pl.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pl.xlf index b75c6f30a3..7ba53f1e50 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pl.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pl.xlf @@ -283,6 +283,11 @@ Rzeczywiste: {2} Inna liczba elementów. + + Element(s) <{0}> is/are not present in the collection + Element(s) <{0}> is/are not present in the collection + + String '{0}' does not start with string '{1}'. {2} Ciąg „{0}” nie rozpoczyna się od ciągu „{1}”. {2} diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf index bd1a49ab9d..e71392bd97 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf @@ -283,6 +283,11 @@ Real: {2} Número diferente de elementos. + + Element(s) <{0}> is/are not present in the collection + Element(s) <{0}> is/are not present in the collection + + String '{0}' does not start with string '{1}'. {2} A cadeia de caracteres “{0}” não começa com a cadeia de caracteres “{1}”. {2} diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ru.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ru.xlf index f7fca4b5e4..b65b06a8bd 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ru.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ru.xlf @@ -283,6 +283,11 @@ Actual: {2} Разное число элементов. + + Element(s) <{0}> is/are not present in the collection + Element(s) <{0}> is/are not present in the collection + + String '{0}' does not start with string '{1}'. {2} Строка "{0}" не начинается со строки "{1}". {2} diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.tr.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.tr.xlf index 9a3c18b600..f96e7d2c9e 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.tr.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.tr.xlf @@ -283,6 +283,11 @@ Gerçekte olan: {2} Öğe sayıları farklı. + + Element(s) <{0}> is/are not present in the collection + Element(s) <{0}> is/are not present in the collection + + String '{0}' does not start with string '{1}'. {2} '{0}' dizesi, '{1}' dizesi ile başlamıyor. {2} diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf index 2e9d053375..85767651ac 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf @@ -283,6 +283,11 @@ Actual: {2} 不同数量的元素。 + + Element(s) <{0}> is/are not present in the collection + Element(s) <{0}> is/are not present in the collection + + String '{0}' does not start with string '{1}'. {2} 字符串 '{0}' 不以字符串 '{1}' 开头。{2} diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf index ce0eb0b961..e0e1d2018b 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf @@ -283,6 +283,11 @@ Actual: {2} 項目數目不同。 + + Element(s) <{0}> is/are not present in the collection + Element(s) <{0}> is/are not present in the collection + + String '{0}' does not start with string '{1}'. {2} 字串 '{0}' 不是以字串 '{1}' 開頭。{2} diff --git a/test/UnitTests/TestFramework.UnitTests/Assertions/CollectionAssertTests.cs b/test/UnitTests/TestFramework.UnitTests/Assertions/CollectionAssertTests.cs index a521130da3..26e2c90182 100644 --- a/test/UnitTests/TestFramework.UnitTests/Assertions/CollectionAssertTests.cs +++ b/test/UnitTests/TestFramework.UnitTests/Assertions/CollectionAssertTests.cs @@ -108,7 +108,7 @@ public void CollectionAssertAllItemsAreUniqueMessageParametersNullabilityPostCon public void CollectionAssertIsSubsetOfNullabilityPostConditions() { ICollection? collection = GetCollection(); - ICollection? superset = GetMatchingSuperSet(); + ICollection? superset = GetMatchingSuperset(); CollectionAssert.IsSubsetOf(collection, superset); _ = collection.Count; // no warning _ = superset.Count; // no warning @@ -117,7 +117,7 @@ public void CollectionAssertIsSubsetOfNullabilityPostConditions() public void CollectionAssertIsSubsetOfMessageNullabilityPostConditions() { ICollection? collection = GetCollection(); - ICollection? superset = GetMatchingSuperSet(); + ICollection? superset = GetMatchingSuperset(); CollectionAssert.IsSubsetOf(collection, superset, "message"); _ = collection.Count; // no warning _ = superset.Count; // no warning @@ -126,16 +126,55 @@ public void CollectionAssertIsSubsetOfMessageNullabilityPostConditions() public void CollectionAssertIsSubsetOfMessageParametersNullabilityPostConditions() { ICollection? collection = GetCollection(); - ICollection? superset = GetMatchingSuperSet(); + ICollection? superset = GetMatchingSuperset(); CollectionAssert.IsSubsetOf(collection, superset, "message format {0} {1}", 1, 2); _ = collection.Count; // no warning _ = superset.Count; // no warning } + public void CollectionAssertIsSubsetOf_ReturnedSubsetValueMessage_ThrowExceptionMessage() + { + // Arrange + ICollection? collection = GetSubsetCollection(); + ICollection? superset = GetSupersetCollection(); + + // Act + Action action = () => CollectionAssert.IsSubsetOf(collection, superset); + + // Assert + action.Should().Throw().WithMessage("CollectionAssert.IsSubsetOf failed. Element(s) is/are not present in the collection"); + } + + public void CollectionAssertIsSubsetOf_WithMessageParams_ReturnedSubsetValueMessage_ThrowExceptionMessage() + { + // Arrange + ICollection? collection = GetSubsetCollection(); + ICollection? superset = GetSupersetCollection(); + + // Act + Action action = () => CollectionAssert.IsSubsetOf(collection, superset, "message format {0} {1}", 1, 2); + + // Assert + action.Should().Throw().WithMessage("CollectionAssert.IsSubsetOf failed. Element(s) is/are not present in the collection"); + } + + public void CollectionAssertIsSubsetOf_WithMessage_ReturnedSubsetValueMessage_ThrowExceptionMessage() + { + // Arrange + ICollection? collection = GetSubsetCollection(); + ICollection? superset = GetSupersetCollection(); + + // Act + Action action = () => CollectionAssert.IsSubsetOf(collection, superset, "message"); + + // Assert + action.Should().Throw().WithMessage("CollectionAssert.IsSubsetOf failed. Element(s) is/are not present in the collection"); + } + public void CollectionAssertIsNotSubsetOfNullabilityPostConditions() { ICollection? collection = GetCollection(); - ICollection? superset = GetNotMatchingSuperSet(); + ICollection? superset = GetNotMatchingSuperset(); CollectionAssert.IsNotSubsetOf(collection, superset); _ = collection.Count; // no warning _ = superset.Count; // no warning @@ -144,7 +183,7 @@ public void CollectionAssertIsNotSubsetOfNullabilityPostConditions() public void CollectionAssertIsNotSubsetOfMessageNullabilityPostConditions() { ICollection? collection = GetCollection(); - ICollection? superset = GetNotMatchingSuperSet(); + ICollection? superset = GetNotMatchingSuperset(); CollectionAssert.IsNotSubsetOf(collection, superset, "message"); _ = collection.Count; // no warning _ = superset.Count; // no warning @@ -153,7 +192,7 @@ public void CollectionAssertIsNotSubsetOfMessageNullabilityPostConditions() public void CollectionAssertIsNotSubsetOfMessageParametersNullabilityPostConditions() { ICollection? collection = GetCollection(); - ICollection? superset = GetNotMatchingSuperSet(); + ICollection? superset = GetNotMatchingSuperset(); CollectionAssert.IsNotSubsetOf(collection, superset, "message format {0} {1}", 1, 2); _ = collection.Count; // no warning _ = superset.Count; // no warning @@ -338,7 +377,7 @@ public void CollectionAssertAreNotEqual_NotEqualDeeplyNestedLists_Passes() public void CollectionAssertAreNotEqualComparerNullabilityPostConditions() { ICollection? collection1 = GetCollection(); - ICollection? collection2 = GetMatchingSuperSet(); + ICollection? collection2 = GetMatchingSuperset(); IComparer? comparer = GetComparer(); CollectionAssert.AreNotEqual(collection1, collection2, comparer); comparer.ToString(); // no warning @@ -347,7 +386,7 @@ public void CollectionAssertAreNotEqualComparerNullabilityPostConditions() public void CollectionAssertAreNotEqualComparerMessageNullabilityPostConditions() { ICollection? collection1 = GetCollection(); - ICollection? collection2 = GetMatchingSuperSet(); + ICollection? collection2 = GetMatchingSuperset(); IComparer? comparer = GetComparer(); CollectionAssert.AreNotEqual(collection1, collection2, comparer, "message"); comparer.ToString(); // no warning @@ -356,7 +395,7 @@ public void CollectionAssertAreNotEqualComparerMessageNullabilityPostConditions( public void CollectionAssertAreNotEqualComparerMessageParametersNullabilityPostConditions() { ICollection? collection1 = GetCollection(); - ICollection? collection2 = GetMatchingSuperSet(); + ICollection? collection2 = GetMatchingSuperset(); IComparer? comparer = GetComparer(); CollectionAssert.AreNotEqual(collection1, collection2, comparer, "message format {0} {1}", 1, 2); comparer.ToString(); // no warning @@ -364,8 +403,8 @@ public void CollectionAssertAreNotEqualComparerMessageParametersNullabilityPostC public void CollectionAssertAreEquivalent_SameItemsWithDifferentOrder_DoesNotThrow() { - ICollection? collection1 = GetMatchingSuperSet(); - ICollection? collection2 = GetReversedMatchingSuperSet(); + ICollection? collection1 = GetMatchingSuperset(); + ICollection? collection2 = GetReversedMatchingSuperset(); CollectionAssert.AreEquivalent(collection1, collection2); } @@ -381,7 +420,7 @@ public void CollectionAssertAreEquivalent_WithMatchingNullableSets_DoesNotThrow( public void CollectionAssertAreEquivalent_FailWhenNotEquivalent_WithMessage() { ICollection? collection1 = GetCollection(); - ICollection? collection2 = GetMatchingSuperSet(); + ICollection? collection2 = GetMatchingSuperset(); Action action = () => CollectionAssert.AreEquivalent(collection1, collection2, "message"); action.Should().Throw().And .Message.Should().Contain("message"); @@ -390,7 +429,7 @@ public void CollectionAssertAreEquivalent_FailWhenNotEquivalent_WithMessage() public void CollectionAssertAreEquivalent_FailWhenNotEquivalent_WithMessageAndParams() { ICollection? collection1 = GetCollection(); - ICollection? collection2 = GetMatchingSuperSet(); + ICollection? collection2 = GetMatchingSuperset(); Action action = () => CollectionAssert.AreEquivalent(collection1, collection2, "message format {0} {1}", 1, 2); action.Should().Throw().And. Message.Should().Contain("message"); @@ -398,15 +437,15 @@ public void CollectionAssertAreEquivalent_FailWhenNotEquivalent_WithMessageAndPa public void CollectionAssertAreEquivalent_WithInsensitiveCaseComparer_DoesNotThrow() { - ICollection? collection1 = GetMatchingSuperSet(); - ICollection? collection2 = GetLettersCaseMismatchingSuperSet(); + ICollection? collection1 = GetMatchingSuperset(); + ICollection? collection2 = GetLettersCaseMismatchingSuperset(); CollectionAssert.AreEquivalent(collection1?.Cast(), collection2?.Cast(), new CaseInsensitiveEqualityComparer()); } public void CollectionAssertAreEquivalent_FailsWithInsensitiveCaseComparer_WithMessage() { ICollection? collection1 = GetCollection(); - ICollection? collection2 = GetLettersCaseMismatchingSuperSet(); + ICollection? collection2 = GetLettersCaseMismatchingSuperset(); Action action = () => CollectionAssert.AreEquivalent(collection1?.Cast(), collection2?.Cast(), new CaseInsensitiveEqualityComparer(), "message"); action.Should().Throw().And .Message.Should().Contain("message"); @@ -415,7 +454,7 @@ public void CollectionAssertAreEquivalent_FailsWithInsensitiveCaseComparer_WithM public void CollectionAssertAreEquivalent_FailsWithInsensitiveCaseComparer_WithMessageAndParams() { ICollection? collection1 = GetCollection(); - ICollection? collection2 = GetLettersCaseMismatchingSuperSet(); + ICollection? collection2 = GetLettersCaseMismatchingSuperset(); Action action = () => CollectionAssert.AreEquivalent(collection1?.Cast(), collection2?.Cast(), new CaseInsensitiveEqualityComparer(), "message format {0} {1}", 1, 2); action.Should().Throw().And .Message.Should().Contain("message"); @@ -424,14 +463,14 @@ public void CollectionAssertAreEquivalent_FailsWithInsensitiveCaseComparer_WithM public void CollectionAssertAreNotEquivalent_SameItemsWithDifferentOrder_DoesNotThrow() { ICollection? collection1 = GetCollection(); - ICollection? collection2 = GetMatchingSuperSet(); + ICollection? collection2 = GetMatchingSuperset(); CollectionAssert.AreNotEquivalent(collection1, collection2); } public void CollectionAssertAreNotEquivalent_FailWhenNotEquivalent_WithMessage() { - ICollection? collection1 = GetReversedMatchingSuperSet(); - ICollection? collection2 = GetMatchingSuperSet(); + ICollection? collection1 = GetReversedMatchingSuperset(); + ICollection? collection2 = GetMatchingSuperset(); Action action = () => CollectionAssert.AreNotEquivalent(collection1, collection2, "message"); action.Should().Throw().And .Message.Should().Contain("message"); @@ -439,8 +478,8 @@ public void CollectionAssertAreNotEquivalent_FailWhenNotEquivalent_WithMessage() public void CollectionAssertAreNotEquivalent_FailWhenNotEquivalent_WithMessageAndParams() { - ICollection? collection1 = GetReversedMatchingSuperSet(); - ICollection? collection2 = GetMatchingSuperSet(); + ICollection? collection1 = GetReversedMatchingSuperset(); + ICollection? collection2 = GetMatchingSuperset(); Action action = () => CollectionAssert.AreNotEquivalent(collection1, collection2, "message format {0} {1}", 1, 2); action.Should().Throw().And .Message.Should().Contain("message"); @@ -449,14 +488,14 @@ public void CollectionAssertAreNotEquivalent_FailWhenNotEquivalent_WithMessageAn public void CollectionAssertAreNotEquivalent_WithInsensitiveCaseComparer_DoesNotThrow() { ICollection? collection1 = GetCollection(); - ICollection? collection2 = GetMatchingSuperSet(); + ICollection? collection2 = GetMatchingSuperset(); CollectionAssert.AreNotEquivalent(collection1?.Cast(), collection2?.Cast(), EqualityComparer.Default); } public void CollectionAssertAreNotEquivalent_FailsWithInsensitiveCaseComparer_WithMessage() { - ICollection? collection1 = GetMatchingSuperSet(); - ICollection? collection2 = GetLettersCaseMismatchingSuperSet(); + ICollection? collection1 = GetMatchingSuperset(); + ICollection? collection2 = GetLettersCaseMismatchingSuperset(); Action action = () => CollectionAssert.AreNotEquivalent(collection1?.Cast(), collection2?.Cast(), new CaseInsensitiveNotEqualityComparer(), "message"); action.Should().Throw() .And.Message.Should().Contain("message"); @@ -464,8 +503,8 @@ public void CollectionAssertAreNotEquivalent_FailsWithInsensitiveCaseComparer_Wi public void CollectionAssertAreNotEquivalent_FailsWithInsensitiveCaseComparer_WithMessageAndParams() { - ICollection? collection1 = GetMatchingSuperSet(); - ICollection? collection2 = GetLettersCaseMismatchingSuperSet(); + ICollection? collection1 = GetMatchingSuperset(); + ICollection? collection2 = GetLettersCaseMismatchingSuperset(); Action action = () => CollectionAssert.AreNotEquivalent(collection1?.Cast(), collection2?.Cast(), new CaseInsensitiveNotEqualityComparer(), "message format {0} {1}", 1, 2); action.Should().Throw() .And.Message.Should().Contain("message"); @@ -521,17 +560,21 @@ private static List GenerateDeeplyNestedCollection(int depth) private ICollection? GetCollection() => new[] { "item" }; + private ICollection? GetSubsetCollection() => new[] { "iem", "a", "b" }; + private object? GetMatchingElement() => "item"; private object? GetNotMatchingElement() => "not found"; - private ICollection? GetMatchingSuperSet() => new[] { "item", "item2" }; + private ICollection? GetMatchingSuperset() => new[] { "item", "item2" }; + + private ICollection? GetSupersetCollection() => new[] { "item", "item2", "c", "d" }; - private ICollection? GetLettersCaseMismatchingSuperSet() => new[] { "Item", "iTem2" }; + private ICollection? GetLettersCaseMismatchingSuperset() => new[] { "Item", "iTem2" }; - private ICollection? GetReversedMatchingSuperSet() => new[] { "item2", "item" }; + private ICollection? GetReversedMatchingSuperset() => new[] { "item2", "item" }; - private ICollection? GetNotMatchingSuperSet() => new[] { "item3" }; + private ICollection? GetNotMatchingSuperset() => new[] { "item3" }; private ICollection? GetNestedLists() => new List> { From 0f88daa1f377afaac08ffff1c29ecca6cb79e9a4 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Wed, 24 Sep 2025 10:23:22 +0200 Subject: [PATCH 515/541] Follow-up on CollectionAssert change (#6597) --- .../TestFramework/Assertions/CollectionAssert.cs | 12 ++++++++++-- .../TestFramework/Resources/FrameworkMessages.resx | 2 +- .../Resources/xlf/FrameworkMessages.cs.xlf | 4 ++-- .../Resources/xlf/FrameworkMessages.de.xlf | 4 ++-- .../Resources/xlf/FrameworkMessages.es.xlf | 4 ++-- .../Resources/xlf/FrameworkMessages.fr.xlf | 4 ++-- .../Resources/xlf/FrameworkMessages.it.xlf | 4 ++-- .../Resources/xlf/FrameworkMessages.ja.xlf | 4 ++-- .../Resources/xlf/FrameworkMessages.ko.xlf | 4 ++-- .../Resources/xlf/FrameworkMessages.pl.xlf | 4 ++-- .../Resources/xlf/FrameworkMessages.pt-BR.xlf | 4 ++-- .../Resources/xlf/FrameworkMessages.ru.xlf | 4 ++-- .../Resources/xlf/FrameworkMessages.tr.xlf | 4 ++-- .../Resources/xlf/FrameworkMessages.zh-Hans.xlf | 4 ++-- .../Resources/xlf/FrameworkMessages.zh-Hant.xlf | 4 ++-- .../Assertions/CollectionAssertTests.cs | 6 +++--- 16 files changed, 40 insertions(+), 32 deletions(-) diff --git a/src/TestFramework/TestFramework/Assertions/CollectionAssert.cs b/src/TestFramework/TestFramework/Assertions/CollectionAssert.cs index f96ef84443..b0534331f5 100644 --- a/src/TestFramework/TestFramework/Assertions/CollectionAssert.cs +++ b/src/TestFramework/TestFramework/Assertions/CollectionAssert.cs @@ -423,8 +423,16 @@ public static void IsSubsetOf([NotNull] ICollection? subset, [NotNull] ICollecti { string returnedSubsetValueMessage = string.Join(", ", isSubsetValue.Item2.Select(item => Convert.ToString(item, CultureInfo.InvariantCulture))); - returnedSubsetValueMessage = string.Format(CultureInfo.InvariantCulture, FrameworkMessages.ReturnedSubsetValueMessage, returnedSubsetValueMessage.Trim()); - Assert.ThrowAssertFailed("CollectionAssert.IsSubsetOf", returnedSubsetValueMessage); + returnedSubsetValueMessage = string.Format(CultureInfo.InvariantCulture, FrameworkMessages.ReturnedSubsetValueMessage, returnedSubsetValueMessage); + string userMessage = Assert.BuildUserMessage(message, parameters); + if (string.IsNullOrEmpty(userMessage)) + { + Assert.ThrowAssertFailed("CollectionAssert.IsSubsetOf", returnedSubsetValueMessage); + } + else + { + Assert.ThrowAssertFailed("CollectionAssert.IsSubsetOf", $"{returnedSubsetValueMessage} {userMessage}"); + } } } diff --git a/src/TestFramework/TestFramework/Resources/FrameworkMessages.resx b/src/TestFramework/TestFramework/Resources/FrameworkMessages.resx index b748db7eb1..2de03a6968 100644 --- a/src/TestFramework/TestFramework/Resources/FrameworkMessages.resx +++ b/src/TestFramework/TestFramework/Resources/FrameworkMessages.resx @@ -371,6 +371,6 @@ Actual: {2} CollectionAssert.ReferenceEquals should not be used for Assertions. Please use CollectionAssert methods or Assert.AreSame & overloads instead. - Element(s) <{0}> is/are not present in the collection + Element(s) <{0}> is/are not present in the collection. \ No newline at end of file diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.cs.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.cs.xlf index 8dd3b5763e..7f5e380557 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.cs.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.cs.xlf @@ -284,8 +284,8 @@ Skutečnost: {2} - Element(s) <{0}> is/are not present in the collection - Element(s) <{0}> is/are not present in the collection + Element(s) <{0}> is/are not present in the collection. + Element(s) <{0}> is/are not present in the collection. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.de.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.de.xlf index c8a2b5a22a..db8144a691 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.de.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.de.xlf @@ -284,8 +284,8 @@ Tatsächlich: {2} - Element(s) <{0}> is/are not present in the collection - Element(s) <{0}> is/are not present in the collection + Element(s) <{0}> is/are not present in the collection. + Element(s) <{0}> is/are not present in the collection. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.es.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.es.xlf index 8ac18cf8c0..c3c2d018c6 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.es.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.es.xlf @@ -284,8 +284,8 @@ Real: {2} - Element(s) <{0}> is/are not present in the collection - Element(s) <{0}> is/are not present in the collection + Element(s) <{0}> is/are not present in the collection. + Element(s) <{0}> is/are not present in the collection. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.fr.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.fr.xlf index 8301bb846d..4f1d8fd807 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.fr.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.fr.xlf @@ -284,8 +284,8 @@ Réel : {2} - Element(s) <{0}> is/are not present in the collection - Element(s) <{0}> is/are not present in the collection + Element(s) <{0}> is/are not present in the collection. + Element(s) <{0}> is/are not present in the collection. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.it.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.it.xlf index 6ee410aac8..d28a976988 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.it.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.it.xlf @@ -284,8 +284,8 @@ Effettivo: {2} - Element(s) <{0}> is/are not present in the collection - Element(s) <{0}> is/are not present in the collection + Element(s) <{0}> is/are not present in the collection. + Element(s) <{0}> is/are not present in the collection. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ja.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ja.xlf index 09d2a5859d..9d957951d5 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ja.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ja.xlf @@ -284,8 +284,8 @@ Actual: {2} - Element(s) <{0}> is/are not present in the collection - Element(s) <{0}> is/are not present in the collection + Element(s) <{0}> is/are not present in the collection. + Element(s) <{0}> is/are not present in the collection. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ko.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ko.xlf index 37eb133061..2445d7f5ff 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ko.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ko.xlf @@ -284,8 +284,8 @@ Actual: {2} - Element(s) <{0}> is/are not present in the collection - Element(s) <{0}> is/are not present in the collection + Element(s) <{0}> is/are not present in the collection. + Element(s) <{0}> is/are not present in the collection. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pl.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pl.xlf index 7ba53f1e50..a35b7d0f19 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pl.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pl.xlf @@ -284,8 +284,8 @@ Rzeczywiste: {2} - Element(s) <{0}> is/are not present in the collection - Element(s) <{0}> is/are not present in the collection + Element(s) <{0}> is/are not present in the collection. + Element(s) <{0}> is/are not present in the collection. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf index e71392bd97..85960e12b8 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.pt-BR.xlf @@ -284,8 +284,8 @@ Real: {2} - Element(s) <{0}> is/are not present in the collection - Element(s) <{0}> is/are not present in the collection + Element(s) <{0}> is/are not present in the collection. + Element(s) <{0}> is/are not present in the collection. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ru.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ru.xlf index b65b06a8bd..76d4ab548d 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ru.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.ru.xlf @@ -284,8 +284,8 @@ Actual: {2} - Element(s) <{0}> is/are not present in the collection - Element(s) <{0}> is/are not present in the collection + Element(s) <{0}> is/are not present in the collection. + Element(s) <{0}> is/are not present in the collection. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.tr.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.tr.xlf index f96e7d2c9e..1f34a6bc07 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.tr.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.tr.xlf @@ -284,8 +284,8 @@ Gerçekte olan: {2} - Element(s) <{0}> is/are not present in the collection - Element(s) <{0}> is/are not present in the collection + Element(s) <{0}> is/are not present in the collection. + Element(s) <{0}> is/are not present in the collection. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf index 85767651ac..6bc1ce182d 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hans.xlf @@ -284,8 +284,8 @@ Actual: {2} - Element(s) <{0}> is/are not present in the collection - Element(s) <{0}> is/are not present in the collection + Element(s) <{0}> is/are not present in the collection. + Element(s) <{0}> is/are not present in the collection. diff --git a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf index e0e1d2018b..6433c45d7b 100644 --- a/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf +++ b/src/TestFramework/TestFramework/Resources/xlf/FrameworkMessages.zh-Hant.xlf @@ -284,8 +284,8 @@ Actual: {2} - Element(s) <{0}> is/are not present in the collection - Element(s) <{0}> is/are not present in the collection + Element(s) <{0}> is/are not present in the collection. + Element(s) <{0}> is/are not present in the collection. diff --git a/test/UnitTests/TestFramework.UnitTests/Assertions/CollectionAssertTests.cs b/test/UnitTests/TestFramework.UnitTests/Assertions/CollectionAssertTests.cs index 26e2c90182..07c8782bc6 100644 --- a/test/UnitTests/TestFramework.UnitTests/Assertions/CollectionAssertTests.cs +++ b/test/UnitTests/TestFramework.UnitTests/Assertions/CollectionAssertTests.cs @@ -142,7 +142,7 @@ public void CollectionAssertIsSubsetOf_ReturnedSubsetValueMessage_ThrowException Action action = () => CollectionAssert.IsSubsetOf(collection, superset); // Assert - action.Should().Throw().WithMessage("CollectionAssert.IsSubsetOf failed. Element(s) is/are not present in the collection"); + action.Should().Throw().WithMessage("CollectionAssert.IsSubsetOf failed. Element(s) is/are not present in the collection."); } public void CollectionAssertIsSubsetOf_WithMessageParams_ReturnedSubsetValueMessage_ThrowExceptionMessage() @@ -155,7 +155,7 @@ public void CollectionAssertIsSubsetOf_WithMessageParams_ReturnedSubsetValueMess Action action = () => CollectionAssert.IsSubsetOf(collection, superset, "message format {0} {1}", 1, 2); // Assert - action.Should().Throw().WithMessage("CollectionAssert.IsSubsetOf failed. Element(s) is/are not present in the collection"); + action.Should().Throw().WithMessage("CollectionAssert.IsSubsetOf failed. Element(s) is/are not present in the collection. message format 1 2"); } public void CollectionAssertIsSubsetOf_WithMessage_ReturnedSubsetValueMessage_ThrowExceptionMessage() @@ -168,7 +168,7 @@ public void CollectionAssertIsSubsetOf_WithMessage_ReturnedSubsetValueMessage_Th Action action = () => CollectionAssert.IsSubsetOf(collection, superset, "message"); // Assert - action.Should().Throw().WithMessage("CollectionAssert.IsSubsetOf failed. Element(s) is/are not present in the collection"); + action.Should().Throw().WithMessage("CollectionAssert.IsSubsetOf failed. Element(s) is/are not present in the collection. message"); } public void CollectionAssertIsNotSubsetOfNullabilityPostConditions() From 74721fc4a96eefb3b757e3ffacaae1fdcbe7a0f8 Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Thu, 25 Sep 2025 09:17:14 +0200 Subject: [PATCH 516/541] [main] Update dependencies from microsoft/testfx (#6603) Co-authored-by: dotnet-maestro[bot] --- eng/Version.Details.xml | 8 ++++---- eng/Versions.props | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index a01da254fa..2df25ad0e3 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -17,13 +17,13 @@ https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage 957aa737e42290c129a620df7129f03189743dd1 - + https://github.com/microsoft/testfx - 7812bf1fe7289e9f528ced8a230502c1e0bfe50f + 0f88daa1f377afaac08ffff1c29ecca6cb79e9a4 - + https://github.com/microsoft/testfx - 7812bf1fe7289e9f528ced8a230502c1e0bfe50f + 0f88daa1f377afaac08ffff1c29ecca6cb79e9a4 diff --git a/eng/Versions.props b/eng/Versions.props index e0dd7d7b27..7eecb78de7 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -10,7 +10,7 @@ 11.0.0-beta.25469.3 18.0.0-preview.25469.1 - 3.11.0-preview.25470.1 - 1.9.0-preview.25470.1 + 3.11.0-preview.25474.1 + 1.9.0-preview.25474.1 From 67b57cb949299945cfe00361d4b87abd52ced0e8 Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Fri, 26 Sep 2025 05:21:45 +0200 Subject: [PATCH 517/541] [main] Update dependencies from microsoft/testfx (#6606) Co-authored-by: dotnet-maestro[bot] --- eng/Version.Details.xml | 8 ++++---- eng/Versions.props | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index 2df25ad0e3..2287b0fd22 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -17,13 +17,13 @@ https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage 957aa737e42290c129a620df7129f03189743dd1 - + https://github.com/microsoft/testfx - 0f88daa1f377afaac08ffff1c29ecca6cb79e9a4 + 74721fc4a96eefb3b757e3ffacaae1fdcbe7a0f8 - + https://github.com/microsoft/testfx - 0f88daa1f377afaac08ffff1c29ecca6cb79e9a4 + 74721fc4a96eefb3b757e3ffacaae1fdcbe7a0f8 diff --git a/eng/Versions.props b/eng/Versions.props index 7eecb78de7..392e6354d3 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -10,7 +10,7 @@ 11.0.0-beta.25469.3 18.0.0-preview.25469.1 - 3.11.0-preview.25474.1 - 1.9.0-preview.25474.1 + 3.11.0-preview.25475.1 + 1.9.0-preview.25475.1 From ee3d442c7f925daf899bd5e80f45c549f2cc417a Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Fri, 26 Sep 2025 04:03:33 +0000 Subject: [PATCH 518/541] [main] Update dependencies from devdiv/DevDiv/vs-code-coverage (#6595) Co-authored-by: dotnet-maestro[bot] --- NuGet.config | 8 ++++++++ eng/Version.Details.xml | 4 ++-- eng/Versions.props | 2 +- 3 files changed, 11 insertions(+), 3 deletions(-) diff --git a/NuGet.config b/NuGet.config index 712f79ac00..5c00c1d17d 100644 --- a/NuGet.config +++ b/NuGet.config @@ -5,6 +5,10 @@ + + + + @@ -17,6 +21,10 @@ + + + + diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index 2287b0fd22..aa95ee1df9 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -13,9 +13,9 @@ https://github.com/dotnet/arcade dbc4dce57f6a2087f13d86e89dfb0334be3c42e2 - + https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage - 957aa737e42290c129a620df7129f03189743dd1 + b1e7fa5bb1a3e468b6f9d47cf61a3b5616c44713 https://github.com/microsoft/testfx diff --git a/eng/Versions.props b/eng/Versions.props index 392e6354d3..e7a901c1f5 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -8,7 +8,7 @@ 11.0.0-beta.25469.3 - 18.0.0-preview.25469.1 + 18.0.4-preview.25475.6 3.11.0-preview.25475.1 1.9.0-preview.25475.1 From 7bbc1b927447ff81466a47dfcf85df7bf5c1708d Mon Sep 17 00:00:00 2001 From: Copilot <198982749+Copilot@users.noreply.github.com> Date: Fri, 26 Sep 2025 09:59:50 +0200 Subject: [PATCH 519/541] Fix MSTEST0025 false positive for reference types in Assert.IsNull() (#6601) Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: Youssef1313 <31348972+Youssef1313@users.noreply.github.com> --- ...rtFailOverAlwaysFalseConditionsAnalyzer.cs | 2 +- ...lOverAlwaysFalseConditionsAnalyzerTests.cs | 97 +++++++++++++++---- 2 files changed, 77 insertions(+), 22 deletions(-) diff --git a/src/Analyzers/MSTest.Analyzers/PreferAssertFailOverAlwaysFalseConditionsAnalyzer.cs b/src/Analyzers/MSTest.Analyzers/PreferAssertFailOverAlwaysFalseConditionsAnalyzer.cs index d06a95c547..ba18ade548 100644 --- a/src/Analyzers/MSTest.Analyzers/PreferAssertFailOverAlwaysFalseConditionsAnalyzer.cs +++ b/src/Analyzers/MSTest.Analyzers/PreferAssertFailOverAlwaysFalseConditionsAnalyzer.cs @@ -127,7 +127,7 @@ private static bool IsNotNullableType(IArgumentOperation valueArgumentOperation) { ITypeSymbol? valueArgType = valueArgumentOperation.Value.GetReferencedMemberOrLocalOrParameter().GetReferencedMemberOrLocalOrParameter(); return valueArgType is not null - && valueArgType.NullableAnnotation == NullableAnnotation.NotAnnotated + && valueArgType.IsValueType && valueArgType.OriginalDefinition.SpecialType != SpecialType.System_Nullable_T; } diff --git a/test/UnitTests/MSTest.Analyzers.UnitTests/PreferAssertFailOverAlwaysFalseConditionsAnalyzerTests.cs b/test/UnitTests/MSTest.Analyzers.UnitTests/PreferAssertFailOverAlwaysFalseConditionsAnalyzerTests.cs index 69f3b533a6..3b6c5b3d01 100644 --- a/test/UnitTests/MSTest.Analyzers.UnitTests/PreferAssertFailOverAlwaysFalseConditionsAnalyzerTests.cs +++ b/test/UnitTests/MSTest.Analyzers.UnitTests/PreferAssertFailOverAlwaysFalseConditionsAnalyzerTests.cs @@ -125,7 +125,7 @@ public void Test() } [TestMethod] - public async Task WhenIsNullAssertion_ValueParameterAsReferenceObjectIsNotNullable_Diagnostic() + public async Task WhenIsNullAssertion_ValueParameterAsReferenceObjectIsNotNullable_NoDiagnostic() { string code = """ using Microsoft.VisualStudio.TestTools.UnitTesting; @@ -137,7 +137,7 @@ public class TestClass public void Test() { ObjectClass obj = new ObjectClass(); - [|Assert.IsNull(obj)|]; + Assert.IsNull(obj); } } @@ -146,26 +146,8 @@ public class ObjectClass } """; - string fixedCode = """ - using Microsoft.VisualStudio.TestTools.UnitTesting; - #nullable enable - [TestClass] - public class TestClass - { - [TestMethod] - public void Test() - { - ObjectClass obj = new ObjectClass(); - Assert.Fail(); - } - } - public class ObjectClass - { - - } - """; - await VerifyCS.VerifyCodeFixAsync(code, fixedCode); + await VerifyCS.VerifyCodeFixAsync(code, code); } [TestMethod] @@ -1470,4 +1452,77 @@ public void TestMethod() await VerifyCS.VerifyCodeFixAsync(code, code); } + + [TestMethod] + public async Task WhenIsNullAssertion_ReferenceTypeInNullableDisableContext_NoDiagnostic() + { + string code = """ + using System.Diagnostics.CodeAnalysis; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public sealed class MyTests + { + #nullable disable + [TestMethod] + public void Repro() + { + Assert.IsFalse(TryGetPool(poolKey: null, out var pool)); + Assert.IsNull(pool); + } + #nullable restore + + #nullable enable + internal bool TryGetPool(string? poolKey, [MaybeNullWhen(false)] out object pool) + { + if (poolKey is not null) + { + pool = new object(); + return true; + } + + pool = null; + return false; + } + #nullable restore + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, code); + } + + [TestMethod] + public async Task WhenIsNullAssertion_ValueTypeParameter_Diagnostic() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class TestClass + { + [TestMethod] + public void Test() + { + int value = 42; + [|Assert.IsNull(value)|]; + } + } + """; + string fixedCode = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class TestClass + { + [TestMethod] + public void Test() + { + int value = 42; + Assert.Fail(); + } + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, fixedCode); + } } From 5f259677e63e020a42eb5e11dcf1aa5c7c82fa04 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Fri, 26 Sep 2025 16:13:16 +0200 Subject: [PATCH 520/541] Fix MSTEST0037 false positive for Contains with type different from the generic parameter of `IEnumerable` (#6607) --- .../UseProperAssertMethodsAnalyzer.cs | 25 ++++++++++--- .../UseProperAssertMethodsAnalyzerTests.cs | 35 +++++++++++++++++++ 2 files changed, 56 insertions(+), 4 deletions(-) diff --git a/src/Analyzers/MSTest.Analyzers/UseProperAssertMethodsAnalyzer.cs b/src/Analyzers/MSTest.Analyzers/UseProperAssertMethodsAnalyzer.cs index 932774bd5a..20ca9e57bc 100644 --- a/src/Analyzers/MSTest.Analyzers/UseProperAssertMethodsAnalyzer.cs +++ b/src/Analyzers/MSTest.Analyzers/UseProperAssertMethodsAnalyzer.cs @@ -450,13 +450,30 @@ private static CollectionCheckStatus RecognizeCollectionMethodCheck( string methodName = invocation.TargetMethod.Name; // Check for Collection.Contains(item) - if (methodName == "Contains" && invocation.Arguments.Length == 1) + // We need to also ensure that invocation.TargetMethod.OriginalDefinition.Parameters[0] matches the type of the ienumerable returned by invocation.TargetMethod.ContainingType.OriginalDefinition.AllInterfaces + if (methodName == "Contains" && + invocation.Arguments.Length == 1 && + invocation.TargetMethod.OriginalDefinition.Parameters.Length == 1 && + invocation.TargetMethod.OriginalDefinition.Parameters[0].Type is { } containsParameterType) { if (IsBCLCollectionType(invocation.TargetMethod.ContainingType, objectTypeSymbol)) { - collectionExpression = invocation.Instance?.Syntax; - itemExpression = invocation.Arguments[0].Value.Syntax; - return CollectionCheckStatus.Contains; + ITypeSymbol? enumerableElementType = invocation.TargetMethod.ContainingType.OriginalDefinition.AllInterfaces.FirstOrDefault( + i => i.OriginalDefinition.SpecialType == SpecialType.System_Collections_Generic_IEnumerable_T)?.TypeArguments[0]; + + if (enumerableElementType is null || enumerableElementType.Equals(containsParameterType, SymbolEqualityComparer.Default)) + { + // If enumerableElementType is null, we expect that this is a non-generic IEnumerable. So we simply report the diagnostic. + // If it's not null, ensure that the "T" of "IEnumerable" matches the type of the Contains method. + // The type comparison here is not for "substituted" types. + // So, when analyzing KeyedCollection.Contains(TKey), we will have: + // 1. containsParameterType as the symbol referring to "TKey". + // 2. enumerableElementType as the symbol referring to "TItem". + // So, even if we are dealing with KeyedCollection, the types won't match, and we won't produce a diagnostic. + collectionExpression = invocation.Instance?.Syntax; + itemExpression = invocation.Arguments[0].Value.Syntax; + return CollectionCheckStatus.Contains; + } } } } diff --git a/test/UnitTests/MSTest.Analyzers.UnitTests/UseProperAssertMethodsAnalyzerTests.cs b/test/UnitTests/MSTest.Analyzers.UnitTests/UseProperAssertMethodsAnalyzerTests.cs index e2e64f51f1..e34ccd5ce1 100644 --- a/test/UnitTests/MSTest.Analyzers.UnitTests/UseProperAssertMethodsAnalyzerTests.cs +++ b/test/UnitTests/MSTest.Analyzers.UnitTests/UseProperAssertMethodsAnalyzerTests.cs @@ -1310,6 +1310,41 @@ public void MyTestMethod() await VerifyCS.VerifyAnalyzerAsync(code); } + [TestMethod] + public async Task WhenAssertIsTrueOrIsFalseWithWrongContainsMethod() + { + string code = """ + using System.Collections.ObjectModel; + using System.IO; + + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTests + { + [TestMethod] + public void Contains() + { + // This collection is KeyedCollection + // It implements IEnumerable, but the available Contains method searches for TKey. + // Whether or not the type of TKey and TItem match, we shouldn't raise a diagnostic as it changes semantics. + var collection = new MyKeyedCollection(); + Assert.IsFalse(collection.Contains(5)); + Assert.IsTrue(collection.Contains(5)); + } + + internal class MyKeyedCollection : KeyedCollection + { + protected override int GetKeyForItem(int item) + { + return 667; + } + } + } + """; + await VerifyCS.VerifyCodeFixAsync(code, code); + } + #region New test cases for string methods [TestMethod] From 85fcd434ec43f7a51c9f3d405294a5b9516b54c4 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Fri, 26 Sep 2025 17:11:50 +0200 Subject: [PATCH 521/541] Don't suggest HasCount when Length/Count access is on the "expected" side (#6608) --- .../UseProperAssertMethodsAnalyzer.cs | 36 ------------------- .../UseProperAssertMethodsAnalyzerTests.cs | 22 +++++------- 2 files changed, 8 insertions(+), 50 deletions(-) diff --git a/src/Analyzers/MSTest.Analyzers/UseProperAssertMethodsAnalyzer.cs b/src/Analyzers/MSTest.Analyzers/UseProperAssertMethodsAnalyzer.cs index 20ca9e57bc..5093aa9a9f 100644 --- a/src/Analyzers/MSTest.Analyzers/UseProperAssertMethodsAnalyzer.cs +++ b/src/Analyzers/MSTest.Analyzers/UseProperAssertMethodsAnalyzer.cs @@ -929,42 +929,6 @@ expectedArgument.ConstantValue.Value is int expectedValue && } } - // Check if actualArgument is a literal and expectedArgument is a count/length property - if (expectedArgument is IPropertyReferenceOperation propertyRef2 && - TryGetCollectionExpressionIfBCLCollectionLengthOrCount(propertyRef2, objectTypeSymbol) is { } expression2) - { - bool isEmpty = actualArgument.ConstantValue.HasValue && - actualArgument.ConstantValue.Value is int actualValue && - actualValue == 0; - - if (isEmpty) - { - // We have Assert.AreEqual(collection.Count/Length, expectedCount) - // We want Assert.IsEmpty(collection) - // So, only two replacements are needed: - // 1. Replace collection.Count/Length with expectedCount - // 2. Replace expectedCount with collection - nodeToBeReplaced1 = expectedArgument.Syntax; // collection.Count/Length - replacement1 = expression2; // collection - nodeToBeReplaced2 = actualArgument.Syntax; // expectedCount - replacement2 = null; - return CountCheckStatus.IsEmpty; - } - else - { - // We have Assert.AreEqual(collection.Count/Length, expectedCount) - // We want Assert.HasCount(expectedCount, collection) - // So, only two replacements are needed: - // 1. Replace collection.Count/Length with expectedCount - // 2. Replace expectedCount with collection - nodeToBeReplaced1 = expectedArgument.Syntax; // collection.Count/Length - replacement1 = actualArgument.Syntax; // expectedCount - nodeToBeReplaced2 = actualArgument.Syntax; // expectedCount - replacement2 = expression2; // collection - return CountCheckStatus.HasCount; - } - } - nodeToBeReplaced1 = null; replacement1 = null; nodeToBeReplaced2 = null; diff --git a/test/UnitTests/MSTest.Analyzers.UnitTests/UseProperAssertMethodsAnalyzerTests.cs b/test/UnitTests/MSTest.Analyzers.UnitTests/UseProperAssertMethodsAnalyzerTests.cs index e34ccd5ce1..6be0ddc467 100644 --- a/test/UnitTests/MSTest.Analyzers.UnitTests/UseProperAssertMethodsAnalyzerTests.cs +++ b/test/UnitTests/MSTest.Analyzers.UnitTests/UseProperAssertMethodsAnalyzerTests.cs @@ -1866,7 +1866,7 @@ public void MyTestMethod() { var list = new List(); {|#0:Assert.AreEqual(0, list.Count)|}; - {|#1:Assert.AreEqual(list.Count, 0)|}; + Assert.AreEqual(list.Count, 0); } } """; @@ -1883,7 +1883,7 @@ public void MyTestMethod() { var list = new List(); Assert.IsEmpty(list); - Assert.IsEmpty(list); + Assert.AreEqual(list.Count, 0); } } """; @@ -1893,8 +1893,6 @@ await VerifyCS.VerifyCodeFixAsync( [ // /0/Test0.cs(11,9): info MSTEST0037: Use 'Assert.IsEmpty' instead of 'Assert.AreEqual' VerifyCS.DiagnosticIgnoringAdditionalLocations().WithLocation(0).WithArguments("IsEmpty", "AreEqual"), - // /0/Test0.cs(12,9): info MSTEST0037: Use 'Assert.IsEmpty' instead of 'Assert.AreEqual' - VerifyCS.DiagnosticIgnoringAdditionalLocations().WithLocation(1).WithArguments("IsEmpty", "AreEqual"), ], fixedCode); } @@ -1915,9 +1913,9 @@ public void MyTestMethod() var list = new List { 1, 2, 3 }; int x = 3; {|#0:Assert.AreEqual(3, list.Count)|}; - {|#1:Assert.AreEqual(list.Count, 3)|}; - {|#2:Assert.AreEqual(x, list.Count)|}; - {|#3:Assert.AreEqual(list.Count, x)|}; + Assert.AreEqual(list.Count, 3); + {|#1:Assert.AreEqual(x, list.Count)|}; + Assert.AreEqual(list.Count, x); } } """; @@ -1935,9 +1933,9 @@ public void MyTestMethod() var list = new List { 1, 2, 3 }; int x = 3; Assert.HasCount(3, list); - Assert.HasCount(3, list); - Assert.HasCount(x, list); + Assert.AreEqual(list.Count, 3); Assert.HasCount(x, list); + Assert.AreEqual(list.Count, x); } } """; @@ -1947,12 +1945,8 @@ await VerifyCS.VerifyCodeFixAsync( [ // /0/Test0.cs(12,9): info MSTEST0037: Use 'Assert.HasCount' instead of 'Assert.AreEqual' VerifyCS.DiagnosticIgnoringAdditionalLocations().WithLocation(0).WithArguments("HasCount", "AreEqual"), - // /0/Test0.cs(13,9): info MSTEST0037: Use 'Assert.HasCount' instead of 'Assert.AreEqual' - VerifyCS.DiagnosticIgnoringAdditionalLocations().WithLocation(1).WithArguments("HasCount", "AreEqual"), // /0/Test0.cs(14,9): info MSTEST0037: Use 'Assert.HasCount' instead of 'Assert.AreEqual' - VerifyCS.DiagnosticIgnoringAdditionalLocations().WithLocation(2).WithArguments("HasCount", "AreEqual"), - // /0/Test0.cs(15,9): info MSTEST0037: Use 'Assert.HasCount' instead of 'Assert.AreEqual' - VerifyCS.DiagnosticIgnoringAdditionalLocations().WithLocation(3).WithArguments("HasCount", "AreEqual"), + VerifyCS.DiagnosticIgnoringAdditionalLocations().WithLocation(1).WithArguments("HasCount", "AreEqual"), ], fixedCode); } From c743558e7a53a051942d88207ef4bb642f9f6f04 Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Sat, 27 Sep 2025 11:11:20 +0200 Subject: [PATCH 522/541] [main] Update dependencies from dotnet/arcade (#6609) Co-authored-by: dotnet-maestro[bot] --- eng/Version.Details.xml | 12 ++++++------ eng/Versions.props | 2 +- global.json | 2 +- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index aa95ee1df9..16a55f2db4 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -1,17 +1,17 @@ - + https://github.com/dotnet/arcade - dbc4dce57f6a2087f13d86e89dfb0334be3c42e2 + 432dff2f163e6a5fdb3c9052c2e58c4ab8c0e2c4 - + https://github.com/dotnet/arcade - dbc4dce57f6a2087f13d86e89dfb0334be3c42e2 + 432dff2f163e6a5fdb3c9052c2e58c4ab8c0e2c4 - + https://github.com/dotnet/arcade - dbc4dce57f6a2087f13d86e89dfb0334be3c42e2 + 432dff2f163e6a5fdb3c9052c2e58c4ab8c0e2c4 https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage diff --git a/eng/Versions.props b/eng/Versions.props index e7a901c1f5..e0786ddc8a 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -7,7 +7,7 @@ preview - 11.0.0-beta.25469.3 + 11.0.0-beta.25476.3 18.0.4-preview.25475.6 3.11.0-preview.25475.1 diff --git a/global.json b/global.json index 23153405ba..055b42b056 100644 --- a/global.json +++ b/global.json @@ -36,7 +36,7 @@ "runner": "Microsoft.Testing.Platform" }, "msbuild-sdks": { - "Microsoft.DotNet.Arcade.Sdk": "11.0.0-beta.25469.3", + "Microsoft.DotNet.Arcade.Sdk": "11.0.0-beta.25476.3", "MSBuild.Sdk.Extras": "3.0.44" } } From 103d51afb7b4852b4002356ff8b20e213850f412 Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Sat, 27 Sep 2025 11:12:03 +0200 Subject: [PATCH 523/541] [main] Update dependencies from microsoft/testfx (#6610) Co-authored-by: dotnet-maestro[bot] --- eng/Version.Details.xml | 8 ++++---- eng/Versions.props | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index 16a55f2db4..83fdb8062c 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -17,13 +17,13 @@ https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage b1e7fa5bb1a3e468b6f9d47cf61a3b5616c44713 - + https://github.com/microsoft/testfx - 74721fc4a96eefb3b757e3ffacaae1fdcbe7a0f8 + 85fcd434ec43f7a51c9f3d405294a5b9516b54c4 - + https://github.com/microsoft/testfx - 74721fc4a96eefb3b757e3ffacaae1fdcbe7a0f8 + 85fcd434ec43f7a51c9f3d405294a5b9516b54c4 diff --git a/eng/Versions.props b/eng/Versions.props index e0786ddc8a..213c0cdb0a 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -10,7 +10,7 @@ 11.0.0-beta.25476.3 18.0.4-preview.25475.6 - 3.11.0-preview.25475.1 - 1.9.0-preview.25475.1 + 3.11.0-preview.25476.4 + 1.9.0-preview.25476.4 From cca621cd1aecfb8c6f5f37315168bff19fdde072 Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Sun, 28 Sep 2025 08:35:01 +0200 Subject: [PATCH 524/541] [main] Update dependencies from microsoft/testfx (#6613) Co-authored-by: dotnet-maestro[bot] --- eng/Version.Details.xml | 8 ++++---- eng/Versions.props | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index 83fdb8062c..33e2883acf 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -17,13 +17,13 @@ https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage b1e7fa5bb1a3e468b6f9d47cf61a3b5616c44713 - + https://github.com/microsoft/testfx - 85fcd434ec43f7a51c9f3d405294a5b9516b54c4 + 103d51afb7b4852b4002356ff8b20e213850f412 - + https://github.com/microsoft/testfx - 85fcd434ec43f7a51c9f3d405294a5b9516b54c4 + 103d51afb7b4852b4002356ff8b20e213850f412 diff --git a/eng/Versions.props b/eng/Versions.props index 213c0cdb0a..57969b6cba 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -10,7 +10,7 @@ 11.0.0-beta.25476.3 18.0.4-preview.25475.6 - 3.11.0-preview.25476.4 - 1.9.0-preview.25476.4 + 3.11.0-preview.25477.1 + 1.9.0-preview.25477.1 From 7676243b3f031de055c7f8d4c6c0cac6b5cadc44 Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Sun, 28 Sep 2025 08:35:21 +0200 Subject: [PATCH 525/541] [main] Update dependencies from dotnet/arcade (#6612) Co-authored-by: dotnet-maestro[bot] --- eng/Version.Details.xml | 12 ++++++------ eng/Versions.props | 2 +- global.json | 2 +- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index 33e2883acf..57b223aa75 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -1,17 +1,17 @@ - + https://github.com/dotnet/arcade - 432dff2f163e6a5fdb3c9052c2e58c4ab8c0e2c4 + e19df003785d0b81e2e3e1bf6e588bf8d913e95e - + https://github.com/dotnet/arcade - 432dff2f163e6a5fdb3c9052c2e58c4ab8c0e2c4 + e19df003785d0b81e2e3e1bf6e588bf8d913e95e - + https://github.com/dotnet/arcade - 432dff2f163e6a5fdb3c9052c2e58c4ab8c0e2c4 + e19df003785d0b81e2e3e1bf6e588bf8d913e95e https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage diff --git a/eng/Versions.props b/eng/Versions.props index 57969b6cba..9cca6f4f2b 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -7,7 +7,7 @@ preview - 11.0.0-beta.25476.3 + 11.0.0-beta.25477.2 18.0.4-preview.25475.6 3.11.0-preview.25477.1 diff --git a/global.json b/global.json index 055b42b056..bc3fc31b2f 100644 --- a/global.json +++ b/global.json @@ -36,7 +36,7 @@ "runner": "Microsoft.Testing.Platform" }, "msbuild-sdks": { - "Microsoft.DotNet.Arcade.Sdk": "11.0.0-beta.25476.3", + "Microsoft.DotNet.Arcade.Sdk": "11.0.0-beta.25477.2", "MSBuild.Sdk.Extras": "3.0.44" } } From 1406f4d1f1831b11dd0b5e00be540b2007614425 Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Mon, 29 Sep 2025 08:45:13 +0200 Subject: [PATCH 526/541] [main] Update dependencies from microsoft/testfx (#6614) Co-authored-by: dotnet-maestro[bot] --- eng/Version.Details.xml | 8 ++++---- eng/Versions.props | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index 57b223aa75..a8ac1c6d10 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -17,13 +17,13 @@ https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage b1e7fa5bb1a3e468b6f9d47cf61a3b5616c44713 - + https://github.com/microsoft/testfx - 103d51afb7b4852b4002356ff8b20e213850f412 + 7676243b3f031de055c7f8d4c6c0cac6b5cadc44 - + https://github.com/microsoft/testfx - 103d51afb7b4852b4002356ff8b20e213850f412 + 7676243b3f031de055c7f8d4c6c0cac6b5cadc44 diff --git a/eng/Versions.props b/eng/Versions.props index 9cca6f4f2b..718adbf270 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -10,7 +10,7 @@ 11.0.0-beta.25477.2 18.0.4-preview.25475.6 - 3.11.0-preview.25477.1 - 1.9.0-preview.25477.1 + 3.11.0-preview.25477.2 + 1.9.0-preview.25477.2 From 923a2fb30d6ad3ddb140d0569a9d3710ae9fd25d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Jare=C5=A1?= Date: Mon, 29 Sep 2025 11:51:17 +0200 Subject: [PATCH 527/541] Dump child process on hang (#6574) --- .../HangDumpExtensions.cs | 1 - .../HangDumpProcessLifetimeHandler.cs | 215 +++++++++++++----- .../Helpers/IProcessExtensions.cs | 188 +++++++++++++++ .../Helpers/ProcessTreeNode.cs | 17 ++ .../Resources/ExtensionResources.resx | 19 ++ .../Resources/xlf/ExtensionResources.cs.xlf | 25 ++ .../Resources/xlf/ExtensionResources.de.xlf | 25 ++ .../Resources/xlf/ExtensionResources.es.xlf | 25 ++ .../Resources/xlf/ExtensionResources.fr.xlf | 25 ++ .../Resources/xlf/ExtensionResources.it.xlf | 25 ++ .../Resources/xlf/ExtensionResources.ja.xlf | 25 ++ .../Resources/xlf/ExtensionResources.ko.xlf | 25 ++ .../Resources/xlf/ExtensionResources.pl.xlf | 25 ++ .../xlf/ExtensionResources.pt-BR.xlf | 25 ++ .../Resources/xlf/ExtensionResources.ru.xlf | 25 ++ .../Resources/xlf/ExtensionResources.tr.xlf | 25 ++ .../xlf/ExtensionResources.zh-Hans.xlf | 25 ++ .../xlf/ExtensionResources.zh-Hant.xlf | 25 ++ .../Helpers/System/IProcess.cs | 7 +- .../Helpers/System/SystemProcess.cs | 4 +- .../HangDumpProcessTreeTests.cs | 172 ++++++++++++++ 21 files changed, 889 insertions(+), 59 deletions(-) create mode 100644 src/Platform/Microsoft.Testing.Extensions.HangDump/Helpers/IProcessExtensions.cs create mode 100644 src/Platform/Microsoft.Testing.Extensions.HangDump/Helpers/ProcessTreeNode.cs create mode 100644 test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/HangDumpProcessTreeTests.cs diff --git a/src/Platform/Microsoft.Testing.Extensions.HangDump/HangDumpExtensions.cs b/src/Platform/Microsoft.Testing.Extensions.HangDump/HangDumpExtensions.cs index f226b68da5..e0ce018e0b 100644 --- a/src/Platform/Microsoft.Testing.Extensions.HangDump/HangDumpExtensions.cs +++ b/src/Platform/Microsoft.Testing.Extensions.HangDump/HangDumpExtensions.cs @@ -36,7 +36,6 @@ public static void AddHangDumpProvider(this ITestApplicationBuilder builder) serviceProvider.GetTask(), serviceProvider.GetEnvironment(), serviceProvider.GetLoggerFactory(), - serviceProvider.GetTestApplicationModuleInfo(), serviceProvider.GetConfiguration(), serviceProvider.GetProcessHandler(), serviceProvider, diff --git a/src/Platform/Microsoft.Testing.Extensions.HangDump/HangDumpProcessLifetimeHandler.cs b/src/Platform/Microsoft.Testing.Extensions.HangDump/HangDumpProcessLifetimeHandler.cs index 03130bdd14..79f8ce2c02 100644 --- a/src/Platform/Microsoft.Testing.Extensions.HangDump/HangDumpProcessLifetimeHandler.cs +++ b/src/Platform/Microsoft.Testing.Extensions.HangDump/HangDumpProcessLifetimeHandler.cs @@ -1,9 +1,9 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using Microsoft.Testing.Extensions.Diagnostics.Helpers; using Microsoft.Testing.Extensions.Diagnostics.Resources; using Microsoft.Testing.Extensions.HangDump.Serializers; -using Microsoft.Testing.Platform; using Microsoft.Testing.Platform.CommandLine; using Microsoft.Testing.Platform.Configurations; using Microsoft.Testing.Platform.Extensions.Messages; @@ -32,7 +32,7 @@ internal sealed class HangDumpProcessLifetimeHandler : ITestHostProcessLifetimeH #endif { private readonly IMessageBus _messageBus; - private readonly IOutputDevice _outputDisplay; + private readonly OutputDeviceWriter _outputDisplay; private readonly ICommandLineOptions _commandLineOptions; private readonly ITask _task; private readonly IEnvironment _environment; @@ -45,6 +45,7 @@ internal sealed class HangDumpProcessLifetimeHandler : ITestHostProcessLifetimeH private readonly ILogger _logger; private readonly ManualResetEventSlim _mutexNameReceived = new(false); private readonly ManualResetEventSlim _waitConsumerPipeName = new(false); + private readonly List _dumpFiles = []; private TimeSpan _activityTimerValue = TimeSpan.FromMinutes(30); private Task? _waitConnectionTask; @@ -53,21 +54,19 @@ internal sealed class HangDumpProcessLifetimeHandler : ITestHostProcessLifetimeH private string? _activityTimerMutexName; private bool _exitActivityIndicatorTask; private string _dumpType = "Full"; - private string _dumpFileNamePattern; + private string? _dumpFileNamePattern; private Mutex? _activityIndicatorMutex; private ITestHostProcessInformation? _testHostProcessInformation; - private string _dumpFileTaken = string.Empty; private NamedPipeClient? _namedPipeClient; public HangDumpProcessLifetimeHandler( PipeNameDescription pipeNameDescription, IMessageBus messageBus, - IOutputDevice outputDisplay, + IOutputDevice outputDevice, ICommandLineOptions commandLineOptions, ITask task, IEnvironment environment, ILoggerFactory loggerFactory, - ITestApplicationModuleInfo testApplicationModuleInfo, IConfiguration configuration, IProcessHandler processHandler, IServiceProvider serviceProvider, @@ -77,7 +76,7 @@ public HangDumpProcessLifetimeHandler( _traceEnabled = _logger.IsEnabled(LogLevel.Trace); _pipeNameDescription = pipeNameDescription; _messageBus = messageBus; - _outputDisplay = outputDisplay; + _outputDisplay = new OutputDeviceWriter(outputDevice, this); _commandLineOptions = commandLineOptions; _task = task; _environment = environment; @@ -85,7 +84,6 @@ public HangDumpProcessLifetimeHandler( _processHandler = processHandler; _clock = clock; _testApplicationCancellationTokenSource = serviceProvider.GetTestApplicationCancellationTokenSource(); - _dumpFileNamePattern = $"{Path.GetFileNameWithoutExtension(testApplicationModuleInfo.GetCurrentTestApplicationFullPath())}_%p_hang.dmp"; } public string Uid => nameof(HangDumpProcessLifetimeHandler); @@ -196,11 +194,11 @@ public async Task OnTestHostProcessStartedAsync(ITestHostProcessInformation test { try { - await ActivityTimerAsync().ConfigureAwait(false); + await ActivityTimerAsync(cancellation).ConfigureAwait(false); } catch (Exception e) { - await _outputDisplay.DisplayAsync(this, new ErrorMessageOutputDeviceData(string.Format(CultureInfo.InvariantCulture, ExtensionResources.HangDumpFailed, e.ToString(), GetDiskInfo()))).ConfigureAwait(false); + await _outputDisplay.DisplayAsync(new ErrorMessageOutputDeviceData(string.Format(CultureInfo.InvariantCulture, ExtensionResources.HangDumpFailed, e.ToString(), GetDiskInfo()))).ConfigureAwait(false); throw; } }, "[HangDump] ActivityTimerAsync", cancellation); @@ -242,17 +240,17 @@ public async Task OnTestHostProcessExitedAsync(ITestHostProcessInformation testH _activityIndicatorMutex?.Dispose(); } - if (!RoslynString.IsNullOrEmpty(_dumpFileTaken)) + foreach (string dumpFile in _dumpFiles) { - await _messageBus.PublishAsync(this, new FileArtifact(new FileInfo(_dumpFileTaken), ExtensionResources.HangDumpArtifactDisplayName, ExtensionResources.HangDumpArtifactDescription)).ConfigureAwait(false); + await _messageBus.PublishAsync(this, new FileArtifact(new FileInfo(dumpFile), ExtensionResources.HangDumpArtifactDisplayName, ExtensionResources.HangDumpArtifactDescription)).ConfigureAwait(false); } } - private async Task ActivityTimerAsync() + private async Task ActivityTimerAsync(CancellationToken cancellationToken) { _logger.LogDebug("Wait for mutex name from the test host"); - if (!_mutexNameReceived.Wait(TimeoutHelper.DefaultHangTimeSpanTimeout)) + if (!_mutexNameReceived.Wait(TimeoutHelper.DefaultHangTimeSpanTimeout, cancellationToken)) { throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, ExtensionResources.MutexNameReceptionTimeoutErrorMessage, TimeoutHelper.DefaultHangTimeoutSeconds)); } @@ -340,19 +338,97 @@ private async Task ActivityTimerAsync() if (timeoutFired) { - await TakeDumpAsync().ConfigureAwait(false); + await TakeDumpOfTreeAsync(cancellationToken).ConfigureAwait(false); } } - private async Task TakeDumpAsync() + private async Task TakeDumpOfTreeAsync(CancellationToken cancellationToken) { ApplicationStateGuard.Ensure(_testHostProcessInformation is not null); - ApplicationStateGuard.Ensure(_dumpType is not null); await _logger.LogInformationAsync($"Hang dump timeout({_activityTimerValue}) expired.").ConfigureAwait(false); - await _outputDisplay.DisplayAsync(this, new ErrorMessageOutputDeviceData(string.Format(CultureInfo.InvariantCulture, ExtensionResources.HangDumpTimeoutExpired, _activityTimerValue))).ConfigureAwait(false); + await _outputDisplay.DisplayAsync(new ErrorMessageOutputDeviceData(string.Format(CultureInfo.InvariantCulture, ExtensionResources.HangDumpTimeoutExpired, _activityTimerValue))).ConfigureAwait(false); + + using IProcess process = _processHandler.GetProcessById(_testHostProcessInformation.PID); + var processTree = (await process.GetProcessTreeAsync(_logger, _outputDisplay, cancellationToken).ConfigureAwait(false)).Where(p => p.Process?.Name is not null and not "conhost" and not "WerFault").ToList(); + IEnumerable bottomUpTree = processTree.OrderByDescending(t => t.Level).Select(t => t.Process).OfType(); + + try + { + if (processTree.Count > 1) + { + await _outputDisplay.DisplayAsync(new ErrorMessageOutputDeviceData(ExtensionResources.DumpingProcessTree)).ConfigureAwait(false); + + foreach (ProcessTreeNode? p in processTree.OrderBy(t => t.Level)) + { + await _outputDisplay.DisplayAsync(new ErrorMessageOutputDeviceData($"{(p.Level != 0 ? " + " : " > ")}{new string('-', p.Level)} {p.Process!.Id} - {p.Process.Name}")).ConfigureAwait(false); + } + } + else + { + await _outputDisplay.DisplayAsync(new ErrorMessageOutputDeviceData(string.Format(CultureInfo.InvariantCulture, ExtensionResources.DumpingProcess, process.Id, process.Name))).ConfigureAwait(false); + } + + await _logger.LogInformationAsync($"Hang dump timeout({_activityTimerValue}) expired.").ConfigureAwait(false); + + // Do not suspend processes with NetClient dumper it stops the diagnostic thread running in + // them and hang dump request will get stuck forever, because the process is not co-operating. + // Instead we start one task per dump asynchronously, and hope that the parent process will start dumping + // before the child process is done dumping. This way if the parent is waiting for the children to exit, + // we will be dumping it before it observes the child exiting and we get a more accurate results. If we did not + // do this, then parent that is awaiting child might exit before we get to dumping it. + foreach (IProcess p in bottomUpTree) + { + try + { + await TakeDumpAsync(p).ConfigureAwait(false); + } + catch (Exception e) + { + // exceptions.Add(new InvalidOperationException($"Error while taking dump of process {p.Name} {p.Id}", e)); + await _logger.LogErrorAsync($"Error while taking dump of process {p.Id} - {p.Name}", e).ConfigureAwait(false); + await _outputDisplay.DisplayAsync(new ErrorMessageOutputDeviceData(string.Format(CultureInfo.InvariantCulture, ExtensionResources.ErrorWhileDumpingProcess, p.Id, p.Name, e))).ConfigureAwait(false); + } + } + } + finally + { + NotifyCrashDumpServiceIfEnabled(); + + // Some of the processes might crashed, which breaks the process tree (on windows it is just an illusion), + // so try extra hard to kill all the known processes in the tree, since we already spent a bunch of time getting + // to know which processes are involved. + foreach (ProcessTreeNode node in processTree) + { + IProcess? p = node.Process; + if (p == null) + { + continue; + } - string finalDumpFileName = _dumpFileNamePattern.Replace("%p", _testHostProcessInformation.PID.ToString(CultureInfo.InvariantCulture)); + try + { + if (!p.HasExited) + { + p.Kill(); + await p.WaitForExitAsync().ConfigureAwait(false); + } + } + catch (Exception e) + { + await _logger.LogErrorAsync($"Problem killing {p.Id} - {p.Name}", e).ConfigureAwait(false); + await _outputDisplay.DisplayAsync(new ErrorMessageOutputDeviceData(string.Format(CultureInfo.InvariantCulture, ExtensionResources.ErrorKillingProcess, p.Id, p.Name, e))).ConfigureAwait(false); + } + } + } + } + + private async Task TakeDumpAsync(IProcess process) + { + ApplicationStateGuard.Ensure(_testHostProcessInformation is not null); + ApplicationStateGuard.Ensure(_dumpType is not null); + + string finalDumpFileName = (_dumpFileNamePattern ?? $"{process.Name}_%p_hang.dmp").Replace("%p", process.Id.ToString(CultureInfo.InvariantCulture)); finalDumpFileName = Path.Combine(_configuration.GetTestResultDirectory(), finalDumpFileName); ApplicationStateGuard.Ensure(_namedPipeClient is not null); @@ -364,11 +440,11 @@ private async Task TakeDumpAsync() using (FileStream fs = File.OpenWrite(hangTestsFileName)) using (StreamWriter sw = new(fs)) { - await _outputDisplay.DisplayAsync(this, new ErrorMessageOutputDeviceData(ExtensionResources.RunningTestsWhileDumping)).ConfigureAwait(false); + await _outputDisplay.DisplayAsync(new ErrorMessageOutputDeviceData(ExtensionResources.RunningTestsWhileDumping)).ConfigureAwait(false); foreach ((string testName, int seconds) in tests.Tests) { await sw.WriteLineAsync($"[{TimeSpan.FromSeconds(seconds)}] {testName}").ConfigureAwait(false); - await _outputDisplay.DisplayAsync(this, new ErrorMessageOutputDeviceData($"[{TimeSpan.FromSeconds(seconds)}] {testName}")).ConfigureAwait(false); + await _outputDisplay.DisplayAsync(new ErrorMessageOutputDeviceData($"[{TimeSpan.FromSeconds(seconds)}] {testName}")).ConfigureAwait(false); } } @@ -377,50 +453,57 @@ private async Task TakeDumpAsync() await _logger.LogInformationAsync($"Creating dump filename {finalDumpFileName}").ConfigureAwait(false); - await _outputDisplay.DisplayAsync(this, new ErrorMessageOutputDeviceData(string.Format(CultureInfo.InvariantCulture, ExtensionResources.CreatingDumpFile, finalDumpFileName))).ConfigureAwait(false); + await _outputDisplay.DisplayAsync(new ErrorMessageOutputDeviceData(string.Format(CultureInfo.InvariantCulture, ExtensionResources.CreatingDumpFile, finalDumpFileName))).ConfigureAwait(false); + +#if NETCOREAPP + DiagnosticsClient diagnosticsClient = new(process.Id); + DumpType dumpType = _dumpType.ToLowerInvariant().Trim() switch + { + "mini" => DumpType.Normal, + "heap" => DumpType.WithHeap, + "triage" => DumpType.Triage, + "full" => DumpType.Full, + _ => throw ApplicationStateGuard.Unreachable(), + }; + + // Wrap the dump path into "" when it has space in it, this is a workaround for this runtime issue: https://github.com/dotnet/diagnostics/issues/5020 + // It only affects windows. Otherwise the dump creation fails with: [createdump] The pid argument is no longer supported + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && finalDumpFileName.Contains(' ')) + { + finalDumpFileName = $"\"{finalDumpFileName}\""; + } try { -#if NETCOREAPP - DiagnosticsClient diagnosticsClient = new(_testHostProcessInformation.PID); - DumpType dumpType = _dumpType.ToLowerInvariant().Trim() switch - { - "mini" => DumpType.Normal, - "heap" => DumpType.WithHeap, - "triage" => DumpType.Triage, - "full" => DumpType.Full, - _ => throw ApplicationStateGuard.Unreachable(), - }; - - // Wrap the dump path into "" when it has space in it, this is a workaround for this runtime issue: https://github.com/dotnet/diagnostics/issues/5020 - // It only affects windows. Otherwise the dump creation fails with: [createdump] The pid argument is no longer supported - if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && finalDumpFileName.Contains(' ')) - { - finalDumpFileName = $"\"{finalDumpFileName}\""; - } + diagnosticsClient.WriteDump(dumpType, finalDumpFileName, logDumpGeneration: false); + } + catch (Exception e) + { + await _logger.LogErrorAsync($"Error while writing dump of process {process.Name} {process.Id}", e).ConfigureAwait(false); + await _outputDisplay.DisplayAsync(new ErrorMessageOutputDeviceData(string.Format(CultureInfo.InvariantCulture, ExtensionResources.ErrorWhileDumpingProcess, process.Id, process.Name, e))).ConfigureAwait(false); + } - diagnosticsClient.WriteDump(dumpType, finalDumpFileName, true); #else - MiniDumpWriteDump.MiniDumpTypeOption miniDumpTypeOption = _dumpType.ToLowerInvariant().Trim() switch - { - "mini" => MiniDumpWriteDump.MiniDumpTypeOption.Mini, - "heap" => MiniDumpWriteDump.MiniDumpTypeOption.Heap, - "full" => MiniDumpWriteDump.MiniDumpTypeOption.Full, - _ => throw ApplicationStateGuard.Unreachable(), - }; - - MiniDumpWriteDump.CollectDumpUsingMiniDumpWriteDump(_testHostProcessInformation.PID, finalDumpFileName, miniDumpTypeOption); -#endif + MiniDumpWriteDump.MiniDumpTypeOption miniDumpTypeOption = _dumpType.ToLowerInvariant().Trim() switch + { + "mini" => MiniDumpWriteDump.MiniDumpTypeOption.Mini, + "heap" => MiniDumpWriteDump.MiniDumpTypeOption.Heap, + "full" => MiniDumpWriteDump.MiniDumpTypeOption.Full, + _ => throw ApplicationStateGuard.Unreachable(), + }; - _dumpFileTaken = finalDumpFileName; + try + { + MiniDumpWriteDump.CollectDumpUsingMiniDumpWriteDump(process.Id, finalDumpFileName, miniDumpTypeOption); } - finally + catch (Exception e) { - NotifyCrashDumpServiceIfEnabled(); - using IProcess process = _processHandler.GetProcessById(_testHostProcessInformation.PID); - process.Kill(); - await process.WaitForExitAsync().ConfigureAwait(false); + await _logger.LogErrorAsync($"Error while writing dump of process {process.Name} {process.Id}", e).ConfigureAwait(false); + await _outputDisplay.DisplayAsync(new ErrorMessageOutputDeviceData(string.Format(CultureInfo.InvariantCulture, ExtensionResources.ErrorWhileDumpingProcess, process.Id, process.Name, e))).ConfigureAwait(false); } +#endif + + _dumpFiles.Add(finalDumpFileName); } private static void NotifyCrashDumpServiceIfEnabled() @@ -459,3 +542,23 @@ public async ValueTask DisposeAsync() } #endif } + +internal sealed class OutputDeviceWriter +{ + private readonly IOutputDevice _outputDevice; + private readonly IOutputDeviceDataProducer _outputDeviceDataProducer; + + public OutputDeviceWriter(IOutputDevice outputDevice, IOutputDeviceDataProducer outputDeviceDataProducer) + { + _outputDevice = outputDevice; + _outputDeviceDataProducer = outputDeviceDataProducer; + } + + /// + /// Displays the output data asynchronously, using the stored producer. + /// + /// The output data. + /// A task representing the asynchronous operation. + public async Task DisplayAsync(IOutputDeviceData data) + => await _outputDevice.DisplayAsync(_outputDeviceDataProducer, data).ConfigureAwait(false); +} diff --git a/src/Platform/Microsoft.Testing.Extensions.HangDump/Helpers/IProcessExtensions.cs b/src/Platform/Microsoft.Testing.Extensions.HangDump/Helpers/IProcessExtensions.cs new file mode 100644 index 0000000000..5ff92df9e8 --- /dev/null +++ b/src/Platform/Microsoft.Testing.Extensions.HangDump/Helpers/IProcessExtensions.cs @@ -0,0 +1,188 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using Microsoft.Testing.Extensions.Diagnostics.Resources; +using Microsoft.Testing.Platform; +using Microsoft.Testing.Platform.Helpers; +using Microsoft.Testing.Platform.Logging; +using Microsoft.Testing.Platform.OutputDevice; + +namespace Microsoft.Testing.Extensions.Diagnostics.Helpers; + +/// +/// Helper functions for IProcess. +/// +internal static class IProcessExtensions +{ + private const int InvalidProcessId = -1; + + public static async Task> GetProcessTreeAsync(this IProcess process, ILogger logger, OutputDeviceWriter outputDisplay, CancellationToken cancellationToken) + { + var childProcesses = Process.GetProcesses() + .Where(p => IsChildCandidate(p, process)) + .ToList(); + + var acc = new List(); + foreach (Process c in childProcesses) + { + cancellationToken.ThrowIfCancellationRequested(); + + try + { + int parentId = await GetParentPidAsync(c, logger, outputDisplay).ConfigureAwait(false); + + acc.Add(new ProcessTreeNode { ParentId = parentId, Process = new SystemProcess(c) }); + } + catch (Exception e) + { + logger.LogError($"Failed to get parent for process {c.Id} - {c.ProcessName}", e); + await outputDisplay.DisplayAsync(new ErrorMessageOutputDeviceData(string.Format(CultureInfo.InvariantCulture, ExtensionResources.ErrorGettingParentOfProcess, c.Id, c.ProcessName, e))).ConfigureAwait(false); + } + } + + int level = 1; + int limit = 10; + ResolveChildren(process, logger, acc, level, limit); + + return [new() { Process = process, Level = 0 }, .. acc.Where(a => a.Level > 0)]; + } + + /// + /// Returns the parent id of a process or -1 if it fails. + /// + /// The process to find parent of. + /// The logger. + /// The output display.git. + /// The pid of the parent process. + internal static async Task GetParentPidAsync(Process process, ILogger logger, OutputDeviceWriter outputDisplay) + => RuntimeInformation.IsOSPlatform(OSPlatform.Windows) + ? await GetParentPidWindowsAsync(process).ConfigureAwait(false) + : RuntimeInformation.IsOSPlatform(OSPlatform.Linux) + ? await GetParentPidLinuxAsync(process).ConfigureAwait(false) + : RuntimeInformation.IsOSPlatform(OSPlatform.OSX) ? + await GetParentPidMacOsAsync(process, logger, outputDisplay).ConfigureAwait(false) + : throw new PlatformNotSupportedException(); + + internal static Task GetParentPidWindowsAsync(Process process) + { + IntPtr handle = process.Handle; + int res = NtQueryInformationProcess(handle, 0, out ProcessBasicInformation pbi, Marshal.SizeOf(), out int _); + + int p = res != 0 ? InvalidProcessId : pbi.InheritedFromUniqueProcessId.ToInt32(); + + return Task.FromResult(p); + } + + /// Read the /proc file system for information about the parent. + /// The process to get the parent process from. + /// The process id. + internal static Task GetParentPidLinuxAsync(Process process) + { + int pid = process.Id; + + // read /proc//stat + // 4th column will contain the ppid, 92 in the example below + // ex: 93 (bash) S 92 93 2 4294967295 ... + string path = $"/proc/{pid}/stat"; + string stat = File.ReadAllText(path); + string[] parts = stat.Split(' '); + + int ppid = parts.Length < 5 ? InvalidProcessId : int.Parse(parts[3], CultureInfo.CurrentCulture); + + return Task.FromResult(ppid); + } + + internal static async Task GetParentPidMacOsAsync(Process process, ILogger logger, OutputDeviceWriter outputDisplay) + { + var output = new StringBuilder(); + var err = new StringBuilder(); + Process ps = new(); + ps.StartInfo.FileName = "ps"; + ps.StartInfo.Arguments = $"-o ppid= {process.Id}"; + ps.StartInfo.UseShellExecute = false; + ps.StartInfo.RedirectStandardOutput = true; + ps.StartInfo.RedirectStandardError = true; + ps.OutputDataReceived += (_, e) => output.Append(e.Data); + ps.ErrorDataReceived += (_, e) => err.Append(e.Data); + ps.Start(); + ps.BeginOutputReadLine(); + ps.BeginErrorReadLine(); + + int timeout = 5_000; +#if !NETSTANDARD2_0 + // This will read the output streams till the end. + await ps.WaitForExitAsync(new CancellationTokenSource(timeout).Token).ConfigureAwait(false); +#else + // This won't read the streams till the end. If we timeout, we need to use the + // wait without timeout, but that can hang, so we offload that into a task so we can abandon it and continue. + if (!ps.WaitForExit(timeout)) + { + await Task.Run(ps.WaitForExit, new CancellationTokenSource(timeout).Token).ConfigureAwait(false); + } +#endif + + string o = output.ToString(); + string e = err.ToString(); + + int parent = int.TryParse(o.Trim(), out int ppid) ? ppid : InvalidProcessId; + + if (!RoslynString.IsNullOrWhiteSpace(e)) + { + logger.LogError($"Error getting parent of process {process.Id} - {process.ProcessName}, {e}."); + await outputDisplay.DisplayAsync(new ErrorMessageOutputDeviceData(string.Format(CultureInfo.InvariantCulture, ExtensionResources.ErrorGettingParentOfProcess, process.Id, process.ProcessName, e))).ConfigureAwait(false); + } + + return parent; + } + + private static void ResolveChildren(IProcess parent, ILogger logger, List acc, int level, int limit) + { + if (limit < 0) + { + // hit recursion limit, just returning + return; + } + + // only take children that are newer than the parent, because process ids (PIDs) get recycled + var children = acc.Where(p => p.ParentId == parent.Id && p.Process?.StartTime > parent.StartTime).ToList(); + + foreach (ProcessTreeNode child in children) + { + child.Level = level; + ResolveChildren(child.Process!, logger, acc, level + 1, limit); + } + } + + private static bool IsChildCandidate(Process child, IProcess parent) + { + // this is extremely slow under debugger, but fast without it + try + { + return child.StartTime > parent.StartTime && child.Id != parent.Id; + } + catch + { + /* access denied or process has exits most likely */ + return false; + } + } + + [StructLayout(LayoutKind.Sequential)] + private struct ProcessBasicInformation + { + public readonly IntPtr ExitStatus; + public readonly IntPtr PebBaseAddress; + public readonly IntPtr AffinityMask; + public readonly IntPtr BasePriority; + public readonly IntPtr UniqueProcessId; + public IntPtr InheritedFromUniqueProcessId; + } + + [DllImport("ntdll.dll", SetLastError = true)] + private static extern int NtQueryInformationProcess( + IntPtr processHandle, + int processInformationClass, + out ProcessBasicInformation processInformation, + int processInformationLength, + out int returnLength); +} diff --git a/src/Platform/Microsoft.Testing.Extensions.HangDump/Helpers/ProcessTreeNode.cs b/src/Platform/Microsoft.Testing.Extensions.HangDump/Helpers/ProcessTreeNode.cs new file mode 100644 index 0000000000..0b8d1aa99a --- /dev/null +++ b/src/Platform/Microsoft.Testing.Extensions.HangDump/Helpers/ProcessTreeNode.cs @@ -0,0 +1,17 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using Microsoft.Testing.Platform.Helpers; + +namespace Microsoft.Testing.Extensions.Diagnostics.Helpers; + +internal sealed class ProcessTreeNode +{ + public IProcess? Process { get; set; } + + public int Level { get; set; } + + public int ParentId { get; set; } + + public Process? ParentProcess { get; set; } +} diff --git a/src/Platform/Microsoft.Testing.Extensions.HangDump/Resources/ExtensionResources.resx b/src/Platform/Microsoft.Testing.Extensions.HangDump/Resources/ExtensionResources.resx index c49f7c7c4d..9f26cb952d 100644 --- a/src/Platform/Microsoft.Testing.Extensions.HangDump/Resources/ExtensionResources.resx +++ b/src/Platform/Microsoft.Testing.Extensions.HangDump/Resources/ExtensionResources.resx @@ -120,6 +120,25 @@ Creating dump file '{0}' + + Dumping process {0} - {1} + 0 is pid, 1 is the name of the process + + + Dumping this process tree (from bottom): + + + Error getting parent of process {0} - {1}: {2}" + 0 is pid, 1 is name, 2 is the exception + + + Error while killing process {0} - {1}: {2} + 0 is pid, 1 is name, 2 is the exception + + + Error while taking dump of process {0} - {1}: {2} + 0 is pid, 1 is name, 2 is the exception from the system + The hang dump file diff --git a/src/Platform/Microsoft.Testing.Extensions.HangDump/Resources/xlf/ExtensionResources.cs.xlf b/src/Platform/Microsoft.Testing.Extensions.HangDump/Resources/xlf/ExtensionResources.cs.xlf index ca975dba15..84139c78be 100644 --- a/src/Platform/Microsoft.Testing.Extensions.HangDump/Resources/xlf/ExtensionResources.cs.xlf +++ b/src/Platform/Microsoft.Testing.Extensions.HangDump/Resources/xlf/ExtensionResources.cs.xlf @@ -7,6 +7,31 @@ Vytváří se soubor výpisu paměti {0}. + + Dumping process {0} - {1} + Dumping process {0} - {1} + 0 is pid, 1 is the name of the process + + + Dumping this process tree (from bottom): + Dumping this process tree (from bottom): + + + + Error getting parent of process {0} - {1}: {2}" + Error getting parent of process {0} - {1}: {2}" + 0 is pid, 1 is name, 2 is the exception + + + Error while killing process {0} - {1}: {2} + Error while killing process {0} - {1}: {2} + 0 is pid, 1 is name, 2 is the exception + + + Error while taking dump of process {0} - {1}: {2} + Error while taking dump of process {0} - {1}: {2} + 0 is pid, 1 is name, 2 is the exception from the system + The hang dump file Soubor výpisu paměti při zablokování diff --git a/src/Platform/Microsoft.Testing.Extensions.HangDump/Resources/xlf/ExtensionResources.de.xlf b/src/Platform/Microsoft.Testing.Extensions.HangDump/Resources/xlf/ExtensionResources.de.xlf index c2984eecb4..dfd150b085 100644 --- a/src/Platform/Microsoft.Testing.Extensions.HangDump/Resources/xlf/ExtensionResources.de.xlf +++ b/src/Platform/Microsoft.Testing.Extensions.HangDump/Resources/xlf/ExtensionResources.de.xlf @@ -7,6 +7,31 @@ Speicherabbilddatei "{0}" wird erstellt + + Dumping process {0} - {1} + Dumping process {0} - {1} + 0 is pid, 1 is the name of the process + + + Dumping this process tree (from bottom): + Dumping this process tree (from bottom): + + + + Error getting parent of process {0} - {1}: {2}" + Error getting parent of process {0} - {1}: {2}" + 0 is pid, 1 is name, 2 is the exception + + + Error while killing process {0} - {1}: {2} + Error while killing process {0} - {1}: {2} + 0 is pid, 1 is name, 2 is the exception + + + Error while taking dump of process {0} - {1}: {2} + Error while taking dump of process {0} - {1}: {2} + 0 is pid, 1 is name, 2 is the exception from the system + The hang dump file Die Absturzspeicherabbilddatei diff --git a/src/Platform/Microsoft.Testing.Extensions.HangDump/Resources/xlf/ExtensionResources.es.xlf b/src/Platform/Microsoft.Testing.Extensions.HangDump/Resources/xlf/ExtensionResources.es.xlf index bd2919495c..82228ab65e 100644 --- a/src/Platform/Microsoft.Testing.Extensions.HangDump/Resources/xlf/ExtensionResources.es.xlf +++ b/src/Platform/Microsoft.Testing.Extensions.HangDump/Resources/xlf/ExtensionResources.es.xlf @@ -7,6 +7,31 @@ Creando archivo de volcado '{0}' + + Dumping process {0} - {1} + Dumping process {0} - {1} + 0 is pid, 1 is the name of the process + + + Dumping this process tree (from bottom): + Dumping this process tree (from bottom): + + + + Error getting parent of process {0} - {1}: {2}" + Error getting parent of process {0} - {1}: {2}" + 0 is pid, 1 is name, 2 is the exception + + + Error while killing process {0} - {1}: {2} + Error while killing process {0} - {1}: {2} + 0 is pid, 1 is name, 2 is the exception + + + Error while taking dump of process {0} - {1}: {2} + Error while taking dump of process {0} - {1}: {2} + 0 is pid, 1 is name, 2 is the exception from the system + The hang dump file El archivo de volcado de memoria diff --git a/src/Platform/Microsoft.Testing.Extensions.HangDump/Resources/xlf/ExtensionResources.fr.xlf b/src/Platform/Microsoft.Testing.Extensions.HangDump/Resources/xlf/ExtensionResources.fr.xlf index 62e6150c3e..f4fae09fd4 100644 --- a/src/Platform/Microsoft.Testing.Extensions.HangDump/Resources/xlf/ExtensionResources.fr.xlf +++ b/src/Platform/Microsoft.Testing.Extensions.HangDump/Resources/xlf/ExtensionResources.fr.xlf @@ -7,6 +7,31 @@ Création du fichier de vidage «{0}» + + Dumping process {0} - {1} + Dumping process {0} - {1} + 0 is pid, 1 is the name of the process + + + Dumping this process tree (from bottom): + Dumping this process tree (from bottom): + + + + Error getting parent of process {0} - {1}: {2}" + Error getting parent of process {0} - {1}: {2}" + 0 is pid, 1 is name, 2 is the exception + + + Error while killing process {0} - {1}: {2} + Error while killing process {0} - {1}: {2} + 0 is pid, 1 is name, 2 is the exception + + + Error while taking dump of process {0} - {1}: {2} + Error while taking dump of process {0} - {1}: {2} + 0 is pid, 1 is name, 2 is the exception from the system + The hang dump file Fichier de vidage de blocage diff --git a/src/Platform/Microsoft.Testing.Extensions.HangDump/Resources/xlf/ExtensionResources.it.xlf b/src/Platform/Microsoft.Testing.Extensions.HangDump/Resources/xlf/ExtensionResources.it.xlf index 753a327bc3..a639e8bb5a 100644 --- a/src/Platform/Microsoft.Testing.Extensions.HangDump/Resources/xlf/ExtensionResources.it.xlf +++ b/src/Platform/Microsoft.Testing.Extensions.HangDump/Resources/xlf/ExtensionResources.it.xlf @@ -7,6 +7,31 @@ Creazione del file di dump '{0}' + + Dumping process {0} - {1} + Dumping process {0} - {1} + 0 is pid, 1 is the name of the process + + + Dumping this process tree (from bottom): + Dumping this process tree (from bottom): + + + + Error getting parent of process {0} - {1}: {2}" + Error getting parent of process {0} - {1}: {2}" + 0 is pid, 1 is name, 2 is the exception + + + Error while killing process {0} - {1}: {2} + Error while killing process {0} - {1}: {2} + 0 is pid, 1 is name, 2 is the exception + + + Error while taking dump of process {0} - {1}: {2} + Error while taking dump of process {0} - {1}: {2} + 0 is pid, 1 is name, 2 is the exception from the system + The hang dump file Il file di dump di blocco diff --git a/src/Platform/Microsoft.Testing.Extensions.HangDump/Resources/xlf/ExtensionResources.ja.xlf b/src/Platform/Microsoft.Testing.Extensions.HangDump/Resources/xlf/ExtensionResources.ja.xlf index bd9a93f75a..3de6abfab9 100644 --- a/src/Platform/Microsoft.Testing.Extensions.HangDump/Resources/xlf/ExtensionResources.ja.xlf +++ b/src/Platform/Microsoft.Testing.Extensions.HangDump/Resources/xlf/ExtensionResources.ja.xlf @@ -7,6 +7,31 @@ ダンプ ファイル '{0}' を作成しています + + Dumping process {0} - {1} + Dumping process {0} - {1} + 0 is pid, 1 is the name of the process + + + Dumping this process tree (from bottom): + Dumping this process tree (from bottom): + + + + Error getting parent of process {0} - {1}: {2}" + Error getting parent of process {0} - {1}: {2}" + 0 is pid, 1 is name, 2 is the exception + + + Error while killing process {0} - {1}: {2} + Error while killing process {0} - {1}: {2} + 0 is pid, 1 is name, 2 is the exception + + + Error while taking dump of process {0} - {1}: {2} + Error while taking dump of process {0} - {1}: {2} + 0 is pid, 1 is name, 2 is the exception from the system + The hang dump file ハング ダンプ ファイル diff --git a/src/Platform/Microsoft.Testing.Extensions.HangDump/Resources/xlf/ExtensionResources.ko.xlf b/src/Platform/Microsoft.Testing.Extensions.HangDump/Resources/xlf/ExtensionResources.ko.xlf index 310583594e..70a9ee5648 100644 --- a/src/Platform/Microsoft.Testing.Extensions.HangDump/Resources/xlf/ExtensionResources.ko.xlf +++ b/src/Platform/Microsoft.Testing.Extensions.HangDump/Resources/xlf/ExtensionResources.ko.xlf @@ -7,6 +7,31 @@ 덤프 파일 '{0}'을(를) 만드는 중 + + Dumping process {0} - {1} + Dumping process {0} - {1} + 0 is pid, 1 is the name of the process + + + Dumping this process tree (from bottom): + Dumping this process tree (from bottom): + + + + Error getting parent of process {0} - {1}: {2}" + Error getting parent of process {0} - {1}: {2}" + 0 is pid, 1 is name, 2 is the exception + + + Error while killing process {0} - {1}: {2} + Error while killing process {0} - {1}: {2} + 0 is pid, 1 is name, 2 is the exception + + + Error while taking dump of process {0} - {1}: {2} + Error while taking dump of process {0} - {1}: {2} + 0 is pid, 1 is name, 2 is the exception from the system + The hang dump file 중단 덤프 파일 diff --git a/src/Platform/Microsoft.Testing.Extensions.HangDump/Resources/xlf/ExtensionResources.pl.xlf b/src/Platform/Microsoft.Testing.Extensions.HangDump/Resources/xlf/ExtensionResources.pl.xlf index e3a316ebf1..c205dce991 100644 --- a/src/Platform/Microsoft.Testing.Extensions.HangDump/Resources/xlf/ExtensionResources.pl.xlf +++ b/src/Platform/Microsoft.Testing.Extensions.HangDump/Resources/xlf/ExtensionResources.pl.xlf @@ -7,6 +7,31 @@ Tworzenie pliku zrzutu „{0}” + + Dumping process {0} - {1} + Dumping process {0} - {1} + 0 is pid, 1 is the name of the process + + + Dumping this process tree (from bottom): + Dumping this process tree (from bottom): + + + + Error getting parent of process {0} - {1}: {2}" + Error getting parent of process {0} - {1}: {2}" + 0 is pid, 1 is name, 2 is the exception + + + Error while killing process {0} - {1}: {2} + Error while killing process {0} - {1}: {2} + 0 is pid, 1 is name, 2 is the exception + + + Error while taking dump of process {0} - {1}: {2} + Error while taking dump of process {0} - {1}: {2} + 0 is pid, 1 is name, 2 is the exception from the system + The hang dump file Plik zrzutu zawieszenia diff --git a/src/Platform/Microsoft.Testing.Extensions.HangDump/Resources/xlf/ExtensionResources.pt-BR.xlf b/src/Platform/Microsoft.Testing.Extensions.HangDump/Resources/xlf/ExtensionResources.pt-BR.xlf index 437cca313e..585619f8f4 100644 --- a/src/Platform/Microsoft.Testing.Extensions.HangDump/Resources/xlf/ExtensionResources.pt-BR.xlf +++ b/src/Platform/Microsoft.Testing.Extensions.HangDump/Resources/xlf/ExtensionResources.pt-BR.xlf @@ -7,6 +7,31 @@ Criando arquivo de despejo ''{0}'' + + Dumping process {0} - {1} + Dumping process {0} - {1} + 0 is pid, 1 is the name of the process + + + Dumping this process tree (from bottom): + Dumping this process tree (from bottom): + + + + Error getting parent of process {0} - {1}: {2}" + Error getting parent of process {0} - {1}: {2}" + 0 is pid, 1 is name, 2 is the exception + + + Error while killing process {0} - {1}: {2} + Error while killing process {0} - {1}: {2} + 0 is pid, 1 is name, 2 is the exception + + + Error while taking dump of process {0} - {1}: {2} + Error while taking dump of process {0} - {1}: {2} + 0 is pid, 1 is name, 2 is the exception from the system + The hang dump file O arquivo de despejo de travamento diff --git a/src/Platform/Microsoft.Testing.Extensions.HangDump/Resources/xlf/ExtensionResources.ru.xlf b/src/Platform/Microsoft.Testing.Extensions.HangDump/Resources/xlf/ExtensionResources.ru.xlf index d0e463df9d..79810063a9 100644 --- a/src/Platform/Microsoft.Testing.Extensions.HangDump/Resources/xlf/ExtensionResources.ru.xlf +++ b/src/Platform/Microsoft.Testing.Extensions.HangDump/Resources/xlf/ExtensionResources.ru.xlf @@ -7,6 +7,31 @@ Создание файла дампа "{0}" + + Dumping process {0} - {1} + Dumping process {0} - {1} + 0 is pid, 1 is the name of the process + + + Dumping this process tree (from bottom): + Dumping this process tree (from bottom): + + + + Error getting parent of process {0} - {1}: {2}" + Error getting parent of process {0} - {1}: {2}" + 0 is pid, 1 is name, 2 is the exception + + + Error while killing process {0} - {1}: {2} + Error while killing process {0} - {1}: {2} + 0 is pid, 1 is name, 2 is the exception + + + Error while taking dump of process {0} - {1}: {2} + Error while taking dump of process {0} - {1}: {2} + 0 is pid, 1 is name, 2 is the exception from the system + The hang dump file Файл дампа зависания diff --git a/src/Platform/Microsoft.Testing.Extensions.HangDump/Resources/xlf/ExtensionResources.tr.xlf b/src/Platform/Microsoft.Testing.Extensions.HangDump/Resources/xlf/ExtensionResources.tr.xlf index 9dd85248e8..c0b9eaa844 100644 --- a/src/Platform/Microsoft.Testing.Extensions.HangDump/Resources/xlf/ExtensionResources.tr.xlf +++ b/src/Platform/Microsoft.Testing.Extensions.HangDump/Resources/xlf/ExtensionResources.tr.xlf @@ -7,6 +7,31 @@ Döküm dosyası '{0}' oluşturuluyor + + Dumping process {0} - {1} + Dumping process {0} - {1} + 0 is pid, 1 is the name of the process + + + Dumping this process tree (from bottom): + Dumping this process tree (from bottom): + + + + Error getting parent of process {0} - {1}: {2}" + Error getting parent of process {0} - {1}: {2}" + 0 is pid, 1 is name, 2 is the exception + + + Error while killing process {0} - {1}: {2} + Error while killing process {0} - {1}: {2} + 0 is pid, 1 is name, 2 is the exception + + + Error while taking dump of process {0} - {1}: {2} + Error while taking dump of process {0} - {1}: {2} + 0 is pid, 1 is name, 2 is the exception from the system + The hang dump file Askıda kalma dökümü dosyası diff --git a/src/Platform/Microsoft.Testing.Extensions.HangDump/Resources/xlf/ExtensionResources.zh-Hans.xlf b/src/Platform/Microsoft.Testing.Extensions.HangDump/Resources/xlf/ExtensionResources.zh-Hans.xlf index ef45b929ac..f1d1efbd76 100644 --- a/src/Platform/Microsoft.Testing.Extensions.HangDump/Resources/xlf/ExtensionResources.zh-Hans.xlf +++ b/src/Platform/Microsoft.Testing.Extensions.HangDump/Resources/xlf/ExtensionResources.zh-Hans.xlf @@ -7,6 +7,31 @@ 正在创建转储文件“{0}” + + Dumping process {0} - {1} + Dumping process {0} - {1} + 0 is pid, 1 is the name of the process + + + Dumping this process tree (from bottom): + Dumping this process tree (from bottom): + + + + Error getting parent of process {0} - {1}: {2}" + Error getting parent of process {0} - {1}: {2}" + 0 is pid, 1 is name, 2 is the exception + + + Error while killing process {0} - {1}: {2} + Error while killing process {0} - {1}: {2} + 0 is pid, 1 is name, 2 is the exception + + + Error while taking dump of process {0} - {1}: {2} + Error while taking dump of process {0} - {1}: {2} + 0 is pid, 1 is name, 2 is the exception from the system + The hang dump file 挂起转储文件 diff --git a/src/Platform/Microsoft.Testing.Extensions.HangDump/Resources/xlf/ExtensionResources.zh-Hant.xlf b/src/Platform/Microsoft.Testing.Extensions.HangDump/Resources/xlf/ExtensionResources.zh-Hant.xlf index 157985b3e7..811a36819b 100644 --- a/src/Platform/Microsoft.Testing.Extensions.HangDump/Resources/xlf/ExtensionResources.zh-Hant.xlf +++ b/src/Platform/Microsoft.Testing.Extensions.HangDump/Resources/xlf/ExtensionResources.zh-Hant.xlf @@ -7,6 +7,31 @@ 正在建立傾印檔案 '{0}' + + Dumping process {0} - {1} + Dumping process {0} - {1} + 0 is pid, 1 is the name of the process + + + Dumping this process tree (from bottom): + Dumping this process tree (from bottom): + + + + Error getting parent of process {0} - {1}: {2}" + Error getting parent of process {0} - {1}: {2}" + 0 is pid, 1 is name, 2 is the exception + + + Error while killing process {0} - {1}: {2} + Error while killing process {0} - {1}: {2} + 0 is pid, 1 is name, 2 is the exception + + + Error while taking dump of process {0} - {1}: {2} + Error while taking dump of process {0} - {1}: {2} + 0 is pid, 1 is name, 2 is the exception from the system + The hang dump file 擱置傾印檔案 diff --git a/src/Platform/Microsoft.Testing.Platform/Helpers/System/IProcess.cs b/src/Platform/Microsoft.Testing.Platform/Helpers/System/IProcess.cs index 49f677afd2..859514788d 100644 --- a/src/Platform/Microsoft.Testing.Platform/Helpers/System/IProcess.cs +++ b/src/Platform/Microsoft.Testing.Platform/Helpers/System/IProcess.cs @@ -22,6 +22,9 @@ internal interface IProcess : IDisposable /// IMainModule? MainModule { get; } + /// + DateTime StartTime { get; } + /// /// Instructs the Process component to wait for the associated process to exit, or for the cancellationToken to be canceled. /// @@ -30,6 +33,8 @@ internal interface IProcess : IDisposable /// void WaitForExit(); - /// + /// + /// Kills the process and try to kill all child processes. + /// void Kill(); } diff --git a/src/Platform/Microsoft.Testing.Platform/Helpers/System/SystemProcess.cs b/src/Platform/Microsoft.Testing.Platform/Helpers/System/SystemProcess.cs index 17f6caa6bc..1fb7c2d472 100644 --- a/src/Platform/Microsoft.Testing.Platform/Helpers/System/SystemProcess.cs +++ b/src/Platform/Microsoft.Testing.Platform/Helpers/System/SystemProcess.cs @@ -24,6 +24,8 @@ public SystemProcess(Process process) public int ExitCode => _process.ExitCode; + public DateTime StartTime => _process.StartTime; + public IMainModule? MainModule => _process.MainModule is null ? null @@ -39,7 +41,7 @@ public Task WaitForExitAsync() => _process.WaitForExitAsync(); public void Kill() - => _process.Kill(true); + => _process.Kill(entireProcessTree: true); public void Dispose() => _process.Dispose(); #pragma warning restore CA1416 diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/HangDumpProcessTreeTests.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/HangDumpProcessTreeTests.cs new file mode 100644 index 0000000000..83180701dd --- /dev/null +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/HangDumpProcessTreeTests.cs @@ -0,0 +1,172 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +namespace Microsoft.Testing.Platform.Acceptance.IntegrationTests; + +[TestClass] +public sealed class HangDumpProcessTreeTests : AcceptanceTestBase +{ + [DynamicData(nameof(TargetFrameworks.AllForDynamicData), typeof(TargetFrameworks))] + [TestMethod] + public async Task HangDump_DumpAllChildProcesses_CreateDump(string tfm) + { + string resultDirectory = Path.Combine(AssetFixture.TargetAssetPath, Guid.NewGuid().ToString("N"), tfm); + var testHost = TestInfrastructure.TestHost.LocateFrom(AssetFixture.TargetAssetPath, "HangDumpWithChild", tfm); + TestHostResult testHostResult = await testHost.ExecuteAsync( + $"--hangdump --hangdump-timeout 8s --hangdump-type mini --results-directory {resultDirectory}", + new Dictionary + { + { "SLEEPTIMEMS1", "4000" }, + { "SLEEPTIMEMS2", "600000" }, + }, + cancellationToken: TestContext.CancellationToken); + testHostResult.AssertExitCodeIs(ExitCodes.TestHostProcessExitedNonGracefully); + string[] dumpFiles = Directory.GetFiles(resultDirectory, "HangDump*.dmp", SearchOption.AllDirectories); + Assert.HasCount(4, dumpFiles, $"There should be 4 dumps, one for each process in the tree. {testHostResult}"); + } + + public sealed class TestAssetFixture() : TestAssetFixtureBase(AcceptanceFixture.NuGetGlobalPackagesFolder) + { + private const string AssetName = "AssetFixture"; + + public string TargetAssetPath => GetAssetPath(AssetName); + + public override IEnumerable<(string ID, string Name, string Code)> GetAssetsToGenerate() + { + yield return (AssetName, AssetName, + Sources + .PatchTargetFrameworks(TargetFrameworks.All) + .PatchCodeWithReplace("$MicrosoftTestingPlatformVersion$", MicrosoftTestingPlatformVersion)); + } + + private const string Sources = """ +#file HangDumpWithChild.csproj + + + + $TargetFrameworks$ + Exe + true + enable + preview + + + + + + + +#file Program.cs +using System; +using System.Linq; +using System.Diagnostics; +using System.Threading; +using System.Threading.Tasks; +using System.Globalization; +using Microsoft.Testing.Platform; +using Microsoft.Testing.Platform.Extensions.TestFramework; +using Microsoft.Testing.Platform.Builder; +using Microsoft.Testing.Platform.Capabilities.TestFramework; +using Microsoft.Testing.Extensions; +using Microsoft.Testing.Platform.Extensions.Messages; +using Microsoft.Testing.Platform.Requests; +using Microsoft.Testing.Platform.Services; + +public class Startup +{ + public static async Task Main(string[] args) + { + Process self = Process.GetCurrentProcess(); + string path = self.MainModule!.FileName!; + + if (args[0] == "--child") + { + int child = int.Parse(args[1], CultureInfo.InvariantCulture); + + if (child != 0) + { + var process = Process.Start(new ProcessStartInfo(path, $"--child {child - 1}") + { + UseShellExecute = false, + }); + + // Wait for the child to exit, to make sure we dumping the process in order that will + // end up with multiple dumps. Because typically the parent starts the child and waits for it. + process!.WaitForExit(); + return 0; + } + else + { + // Just sleep for a long time. + Thread.Sleep(3_600_000); + return 0; + } + } + + // We are running under testhost controller, don't start extra processes when we are the controller. + if (args.Any(a => a == "--internal-testhostcontroller-pid")) + { + + Process.Start(new ProcessStartInfo(path, $"--child 2") + { + UseShellExecute = false, + }); + } + + ITestApplicationBuilder builder = await TestApplication.CreateBuilderAsync(args); + builder.RegisterTestFramework(_ => new TestFrameworkCapabilities(), (_,__) => new DummyTestFramework()); + builder.AddHangDumpProvider(); + using ITestApplication app = await builder.BuildAsync(); + return await app.RunAsync(); + } +} + +public class DummyTestFramework : ITestFramework, IDataProducer +{ + public string Uid => nameof(DummyTestFramework); + + public string Version => "2.0.0"; + + public string DisplayName => nameof(DummyTestFramework); + + public string Description => nameof(DummyTestFramework); + + public Task IsEnabledAsync() => Task.FromResult(true); + + public Type[] DataTypesProduced => new[] { typeof(TestNodeUpdateMessage) }; + + public Task CreateTestSessionAsync(CreateTestSessionContext context) + => Task.FromResult(new CreateTestSessionResult() { IsSuccess = true }); + + public Task CloseTestSessionAsync(CloseTestSessionContext context) + => Task.FromResult(new CloseTestSessionResult() { IsSuccess = true }); + + public async Task ExecuteRequestAsync(ExecuteRequestContext context) + { + + Thread.Sleep(int.Parse(Environment.GetEnvironmentVariable("SLEEPTIMEMS1")!, CultureInfo.InvariantCulture)); + + await context.MessageBus.PublishAsync(this, new TestNodeUpdateMessage(context.Request.Session.SessionUid, new TestNode() + { + Uid = "Test1", + DisplayName = "Test1", + Properties = new PropertyBag(new PassedTestNodeStateProperty()), + })); + + Thread.Sleep(int.Parse(Environment.GetEnvironmentVariable("SLEEPTIMEMS2")!, CultureInfo.InvariantCulture)); + + await context.MessageBus.PublishAsync(this, new TestNodeUpdateMessage(context.Request.Session.SessionUid, new TestNode() + { + Uid = "Test2", + DisplayName = "Test2", + Properties = new PropertyBag(new PassedTestNodeStateProperty()), + })); + + context.Complete(); + } +} +"""; + } + + public TestContext TestContext { get; set; } +} From c2d973d9bee8971b403b4c86292ea2a948351579 Mon Sep 17 00:00:00 2001 From: Copilot <198982749+Copilot@users.noreply.github.com> Date: Mon, 29 Sep 2025 16:28:50 +0200 Subject: [PATCH 528/541] Add localized resource strings for TerminalTestReporter summary output (#6602) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: nohwnd <5735905+nohwnd@users.noreply.github.com> Co-authored-by: Jakub Jareš --- .../OutputDevice/Terminal/TerminalTestReporter.cs | 12 ++++++------ .../Resources/PlatformResources.resx | 9 +++++++++ .../Resources/xlf/PlatformResources.cs.xlf | 15 +++++++++++++++ .../Resources/xlf/PlatformResources.de.xlf | 15 +++++++++++++++ .../Resources/xlf/PlatformResources.es.xlf | 15 +++++++++++++++ .../Resources/xlf/PlatformResources.fr.xlf | 15 +++++++++++++++ .../Resources/xlf/PlatformResources.it.xlf | 15 +++++++++++++++ .../Resources/xlf/PlatformResources.ja.xlf | 15 +++++++++++++++ .../Resources/xlf/PlatformResources.ko.xlf | 15 +++++++++++++++ .../Resources/xlf/PlatformResources.pl.xlf | 15 +++++++++++++++ .../Resources/xlf/PlatformResources.pt-BR.xlf | 15 +++++++++++++++ .../Resources/xlf/PlatformResources.ru.xlf | 15 +++++++++++++++ .../Resources/xlf/PlatformResources.tr.xlf | 15 +++++++++++++++ .../Resources/xlf/PlatformResources.zh-Hans.xlf | 15 +++++++++++++++ .../Resources/xlf/PlatformResources.zh-Hant.xlf | 15 +++++++++++++++ 15 files changed, 210 insertions(+), 6 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporter.cs b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporter.cs index 9432a79e97..f128d74c42 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporter.cs +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporter.cs @@ -252,11 +252,11 @@ private void AppendTestRunSummary(ITerminal terminal) bool colorizePassed = passed > 0 && _buildErrorsCount == 0 && failed == 0; bool colorizeSkipped = skipped > 0 && skipped == total && _buildErrorsCount == 0 && failed == 0; - string totalText = $"{SingleIndentation}total: {total}"; - string failedText = $"{SingleIndentation}failed: {failed}"; - string passedText = $"{SingleIndentation}succeeded: {passed}"; - string skippedText = $"{SingleIndentation}skipped: {skipped}"; - string durationText = $"{SingleIndentation}duration: "; + string totalText = $"{SingleIndentation}{PlatformResources.TotalLowercase}: {total}"; + string failedText = $"{SingleIndentation}{PlatformResources.FailedLowercase}: {failed}"; + string passedText = $"{SingleIndentation}{PlatformResources.SucceededLowercase}: {passed}"; + string skippedText = $"{SingleIndentation}{PlatformResources.SkippedLowercase}: {skipped}"; + string durationText = $"{SingleIndentation}{PlatformResources.DurationLowercase}: "; terminal.ResetColor(); terminal.AppendLine(totalText); @@ -890,7 +890,7 @@ public void AppendTestDiscoverySummary(ITerminal terminal) terminal.AppendLine(); } - string durationText = $"{SingleIndentation}duration: "; + string durationText = $"{SingleIndentation}{PlatformResources.DurationLowercase}: "; TimeSpan runDuration = _testExecutionStartTime != null && _testExecutionEndTime != null ? (_testExecutionEndTime - _testExecutionStartTime).Value : TimeSpan.Zero; terminal.Append(durationText); AppendLongDuration(terminal, runDuration, wrapInParentheses: false, colorize: false); diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/PlatformResources.resx b/src/Platform/Microsoft.Testing.Platform/Resources/PlatformResources.resx index a3c8767c8f..5b7a17db4f 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/PlatformResources.resx +++ b/src/Platform/Microsoft.Testing.Platform/Resources/PlatformResources.resx @@ -550,6 +550,9 @@ Read more about Microsoft Testing Platform telemetry: https://aka.ms/testingplat Total + + total + Zero tests ran @@ -557,6 +560,9 @@ Read more about Microsoft Testing Platform telemetry: https://aka.ms/testingplat Console is already in batching mode. Exception that is thrown when console is already collecting input into a batch (into a string builder), and code asks to enable batching mode again. + + duration + failed with {0} error(s) @@ -716,4 +722,7 @@ Takes one argument as string in the format <value>[h|m|s] where 'value' is Allows to pause execution in order to attach to the process for debug purposes. + + succeeded + \ No newline at end of file diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.cs.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.cs.xlf index 774a24e2b1..2204ce6b52 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.cs.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.cs.xlf @@ -224,6 +224,11 @@ Zjišťování testů z + + duration + duration + + Provider '{0}' (UID: {1}) failed with error: {2} Zprostředkovatel {0} (UID: {1}) selhal s chybou: {2}. @@ -758,6 +763,11 @@ Může mít jenom jeden argument jako řetězec ve formátu <value>[h|m|s] Spouští se testovací relace. Cesta k souboru protokolu je '{0}'. + + succeeded + succeeded + + An 'ITestExecutionFilterFactory' factory is already set Objekt pro vytváření ITestExecutionFilterFactory je už nastavený. @@ -977,6 +987,11 @@ Platné hodnoty jsou Normal a Detailed. Výchozí hodnota je Normal. Spustila se nula testů + + total + total + + \ No newline at end of file diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.de.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.de.xlf index 97ae7e4f03..3678a00c80 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.de.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.de.xlf @@ -224,6 +224,11 @@ Tests ermitteln aus + + duration + duration + + Provider '{0}' (UID: {1}) failed with error: {2} Anbieter "{0}" (UID: {1}) ist mit folgendem Fehler fehlgeschlagen: {2} @@ -758,6 +763,11 @@ Nimmt ein Argument als Zeichenfolge im Format <value>[h|m|s], wobei "value Die Testsitzung wird gestartet. Der Protokolldateipfad ist '{0}'. + + succeeded + succeeded + + An 'ITestExecutionFilterFactory' factory is already set Eine "ITestExecutionFilterFactory"-Factory ist bereits festgelegt @@ -977,6 +987,11 @@ Gültige Werte sind „Normal“, „Detailed“. Der Standardwert ist „Normal Es wurden keine Tests ausgeführt. + + total + total + + \ No newline at end of file diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.es.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.es.xlf index d1a6c71998..8d3a675a7a 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.es.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.es.xlf @@ -224,6 +224,11 @@ Detección de pruebas de + + duration + duration + + Provider '{0}' (UID: {1}) failed with error: {2} Error del proveedor "{0}" (UID: {1}) con el error: {2} @@ -758,6 +763,11 @@ Toma un argumento como cadena con el formato <value>[h|m|s] donde 'value' Iniciando sesión de prueba. La ruta de acceso del archivo de registro es '{0}'. + + succeeded + succeeded + + An 'ITestExecutionFilterFactory' factory is already set Ya se ha establecido una fábrica "ITestExecutionFilterFactory" @@ -977,6 +987,11 @@ Los valores válidos son 'Normal', 'Detallado'. El valor predeterminado es 'Norm No se ejecutaron pruebas + + total + total + + \ No newline at end of file diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.fr.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.fr.xlf index 39b10aa4e2..2c6d00578a 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.fr.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.fr.xlf @@ -224,6 +224,11 @@ Découverte des tests à partir de + + duration + duration + + Provider '{0}' (UID: {1}) failed with error: {2} Désolé, échec de l’« {0} » du fournisseur (UID : {1}) avec l’erreur : {2} @@ -758,6 +763,11 @@ Prend un argument sous forme de chaîne au format <value>[h|m|s] où « v Démarrage de la session de test. Le chemin d’accès au fichier journal est '{0}'. + + succeeded + succeeded + + An 'ITestExecutionFilterFactory' factory is already set Désolé, une fabrique « ITestExecutionFilterFactory » est déjà définie @@ -977,6 +987,11 @@ Les valeurs valides sont « Normal » et « Détaillé ». La valeur par dé Zéro tests exécutés + + total + total + + \ No newline at end of file diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.it.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.it.xlf index fe36f4c234..0e04d645af 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.it.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.it.xlf @@ -224,6 +224,11 @@ Individuazione di test da + + duration + duration + + Provider '{0}' (UID: {1}) failed with error: {2} Provider '{0}' (UID: {1}) non riuscito con errore: {2} @@ -758,6 +763,11 @@ Acquisisce un argomento come stringa nel formato <value>[h|m|s] dove 'valu Avvio della sessione di test. Il percorso del file di log è '{0}'. + + succeeded + succeeded + + An 'ITestExecutionFilterFactory' factory is already set È già impostata una factory 'ITestExecutionFilterFactory' @@ -977,6 +987,11 @@ I valori validi sono 'Normal', 'Detailed'. L'impostazione predefinita è 'Normal Nessun test eseguito + + total + total + + \ No newline at end of file diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ja.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ja.xlf index 4a0d6dbfaa..2e95587b6a 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ja.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ja.xlf @@ -224,6 +224,11 @@ からテストを検出しています + + duration + duration + + Provider '{0}' (UID: {1}) failed with error: {2} プロバイダー '{0}' (UID: {1}) が次のエラーで失敗しました: {2} @@ -759,6 +764,11 @@ Takes one argument as string in the format <value>[h|m|s] where 'value' is テスト セッションを開始しています。ログ ファイルのパスが '{0}' です。 + + succeeded + succeeded + + An 'ITestExecutionFilterFactory' factory is already set 'ITestExecutionFilterFactory' ファクトリは既に設定されています @@ -978,6 +988,11 @@ Valid values are 'Normal', 'Detailed'. Default is 'Normal'. 0 件のテストが実行されました + + total + total + + \ No newline at end of file diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ko.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ko.xlf index dfce73d2e4..3a2b31822d 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ko.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ko.xlf @@ -224,6 +224,11 @@ 다음에서 테스트 검색하는 중 + + duration + duration + + Provider '{0}' (UID: {1}) failed with error: {2} 공급자 '{0}'(UID: {1})이 오류 {2}(으)로 실패했습니다. @@ -758,6 +763,11 @@ Takes one argument as string in the format <value>[h|m|s] where 'value' is 테스트 세션을 시작하는 중입니다. 로그 파일 경로가 '{0}'. + + succeeded + succeeded + + An 'ITestExecutionFilterFactory' factory is already set 'ITestExecutionFilterFactory' 팩터리가 이미 설정되어 있음 @@ -977,6 +987,11 @@ Valid values are 'Normal', 'Detailed'. Default is 'Normal'. 테스트가 0개 실행됨 + + total + total + + \ No newline at end of file diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pl.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pl.xlf index 36aa4297ba..7421f6eef8 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pl.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pl.xlf @@ -224,6 +224,11 @@ Odnajdywanie testów w + + duration + duration + + Provider '{0}' (UID: {1}) failed with error: {2} Dostawca „{0}” (UID:{1}) nie powiódł się z powodu błędu: {2} @@ -758,6 +763,11 @@ Pobiera jeden argument jako ciąg w formacie <value>[h|m|s], gdzie element Rozpoczynanie sesji testowej. Ścieżka pliku dziennika jest '{0}'. + + succeeded + succeeded + + An 'ITestExecutionFilterFactory' factory is already set Fabryka „ITestExecutionFilterFactory” jest już ustawiona @@ -977,6 +987,11 @@ Prawidłowe wartości to „Normalne”, „Szczegółowe”. Wartość domyśln Uruchomiono zero testów + + total + total + + \ No newline at end of file diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pt-BR.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pt-BR.xlf index 3927d947cf..0d484a22bf 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pt-BR.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pt-BR.xlf @@ -224,6 +224,11 @@ Descobrindo testes de + + duration + duration + + Provider '{0}' (UID: {1}) failed with error: {2} O provedor ''{0}'' (UID: {1}) falhou com o erro: {2} @@ -758,6 +763,11 @@ Recebe um argumento como cadeia de caracteres no formato <valor>[h|m|s] em Iniciando sessão de teste. O caminho do arquivo de log '{0}'. + + succeeded + succeeded + + An 'ITestExecutionFilterFactory' factory is already set Uma fábrica “ITestExecutionFilterFactory” já está definida @@ -977,6 +987,11 @@ Os valores válidos são “Normal”, “Detalhado”. O padrão é “Normal Zero testes executados + + total + total + + \ No newline at end of file diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ru.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ru.xlf index 29c8f07c1a..73a4cf88ab 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ru.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ru.xlf @@ -224,6 +224,11 @@ Обнаружение тестов из + + duration + duration + + Provider '{0}' (UID: {1}) failed with error: {2} Сбой поставщика "{0}" (ИД пользователя: {1}) с ошибкой: {2} @@ -758,6 +763,11 @@ Takes one argument as string in the format <value>[h|m|s] where 'value' is Запуск тестового сеанса. Путь к файлу журнала '{0}'. + + succeeded + succeeded + + An 'ITestExecutionFilterFactory' factory is already set Фабрика ITestExecutionFilterFactory уже настроена @@ -977,6 +987,11 @@ Valid values are 'Normal', 'Detailed'. Default is 'Normal'. Запущено ноль тестов + + total + total + + \ No newline at end of file diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.tr.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.tr.xlf index 618e7b4c8f..a0662f9594 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.tr.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.tr.xlf @@ -224,6 +224,11 @@ Testler şuradan bulunuyor: + + duration + duration + + Provider '{0}' (UID: {1}) failed with error: {2} '{0}' sağlayıcısı '' (UID: {1}) şu hatayla başarısız oldu: {2} @@ -758,6 +763,11 @@ Bir bağımsız değişkeni, 'value' değerinin kayan olduğu <value>[h|m| Test oturumu başlatılıyor. Günlük dosyası yolu '{0}'. + + succeeded + succeeded + + An 'ITestExecutionFilterFactory' factory is already set Bir 'ITestExecutionFilterFactory' fabrikası zaten ayarlanmış @@ -977,6 +987,11 @@ Geçerli değerler: ‘Normal’, ‘Ayrıntılı’. Varsayılan değer: ‘Nor Sıfır test çalıştırıldı + + total + total + + \ No newline at end of file diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hans.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hans.xlf index 17a1097a91..4303cd2fbd 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hans.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hans.xlf @@ -224,6 +224,11 @@ 正在发现以下位置中的测试 + + duration + duration + + Provider '{0}' (UID: {1}) failed with error: {2} 提供程序 '{0}' (UID: {1}) 失败,出现错误: {2} @@ -758,6 +763,11 @@ Takes one argument as string in the format <value>[h|m|s] where 'value' is 正在启动测试会话。日志文件路径 '{0}'。 + + succeeded + succeeded + + An 'ITestExecutionFilterFactory' factory is already set 已设置“ITestExecutionFilterFactory”工厂 @@ -977,6 +987,11 @@ Valid values are 'Normal', 'Detailed'. Default is 'Normal'. 运行了零个测试 + + total + total + + \ No newline at end of file diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hant.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hant.xlf index 7a913b5b2c..8998bd0ac4 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hant.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hant.xlf @@ -224,6 +224,11 @@ 正在以下位置找測試 + + duration + duration + + Provider '{0}' (UID: {1}) failed with error: {2} 提供者 '{0}' (UID: {1}) 失敗,發生錯誤: {2} @@ -758,6 +763,11 @@ Takes one argument as string in the format <value>[h|m|s] where 'value' is 正在啟動測試會話。記錄檔路徑 '{0}'。 + + succeeded + succeeded + + An 'ITestExecutionFilterFactory' factory is already set 已設定 'ITestExecutionFilterFactory' 中心 @@ -977,6 +987,11 @@ Valid values are 'Normal', 'Detailed'. Default is 'Normal'. 已執行零項測試 + + total + total + + \ No newline at end of file From 7e2fefdb736390eb5e2a5f00465ae4484258b596 Mon Sep 17 00:00:00 2001 From: Muiz Atolagbe <46275427+AtolagbeMuiz@users.noreply.github.com> Date: Mon, 29 Sep 2025 15:58:33 +0100 Subject: [PATCH 529/541] Implement assert contains overload to accept non-generic collection (#6417) Co-authored-by: Youssef Victor --- .../UseProperAssertMethodsAnalyzer.cs | 5 +- .../Assertions/Assert.Contains.cs | 167 +++++++++++++ .../TestFramework/Assertions/Assert.Count.cs | 72 ++++++ .../PublicAPI/PublicAPI.Unshipped.txt | 18 ++ .../UseProperAssertMethodsAnalyzerTests.cs | 155 +++++++++++- .../Assertions/AssertTests.Contains.cs | 221 ++++++++++++++++++ 6 files changed, 627 insertions(+), 11 deletions(-) diff --git a/src/Analyzers/MSTest.Analyzers/UseProperAssertMethodsAnalyzer.cs b/src/Analyzers/MSTest.Analyzers/UseProperAssertMethodsAnalyzer.cs index 5093aa9a9f..47141d2c2e 100644 --- a/src/Analyzers/MSTest.Analyzers/UseProperAssertMethodsAnalyzer.cs +++ b/src/Analyzers/MSTest.Analyzers/UseProperAssertMethodsAnalyzer.cs @@ -484,10 +484,9 @@ private static CollectionCheckStatus RecognizeCollectionMethodCheck( } private static bool IsBCLCollectionType(ITypeSymbol type, INamedTypeSymbol objectTypeSymbol) - // Check if the type implements IEnumerable (but is not string) - // Note: Assert.Contains/IsEmpty/HasCount for collections accept IEnumerable, but not IEnumerable. + // Check if the type implements IEnumerable (but is not string) => type.SpecialType != SpecialType.System_String && type.AllInterfaces.Any(i => - i.OriginalDefinition.SpecialType == SpecialType.System_Collections_Generic_IEnumerable_T) && + i.OriginalDefinition.SpecialType == SpecialType.System_Collections_IEnumerable) && // object is coming from BCL and it's expected to always have a public key. type.ContainingAssembly.Identity.HasPublicKey == objectTypeSymbol.ContainingAssembly.Identity.HasPublicKey && type.ContainingAssembly.Identity.PublicKey.SequenceEqual(objectTypeSymbol.ContainingAssembly.Identity.PublicKey); diff --git a/src/TestFramework/TestFramework/Assertions/Assert.Contains.cs b/src/TestFramework/TestFramework/Assertions/Assert.Contains.cs index 849d9a4bac..80eb6ffcf3 100644 --- a/src/TestFramework/TestFramework/Assertions/Assert.Contains.cs +++ b/src/TestFramework/TestFramework/Assertions/Assert.Contains.cs @@ -178,6 +178,14 @@ public static T ContainsSingle(Func predicate, IEnumerable collec public static void Contains(T expected, IEnumerable collection) => Contains(expected, collection, string.Empty, null); + /// + /// Tests whether the specified non-generic collection contains the given element. + /// + /// The expected item. + /// The non-generic collection (like ArrayList). + public static void Contains(object? expected, IEnumerable collection) + => Contains(expected, collection, string.Empty); + /// /// Tests whether the specified collection contains the given element. /// @@ -205,6 +213,26 @@ public static void Contains(T expected, IEnumerable collection, string? me } } + /// + /// Tests whether the specified collection contains the given element. + /// + /// The expected item. + /// The collection. + /// The message format to display when the assertion fails. + public static void Contains(object? expected, IEnumerable collection, string? message) + { + foreach (object? item in collection) + { + if (object.Equals(item, expected)) + { + return; + } + } + + string userMessage = BuildUserMessage(message); + ThrowAssertContainsItemFailed(userMessage); + } + /// /// Tests whether the specified collection contains the given element. /// @@ -215,6 +243,15 @@ public static void Contains(T expected, IEnumerable collection, string? me public static void Contains(T expected, IEnumerable collection, IEqualityComparer comparer) => Contains(expected, collection, comparer, string.Empty, null); + /// + /// Tests whether the specified collection contains the given element. + /// + /// The expected item. + /// The collection. + /// An equality comparer to compare values. + public static void Contains(object expected, IEnumerable collection, IEqualityComparer comparer) + => Contains(expected, collection, comparer, string.Empty); + /// /// Tests whether the specified collection contains the given element. /// @@ -244,6 +281,27 @@ public static void Contains(T expected, IEnumerable collection, IEqualityC } } + /// + /// Tests whether the specified collection contains the given element. + /// + /// The expected item. + /// The collection. + /// An equality comparer to compare values. + /// The message to display when the assertion fails. + public static void Contains(object expected, IEnumerable collection, IEqualityComparer comparer, string? message) + { + foreach (object? item in collection) + { + if (comparer.Equals(item, expected)) + { + return; + } + } + + string userMessage = BuildUserMessage(message); + ThrowAssertContainsItemFailed(userMessage); + } + /// /// Tests whether the specified collection contains the given element. /// @@ -253,6 +311,14 @@ public static void Contains(T expected, IEnumerable collection, IEqualityC public static void Contains(Func predicate, IEnumerable collection) => Contains(predicate, collection, string.Empty, null); + /// + /// Tests whether the specified collection contains the given element. + /// + /// A function to test each element for a condition. + /// The collection. + public static void Contains(Func predicate, IEnumerable collection) + => Contains(predicate, collection, string.Empty); + /// /// Tests whether the specified collection contains the given element. /// @@ -280,6 +346,26 @@ public static void Contains(Func predicate, IEnumerable collectio } } + /// + /// Tests whether the specified collection contains the given element. + /// + /// A function to test each element for a condition. + /// The collection. + /// The message format to display when the assertion fails. + public static void Contains(Func predicate, IEnumerable collection, string? message) + { + foreach (object? item in collection) + { + if (predicate(item)) + { + return; + } + } + + string userMessage = BuildUserMessage(message); + ThrowAssertContainsPredicateFailed(userMessage); + } + /// /// Tests whether the specified string contains the specified substring /// and throws an exception if the substring does not occur within the @@ -449,6 +535,14 @@ public static void Contains(string substring, string value, StringComparison com public static void DoesNotContain(T expected, IEnumerable collection) => DoesNotContain(expected, collection, string.Empty, null); + /// + /// Tests whether the specified non-generic collection does not contain the specified item. + /// + /// The expected item. + /// The non-generic collection. + public static void DoesNotContain(object? expected, IEnumerable collection) + => DoesNotContain(expected, collection, string.Empty); + /// /// Tests whether the specified collection does not contain the specified item. /// @@ -476,6 +570,24 @@ public static void DoesNotContain(T expected, IEnumerable collection, stri } } + /// + /// Tests whether the specified non-generic collection does not contain the specified item. + /// + /// The expected item. + /// The non-generic collection. + /// The message to display when the assertion fails. + public static void DoesNotContain(object? expected, IEnumerable collection, string? message) + { + foreach (object? item in collection) + { + if (object.Equals(expected, item)) + { + string userMessage = BuildUserMessage(message); + ThrowAssertDoesNotContainItemFailed(userMessage); + } + } + } + /// /// Tests whether the specified collection does not contain the specified item. /// @@ -486,6 +598,15 @@ public static void DoesNotContain(T expected, IEnumerable collection, stri public static void DoesNotContain(T expected, IEnumerable collection, IEqualityComparer comparer) => DoesNotContain(expected, collection, comparer, string.Empty, null); + /// + /// Tests whether the specified collection does not contain the specified item. + /// + /// The expected item. + /// The collection. + /// An equality comparer to compare values. + public static void DoesNotContain(object? expected, IEnumerable collection, IEqualityComparer comparer) + => DoesNotContain(expected, collection, comparer, string.Empty); + /// /// Tests whether the specified collection does not contain the specified item. /// @@ -515,6 +636,26 @@ public static void DoesNotContain(T expected, IEnumerable collection, IEqu } } + /// + /// Tests whether the specified non-generic collection does not contain the specified item, + /// using a custom equality comparer. + /// + /// The expected item. + /// The non-generic collection. + /// An equality comparer to compare values. + /// The message to display when the assertion fails. + public static void DoesNotContain(object? expected, IEnumerable collection, IEqualityComparer comparer, string? message) + { + foreach (object? item in collection) + { + if (comparer.Equals(item, expected)) + { + string userMessage = BuildUserMessage(message); + ThrowAssertDoesNotContainItemFailed(userMessage); + } + } + } + /// /// Tests whether the specified collection does not contain the specified item. /// @@ -524,6 +665,14 @@ public static void DoesNotContain(T expected, IEnumerable collection, IEqu public static void DoesNotContain(Func predicate, IEnumerable collection) => DoesNotContain(predicate, collection, string.Empty, null); + /// + /// Tests whether the specified collection does not contain the specified item. + /// + /// A function to test each element for a condition. + /// The collection. + public static void DoesNotContain(Func predicate, IEnumerable collection) + => DoesNotContain(predicate, collection, string.Empty); + /// /// Tests whether the specified collection does not contain the specified item. /// @@ -551,6 +700,24 @@ public static void DoesNotContain(Func predicate, IEnumerable col } } + /// + /// Tests whether the specified collection does not contain the specified item. + /// + /// A function to test each element for a condition. + /// The collection. + /// The message to display when the assertion fails. + public static void DoesNotContain(Func predicate, IEnumerable collection, string? message) + { + foreach (object? item in collection) + { + if (predicate(item)) + { + string userMessage = BuildUserMessage(message); + ThrowAssertDoesNotContainPredicateFailed(userMessage); + } + } + } + /// /// Tests whether the specified string does not contain the specified substring /// and throws an exception if the substring occurs within the diff --git a/src/TestFramework/TestFramework/Assertions/Assert.Count.cs b/src/TestFramework/TestFramework/Assertions/Assert.Count.cs index d86e37f5a3..0a9dba0f79 100644 --- a/src/TestFramework/TestFramework/Assertions/Assert.Count.cs +++ b/src/TestFramework/TestFramework/Assertions/Assert.Count.cs @@ -171,6 +171,13 @@ public void AppendFormatted(object? value, int alignment = 0, string? format = n public static void IsNotEmpty(IEnumerable collection) => IsNotEmpty(collection, string.Empty, null); + /// + /// Tests that the collection is not empty. + /// + /// The collection. + public static void IsNotEmpty(IEnumerable collection) + => IsNotEmpty(collection, string.Empty); + /// /// Tests whether the collection is not empty. /// @@ -209,6 +216,22 @@ public static void IsNotEmpty(IEnumerable collection, [StringSyntax(String ThrowAssertIsNotEmptyFailed(userMessage); } + /// + /// Tests that the collection is not empty. + /// + /// The collection. + /// The message format to display when the assertion fails. + public static void IsNotEmpty(IEnumerable collection, string? message) + { + if (collection.Cast().Any()) + { + return; + } + + string userMessage = BuildUserMessage(message); + ThrowAssertIsNotEmptyFailed(userMessage); + } + /// /// Tests whether the collection has the expected count/length. /// @@ -218,6 +241,14 @@ public static void IsNotEmpty(IEnumerable collection, [StringSyntax(String public static void HasCount(int expected, IEnumerable collection) => HasCount(expected, collection, string.Empty, null); + /// + /// Tests whether the collection has the expected count/length. + /// + /// The expected count. + /// The collection. + public static void HasCount(int expected, IEnumerable collection) + => HasCount(expected, collection, string.Empty); + /// /// Tests whether the collection has the expected count/length. /// @@ -251,6 +282,15 @@ public static void HasCount(int expected, IEnumerable collection, [Interpo public static void HasCount(int expected, IEnumerable collection, [StringSyntax(StringSyntaxAttribute.CompositeFormat)] string? message, params object?[]? parameters) => HasCount("HasCount", expected, collection, message, parameters); + /// + /// Tests whether the collection has the expected count/length. + /// + /// The expected count. + /// The collection. + /// The message format to display when the assertion fails. + public static void HasCount(int expected, IEnumerable collection, string? message) + => HasCount("HasCount", expected, collection, message); + /// /// Tests that the collection is empty. /// @@ -259,6 +299,13 @@ public static void HasCount(int expected, IEnumerable collection, [StringS public static void IsEmpty(IEnumerable collection) => IsEmpty(collection, string.Empty, null); + /// + /// Tests that the collection is empty. + /// + /// The collection. + public static void IsEmpty(IEnumerable collection) + => IsEmpty(collection, string.Empty); + /// /// Tests that the collection is empty. /// @@ -289,6 +336,14 @@ public static void IsEmpty(IEnumerable collection, [InterpolatedStringHand public static void IsEmpty(IEnumerable collection, [StringSyntax(StringSyntaxAttribute.CompositeFormat)] string? message, params object?[]? parameters) => HasCount("IsEmpty", 0, collection, message, parameters); + /// + /// Tests that the collection is empty. + /// + /// The collection. + /// The message format to display when the assertion fails. + public static void IsEmpty(IEnumerable collection, string? message) + => HasCount("IsEmpty", 0, collection, message); + private static void HasCount(string assertionName, int expected, IEnumerable collection, [StringSyntax(StringSyntaxAttribute.CompositeFormat)] string? message, params object?[]? parameters) { int actualCount = collection.Count(); @@ -301,6 +356,23 @@ private static void HasCount(string assertionName, int expected, IEnumerable< ThrowAssertCountFailed(assertionName, expected, actualCount, userMessage); } + private static void HasCount(string assertionName, int expected, IEnumerable collection, string? message) + { + int actualCount = 0; + foreach (object? item in collection) + { + actualCount++; + } + + if (actualCount == expected) + { + return; + } + + string userMessage = BuildUserMessage(message); + ThrowAssertCountFailed(assertionName, expected, actualCount, userMessage); + } + [DoesNotReturn] private static void ThrowAssertCountFailed(string assertionName, int expectedCount, int actualCount, string userMessage) { diff --git a/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Unshipped.txt b/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Unshipped.txt index 7d27ebf1af..cf84db7811 100644 --- a/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Unshipped.txt +++ b/src/TestFramework/TestFramework/PublicAPI/PublicAPI.Unshipped.txt @@ -1,5 +1,23 @@ #nullable enable Microsoft.VisualStudio.TestTools.UnitTesting.DynamicDataSourceType.Field = 3 -> Microsoft.VisualStudio.TestTools.UnitTesting.DynamicDataSourceType +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.Contains(object! expected, System.Collections.IEnumerable! collection, System.Collections.IEqualityComparer! comparer) -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.Contains(object! expected, System.Collections.IEnumerable! collection, System.Collections.IEqualityComparer! comparer, string? message) -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.Contains(object? expected, System.Collections.IEnumerable! collection) -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.Contains(object? expected, System.Collections.IEnumerable! collection, string? message) -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.HasCount(int expected, System.Collections.IEnumerable! collection) -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.HasCount(int expected, System.Collections.IEnumerable! collection, string? message) -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsEmpty(System.Collections.IEnumerable! collection) -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsEmpty(System.Collections.IEnumerable! collection, string? message) -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsNotEmpty(System.Collections.IEnumerable! collection) -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsNotEmpty(System.Collections.IEnumerable! collection, string? message) -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.DoesNotContain(object? expected, System.Collections.IEnumerable! collection) -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.DoesNotContain(object? expected, System.Collections.IEnumerable! collection, string? message) -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.DoesNotContain(object? expected, System.Collections.IEnumerable! collection, System.Collections.IEqualityComparer! comparer) -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.DoesNotContain(object? expected, System.Collections.IEnumerable! collection, System.Collections.IEqualityComparer! comparer, string? message) -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.DoesNotContain(System.Func! predicate, System.Collections.IEnumerable! collection) -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.DoesNotContain(System.Func! predicate, System.Collections.IEnumerable! collection, string? message) -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.Contains(System.Func! predicate, System.Collections.IEnumerable! collection) -> void +static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.Contains(System.Func! predicate, System.Collections.IEnumerable! collection, string? message) -> void *REMOVED*static Microsoft.VisualStudio.TestTools.UnitTesting.Assert.Instance.get -> Microsoft.VisualStudio.TestTools.UnitTesting.Assert! *REMOVED*static Microsoft.VisualStudio.TestTools.UnitTesting.CollectionAssert.Instance.get -> Microsoft.VisualStudio.TestTools.UnitTesting.CollectionAssert! *REMOVED*static Microsoft.VisualStudio.TestTools.UnitTesting.StringAssert.Instance.get -> Microsoft.VisualStudio.TestTools.UnitTesting.StringAssert! diff --git a/test/UnitTests/MSTest.Analyzers.UnitTests/UseProperAssertMethodsAnalyzerTests.cs b/test/UnitTests/MSTest.Analyzers.UnitTests/UseProperAssertMethodsAnalyzerTests.cs index 6be0ddc467..843ef58b12 100644 --- a/test/UnitTests/MSTest.Analyzers.UnitTests/UseProperAssertMethodsAnalyzerTests.cs +++ b/test/UnitTests/MSTest.Analyzers.UnitTests/UseProperAssertMethodsAnalyzerTests.cs @@ -2197,18 +2197,157 @@ public class MyTestClass public void MyTestMethod() { var x = new Hashtable(); - Assert.AreEqual(4, x.Count); - // error CS0411: The type arguments for method 'Assert.HasCount(int, IEnumerable)' cannot be inferred from the usage. Try specifying the type arguments explicitly. - // When we add a non-generic IEnumerable overload, this test will fail because CS0411 is no longer reported. - // In that case, the analyzer should start reporting a diagnostic for the AreEqual call above. - // The codefix should suggest to switch to HasCount. - // Tracking issue https://github.com/microsoft/testfx/issues/6184. - Assert.{|CS0411:HasCount|}(4, x); + {|#0:Assert.AreEqual(4, x.Count)|}; } } """; - await VerifyCS.VerifyCodeFixAsync(code, code); + string fixedCode = """ + using System; + using System.Collections; + using System.Collections.Generic; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + var x = new Hashtable(); + Assert.HasCount(4, x); + } + } + """; + + await VerifyCS.VerifyCodeFixAsync( + code, + // /0/Test0.cs(13,9): info MSTEST0037: Use 'Assert.HasCount' instead of 'Assert.AreEqual' + VerifyCS.DiagnosticIgnoringAdditionalLocations().WithLocation(0).WithArguments("HasCount", "AreEqual"), + fixedCode); + } + + [TestMethod] + public async Task WhenAssertAreEqualWithNonGenericCollectionCountZero() + { + string code = """ + using System.Collections; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + var hashtable = new Hashtable(); + {|#0:Assert.AreEqual(0, hashtable.Count)|}; + } + } + """; + + string fixedCode = """ + using System.Collections; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + var hashtable = new Hashtable(); + Assert.IsEmpty(hashtable); + } + } + """; + + await VerifyCS.VerifyCodeFixAsync( + code, + VerifyCS.DiagnosticIgnoringAdditionalLocations().WithLocation(0).WithArguments("IsEmpty", "AreEqual"), + fixedCode); + } + + [TestMethod] + public async Task WhenAssertIsTrueWithNonGenericCollectionCountEqualZero() + { + string code = """ + using System.Collections; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + var hashtable = new Hashtable(); + {|#0:Assert.IsTrue(hashtable.Count == 0)|}; + } + } + """; + + string fixedCode = """ + using System.Collections; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + var hashtable = new Hashtable(); + Assert.IsEmpty(hashtable); + } + } + """; + + await VerifyCS.VerifyCodeFixAsync( + code, + VerifyCS.DiagnosticIgnoringAdditionalLocations().WithLocation(0).WithArguments("IsEmpty", "IsTrue"), + fixedCode); + } + + [TestMethod] + public async Task WhenAssertIsTrueWithNonGenericCollectionCountGreaterThanZero() + { + string code = """ + using System.Collections; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + var hashtable = new Hashtable { { "key", "value" } }; + {|#0:Assert.IsTrue(hashtable.Count > 0)|}; + } + } + """; + + string fixedCode = """ + using System.Collections; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void MyTestMethod() + { + var hashtable = new Hashtable { { "key", "value" } }; + Assert.IsNotEmpty(hashtable); + } + } + """; + + await VerifyCS.VerifyCodeFixAsync( + code, + VerifyCS.DiagnosticIgnoringAdditionalLocations().WithLocation(0).WithArguments("IsNotEmpty", "IsTrue"), + fixedCode); } #endregion diff --git a/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.Contains.cs b/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.Contains.cs index b751807d44..ffb1ce1b24 100644 --- a/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.Contains.cs +++ b/test/UnitTests/TestFramework.UnitTests/Assertions/AssertTests.Contains.cs @@ -362,6 +362,84 @@ public void Contains_ValueExpected_ItemDoesNotExist_ThrowsException() action.Should().Throw().WithMessage("*20*"); } + /// + /// Tests the Contains method (value overload) when the expected item is present. + /// + public void Contains_InNonGenericCollection_ValueExpected_ItemDoesNotExist_ThrowsException() + { + // Arrange + var collection = new ArrayList { 5, 10, "a" }; + object expected = 20; + + // Act + Action action = () => Assert.Contains(expected, collection, $"Item {expected} not found"); + + // Assert + action.Should().Throw().WithMessage($"*Item {expected} not found*"); + } + + /// + /// Tests the Contains method (value overload) when the expected item is present. + /// + public void Contains_InNonGenericCollection_ValueExpected_ItemExists_DoesNotThrow() + { + // Arrange + var collection = new ArrayList { 5, 10, "a" }; + + // Act + Action action = () => Assert.Contains("a", collection, "No failure expected"); + + // Assert + action.Should().NotThrow(); + } + + /// + /// Tests the Contains method (value overload) when the expected item is present. + /// + public void Contains_InNonGenericCollection_ValueExpected_ItemExists_DoesNotThrowException() + { + // Arrange + var collection = new ArrayList { 5, 10, "a" }; + + // Act + Action action = () => Assert.Contains(5, collection); + + // Assert + action.Should().NotThrow(); + } + + /// + /// Tests the Contains method (value overload) when the expected item is not present. + /// + public void Contains_InNonGenericCollection_NullableValueExpected_ItemDoesNotExist_ThrowsException() + { + // Arrange + var collection = new ArrayList { 5, 10, "a" }; + object? expected = null; + + // Act + Action action = () => Assert.Contains(expected, collection, $"Item {expected} not found"); + + // Assert + action.Should().Throw().WithMessage($"*Item {expected} not found*"); + } + + /// + /// Tests the Contains method (value overload) when the expected item is present. + /// + public void Contains_InNonGenericCollection_NullableValueExpected_ItemExists_DoesNotThrow() + { + // Arrange + var collection = new ArrayList { null, 10, "a" }; + object? expected = null; + + // Act + Action action = () => Assert.Contains(expected, collection, "No failure expected"); + + // Assert + action.Should().NotThrow(); + } + /// /// Tests the Contains method with a comparer when the expected item is present. /// @@ -410,6 +488,21 @@ public void Contains_Predicate_ItemMatches_DoesNotThrow() action.Should().NotThrow(); } + /// + /// Tests the Contains method that accepts a predicate when an element satisfies the condition. + /// + public void Contains_InNonGenericCollection_Predicate_ItemMatches_DoesNotThrow() + { + // Arrange + var collection = new ArrayList { 2, 4, 6, "a" }; + + // Act + Action action = () => Assert.Contains(IsEven, collection, "Even number exists"); + + // Assert + action.Should().NotThrow(); + } + /// /// Tests the Contains method that accepts a predicate when no element satisfies the condition. /// Expects an exception. @@ -426,6 +519,22 @@ public void Contains_Predicate_NoItemMatches_ThrowsException() action.Should().Throw().WithMessage("*even*"); } + /// + /// Tests the Contains method that accepts a predicate when no element satisfies the condition. + /// Expects an exception. + /// + public void Contains_InNonGenericCollection_Predicate_NoItemMatches_ThrowsException() + { + // Arrange + var collection = new ArrayList { 1, 3, 5, "a" }; + + // Act + Action action = () => Assert.Contains(IsEven, collection, "No even number found"); + + // Assert + action.Should().Throw().WithMessage("*even*"); + } + /// /// Tests the string Contains overload when the substring is contained in the value. /// @@ -494,6 +603,37 @@ public void DoesNotContain_ValueExpected_ItemPresent_ThrowsException() action.Should().Throw().WithMessage("*10*"); } + /// + /// Tests the DoesNotContain method (value overload) when the expected item is not present. + /// + public void DoesNotContain_InNonGenericCollection_ValueExpected_ItemNotPresent_DoesNotThrow() + { + // Arrange + var collection = new ArrayList { 5, 10, 15 }; + + // Act + Action action = () => Assert.DoesNotContain(20, collection, "No failure expected"); + + // Assert + action.Should().NotThrow(); + } + + /// + /// Tests the DoesNotContain method (value overload) when the expected item is present. + /// Expects an exception. + /// + public void DoesNotContain_InNonGenericCollection_ValueExpected_ItemPresent_ThrowsException() + { + // Arrange + var collection = new ArrayList { 5, 10, 15, "a" }; + + // Act + Action action = () => Assert.DoesNotContain(10, collection, "Assert.DoesNotContain failed. Expected collection to not contain the specified item. Item {0} should not be found"); + + // Assert + action.Should().Throw().WithMessage("*Assert.DoesNotContain failed. Expected collection to not contain the specified item. Item {0} should not be found*"); + } + /// /// Tests the DoesNotContain method with a comparer when the item is not present. /// @@ -510,6 +650,22 @@ public void DoesNotContain_WithComparer_ItemNotPresent_DoesNotThrow() action.Should().NotThrow(); } + /// + /// Tests the DoesNotContain method with a comparer when the item is not present. + /// + public void DoesNotContain_InNonGenericCollection_WithComparer_ItemNotPresent_DoesNotThrow() + { + // Arrange + var collection = new ArrayList { "apple", "banana", 1 }; + IEqualityComparer comparer = StringComparer.OrdinalIgnoreCase; + + // Act + Action action = () => Assert.DoesNotContain("cherry", collection, comparer, "No cherry found"); + + // Assert + action.Should().NotThrow(); + } + /// /// Tests the DoesNotContain method with a comparer when the item is present. /// Expects an exception. @@ -527,6 +683,23 @@ public void DoesNotContain_WithComparer_ItemPresent_ThrowsException() action.Should().Throw().WithMessage("*APPLE*"); } + /// + /// Tests the DoesNotContain method with a comparer when the item is present. + /// Expects an exception. + /// + public void DoesNotContain_InNonGenericCollection_WithComparer_ItemPresent_ThrowsException() + { + // Arrange + var collection = new ArrayList { "apple", "banana", 1 }; + IEqualityComparer comparer = StringComparer.OrdinalIgnoreCase; + + // Act + Action action = () => Assert.DoesNotContain("APPLE", collection, comparer, "APPLE"); + + // Assert + action.Should().Throw().WithMessage("*APPLE*"); + } + /// /// Tests the DoesNotContain method that accepts a predicate when no element satisfies the predicate. /// @@ -542,6 +715,21 @@ public void DoesNotContain_Predicate_NoItemMatches_DoesNotThrow() action.Should().NotThrow(); } + /// + /// Tests the DoesNotContain method that accepts a predicate when no element satisfies the predicate. + /// + public void DoesNotContain_InNonGenericCollection_Predicate_NoItemMatches_DoesNotThrow() + { + // Arrange + var collection = new ArrayList { 1, 3, 5, "a" }; + + // Act + Action action = () => Assert.DoesNotContain(IsEven, collection, "All items are odd"); + + // Assert + action.Should().NotThrow(); + } + /// /// Tests the DoesNotContain method that accepts a predicate when at least one element satisfies the predicate. /// Expects an exception. @@ -558,6 +746,22 @@ public void DoesNotContain_Predicate_AtLeastOneItemMatches_ThrowsException() action.Should().Throw().WithMessage("*even*"); } + /// + /// Tests the DoesNotContain method that accepts a predicate when at least one element satisfies the predicate. + /// Expects an exception. + /// + public void DoesNotContain_InNonGenericCollection_Predicate_AtLeastOneItemMatches_ThrowsException() + { + // Arrange + var collection = new ArrayList { 2, 3, 5, "a" }; + + // Act + Action action = () => Assert.DoesNotContain(IsEven, collection, "An even number exists"); + + // Assert + action.Should().Throw().WithMessage("*even*"); + } + /// /// Tests the string DoesNotContain overload when the substring is not contained in the value. /// @@ -729,6 +933,8 @@ public void DoesNotContain_StringWithMessageOnly_SubstringPresent_ThrowsExceptio private static bool IsEven(int x) => x % 2 == 0; + private static bool IsEven(object? x) => x is int i && i % 2 == 0; + #endregion #region ContainsSingle with Predicate Tests @@ -882,6 +1088,21 @@ public void Contains_ItemNotFound_ShowsSpecificErrorMessage() action.Should().Throw().WithMessage("*Expected collection to contain the specified item*"); } + /// + /// Tests that Contains (item) failure shows specific error message. + /// + public void Contains_InNonGenericCollection_ItemNotFound_ShowsSpecificErrorMessage() + { + // Arrange + var collection = new ArrayList { 1, 2, 3 }; + + // Act + Action action = () => Assert.Contains(5, collection); + + // Assert + action.Should().Throw().WithMessage("*Expected collection to contain the specified item*"); + } + /// /// Tests that Contains (predicate) failure shows specific error message. /// From a1cf1fceaa2281f2e283c5f9c89b25f11f9b418f Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Mon, 29 Sep 2025 17:07:20 +0200 Subject: [PATCH 530/541] Fix flow cancellation token codefix to use named arg when necessary (#6617) --- .../FlowTestContextCancellationTokenFixer.cs | 19 +++++--- ...lowTestContextCancellationTokenAnalyzer.cs | 48 ++++++++++++++----- ...stContextCancellationTokenAnalyzerTests.cs | 48 +++++++++++++++++++ 3 files changed, 95 insertions(+), 20 deletions(-) diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/FlowTestContextCancellationTokenFixer.cs b/src/Analyzers/MSTest.Analyzers.CodeFixes/FlowTestContextCancellationTokenFixer.cs index 87f67ebc1b..9a8716502c 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/FlowTestContextCancellationTokenFixer.cs +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/FlowTestContextCancellationTokenFixer.cs @@ -51,6 +51,7 @@ public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) } diagnostic.Properties.TryGetValue(FlowTestContextCancellationTokenAnalyzer.TestContextMemberNamePropertyKey, out string? testContextMemberName); + diagnostic.Properties.TryGetValue(FlowTestContextCancellationTokenAnalyzer.CancellationTokenParameterNamePropertyKey, out string? cancellationTokenParameterName); diagnostic.Properties.TryGetValue(nameof(FlowTestContextCancellationTokenAnalyzer.TestContextState), out string? testContextState); // Register a code action that will invoke the fix @@ -60,7 +61,7 @@ public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) createChangedDocument: async c => { DocumentEditor editor = await DocumentEditor.CreateAsync(context.Document, context.CancellationToken).ConfigureAwait(false); - return ApplyFix(editor, invocationExpression, testContextMemberName, testContextState, adjustedSymbols: null, c); + return ApplyFix(editor, invocationExpression, testContextMemberName, testContextState, cancellationTokenParameterName, adjustedSymbols: null, c); }, equivalenceKey: nameof(FlowTestContextCancellationTokenFixer)), diagnostic); @@ -71,13 +72,14 @@ internal static Document ApplyFix( InvocationExpressionSyntax invocationExpression, string? testContextMemberName, string? testContextState, + string? cancellationTokenParameterName, HashSet? adjustedSymbols, CancellationToken cancellationToken) { if (testContextState == nameof(FlowTestContextCancellationTokenAnalyzer.TestContextState.CouldBeInScopeAsProperty)) { Debug.Assert(testContextMemberName is null, "TestContext member name should be null when state is CouldBeInScopeAsProperty"); - AddCancellationTokenArgument(editor, invocationExpression, "TestContext"); + AddCancellationTokenArgument(editor, invocationExpression, "TestContext", cancellationTokenParameterName); TypeDeclarationSyntax? containingTypeDeclaration = invocationExpression.FirstAncestorOrSelf(); if (containingTypeDeclaration is not null) { @@ -96,7 +98,7 @@ internal static Document ApplyFix( else if (testContextState == nameof(FlowTestContextCancellationTokenAnalyzer.TestContextState.CouldBeInScopeAsParameter)) { Debug.Assert(testContextMemberName is null, "TestContext member name should be null when state is CouldBeInScopeAsParameter"); - AddCancellationTokenArgument(editor, invocationExpression, "testContext"); + AddCancellationTokenArgument(editor, invocationExpression, "testContext", cancellationTokenParameterName); MethodDeclarationSyntax? containingMethodDeclaration = invocationExpression.FirstAncestorOrSelf(); if (containingMethodDeclaration is not null) @@ -116,7 +118,7 @@ internal static Document ApplyFix( else { Guard.NotNull(testContextMemberName); - AddCancellationTokenArgument(editor, invocationExpression, testContextMemberName); + AddCancellationTokenArgument(editor, invocationExpression, testContextMemberName, cancellationTokenParameterName); } return editor.GetChangedDocument(); @@ -125,7 +127,8 @@ internal static Document ApplyFix( internal static void AddCancellationTokenArgument( DocumentEditor editor, InvocationExpressionSyntax invocationExpression, - string testContextMemberName) + string testContextMemberName, + string? cancellationTokenParameterName) { // Find the containing method to determine the context MethodDeclarationSyntax? containingMethod = invocationExpression.FirstAncestorOrSelf(); @@ -140,7 +143,8 @@ internal static void AddCancellationTokenArgument( { var invocationExpression = (InvocationExpressionSyntax)node; ArgumentListSyntax currentArguments = invocationExpression.ArgumentList; - SeparatedSyntaxList newArguments = currentArguments.Arguments.Add(SyntaxFactory.Argument(testContextExpression)); + NameColonSyntax? nameColon = cancellationTokenParameterName is null ? null : SyntaxFactory.NameColon(cancellationTokenParameterName); + SeparatedSyntaxList newArguments = currentArguments.Arguments.Add(SyntaxFactory.Argument(nameColon, default, testContextExpression)); return invocationExpression.WithArgumentList(currentArguments.WithArguments(newArguments)); }); } @@ -252,9 +256,10 @@ private static void FixOneDiagnostic(DocumentEditor documentEditor, Diagnostic d } diagnostic.Properties.TryGetValue(FlowTestContextCancellationTokenAnalyzer.TestContextMemberNamePropertyKey, out string? testContextMemberName); + diagnostic.Properties.TryGetValue(FlowTestContextCancellationTokenAnalyzer.CancellationTokenParameterNamePropertyKey, out string? cancellationTokenParameterName); diagnostic.Properties.TryGetValue(nameof(FlowTestContextCancellationTokenAnalyzer.TestContextState), out string? testContextState); - FlowTestContextCancellationTokenFixer.ApplyFix(documentEditor, invocationExpression, testContextMemberName, testContextState, fixedSymbols, cancellationToken); + FlowTestContextCancellationTokenFixer.ApplyFix(documentEditor, invocationExpression, testContextMemberName, testContextState, cancellationTokenParameterName, fixedSymbols, cancellationToken); } } } diff --git a/src/Analyzers/MSTest.Analyzers/FlowTestContextCancellationTokenAnalyzer.cs b/src/Analyzers/MSTest.Analyzers/FlowTestContextCancellationTokenAnalyzer.cs index 19eb3b5cde..388b893439 100644 --- a/src/Analyzers/MSTest.Analyzers/FlowTestContextCancellationTokenAnalyzer.cs +++ b/src/Analyzers/MSTest.Analyzers/FlowTestContextCancellationTokenAnalyzer.cs @@ -24,6 +24,7 @@ public sealed class FlowTestContextCancellationTokenAnalyzer : DiagnosticAnalyze private static readonly LocalizableResourceString MessageFormat = new(nameof(Resources.FlowTestContextCancellationTokenMessageFormat), Resources.ResourceManager, typeof(Resources)); internal const string TestContextMemberNamePropertyKey = nameof(TestContextMemberNamePropertyKey); + internal const string CancellationTokenParameterNamePropertyKey = nameof(CancellationTokenParameterNamePropertyKey); internal static readonly DiagnosticDescriptor FlowTestContextCancellationTokenRule = DiagnosticDescriptorHelper.Create( DiagnosticIds.FlowTestContextCancellationTokenRuleId, @@ -92,31 +93,52 @@ private static void AnalyzeInvocation( if (parameterHasDefaultValue && invocationOperation.Arguments.FirstOrDefault(arg => SymbolEqualityComparer.Default.Equals(arg.Parameter, cancellationTokenParameter))?.ArgumentKind != ArgumentKind.Explicit) { - // The called method has an optional CancellationToken parameter, but it was not explicitly provided. - context.ReportDiagnostic(invocationOperation.Syntax.CreateDiagnostic(FlowTestContextCancellationTokenRule, properties: GetPropertiesBag(testContextMemberNameInScope, testContextState))); + // The called method has an optional CancellationToken parameter, but it was not explicitly provided. So we report a diagnostic. + // We also pass non-null cancellationTokenParameterName if the codefix should use named argument. + string? cancellationTokenParameterName = null; + int indexOfParameterCorrespondingToLastExplicitArgument = invocationOperation.Arguments.LastOrDefault(arg => arg.ArgumentKind == ArgumentKind.Explicit)?.Parameter?.Ordinal ?? -1; + if (cancellationTokenParameter!.Ordinal != indexOfParameterCorrespondingToLastExplicitArgument + 1) + { + cancellationTokenParameterName = cancellationTokenParameter.Name; + } + + context.ReportDiagnostic(invocationOperation.Syntax.CreateDiagnostic(FlowTestContextCancellationTokenRule, properties: GetPropertiesBag(testContextMemberNameInScope, testContextState, cancellationTokenParameterName))); return; } // At this point, we want to only continue analysis if and only if the called method didn't have a CancellationToken parameter. // In this case, we look for other overloads that might accept a CancellationToken. if (cancellationTokenParameter is null && - HasOverloadWithCancellationToken(method, cancellationTokenSymbol)) + GetCancellationTokenParameterOfOverloadWithCancellationToken(method, cancellationTokenSymbol) is { } cancellationTokenParameterFromDifferentOverload) { - context.ReportDiagnostic(invocationOperation.Syntax.CreateDiagnostic(FlowTestContextCancellationTokenRule, properties: GetPropertiesBag(testContextMemberNameInScope, testContextState))); + string? cancellationTokenParameterName = null; + int indexOfParameterCorrespondingToLastExplicitArgument = invocationOperation.Arguments.LastOrDefault(arg => arg.ArgumentKind == ArgumentKind.Explicit)?.Parameter?.Ordinal ?? -1; + + if (cancellationTokenParameterFromDifferentOverload.Ordinal != indexOfParameterCorrespondingToLastExplicitArgument + 1) + { + cancellationTokenParameterName = cancellationTokenParameterFromDifferentOverload.Name; + } + + context.ReportDiagnostic(invocationOperation.Syntax.CreateDiagnostic(FlowTestContextCancellationTokenRule, properties: GetPropertiesBag(testContextMemberNameInScope, testContextState, cancellationTokenParameterName))); } - static ImmutableDictionary GetPropertiesBag(string? testContextMemberNameInScope, TestContextState? testContextState) + static ImmutableDictionary GetPropertiesBag(string? testContextMemberNameInScope, TestContextState? testContextState, string? cancellationTokenParameterName) { ImmutableDictionary properties = ImmutableDictionary.Empty; properties = testContextMemberNameInScope is not null ? properties.Add(TestContextMemberNamePropertyKey, testContextMemberNameInScope) : properties.Add(nameof(TestContextState), testContextState.ToString()); + if (cancellationTokenParameterName is not null) + { + properties = properties.Add(CancellationTokenParameterNamePropertyKey, cancellationTokenParameterName); + } + return properties; } } - private static bool HasOverloadWithCancellationToken(IMethodSymbol method, INamedTypeSymbol cancellationTokenSymbol) + private static IParameterSymbol? GetCancellationTokenParameterOfOverloadWithCancellationToken(IMethodSymbol method, INamedTypeSymbol cancellationTokenSymbol) { // Look for overloads of the same method that accept CancellationToken INamedTypeSymbol containingType = method.ContainingType; @@ -128,14 +150,14 @@ private static bool HasOverloadWithCancellationToken(IMethodSymbol method, IName candidateMethod.IsStatic == method.IsStatic) { // Check if this method has the same parameters plus a CancellationToken - if (IsCompatibleOverloadWithCancellationToken(method, candidateMethod, cancellationTokenSymbol)) + if (GetCancellationTokenParameterIfCandidateIsValid(method, candidateMethod, cancellationTokenSymbol) is { } parameter) { - return true; + return parameter; } } } - return false; + return null; } private static bool HasOrCouldHaveTestContextInScope( @@ -202,7 +224,7 @@ private static bool HasOrCouldHaveTestContextInScope( return false; } - private static bool IsCompatibleOverloadWithCancellationToken(IMethodSymbol originalMethod, IMethodSymbol candidateMethod, INamedTypeSymbol cancellationTokenSymbol) + private static IParameterSymbol? GetCancellationTokenParameterIfCandidateIsValid(IMethodSymbol originalMethod, IMethodSymbol candidateMethod, INamedTypeSymbol cancellationTokenSymbol) { // Check if the candidate method has all the same parameters as the original method plus a CancellationToken ImmutableArray originalParams = originalMethod.Parameters; @@ -211,7 +233,7 @@ private static bool IsCompatibleOverloadWithCancellationToken(IMethodSymbol orig // The candidate should have one more parameter (the CancellationToken) if (candidateParams.Length != originalParams.Length + 1) { - return false; + return null; } // Check if all original parameters match the first N parameters of the candidate @@ -219,13 +241,13 @@ private static bool IsCompatibleOverloadWithCancellationToken(IMethodSymbol orig { if (!SymbolEqualityComparer.Default.Equals(originalParams[i].Type, candidateParams[i].Type)) { - return false; + return null; } } // Check if the last parameter is CancellationToken IParameterSymbol lastParam = candidateParams[candidateParams.Length - 1]; - return SymbolEqualityComparer.Default.Equals(lastParam.Type, cancellationTokenSymbol); + return SymbolEqualityComparer.Default.Equals(lastParam.Type, cancellationTokenSymbol) ? lastParam : null; } internal enum TestContextState diff --git a/test/UnitTests/MSTest.Analyzers.UnitTests/FlowTestContextCancellationTokenAnalyzerTests.cs b/test/UnitTests/MSTest.Analyzers.UnitTests/FlowTestContextCancellationTokenAnalyzerTests.cs index 311d1d4cff..81b2287f63 100644 --- a/test/UnitTests/MSTest.Analyzers.UnitTests/FlowTestContextCancellationTokenAnalyzerTests.cs +++ b/test/UnitTests/MSTest.Analyzers.UnitTests/FlowTestContextCancellationTokenAnalyzerTests.cs @@ -738,4 +738,52 @@ public static async Task AssemblyCleanup(TestContext testContext) await VerifyCS.VerifyCodeFixAsync(code, fixedCode); } + + [TestMethod] + public async Task WhenMethodWithPositionalArguments_ShouldUseNamedArgumentForCancellationToken() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + using System.Threading; + using System.Threading.Tasks; + public static class TestHelper + { + public static void DoSomething(string x = "", int i = 1, CancellationToken ct = default) { } + } + [TestClass] + public class MyTestClass + { + public TestContext TestContext { get; set; } + [TestMethod] + public void Test() + { + [|TestHelper.DoSomething("test")|]; + [|TestHelper.DoSomething("test", 42)|]; + } + } + """; + + string fixedCode = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + using System.Threading; + using System.Threading.Tasks; + public static class TestHelper + { + public static void DoSomething(string x = "", int i = 1, CancellationToken ct = default) { } + } + [TestClass] + public class MyTestClass + { + public TestContext TestContext { get; set; } + [TestMethod] + public void Test() + { + TestHelper.DoSomething("test", ct: TestContext.CancellationToken); + TestHelper.DoSomething("test", 42, TestContext.CancellationToken); + } + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, fixedCode); + } } From fb48f61b25dd221f0b7568863080ab5339df8def Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Mon, 29 Sep 2025 20:57:27 +0000 Subject: [PATCH 531/541] [main] Update dependencies from dotnet/arcade (#6620) Co-authored-by: dotnet-maestro[bot] --- eng/Version.Details.xml | 12 ++++++------ eng/Versions.props | 2 +- global.json | 2 +- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index a8ac1c6d10..971f4a23a6 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -1,17 +1,17 @@ - + https://github.com/dotnet/arcade - e19df003785d0b81e2e3e1bf6e588bf8d913e95e + 72db5dba8e9f5fa3f8c323fab7d819de3e2b0ee5 - + https://github.com/dotnet/arcade - e19df003785d0b81e2e3e1bf6e588bf8d913e95e + 72db5dba8e9f5fa3f8c323fab7d819de3e2b0ee5 - + https://github.com/dotnet/arcade - e19df003785d0b81e2e3e1bf6e588bf8d913e95e + 72db5dba8e9f5fa3f8c323fab7d819de3e2b0ee5 https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage diff --git a/eng/Versions.props b/eng/Versions.props index 718adbf270..a0b3d94b5f 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -7,7 +7,7 @@ preview - 11.0.0-beta.25477.2 + 11.0.0-beta.25479.2 18.0.4-preview.25475.6 3.11.0-preview.25477.2 diff --git a/global.json b/global.json index bc3fc31b2f..f7a9692bcf 100644 --- a/global.json +++ b/global.json @@ -36,7 +36,7 @@ "runner": "Microsoft.Testing.Platform" }, "msbuild-sdks": { - "Microsoft.DotNet.Arcade.Sdk": "11.0.0-beta.25477.2", + "Microsoft.DotNet.Arcade.Sdk": "11.0.0-beta.25479.2", "MSBuild.Sdk.Extras": "3.0.44" } } From 4accecdbbe6df2ec567ae29e9862c05f3b13e8a3 Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Tue, 30 Sep 2025 09:21:10 +0200 Subject: [PATCH 532/541] [main] Update dependencies from microsoft/testfx (#6622) Co-authored-by: dotnet-maestro[bot] --- eng/Version.Details.xml | 8 ++++---- eng/Versions.props | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index 971f4a23a6..ffccec6cea 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -17,13 +17,13 @@ https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage b1e7fa5bb1a3e468b6f9d47cf61a3b5616c44713 - + https://github.com/microsoft/testfx - 7676243b3f031de055c7f8d4c6c0cac6b5cadc44 + fb48f61b25dd221f0b7568863080ab5339df8def - + https://github.com/microsoft/testfx - 7676243b3f031de055c7f8d4c6c0cac6b5cadc44 + fb48f61b25dd221f0b7568863080ab5339df8def diff --git a/eng/Versions.props b/eng/Versions.props index a0b3d94b5f..1f0d0bd068 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -10,7 +10,7 @@ 11.0.0-beta.25479.2 18.0.4-preview.25475.6 - 3.11.0-preview.25477.2 - 1.9.0-preview.25477.2 + 3.11.0-preview.25479.5 + 1.9.0-preview.25479.5 From 590e7b17ef37a73c7c13fe9d028800225b5f3b72 Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Tue, 30 Sep 2025 07:51:28 +0000 Subject: [PATCH 533/541] [main] Update dependencies from dotnet/arcade (#6623) Co-authored-by: dotnet-maestro[bot] --- eng/Version.Details.xml | 12 ++++++------ eng/Versions.props | 2 +- eng/common/build.sh | 2 +- eng/common/darc-init.sh | 2 +- eng/common/dotnet-install.sh | 2 +- eng/common/dotnet.sh | 2 +- eng/common/internal-feed-operations.sh | 2 +- eng/common/post-build/nuget-verification.ps1 | 2 +- eng/common/sdk-task.ps1 | 2 +- eng/common/tools.ps1 | 4 ++-- global.json | 2 +- 11 files changed, 17 insertions(+), 17 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index ffccec6cea..7ba878bf3e 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -1,17 +1,17 @@ - + https://github.com/dotnet/arcade - 72db5dba8e9f5fa3f8c323fab7d819de3e2b0ee5 + 34019881836f80da952b9e5cb702bebf7b5362c6 - + https://github.com/dotnet/arcade - 72db5dba8e9f5fa3f8c323fab7d819de3e2b0ee5 + 34019881836f80da952b9e5cb702bebf7b5362c6 - + https://github.com/dotnet/arcade - 72db5dba8e9f5fa3f8c323fab7d819de3e2b0ee5 + 34019881836f80da952b9e5cb702bebf7b5362c6 https://dev.azure.com/devdiv/DevDiv/_git/vs-code-coverage diff --git a/eng/Versions.props b/eng/Versions.props index 1f0d0bd068..ca2fdfbda9 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -7,7 +7,7 @@ preview - 11.0.0-beta.25479.2 + 11.0.0-beta.25479.7 18.0.4-preview.25475.6 3.11.0-preview.25479.5 diff --git a/eng/common/build.sh b/eng/common/build.sh index 9767bb411a..ec3e80d189 100755 --- a/eng/common/build.sh +++ b/eng/common/build.sh @@ -92,7 +92,7 @@ runtime_source_feed='' runtime_source_feed_key='' properties=() -while [[ $# > 0 ]]; do +while [[ $# -gt 0 ]]; do opt="$(echo "${1/#--/-}" | tr "[:upper:]" "[:lower:]")" case "$opt" in -help|-h) diff --git a/eng/common/darc-init.sh b/eng/common/darc-init.sh index e889f439b8..9f5ad6b763 100644 --- a/eng/common/darc-init.sh +++ b/eng/common/darc-init.sh @@ -5,7 +5,7 @@ darcVersion='' versionEndpoint='https://maestro.dot.net/api/assets/darc-version?api-version=2020-02-20' verbosity='minimal' -while [[ $# > 0 ]]; do +while [[ $# -gt 0 ]]; do opt="$(echo "$1" | tr "[:upper:]" "[:lower:]")" case "$opt" in --darcversion) diff --git a/eng/common/dotnet-install.sh b/eng/common/dotnet-install.sh index 7b9d97e3bd..61f302bb67 100755 --- a/eng/common/dotnet-install.sh +++ b/eng/common/dotnet-install.sh @@ -18,7 +18,7 @@ architecture='' runtime='dotnet' runtimeSourceFeed='' runtimeSourceFeedKey='' -while [[ $# > 0 ]]; do +while [[ $# -gt 0 ]]; do opt="$(echo "$1" | tr "[:upper:]" "[:lower:]")" case "$opt" in -version|-v) diff --git a/eng/common/dotnet.sh b/eng/common/dotnet.sh index 2ef6823567..f6d24871c1 100644 --- a/eng/common/dotnet.sh +++ b/eng/common/dotnet.sh @@ -19,7 +19,7 @@ source $scriptroot/tools.sh InitializeDotNetCli true # install # Invoke acquired SDK with args if they are provided -if [[ $# > 0 ]]; then +if [[ $# -gt 0 ]]; then __dotnetDir=${_InitializeDotNetCli} dotnetPath=${__dotnetDir}/dotnet ${dotnetPath} "$@" diff --git a/eng/common/internal-feed-operations.sh b/eng/common/internal-feed-operations.sh index 9378223ba0..6299e7effd 100644 --- a/eng/common/internal-feed-operations.sh +++ b/eng/common/internal-feed-operations.sh @@ -100,7 +100,7 @@ operation='' authToken='' repoName='' -while [[ $# > 0 ]]; do +while [[ $# -gt 0 ]]; do opt="$(echo "$1" | tr "[:upper:]" "[:lower:]")" case "$opt" in --operation) diff --git a/eng/common/post-build/nuget-verification.ps1 b/eng/common/post-build/nuget-verification.ps1 index a365194a93..ac5c69ffca 100644 --- a/eng/common/post-build/nuget-verification.ps1 +++ b/eng/common/post-build/nuget-verification.ps1 @@ -30,7 +30,7 @@ [CmdletBinding(PositionalBinding = $false)] param( [string]$NuGetExePath, - [string]$PackageSource = "https://api.nuget.org/v3/index.json", + [string]$PackageSource = "https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-public/nuget/v3/index.json", [string]$DownloadPath, [Parameter(ValueFromRemainingArguments = $true)] [string[]]$args diff --git a/eng/common/sdk-task.ps1 b/eng/common/sdk-task.ps1 index b62e132d32..4655af7a2d 100644 --- a/eng/common/sdk-task.ps1 +++ b/eng/common/sdk-task.ps1 @@ -68,7 +68,7 @@ try { $GlobalJson.tools | Add-Member -Name "vs" -Value (ConvertFrom-Json "{ `"version`": `"16.5`" }") -MemberType NoteProperty } if( -not ($GlobalJson.tools.PSObject.Properties.Name -match "xcopy-msbuild" )) { - $GlobalJson.tools | Add-Member -Name "xcopy-msbuild" -Value "17.13.0" -MemberType NoteProperty + $GlobalJson.tools | Add-Member -Name "xcopy-msbuild" -Value "17.14.16" -MemberType NoteProperty } if ($GlobalJson.tools."xcopy-msbuild".Trim() -ine "none") { $xcopyMSBuildToolsFolder = InitializeXCopyMSBuild $GlobalJson.tools."xcopy-msbuild" -install $true diff --git a/eng/common/tools.ps1 b/eng/common/tools.ps1 index 06b44de787..4bc50bd568 100644 --- a/eng/common/tools.ps1 +++ b/eng/common/tools.ps1 @@ -394,8 +394,8 @@ function InitializeVisualStudioMSBuild([bool]$install, [object]$vsRequirements = # If the version of msbuild is going to be xcopied, # use this version. Version matches a package here: - # https://dev.azure.com/dnceng/public/_artifacts/feed/dotnet-eng/NuGet/Microsoft.DotNet.Arcade.MSBuild.Xcopy/versions/17.13.0 - $defaultXCopyMSBuildVersion = '17.13.0' + # https://dev.azure.com/dnceng/public/_artifacts/feed/dotnet-eng/NuGet/Microsoft.DotNet.Arcade.MSBuild.Xcopy/versions/17.14.16 + $defaultXCopyMSBuildVersion = '17.14.16' if (!$vsRequirements) { if (Get-Member -InputObject $GlobalJson.tools -Name 'vs') { diff --git a/global.json b/global.json index f7a9692bcf..d17d80f519 100644 --- a/global.json +++ b/global.json @@ -36,7 +36,7 @@ "runner": "Microsoft.Testing.Platform" }, "msbuild-sdks": { - "Microsoft.DotNet.Arcade.Sdk": "11.0.0-beta.25479.2", + "Microsoft.DotNet.Arcade.Sdk": "11.0.0-beta.25479.7", "MSBuild.Sdk.Extras": "3.0.44" } } From 19fc92bf7574f8a7a1e356c595187c7949e4b0b3 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Tue, 30 Sep 2025 13:21:40 +0200 Subject: [PATCH 534/541] Include TestFramework.Extensions.dll in TestAdapter NuGet package for .NET Framework (#6625) --- eng/verify-nupkgs.ps1 | 2 +- src/Adapter/MSTest.TestAdapter/MSTest.TestAdapter.nuspec | 7 +++++++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/eng/verify-nupkgs.ps1 b/eng/verify-nupkgs.ps1 index 4e267fc109..719c8aefd7 100644 --- a/eng/verify-nupkgs.ps1 +++ b/eng/verify-nupkgs.ps1 @@ -21,7 +21,7 @@ function Confirm-NugetPackages { $expectedNumOfFiles = @{ "MSTest.Sdk" = 15 "MSTest.TestFramework" = 162 - "MSTest.TestAdapter" = 80 + "MSTest.TestAdapter" = 81 "MSTest" = 14 "MSTest.Analyzers" = 56 } diff --git a/src/Adapter/MSTest.TestAdapter/MSTest.TestAdapter.nuspec b/src/Adapter/MSTest.TestAdapter/MSTest.TestAdapter.nuspec index 513ffc408a..e1388eac5f 100644 --- a/src/Adapter/MSTest.TestAdapter/MSTest.TestAdapter.nuspec +++ b/src/Adapter/MSTest.TestAdapter/MSTest.TestAdapter.nuspec @@ -133,6 +133,13 @@ --> + + + From 8528019fe7f6a96667fb345da2d433fb6a01ec19 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Tue, 30 Sep 2025 16:31:35 +0200 Subject: [PATCH 535/541] Update Changelog for 3.10.5 (#6628) --- docs/Changelog-Platform.md | 23 +++++++++++++++++++++++ docs/Changelog.md | 18 ++++++++++++++++++ 2 files changed, 41 insertions(+) diff --git a/docs/Changelog-Platform.md b/docs/Changelog-Platform.md index 03332943e6..edd71dc4ac 100644 --- a/docs/Changelog-Platform.md +++ b/docs/Changelog-Platform.md @@ -4,6 +4,29 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) +## [1.8.5] - 2025-09-30 + +See full log [of v3.10.4...v3.10.5](https://github.com/microsoft/testfx/compare/v3.10.4...v3.10.5) + +### Fixed + +* Avoid long path issues for pipes by @Youssef1313 in [#6536](https://github.com/microsoft/testfx/pull/6536) +* Clean TestProgressState on TestExecutionCompleted to fix HotReload by @Youssef1313 in [#6505](https://github.com/microsoft/testfx/pull/6551) + +### Artifacts + +* Microsoft.Testing.Platform: [1.8.5](https://www.nuget.org/packages/Microsoft.Testing.Platform/1.8.5) +* Microsoft.Testing.Platform.MSBuild: [1.8.5](https://www.nuget.org/packages/Microsoft.Testing.Platform.MSBuild/1.8.5) +* Microsoft.Testing.Extensions.CrashDump: [1.8.5](https://www.nuget.org/packages/Microsoft.Testing.Extensions.CrashDump/1.8.5) +* Microsoft.Testing.Extensions.HangDump: [1.8.5](https://www.nuget.org/packages/Microsoft.Testing.Extensions.HangDump/1.8.5) +* Microsoft.Testing.Extensions.HotReload: [1.8.5](https://www.nuget.org/packages/Microsoft.Testing.Extensions.HotReload/1.8.5) +* Microsoft.Testing.Extensions.Retry: [1.8.5](https://www.nuget.org/packages/Microsoft.Testing.Extensions.Retry/1.8.5) +* Microsoft.Testing.Extensions.Telemetry: [1.8.5](https://www.nuget.org/packages/Microsoft.Testing.Extensions.Telemetry/1.8.5) +* Microsoft.Testing.Extensions.TrxReport: [1.8.5](https://www.nuget.org/packages/Microsoft.Testing.Extensions.TrxReport/1.8.5) +* Microsoft.Testing.Extensions.TrxReport.Abstractions: [1.8.5](https://www.nuget.org/packages/Microsoft.Testing.Extensions.TrxReport.Abstractions/1.8.5) +* Microsoft.Testing.Extensions.VSTestBridge: [1.8.5](https://www.nuget.org/packages/Microsoft.Testing.Extensions.VSTestBridge/1.8.5) +* Microsoft.Testing.Extensions.AzureDevOpsReport [1.0.0-alpha.25480.6](https://www.nuget.org/packages/Microsoft.Testing.Extensions.AzureDevOpsReport/1.0.0-alpha.25480.6) + ## [1.8.4] - 2025-09-02 See full log [of v3.10.3...v3.10.4](https://github.com/microsoft/testfx/compare/v3.10.3...v3.10.4) diff --git a/docs/Changelog.md b/docs/Changelog.md index ab3fbb01bb..f831a96576 100644 --- a/docs/Changelog.md +++ b/docs/Changelog.md @@ -4,6 +4,24 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) +## [3.10.5] - 2025-09-30 + +See full log [of v3.10.4...v3.10.5](https://github.com/microsoft/testfx/compare/v3.10.4...v3.10.5) + +### Fixed + +* Include TestFramework.Extensions.dll in TestAdapter NuGet package for .NET Framework by @Youssef1313 in [#6625](https://github.com/microsoft/testfx/pull/6625) + +### Artifacts + +* MSTest: [3.10.5](https://www.nuget.org/packages/MSTest/3.10.5) +* MSTest.TestFramework: [3.10.5](https://www.nuget.org/packages/MSTest.TestFramework/3.10.5) +* MSTest.TestAdapter: [3.10.5](https://www.nuget.org/packages/MSTest.TestAdapter/3.10.5) +* MSTest.Analyzers: [3.10.5](https://www.nuget.org/packages/MSTest.Analyzers/3.10.5) +* MSTest.Sdk: [3.10.5](https://www.nuget.org/packages/MSTest.Sdk/3.10.5) +* MSTest.SourceGeneration: [1.0.0-alpha.25480.6](https://www.nuget.org/packages/MSTest.SourceGeneration/1.0.0-alpha.25480.6) +* MSTest.Engine: [1.0.0-alpha.25480.6](https://www.nuget.org/packages/MSTest.Engine/1.0.0-alpha.25480.6) + ## [3.10.4] - 2025-09-02 See full log [of v3.10.3...v3.10.4](https://github.com/microsoft/testfx/compare/v3.10.3...v3.10.4) From 6a267c504c2e44da78a48d0b7b13d6f35984e94b Mon Sep 17 00:00:00 2001 From: youssef-backport-bot Date: Tue, 30 Sep 2025 21:45:02 +0200 Subject: [PATCH 536/541] Update Playwright version to 1.55.0 by @Youssef1313 in #6631 (backport to rel/3.11) (#6632) Co-authored-by: Youssef Victor --- Directory.Packages.props | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Directory.Packages.props b/Directory.Packages.props index b0d823d309..e457c3f542 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -23,7 +23,7 @@ 6.2.14 17.13.0 - 1.54.0 + 1.55.0 17.14.1 1.5.0-preview.24577.4 4.5.4 From a2b8360e16ee952a145a51aadc61783c9793c177 Mon Sep 17 00:00:00 2001 From: youssef-backport-bot Date: Tue, 30 Sep 2025 21:47:19 +0200 Subject: [PATCH 537/541] Update AspireHostingTestingVersion to 9.5.0 by @Youssef1313 in #6629 (backport to rel/3.11) (#6630) Co-authored-by: Youssef Victor --- Directory.Packages.props | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Directory.Packages.props b/Directory.Packages.props index e457c3f542..c66400d3bd 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -12,7 +12,7 @@ false - 9.4.0 + 9.5.0 17.11.4 3.11.0 4.10.0 From 7377cb3ff2a82523bcc987dfd27458eff73314b6 Mon Sep 17 00:00:00 2001 From: Youssef Victor Date: Wed, 1 Oct 2025 07:41:34 +0200 Subject: [PATCH 538/541] Use stable CC in rel/3.11 (#6633) --- eng/Versions.props | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/eng/Versions.props b/eng/Versions.props index ca2fdfbda9..16d9c6a3e2 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -8,7 +8,7 @@ 11.0.0-beta.25479.7 - 18.0.4-preview.25475.6 + 18.0.4 3.11.0-preview.25479.5 1.9.0-preview.25479.5 From 1fa6fa6f173dde00b5b967794ad4ea9dc51d593f Mon Sep 17 00:00:00 2001 From: youssef-backport-bot Date: Wed, 1 Oct 2025 09:23:45 +0200 Subject: [PATCH 539/541] [MTP] Warn when VSTest arguments are passed via dotnet test when they will be ignored by @Copilot in #5698 (backport to rel/3.11) (#6634) Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: Youssef1313 <31348972+Youssef1313@users.noreply.github.com> Co-authored-by: Youssef Victor --- ...Microsoft.Testing.Platform.MSBuild.targets | 22 ++++++++- .../MSBuildTests.Test.cs | 45 +++++++++++++++++++ 2 files changed, 66 insertions(+), 1 deletion(-) diff --git a/src/Platform/Microsoft.Testing.Platform.MSBuild/buildMultiTargeting/Microsoft.Testing.Platform.MSBuild.targets b/src/Platform/Microsoft.Testing.Platform.MSBuild/buildMultiTargeting/Microsoft.Testing.Platform.MSBuild.targets index 04b28bc764..8587250576 100644 --- a/src/Platform/Microsoft.Testing.Platform.MSBuild/buildMultiTargeting/Microsoft.Testing.Platform.MSBuild.targets +++ b/src/Platform/Microsoft.Testing.Platform.MSBuild/buildMultiTargeting/Microsoft.Testing.Platform.MSBuild.targets @@ -331,7 +331,7 @@ False true - + + + + + diff --git a/src/Platform/Microsoft.Testing.Extensions.Telemetry/Microsoft.Testing.Extensions.Telemetry.csproj b/src/Platform/Microsoft.Testing.Extensions.Telemetry/Microsoft.Testing.Extensions.Telemetry.csproj index 5ff94339a8..bc59d4a00a 100644 --- a/src/Platform/Microsoft.Testing.Extensions.Telemetry/Microsoft.Testing.Extensions.Telemetry.csproj +++ b/src/Platform/Microsoft.Testing.Extensions.Telemetry/Microsoft.Testing.Extensions.Telemetry.csproj @@ -2,6 +2,7 @@ netstandard2.0;$(MicrosoftTestingTargetFrameworks) + $(NoWarn);NU1510 @@ -42,6 +43,10 @@ This package provides telemetry for the platform.]]> + + + +