From 4881f55105da6f57b02104730038664db6d999ad Mon Sep 17 00:00:00 2001 From: Bogdan Gavril Date: Tue, 9 Dec 2025 20:59:53 +0000 Subject: [PATCH 1/5] wip --- Directory.Packages.props | 4 +- .../CacheExecutionTests.cs | 4 +- .../Core/Helpers/CoreAssert.cs | 4 +- .../Core/Helpers/RunOnPlatformAttribute.cs | 52 +++--- .../Core/Mocks/MockHttpManager.cs | 2 +- .../Core/Mocks/MockHttpMessageHandler.cs | 10 +- .../KeyGuardAttestationTests.cs | 4 +- .../ManagedIdentityImdsTests.cs | 6 +- .../HeadlessTests/Agentic.cs | 2 +- .../ClientCredentialsTests.NetFwk.cs | 26 +-- .../ClientCredentialsTests.WithRegion.cs | 4 +- .../HeadlessTests/FmiIntegrationTests.cs | 2 +- .../InstanceDiscoveryIntegrationTests.cs | 2 +- .../LongRunningOnBehalfOfTests.cs | 52 +++--- .../ManagedIdentityTests.NetFwk.cs | 12 +- .../MsalCacheStorageIntegrationTests.cs | 8 +- .../OnBehalfOfServicePrincipalTests.cs | 16 +- .../HeadlessTests/OnBehalfOfTests.cs | 10 +- .../HeadlessTests/PoPTests.NetFwk.cs | 6 +- .../HeadlessTests/ProactiveRefreshTests.cs | 6 +- .../HeadlessTests/RuntimeBrokerTests.cs | 86 ++++----- ...UsernamePasswordIntegrationTests.NetFwk.cs | 2 +- ...ticateParametersIntegrationTests.NetFwk.cs | 6 +- .../Infrastructure/IgnoreFederatedTests.cs | 13 +- .../Infrastructure/IgnoreOnOneBranch.cs | 14 +- .../Infrastructure/TargetFramework.cs | 12 +- .../DeviceCodeFlowIntegrationTest.cs | 2 +- .../InteractiveFlowTests.NetFwk.cs | 8 +- .../SeleniumInfrastructureTests.NetFwk.cs | 2 +- ...Microsoft.Identity.Test.Performance.csproj | 4 +- .../ApiConfigTests/AuthorityTests.cs | 57 +++--- .../AppConfigTests/CiamAuthorityTests.cs | 6 +- ...nfidentialClientApplicationBuilderTests.cs | 22 +-- .../ManagedIdentityApplicationBuilderTests.cs | 10 +- .../PublicClientApplicationBuilderTests.cs | 14 +- .../AppTokenProviderTests.cs | 10 +- .../AuthenticationOperationTests.cs | 6 +- .../BrokerTests/BrokerRequestTests.cs | 34 ++-- .../BrokerTests/RuntimeBrokerTests.cs | 4 +- .../BrokerTests/WamGetAccountsTests.cs | 6 +- .../CacheExtension/IntegrationTests.cs | 2 +- .../CacheExtension/MacKeyChainTests.cs | 3 +- .../CacheExtension/MsalCacheHelperTests.cs | 4 +- .../CacheExtension/MsalCacheStorageTests.cs | 8 +- .../CacheExtension/TraceStringListener.cs | 2 +- .../CacheTests/CacheFailureTests.cs | 4 +- .../CacheFallbackOperationsTests.cs | 4 +- .../CacheTests/CacheSerializationTests.cs | 26 +-- .../CacheTests/CacheSyncronizationTests.cs | 6 +- ...emoryPartitionedTokenCacheAccessorTests.cs | 170 +++++++++--------- .../CacheTests/TokenCacheNotificationTests.cs | 2 +- .../CacheTests/TokenCacheTests.cs | 29 ++- .../CacheTests/UnifiedCacheFormatTests.cs | 6 +- .../CacheTests/UnifiedCacheTests.cs | 12 +- .../CoreTests/CoreHelperTests.cs | 21 +-- .../CoreTests/HttpTests/HttpManagerTests.cs | 14 +- .../HttpTests/RedirectUriHelperTests.cs | 12 +- .../InstanceTests/AadAuthorityTests.cs | 36 ++-- .../InstanceTests/AdfsAuthorityTests.cs | 6 +- .../InstanceTests/B2cAuthorityTests.cs | 16 +- .../InstanceTests/DstsAuthorityTests.cs | 4 +- .../InstanceTests/GenericAuthorityTests.cs | 26 ++- .../InstanceTests/InstanceProviderTests.cs | 6 +- .../PublicApiInstanceMetadataTests.cs | 2 +- .../CoreTests/MsalIdHelperTests.cs | 4 +- .../CoreTests/OAuth2Tests/ClaimsTest.cs | 2 +- .../CoreTests/PlatformProxyFactoryTests.cs | 2 +- .../CoreTests/RegionDiscoveryProviderTests.cs | 30 ++-- .../CoreTests/WsTrustTests/MexParserTests.cs | 9 +- .../CoreTests/WsTrustTests/WsTrustTests.cs | 2 +- .../CryptographyTests.cs | 2 +- .../DeviceAuthHelperTests.cs | 12 +- .../MsalExceptionSerializationTests.cs | 2 +- .../ExceptionTests/MsalExceptionTests.cs | 98 +++++----- .../ManagedIdentityTests/AppServiceTests.cs | 4 +- .../ManagedIdentityTests/AzureArcTests.cs | 12 +- .../ManagedIdentityTests/CloudShellTests.cs | 6 +- .../ManagedIdentityTests/CsrValidator.cs | 4 +- .../DefaultRetryPolicyTests.cs | 16 +- .../FriendlyNameCodecTests.cs | 2 +- .../ManagedIdentityTests/ImdsTests.cs | 24 +-- .../ManagedIdentityTests/ImdsV2Tests.cs | 68 +++---- .../InMemoryCertificateCacheTests.cs | 30 ++-- ...InMemoryManagedIdentityKeyProviderTests.cs | 4 +- .../MachineLearningTests.cs | 8 +- .../ManagedIdentityTests.cs | 90 +++++----- .../PersistentCertificateCacheFactoryTests.cs | 2 +- .../PersistentCertificateStoreUnitTests.cs | 4 +- .../ServiceFabricTests.cs | 6 +- .../MetricsTests.cs | 24 +-- .../ParallelRequestsTests.cs | 16 +- .../PublicApiTests/AccountIdTest.cs | 2 +- .../PublicApiTests/AccountTests.cs | 8 +- .../PublicApiTests/AcquireTokenSilentTests.cs | 40 ++--- .../PublicApiTests/AdfsAcceptanceTests.cs | 4 +- .../AuthenticationOperationTests.cs | 2 +- .../PublicApiTests/CacheKeyExtensionTests.cs | 24 +-- .../ClientCredentialWithCertTest.cs | 26 +-- .../ClientCredentialWithRegionTests.cs | 44 ++--- .../ConfidentialClientApplicationTests.cs | 144 +++++++-------- .../PublicApiTests/ExtensiblityTests.cs | 24 +-- .../ExtraBodyParametersTests.cs | 22 +-- .../ExtraQueryParametersTests.cs | 26 +-- .../PublicApiTests/LoggerTests.cs | 14 +- .../PublicApiTests/MtlsPopTests.cs | 21 ++- .../PublicClientApplicationTests.cs | 16 +- .../PublicApiTests/RefreshInTests.cs | 14 +- .../PublicApiTests/TenantIdTests.cs | 6 +- .../RequestsTests/DeviceCodeRequestTests.cs | 8 +- .../RequestsTests/FociTests.cs | 2 +- ...egratedWindowsAuthUsernamePasswordTests.cs | 6 +- .../InteractiveRequestOrchestrationTests.cs | 6 +- .../RequestsTests/InteractiveRequestTests.cs | 22 +-- .../LongRunningOnBehalfOfTests.cs | 70 ++++---- .../RequestsTests/OnBehalfOfTests.cs | 12 +- .../TelemetryTests/HttpTelemetryTests.cs | 10 +- .../TelemetryTests/MsalIdHelperTests.cs | 2 +- .../OTelInstrumentationTests.cs | 2 +- .../TelemetryTests/RegionalTelemetryTests.cs | 8 +- .../TestExtensions.cs | 10 +- .../Throttling/ThrottlingAcceptanceTests.cs | 18 +- .../UtilTests/DateTimeHelperTests.cs | 16 +- .../UtilTests/HttpHeaderSantizerTests.cs | 2 +- .../UtilTests/RetryOperationHelperTest.cs | 6 +- .../UtilTests/StopWatchServiceTests.cs | 24 +-- .../UtilTests/UriBuilderExtensionsTests.cs | 2 +- .../WebUITests/DefaultOsBrowserWebUiTests.cs | 4 +- .../WwwAuthenticateParametersTests.cs | 32 ++-- .../pop/PopAuthenticationOperationTests.cs | 6 +- 129 files changed, 1090 insertions(+), 1069 deletions(-) diff --git a/Directory.Packages.props b/Directory.Packages.props index f01eb48133..51dec22d25 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -57,8 +57,8 @@ - - + + diff --git a/tests/CacheCompat/CommonCache.Test.Unit/CacheExecutionTests.cs b/tests/CacheCompat/CommonCache.Test.Unit/CacheExecutionTests.cs index 5c6ebcd696..613542e70d 100644 --- a/tests/CacheCompat/CommonCache.Test.Unit/CacheExecutionTests.cs +++ b/tests/CacheCompat/CommonCache.Test.Unit/CacheExecutionTests.cs @@ -34,7 +34,7 @@ public static void AssemblyInit(TestContext testContext) s_labUsers.Add(GetPublicAadUserDataAsync().GetAwaiter().GetResult()); } - [DataTestMethod] + [TestMethod] [DataRow(CacheProgramType.MsalV3, CacheProgramType.MsalV3, CacheStorageType.MsalV2, DisplayName = "MsalV3->MsalV3 msal v2 cache")] [DataRow(CacheProgramType.MsalV3, CacheProgramType.MsalV3, CacheStorageType.MsalV3, DisplayName = "MsalV3->MsalV3 msal v3 cache")] public async Task TestMsalV3CacheCompatibilityAsync( @@ -46,7 +46,7 @@ public async Task TestMsalV3CacheCompatibilityAsync( await executor.ExecuteAsync(interactiveType, silentType, CancellationToken.None).ConfigureAwait(false); } - [DataTestMethod] + [TestMethod] [DataRow(CacheProgramType.MsalV3, CacheProgramType.MsalJava, CacheStorageType.MsalV3, DisplayName = "MsalV3->MsalJava msal v3 cache")] [DataRow(CacheProgramType.MsalJava, CacheProgramType.MsalV3, CacheStorageType.MsalV3, DisplayName = "MsalJava->MsalV3 msal v3 cache")] public async Task TestMsalJavaCacheCompatibilityAsync( diff --git a/tests/Microsoft.Identity.Test.Common/Core/Helpers/CoreAssert.cs b/tests/Microsoft.Identity.Test.Common/Core/Helpers/CoreAssert.cs index 00a23a600b..dae697a068 100644 --- a/tests/Microsoft.Identity.Test.Common/Core/Helpers/CoreAssert.cs +++ b/tests/Microsoft.Identity.Test.Common/Core/Helpers/CoreAssert.cs @@ -20,10 +20,10 @@ public static void AreScopesEqual(string scopesExpected, string scopesActual) var actualScopes = ScopeHelper.ConvertStringToScopeSet(scopesActual); // can't use Assert.AreEqual on HashSet, so we'll compare by hand. - Assert.AreEqual(expectedScopes.Count, actualScopes.Count); + Assert.HasCount(expectedScopes.Count, actualScopes); foreach (string expectedScope in expectedScopes) { - Assert.IsTrue(actualScopes.Contains(expectedScope)); + Assert.Contains(expectedScope, actualScopes); } } diff --git a/tests/Microsoft.Identity.Test.Common/Core/Helpers/RunOnPlatformAttribute.cs b/tests/Microsoft.Identity.Test.Common/Core/Helpers/RunOnPlatformAttribute.cs index 1722a7dc35..077a1b9a74 100644 --- a/tests/Microsoft.Identity.Test.Common/Core/Helpers/RunOnPlatformAttribute.cs +++ b/tests/Microsoft.Identity.Test.Common/Core/Helpers/RunOnPlatformAttribute.cs @@ -2,35 +2,37 @@ // Licensed under the MIT License. using System; +using System.Runtime.CompilerServices; using System.Runtime.InteropServices; +using System.Threading.Tasks; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Microsoft.Identity.Test.Common.Core.Helpers { public class RunOnOSXAttribute : RunOnPlatformAttribute { - public RunOnOSXAttribute() : base(OSPlatform.OSX) + public RunOnOSXAttribute([CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1) : base(OSPlatform.OSX, callerFilePath, callerLineNumber) { } } public class RunOnWindowsAttribute : RunOnPlatformAttribute { - public RunOnWindowsAttribute() : base(OSPlatform.Windows) + public RunOnWindowsAttribute([CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1) : base(OSPlatform.Windows, callerFilePath, callerLineNumber) { } } public class RunOnLinuxAttribute : RunOnPlatformAttribute { - public RunOnLinuxAttribute() : base(OSPlatform.Linux) + public RunOnLinuxAttribute([CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1) : base(OSPlatform.Linux, callerFilePath, callerLineNumber) { } } public class DoNotRunOnWindowsAttribute : DoNotRunOnPlatformAttribute { - public DoNotRunOnWindowsAttribute(): base(OSPlatform.Windows) + public DoNotRunOnWindowsAttribute([CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1) : base(OSPlatform.Windows, callerFilePath, callerLineNumber) { } @@ -38,7 +40,7 @@ public DoNotRunOnWindowsAttribute(): base(OSPlatform.Windows) public class DoNotRunOnLinuxAttribute : DoNotRunOnPlatformAttribute { - public DoNotRunOnLinuxAttribute() : base(OSPlatform.Linux) + public DoNotRunOnLinuxAttribute([CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1) : base(OSPlatform.Linux, callerFilePath, callerLineNumber) { } } @@ -47,28 +49,31 @@ public class RunOnPlatformAttribute : TestMethodAttribute { private readonly OSPlatform _platform; - protected RunOnPlatformAttribute(OSPlatform platform) + protected RunOnPlatformAttribute( + OSPlatform platform, [CallerFilePath] string callerFilePath = "", + [CallerLineNumber] int callerLineNumber = -1) : base(callerFilePath, callerLineNumber) { _platform = platform; } - public override TestResult[] Execute(ITestMethod testMethod) + public override Task ExecuteAsync(ITestMethod testMethod) { if ((OsHelper.IsLinuxPlatform() && _platform != OSPlatform.Linux) || - (OsHelper.IsMacPlatform() && _platform != OSPlatform.OSX) || - (OsHelper.IsWindowsPlatform() && _platform != OSPlatform.Windows)) + (OsHelper.IsMacPlatform() && _platform != OSPlatform.OSX) || + (OsHelper.IsWindowsPlatform() && _platform != OSPlatform.Windows)) { - return new[] - { + TestResult[] tr = + [ new TestResult { Outcome = UnitTestOutcome.Inconclusive, TestFailureException = new AssertInconclusiveException("Skipped on platform") } - }; + ]; + return Task.FromResult(tr); } - return base.Execute(testMethod); + return base.ExecuteAsync(testMethod); } } @@ -76,18 +81,18 @@ public class DoNotRunOnPlatformAttribute : TestMethodAttribute { private readonly OSPlatform _platform; - protected DoNotRunOnPlatformAttribute(OSPlatform platform) + protected DoNotRunOnPlatformAttribute(OSPlatform platform, [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1) : base(callerFilePath, callerLineNumber) { _platform = platform; } - public override TestResult[] Execute(ITestMethod testMethod) + public override Task ExecuteAsync(ITestMethod testMethod) { if ((OsHelper.IsLinuxPlatform() && _platform == OSPlatform.Linux) || (OsHelper.IsMacPlatform() && _platform == OSPlatform.OSX) || (OsHelper.IsWindowsPlatform() && _platform == OSPlatform.Windows)) { - return new[] + var tr = new[] { new TestResult { @@ -95,21 +100,26 @@ public override TestResult[] Execute(ITestMethod testMethod) TestFailureException = new AssertInconclusiveException("Skipped on platform") } }; + return Task.FromResult(tr); } - return base.Execute(testMethod); + return base.ExecuteAsync(testMethod); } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)] public sealed class RunOnAzureDevOpsAttribute : TestMethodAttribute { - public override TestResult[] Execute(ITestMethod testMethod) + public RunOnAzureDevOpsAttribute([CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1) : base(callerFilePath, callerLineNumber) + { + } + + public override Task ExecuteAsync(ITestMethod testMethod) { // TF_BUILD is true for all Azure DevOps agents if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("TF_BUILD"))) { - return new[] + var tr = new[] { new TestResult { @@ -117,9 +127,11 @@ public override TestResult[] Execute(ITestMethod testMethod) TestFailureException = new AssertInconclusiveException("Skipped outside Azure DevOps") } }; + return Task.FromResult(tr); + } - return base.Execute(testMethod); + return base.ExecuteAsync(testMethod); } } } diff --git a/tests/Microsoft.Identity.Test.Common/Core/Mocks/MockHttpManager.cs b/tests/Microsoft.Identity.Test.Common/Core/Mocks/MockHttpManager.cs index 782e9b172c..47504ba71b 100644 --- a/tests/Microsoft.Identity.Test.Common/Core/Mocks/MockHttpManager.cs +++ b/tests/Microsoft.Identity.Test.Common/Core/Mocks/MockHttpManager.cs @@ -63,7 +63,7 @@ public void Dispose() { string remainingMocks = string.Join(" ", _httpMessageHandlerQueue.Select(m => GetExpectedUrlFromHandler(m))); - Assert.AreEqual(0, _httpMessageHandlerQueue.Count, + Assert.IsEmpty(_httpMessageHandlerQueue, "All mocks should have been consumed. Remaining mocks are for: " + remainingMocks); } } diff --git a/tests/Microsoft.Identity.Test.Common/Core/Mocks/MockHttpMessageHandler.cs b/tests/Microsoft.Identity.Test.Common/Core/Mocks/MockHttpMessageHandler.cs index 061d5b15ce..6c7d87f5be 100644 --- a/tests/Microsoft.Identity.Test.Common/Core/Mocks/MockHttpMessageHandler.cs +++ b/tests/Microsoft.Identity.Test.Common/Core/Mocks/MockHttpMessageHandler.cs @@ -61,7 +61,7 @@ protected override async Task SendAsync(HttpRequestMessage if (ExpectedMtlsBindingCertificate != null) { - Assert.AreEqual(1, base.ClientCertificates.Count); + Assert.HasCount(1, base.ClientCertificates); Assert.AreEqual(ExpectedMtlsBindingCertificate, base.ClientCertificates[0]); } @@ -90,7 +90,7 @@ private void ValidateExpectedQueryParams(Uri uri) { Assert.IsFalse(string.IsNullOrEmpty(uri.Query), $"Provided url ({uri.AbsoluteUri}) does not contain query parameters as expected."); Dictionary inputQp = CoreHelpers.ParseKeyValueList(uri.Query.Substring(1), '&', false, null); - Assert.AreEqual(ExpectedQueryParams.Count, inputQp.Count, "Different number of query params."); + Assert.HasCount(ExpectedQueryParams.Count, inputQp, "Different number of query params."); foreach (var key in ExpectedQueryParams.Keys) { Assert.IsTrue(inputQp.ContainsKey(key), $"Expected query parameter ({key}) not found in the url ({uri.AbsoluteUri})."); @@ -121,8 +121,8 @@ private void ValidateNotExpectedQueryParams(Uri uri) } // Fail if any "not expected" key/value pairs were found - Assert.IsTrue( - unexpectedKeysFound.Count == 0, + Assert.IsEmpty( + unexpectedKeysFound, $"Did not expect to find these query parameter keys/values: {string.Join(", ", unexpectedKeysFound)}" ); } @@ -169,7 +169,7 @@ private void ValidateNotExpectedPostData() } // Assert that no unexpected keys were found, reporting all violations at once - Assert.IsTrue(unexpectedKeysFound.Count == 0, $"Did not expect to find post data keys: {string.Join(", ", unexpectedKeysFound)}"); + Assert.IsEmpty(unexpectedKeysFound, $"Did not expect to find post data keys: {string.Join(", ", unexpectedKeysFound)}"); } } diff --git a/tests/Microsoft.Identity.Test.E2e/KeyGuardAttestationTests.cs b/tests/Microsoft.Identity.Test.E2e/KeyGuardAttestationTests.cs index 4542e9c210..d483bd74ba 100644 --- a/tests/Microsoft.Identity.Test.E2e/KeyGuardAttestationTests.cs +++ b/tests/Microsoft.Identity.Test.E2e/KeyGuardAttestationTests.cs @@ -144,7 +144,7 @@ public void Attest_KeyGuardKey_OnAzureArc_Succeeds() Assert.IsFalse(string.IsNullOrEmpty(result.Jwt), "Expected a non-empty attestation JWT."); var parts = result.Jwt.Split('.'); - Assert.AreEqual(3, parts.Length, "Expected a JWT (3 parts)."); + Assert.HasCount(3, parts, "Expected a JWT (3 parts)."); } catch (CryptographicException ex) { @@ -203,7 +203,7 @@ public async Task Attest_KeyGuardKey_OnAzureArc_Async_Succeeds() Assert.IsFalse(string.IsNullOrEmpty(result.Jwt), "Expected a non-empty attestation JWT from async path."); var parts = result.Jwt.Split('.'); - Assert.AreEqual(3, parts.Length, "Expected a JWT (3 parts) from async path."); + Assert.HasCount(3, parts, "Expected a JWT (3 parts) from async path."); } catch (CryptographicException ex) { diff --git a/tests/Microsoft.Identity.Test.E2e/ManagedIdentityImdsTests.cs b/tests/Microsoft.Identity.Test.E2e/ManagedIdentityImdsTests.cs index d0b149c232..1dc7b7b66c 100644 --- a/tests/Microsoft.Identity.Test.E2e/ManagedIdentityImdsTests.cs +++ b/tests/Microsoft.Identity.Test.E2e/ManagedIdentityImdsTests.cs @@ -37,7 +37,7 @@ private static IManagedIdentityApplication BuildMi( [RunOnAzureDevOps] [TestCategory("MI_E2E_Imds")] - [DataTestMethod] + [TestMethod] [DataRow(null /*SAMI*/, null, DisplayName = "AcquireToken_OnImds_Succeeds-SAMI")] [DataRow("8ef2ae5a-f349-4d36-bc0e-a567f2cc50f7", "clientid", DisplayName = "AcquireToken_OnImds_Succeeds-UAMI-ClientId")] [DataRow("/subscriptions/6f52c299-a200-4fe1-8822-a3b61cf1f931/resourcegroups/DevOpsHostedAgents/providers/Microsoft.ManagedIdentity/userAssignedIdentities/ID4SMSIHostedAgent_UAMI", @@ -67,7 +67,7 @@ public async Task AcquireToken_OnImds_Succeeds(string id, string idType) [RunOnAzureDevOps] [TestCategory("MI_E2E_Imds")] - [DataTestMethod] + [TestMethod] [DataRow(null /*SAMI*/, null, DisplayName = "AcquireToken_OnImds_Fails_WithMtlsProofOfPossession-SAMI")] [DataRow("8ef2ae5a-f349-4d36-bc0e-a567f2cc50f7", "clientid", DisplayName = "AcquireToken_OnImds_Fails_WithMtlsProofOfPossession-UAMI-ClientId")] [DataRow("/subscriptions/6f52c299-a200-4fe1-8822-a3b61cf1f931/resourcegroups/DevOpsHostedAgents/providers/Microsoft.ManagedIdentity/userAssignedIdentities/ID4SMSIHostedAgent_UAMI", @@ -77,7 +77,7 @@ public async Task AcquireToken_OnImds_Fails_WithMtlsProofOfPossession(string id, { var mi = BuildMi(id, idType); - var ex = await Assert.ThrowsExceptionAsync(async () => + var ex = await Assert.ThrowsAsync(async () => await mi.AcquireTokenForManagedIdentity(ArmScope) .WithMtlsProofOfPossession() .ExecuteAsync().ConfigureAwait(false) diff --git a/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/Agentic.cs b/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/Agentic.cs index 2c2fd268fa..3e8d7b4946 100644 --- a/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/Agentic.cs +++ b/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/Agentic.cs @@ -87,7 +87,7 @@ private static async Task AgentUserIdentityGetsTokenForGraphAsync() IAccount account = await cca.GetAccountAsync(result.Account.HomeAccountId.Identifier).ConfigureAwait(false); var result2 = await cca.AcquireTokenSilent([Scope], account).ExecuteAsync().ConfigureAwait(false); - Assert.IsTrue(result2.AuthenticationResultMetadata.TokenSource == TokenSource.Cache, "Token should be from cache"); + Assert.AreEqual(TokenSource.Cache, result2.AuthenticationResultMetadata.TokenSource, "Token should be from cache"); } private static async Task GetAppCredentialAsync(string fmiPath) diff --git a/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/ClientCredentialsTests.NetFwk.cs b/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/ClientCredentialsTests.NetFwk.cs index 91f01831fd..4d010cc005 100644 --- a/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/ClientCredentialsTests.NetFwk.cs +++ b/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/ClientCredentialsTests.NetFwk.cs @@ -53,7 +53,7 @@ public void TestInitialize() // regression test based on SAL introducing a new SKU value and making ESTS not issue the refresh_in value // This needs to run on .NET and .NET FWK to protect against MSAL SKU value changes - [DataTestMethod] + [TestMethod] [DataRow(true)] [DataRow(false)] public async Task RefreshOnIsEnabled(bool useRegional) @@ -87,7 +87,7 @@ public async Task RefreshOnIsEnabled(bool useRegional) result.AuthenticationResultMetadata.RegionDetails.RegionOutcome); } - [DataTestMethod] + [TestMethod] [DataRow(Cloud.Public, TargetFrameworks.NetFx | TargetFrameworks.NetCore)] #if !IGNORE_FEDERATED [DataRow(Cloud.Adfs, TargetFrameworks.NetFx | TargetFrameworks.NetCore)] @@ -100,7 +100,7 @@ public async Task WithCertificate_TestAsync(Cloud cloud, TargetFrameworks runOn, await RunClientCredsAsync(cloud, CredentialType.Cert, useAppIdUri).ConfigureAwait(false); } - [DataTestMethod] + [TestMethod] [DataRow(Cloud.Public, TargetFrameworks.NetCore)] #if !IGNORE_FEDERATED [DataRow(Cloud.Adfs, TargetFrameworks.NetFx)] @@ -112,7 +112,7 @@ public async Task WithSecret_TestAsync(Cloud cloud, TargetFrameworks runOn) await RunClientCredsAsync(cloud, CredentialType.Secret).ConfigureAwait(false); } - [DataTestMethod] + [TestMethod] [DataRow(Cloud.Public, TargetFrameworks.NetCore)] #if !IGNORE_FEDERATED [DataRow(Cloud.Adfs, TargetFrameworks.NetCore)] @@ -124,7 +124,7 @@ public async Task WithClientAssertion_Manual_TestAsync(Cloud cloud, TargetFramew await RunClientCredsAsync(cloud, CredentialType.ClientAssertion_Manual).ConfigureAwait(false); } - [DataTestMethod] + [TestMethod] [DataRow(Cloud.Public, TargetFrameworks.NetFx)] #if !IGNORE_FEDERATED [DataRow(Cloud.Adfs, TargetFrameworks.NetFx)] @@ -136,7 +136,7 @@ public async Task WithClientAssertion_Wilson_TestAsync(Cloud cloud, TargetFramew await RunClientCredsAsync(cloud, CredentialType.ClientAssertion_Wilson).ConfigureAwait(false); } - [DataTestMethod] + [TestMethod] [DataRow(Cloud.Public, TargetFrameworks.NetCore)] // [DataRow(Cloud.Arlington)] - cert not setup public async Task WithClientClaims_ExtraClaims_TestAsync(Cloud cloud, TargetFrameworks runOn) @@ -145,7 +145,7 @@ public async Task WithClientClaims_ExtraClaims_TestAsync(Cloud cloud, TargetFram await RunClientCredsAsync(cloud, CredentialType.ClientClaims_ExtraClaims).ConfigureAwait(false); } - [DataTestMethod] + [TestMethod] [DataRow(Cloud.Public, TargetFrameworks.NetFx)] #if !IGNORE_FEDERATED [DataRow(Cloud.Adfs, TargetFrameworks.NetCore)] @@ -157,7 +157,7 @@ public async Task WithClientClaims_OverrideClaims_TestAsync(Cloud cloud, TargetF await RunClientCredsAsync(cloud, CredentialType.ClientClaims_MergeClaims).ConfigureAwait(false); } - [DataTestMethod] + [TestMethod] [DataRow(Cloud.Public, TargetFrameworks.NetCore)] // [DataRow(Cloud.Arlington)] - cert not setup public async Task WithClientClaims_SendX5C_ExtraClaims_TestAsync(Cloud cloud, TargetFrameworks runOn) @@ -166,7 +166,7 @@ public async Task WithClientClaims_SendX5C_ExtraClaims_TestAsync(Cloud cloud, Ta await RunClientCredsAsync(cloud, CredentialType.ClientClaims_ExtraClaims, sendX5C: true).ConfigureAwait(false); } - [DataTestMethod] + [TestMethod] [DataRow(Cloud.Public, TargetFrameworks.NetFx)] #if !IGNORE_FEDERATED [DataRow(Cloud.Adfs, TargetFrameworks.NetCore)] @@ -178,7 +178,7 @@ public async Task WithClientClaims_SendX5C_OverrideClaims_TestAsync(Cloud cloud, await RunClientCredsAsync(cloud, CredentialType.ClientClaims_MergeClaims, sendX5C: true).ConfigureAwait(false); } - [DataTestMethod] + [TestMethod] [DataRow(Cloud.Public, TargetFrameworks.NetCore)] public async Task WithOnBeforeTokenRequest_TestAsync(Cloud cloud, TargetFrameworks runOn) { @@ -314,8 +314,8 @@ private async Task RunClientCredsAsync(Cloud cloud, CredentialType credentialTyp CollectionAssert.AreEquivalent(settings.AppScopes.ToArray(), appCacheRecorder.LastAfterAccessNotificationArgs.RequestScopes.ToArray()); Assert.AreEqual(settings.TenantId, appCacheRecorder.LastBeforeAccessNotificationArgs.RequestTenantId ?? ""); Assert.AreEqual(settings.TenantId, appCacheRecorder.LastAfterAccessNotificationArgs.RequestTenantId ?? ""); - Assert.IsTrue(authResult.AuthenticationResultMetadata.DurationTotalInMs > 0); - Assert.IsTrue(authResult.AuthenticationResultMetadata.DurationInHttpInMs > 0); + Assert.IsGreaterThan(0, authResult.AuthenticationResultMetadata.DurationTotalInMs); + Assert.IsGreaterThan(0, authResult.AuthenticationResultMetadata.DurationInHttpInMs); Assert.AreEqual( GetExpectedCacheKey(settings.ClientId, settings.TenantId), appCacheRecorder.LastAfterAccessNotificationArgs.SuggestedCacheKey); @@ -330,7 +330,7 @@ private async Task RunClientCredsAsync(Cloud cloud, CredentialType credentialTyp .ConfigureAwait(false); MsalAssert.AssertAuthResult(authResult); - Assert.IsTrue(authResult.AuthenticationResultMetadata.DurationInHttpInMs == 0); + Assert.AreEqual(0, authResult.AuthenticationResultMetadata.DurationInHttpInMs); appCacheRecorder.AssertAccessCounts(2, 1); Assert.AreEqual(TokenSource.Cache, authResult.AuthenticationResultMetadata.TokenSource); diff --git a/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/ClientCredentialsTests.WithRegion.cs b/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/ClientCredentialsTests.WithRegion.cs index ea4b57d6ac..7e5ee34cdf 100644 --- a/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/ClientCredentialsTests.WithRegion.cs +++ b/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/ClientCredentialsTests.WithRegion.cs @@ -57,7 +57,7 @@ public void TestCleanup() Environment.SetEnvironmentVariable(TestConstants.RegionName, null); } - [DataTestMethod] + [TestMethod] [DataRow(true)] [DataRow(false)] public async Task AcquireTokenToRegionalEndpointAsync(bool instanceDiscoveryEnabled) @@ -88,7 +88,7 @@ public async Task InvalidRegion_GoesToInvalidAuthority_Async() Environment.SetEnvironmentVariable(TestConstants.RegionName, TestConstants.Region); - var ex = await Assert.ThrowsExceptionAsync( + var ex = await Assert.ThrowsAsync( async () => await GetAuthenticationResultAsync(settings.AppScopes).ConfigureAwait(false)).ConfigureAwait(false); Assert.IsTrue(ex is HttpRequestException); diff --git a/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/FmiIntegrationTests.cs b/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/FmiIntegrationTests.cs index 9da2a2852d..7549760f6e 100644 --- a/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/FmiIntegrationTests.cs +++ b/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/FmiIntegrationTests.cs @@ -286,7 +286,7 @@ private void AssertResults( audience = audience.Substring(0, audience.Length - "/.default".Length); } Assert.AreEqual(expectedAudience, audience); - Assert.IsTrue(subject.Contains(expectedFmiPath)); + Assert.Contains(expectedFmiPath, subject); Assert.AreEqual(expectedInternalCacheKey, token.CacheKey); } } diff --git a/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/InstanceDiscoveryIntegrationTests.cs b/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/InstanceDiscoveryIntegrationTests.cs index cc050eadbd..f2e1c90d16 100644 --- a/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/InstanceDiscoveryIntegrationTests.cs +++ b/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/InstanceDiscoveryIntegrationTests.cs @@ -90,7 +90,7 @@ public async Task FailedAuthorityValidationTestAsync() .ConfigureAwait(false); #pragma warning restore CS0618 - Assert.IsTrue(exception.Message.Contains("AADSTS50049")); + Assert.Contains("AADSTS50049", exception.Message); Assert.AreEqual("invalid_instance", exception.ErrorCode); } diff --git a/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/LongRunningOnBehalfOfTests.cs b/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/LongRunningOnBehalfOfTests.cs index 358cef30ca..ea81ef5612 100644 --- a/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/LongRunningOnBehalfOfTests.cs +++ b/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/LongRunningOnBehalfOfTests.cs @@ -75,15 +75,15 @@ public async Task LongRunningAndNormalObo_WithDifferentKeys_TestAsync() // Cache has 1 partition (user-provided key) with 1 token Assert.AreEqual(TokenSource.IdentityProvider, result.AuthenticationResultMetadata.TokenSource); - Assert.AreEqual(1, cca.UserTokenCacheInternal.Accessor.GetAllAccessTokens().Count); - Assert.AreEqual(1, cca.UserTokenCacheInternal.Accessor.GetAllRefreshTokens().Count); + Assert.HasCount(1, cca.UserTokenCacheInternal.Accessor.GetAllAccessTokens()); + Assert.HasCount(1, cca.UserTokenCacheInternal.Accessor.GetAllRefreshTokens()); result = await cca.AcquireTokenOnBehalfOf(s_scopes, userAssertion).ExecuteAsync().ConfigureAwait(false); // Cache has 2 partitions (user-provided key, assertion) with 1 token each Assert.AreEqual(TokenSource.IdentityProvider, result.AuthenticationResultMetadata.TokenSource); - Assert.AreEqual(2, cca.UserTokenCacheInternal.Accessor.GetAllAccessTokens().Count); - Assert.AreEqual(1, cca.UserTokenCacheInternal.Accessor.GetAllRefreshTokens().Count); + Assert.HasCount(2, cca.UserTokenCacheInternal.Accessor.GetAllAccessTokens()); + Assert.HasCount(1, cca.UserTokenCacheInternal.Accessor.GetAllRefreshTokens()); // Returns long-running token result = await cca.AcquireTokenInLongRunningProcess(s_scopes, oboCacheKey).ExecuteAsync().ConfigureAwait(false); @@ -129,8 +129,8 @@ public async Task LongRunningThenNormalObo_WithTheSameKey_TestAsync() Assert.AreEqual(userAssertion.AssertionHash, oboCacheKey); Assert.AreEqual(TokenSource.IdentityProvider, result.AuthenticationResultMetadata.TokenSource); - Assert.AreEqual(1, cca.UserTokenCacheInternal.Accessor.GetAllAccessTokens().Count); - Assert.AreEqual(1, cca.UserTokenCacheInternal.Accessor.GetAllRefreshTokens().Count); + Assert.HasCount(1, cca.UserTokenCacheInternal.Accessor.GetAllAccessTokens()); + Assert.HasCount(1, cca.UserTokenCacheInternal.Accessor.GetAllRefreshTokens()); // AcquireLR - AT from cache result = await cca.AcquireTokenInLongRunningProcess(s_scopes, oboCacheKey).ExecuteAsync().ConfigureAwait(false); @@ -150,8 +150,8 @@ public async Task LongRunningThenNormalObo_WithTheSameKey_TestAsync() .ExecuteAsync().ConfigureAwait(false); Assert.AreEqual(TokenSource.IdentityProvider, result.AuthenticationResultMetadata.TokenSource); - Assert.AreEqual(1, cca.UserTokenCacheInternal.Accessor.GetAllAccessTokens().Count); - Assert.AreEqual(1, cca.UserTokenCacheInternal.Accessor.GetAllRefreshTokens().Count); + Assert.HasCount(1, cca.UserTokenCacheInternal.Accessor.GetAllAccessTokens()); + Assert.HasCount(1, cca.UserTokenCacheInternal.Accessor.GetAllRefreshTokens()); // Expire AT TokenCacheHelper.ExpireAllAccessTokens(cca.UserTokenCacheInternal); @@ -160,8 +160,8 @@ public async Task LongRunningThenNormalObo_WithTheSameKey_TestAsync() result = await cca.AcquireTokenInLongRunningProcess(s_scopes, oboCacheKey).ExecuteAsync().ConfigureAwait(false); Assert.AreEqual(TokenSource.IdentityProvider, result.AuthenticationResultMetadata.TokenSource); - Assert.AreEqual(1, cca.UserTokenCacheInternal.Accessor.GetAllAccessTokens().Count); - Assert.AreEqual(1, cca.UserTokenCacheInternal.Accessor.GetAllRefreshTokens().Count); + Assert.HasCount(1, cca.UserTokenCacheInternal.Accessor.GetAllAccessTokens()); + Assert.HasCount(1, cca.UserTokenCacheInternal.Accessor.GetAllRefreshTokens()); // Expire AT TokenCacheHelper.ExpireAllAccessTokens(cca.UserTokenCacheInternal); @@ -170,8 +170,8 @@ public async Task LongRunningThenNormalObo_WithTheSameKey_TestAsync() result = await cca.AcquireTokenOnBehalfOf(s_scopes, userAssertion).ExecuteAsync().ConfigureAwait(false); Assert.AreEqual(TokenSource.IdentityProvider, result.AuthenticationResultMetadata.TokenSource); - Assert.AreEqual(1, cca.UserTokenCacheInternal.Accessor.GetAllAccessTokens().Count); - Assert.AreEqual(1, cca.UserTokenCacheInternal.Accessor.GetAllRefreshTokens().Count); + Assert.HasCount(1, cca.UserTokenCacheInternal.Accessor.GetAllAccessTokens()); + Assert.HasCount(1, cca.UserTokenCacheInternal.Accessor.GetAllRefreshTokens()); } [TestMethod] @@ -273,8 +273,8 @@ public async Task NormalOboThenLongRunningAcquire_WithTheSameKey_TestAsync() var result = await cca.AcquireTokenOnBehalfOf(s_scopes, userAssertion).ExecuteAsync().ConfigureAwait(false); Assert.AreEqual(TokenSource.IdentityProvider, result.AuthenticationResultMetadata.TokenSource); - Assert.AreEqual(1, cca.UserTokenCacheInternal.Accessor.GetAllAccessTokens().Count); - Assert.AreEqual(0, cca.UserTokenCacheInternal.Accessor.GetAllRefreshTokens().Count); + Assert.HasCount(1, cca.UserTokenCacheInternal.Accessor.GetAllAccessTokens()); + Assert.IsEmpty(cca.UserTokenCacheInternal.Accessor.GetAllRefreshTokens()); // AcquireLR - AT from cache result = await cca.AcquireTokenInLongRunningProcess(s_scopes, oboCacheKey).ExecuteAsync().ConfigureAwait(false); @@ -300,8 +300,8 @@ public async Task NormalOboThenLongRunningAcquire_WithTheSameKey_TestAsync() .ExecuteAsync().ConfigureAwait(false); Assert.AreEqual(TokenSource.IdentityProvider, result.AuthenticationResultMetadata.TokenSource); - Assert.AreEqual(1, cca.UserTokenCacheInternal.Accessor.GetAllAccessTokens().Count); - Assert.AreEqual(1, cca.UserTokenCacheInternal.Accessor.GetAllRefreshTokens().Count); + Assert.HasCount(1, cca.UserTokenCacheInternal.Accessor.GetAllAccessTokens()); + Assert.HasCount(1, cca.UserTokenCacheInternal.Accessor.GetAllRefreshTokens()); // Expire AT TokenCacheHelper.ExpireAllAccessTokens(cca.UserTokenCacheInternal); @@ -310,8 +310,8 @@ public async Task NormalOboThenLongRunningAcquire_WithTheSameKey_TestAsync() result = await cca.AcquireTokenInLongRunningProcess(s_scopes, oboCacheKey).ExecuteAsync().ConfigureAwait(false); Assert.AreEqual(TokenSource.IdentityProvider, result.AuthenticationResultMetadata.TokenSource); - Assert.AreEqual(1, cca.UserTokenCacheInternal.Accessor.GetAllAccessTokens().Count); - Assert.AreEqual(1, cca.UserTokenCacheInternal.Accessor.GetAllRefreshTokens().Count); + Assert.HasCount(1, cca.UserTokenCacheInternal.Accessor.GetAllAccessTokens()); + Assert.HasCount(1, cca.UserTokenCacheInternal.Accessor.GetAllRefreshTokens()); } /// @@ -345,8 +345,8 @@ public async Task NormalOboThenLongRunningInitiate_WithTheSameKey_TestAsync() var result = await cca.AcquireTokenOnBehalfOf(s_scopes, userAssertion).ExecuteAsync().ConfigureAwait(false); Assert.AreEqual(TokenSource.IdentityProvider, result.AuthenticationResultMetadata.TokenSource); - Assert.AreEqual(1, cca.UserTokenCacheInternal.Accessor.GetAllAccessTokens().Count); - Assert.AreEqual(0, cca.UserTokenCacheInternal.Accessor.GetAllRefreshTokens().Count); + Assert.HasCount(1, cca.UserTokenCacheInternal.Accessor.GetAllAccessTokens()); + Assert.IsEmpty(cca.UserTokenCacheInternal.Accessor.GetAllRefreshTokens()); // InitiateLR - AT from IdentityProvider result = await cca.InitiateLongRunningProcessInWebApi(s_scopes, userAuthResult.AccessToken, ref oboCacheKey) @@ -362,8 +362,8 @@ public async Task NormalOboThenLongRunningInitiate_WithTheSameKey_TestAsync() .ExecuteAsync().ConfigureAwait(false); Assert.AreEqual(TokenSource.IdentityProvider, result.AuthenticationResultMetadata.TokenSource); - Assert.AreEqual(1, cca.UserTokenCacheInternal.Accessor.GetAllAccessTokens().Count); - Assert.AreEqual(1, cca.UserTokenCacheInternal.Accessor.GetAllRefreshTokens().Count); + Assert.HasCount(1, cca.UserTokenCacheInternal.Accessor.GetAllAccessTokens()); + Assert.HasCount(1, cca.UserTokenCacheInternal.Accessor.GetAllRefreshTokens()); // Expire AT TokenCacheHelper.ExpireAllAccessTokens(cca.UserTokenCacheInternal); @@ -372,8 +372,8 @@ public async Task NormalOboThenLongRunningInitiate_WithTheSameKey_TestAsync() result = await cca.AcquireTokenInLongRunningProcess(s_scopes, oboCacheKey).ExecuteAsync().ConfigureAwait(false); Assert.AreEqual(TokenSource.IdentityProvider, result.AuthenticationResultMetadata.TokenSource); - Assert.AreEqual(1, cca.UserTokenCacheInternal.Accessor.GetAllAccessTokens().Count); - Assert.AreEqual(1, cca.UserTokenCacheInternal.Accessor.GetAllRefreshTokens().Count); + Assert.HasCount(1, cca.UserTokenCacheInternal.Accessor.GetAllAccessTokens()); + Assert.HasCount(1, cca.UserTokenCacheInternal.Accessor.GetAllRefreshTokens()); } [TestMethod] @@ -404,8 +404,8 @@ public async Task WithDifferentScopes_TestAsync() // Cache has 1 partition (user-provided key) with 1 token Assert.AreEqual(TokenSource.IdentityProvider, result.AuthenticationResultMetadata.TokenSource); - Assert.AreEqual(1, cca.UserTokenCacheInternal.Accessor.GetAllAccessTokens().Count); - Assert.AreEqual(1, cca.UserTokenCacheInternal.Accessor.GetAllRefreshTokens().Count); + Assert.HasCount(1, cca.UserTokenCacheInternal.Accessor.GetAllAccessTokens()); + Assert.HasCount(1, cca.UserTokenCacheInternal.Accessor.GetAllRefreshTokens()); // No matching AT, uses RT to retrieve new AT. result = await cca.AcquireTokenInLongRunningProcess(scopes2, oboCacheKey).ExecuteAsync().ConfigureAwait(false); diff --git a/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/ManagedIdentityTests.NetFwk.cs b/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/ManagedIdentityTests.NetFwk.cs index 509bd94329..e01683d62e 100644 --- a/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/ManagedIdentityTests.NetFwk.cs +++ b/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/ManagedIdentityTests.NetFwk.cs @@ -59,7 +59,7 @@ public class ManagedIdentityTests //non existent Resource ID of the User Assigned Identity private const string Non_Existent_UamiResourceId = "/subscriptions/userAssignedIdentities/NO_ID"; - [DataTestMethod] + [TestMethod] [DataRow(MsiAzureResource.WebApp, "", DisplayName = "System_Identity_Web_App")] [DataRow(MsiAzureResource.WebApp, UserAssignedClientID, UserAssignedIdentityId.ClientId, DisplayName = "ClientId_Web_App")] [DataRow(MsiAzureResource.WebApp, UamiResourceId, UserAssignedIdentityId.ResourceId, DisplayName = "ResourceID_Web_App")] @@ -273,7 +273,7 @@ public async Task AcquireMsiToken_ExchangeForEstsToken_Successfully() } } - [DataTestMethod] + [TestMethod] [DataRow(MsiAzureResource.WebApp, SomeRandomGuid, UserAssignedIdentityId.ClientId, DisplayName = "ClientId_Web_App")] [DataRow(MsiAzureResource.WebApp, SomeRandomGuid, UserAssignedIdentityId.ObjectId, DisplayName = "ObjectId_Web_App")] [DataRow(MsiAzureResource.WebApp, Non_Existent_UamiResourceId, UserAssignedIdentityId.ResourceId, DisplayName = "ResourceID_Web_App")] @@ -311,12 +311,12 @@ await mia ManagedIdentitySource.Imds : ManagedIdentitySource.AppService; //Assert - Assert.IsTrue(ex.ErrorCode == MsalError.ManagedIdentityRequestFailed); + Assert.AreEqual(MsalError.ManagedIdentityRequestFailed, ex.ErrorCode); Assert.AreEqual(expectedResource.ToString(), ex.AdditionalExceptionData[MsalException.ManagedIdentitySource]); } } - [DataTestMethod] + [TestMethod] [DataRow(MsiAzureResource.WebApp, "", UserAssignedIdentityId.None, DisplayName = "System_Identity_Web_App")] [DataRow(MsiAzureResource.WebApp, UserAssignedClientID, UserAssignedIdentityId.ClientId, DisplayName = "ClientId_Web_App")] [DataRow(MsiAzureResource.WebApp, UamiResourceId, UserAssignedIdentityId.ResourceId, DisplayName = "ResourceId_Web_App")] @@ -349,12 +349,12 @@ await mia }).ConfigureAwait(false); //Assert - Assert.IsTrue(ex.ErrorCode == MsalError.ManagedIdentityRequestFailed); + Assert.AreEqual(MsalError.ManagedIdentityRequestFailed, ex.ErrorCode); Assert.AreEqual(ManagedIdentitySource.AppService.ToString(), ex.AdditionalExceptionData[MsalException.ManagedIdentitySource]); } } - [DataTestMethod] + [TestMethod] [DataRow(MsiAzureResource.WebApp, "", DisplayName = "System_Identity_Web_App")] [DataRow(MsiAzureResource.WebApp, UserAssignedClientID, UserAssignedIdentityId.ClientId, DisplayName = "ClientId_Web_App")] [DataRow(MsiAzureResource.WebApp, UamiResourceId, UserAssignedIdentityId.ResourceId, DisplayName = "ResourceID_Web_App")] diff --git a/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/MsalCacheStorageIntegrationTests.cs b/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/MsalCacheStorageIntegrationTests.cs index 3f2f7b9b8c..2f150f76fc 100644 --- a/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/MsalCacheStorageIntegrationTests.cs +++ b/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/MsalCacheStorageIntegrationTests.cs @@ -164,7 +164,7 @@ public void MsalNewStoreNoFile() public void MsalWriteEmptyData() { var store = Storage.Create(s_storageCreationProperties, logger: _logger); - Assert.ThrowsException(() => store.WriteData(null)); + Assert.Throws(() => store.WriteData(null)); store.WriteData(new byte[0]); @@ -175,7 +175,7 @@ public void MsalWriteEmptyData() public void MsalWriteGoodData() { var store = Storage.Create(s_storageCreationProperties, logger: _logger); - Assert.ThrowsException(() => store.WriteData(null)); + Assert.Throws(() => store.WriteData(null)); byte[] data = { 2, 2, 3 }; byte[] data2 = { 2, 2, 3, 4, 4 }; @@ -233,7 +233,7 @@ public static void AssertChmod600(string filePath) var acl = fi.GetAccessControl(); var accessRules = acl.GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier)); - Assert.AreEqual(1, accessRules.Count); + Assert.HasCount(1, accessRules); var rule = accessRules.Cast().Single(); @@ -247,7 +247,7 @@ public static void AssertChmod600(string filePath) { // e.g. -rw------ 1 user1 user1 1280 Mar 23 08:39 /home/user1/g/Program.cs var output = ExecuteAndCaptureOutput($"ls -l {filePath}"); - Assert.IsTrue(output.StartsWith("-rw------")); // 600 + Assert.StartsWith("-rw------", output); // 600 } } diff --git a/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/OnBehalfOfServicePrincipalTests.cs b/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/OnBehalfOfServicePrincipalTests.cs index 0885f64af5..d636bd4bf8 100644 --- a/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/OnBehalfOfServicePrincipalTests.cs +++ b/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/OnBehalfOfServicePrincipalTests.cs @@ -143,10 +143,10 @@ public async Task LongRunningObo_TestAsync() Assert.IsNull( userCacheRecorder.LastAfterAccessNotificationArgs.SuggestedCacheExpiry, "The cache expiry is not set because there is an RT in the cache"); - Assert.AreEqual(1, middletierServiceApp.UserTokenCacheInternal.Accessor.GetAllAccessTokens().Count); - Assert.AreEqual(1, middletierServiceApp.UserTokenCacheInternal.Accessor.GetAllRefreshTokens().Count); - Assert.AreEqual(1, middletierServiceApp.UserTokenCacheInternal.Accessor.GetAllIdTokens().Count); - Assert.AreEqual(1, middletierServiceApp.UserTokenCacheInternal.Accessor.GetAllAccounts().Count); + Assert.HasCount(1, middletierServiceApp.UserTokenCacheInternal.Accessor.GetAllAccessTokens()); + Assert.HasCount(1, middletierServiceApp.UserTokenCacheInternal.Accessor.GetAllRefreshTokens()); + Assert.HasCount(1, middletierServiceApp.UserTokenCacheInternal.Accessor.GetAllIdTokens()); + Assert.HasCount(1, middletierServiceApp.UserTokenCacheInternal.Accessor.GetAllAccounts()); Trace.WriteLine("3. Later, mid-tier needs the token again, and one is in the cache"); authenticationResult = await middletierServiceApp @@ -172,10 +172,10 @@ public async Task LongRunningObo_TestAsync() Assert.IsNull( userCacheRecorder.LastAfterAccessNotificationArgs.SuggestedCacheExpiry, "The cache expiry is not set because there is an RT in the cache"); - Assert.AreEqual(1, middletierServiceApp.UserTokenCacheInternal.Accessor.GetAllAccessTokens().Count); - Assert.AreEqual(1, middletierServiceApp.UserTokenCacheInternal.Accessor.GetAllRefreshTokens().Count); - Assert.AreEqual(1, middletierServiceApp.UserTokenCacheInternal.Accessor.GetAllIdTokens().Count); - Assert.AreEqual(1, middletierServiceApp.UserTokenCacheInternal.Accessor.GetAllAccounts().Count); + Assert.HasCount(1, middletierServiceApp.UserTokenCacheInternal.Accessor.GetAllAccessTokens()); + Assert.HasCount(1, middletierServiceApp.UserTokenCacheInternal.Accessor.GetAllRefreshTokens()); + Assert.HasCount(1, middletierServiceApp.UserTokenCacheInternal.Accessor.GetAllIdTokens()); + Assert.HasCount(1, middletierServiceApp.UserTokenCacheInternal.Accessor.GetAllAccounts()); Trace.WriteLine("5. Subsequent acquire token calls should return cached token."); authenticationResult = await middletierServiceApp diff --git a/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/OnBehalfOfTests.cs b/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/OnBehalfOfTests.cs index ffa1e80daf..27d9c92a6c 100644 --- a/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/OnBehalfOfTests.cs +++ b/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/OnBehalfOfTests.cs @@ -51,7 +51,7 @@ public void TestInitialize() /// Tests the behavior when calling OBO and silent in different orders with multiple users. /// OBO calls should return tokens for correct users, silent calls should throw. /// - [DataTestMethod] + [TestMethod] [DataRow(false, false)] [DataRow(true, false)] [DataRow(true, true)] @@ -132,7 +132,7 @@ await AssertException.TaskThrowsAsync(() => Assert.AreEqual(CacheRefreshReason.NotApplicable, authResult.AuthenticationResultMetadata.CacheRefreshReason); oboTokens.Add(authResult.AccessToken); - Assert.AreEqual(2, oboTokens.Count); + Assert.HasCount(2, oboTokens); // Silent calls should throw await AssertException.TaskThrowsAsync(() => @@ -204,7 +204,7 @@ public async Task OboAndClientCredentials_WithRegional_ReturnsCorrectTokens_Test .ConfigureAwait(false); Assert.AreEqual(TokenSource.IdentityProvider, oboResult.AuthenticationResultMetadata.TokenSource); - Assert.IsFalse(oboResult.AuthenticationResultMetadata.TokenEndpoint.Contains(TestConstants.Region)); + Assert.DoesNotContain(TestConstants.Region, oboResult.AuthenticationResultMetadata.TokenEndpoint); // Client uses regional - IdP var clientResult = await cca.AcquireTokenForClient(new string[] { "https://graph.microsoft.com/.default" }) @@ -212,7 +212,7 @@ public async Task OboAndClientCredentials_WithRegional_ReturnsCorrectTokens_Test .ConfigureAwait(false); Assert.AreEqual(TokenSource.IdentityProvider, clientResult.AuthenticationResultMetadata.TokenSource); - Assert.IsTrue(clientResult.AuthenticationResultMetadata.TokenEndpoint.Contains(TestConstants.Region)); + Assert.Contains(TestConstants.Region, clientResult.AuthenticationResultMetadata.TokenEndpoint); // OBO from cache oboResult = await cca.AcquireTokenOnBehalfOf(s_scopes, new UserAssertion(userResult.AccessToken)) @@ -413,7 +413,7 @@ public async Task WithCache_TestAsync() void AssertLastHttpContent(string content) { - Assert.IsTrue(HttpSnifferClientFactory.LastHttpContentData.Contains(content)); + Assert.Contains(content, HttpSnifferClientFactory.LastHttpContentData); HttpSnifferClientFactory.LastHttpContentData = string.Empty; } } diff --git a/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/PoPTests.NetFwk.cs b/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/PoPTests.NetFwk.cs index c3f6b1b61c..54cddd23d3 100644 --- a/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/PoPTests.NetFwk.cs +++ b/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/PoPTests.NetFwk.cs @@ -136,9 +136,9 @@ private async Task BearerAndPoP_CanCoexist_Async() .ExecuteAsync() .ConfigureAwait(false); Assert.AreEqual("Bearer", result.TokenType); - Assert.AreEqual( + Assert.HasCount( 2, - (cca as ConfidentialClientApplication).AppTokenCacheInternal.Accessor.GetAllAccessTokens().Count); + (cca as ConfidentialClientApplication).AppTokenCacheInternal.Accessor.GetAllAccessTokens()); } private async Task MultipleKeys_Async() @@ -639,7 +639,7 @@ public async Task InMemoryCryptoProvider_WithGraph() var response = await httpClient.GetAsync("https://graph.microsoft.com/v1.0/users").ConfigureAwait(false); // Check for WWW-Authenticate header - Assert.IsTrue(response.StatusCode == HttpStatusCode.Unauthorized, "The response should be Unauthorized (401)"); + Assert.AreEqual(HttpStatusCode.Unauthorized, response.StatusCode, "The response should be Unauthorized (401)"); // Extract WWW-Authenticate header to get the nonce var authParams = await WwwAuthenticateParameters.CreateFromAuthenticationResponseAsync( diff --git a/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/ProactiveRefreshTests.cs b/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/ProactiveRefreshTests.cs index b6aac1db7d..d4ed3fcdd4 100644 --- a/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/ProactiveRefreshTests.cs +++ b/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/ProactiveRefreshTests.cs @@ -64,7 +64,7 @@ public async Task ProactiveRefreshTriggers_WithTelemetry_Test() Assert.IsNotNull(authResult.AccessToken); Assert.AreEqual(TokenSource.Cache, authResult.AuthenticationResultMetadata.TokenSource); Assert.AreEqual(CacheRefreshReason.NotApplicable, authResult.AuthenticationResultMetadata.CacheRefreshReason); - Assert.IsTrue(authResult.AuthenticationResultMetadata.DurationTotalInMs < 50); + Assert.IsLessThan(50, authResult.AuthenticationResultMetadata.DurationTotalInMs); Trace.WriteLine("Update the refresh token in the cache to trigger proactive refresh."); TestCommon.UpdateATWithRefreshOn(confidentialApp.AppTokenCacheInternal.Accessor); @@ -79,7 +79,7 @@ public async Task ProactiveRefreshTriggers_WithTelemetry_Test() Assert.IsNotNull(authResult.AccessToken); Assert.AreEqual(TokenSource.Cache, authResult.AuthenticationResultMetadata.TokenSource); Assert.AreEqual(CacheRefreshReason.ProactivelyRefreshed, authResult.AuthenticationResultMetadata.CacheRefreshReason); - Assert.IsTrue(authResult.AuthenticationResultMetadata.DurationTotalInMs < 50); + Assert.IsLessThan(50, authResult.AuthenticationResultMetadata.DurationTotalInMs); meterProvider.ForceFlush(); @@ -91,7 +91,7 @@ public async Task ProactiveRefreshTriggers_WithTelemetry_Test() private long ValidateSuccessMetrics(MeterProvider meterProvider, List exportedMetrics) { - Assert.AreEqual(5, exportedMetrics.Count); + Assert.HasCount(5, exportedMetrics); foreach (var metric in exportedMetrics) { diff --git a/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/RuntimeBrokerTests.cs b/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/RuntimeBrokerTests.cs index 52896c6ce1..8aa09f48cd 100644 --- a/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/RuntimeBrokerTests.cs +++ b/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/RuntimeBrokerTests.cs @@ -55,7 +55,7 @@ private string CreateJwk() return jwk; } - + // This test should fail locally but succeed in a CI build. [IgnoreOnOneBranch] [TestMethod] @@ -83,7 +83,7 @@ public async Task WamSilentAuthUserInteractionRequiredAsync() } catch (MsalUiRequiredException ex) { - Assert.IsTrue(!string.IsNullOrEmpty(ex.ErrorCode)); + Assert.IsFalse(string.IsNullOrEmpty(ex.ErrorCode)); } catch (Exception ex) { @@ -114,22 +114,22 @@ public async Task ExtractNonceWithAuthParserAndValidateShrAsync() Uri requestUri = new Uri("https://www.contoso.com/path1/path2?queryParam1=a&queryParam2=b"); - #pragma warning disable CS0618 // Type or member is obsolete +#pragma warning disable CS0618 // Type or member is obsolete var result = await pca .AcquireTokenByUsernamePassword( scopes, labResponse.User.Upn, labResponse.User.GetOrFetchPassword()) .WithProofOfPossession( - parsedHeaders.PopNonce, + parsedHeaders.PopNonce, HttpMethod.Get, requestUri) .ExecuteAsync().ConfigureAwait(false); - #pragma warning restore CS0618 +#pragma warning restore CS0618 MsalAssert.AssertAuthResult( - result, - TokenSource.Broker, + result, + TokenSource.Broker, labResponse.Lab.TenantId, scopes, true); @@ -139,7 +139,7 @@ public async Task ExtractNonceWithAuthParserAndValidateShrAsync() HttpMethod.Get, result); } - + [DoNotRunOnLinux] // Linux broker return different error code [IgnoreOnOneBranch] [TestMethod] @@ -156,7 +156,7 @@ public async Task WamInvalidROPC_ThrowsException_TestAsync() .WithBroker(_brokerOptions) .Build(); - #pragma warning disable CS0618 // Type or member is obsolete +#pragma warning disable CS0618 // Type or member is obsolete MsalServiceException ex = await AssertException.TaskThrowsAsync(() => pca.AcquireTokenByUsernamePassword( scopes, @@ -164,14 +164,14 @@ public async Task WamInvalidROPC_ThrowsException_TestAsync() "badPassword") .ExecuteAsync()) .ConfigureAwait(false); - #pragma warning restore CS0618 +#pragma warning restore CS0618 Assert.AreEqual("0x2142008A", ex.AdditionalExceptionData[MsalException.BrokerErrorTag]); Assert.AreEqual("User name is malformed.", ex.AdditionalExceptionData[MsalException.BrokerErrorContext]); // message might change. not a big deal Assert.AreEqual("ApiContractViolation", ex.AdditionalExceptionData[MsalException.BrokerErrorStatus]); Assert.AreEqual("3399811229", ex.AdditionalExceptionData[MsalException.BrokerErrorCode]); Assert.IsNotNull(ex.AdditionalExceptionData[MsalException.BrokerTelemetry]); - + } [IgnoreOnOneBranch] @@ -199,8 +199,8 @@ public async Task WamSilentAuthLoginHintNoAccontInCacheAsync() } catch (MsalUiRequiredException ex) { - Assert.IsTrue(ex.Message.Contains("You are trying to acquire a token silently using a login hint. " + - "No account was found in the token cache having this login hint")); + Assert.Contains("You are trying to acquire a token silently using a login hint. " + + "No account was found in the token cache having this login hint", ex.Message); } } @@ -209,7 +209,7 @@ public async Task WamSilentAuthLoginHintNoAccontInCacheAsync() public async Task WamUsernamePasswordRequestAsync() { var labResponse = await LabUserHelper.GetDefaultUserAsync().ConfigureAwait(false); - string[] scopes = { "User.Read" }; + string[] scopes = { "User.Read" }; IntPtr intPtr = TestUtils.GetWindowHandle(); @@ -227,9 +227,9 @@ public async Task WamUsernamePasswordRequestAsync() var accounts = await pca.GetAccountsAsync().ConfigureAwait(false); // Acquire token using username password - #pragma warning disable CS0618 // Type or member is obsolete +#pragma warning disable CS0618 // Type or member is obsolete var result = await pca.AcquireTokenByUsernamePassword(scopes, labResponse.User.Upn, labResponse.User.GetOrFetchPassword()).ExecuteAsync().ConfigureAwait(false); - #pragma warning restore CS0618 +#pragma warning restore CS0618 MsalAssert.AssertAuthResult(result, TokenSource.Broker, labResponse.Lab.TenantId, scopes); Assert.IsNotNull(result.AuthenticationResultMetadata.Telemetry); @@ -278,12 +278,12 @@ public async Task WamWithSSHCertificateAuthenticationSchemeAsync() string jwk = CreateJwk(); //Do a login with username password - #pragma warning disable CS0618 // Type or member is obsolete +#pragma warning disable CS0618 // Type or member is obsolete AuthenticationResult result = await pca .AcquireTokenByUsernamePassword(_SSH_scopes, labResponse.User.Upn, labResponse.User.GetOrFetchPassword()) .ExecuteAsync() .ConfigureAwait(false); - #pragma warning restore CS0618 +#pragma warning restore CS0618 //Assert successful login var accounts = await pca.GetAccountsAsync().ConfigureAwait(false); @@ -320,14 +320,14 @@ public async Task WamUsernamePasswordWithForceRefreshAsync() .Build(); // Acquire token using username password - #pragma warning disable CS0618 // Type or member is obsolete +#pragma warning disable CS0618 // Type or member is obsolete var result = await pca.AcquireTokenByUsernamePassword( - scopes, - labResponse.User.Upn, + scopes, + labResponse.User.Upn, labResponse.User.GetOrFetchPassword()) .ExecuteAsync() .ConfigureAwait(false); - #pragma warning restore CS0618 +#pragma warning restore CS0618 string ropcToken = result.AccessToken; @@ -335,7 +335,7 @@ public async Task WamUsernamePasswordWithForceRefreshAsync() Assert.IsNotNull(result.AuthenticationResultMetadata.Telemetry); // Get Accounts - var accounts = await pca.GetAccountsAsync().ConfigureAwait(false); + var accounts = await pca.GetAccountsAsync().ConfigureAwait(false); var account = accounts.FirstOrDefault(); Assert.IsNotNull(account); @@ -355,7 +355,6 @@ public async Task WamUsernamePasswordWithForceRefreshAsync() [IgnoreOnOneBranch] [TestMethod] - [ExpectedException(typeof(MsalUiRequiredException))] public async Task WamUsernamePasswordRequestAsync_WithPiiAsync() { var labResponse = await LabUserHelper.GetDefaultUserAsync().ConfigureAwait(false); @@ -376,9 +375,9 @@ public async Task WamUsernamePasswordRequestAsync_WithPiiAsync() .Build(); // Acquire token using username password - #pragma warning disable CS0618 // Type or member is obsolete +#pragma warning disable CS0618 // Type or member is obsolete var result = await pca.AcquireTokenByUsernamePassword(scopes, labResponse.User.Upn, labResponse.User.GetOrFetchPassword()).ExecuteAsync().ConfigureAwait(false); - #pragma warning restore CS0618 +#pragma warning restore CS0618 MsalAssert.AssertAuthResult(result, TokenSource.Broker, labResponse.Lab.TenantId, scopes); Assert.IsNotNull(result.AuthenticationResultMetadata.Telemetry); @@ -405,7 +404,10 @@ public async Task WamUsernamePasswordRequestAsync_WithPiiAsync() Assert.IsNotNull(accounts); // this should throw MsalUiRequiredException - result = await pca.AcquireTokenSilent(scopes, account).ExecuteAsync().ConfigureAwait(false); + await Assert.ThrowsAsync(async () => + { + await pca.AcquireTokenSilent(scopes, account).ExecuteAsync().ConfigureAwait(false); + }).ConfigureAwait(false); } [DoNotRunOnLinux] // List Windows Work and School accounts is not supported on Linux @@ -431,9 +433,9 @@ public async Task WamListWindowsWorkAndSchoolAccountsAsync() .Build(); // Acquire token using username password - #pragma warning disable CS0618 // Type or member is obsolete +#pragma warning disable CS0618 // Type or member is obsolete var result = await pca.AcquireTokenByUsernamePassword(scopes, labResponse.User.Upn, labResponse.User.GetOrFetchPassword()).ExecuteAsync().ConfigureAwait(false); - #pragma warning restore CS0618 +#pragma warning restore CS0618 MsalAssert.AssertAuthResult(result, TokenSource.Broker, labResponse.Lab.TenantId, scopes); Assert.IsNotNull(result.AuthenticationResultMetadata.Telemetry); @@ -449,9 +451,8 @@ public async Task WamListWindowsWorkAndSchoolAccountsAsync() } [IgnoreOnOneBranch] - [DataTestMethod] - [DataRow(null)] [TestMethod] + [DataRow(null)] public async Task WamAddDefaultScopesWhenNoScopesArePassedAsync(string scopes) { IntPtr intPtr = TestUtils.GetWindowHandle(); @@ -465,18 +466,21 @@ public async Task WamAddDefaultScopesWhenNoScopesArePassedAsync(string scopes) .WithBroker(_brokerOptions) .Build(); // Act - if (SharedUtilities.IsLinuxPlatform()) { + if (SharedUtilities.IsLinuxPlatform()) + { var exLinux = await AssertException.TaskThrowsAsync( () => pca.AcquireTokenSilent(new string[] { scopes }, PublicClientApplication.OperatingSystemAccount) .ExecuteAsync()) .ConfigureAwait(false); StringAssert.Contains(exLinux.AdditionalExceptionData[MsalException.BrokerErrorContext], "requestedScopes is NULL or EMPTY"); - } else { + } + else + { var ex = await AssertException.TaskThrowsAsync( () => pca.AcquireTokenSilent(new string[] { scopes }, PublicClientApplication.OperatingSystemAccount) .ExecuteAsync()) .ConfigureAwait(false); - Assert.IsTrue(!string.IsNullOrEmpty(ex.ErrorCode)); + Assert.IsFalse(string.IsNullOrEmpty(ex.ErrorCode)); } } @@ -504,12 +508,12 @@ public async Task WamUsernamePasswordPopTokenEnforcedWithCaOnValidResourceAsync( // Acquire token using username password with POP on a valid resource // CA policy enforces token issuance to popUser only for SPO // https://learn.microsoft.com/azure/active-directory/conditional-access/concept-token-protection - #pragma warning disable CS0618 // Type or member is obsolete +#pragma warning disable CS0618 // Type or member is obsolete var result = await pca.AcquireTokenByUsernamePassword(scopes, labResponse.User.Upn, labResponse.User.GetOrFetchPassword()) .WithProofOfPossession("some_nonce", System.Net.Http.HttpMethod.Get, new Uri(pca.Authority)) .ExecuteAsync() .ConfigureAwait(false); - #pragma warning restore CS0618 +#pragma warning restore CS0618 //Act Assert.AreEqual(labResponse.User.Upn, result.Account.Username); @@ -518,7 +522,6 @@ public async Task WamUsernamePasswordPopTokenEnforcedWithCaOnValidResourceAsync( [DoNotRunOnLinux] // POP are not supported on Linux [IgnoreOnOneBranch] [TestMethod] - [ExpectedException(typeof(MsalUiRequiredException))] public async Task WamUsernamePasswordPopTokenEnforcedWithCaOnInValidResourceAsync() { //Arrange @@ -540,12 +543,13 @@ public async Task WamUsernamePasswordPopTokenEnforcedWithCaOnInValidResourceAsyn // Acquire token using username password with POP on a resource not in the CA policy // CA policy enforces token issuance to popUser only for Exchange Online this call will fail with UI Required Exception // https://learn.microsoft.com/azure/active-directory/conditional-access/concept-token-protection - #pragma warning disable CS0618 // Type or member is obsolete - var result = await pca.AcquireTokenByUsernamePassword(scopes, labResponse.User.Upn, labResponse.User.GetOrFetchPassword()) +#pragma warning disable CS0618 // Type or member is obsolete + await Assert.ThrowsAsync(async () => + await pca.AcquireTokenByUsernamePassword(scopes, labResponse.User.Upn, labResponse.User.GetOrFetchPassword()) .WithProofOfPossession("some_nonce", System.Net.Http.HttpMethod.Get, new Uri(pca.Authority)) - .ExecuteAsync() + .ExecuteAsync().ConfigureAwait(false)) .ConfigureAwait(false); - #pragma warning restore CS0618 +#pragma warning restore CS0618 } } } diff --git a/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/UsernamePasswordIntegrationTests.NetFwk.cs b/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/UsernamePasswordIntegrationTests.NetFwk.cs index 3dfdba5f5c..3630e6abd8 100644 --- a/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/UsernamePasswordIntegrationTests.NetFwk.cs +++ b/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/UsernamePasswordIntegrationTests.NetFwk.cs @@ -276,7 +276,7 @@ private void AssertCcsRoutingInformationIsNotSent(HttpSnifferClientFactory facto private void AssertTenantProfiles(IEnumerable tenantProfiles, string tenantId) { Assert.IsNotNull(tenantProfiles); - Assert.IsTrue(tenantProfiles.Count() > 0); + Assert.IsGreaterThan(0, tenantProfiles.Count()); TenantProfile tenantProfile = tenantProfiles.Single(tp => tp.TenantId == tenantId); Assert.IsNotNull(tenantProfile); diff --git a/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/WwwAuthenticateParametersIntegrationTests.NetFwk.cs b/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/WwwAuthenticateParametersIntegrationTests.NetFwk.cs index aa8e4cb076..6e22336511 100644 --- a/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/WwwAuthenticateParametersIntegrationTests.NetFwk.cs +++ b/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/WwwAuthenticateParametersIntegrationTests.NetFwk.cs @@ -31,7 +31,7 @@ public async Task CreateWwwAuthenticateResponseFromKeyVaultUrlAsync() Assert.AreEqual("login.microsoftonline.com", new Uri(authParams.Authority).Host); Assert.AreEqual("72f988bf-86f1-41af-91ab-2d7cd011db47", authParams.GetTenantId()); // because the Key Vault resource belong to Microsoft Corp tenant - Assert.AreEqual(2, authParams.RawParameters.Count); + Assert.HasCount(2, authParams.RawParameters); Assert.IsNull(authParams.Claims); Assert.IsNull(authParams.Error); } @@ -44,7 +44,7 @@ public async Task CreateWwwAuthenticateResponseFromGraphUrlAsync() Assert.AreEqual("https://login.microsoftonline.com/common", authParams.Authority); Assert.AreEqual("common", authParams.GetTenantId()); - Assert.AreEqual(3, authParams.RawParameters.Count); + Assert.HasCount(3, authParams.RawParameters); Assert.IsNull(authParams.Claims); Assert.IsNull(authParams.Error); } @@ -94,7 +94,7 @@ private static async Task RunTestForSettingsAsync(string hostName, string apiVer Assert.AreEqual($"https://{authority}/{tenantId}", authParams.Authority); // authority URI consists of AAD endpoint and tenant ID Assert.AreEqual(tenantId, authParams.GetTenantId()); // tenant ID is extracted out of authority URI - Assert.AreEqual(3, authParams.RawParameters.Count); + Assert.HasCount(3, authParams.RawParameters); Assert.IsNull(authParams.Claims); Assert.AreEqual("invalid_token", authParams.Error); Assert.AreEqual($"https://{authority}/{tenantId}", authParams.RawParameters["authorization_uri"]); diff --git a/tests/Microsoft.Identity.Test.Integration.netcore/Infrastructure/IgnoreFederatedTests.cs b/tests/Microsoft.Identity.Test.Integration.netcore/Infrastructure/IgnoreFederatedTests.cs index bb79741cd0..65bfd43e12 100644 --- a/tests/Microsoft.Identity.Test.Integration.netcore/Infrastructure/IgnoreFederatedTests.cs +++ b/tests/Microsoft.Identity.Test.Integration.netcore/Infrastructure/IgnoreFederatedTests.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; using Microsoft.VisualStudio.TestTools.UnitTesting; @@ -15,10 +16,14 @@ namespace Microsoft.Identity.Test.Integration.Infrastructure /// internal class IgnoreFederatedTestsAttribute : TestMethodAttribute { - public override TestResult[] Execute(ITestMethod testMethod) + public IgnoreFederatedTestsAttribute([CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1) : base(callerFilePath, callerLineNumber) + { + } + + public override Task ExecuteAsync(ITestMethod testMethod) { #if IGNORE_FEDERATED - return new[] + return Task.FromResult(new[] { new TestResult { @@ -26,9 +31,9 @@ public override TestResult[] Execute(ITestMethod testMethod) TestFailureException = new AssertInconclusiveException( $"Skipped on OneBranch pipeline") } - }; + }); #else - return base.Execute(testMethod); + return base.ExecuteAsync(testMethod); #endif } } diff --git a/tests/Microsoft.Identity.Test.Integration.netcore/Infrastructure/IgnoreOnOneBranch.cs b/tests/Microsoft.Identity.Test.Integration.netcore/Infrastructure/IgnoreOnOneBranch.cs index 16910bf777..762e556377 100644 --- a/tests/Microsoft.Identity.Test.Integration.netcore/Infrastructure/IgnoreOnOneBranch.cs +++ b/tests/Microsoft.Identity.Test.Integration.netcore/Infrastructure/IgnoreOnOneBranch.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; using Microsoft.VisualStudio.TestTools.UnitTesting; @@ -12,10 +13,16 @@ namespace Microsoft.Identity.Test.Integration.Infrastructure { internal class IgnoreOnOneBranchAttribute : TestMethodAttribute { - public override TestResult[] Execute(ITestMethod testMethod) + public IgnoreOnOneBranchAttribute( + [CallerFilePath] string callerFilePath = "", + [CallerLineNumber] int callerLineNumber = -1) : base(callerFilePath, callerLineNumber) + { + } + + public override Task ExecuteAsync(ITestMethod testMethod) { #if ONEBRANCH_BUILD - return new[] + var tr = new[] { new TestResult { @@ -24,8 +31,9 @@ public override TestResult[] Execute(ITestMethod testMethod) $"Skipped on OneBranch pipeline") } }; + return Task.FromResult(tr); #else - return base.Execute(testMethod); + return base.ExecuteAsync(testMethod); #endif } } diff --git a/tests/Microsoft.Identity.Test.Integration.netcore/Infrastructure/TargetFramework.cs b/tests/Microsoft.Identity.Test.Integration.netcore/Infrastructure/TargetFramework.cs index ac8c1435ac..d481fbc53c 100644 --- a/tests/Microsoft.Identity.Test.Integration.netcore/Infrastructure/TargetFramework.cs +++ b/tests/Microsoft.Identity.Test.Integration.netcore/Infrastructure/TargetFramework.cs @@ -2,6 +2,8 @@ // Licensed under the MIT License. using System; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Microsoft.Identity.Test.Common.Core.Helpers @@ -13,17 +15,17 @@ public class RunOnAttribute : TestMethodAttribute { private readonly TargetFrameworks _tfms; - public RunOnAttribute(TargetFrameworks tfms) + public RunOnAttribute(TargetFrameworks tfms, [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1) : base(callerFilePath, callerLineNumber) { _tfms = tfms; } - public override TestResult[] Execute(ITestMethod testMethod) + public override Task ExecuteAsync(ITestMethod testMethod) { if (RunOnHelper.IsNetFwk() && (_tfms & TargetFrameworks.NetFx) != TargetFrameworks.NetFx || RunOnHelper.IsNetCore() && (_tfms & TargetFrameworks.NetCore) != TargetFrameworks.NetCore) { - return new[] + return Task.FromResult(new[] { new TestResult { @@ -31,10 +33,10 @@ public override TestResult[] Execute(ITestMethod testMethod) TestFailureException = new AssertInconclusiveException( $"Skipped on target framework {_tfms}") } - }; + }); } - return base.Execute(testMethod); + return base.ExecuteAsync(testMethod); } } diff --git a/tests/Microsoft.Identity.Test.Integration.netcore/SeleniumTests/DeviceCodeFlowIntegrationTest.cs b/tests/Microsoft.Identity.Test.Integration.netcore/SeleniumTests/DeviceCodeFlowIntegrationTest.cs index 172ab1a95a..ef2c9ddd51 100644 --- a/tests/Microsoft.Identity.Test.Integration.netcore/SeleniumTests/DeviceCodeFlowIntegrationTest.cs +++ b/tests/Microsoft.Identity.Test.Integration.netcore/SeleniumTests/DeviceCodeFlowIntegrationTest.cs @@ -114,7 +114,7 @@ private async Task AcquireTokenSilentAfterDeviceCodeFlowWithBrokerAsync(LabRespo Assert.IsNotNull(result); var account = result.Account as Account; - Assert.IsTrue(account.AccountSource == "device_code_flow"); + Assert.AreEqual("device_code_flow", account.AccountSource); Assert.IsTrue(!string.IsNullOrEmpty(result.AccessToken)); var silentTokenResult = await pca.AcquireTokenSilent(s_scopes, result.Account).ExecuteAsync(CancellationToken.None).ConfigureAwait(false); diff --git a/tests/Microsoft.Identity.Test.Integration.netcore/SeleniumTests/InteractiveFlowTests.NetFwk.cs b/tests/Microsoft.Identity.Test.Integration.netcore/SeleniumTests/InteractiveFlowTests.NetFwk.cs index c71dd11577..b0937443b2 100644 --- a/tests/Microsoft.Identity.Test.Integration.netcore/SeleniumTests/InteractiveFlowTests.NetFwk.cs +++ b/tests/Microsoft.Identity.Test.Integration.netcore/SeleniumTests/InteractiveFlowTests.NetFwk.cs @@ -111,7 +111,7 @@ public async Task Interactive_Arlington_MultiCloudSupport_AADAsync() Assert.IsNotNull(result.Account.GetTenantProfiles()); Assert.IsTrue(result.Account.GetTenantProfiles().Any()); Assert.AreEqual(labResponse.User.Upn, result.Account.Username); - Assert.IsTrue(labResponse.Lab.Authority.Contains(result.Account.Environment)); + Assert.Contains(result.Account.Environment, labResponse.Lab.Authority); Trace.WriteLine("Part 2 - Get Accounts"); var accounts = await pca.GetAccountsAsync().ConfigureAwait(false); @@ -136,7 +136,7 @@ public async Task Interactive_Arlington_MultiCloudSupport_AADAsync() Assert.IsNotNull(result.Account); Assert.IsNotNull(result.Account.GetTenantProfiles()); Assert.IsTrue(result.Account.GetTenantProfiles().Any()); - Assert.IsTrue(labResponse.Lab.Authority.Contains(result.Account.Environment)); + Assert.Contains(result.Account.Environment, labResponse.Lab.Authority); } [RunOn(TargetFrameworks.NetCore)] @@ -240,8 +240,8 @@ private async Task RunTestForUserAsync(LabResponse labResp .ExecuteAsync(new CancellationTokenSource(_interactiveAuthTimeout).Token) .ConfigureAwait(false); - Assert.IsTrue(result.AuthenticationResultMetadata.DurationTotalInMs > 0); - Assert.IsTrue(result.AuthenticationResultMetadata.DurationInHttpInMs > 0); + Assert.IsGreaterThan(0, result.AuthenticationResultMetadata.DurationTotalInMs); + Assert.IsGreaterThan(0, result.AuthenticationResultMetadata.DurationInHttpInMs); userCacheAccess.AssertAccessCounts(0, 1); IAccount account = await MsalAssert.AssertSingleAccountAsync(labResponse, pca, result).ConfigureAwait(false); diff --git a/tests/Microsoft.Identity.Test.Integration.netcore/SeleniumTests/SeleniumInfrastructureTests.NetFwk.cs b/tests/Microsoft.Identity.Test.Integration.netcore/SeleniumTests/SeleniumInfrastructureTests.NetFwk.cs index 48bbefc6de..b0c6b46988 100644 --- a/tests/Microsoft.Identity.Test.Integration.netcore/SeleniumTests/SeleniumInfrastructureTests.NetFwk.cs +++ b/tests/Microsoft.Identity.Test.Integration.netcore/SeleniumTests/SeleniumInfrastructureTests.NetFwk.cs @@ -36,7 +36,7 @@ public void TestInitialize() #endregion // This test checks that MSAL.netcore / MSAL.netfx / MSAL.netstandard DLLs are actually used - [DataTestMethod()] + [TestMethod()] [DataRow(TargetFrameworks.NetCore)] [DataRow(TargetFrameworks.NetFx)] public void AssertTfm(TargetFrameworks targetFwk) diff --git a/tests/Microsoft.Identity.Test.Performance/Microsoft.Identity.Test.Performance.csproj b/tests/Microsoft.Identity.Test.Performance/Microsoft.Identity.Test.Performance.csproj index 24d2996016..03c91e9115 100644 --- a/tests/Microsoft.Identity.Test.Performance/Microsoft.Identity.Test.Performance.csproj +++ b/tests/Microsoft.Identity.Test.Performance/Microsoft.Identity.Test.Performance.csproj @@ -31,8 +31,8 @@ - - + + diff --git a/tests/Microsoft.Identity.Test.Unit/ApiConfigTests/AuthorityTests.cs b/tests/Microsoft.Identity.Test.Unit/ApiConfigTests/AuthorityTests.cs index 17821aae1b..bf09c87ea3 100644 --- a/tests/Microsoft.Identity.Test.Unit/ApiConfigTests/AuthorityTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/ApiConfigTests/AuthorityTests.cs @@ -51,6 +51,7 @@ public override void TestCleanup() base.TestCleanup(); } + [TestMethod] [DataRow(TestConstants.ADFSAuthority)] [DataRow(TestConstants.GenericAuthority)] public void WithTenantIdAtRequestLevel_Noop_AdfsGeneric(string inputAuthority) @@ -76,7 +77,7 @@ public void WithTenantIdAtRequestLevel_Noop_AdfsGeneric(string inputAuthority) "The tenant id should have been changed"); } - [DataTestMethod] + [TestMethod] [DataRow(TestConstants.DstsAuthorityCommon)] [DataRow(TestConstants.DstsAuthorityTenanted)] [DataRow(TestConstants.CiamAuthorityMainFormat)] @@ -105,7 +106,7 @@ public void WithTenantIdAtRequestLevel_NonAad(string inputAuthority) "The tenant id should have been changed"); } - [DataTestMethod] + [TestMethod] [DataRow(TestConstants.AuthorityCommonTenant, true)] [DataRow(TestConstants.AuthorityCommonPpeAuthority, true)] [DataRow(TestConstants.DstsAuthorityCommon, false)] @@ -119,7 +120,7 @@ public void WithTenantIdAtRequestLevel_NonAad(string inputAuthority) public void IsSha2Supported(string inputAuthority, bool expected) { Authority a = Authority.CreateAuthority(inputAuthority); - Assert.AreEqual(a.AuthorityInfo.IsSha2CredentialSupported, expected); + Assert.AreEqual(expected, a.AuthorityInfo.IsSha2CredentialSupported); } [TestMethod] @@ -129,7 +130,7 @@ public void GenericSha2() Assert.IsFalse(ai.IsSha2CredentialSupported); } - [DataTestMethod] + [TestMethod] [DataRow(TestConstants.AuthorityCommonTenant)] [DataRow(TestConstants.AuthorityCommonPpeAuthority)] [DataRow(TestConstants.AuthorityConsumersTenant)] @@ -201,8 +202,8 @@ public void WithTenantId_B2C() "The tenant id should have NOT changed"); } - [DataTestMethod] - [DynamicData(nameof(TestData.GetAuthorityWithExpectedTenantId), typeof(TestData), DynamicDataSourceType.Method)] + [TestMethod] + [DynamicData(nameof(TestData.GetAuthorityWithExpectedTenantId), typeof(TestData))] public void AADWithTenantId_Success(Uri authorityValue, string tenantId) { // Ignore authorityValue, it's just that we don't need to create another TestData method @@ -224,8 +225,8 @@ public void AADWithTenantId_Success(Uri authorityValue, string tenantId) Assert.AreEqual(tenantId, AuthorityHelpers.GetTenantId(parameterBuilder.CommonParameters.AuthorityOverride.CanonicalAuthority)); } - [DataTestMethod] - [DynamicData(nameof(TestData.GetAuthorityWithExpectedTenantId), typeof(TestData), DynamicDataSourceType.Method)] + [TestMethod] + [DynamicData(nameof(TestData.GetAuthorityWithExpectedTenantId), typeof(TestData))] public void AADWithTenantIdFromAuthority_Success(Uri authorityValue, string expectedTenantId) { var app = ConfidentialClientApplicationBuilder @@ -245,12 +246,12 @@ public void AADWithTenantIdFromAuthority_Success(Uri authorityValue, string expe Assert.AreEqual(expectedTenantId, AuthorityHelpers.GetTenantId(parameterBuilder.CommonParameters.AuthorityOverride.CanonicalAuthority)); } - [DataTestMethod] + [TestMethod] [DataRow("malformed tenant")] public void WithTenantId_AppLevel_MalformedTenant_ThrowsException(string tenantId) { // Tenant and authority modifiers - Assert.ThrowsException(() => + Assert.Throws(() => ConfidentialClientApplicationBuilder .Create(TestConstants.ClientId) .WithTenantId(tenantId) @@ -259,7 +260,7 @@ public void WithTenantId_AppLevel_MalformedTenant_ThrowsException(string tenantI .Build()); // Tenant only modifier - Assert.ThrowsException(() => + Assert.Throws(() => ConfidentialClientApplicationBuilder .Create(TestConstants.ClientId) .WithTenantId(tenantId) @@ -267,9 +268,8 @@ public void WithTenantId_AppLevel_MalformedTenant_ThrowsException(string tenantI .Build()); } - [DataTestMethod] + [TestMethod] [DataRow("malformed tenant")] - [ExpectedException(typeof(ArgumentException))] public void WithTenantId_RequestLevel_MalformedTenant_ThrowsException(string tenantId) { var app = ConfidentialClientApplicationBuilder @@ -278,13 +278,13 @@ public void WithTenantId_RequestLevel_MalformedTenant_ThrowsException(string ten .Build(); // Tenant and authority modifiers - app.AcquireTokenByAuthorizationCode(TestConstants.s_scope, "code") - .WithTenantId(tenantId); + Assert.Throws(() => + app.AcquireTokenByAuthorizationCode(TestConstants.s_scope, "code") + .WithTenantId(tenantId)); } - [DataTestMethod] + [TestMethod] [DataRow(null)] - [ExpectedException(typeof(ArgumentNullException))] public void WithTenantIdFromAuthority_NullUriAuthority_ThrowsException(Uri authorityValue) { var app = ConfidentialClientApplicationBuilder @@ -292,12 +292,12 @@ public void WithTenantIdFromAuthority_NullUriAuthority_ThrowsException(Uri autho .WithClientSecret("secret") .Build(); - app.AcquireTokenByAuthorizationCode(TestConstants.s_scope, "code") - .WithTenantIdFromAuthority(authorityValue); + Assert.Throws(() => + app.AcquireTokenByAuthorizationCode(TestConstants.s_scope, "code") + .WithTenantIdFromAuthority(authorityValue)); } [TestMethod] - [ExpectedException(typeof(ArgumentException))] public void WithTenantIdFromAuthority_MalformedTenant_ThrowsException() { var invalidAuthorityUri = new Uri("https://login.microsoftonline.com/invalid tenant/"); @@ -306,8 +306,9 @@ public void WithTenantIdFromAuthority_MalformedTenant_ThrowsException() .WithClientSecret("secret") .Build(); - app.AcquireTokenByAuthorizationCode(TestConstants.s_scope, "code") - .WithTenantIdFromAuthority(invalidAuthorityUri); + Assert.Throws(() => + app.AcquireTokenByAuthorizationCode(TestConstants.s_scope, "code") + .WithTenantIdFromAuthority(invalidAuthorityUri) ); } [TestMethod] @@ -372,7 +373,7 @@ public async Task AuthorityMismatchTestAsync() public async Task DefaultAuthorityDifferentTypeTestAsync() { _testRequestContext.ServiceBundle.Config.Authority = s_commonAuthority; - var ex = await Assert.ThrowsExceptionAsync( + var ex = await Assert.ThrowsAsync( () => Authority.CreateAuthorityForRequestAsync(_testRequestContext, s_b2cAuthority.AuthorityInfo, null)).ConfigureAwait(false); Assert.AreEqual(MsalError.B2CAuthorityHostMismatch, ex.ErrorCode); @@ -384,18 +385,18 @@ public async Task DifferentHostsAsync() _harness.HttpManager.AddInstanceDiscoveryMockHandler(); _testRequestContext.ServiceBundle.Config.HttpManager = _harness.HttpManager; _testRequestContext.ServiceBundle.Config.Authority = s_commonAuthority; - var ex = await Assert.ThrowsExceptionAsync( + var ex = await Assert.ThrowsAsync( () => Authority.CreateAuthorityForRequestAsync(_testRequestContext, s_ppeOrgAuthority.AuthorityInfo, null)).ConfigureAwait(false); Assert.AreEqual(MsalError.AuthorityHostMismatch, ex.ErrorCode); _harness.HttpManager.AddInstanceDiscoveryMockHandler(); _testRequestContext.ServiceBundle.Config.Authority = s_ppeOrgAuthority; - var ex2 = await Assert.ThrowsExceptionAsync( + var ex2 = await Assert.ThrowsAsync( () => Authority.CreateAuthorityForRequestAsync(_testRequestContext, s_commonAuthority.AuthorityInfo, null)).ConfigureAwait(false); Assert.AreEqual(MsalError.AuthorityHostMismatch, ex2.ErrorCode); _testRequestContext.ServiceBundle.Config.Authority = Authority.CreateAuthority(TestConstants.ADFSAuthority, true); - var ex3 = await Assert.ThrowsExceptionAsync( + var ex3 = await Assert.ThrowsAsync( () => Authority.CreateAuthorityForRequestAsync( _testRequestContext, AuthorityInfo.FromAdfsAuthority(TestConstants.ADFSAuthority2, true), @@ -403,7 +404,7 @@ public async Task DifferentHostsAsync() Assert.AreEqual(MsalError.AuthorityHostMismatch, ex3.ErrorCode); _testRequestContext.ServiceBundle.Config.Authority = Authority.CreateAuthority(TestConstants.B2CAuthority, true); - var ex4 = await Assert.ThrowsExceptionAsync( + var ex4 = await Assert.ThrowsAsync( () => Authority.CreateAuthorityForRequestAsync( _testRequestContext, AuthorityInfo.FromAuthorityUri(TestConstants.B2CCustomDomain, true), @@ -435,7 +436,7 @@ public void IsDefaultAuthorityTest() Assert.IsFalse(s_b2cAuthority.AuthorityInfo.IsDefaultAuthority); } - [DataTestMethod] + [TestMethod] [DataRow(TestConstants.AuthorityCommonTenant, typeof(AadAuthority), "Aad")] [DataRow(TestConstants.AuthorityCommonPpeAuthority, typeof(AadAuthority), "Aad")] [DataRow(TestConstants.AuthorityConsumersTenant, typeof(AadAuthority), "Aad")] diff --git a/tests/Microsoft.Identity.Test.Unit/AppConfigTests/CiamAuthorityTests.cs b/tests/Microsoft.Identity.Test.Unit/AppConfigTests/CiamAuthorityTests.cs index 63ad9d2db9..f38de7adcc 100644 --- a/tests/Microsoft.Identity.Test.Unit/AppConfigTests/CiamAuthorityTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/AppConfigTests/CiamAuthorityTests.cs @@ -96,7 +96,7 @@ public void CiamAuthorityAdapater_WithInstanceAndNullTenantTest() Assert.AreEqual(ciamTransformedAuthority, transformedAuthority.AbsoluteUri); } - [DataTestMethod] + [TestMethod] [DataRow("https://idgciamdemo.ciamlogin.com/", "https://idgciamdemo.ciamlogin.com/idgciamdemo.onmicrosoft.com/")] [DataRow("https://idgciamdemo.ciamlogin.com/d57fb3d4-4b5a-4144-9328-9c1f7d58179d", "https://idgciamdemo.ciamlogin.com/d57fb3d4-4b5a-4144-9328-9c1f7d58179d/")] [DataRow("https://idgciamdemo.ciamlogin.com/idgciamdemo.onmicrosoft.com", "https://idgciamdemo.ciamlogin.com/idgciamdemo.onmicrosoft.com/")] @@ -113,7 +113,7 @@ public void CiamWithAuthorityTransformationTest(string authority, string expecte Assert.AreEqual(expectedAuthority, effectiveAuthority); } - [DataTestMethod] + [TestMethod] [DataRow("https://app.ciamlogin.com/")] //[DataRow("https://app.ciamlogin.com/d57fb3d4-4b5a-4144-9328-9c1f7d58179d")] //[DataRow("https://app.ciamlogin.com/aDomain")] @@ -172,7 +172,7 @@ static async Task TestRequestAuthorityAsync(MockHttpAndServiceBundle harness, st } } - [DataTestMethod] + [TestMethod] [DataRow("https://app.ciamlogin.com/")] [DataRow("https://app.ciamlogin.com/d57fb3d4-4b5a-4144-9328-9c1f7d58179d")] [DataRow("https://app.ciamlogin.com/aDomain")] diff --git a/tests/Microsoft.Identity.Test.Unit/AppConfigTests/ConfidentialClientApplicationBuilderTests.cs b/tests/Microsoft.Identity.Test.Unit/AppConfigTests/ConfidentialClientApplicationBuilderTests.cs index 1bab2b0ab3..baaef1c085 100644 --- a/tests/Microsoft.Identity.Test.Unit/AppConfigTests/ConfidentialClientApplicationBuilderTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/AppConfigTests/ConfidentialClientApplicationBuilderTests.cs @@ -43,12 +43,12 @@ public void TestConstructor() Assert.AreEqual(TestConstants.ClientId, cca.AppConfig.ClientId); Assert.IsNull(cca.AppConfig.ClientName); Assert.IsNull(cca.AppConfig.ClientVersion); - Assert.AreEqual(false, cca.AppConfig.EnablePiiLogging); + Assert.IsFalse(cca.AppConfig.EnablePiiLogging); Assert.IsNull(cca.AppConfig.HttpClientFactory); - Assert.AreEqual(false, cca.AppConfig.IsDefaultPlatformLoggingEnabled); + Assert.IsFalse(cca.AppConfig.IsDefaultPlatformLoggingEnabled); Assert.IsNull(cca.AppConfig.LoggingCallback); Assert.AreEqual(Constants.DefaultConfidentialClientRedirectUri, cca.AppConfig.RedirectUri); - Assert.AreEqual(null, cca.AppConfig.TenantId); + Assert.IsNull(cca.AppConfig.TenantId); } private ConfidentialClientApplicationOptions CreateConfidentialClientApplicationOptions() @@ -114,7 +114,7 @@ public void CacheSynchronization_Default_IsTrue() Assert.IsTrue((cca.AppConfig as ApplicationConfiguration).CacheSynchronizationEnabled); } - [DataTestMethod] + [TestMethod] [DataRow(false)] [DataRow(true)] public void CacheSynchronization_WithOptions(bool enableCacheSynchronization) @@ -129,7 +129,7 @@ public void CacheSynchronization_WithOptions(bool enableCacheSynchronization) Assert.AreEqual(enableCacheSynchronization, (cca.AppConfig as ApplicationConfiguration).CacheSynchronizationEnabled); } - [DataTestMethod] + [TestMethod] [DataRow(false, false, false)] [DataRow(true, true, true)] [DataRow(true, false, false)] @@ -289,7 +289,7 @@ public void TestConstructor_WithWhitespaceRedirectUri() [TestMethod] public void TestConstructor_WithInvalidRedirectUri() { - Assert.ThrowsException(() => + Assert.Throws(() => ConfidentialClientApplicationBuilder.Create(TestConstants.ClientId) .WithClientSecret("cats") .WithRedirectUri("this is not a valid uri") @@ -391,7 +391,7 @@ public void TestConstructor_WithValidInstanceDicoveryMetadata() .Build(); var instanceDiscoveryMetadata = (cca.AppConfig as ApplicationConfiguration).CustomInstanceDiscoveryMetadata; - Assert.AreEqual(2, instanceDiscoveryMetadata.Metadata.Length); + Assert.HasCount(2, instanceDiscoveryMetadata.Metadata); } [TestMethod] @@ -404,7 +404,7 @@ public void TestConstructor_InstanceMetadata_ValidateAuthority_MutuallyExclusive .WithClientSecret("cats") .WithAuthority("https://some.authority/bogus/", true) .Build()); - Assert.AreEqual(ex.ErrorCode, MsalError.ValidateAuthorityOrCustomMetadata); + Assert.AreEqual(MsalError.ValidateAuthorityOrCustomMetadata, ex.ErrorCode); } [TestMethod] @@ -415,10 +415,10 @@ public void TestConstructor_BadInstanceMetadata() .WithClientSecret("cats") .Build()); - Assert.AreEqual(ex.ErrorCode, MsalError.InvalidUserInstanceMetadata); + Assert.AreEqual(MsalError.InvalidUserInstanceMetadata, ex.ErrorCode); } - [DataTestMethod] + [TestMethod] [DataRow(true)] [DataRow(false)] [DataRow(null)] // Not specified, default is true @@ -442,7 +442,7 @@ public void TestConstructor_WithLegacyCacheCompatibility(bool? isLegacyCacheComp Assert.AreEqual(isLegacyCacheCompatibilityEnabled, cca.AppConfig.LegacyCacheCompatibilityEnabled); } - [DataTestMethod] + [TestMethod] [DataRow(true)] [DataRow(false)] [DataRow(null)] // Not specified, default is true diff --git a/tests/Microsoft.Identity.Test.Unit/AppConfigTests/ManagedIdentityApplicationBuilderTests.cs b/tests/Microsoft.Identity.Test.Unit/AppConfigTests/ManagedIdentityApplicationBuilderTests.cs index 6897f314b0..77316c9c7b 100644 --- a/tests/Microsoft.Identity.Test.Unit/AppConfigTests/ManagedIdentityApplicationBuilderTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/AppConfigTests/ManagedIdentityApplicationBuilderTests.cs @@ -49,8 +49,8 @@ public void TestConstructor() // Validate Defaults Assert.AreEqual(LogLevel.Info, mi.ServiceBundle.Config.LogLevel); - Assert.AreEqual(false, mi.ServiceBundle.Config.EnablePiiLogging); - Assert.AreEqual(false, mi.ServiceBundle.Config.IsDefaultPlatformLoggingEnabled); + Assert.IsFalse(mi.ServiceBundle.Config.EnablePiiLogging); + Assert.IsFalse(mi.ServiceBundle.Config.IsDefaultPlatformLoggingEnabled); } [TestMethod] @@ -76,11 +76,11 @@ public void TestConstructor_WithCreateUserAssignedId() // Validate Defaults Assert.AreEqual(LogLevel.Info, mi.ServiceBundle.Config.LogLevel); - Assert.AreEqual(false, mi.ServiceBundle.Config.EnablePiiLogging); - Assert.AreEqual(false, mi.ServiceBundle.Config.IsDefaultPlatformLoggingEnabled); + Assert.IsFalse(mi.ServiceBundle.Config.EnablePiiLogging); + Assert.IsFalse(mi.ServiceBundle.Config.IsDefaultPlatformLoggingEnabled); } - [DataTestMethod] + [TestMethod] [DataRow(TestConstants.ClientId, UserAssignedIdentityId.ClientId)] [DataRow("resourceId", UserAssignedIdentityId.ResourceId)] [DataRow("resourceId/subscription", UserAssignedIdentityId.ResourceId)] diff --git a/tests/Microsoft.Identity.Test.Unit/AppConfigTests/PublicClientApplicationBuilderTests.cs b/tests/Microsoft.Identity.Test.Unit/AppConfigTests/PublicClientApplicationBuilderTests.cs index c472cc08d8..e24cc9ce63 100644 --- a/tests/Microsoft.Identity.Test.Unit/AppConfigTests/PublicClientApplicationBuilderTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/AppConfigTests/PublicClientApplicationBuilderTests.cs @@ -150,7 +150,7 @@ public void TestConstructor_WithValidInstanceDicoveryMetadata() .Build(); var instanceDiscoveryMetadata = (pca.AppConfig as ApplicationConfiguration).CustomInstanceDiscoveryMetadata; - Assert.AreEqual(2, instanceDiscoveryMetadata.Metadata.Length); + Assert.HasCount(2, instanceDiscoveryMetadata.Metadata); } [TestMethod] @@ -162,7 +162,7 @@ public void TestConstructor_InstanceMetadata_ValidateAuthority_MutuallyExclusive .WithInstanceDiscoveryMetadata(instanceMetadataJson) .WithAuthority("https://some.authority/bogus/", true) .Build()); - Assert.AreEqual(ex.ErrorCode, MsalError.ValidateAuthorityOrCustomMetadata); + Assert.AreEqual(MsalError.ValidateAuthorityOrCustomMetadata, ex.ErrorCode); } [TestMethod] @@ -172,7 +172,7 @@ public void TestConstructor_InstanceMetadataUri_ValidateAuthority_MutuallyExclus .WithInstanceDiscoveryMetadata(new Uri("https://some_uri.com")) .WithAuthority("https://some.authority/bogus/", true) .Build()); - Assert.AreEqual(ex.ErrorCode, MsalError.ValidateAuthorityOrCustomMetadata); + Assert.AreEqual(MsalError.ValidateAuthorityOrCustomMetadata, ex.ErrorCode); } [TestMethod] @@ -185,7 +185,7 @@ public void TestConstructor_WithInstanceDiscoveryMetadata_OnlyOneOverload() .WithInstanceDiscoveryMetadata(new Uri("https://some_uri.com")) .WithAuthority("https://some.authority/bogus/", true) .Build()); - Assert.AreEqual(ex.ErrorCode, MsalError.CustomMetadataInstanceOrUri); + Assert.AreEqual(MsalError.CustomMetadataInstanceOrUri, ex.ErrorCode); } [TestMethod] @@ -195,7 +195,7 @@ public void TestConstructor_BadInstanceMetadata() .WithInstanceDiscoveryMetadata("{bad_json_metadata") .Build()); - Assert.AreEqual(ex.ErrorCode, MsalError.InvalidUserInstanceMetadata); + Assert.AreEqual(MsalError.InvalidUserInstanceMetadata, ex.ErrorCode); } [TestMethod] @@ -351,7 +351,7 @@ public void EnsureCreatePublicClientWithAzureAdMyOrgAndValidTenantSucceeds() Assert.AreEqual($"https://login.microsoftonline.com/{tenantId}/", pca.Authority); } - [DataTestMethod] + [TestMethod] [DataRow(AzureCloudInstance.AzurePublic, AadAuthorityAudience.AzureAdMultipleOrgs, TestConstants.AuthorityOrganizationsTenant, DisplayName = "AzurePublic + AzureAdMultipleOrgs")] [DataRow(AzureCloudInstance.AzurePublic, AadAuthorityAudience.AzureAdAndPersonalMicrosoftAccount, TestConstants.AuthorityCommonTenant, DisplayName = "AzurePublic + AzureAdAndPersonalMicrosoftAccount")] [DataRow(AzureCloudInstance.AzurePublic, AadAuthorityAudience.PersonalMicrosoftAccount, "https://login.microsoftonline.com/consumers/", DisplayName = "AzurePublic + PersonalMicrosoftAccount")] @@ -501,7 +501,7 @@ public void TestAadAuthorityWithInvalidSegmentCount() catch (Exception ex) { Assert.IsTrue(ex is ArgumentException); - Assert.IsTrue(ex.Message.Contains(MsalErrorMessage.AuthorityUriInvalidPath)); + Assert.Contains(MsalErrorMessage.AuthorityUriInvalidPath, ex.Message); } } diff --git a/tests/Microsoft.Identity.Test.Unit/AppTokenProviderTests.cs b/tests/Microsoft.Identity.Test.Unit/AppTokenProviderTests.cs index 9dcc882b9a..429550e9c2 100644 --- a/tests/Microsoft.Identity.Test.Unit/AppTokenProviderTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/AppTokenProviderTests.cs @@ -61,7 +61,7 @@ public async Task ValidateAppTokenProviderAsync() var tokens = app.AppTokenCacheInternal.Accessor.GetAllAccessTokens(); - Assert.AreEqual(1, tokens.Count); + Assert.HasCount(1, tokens); var token = tokens.FirstOrDefault(); Assert.IsNotNull(token); @@ -97,7 +97,7 @@ public async Task ValidateAppTokenProviderAsync() Assert.IsNotNull(result.AccessToken); Assert.AreEqual(TestConstants.DefaultAccessToken + differentScopesForAt, result.AccessToken); Assert.AreEqual(TokenSource.IdentityProvider, result.AuthenticationResultMetadata.TokenSource); - Assert.AreEqual(app.AppTokenCacheInternal.Accessor.GetAllAccessTokens().Count, 2); + Assert.HasCount(2, app.AppTokenCacheInternal.Accessor.GetAllAccessTokens()); Assert.AreEqual(3, callbackInvoked); // Acquire token from app provider with claims. Should not use cache @@ -112,7 +112,7 @@ public async Task ValidateAppTokenProviderAsync() } } - [DataTestMethod] + [TestMethod] [DataRow(3600, 0, 0)] [DataRow(3600, 500, 500)] [DataRow(7200, 0, 3600)] @@ -203,7 +203,7 @@ public async Task ParallelRequests_CallTokenEndpointOnceAsync() { // Increment identity hits count Interlocked.Increment(ref identityProviderHits); - Assert.IsTrue(identityProviderHits == 1); + Assert.AreEqual(1, identityProviderHits); } else { @@ -217,7 +217,7 @@ public async Task ParallelRequests_CallTokenEndpointOnceAsync() Debug.WriteLine($"Total Identity Hits: {identityProviderHits}"); Debug.WriteLine($"Total Cache Hits: {cacheHits}"); - Assert.IsTrue(cacheHits == 9); + Assert.AreEqual(9, cacheHits); harness.HttpManager.ClearQueue(); diff --git a/tests/Microsoft.Identity.Test.Unit/AuthExtension/AuthenticationOperationTests.cs b/tests/Microsoft.Identity.Test.Unit/AuthExtension/AuthenticationOperationTests.cs index 972b0af12e..dd5710a225 100644 --- a/tests/Microsoft.Identity.Test.Unit/AuthExtension/AuthenticationOperationTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/AuthExtension/AuthenticationOperationTests.cs @@ -62,12 +62,12 @@ public async Task Should_UseCustomRequestHeaders_And_StoreAdditionalParameters() .ConfigureAwait(false); Assert.AreEqual(TokenSource.Cache, result.AuthenticationResultMetadata.TokenSource); - Assert.IsTrue(result.AdditionalResponseParameters == null); + Assert.IsNull(result.AdditionalResponseParameters); Assert.AreEqual(expectedAt, result.AccessToken); } } - [DataTestMethod] // Fix for regression https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/issues/5261 + [TestMethod] // Fix for regression https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/issues/5261 [DataRow(false)] [DataRow(true)] public async Task Should_UseCustomRequestHeaders_And_StoreAdditionalParametersWithCaching(bool useSerializedCache) @@ -188,7 +188,7 @@ public async Task Should_UseEmptyExtension_And_Parameters() .ConfigureAwait(false); Assert.AreEqual(TokenSource.Cache, result.AuthenticationResultMetadata.TokenSource); - Assert.IsTrue(result.AdditionalResponseParameters == null); + Assert.IsNull(result.AdditionalResponseParameters); Assert.AreEqual(expectedAt, result.AccessToken); } } diff --git a/tests/Microsoft.Identity.Test.Unit/BrokerTests/BrokerRequestTests.cs b/tests/Microsoft.Identity.Test.Unit/BrokerTests/BrokerRequestTests.cs index 08ddb77646..c6a0f5dff8 100644 --- a/tests/Microsoft.Identity.Test.Unit/BrokerTests/BrokerRequestTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/BrokerTests/BrokerRequestTests.cs @@ -118,8 +118,8 @@ public void BrokerInteractionRequiredErrorResponseTest() Assert.IsNotNull(exc); Assert.AreEqual(MsalError.InteractionRequired, exc.ErrorCode); Assert.AreEqual(MsalErrorMessage.BrokerResponseError + MsalError.InteractionRequired, exc.Message); - Assert.AreEqual(exc.StatusCode, (int)HttpStatusCode.Unauthorized); - Assert.AreEqual(exc.ResponseBody, "SomeBody"); + Assert.AreEqual((int)HttpStatusCode.Unauthorized, exc.StatusCode); + Assert.AreEqual("SomeBody", exc.ResponseBody); Assert.IsNotNull(exc.Headers); }); } @@ -146,8 +146,8 @@ public void BrokerInvalidGrantErrorResponseTest() Assert.IsNotNull(exc); Assert.AreEqual(MsalError.InvalidGrantError, exc.ErrorCode); Assert.AreEqual(MsalErrorMessage.BrokerResponseError + MsalError.InvalidGrantError, exc.Message); - Assert.AreEqual(exc.StatusCode, (int)HttpStatusCode.Unauthorized); - Assert.AreEqual(exc.ResponseBody, "SomeBody"); + Assert.AreEqual((int)HttpStatusCode.Unauthorized, exc.StatusCode); + Assert.AreEqual("SomeBody", exc.ResponseBody); Assert.IsNotNull(exc.Headers); }); } @@ -200,7 +200,7 @@ public void BrokerInteractiveRequestTest() null, broker, "install_url"); - Assert.AreEqual(false, _brokerInteractiveRequest.Broker.IsBrokerInstalledAndInvokable(AuthorityType.Aad)); + Assert.IsFalse(_brokerInteractiveRequest.Broker.IsBrokerInstalledAndInvokable(AuthorityType.Aad)); } } @@ -224,7 +224,7 @@ public void BrokerSilentRequestTest() Assert.IsFalse(_brokerInteractiveRequest.Broker.IsBrokerInstalledAndInvokable(AuthorityType.Generic)); Assert.IsFalse(_brokerInteractiveRequest.Broker.IsBrokerInstalledAndInvokable(AuthorityType.Dsts)); - Assert.AreEqual(false, _brokerInteractiveRequest.Broker.IsBrokerInstalledAndInvokable(AuthorityType.Aad)); + Assert.IsFalse(_brokerInteractiveRequest.Broker.IsBrokerInstalledAndInvokable(AuthorityType.Aad)); } } @@ -400,9 +400,9 @@ public void CreateFromiOSBroker_HandlesNoErrorMetadata() Assert.AreEqual(TestConstants.TestErrCode, token.Error); Assert.AreEqual(TestConstants.iOSBrokerSuberrCode, token.SubError); Assert.AreEqual(TestConstants.iOSBrokerErrDescr, token.ErrorDescription); - Assert.AreEqual(null, token.AccountUserId); - Assert.AreEqual(null, token.TenantId); - Assert.AreEqual(null, token.Upn); + Assert.IsNull(token.AccountUserId); + Assert.IsNull(token.TenantId); + Assert.IsNull(token.Upn); } [TestMethod] @@ -421,7 +421,7 @@ public void CreateFromiOSBroker_HandlesNoAccountId() Assert.AreEqual(TestConstants.TestErrCode, token.Error); Assert.AreEqual(string.Empty, token.SubError); Assert.AreEqual(TestConstants.iOSBrokerErrDescr, token.ErrorDescription); - Assert.AreEqual(null, token.AccountUserId); + Assert.IsNull(token.AccountUserId); Assert.AreEqual(TestConstants.Username, token.Upn); } @@ -442,10 +442,10 @@ public void CreateFromiOSBroker_HandlesNoUpn() Assert.AreEqual(string.Empty, token.SubError); Assert.AreEqual(TestConstants.iOSBrokerErrDescr, token.ErrorDescription); Assert.AreEqual("test_home", token.AccountUserId); - Assert.AreEqual(null, token.Upn); + Assert.IsNull(token.Upn); } - [DataTestMethod] + [TestMethod] [DataRow(typeof(NullBroker))] [DataRow(typeof(IosBrokerMock))] [TestCategory(TestCategories.Regression)] //https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/issues/2706 @@ -473,7 +473,7 @@ public async Task NullAndIosBroker_GetAccounts_Async(Type brokerType) } } - [DataTestMethod] + [TestMethod] [DataRow(typeof(NullBroker))] [DataRow(typeof(IosBrokerMock))] [TestCategory(TestCategories.Regression)] //https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/issues/2706 @@ -761,7 +761,7 @@ public void NoTokenFoundThrowsUIRequiredTest() } catch (MsalUiRequiredException ex) { - Assert.IsTrue(ex.ErrorCode == BrokerResponseConst.AndroidNoTokenFound); + Assert.AreEqual(BrokerResponseConst.AndroidNoTokenFound, ex.ErrorCode); return; } @@ -780,7 +780,7 @@ public void NoAccountFoundThrowsUIRequiredTest() } catch (MsalUiRequiredException ex) { - Assert.IsTrue(ex.ErrorCode == BrokerResponseConst.AndroidNoAccountFound); + Assert.AreEqual(BrokerResponseConst.AndroidNoAccountFound, ex.ErrorCode); return; } @@ -799,7 +799,7 @@ public void InvalidRefreshTokenUsedThrowsUIRequiredTest() } catch (MsalUiRequiredException ex) { - Assert.IsTrue(ex.ErrorCode == BrokerResponseConst.AndroidInvalidRefreshToken); + Assert.AreEqual(BrokerResponseConst.AndroidInvalidRefreshToken, ex.ErrorCode); return; } @@ -864,7 +864,7 @@ public async Task MultiCloud_WithBroker_Async() Assert.AreEqual("login.microsoftonline.us", account.Environment); Assert.AreEqual(TestConstants.Utid, result.TenantId); - await Assert.ThrowsExceptionAsync( + await Assert.ThrowsAsync( async () => await globalPca.AcquireTokenSilent(TestConstants.s_graphScopes, PublicClientApplication.OperatingSystemAccount).ExecuteAsync().ConfigureAwait(false)).ConfigureAwait(false); } } diff --git a/tests/Microsoft.Identity.Test.Unit/BrokerTests/RuntimeBrokerTests.cs b/tests/Microsoft.Identity.Test.Unit/BrokerTests/RuntimeBrokerTests.cs index 01f55872c9..3e50cf46b8 100644 --- a/tests/Microsoft.Identity.Test.Unit/BrokerTests/RuntimeBrokerTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/BrokerTests/RuntimeBrokerTests.cs @@ -160,7 +160,7 @@ public async Task ATS_CallsLog_When_CalledAsync() } } - [DataTestMethod] + [TestMethod] [DataRow(Client.NativeInterop.LogLevel.Trace, Client.LogLevel.Verbose)] [DataRow(Client.NativeInterop.LogLevel.Debug, Client.LogLevel.Verbose)] [DataRow(Client.NativeInterop.LogLevel.Info, Client.LogLevel.Info)] @@ -181,7 +181,7 @@ public void LogEventRaised_MapsEvents_Correctly_When_No_Pii(Client.NativeInterop _logger.Received().Log(msalLogLevel, string.Empty, logMessage); } - [DataTestMethod] + [TestMethod] [DataRow(Client.NativeInterop.LogLevel.Trace, Client.LogLevel.Verbose)] [DataRow(Client.NativeInterop.LogLevel.Debug, Client.LogLevel.Verbose)] [DataRow(Client.NativeInterop.LogLevel.Info, Client.LogLevel.Info)] diff --git a/tests/Microsoft.Identity.Test.Unit/BrokerTests/WamGetAccountsTests.cs b/tests/Microsoft.Identity.Test.Unit/BrokerTests/WamGetAccountsTests.cs index 84d19c68c4..b4fb310c42 100644 --- a/tests/Microsoft.Identity.Test.Unit/BrokerTests/WamGetAccountsTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/BrokerTests/WamGetAccountsTests.cs @@ -51,7 +51,7 @@ public async Task WAM_AccountIdWriteback_Async() // Assert var wamAccountIds = (accounts.Single() as Account).WamAccountIds; - Assert.AreEqual(1, wamAccountIds.Count); + Assert.HasCount(1, wamAccountIds); Assert.AreEqual("wam1", wamAccountIds[TestConstants.ClientId]); var pca2 = PublicClientApplicationBuilder.Create(TestConstants.ClientId2) @@ -118,7 +118,7 @@ public async Task WAM_AccountIds_GetMerged_Async() // Assert var wamAccountIds = (accounts1.Single() as Account).WamAccountIds; - Assert.AreEqual(2, wamAccountIds.Count); + Assert.HasCount(2, wamAccountIds); Assert.AreEqual("wam2", wamAccountIds[TestConstants.ClientId]); Assert.AreEqual("wam3", wamAccountIds[TestConstants.ClientId2]); CoreAssert.AssertDictionariesAreEqual(wamAccountIds, (accounts2.Single() as Account).WamAccountIds, StringComparer.Ordinal); @@ -158,7 +158,7 @@ public async Task GetAccounts_Returns_Both_WAM_And_Cache_Accounts_Async() // Assert Assert.AreEqual(2, accounts.Count()); var wamAccountIds = (accounts.Single(acc => acc.HomeAccountId.Identifier == commonAccId) as Account).WamAccountIds; - Assert.AreEqual(1, wamAccountIds.Count); + Assert.HasCount(1, wamAccountIds); Assert.AreEqual("wam_acc_id", wamAccountIds[TestConstants.ClientId]); } } diff --git a/tests/Microsoft.Identity.Test.Unit/CacheExtension/IntegrationTests.cs b/tests/Microsoft.Identity.Test.Unit/CacheExtension/IntegrationTests.cs index 3f5aed6822..cf846647e3 100644 --- a/tests/Microsoft.Identity.Test.Unit/CacheExtension/IntegrationTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/CacheExtension/IntegrationTests.cs @@ -87,7 +87,7 @@ public void ImportExport() string dataString = "Hello World"; byte[] dataBytes = Encoding.UTF8.GetBytes(dataString); var result = _cacheHelper.LoadUnencryptedTokenCache(); - Assert.AreEqual(0, result.Length); + Assert.IsEmpty(result); _cacheHelper.SaveUnencryptedTokenCache(dataBytes); byte[] actualData = _cacheHelper.LoadUnencryptedTokenCache(); diff --git a/tests/Microsoft.Identity.Test.Unit/CacheExtension/MacKeyChainTests.cs b/tests/Microsoft.Identity.Test.Unit/CacheExtension/MacKeyChainTests.cs index fa9d67841f..26deca9c1c 100644 --- a/tests/Microsoft.Identity.Test.Unit/CacheExtension/MacKeyChainTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/CacheExtension/MacKeyChainTests.cs @@ -170,8 +170,7 @@ private void VerifyKeyIsNull(string serviceName, string accountName) if (_macOSKeychain.Get(serviceName, accountName) != null) { Assert.Fail( - "key exists when it shouldn't be. keychainData=\"{0}\"", - _macOSKeychain.Get(serviceName, accountName).Password); + $"key exists when it shouldn't be. keychainData=\"{_macOSKeychain.Get(serviceName, accountName).Password}\""); } } } diff --git a/tests/Microsoft.Identity.Test.Unit/CacheExtension/MsalCacheHelperTests.cs b/tests/Microsoft.Identity.Test.Unit/CacheExtension/MsalCacheHelperTests.cs index 06c2069d0c..a12b570866 100644 --- a/tests/Microsoft.Identity.Test.Unit/CacheExtension/MsalCacheHelperTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/CacheExtension/MsalCacheHelperTests.cs @@ -247,7 +247,7 @@ public void LockTimeoutTest() // Wait for the seconf thread to finish resetEvent1.Wait(); - Assert.IsTrue(getTime.ElapsedMilliseconds > 2000); + Assert.IsGreaterThan(2000, getTime.ElapsedMilliseconds); } [RunOnWindows] @@ -358,7 +358,7 @@ public async Task RegressionTest_CorruptedCacheIsDeleted_NoEvent_Async() .ConfigureAwait(false); // Assert - Assert.AreEqual(ex.ErrorCode, "json_parse_failed"); + Assert.AreEqual("json_parse_failed", ex.ErrorCode); byte[] data = storage.ReadData(); Assert.IsFalse(data.Any(), "Cache is corrupt, so it should have been deleted"); } diff --git a/tests/Microsoft.Identity.Test.Unit/CacheExtension/MsalCacheStorageTests.cs b/tests/Microsoft.Identity.Test.Unit/CacheExtension/MsalCacheStorageTests.cs index ea17044319..971de16d09 100644 --- a/tests/Microsoft.Identity.Test.Unit/CacheExtension/MsalCacheStorageTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/CacheExtension/MsalCacheStorageTests.cs @@ -101,7 +101,7 @@ public void CacheStorageReadCanHandleReadingNull() byte[] result = storage.ReadData(); // Assert - Assert.AreEqual(0, result.Length); + Assert.IsEmpty(result); } @@ -132,9 +132,9 @@ public void CacheStorageCanHandleMultipleExceptionsWhenReading() } // Assert - Assert.IsTrue(stringListener.CurrentLog.Contains("TestSource Error")); - Assert.IsTrue(stringListener.CurrentLog.Contains("InvalidOperationException")); - Assert.IsTrue(stringListener.CurrentLog.Contains("some error")); + Assert.Contains("TestSource Error", stringListener.CurrentLog); + Assert.Contains("InvalidOperationException", stringListener.CurrentLog); + Assert.Contains("some error", stringListener.CurrentLog); } [TestMethod] diff --git a/tests/Microsoft.Identity.Test.Unit/CacheExtension/TraceStringListener.cs b/tests/Microsoft.Identity.Test.Unit/CacheExtension/TraceStringListener.cs index 87b6ee1a0b..d00c3bc6f8 100644 --- a/tests/Microsoft.Identity.Test.Unit/CacheExtension/TraceStringListener.cs +++ b/tests/Microsoft.Identity.Test.Unit/CacheExtension/TraceStringListener.cs @@ -39,7 +39,7 @@ public override void WriteLine(string message) public void AssertContains(string needle) { - Assert.IsTrue(CurrentLog.Contains(needle)); + Assert.Contains(needle, CurrentLog); } private static string FormatLogMessage(string message) diff --git a/tests/Microsoft.Identity.Test.Unit/CacheTests/CacheFailureTests.cs b/tests/Microsoft.Identity.Test.Unit/CacheTests/CacheFailureTests.cs index a3ee824706..383636d4ec 100644 --- a/tests/Microsoft.Identity.Test.Unit/CacheTests/CacheFailureTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/CacheTests/CacheFailureTests.cs @@ -47,8 +47,8 @@ public async Task MsalOnly_FailToDeserializeTestsAsync() Assert.IsNotNull(cacheReadException); Assert.AreEqual(ex, cacheReadException); - Assert.IsTrue(ex.Message.Contains("Lorem")); - Assert.IsFalse(ex.Message.Contains("LoremIpsum")); + Assert.Contains("Lorem", ex.Message); + Assert.DoesNotContain("LoremIpsum", ex.Message); } } diff --git a/tests/Microsoft.Identity.Test.Unit/CacheTests/CacheFallbackOperationsTests.cs b/tests/Microsoft.Identity.Test.Unit/CacheTests/CacheFallbackOperationsTests.cs index b5981956b4..8df57ae280 100644 --- a/tests/Microsoft.Identity.Test.Unit/CacheTests/CacheFallbackOperationsTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/CacheTests/CacheFallbackOperationsTests.cs @@ -391,7 +391,7 @@ private void AssertCacheEntryCount(int expectedEntryCount) { IDictionary cache = AdalCacheOperations.Deserialize(_logger, _legacyCachePersistence.LoadCache()); - Assert.AreEqual(expectedEntryCount, cache.Count); + Assert.HasCount(expectedEntryCount, cache); } [TestMethod] @@ -401,7 +401,7 @@ public void RemoveAdalUser_RemovesUserNoClientInfo_And_NoDisplayName() LegacyTokenCacheHelper.PopulateLegacyCache(_logger, _legacyCachePersistence); IDictionary adalCacheBeforeDelete = AdalCacheOperations.Deserialize(_logger, _legacyCachePersistence.LoadCache()); - Assert.AreEqual(6, adalCacheBeforeDelete.Count); + Assert.HasCount(6, adalCacheBeforeDelete); // Act - nothing happens and a message is logged CacheFallbackOperations.RemoveAdalUser( diff --git a/tests/Microsoft.Identity.Test.Unit/CacheTests/CacheSerializationTests.cs b/tests/Microsoft.Identity.Test.Unit/CacheTests/CacheSerializationTests.cs index 5505ee114e..f6cae092b2 100644 --- a/tests/Microsoft.Identity.Test.Unit/CacheTests/CacheSerializationTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/CacheTests/CacheSerializationTests.cs @@ -420,10 +420,10 @@ public void TestSerializeAccountWithWamId() item.WamAccountIds = new Dictionary() { { "client_id_1", "wam_id_1" }, { "client_id_2", "wam_id_2" } }; string asJson = item.ToJsonString(); - Assert.IsTrue(asJson.Contains(@" ""wam_account_ids"": { + Assert.Contains(@" ""wam_account_ids"": { ""client_id_1"": ""wam_id_1"", ""client_id_2"": ""wam_id_2"" - }")); + }", asJson); var item2 = MsalAccountCacheItem.FromJsonString(asJson); AssertAccountCacheItemsAreEqual(item, item2); @@ -615,8 +615,8 @@ public void TestSerializeContainsNoNulls() byte[] bytes = s1.Serialize(null); string json = CoreHelpers.ByteArrayToString(bytes); - Assert.IsTrue(json.Contains(prefix)); - Assert.IsFalse(json.ToLowerInvariant().Contains("null")); + Assert.Contains(prefix, json); + Assert.DoesNotContain("null", json.ToLowerInvariant()); } [TestMethod] @@ -709,11 +709,11 @@ public void TestMsalNet2XCacheSerializationInterop() byte[] bytes = File.ReadAllBytes(binFilePath); s.Deserialize(bytes, false); - Assert.AreEqual(1, accessor.GetAllAccessTokens().Count); - Assert.AreEqual(1, accessor.GetAllRefreshTokens().Count); - Assert.AreEqual(1, accessor.GetAllIdTokens().Count); - Assert.AreEqual(1, accessor.GetAllAccounts().Count); - Assert.AreEqual(0, accessor.GetAllAppMetadata().Count); + Assert.HasCount(1, accessor.GetAllAccessTokens()); + Assert.HasCount(1, accessor.GetAllRefreshTokens()); + Assert.HasCount(1, accessor.GetAllIdTokens()); + Assert.HasCount(1, accessor.GetAllAccounts()); + Assert.IsEmpty(accessor.GetAllAppMetadata()); MsalAccessTokenCacheItem expectedAccessTokenItem = new MsalAccessTokenCacheItem( "login.windows.net", @@ -769,10 +769,10 @@ public void TestMsalNet2XCacheSerializationInterop() private void AssertAccessorsAreEqual(ITokenCacheAccessor expected, ITokenCacheAccessor actual) { - Assert.AreEqual(expected.GetAllAccessTokens().Count, actual.GetAllAccessTokens().Count); - Assert.AreEqual(expected.GetAllRefreshTokens().Count, actual.GetAllRefreshTokens().Count); - Assert.AreEqual(expected.GetAllIdTokens().Count, actual.GetAllIdTokens().Count); - Assert.AreEqual(expected.GetAllAccounts().Count, actual.GetAllAccounts().Count); + Assert.HasCount(expected.GetAllAccessTokens().Count, actual.GetAllAccessTokens()); + Assert.HasCount(expected.GetAllRefreshTokens().Count, actual.GetAllRefreshTokens()); + Assert.HasCount(expected.GetAllIdTokens().Count, actual.GetAllIdTokens()); + Assert.HasCount(expected.GetAllAccounts().Count, actual.GetAllAccounts()); } private void AssertContainsKey(JObject j, string key) diff --git a/tests/Microsoft.Identity.Test.Unit/CacheTests/CacheSyncronizationTests.cs b/tests/Microsoft.Identity.Test.Unit/CacheTests/CacheSyncronizationTests.cs index 21b5520cbb..002033743f 100644 --- a/tests/Microsoft.Identity.Test.Unit/CacheTests/CacheSyncronizationTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/CacheTests/CacheSyncronizationTests.cs @@ -49,7 +49,7 @@ private async Task RunSemaphoreTestAsync(bool useCacheSyncronization) var result = await app.AcquireTokenForClient(TestConstants.s_scope.ToArray()) .ExecuteAsync() .ConfigureAwait(false); - Assert.IsTrue(result.AuthenticationResultMetadata.TokenSource == TokenSource.IdentityProvider); + Assert.AreEqual(TokenSource.IdentityProvider, result.AuthenticationResultMetadata.TokenSource); var blockingTask = RunAsync(inMemoryTokenCache, app, true); var nonBlockingTask1 = RunAsync(inMemoryTokenCache, app, false); @@ -67,8 +67,8 @@ private async Task RunSemaphoreTestAsync(bool useCacheSyncronization) Assert.IsTrue(nonBlockingTask1.IsCompleted); Assert.IsTrue(nonBlockingTask2.IsCompleted); Assert.IsFalse(blockingTask.IsCompleted, "The blocking task should still be blocked"); - Assert.IsTrue(nonBlockingTask1.Result.AuthenticationResultMetadata.TokenSource == TokenSource.Cache); - Assert.IsTrue(nonBlockingTask2.Result.AuthenticationResultMetadata.TokenSource == TokenSource.Cache); + Assert.AreEqual(TokenSource.Cache, nonBlockingTask1.Result.AuthenticationResultMetadata.TokenSource); + Assert.AreEqual(TokenSource.Cache, nonBlockingTask2.Result.AuthenticationResultMetadata.TokenSource); } } } diff --git a/tests/Microsoft.Identity.Test.Unit/CacheTests/InMemoryPartitionedTokenCacheAccessorTests.cs b/tests/Microsoft.Identity.Test.Unit/CacheTests/InMemoryPartitionedTokenCacheAccessorTests.cs index c46ba5d9a0..f1848b43fe 100644 --- a/tests/Microsoft.Identity.Test.Unit/CacheTests/InMemoryPartitionedTokenCacheAccessorTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/CacheTests/InMemoryPartitionedTokenCacheAccessorTests.cs @@ -17,7 +17,7 @@ namespace Microsoft.Identity.Test.Unit.CacheTests public class InMemoryPartitionedTokenCacheAccessorTests { #region Access token tests - [DataTestMethod] + [TestMethod] [DataRow(true)] [DataRow(false)] public void SaveAccessToken_Test(bool isAppCache) @@ -29,8 +29,8 @@ public void SaveAccessToken_Test(bool isAppCache) // Assert: Save with new item accessor.SaveAccessToken(at1); - Assert.AreEqual(1, accessor.GetAllAccessTokens().Count); - Assert.AreEqual(1, GetAccessTokenCache(accessor, isAppCache).Count); + Assert.HasCount(1, accessor.GetAllAccessTokens()); + Assert.HasCount(1, GetAccessTokenCache(accessor, isAppCache)); string partitionKey1 = GetPartitionKey(isAppCache, at1); Assert.IsNotNull(GetAccessTokenCache(accessor, isAppCache)[partitionKey1][at1.CacheKey]); @@ -39,8 +39,8 @@ public void SaveAccessToken_Test(bool isAppCache) // Assert: Save under the existing partition accessor.SaveAccessToken(at2); - Assert.AreEqual(2, accessor.GetAllAccessTokens().Count); - Assert.AreEqual(1, GetAccessTokenCache(accessor, isAppCache).Count); + Assert.HasCount(2, accessor.GetAllAccessTokens()); + Assert.HasCount(1, GetAccessTokenCache(accessor, isAppCache)); Assert.IsNotNull(GetAccessTokenCache(accessor, isAppCache)[partitionKey1][at2.CacheKey]); var at3 = TokenCacheHelper.CreateAccessTokenItem("scope1", "tenant2", "homeAccountId2"); @@ -50,13 +50,13 @@ public void SaveAccessToken_Test(bool isAppCache) // Assert: Save overwrites the existing token accessor.SaveAccessToken(at3); - Assert.AreEqual(3, accessor.GetAllAccessTokens().Count); - Assert.AreEqual(2, GetAccessTokenCache(accessor, isAppCache).Count); + Assert.HasCount(3, accessor.GetAllAccessTokens()); + Assert.HasCount(2, GetAccessTokenCache(accessor, isAppCache)); string partitionKey2 = GetPartitionKey(isAppCache, at3); Assert.IsNotNull(GetAccessTokenCache(accessor, isAppCache)[partitionKey2][at3.CacheKey]); } - [DataTestMethod] + [TestMethod] [DataRow(true)] [DataRow(false)] public void DeleteAccessToken_Test(bool isAppCache) @@ -73,15 +73,15 @@ public void DeleteAccessToken_Test(bool isAppCache) accessor.SaveAccessToken(at2); accessor.SaveAccessToken(at3); - Assert.AreEqual(3, accessor.GetAllAccessTokens().Count); + Assert.HasCount(3, accessor.GetAllAccessTokens()); // Assert: Delete an existing item accessor.DeleteAccessToken(at1); - Assert.AreEqual(2, accessor.GetAllAccessTokens().Count); + Assert.HasCount(2, accessor.GetAllAccessTokens()); } - [DataTestMethod] + [TestMethod] [DataRow(true)] [DataRow(false)] public void GetAllAccessTokens_Test(bool isAppCache) @@ -94,22 +94,22 @@ public void GetAllAccessTokens_Test(bool isAppCache) string partitionKey2 = GetPartitionKey(isAppCache, at3); // Assert: Returns empty collection - Assert.AreEqual(0, accessor.GetAllAccessTokens().Count); - Assert.AreEqual(0, accessor.GetAllAccessTokens(partitionKey1).Count); + Assert.IsEmpty(accessor.GetAllAccessTokens()); + Assert.IsEmpty(accessor.GetAllAccessTokens(partitionKey1)); accessor.SaveAccessToken(at1); accessor.SaveAccessToken(at2); accessor.SaveAccessToken(at3); // Assert: Get all tokens and get all tokens by partition key - Assert.AreEqual(3, accessor.GetAllAccessTokens().Count); - Assert.AreEqual(2, accessor.GetAllAccessTokens(partitionKey1).Count); - Assert.AreEqual(1, accessor.GetAllAccessTokens(partitionKey2).Count); + Assert.HasCount(3, accessor.GetAllAccessTokens()); + Assert.HasCount(2, accessor.GetAllAccessTokens(partitionKey1)); + Assert.HasCount(1, accessor.GetAllAccessTokens(partitionKey2)); } #endregion #region App metadata tests - [DataTestMethod] + [TestMethod] [DataRow(true)] [DataRow(false)] @@ -121,15 +121,15 @@ public void SaveAppMetadata_Test(bool isAppCache) accessor.SaveAppMetadata(TokenCacheHelper.CreateAppMetadataItem()); accessor.SaveAppMetadata(TokenCacheHelper.CreateAppMetadataItem()); - Assert.AreEqual(1, GetAppMetadataCache(accessor, isAppCache).Count); + Assert.HasCount(1, GetAppMetadataCache(accessor, isAppCache)); // Assert: Different key accessor.SaveAppMetadata(TokenCacheHelper.CreateAppMetadataItem(TestConstants.ClientId2)); - Assert.AreEqual(2, GetAppMetadataCache(accessor, isAppCache).Count); + Assert.HasCount(2, GetAppMetadataCache(accessor, isAppCache)); } - [DataTestMethod] + [TestMethod] [DataRow(true)] [DataRow(false)] @@ -142,7 +142,7 @@ public void GetAppMetadata_Test(bool isAppCache) Assert.AreEqual(appMetadataItem.CacheKey, accessor.GetAppMetadata(appMetadataItem).CacheKey); } - [DataTestMethod] + [TestMethod] [DataRow(true)] [DataRow(false)] @@ -154,14 +154,14 @@ public void GetAllAppMetadata_Test(bool isAppCache) accessor.SaveAppMetadata(TokenCacheHelper.CreateAppMetadataItem()); accessor.SaveAppMetadata(TokenCacheHelper.CreateAppMetadataItem()); - Assert.AreEqual(1, GetAppMetadataCache(accessor, isAppCache).Count); - Assert.AreEqual(1, accessor.GetAllAppMetadata().Count); + Assert.HasCount(1, GetAppMetadataCache(accessor, isAppCache)); + Assert.HasCount(1, accessor.GetAllAppMetadata()); // Assert: Different key accessor.SaveAppMetadata(TokenCacheHelper.CreateAppMetadataItem(TestConstants.ClientId2)); - Assert.AreEqual(2, GetAppMetadataCache(accessor, isAppCache).Count); - Assert.AreEqual(2, accessor.GetAllAppMetadata().Count); + Assert.HasCount(2, GetAppMetadataCache(accessor, isAppCache)); + Assert.HasCount(2, accessor.GetAllAppMetadata()); } #endregion @@ -176,8 +176,8 @@ public void SaveRefreshToken_Test() // Assert: Saves with new item accessor.SaveRefreshToken(rt1); - Assert.AreEqual(1, accessor.GetAllRefreshTokens().Count); - Assert.AreEqual(1, accessor.RefreshTokenCacheDictionary.Count); + Assert.HasCount(1, accessor.GetAllRefreshTokens()); + Assert.HasCount(1, accessor.RefreshTokenCacheDictionary); string partitionKey1 = CacheKeyFactory.GetKeyFromCachedItem(rt1); Assert.IsNotNull(accessor.RefreshTokenCacheDictionary[partitionKey1][rt1.CacheKey]); @@ -186,8 +186,8 @@ public void SaveRefreshToken_Test() // Assert: Save under the existing partition accessor.SaveRefreshToken(rt2); - Assert.AreEqual(2, accessor.GetAllRefreshTokens().Count); - Assert.AreEqual(1, accessor.RefreshTokenCacheDictionary.Count); + Assert.HasCount(2, accessor.GetAllRefreshTokens()); + Assert.HasCount(1, accessor.RefreshTokenCacheDictionary); Assert.IsNotNull(accessor.RefreshTokenCacheDictionary[partitionKey1][rt2.CacheKey]); var rt3 = TokenCacheHelper.CreateRefreshTokenItem("userAssertion2", "homeAccountId"); @@ -197,8 +197,8 @@ public void SaveRefreshToken_Test() // Assert: Save overwrites the existing token accessor.SaveRefreshToken(rt3); - Assert.AreEqual(3, accessor.GetAllRefreshTokens().Count); - Assert.AreEqual(2, accessor.RefreshTokenCacheDictionary.Count); + Assert.HasCount(3, accessor.GetAllRefreshTokens()); + Assert.HasCount(2, accessor.RefreshTokenCacheDictionary); string partitionKey2 = CacheKeyFactory.GetKeyFromCachedItem(rt3); Assert.IsNotNull(accessor.RefreshTokenCacheDictionary[partitionKey2][rt3.CacheKey]); } @@ -218,12 +218,12 @@ public void DeleteRefreshToken_Test() accessor.SaveRefreshToken(rt2); accessor.SaveRefreshToken(rt3); - Assert.AreEqual(3, accessor.GetAllRefreshTokens().Count); + Assert.HasCount(3, accessor.GetAllRefreshTokens()); // Assert: Delete on existing item accessor.DeleteRefreshToken(rt1); - Assert.AreEqual(2, accessor.GetAllRefreshTokens().Count); + Assert.HasCount(2, accessor.GetAllRefreshTokens()); } [TestMethod] @@ -237,17 +237,17 @@ public void GetAllRefreshTokens_Test() string partitionKey2 = CacheKeyFactory.GetKeyFromCachedItem(rt3); // Assert: Returns empty collection - Assert.AreEqual(0, accessor.GetAllRefreshTokens().Count); - Assert.AreEqual(0, accessor.GetAllRefreshTokens(partitionKey1).Count); + Assert.IsEmpty(accessor.GetAllRefreshTokens()); + Assert.IsEmpty(accessor.GetAllRefreshTokens(partitionKey1)); accessor.SaveRefreshToken(rt1); accessor.SaveRefreshToken(rt2); accessor.SaveRefreshToken(rt3); // Assert: Get all tokens and get all tokens by partition key - Assert.AreEqual(3, accessor.GetAllRefreshTokens().Count); - Assert.AreEqual(2, accessor.GetAllRefreshTokens(partitionKey1).Count); - Assert.AreEqual(1, accessor.GetAllRefreshTokens(partitionKey2).Count); + Assert.HasCount(3, accessor.GetAllRefreshTokens()); + Assert.HasCount(2, accessor.GetAllRefreshTokens(partitionKey1)); + Assert.HasCount(1, accessor.GetAllRefreshTokens(partitionKey2)); } #endregion @@ -262,8 +262,8 @@ public void SaveIdToken_Test() // Assert: Saves with new item accessor.SaveIdToken(idt1); - Assert.AreEqual(1, accessor.GetAllIdTokens().Count); - Assert.AreEqual(1, accessor.IdTokenCacheDictionary.Count); + Assert.HasCount(1, accessor.GetAllIdTokens()); + Assert.HasCount(1, accessor.IdTokenCacheDictionary); string partitionKey1 = CacheKeyFactory.GetKeyFromCachedItem(idt1); Assert.IsNotNull(accessor.IdTokenCacheDictionary[partitionKey1][idt1.CacheKey]); @@ -272,8 +272,8 @@ public void SaveIdToken_Test() // Assert: Save under the existing partition accessor.SaveIdToken(idt2); - Assert.AreEqual(2, accessor.GetAllIdTokens().Count); - Assert.AreEqual(1, accessor.IdTokenCacheDictionary.Count); + Assert.HasCount(2, accessor.GetAllIdTokens()); + Assert.HasCount(1, accessor.IdTokenCacheDictionary); Assert.IsNotNull(accessor.IdTokenCacheDictionary[partitionKey1][idt2.CacheKey]); var idt3 = TokenCacheHelper.CreateIdTokenCacheItem("tenant1", "homeAccountId2"); @@ -283,8 +283,8 @@ public void SaveIdToken_Test() // Assert: Save overwrites the existing token accessor.SaveIdToken(idt3); - Assert.AreEqual(3, accessor.GetAllIdTokens().Count); - Assert.AreEqual(2, accessor.IdTokenCacheDictionary.Count); + Assert.HasCount(3, accessor.GetAllIdTokens()); + Assert.HasCount(2, accessor.IdTokenCacheDictionary); string partitionKey2 = CacheKeyFactory.GetKeyFromCachedItem(idt3); Assert.IsNotNull(accessor.IdTokenCacheDictionary[partitionKey2][idt3.CacheKey]); } @@ -304,12 +304,12 @@ public void DeleteIdToken_Test() accessor.SaveIdToken(idt2); accessor.SaveIdToken(idt3); - Assert.AreEqual(3, accessor.GetAllIdTokens().Count); + Assert.HasCount(3, accessor.GetAllIdTokens()); // Assert: Delete on existing item accessor.DeleteIdToken(idt1); - Assert.AreEqual(2, accessor.GetAllIdTokens().Count); + Assert.HasCount(2, accessor.GetAllIdTokens()); } [TestMethod] @@ -345,17 +345,17 @@ public void GetAllIdTokens_Test() string partitionKey2 = CacheKeyFactory.GetKeyFromCachedItem(idt2); // Assert: Returns empty collection - Assert.AreEqual(0, accessor.GetAllIdTokens().Count); - Assert.AreEqual(0, accessor.GetAllIdTokens(partitionKey1).Count); + Assert.IsEmpty(accessor.GetAllIdTokens()); + Assert.IsEmpty(accessor.GetAllIdTokens(partitionKey1)); accessor.SaveIdToken(idt1); accessor.SaveIdToken(idt2); accessor.SaveIdToken(idt3); // Assert: Get all tokens and get all tokens by partition key - Assert.AreEqual(3, accessor.GetAllIdTokens().Count); - Assert.AreEqual(2, accessor.GetAllIdTokens(partitionKey1).Count); - Assert.AreEqual(1, accessor.GetAllIdTokens(partitionKey2).Count); + Assert.HasCount(3, accessor.GetAllIdTokens()); + Assert.HasCount(2, accessor.GetAllIdTokens(partitionKey1)); + Assert.HasCount(1, accessor.GetAllIdTokens(partitionKey2)); } #endregion @@ -370,8 +370,8 @@ public void SaveAccount_Test() // Assert: Saves with new item accessor.SaveAccount(acc1); - Assert.AreEqual(1, accessor.GetAllAccounts().Count); - Assert.AreEqual(1, accessor.AccountCacheDictionary.Count); + Assert.HasCount(1, accessor.GetAllAccounts()); + Assert.HasCount(1, accessor.AccountCacheDictionary); string partitionKey1 = CacheKeyFactory.GetKeyFromCachedItem(acc1); Assert.IsNotNull(accessor.AccountCacheDictionary[partitionKey1][acc1.CacheKey]); @@ -380,8 +380,8 @@ public void SaveAccount_Test() // Assert: Save under the existing partition accessor.SaveAccount(acc2); - Assert.AreEqual(2, accessor.GetAllAccounts().Count); - Assert.AreEqual(1, accessor.AccountCacheDictionary.Count); + Assert.HasCount(2, accessor.GetAllAccounts()); + Assert.HasCount(1, accessor.AccountCacheDictionary); Assert.IsNotNull(accessor.AccountCacheDictionary[partitionKey1][acc2.CacheKey]); var acc3 = TokenCacheHelper.CreateAccountItem("tenant1", "homeAccountId2"); @@ -391,8 +391,8 @@ public void SaveAccount_Test() // Assert: Save overwrites the existing token accessor.SaveAccount(acc3); - Assert.AreEqual(3, accessor.GetAllAccounts().Count); - Assert.AreEqual(2, accessor.AccountCacheDictionary.Count); + Assert.HasCount(3, accessor.GetAllAccounts()); + Assert.HasCount(2, accessor.AccountCacheDictionary); string partitionKey2 = CacheKeyFactory.GetKeyFromCachedItem(acc3); Assert.IsNotNull(accessor.AccountCacheDictionary[partitionKey2][acc3.CacheKey]); } @@ -412,12 +412,12 @@ public void DeleteAccount_Test() accessor.SaveAccount(acc2); accessor.SaveAccount(acc3); - Assert.AreEqual(3, accessor.GetAllAccounts().Count); + Assert.HasCount(3, accessor.GetAllAccounts()); // Assert: Delete on existing item accessor.DeleteAccount(acc1); - Assert.AreEqual(2, accessor.GetAllAccounts().Count); + Assert.HasCount(2, accessor.GetAllAccounts()); } [TestMethod] @@ -451,17 +451,17 @@ public void GetAllAccounts_Test() string partitionKey2 = CacheKeyFactory.GetKeyFromCachedItem(acc2); // Assert: Returns empty collection - Assert.AreEqual(0, accessor.GetAllAccounts().Count); - Assert.AreEqual(0, accessor.GetAllAccounts(partitionKey1).Count); + Assert.IsEmpty(accessor.GetAllAccounts()); + Assert.IsEmpty(accessor.GetAllAccounts(partitionKey1)); accessor.SaveAccount(acc1); accessor.SaveAccount(acc2); accessor.SaveAccount(acc3); // Assert: Get all tokens and get all tokens by partition key - Assert.AreEqual(3, accessor.GetAllAccounts().Count); - Assert.AreEqual(2, accessor.GetAllAccounts(partitionKey1).Count); - Assert.AreEqual(1, accessor.GetAllAccounts(partitionKey2).Count); + Assert.HasCount(3, accessor.GetAllAccounts()); + Assert.HasCount(2, accessor.GetAllAccounts(partitionKey1)); + Assert.HasCount(1, accessor.GetAllAccounts(partitionKey2)); } #endregion @@ -472,11 +472,11 @@ public void ClearCache_AppCache_Test() var accessor = new InMemoryPartitionedAppTokenCacheAccessor(new NullLogger(), null); accessor.SaveAccessToken(TokenCacheHelper.CreateAccessTokenItem()); - Assert.AreEqual(1, accessor.AccessTokenCacheDictionary.Count); + Assert.HasCount(1, accessor.AccessTokenCacheDictionary); accessor.Clear(); - Assert.AreEqual(0, accessor.AccessTokenCacheDictionary.Count); + Assert.IsEmpty(accessor.AccessTokenCacheDictionary); } [TestMethod] @@ -488,17 +488,17 @@ public void ClearCache_UserCache_Test() accessor.SaveIdToken(TokenCacheHelper.CreateIdTokenCacheItem()); accessor.SaveAccount(TokenCacheHelper.CreateAccountItem()); - Assert.AreEqual(1, accessor.AccessTokenCacheDictionary.Count); - Assert.AreEqual(1, accessor.RefreshTokenCacheDictionary.Count); - Assert.AreEqual(1, accessor.IdTokenCacheDictionary.Count); - Assert.AreEqual(1, accessor.AccountCacheDictionary.Count); + Assert.HasCount(1, accessor.AccessTokenCacheDictionary); + Assert.HasCount(1, accessor.RefreshTokenCacheDictionary); + Assert.HasCount(1, accessor.IdTokenCacheDictionary); + Assert.HasCount(1, accessor.AccountCacheDictionary); accessor.Clear(); - Assert.AreEqual(0, accessor.AccessTokenCacheDictionary.Count); - Assert.AreEqual(0, accessor.RefreshTokenCacheDictionary.Count); - Assert.AreEqual(0, accessor.IdTokenCacheDictionary.Count); - Assert.AreEqual(0, accessor.AccountCacheDictionary.Count); + Assert.IsEmpty(accessor.AccessTokenCacheDictionary); + Assert.IsEmpty(accessor.RefreshTokenCacheDictionary); + Assert.IsEmpty(accessor.IdTokenCacheDictionary); + Assert.IsEmpty(accessor.AccountCacheDictionary); } [TestMethod] @@ -550,41 +550,41 @@ public void NoSupportedMethods_AppCache_Test() { var accessor = new InMemoryPartitionedAppTokenCacheAccessor(new NullLogger(), null); - var ex = Assert.ThrowsException(() => accessor.SaveRefreshToken(TokenCacheHelper.CreateRefreshTokenItem())); + var ex = Assert.Throws(() => accessor.SaveRefreshToken(TokenCacheHelper.CreateRefreshTokenItem())); Assert.AreEqual(MsalError.CombinedUserAppCacheNotSupported, ex.ErrorCode); Assert.AreEqual(MsalErrorMessage.CombinedUserAppCacheNotSupported, ex.Message); - ex = Assert.ThrowsException(() => accessor.SaveIdToken(TokenCacheHelper.CreateIdTokenCacheItem())); + ex = Assert.Throws(() => accessor.SaveIdToken(TokenCacheHelper.CreateIdTokenCacheItem())); Assert.AreEqual(MsalError.CombinedUserAppCacheNotSupported, ex.ErrorCode); Assert.AreEqual(MsalErrorMessage.CombinedUserAppCacheNotSupported, ex.Message); - ex = Assert.ThrowsException(() => accessor.SaveAccount(TokenCacheHelper.CreateAccountItem())); + ex = Assert.Throws(() => accessor.SaveAccount(TokenCacheHelper.CreateAccountItem())); Assert.AreEqual(MsalError.CombinedUserAppCacheNotSupported, ex.ErrorCode); Assert.AreEqual(MsalErrorMessage.CombinedUserAppCacheNotSupported, ex.Message); - ex = Assert.ThrowsException(() => accessor.GetIdToken(TokenCacheHelper.CreateAccessTokenItem())); + ex = Assert.Throws(() => accessor.GetIdToken(TokenCacheHelper.CreateAccessTokenItem())); Assert.AreEqual(MsalError.CombinedUserAppCacheNotSupported, ex.ErrorCode); Assert.AreEqual(MsalErrorMessage.CombinedUserAppCacheNotSupported, ex.Message); - ex = Assert.ThrowsException(() => accessor.GetAccount(TokenCacheHelper.CreateAccountItem())); + ex = Assert.Throws(() => accessor.GetAccount(TokenCacheHelper.CreateAccountItem())); Assert.AreEqual(MsalError.CombinedUserAppCacheNotSupported, ex.ErrorCode); Assert.AreEqual(MsalErrorMessage.CombinedUserAppCacheNotSupported, ex.Message); - ex = Assert.ThrowsException(() => accessor.DeleteRefreshToken(TokenCacheHelper.CreateRefreshTokenItem())); + ex = Assert.Throws(() => accessor.DeleteRefreshToken(TokenCacheHelper.CreateRefreshTokenItem())); Assert.AreEqual(MsalError.CombinedUserAppCacheNotSupported, ex.ErrorCode); Assert.AreEqual(MsalErrorMessage.CombinedUserAppCacheNotSupported, ex.Message); - ex = Assert.ThrowsException(() => accessor.DeleteIdToken(TokenCacheHelper.CreateIdTokenCacheItem())); + ex = Assert.Throws(() => accessor.DeleteIdToken(TokenCacheHelper.CreateIdTokenCacheItem())); Assert.AreEqual(MsalError.CombinedUserAppCacheNotSupported, ex.ErrorCode); Assert.AreEqual(MsalErrorMessage.CombinedUserAppCacheNotSupported, ex.Message); - ex = Assert.ThrowsException(() => accessor.DeleteAccount(TokenCacheHelper.CreateAccountItem())); + ex = Assert.Throws(() => accessor.DeleteAccount(TokenCacheHelper.CreateAccountItem())); Assert.AreEqual(MsalError.CombinedUserAppCacheNotSupported, ex.ErrorCode); Assert.AreEqual(MsalErrorMessage.CombinedUserAppCacheNotSupported, ex.Message); - Assert.AreEqual(0, accessor.GetAllRefreshTokens().Count); - Assert.AreEqual(0, accessor.GetAllIdTokens().Count); - Assert.AreEqual(0, accessor.GetAllAccounts().Count); + Assert.IsEmpty(accessor.GetAllRefreshTokens()); + Assert.IsEmpty(accessor.GetAllIdTokens()); + Assert.IsEmpty(accessor.GetAllAccounts()); } #endregion diff --git a/tests/Microsoft.Identity.Test.Unit/CacheTests/TokenCacheNotificationTests.cs b/tests/Microsoft.Identity.Test.Unit/CacheTests/TokenCacheNotificationTests.cs index d727becc63..5757e27a22 100644 --- a/tests/Microsoft.Identity.Test.Unit/CacheTests/TokenCacheNotificationTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/CacheTests/TokenCacheNotificationTests.cs @@ -555,7 +555,7 @@ public async Task TokenCacheSerializationArgs_AppCache_IsFmiClientNode_Async(str if (clientId.Equals(TestConstants.FmiNodeClientId)) { // string should not be null or empty - Assert.IsTrue(!string.IsNullOrEmpty(args.NoDistributedCacheUseReason)); + Assert.IsFalse(string.IsNullOrEmpty(args.NoDistributedCacheUseReason)); } else { diff --git a/tests/Microsoft.Identity.Test.Unit/CacheTests/TokenCacheTests.cs b/tests/Microsoft.Identity.Test.Unit/CacheTests/TokenCacheTests.cs index c38e40992f..a8851fab8a 100644 --- a/tests/Microsoft.Identity.Test.Unit/CacheTests/TokenCacheTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/CacheTests/TokenCacheTests.cs @@ -45,11 +45,10 @@ public override void TestInitialize() base.TestInitialize(); } - [DataTestMethod] + [TestMethod] [DataRow(true, true, true)] [DataRow(true, false, false)] [DataRow(false, true, false)] - [DataRow(false, true, false)] public async Task WithLegacyCacheCompatibilityTest_Async( bool enableLegacyCacheCompatibility, bool serializeCache, @@ -98,7 +97,7 @@ public async Task WithLegacyCacheCompatibilityTest_Async( } } - [DataTestMethod] + [TestMethod] [DataRow(true)] [DataRow(false)] public async Task WithMultiCloudSupportTest_Async( @@ -703,7 +702,7 @@ public async Task DoNotSaveRefreshTokenInAdalCacheForMsalB2CAuthorityTestAsync() cache.LegacyPersistence.WriteCache(AdalCacheOperations.Serialize(serviceBundle.ApplicationLogger, dictionary)); // ADAL cache is empty because B2C scenario is only for MSAL - Assert.AreEqual(0, dictionary.Count); + Assert.IsEmpty(dictionary); } [TestMethod] @@ -1282,7 +1281,7 @@ public void FindAccessToken_ScopeCaseInsensitive() var item = cache.FindAccessTokenAsync(requestParams).Result; Assert.IsNotNull(item); - Assert.IsTrue(item.ScopeSet.Contains(scopeInCache)); + Assert.Contains(scopeInCache, item.ScopeSet); } [TestMethod] @@ -1373,7 +1372,7 @@ public void TestIsFociMember_EnvAlias() bool? result = cache.IsFociMemberAsync(requestParams, "1").Result; //request params uses ProductionPrefEnvAlias // Assert - Assert.AreEqual(true, result.Value); + Assert.IsTrue(result.Value); } } @@ -1413,22 +1412,22 @@ public async Task ValidateTokenCacheContentsAreLogged_TestAsync() await cache.SaveTokenResponseAsync(requestParams, response).ConfigureAwait(false); //Assert - Assert.IsTrue(logs != string.Empty); - Assert.IsTrue(logs.Contains("Total number of access tokens in the cache: 12")); - Assert.IsTrue(logs.Contains("Total number of refresh tokens in the cache: 12")); - Assert.IsTrue(logs.Contains("First 10 access token cache keys:")); - Assert.IsTrue(logs.Contains("First 10 refresh token cache keys:")); + Assert.AreNotEqual(string.Empty, logs); + Assert.Contains("Total number of access tokens in the cache: 12", logs); + Assert.Contains("Total number of refresh tokens in the cache: 12", logs); + Assert.Contains("First 10 access token cache keys:", logs); + Assert.Contains("First 10 refresh token cache keys:", logs); var accessTokens = cache.Accessor.GetAllAccessTokens().ToList(); var refreshTokens = cache.Accessor.GetAllRefreshTokens().ToList(); for (int i = 0; i < 10; i++) { - Assert.IsTrue(logs.Contains(accessTokens[i].ToLogString())); - Assert.IsTrue(logs.Contains(refreshTokens[i].ToLogString())); + Assert.Contains(accessTokens[i].ToLogString(), logs); + Assert.Contains(refreshTokens[i].ToLogString(), logs); } } - [DataTestMethod] + [TestMethod] [DataRow(true)] [DataRow(false)] public void AccessTokenCacheItem_ToLogString_UsesPiiFlag_Test(bool enablePii) @@ -1441,7 +1440,7 @@ public void AccessTokenCacheItem_ToLogString_UsesPiiFlag_Test(bool enablePii) Assert.AreNotEqual(enablePii, log.Contains(accessTokenCacheItem.HomeAccountId.GetHashCode().ToString())); } - [DataTestMethod] + [TestMethod] [DataRow(true)] [DataRow(false)] public void RefreshTokenCacheItem_ToLogString_UsesPiiFlag_Test(bool enablePii) diff --git a/tests/Microsoft.Identity.Test.Unit/CacheTests/UnifiedCacheFormatTests.cs b/tests/Microsoft.Identity.Test.Unit/CacheTests/UnifiedCacheFormatTests.cs index 4d3efbea57..895487135a 100644 --- a/tests/Microsoft.Identity.Test.Unit/CacheTests/UnifiedCacheFormatTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/CacheTests/UnifiedCacheFormatTests.cs @@ -189,7 +189,7 @@ private void RunCacheFormatValidation(MockHttpAndServiceBundle harness) private void ValidateAt(ITokenCacheInternal cache) { var atList = cache.Accessor.GetAllAccessTokens().ToList(); - Assert.AreEqual(1, atList.Count); + Assert.HasCount(1, atList); var actualPayload = JsonConvert.DeserializeObject(atList.First().ToJsonString()); var expectedPayload = JsonConvert.DeserializeObject(_expectedAtCacheValue); @@ -205,7 +205,7 @@ private void ValidateAt(ITokenCacheInternal cache) { if (!"extended_expires_on".Equals(propName)) { - Assert.IsTrue(actualPayload.GetValue(propName).Type == JTokenType.String); + Assert.AreEqual(JTokenType.String, actualPayload.GetValue(propName).Type); } } else @@ -274,7 +274,7 @@ private void ValidateAccount(ITokenCacheInternal cache) private void ValidateCacheEntityValue(string expectedEntityValue, ICollection entities) { - Assert.IsTrue(entities.Count == 1); + Assert.HasCount(1, entities); var actualPayload = JsonConvert.DeserializeObject(entities.First()); var expectedPayload = JsonConvert.DeserializeObject(expectedEntityValue); diff --git a/tests/Microsoft.Identity.Test.Unit/CacheTests/UnifiedCacheTests.cs b/tests/Microsoft.Identity.Test.Unit/CacheTests/UnifiedCacheTests.cs index 1e9bcc7e71..d050fb9428 100644 --- a/tests/Microsoft.Identity.Test.Unit/CacheTests/UnifiedCacheTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/CacheTests/UnifiedCacheTests.cs @@ -58,7 +58,7 @@ public void UnifiedCache_MsalStoresToAndReadRtFromAdalCache() IDictionary adalCacheDictionary = AdalCacheOperations.Deserialize(app.ServiceBundle.ApplicationLogger, app.UserTokenCacheInternal.LegacyPersistence.LoadCache()); - Assert.IsTrue(adalCacheDictionary.Count == 1); + Assert.HasCount(1, adalCacheDictionary); var requestContext = new RequestContext(app.ServiceBundle, Guid.NewGuid(), null); @@ -143,7 +143,7 @@ public void UnifiedCache_RemoveAccountIsApplicationSpecific() Assert.IsNotNull(result); - Assert.AreEqual(1, app.UserTokenCacheInternal.Accessor.GetAllAccounts().Count); + Assert.HasCount(1, app.UserTokenCacheInternal.Accessor.GetAllAccounts()); Assert.AreEqual(1, app.GetAccountsAsync().Result.Count()); // login to app1 with same credentials @@ -178,10 +178,10 @@ public void UnifiedCache_RemoveAccountIsApplicationSpecific() // make sure that only one account cache entity was created Assert.AreEqual(1, app1.GetAccountsAsync().Result.Count()); - Assert.AreEqual(2, app1.UserTokenCacheInternal.Accessor.GetAllAccessTokens().Count); - Assert.AreEqual(2, app1.UserTokenCacheInternal.Accessor.GetAllRefreshTokens().Count); - Assert.AreEqual(2, app1.UserTokenCacheInternal.Accessor.GetAllIdTokens().Count); - Assert.AreEqual(1, app1.UserTokenCacheInternal.Accessor.GetAllAccounts().Count); + Assert.HasCount(2, app1.UserTokenCacheInternal.Accessor.GetAllAccessTokens()); + Assert.HasCount(2, app1.UserTokenCacheInternal.Accessor.GetAllRefreshTokens()); + Assert.HasCount(2, app1.UserTokenCacheInternal.Accessor.GetAllIdTokens()); + Assert.HasCount(1, app1.UserTokenCacheInternal.Accessor.GetAllAccounts()); // remove account from app app.RemoveAsync(app.GetAccountsAsync().Result.First()).Wait(); diff --git a/tests/Microsoft.Identity.Test.Unit/CoreTests/CoreHelperTests.cs b/tests/Microsoft.Identity.Test.Unit/CoreTests/CoreHelperTests.cs index a071b9b7b6..e503ef087f 100644 --- a/tests/Microsoft.Identity.Test.Unit/CoreTests/CoreHelperTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/CoreTests/CoreHelperTests.cs @@ -16,27 +16,20 @@ public class CoreHelperTests public void UrlEncodeDecodeTest() { // url without blank can be converted correctly. - Assert.AreEqual(CoreHelpers.UrlEncode("https://login.microsoftonline.com/organizations/oauth2/v2.0/authorize"), - "https%3A%2F%2Flogin.microsoftonline.com%2Forganizations%2Foauth2%2Fv2.0%2Fauthorize"); + Assert.AreEqual("https%3A%2F%2Flogin.microsoftonline.com%2Forganizations%2Foauth2%2Fv2.0%2Fauthorize", CoreHelpers.UrlEncode("https://login.microsoftonline.com/organizations/oauth2/v2.0/authorize")); // url with blank can be converted correctly. " " needs to be replaced by "%20" - Assert.AreEqual(CoreHelpers.UrlEncode("https://management.core.windows.net//.default openid profile offline_access"), - "https%3A%2F%2Fmanagement.core.windows.net%2F%2F.default%20openid%20profile%20offline_access"); + Assert.AreEqual("https%3A%2F%2Fmanagement.core.windows.net%2F%2F.default%20openid%20profile%20offline_access", CoreHelpers.UrlEncode("https://management.core.windows.net//.default openid profile offline_access")); // Encoded url should be decoded correctly. - Assert.AreEqual(CoreHelpers.UrlDecode("https%3A%2F%2Flogin.microsoftonline.com%2Forganizations%2Foauth2%2Fv2.0%2Fauthorize"), - "https://login.microsoftonline.com/organizations/oauth2/v2.0/authorize"); + Assert.AreEqual("https://login.microsoftonline.com/organizations/oauth2/v2.0/authorize", CoreHelpers.UrlDecode("https%3A%2F%2Flogin.microsoftonline.com%2Forganizations%2Foauth2%2Fv2.0%2Fauthorize")); // Encoded url with blank should be decoded correctly. - Assert.AreEqual(CoreHelpers.UrlDecode("https%3A%2F%2Fmanagement.core.windows.net%2F%2F.default%20openid%20profile%20offline_access"), - "https://management.core.windows.net//.default openid profile offline_access"); + Assert.AreEqual("https://management.core.windows.net//.default openid profile offline_access", CoreHelpers.UrlDecode("https%3A%2F%2Fmanagement.core.windows.net%2F%2F.default%20openid%20profile%20offline_access")); // Encoded url with "+" should be decoded correctly. - Assert.AreEqual(CoreHelpers.UrlDecode("https%3A%2F%2Fmanagement.core.windows.net%2F%2F.default+openid+profile+offline_access"), - "https://management.core.windows.net//.default openid profile offline_access"); + Assert.AreEqual("https://management.core.windows.net//.default openid profile offline_access", CoreHelpers.UrlDecode("https%3A%2F%2Fmanagement.core.windows.net%2F%2F.default+openid+profile+offline_access")); // Test special OAuth characters (query string scenarios) - Assert.AreEqual(CoreHelpers.UrlEncode("redirect_uri=https://example.com/callback?code=1234"), - "redirect_uri%3Dhttps%3A%2F%2Fexample.com%2Fcallback%3Fcode%3D1234"); - Assert.AreEqual(CoreHelpers.UrlDecode("redirect_uri%3Dhttps%3A%2F%2Fexample.com%2Fcallback%3Fcode%3D1234"), - "redirect_uri=https://example.com/callback?code=1234"); + Assert.AreEqual("redirect_uri%3Dhttps%3A%2F%2Fexample.com%2Fcallback%3Fcode%3D1234", CoreHelpers.UrlEncode("redirect_uri=https://example.com/callback?code=1234")); + Assert.AreEqual("redirect_uri=https://example.com/callback?code=1234", CoreHelpers.UrlDecode("redirect_uri%3Dhttps%3A%2F%2Fexample.com%2Fcallback%3Fcode%3D1234")); } } } diff --git a/tests/Microsoft.Identity.Test.Unit/CoreTests/HttpTests/HttpManagerTests.cs b/tests/Microsoft.Identity.Test.Unit/CoreTests/HttpTests/HttpManagerTests.cs index 64ba873a4a..a6cadc8bb0 100644 --- a/tests/Microsoft.Identity.Test.Unit/CoreTests/HttpTests/HttpManagerTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/CoreTests/HttpTests/HttpManagerTests.cs @@ -89,7 +89,7 @@ public async Task MtlsCertAndValidateCallbackFailsAsync() using (var httpManager = new MockHttpManager()) { - await Assert.ThrowsExceptionAsync(() => + await Assert.ThrowsAsync(() => httpManager.SendRequestAsync( new Uri(TestConstants.AuthorityHomeTenant + "oauth2/v2.0/token?key1=qp1&key2=qp2"), headers: null, @@ -170,9 +170,7 @@ public async Task TestSendPostNullHeaderNullBodyAsync() Assert.IsNotNull(response); Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); - Assert.AreEqual( - actualResponseBody, - response.Body); + Assert.AreEqual(response.Body, actualResponseBody); } } @@ -212,7 +210,7 @@ public async Task TestSendPostNoFailureAsync() Assert.IsNotNull(response); Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); - Assert.AreEqual(actualResponseBody, response.Body); + Assert.AreEqual(response.Body, actualResponseBody); } } @@ -264,7 +262,7 @@ public async Task TestSendGetWithCanceledTokenAsync() CancellationTokenSource cts = new CancellationTokenSource(); cts.Cancel(); - await Assert.ThrowsExceptionAsync(() => + await Assert.ThrowsAsync(() => httpManager.SendRequestAsync( new Uri(TestConstants.AuthorityHomeTenant + "oauth2/token?key1=qp1&key2=qp2"), headers: queryParams, @@ -287,7 +285,7 @@ public async Task TestSendGetWithHttp500TypeFailureWithInternalRetriesDisabledAs { httpManager.AddResiliencyMessageMockHandler(HttpMethod.Get, HttpStatusCode.GatewayTimeout); - var ex = await Assert.ThrowsExceptionAsync(() => + var ex = await Assert.ThrowsAsync(() => httpManager.SendRequestAsync( new Uri(TestConstants.AuthorityHomeTenant + "oauth2/token"), headers: null, @@ -320,7 +318,7 @@ public async Task TestSendGetWithHttp500TypeFailureAsync() httpManager.AddResiliencyMessageMockHandler(HttpMethod.Get, HttpStatusCode.GatewayTimeout); } - var ex = await Assert.ThrowsExceptionAsync(() => + var ex = await Assert.ThrowsAsync(() => httpManager.SendRequestAsync( new Uri(TestConstants.AuthorityHomeTenant + "oauth2/token"), headers: null, diff --git a/tests/Microsoft.Identity.Test.Unit/CoreTests/HttpTests/RedirectUriHelperTests.cs b/tests/Microsoft.Identity.Test.Unit/CoreTests/HttpTests/RedirectUriHelperTests.cs index 49a32e395c..4e1582e4b5 100644 --- a/tests/Microsoft.Identity.Test.Unit/CoreTests/HttpTests/RedirectUriHelperTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/CoreTests/HttpTests/RedirectUriHelperTests.cs @@ -19,10 +19,10 @@ public class RedirectUriHelperTests : TestBase public void ValidateRedirectUri_Throws() { - Assert.ThrowsException( + Assert.Throws( () => RedirectUriHelper.Validate(null)); - Assert.ThrowsException( + Assert.Throws( () => RedirectUriHelper.Validate(new Uri("https://redirectUri/uri#fragment")), "Validatation should fail if uri has a fragment, i.e. #foo"); } @@ -43,7 +43,7 @@ public void ValidateRedirectUri_DoesNotThrow() [TestMethod] public void ValidateRedirectUri_NoOAuth2DefaultWhenUsingSystemBrowser() { - Assert.ThrowsException(() => + Assert.Throws(() => RedirectUriHelper.Validate(new Uri(Constants.DefaultRedirectUri), true)); RedirectUriHelper.Validate(new Uri(Constants.DefaultRedirectUri), false); @@ -61,16 +61,16 @@ public void iOSBrokerRedirectUri() RedirectUriHelper.ValidateIosBrokerRedirectUri(new Uri($"myscheme://{bundleId}/suffix"), bundleId, new NullLogger()); // the comparison MUST be case sensitive - Assert.ThrowsException(() => + Assert.Throws(() => RedirectUriHelper.ValidateIosBrokerRedirectUri( new Uri($"msauth.{bundleId.ToUpper(CultureInfo.InvariantCulture)}://auth"), bundleId, new NullLogger())); - Assert.ThrowsException(() => + Assert.Throws(() => RedirectUriHelper.ValidateIosBrokerRedirectUri( new Uri($"other.{bundleId}://auth"), bundleId, new NullLogger())); - Assert.ThrowsException(() => + Assert.Throws(() => RedirectUriHelper.ValidateIosBrokerRedirectUri( new Uri($"msauth.{bundleId}://other"), bundleId, new NullLogger())); } diff --git a/tests/Microsoft.Identity.Test.Unit/CoreTests/InstanceTests/AadAuthorityTests.cs b/tests/Microsoft.Identity.Test.Unit/CoreTests/InstanceTests/AadAuthorityTests.cs index 9208e26110..bba573706d 100644 --- a/tests/Microsoft.Identity.Test.Unit/CoreTests/InstanceTests/AadAuthorityTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/CoreTests/InstanceTests/AadAuthorityTests.cs @@ -42,7 +42,7 @@ public async Task CreateEndpointsWithCommonTenantAsync() Authority instance = Authority.CreateAuthority("https://login.microsoftonline.com/common"); Assert.IsNotNull(instance); - Assert.AreEqual(instance.AuthorityInfo.AuthorityType, AuthorityType.Aad); + Assert.AreEqual(AuthorityType.Aad, instance.AuthorityInfo.AuthorityType); Assert.AreEqual( "https://login.microsoftonline.com/common/oauth2/v2.0/authorize", @@ -87,7 +87,7 @@ public async Task FailedValidationTestAsync(bool isInstanceDiscoveryEnabled) Authority instance = Authority.CreateAuthority("https://login.microsoft0nline.com/mytenant.com", true); Assert.IsNotNull(instance); - Assert.AreEqual(instance.AuthorityInfo.AuthorityType, AuthorityType.Aad); + Assert.AreEqual(AuthorityType.Aad, instance.AuthorityInfo.AuthorityType); TestCommon.CreateServiceBundleWithCustomHttpManager(harness.HttpManager, authority: instance.AuthorityInfo.CanonicalAuthority.ToString(), validateAuthority: true); try @@ -105,7 +105,7 @@ public async Task FailedValidationTestAsync(bool isInstanceDiscoveryEnabled) catch (Exception exc) { Assert.IsTrue(exc is MsalServiceException); - Assert.AreEqual(((MsalServiceException)exc).ErrorCode, "invalid_instance"); + Assert.AreEqual("invalid_instance", ((MsalServiceException)exc).ErrorCode); } } @@ -129,19 +129,19 @@ public void TenantSpecificAuthorityInitTest() .WithAuthority(host, TestConstants.TenantId) .BuildConcrete(); - Assert.AreEqual(publicClient.Authority, expectedAuthority); + Assert.AreEqual(expectedAuthority, publicClient.Authority); publicClient = PublicClientApplicationBuilder.Create(TestConstants.ClientId) .WithAuthority(host, new Guid(TestConstants.TenantId)) .BuildConcrete(); - Assert.AreEqual(publicClient.Authority, expectedAuthority); + Assert.AreEqual(expectedAuthority, publicClient.Authority); publicClient = PublicClientApplicationBuilder.Create(TestConstants.ClientId) .WithAuthority(new Uri(expectedAuthority)) .BuildConcrete(); - Assert.AreEqual(publicClient.Authority, expectedAuthority); + Assert.AreEqual(expectedAuthority, publicClient.Authority); } [TestMethod] @@ -169,7 +169,7 @@ public void MalformedAuthorityInitTest() .WithAuthority(host, new Guid(TestConstants.TenantId)) .BuildConcrete(); - Assert.AreEqual(publicClient.Authority, expectedAuthority); + Assert.AreEqual(expectedAuthority, publicClient.Authority); //Check additional path segments fullAuthority = string.Concat(host, TestConstants.TenantId, "/ABCD!@#$TEST//"); @@ -178,29 +178,29 @@ public void MalformedAuthorityInitTest() .WithAuthority(new Uri(fullAuthority)) .BuildConcrete(); - Assert.AreEqual(publicClient.Authority, expectedAuthority); + Assert.AreEqual(expectedAuthority, publicClient.Authority); } - [DataTestMethod] + [TestMethod] [DataRow("http://login.microsoftonline.com/", "ten ant")] [DataRow("https://login.microsoftonline.com/", "ten ant")] public void MalformedAuthority_ThrowsException(string malformedCloudInstanceUri, string malformedTenant) { - Assert.ThrowsException(() => + Assert.Throws(() => ConfidentialClientApplicationBuilder .Create(TestConstants.ClientId) .WithAuthority($"{malformedCloudInstanceUri}{malformedTenant}") .WithClientSecret(TestConstants.ClientSecret) .Build()); - Assert.ThrowsException(() => + Assert.Throws(() => ConfidentialClientApplicationBuilder .Create(TestConstants.ClientId) .WithAuthority(malformedCloudInstanceUri, malformedTenant) .WithClientSecret(TestConstants.ClientSecret) .Build()); - Assert.ThrowsException(() => + Assert.Throws(() => ConfidentialClientApplicationBuilder .Create(TestConstants.ClientId) .WithAuthority(AzureCloudInstance.AzurePublic, malformedTenant) @@ -267,13 +267,13 @@ public void TenantlessAuthorityChanges() string updatedAuthority = authority.GetTenantedAuthority(TestConstants.Utid, false); Assert.AreEqual(TestConstants.AuthorityUtidTenant, updatedAuthority); - Assert.AreEqual(updatedAuthority, TestConstants.AuthorityUtidTenant); + Assert.AreEqual(TestConstants.AuthorityUtidTenant, updatedAuthority); authority = Authority.CreateAuthorityWithTenant( authority.AuthorityInfo, TestConstants.Utid); - Assert.AreEqual(authority.AuthorityInfo.CanonicalAuthority.AbsoluteUri, TestConstants.AuthorityUtidTenant); + Assert.AreEqual(TestConstants.AuthorityUtidTenant, authority.AuthorityInfo.CanonicalAuthority.AbsoluteUri); } [TestMethod] @@ -312,7 +312,7 @@ public void IsOrganizationsTenantWithMsaPassthroughEnabled() AadAuthority aadAuthorityInstance = new AadAuthority(Authority.CreateAuthority("https://login.microsoftonline.com/common").AuthorityInfo); Assert.IsNotNull(aadAuthorityInstance); - Assert.AreEqual(aadAuthorityInstance.AuthorityInfo.AuthorityType, AuthorityType.Aad); + Assert.AreEqual(AuthorityType.Aad, aadAuthorityInstance.AuthorityInfo.AuthorityType); Assert.IsFalse(aadAuthorityInstance.IsOrganizationsTenantWithMsaPassthroughEnabled(true, "")); Assert.IsFalse(aadAuthorityInstance.IsOrganizationsTenantWithMsaPassthroughEnabled(true, "9188040d-6c67-4c5b-b112-36a304b66dad")); @@ -340,7 +340,7 @@ public void IsCommonOrOrganizationsTenantTest() AadAuthority aadAuthorityInstance = new AadAuthority(Authority.CreateAuthority("https://login.microsoftonline.com/common").AuthorityInfo); Assert.IsNotNull(aadAuthorityInstance); - Assert.AreEqual(aadAuthorityInstance.AuthorityInfo.AuthorityType, AuthorityType.Aad); + Assert.AreEqual(AuthorityType.Aad, aadAuthorityInstance.AuthorityInfo.AuthorityType); Assert.IsTrue(aadAuthorityInstance.IsCommonOrOrganizationsTenant()); @@ -348,7 +348,7 @@ public void IsCommonOrOrganizationsTenantTest() aadAuthorityInstance = new AadAuthority(Authority.CreateAuthority("https://login.microsoftonline.com/organizations").AuthorityInfo); Assert.IsNotNull(aadAuthorityInstance); - Assert.AreEqual(aadAuthorityInstance.AuthorityInfo.AuthorityType, AuthorityType.Aad); + Assert.AreEqual(AuthorityType.Aad, aadAuthorityInstance.AuthorityInfo.AuthorityType); Assert.IsTrue(aadAuthorityInstance.IsCommonOrOrganizationsTenant()); @@ -356,7 +356,7 @@ public void IsCommonOrOrganizationsTenantTest() aadAuthorityInstance = new AadAuthority(Authority.CreateAuthority("https://login.microsoftonline.com/consumers").AuthorityInfo); Assert.IsNotNull(aadAuthorityInstance); - Assert.AreEqual(aadAuthorityInstance.AuthorityInfo.AuthorityType, AuthorityType.Aad); + Assert.AreEqual(AuthorityType.Aad, aadAuthorityInstance.AuthorityInfo.AuthorityType); Assert.IsFalse(aadAuthorityInstance.IsCommonOrOrganizationsTenant()); } diff --git a/tests/Microsoft.Identity.Test.Unit/CoreTests/InstanceTests/AdfsAuthorityTests.cs b/tests/Microsoft.Identity.Test.Unit/CoreTests/InstanceTests/AdfsAuthorityTests.cs index 3a0913e65a..0200c02e04 100644 --- a/tests/Microsoft.Identity.Test.Unit/CoreTests/InstanceTests/AdfsAuthorityTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/CoreTests/InstanceTests/AdfsAuthorityTests.cs @@ -10,12 +10,12 @@ namespace Microsoft.Identity.Test.Unit.CoreTests.InstanceTests [TestClass] public class AdfsAuthorityTests { - [DataTestMethod] + [TestMethod] [DataRow("https://someAdfs.com/a dfs/")] [DataRow("http://someAdfs.com/adfs/")] public void MalformedAuthority_ThrowsException(string malformedAuthority) { - Assert.ThrowsException(() => + Assert.Throws(() => ConfidentialClientApplicationBuilder .Create(TestConstants.ClientId) .WithAdfsAuthority(malformedAuthority) @@ -27,7 +27,7 @@ public void MalformedAuthority_ThrowsException(string malformedAuthority) .WithClientSecret(TestConstants.ClientSecret) .Build(); - Assert.ThrowsException(() => + Assert.Throws(() => app.AcquireTokenByAuthorizationCode(TestConstants.s_scope, "code") .WithAdfsAuthority(malformedAuthority)); } diff --git a/tests/Microsoft.Identity.Test.Unit/CoreTests/InstanceTests/B2cAuthorityTests.cs b/tests/Microsoft.Identity.Test.Unit/CoreTests/InstanceTests/B2cAuthorityTests.cs index ecdebb59f0..d2236203dd 100644 --- a/tests/Microsoft.Identity.Test.Unit/CoreTests/InstanceTests/B2cAuthorityTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/CoreTests/InstanceTests/B2cAuthorityTests.cs @@ -17,23 +17,23 @@ public class B2CAuthorityTests : TestBase [TestMethod] public void NotEnoughPathSegments_ThrowsException_Test() { - var ex = Assert.ThrowsException(() => + var ex = Assert.Throws(() => Authority.CreateAuthority("https://login.microsoftonline.in/tfp/")); Assert.AreEqual(MsalErrorMessage.B2cAuthorityUriInvalidPath, ex.Message); } - [DataTestMethod] + [TestMethod] [DataRow("https://sometenantid.b2clogin.com/tfp/sometenantid/policy/", "sometenantid")] [DataRow("https://catsareamazing.com/tfp/catsareamazing/policy/", "catsareamazing")] [DataRow("https://sometenantid.b2clogin.de/tfp/tid/policy/", "tid")] public void AuthorityDoesNotUpdateTenant(string authorityUri, string actualTenant) { Authority authority = Authority.CreateAuthority(authorityUri); - Assert.AreEqual(actualTenant, authority.TenantId); + Assert.AreEqual(authority.TenantId, actualTenant); string updatedAuthority = authority.GetTenantedAuthority("other_tenant_id", false); - Assert.AreEqual(actualTenant, authority.TenantId); + Assert.AreEqual(authority.TenantId, actualTenant); Assert.AreEqual(updatedAuthority, authorityUri); authority = Authority.CreateAuthorityWithTenant(authority.AuthorityInfo, "other_tenant_id_2"); @@ -53,7 +53,7 @@ public void B2CLoginAuthorityEndpoints_Success() null); Assert.IsNotNull(instance); - Assert.AreEqual(instance.AuthorityInfo.AuthorityType, AuthorityType.B2C); + Assert.AreEqual(AuthorityType.B2C, instance.AuthorityInfo.AuthorityType); Assert.AreEqual( "https://sometenantid.b2clogin.com/tfp/6babcaad-604b-40ac-a9d7-9fd97c0b779f/b2c_1_susi/oauth2/v2.0/authorize", instance.GetAuthorizationEndpointAsync(_testRequestContext).Result); @@ -87,12 +87,12 @@ public void CanonicalAuthority_Success() Assert.AreEqual(new Uri(UriVanityPort), authority.AuthorityInfo.CanonicalAuthority); } - [DataTestMethod] + [TestMethod] [DataRow("https://login.microsoftonline.in/tfp/te nant/b2c_1_susi/")] [DataRow("http://login.microsoftonline.in/tfp/tenant/b2c_1_susi/")] public void MalformedAuthority_ThrowsException(string malformedAuthority) { - Assert.ThrowsException(() => + Assert.Throws(() => ConfidentialClientApplicationBuilder .Create(TestConstants.ClientId) .WithB2CAuthority(malformedAuthority) @@ -104,7 +104,7 @@ public void MalformedAuthority_ThrowsException(string malformedAuthority) .WithClientSecret(TestConstants.ClientSecret) .Build(); - Assert.ThrowsException(() => + Assert.Throws(() => app.AcquireTokenByAuthorizationCode(TestConstants.s_scope, "code") .WithB2CAuthority(malformedAuthority)); } diff --git a/tests/Microsoft.Identity.Test.Unit/CoreTests/InstanceTests/DstsAuthorityTests.cs b/tests/Microsoft.Identity.Test.Unit/CoreTests/InstanceTests/DstsAuthorityTests.cs index 27c25c3156..265af7c244 100644 --- a/tests/Microsoft.Identity.Test.Unit/CoreTests/InstanceTests/DstsAuthorityTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/CoreTests/InstanceTests/DstsAuthorityTests.cs @@ -44,7 +44,7 @@ private static MockHttpMessageHandler CreateTokenResponseHttpHandler(string auth }; } - [DataTestMethod] + [TestMethod] [DataRow(TestConstants.DstsAuthorityCommon)] [DataRow(TestConstants.DstsAuthorityTenanted)] public async Task DstsClientCredentialSuccessfulTestAsync(string authority) @@ -153,7 +153,7 @@ public void DstsAuthority_WithTenantId_Success() Assert.AreEqual(TestConstants.TenantId2, AuthorityHelpers.GetTenantId(parameterBuilder.CommonParameters.AuthorityOverride.CanonicalAuthority)); } - [DataTestMethod] + [TestMethod] [DataRow(TestConstants.DstsAuthorityCommon)] [DataRow(TestConstants.DstsAuthorityTenanted)] public void DstsEndpointsTest(string authority) diff --git a/tests/Microsoft.Identity.Test.Unit/CoreTests/InstanceTests/GenericAuthorityTests.cs b/tests/Microsoft.Identity.Test.Unit/CoreTests/InstanceTests/GenericAuthorityTests.cs index 159a136158..a9b7388249 100644 --- a/tests/Microsoft.Identity.Test.Unit/CoreTests/InstanceTests/GenericAuthorityTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/CoreTests/InstanceTests/GenericAuthorityTests.cs @@ -22,7 +22,7 @@ namespace Microsoft.Identity.Test.Unit.CoreTests.InstanceTests [TestClass] public class GenericAuthorityTests : TestBase { - [DataTestMethod] + [TestMethod] [DataRow(true)] [DataRow(false)] /// AAD doesn't returns the "scope" in the response @@ -218,7 +218,7 @@ public async Task UserAuth_ScopeOrder_Async() var account1 = accounts.First(); Assert.AreEqual("sub", account1.HomeAccountId.Identifier); - Assert.AreEqual(null, account1.HomeAccountId.TenantId); + Assert.IsNull(account1.HomeAccountId.TenantId); // This is because of how we've done it in ADFS. Probably doesn't matter what value is used here, as it is not defined for non-Microsoft. Assert.AreEqual("sub", account1.HomeAccountId.ObjectId); @@ -258,20 +258,20 @@ public async Task UserAuth_ScopeOrder_Async() } } - [DataTestMethod] + [TestMethod] [DataRow("https://demo.duend esoftware.com")] - [ExpectedException(typeof(ArgumentException))] public void MalformedAuthority_ThrowsException(string malformedAuthority) { // Tenant and authority modifiers + Assert.Throws(() => ConfidentialClientApplicationBuilder .Create(TestConstants.ClientId) .WithOidcAuthority(malformedAuthority) .WithClientSecret(TestConstants.ClientSecret) - .Build(); + .Build()); } - [DataTestMethod] + [TestMethod] [DataRow("oidc_response_not_json")] [DataRow("oidc_response_http_error")] public async Task BadOidcResponse_ThrowsException_Async(string badOidcResponseType) @@ -364,11 +364,10 @@ public async Task Oidc_Malformed_Failure_Async() .ExecuteAsync()) .ConfigureAwait(false); - Assert.IsTrue(ex.Message.Contains( - string.Format( - CultureInfo.InvariantCulture, - MsalErrorMessage.MalformedOidcAuthorityFormat, - TestConstants.CiamCUDAuthorityMalformed))); + Assert.Contains(string.Format( + CultureInfo.InvariantCulture, + MsalErrorMessage.MalformedOidcAuthorityFormat, + TestConstants.CiamCUDAuthorityMalformed), ex.Message); httpManager.AddFailureTokenEndpointResponse( error: "error", @@ -380,11 +379,10 @@ public async Task Oidc_Malformed_Failure_Async() .ExecuteAsync()) .ConfigureAwait(false); - Assert.IsTrue(ex.Message.Contains( - string.Format( + Assert.Contains(string.Format( CultureInfo.InvariantCulture, MsalErrorMessage.MalformedOidcAuthorityFormat, - TestConstants.CiamCUDAuthorityMalformed))); + TestConstants.CiamCUDAuthorityMalformed), ex.Message); } } diff --git a/tests/Microsoft.Identity.Test.Unit/CoreTests/InstanceTests/InstanceProviderTests.cs b/tests/Microsoft.Identity.Test.Unit/CoreTests/InstanceTests/InstanceProviderTests.cs index f00d9eb1dd..9252fb7c14 100644 --- a/tests/Microsoft.Identity.Test.Unit/CoreTests/InstanceTests/InstanceProviderTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/CoreTests/InstanceTests/InstanceProviderTests.cs @@ -106,11 +106,11 @@ public void UserMetadataProvider_RespondsIfEnvironmentsAreKnown() Assert.IsNotNull(result3); MsalClientException ex; - ex = Assert.ThrowsException(() => userMetadataProvider.GetMetadataOrThrow("non_existent", _logger)); + ex = Assert.Throws(() => userMetadataProvider.GetMetadataOrThrow("non_existent", _logger)); Assert.AreEqual(MsalError.InvalidUserInstanceMetadata, ex.ErrorCode); - ex = Assert.ThrowsException(() => userMetadataProvider.GetMetadataOrThrow(null, _logger)); + ex = Assert.Throws(() => userMetadataProvider.GetMetadataOrThrow(null, _logger)); Assert.AreEqual(MsalError.InvalidUserInstanceMetadata, ex.ErrorCode); - ex = Assert.ThrowsException(() => userMetadataProvider.GetMetadataOrThrow("", _logger)); + ex = Assert.Throws(() => userMetadataProvider.GetMetadataOrThrow("", _logger)); Assert.AreEqual(MsalError.InvalidUserInstanceMetadata, ex.ErrorCode); } diff --git a/tests/Microsoft.Identity.Test.Unit/CoreTests/InstanceTests/PublicApiInstanceMetadataTests.cs b/tests/Microsoft.Identity.Test.Unit/CoreTests/InstanceTests/PublicApiInstanceMetadataTests.cs index 4d072ea1d5..de1662cfbf 100644 --- a/tests/Microsoft.Identity.Test.Unit/CoreTests/InstanceTests/PublicApiInstanceMetadataTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/CoreTests/InstanceTests/PublicApiInstanceMetadataTests.cs @@ -79,7 +79,7 @@ public async Task AcquireTokenInterative_WithBadCustomInstanceMetadata_Async(boo .WithHttpManager(harness.HttpManager) .BuildConcrete(); - var ex = await Assert.ThrowsExceptionAsync(() => app + var ex = await Assert.ThrowsAsync(() => app .AcquireTokenInteractive(TestConstants.s_scope) .ExecuteAsync(CancellationToken.None)) .ConfigureAwait(false); diff --git a/tests/Microsoft.Identity.Test.Unit/CoreTests/MsalIdHelperTests.cs b/tests/Microsoft.Identity.Test.Unit/CoreTests/MsalIdHelperTests.cs index 134516e769..34d1352e19 100644 --- a/tests/Microsoft.Identity.Test.Unit/CoreTests/MsalIdHelperTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/CoreTests/MsalIdHelperTests.cs @@ -32,14 +32,14 @@ public void XClientOSTest() if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { // This matches the ESTS code https://msazure.visualstudio.com/One/_git/ESTS-Main?path=/src/Product/Microsoft.AzureAD.ESTS/Sts/ClientInfo.cs&version=GBmaster&_a=contents - Assert.IsTrue(os.Contains("Windows")); + Assert.Contains("Windows", os); Regex AdalOsVersionRegex = new Regex(@"[\d]+[.\d]*", RegexOptions.Compiled); Match match = AdalOsVersionRegex.Match(os); Assert.IsTrue(match.Success); NuGetVersion.TryParse(match.Value, out var semanticVersion); - Assert.IsTrue(semanticVersion.Major >= 10); + Assert.IsGreaterThanOrEqualTo(10, semanticVersion.Major); } diff --git a/tests/Microsoft.Identity.Test.Unit/CoreTests/OAuth2Tests/ClaimsTest.cs b/tests/Microsoft.Identity.Test.Unit/CoreTests/OAuth2Tests/ClaimsTest.cs index 0a013f4b90..ee314f40a3 100644 --- a/tests/Microsoft.Identity.Test.Unit/CoreTests/OAuth2Tests/ClaimsTest.cs +++ b/tests/Microsoft.Identity.Test.Unit/CoreTests/OAuth2Tests/ClaimsTest.cs @@ -242,7 +242,7 @@ public async Task Claims_Fail_WhenClaimsIsNotJson_Async() Assert.AreEqual(MsalError.InvalidJsonClaimsFormat, ex.ErrorCode); } - [DataTestMethod] + [TestMethod] [DynamicData(nameof(TestData.GetClaimsAndCapabilities), typeof(TestData), DynamicDataSourceType.Method)] public void ClaimsMerge_Test(string claims, string[] capabilities, string expectedMergedJson) { diff --git a/tests/Microsoft.Identity.Test.Unit/CoreTests/PlatformProxyFactoryTests.cs b/tests/Microsoft.Identity.Test.Unit/CoreTests/PlatformProxyFactoryTests.cs index dd8591555a..7d1f5dbbb4 100644 --- a/tests/Microsoft.Identity.Test.Unit/CoreTests/PlatformProxyFactoryTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/CoreTests/PlatformProxyFactoryTests.cs @@ -25,7 +25,7 @@ public void PlatformProxyFactoryDoesNotCacheTheProxy() var proxy2 = PlatformProxyFactory.CreatePlatformProxy(null); // Assert - Assert.IsFalse(proxy1 == proxy2); + Assert.AreNotEqual(proxy2, proxy1); } [TestMethod] diff --git a/tests/Microsoft.Identity.Test.Unit/CoreTests/RegionDiscoveryProviderTests.cs b/tests/Microsoft.Identity.Test.Unit/CoreTests/RegionDiscoveryProviderTests.cs index f96d24c4be..a564e780b6 100644 --- a/tests/Microsoft.Identity.Test.Unit/CoreTests/RegionDiscoveryProviderTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/CoreTests/RegionDiscoveryProviderTests.cs @@ -150,7 +150,7 @@ public async Task FetchRegionFromLocalImdsThenGetMetadataFromCacheAsync() ValidateInstanceMetadata(regionalMetadata); } - [DataTestMethod] + [TestMethod] [DataRow(HttpStatusCode.NotFound, 0, TestConstants.RegionAutoDetectNotFoundFailureMessage)] // No retries for 404 errors [DataRow(HttpStatusCode.InternalServerError, TestRegionDiscoveryRetryPolicy.NumRetries, TestConstants.RegionAutoDetectInternalServerErrorFailureMessage)] public async Task SuccessfulResponseFromUserProvidedRegionAsync( @@ -175,7 +175,7 @@ public async Task SuccessfulResponseFromUserProvidedRegionAsync( Assert.AreEqual(TestConstants.Region, _testRequestContext.ApiEvent.RegionUsed); Assert.AreEqual(RegionAutodetectionSource.FailedAutoDiscovery, _testRequestContext.ApiEvent.RegionAutodetectionSource); Assert.AreEqual(RegionOutcome.UserProvidedAutodetectionFailed, _testRequestContext.ApiEvent.RegionOutcome); - Assert.IsTrue(_testRequestContext.ApiEvent.RegionDiscoveryFailureReason.Contains(expectedFailureMessage)); + Assert.Contains(expectedFailureMessage, _testRequestContext.ApiEvent.RegionDiscoveryFailureReason); // Verify all mock responses were consumed Assert.AreEqual(0, _httpManager.QueueSize); @@ -270,7 +270,7 @@ public async Task InvalidRegionEnvVariableAsync() ValidateInstanceMetadata(regionalMetadata); } - [DataTestMethod] + [TestMethod] [DataRow("Region with spaces")] [DataRow("invalid`region")] public async Task InvalidImdsAsync(string region) @@ -313,13 +313,13 @@ public async Task ResponseMissingRegionFromLocalImdsAsync() // Assert Assert.IsNull(regionalMetadata, "Discovery requested, but it failed."); - Assert.AreEqual(null, _testRequestContext.ApiEvent.RegionUsed); + Assert.IsNull(_testRequestContext.ApiEvent.RegionUsed); Assert.AreEqual(RegionAutodetectionSource.FailedAutoDiscovery, _testRequestContext.ApiEvent.RegionAutodetectionSource); Assert.AreEqual(RegionOutcome.FallbackToGlobal, _testRequestContext.ApiEvent.RegionOutcome); - Assert.IsTrue(_testRequestContext.ApiEvent.RegionDiscoveryFailureReason.Contains(TestConstants.RegionAutoDetectOkFailureMessage)); + Assert.Contains(TestConstants.RegionAutoDetectOkFailureMessage, _testRequestContext.ApiEvent.RegionDiscoveryFailureReason); } - [DataTestMethod] + [TestMethod] [DataRow(HttpStatusCode.NotFound, 0, TestConstants.RegionAutoDetectNotFoundFailureMessage)] // No retries for 404 errors [DataRow(HttpStatusCode.InternalServerError, TestRegionDiscoveryRetryPolicy.NumRetries, TestConstants.RegionAutoDetectInternalServerErrorFailureMessage)] public async Task ErrorResponseFromLocalImdsAsync( @@ -339,10 +339,10 @@ public async Task ErrorResponseFromLocalImdsAsync( Assert.IsNull(regionalMetadata, "Discovery requested, but it failed."); - Assert.AreEqual(null, _testRequestContext.ApiEvent.RegionUsed); + Assert.IsNull(_testRequestContext.ApiEvent.RegionUsed); Assert.AreEqual(RegionAutodetectionSource.FailedAutoDiscovery, _testRequestContext.ApiEvent.RegionAutodetectionSource); Assert.AreEqual(RegionOutcome.FallbackToGlobal, _testRequestContext.ApiEvent.RegionOutcome); - Assert.IsTrue(_testRequestContext.ApiEvent.RegionDiscoveryFailureReason.Contains(expectedFailureMessage)); + Assert.Contains(expectedFailureMessage, _testRequestContext.ApiEvent.RegionDiscoveryFailureReason); // Verify all mock responses were consumed Assert.AreEqual(0, _httpManager.QueueSize); @@ -382,10 +382,10 @@ public async Task UpdateApiversionFailsWithEmptyResponseBodyAsync() // Assert Assert.IsNull(regionalMetadata, "Discovery requested, but it failed."); - Assert.AreEqual(null, _testRequestContext.ApiEvent.RegionUsed); + Assert.IsNull(_testRequestContext.ApiEvent.RegionUsed); Assert.AreEqual(RegionAutodetectionSource.FailedAutoDiscovery, _testRequestContext.ApiEvent.RegionAutodetectionSource); Assert.AreEqual(RegionOutcome.FallbackToGlobal, _testRequestContext.ApiEvent.RegionOutcome); - Assert.IsTrue(_testRequestContext.ApiEvent.RegionDiscoveryFailureReason.Contains(TestConstants.RegionDiscoveryNotSupportedErrorMessage)); + Assert.Contains(TestConstants.RegionDiscoveryNotSupportedErrorMessage, _testRequestContext.ApiEvent.RegionDiscoveryFailureReason); } [TestMethod] @@ -403,10 +403,10 @@ public async Task UpdateApiversionFailsWithNoNewestVersionsAsync() // Assert Assert.IsNull(regionalMetadata, "Discovery requested, but it failed."); - Assert.AreEqual(null, _testRequestContext.ApiEvent.RegionUsed); + Assert.IsNull(_testRequestContext.ApiEvent.RegionUsed); Assert.AreEqual(RegionAutodetectionSource.FailedAutoDiscovery, _testRequestContext.ApiEvent.RegionAutodetectionSource); Assert.AreEqual(RegionOutcome.FallbackToGlobal, _testRequestContext.ApiEvent.RegionOutcome); - Assert.IsTrue(_testRequestContext.ApiEvent.RegionDiscoveryFailureReason.Contains(TestConstants.RegionDiscoveryNotSupportedErrorMessage)); + Assert.Contains(TestConstants.RegionDiscoveryNotSupportedErrorMessage, _testRequestContext.ApiEvent.RegionDiscoveryFailureReason); } [TestMethod] @@ -447,7 +447,7 @@ public async Task RegionDiscoveryFails500PermanentlyAsync() new Uri("https://login.microsoftonline.com/common/"), _testRequestContext).ConfigureAwait(false); Assert.IsNull(regionalMetadata, "Discovery should fail after max retries"); - Assert.AreEqual(null, _testRequestContext.ApiEvent.RegionUsed); + Assert.IsNull(_testRequestContext.ApiEvent.RegionUsed); Assert.AreEqual(RegionAutodetectionSource.FailedAutoDiscovery, _testRequestContext.ApiEvent.RegionAutodetectionSource); Assert.AreEqual(RegionOutcome.FallbackToGlobal, _testRequestContext.ApiEvent.RegionOutcome); @@ -456,7 +456,7 @@ public async Task RegionDiscoveryFails500PermanentlyAsync() Assert.AreEqual(NumRequests, requestsMade); } - [DataTestMethod] + [TestMethod] [DataRow(HttpStatusCode.NotFound)] [DataRow(HttpStatusCode.RequestTimeout)] public async Task RegionDiscoveryDoesNotRetryOnNonRetryableStatusCodesAsync(HttpStatusCode statusCode) @@ -469,7 +469,7 @@ public async Task RegionDiscoveryDoesNotRetryOnNonRetryableStatusCodesAsync(Http new Uri("https://login.microsoftonline.com/common/"), _testRequestContext).ConfigureAwait(false); Assert.IsNull(regionalMetadata, "Discovery should fail and not retry"); - Assert.AreEqual(null, _testRequestContext.ApiEvent.RegionUsed); + Assert.IsNull(_testRequestContext.ApiEvent.RegionUsed); Assert.AreEqual(RegionAutodetectionSource.FailedAutoDiscovery, _testRequestContext.ApiEvent.RegionAutodetectionSource); Assert.AreEqual(RegionOutcome.FallbackToGlobal, _testRequestContext.ApiEvent.RegionOutcome); diff --git a/tests/Microsoft.Identity.Test.Unit/CoreTests/WsTrustTests/MexParserTests.cs b/tests/Microsoft.Identity.Test.Unit/CoreTests/WsTrustTests/MexParserTests.cs index 64c9466986..4069b518fa 100644 --- a/tests/Microsoft.Identity.Test.Unit/CoreTests/WsTrustTests/MexParserTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/CoreTests/WsTrustTests/MexParserTests.cs @@ -35,14 +35,14 @@ public void WsTrust2005AddressExtractionTest() Assert.AreEqual( "https://sts.usystech.net/adfs/services/trust/2005/windowstransport", wsTrustEndpoint.Uri.AbsoluteUri); - Assert.AreEqual(wsTrustEndpoint.Version, WsTrustVersion.WsTrust2005); + Assert.AreEqual(WsTrustVersion.WsTrust2005, wsTrustEndpoint.Version); // Act wsTrustEndpoint = mexDocument.GetWsTrustUsernamePasswordEndpoint(); // Assert Assert.AreEqual("https://sts.usystech.net/adfs/services/trust/2005/usernamemixed", wsTrustEndpoint.Uri.AbsoluteUri); - Assert.AreEqual(wsTrustEndpoint.Version, WsTrustVersion.WsTrust2005); + Assert.AreEqual(WsTrustVersion.WsTrust2005, wsTrustEndpoint.Version); } [TestMethod] @@ -70,10 +70,11 @@ await harness.ServiceBundle.WsTrustWebRequestManager.GetMexDocumentAsync("http:/ [TestMethod] [Description("Mex endpoint fails to parse")] - [ExpectedException(typeof(XmlException))] public void MexEndpointFailsToParseTest() { - var mexDocument = new MexDocument("malformed, non-xml content"); + Assert.Throws( + () => + new MexDocument("malformed, non-xml content")); } } } diff --git a/tests/Microsoft.Identity.Test.Unit/CoreTests/WsTrustTests/WsTrustTests.cs b/tests/Microsoft.Identity.Test.Unit/CoreTests/WsTrustTests/WsTrustTests.cs index 486916bc8d..ac1ab08d64 100644 --- a/tests/Microsoft.Identity.Test.Unit/CoreTests/WsTrustTests/WsTrustTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/CoreTests/WsTrustTests/WsTrustTests.cs @@ -128,7 +128,7 @@ public async Task WsTrustRequestParseErrorTestAsync() catch (MsalException ex) { Assert.AreEqual(MsalError.ParsingWsTrustResponseFailed, ex.ErrorCode); - Assert.AreEqual(ex.Message, expectedMessage); + Assert.AreEqual(expectedMessage, ex.Message); } } } diff --git a/tests/Microsoft.Identity.Test.Unit/CryptographyTests.cs b/tests/Microsoft.Identity.Test.Unit/CryptographyTests.cs index fa69507108..057b4368bf 100644 --- a/tests/Microsoft.Identity.Test.Unit/CryptographyTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/CryptographyTests.cs @@ -48,7 +48,7 @@ public void SignWithNonRsaCertificate_ThrowsException() crypto.SignWithCertificate("TEST", cert, RSASignaturePadding.Pkcs1); }); - Assert.AreEqual(ex.ErrorCode, MsalError.CertificateNotRsa); + Assert.AreEqual(MsalError.CertificateNotRsa, ex.ErrorCode); Assert.AreEqual(ex.Message, MsalErrorMessage.CertMustBeRsa(cert.PublicKey.Oid.FriendlyName)); } } diff --git a/tests/Microsoft.Identity.Test.Unit/DeviceAuthHelperTests.cs b/tests/Microsoft.Identity.Test.Unit/DeviceAuthHelperTests.cs index 17d510a44c..b59085daab 100644 --- a/tests/Microsoft.Identity.Test.Unit/DeviceAuthHelperTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/DeviceAuthHelperTests.cs @@ -36,10 +36,10 @@ public void ParsePKeyAuthChallengeData() var result = DeviceAuthHelper.ParseChallengeData(s_httpResponse.Headers); //Assert - Assert.AreEqual(result["Version"], "1.0"); - Assert.AreEqual(result["CertThumbprint"], "thumbprint"); - Assert.AreEqual(result["Context"], "context"); - Assert.AreEqual(result["Nonce"], "nonce"); + Assert.AreEqual("1.0", result["Version"]); + Assert.AreEqual("thumbprint", result["CertThumbprint"]); + Assert.AreEqual("context", result["Context"]); + Assert.AreEqual("nonce", result["Nonce"]); } [TestMethod] @@ -67,8 +67,8 @@ public void GetDeviceAuthBypassChallengeResponse() var result2 = DeviceAuthHelper.GetBypassChallengeResponse(pKeyAuthHeaders); //Assert - Assert.AreEqual(result1, TestConstants.PKeyAuthResponse); - Assert.AreEqual(result2, TestConstants.PKeyAuthResponse); + Assert.AreEqual(TestConstants.PKeyAuthResponse, result1); + Assert.AreEqual(TestConstants.PKeyAuthResponse, result2); } [TestMethod] diff --git a/tests/Microsoft.Identity.Test.Unit/ExceptionTests/MsalExceptionSerializationTests.cs b/tests/Microsoft.Identity.Test.Unit/ExceptionTests/MsalExceptionSerializationTests.cs index 114e3496c2..d6afb34e2e 100644 --- a/tests/Microsoft.Identity.Test.Unit/ExceptionTests/MsalExceptionSerializationTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/ExceptionTests/MsalExceptionSerializationTests.cs @@ -25,7 +25,7 @@ public class MsalExceptionSerializationTests private const string BrokerErrorCode = "broker error code"; private const string BrokerTelemetry = "{\"error-property1\": \"0\",\"error-property2\": \"abc\"}"; - [DataTestMethod] + [TestMethod] [DataRow(false)] [DataRow(true)] public void MsalException_CanSerializeAndDeserializeRoundTrip(bool includeAdditionalExceptionData) diff --git a/tests/Microsoft.Identity.Test.Unit/ExceptionTests/MsalExceptionTests.cs b/tests/Microsoft.Identity.Test.Unit/ExceptionTests/MsalExceptionTests.cs index 9accbc44be..16162dd9b5 100644 --- a/tests/Microsoft.Identity.Test.Unit/ExceptionTests/MsalExceptionTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/ExceptionTests/MsalExceptionTests.cs @@ -66,11 +66,11 @@ public void MsalClientException_FromMessageAndCode() // Assert Assert.IsFalse(string.IsNullOrEmpty(piiMessage)); - Assert.IsTrue( - piiMessage.Contains(typeof(MsalClientException).Name), - "The pii message should contain the exception type"); - Assert.IsTrue(piiMessage.Contains(ExCode)); - Assert.IsFalse(piiMessage.Contains(ExMessage)); + Assert.Contains( +typeof(MsalClientException).Name, + piiMessage, "The pii message should contain the exception type"); + Assert.Contains(ExCode, piiMessage); + Assert.DoesNotContain(ExMessage, piiMessage); } [TestMethod] @@ -153,7 +153,7 @@ private static void ValidateClassification( var msalException = MsalServiceExceptionFactory.FromHttpResponse(ExCode, ExMessage, httpResponse); Assert.AreEqual(ExCode, msalException.ErrorCode); - Assert.IsTrue(msalException.Message.Contains(ExMessage)); + Assert.Contains(ExMessage, msalException.Message); Assert.AreEqual("some_claims", msalException.Claims); Assert.AreEqual("6347d33d-941a-4c35-9912-a9cf54fb1b3e", msalException.CorrelationId); Assert.AreEqual(suberror ?? "", msalException.SubError); @@ -173,8 +173,8 @@ private static void ValidateExceptionProductInformation(MsalException exception) string msalProductName = PlatformProxyFactory.CreatePlatformProxy(null).GetProductName(); string msalVersion = MsalIdHelper.GetMsalVersion(); - Assert.IsTrue(exceptionString.Contains(msalProductName), "Exception should contain the msalProductName"); - Assert.IsTrue(exceptionString.Contains(msalVersion), "Exception should contain the msalVersion"); + Assert.Contains(msalProductName, exceptionString, "Exception should contain the msalProductName"); + Assert.Contains(msalVersion, exceptionString, "Exception should contain the msalVersion"); } [TestMethod] @@ -217,7 +217,7 @@ public void InvalidClientException_IsRepackaged() // Assert var msalServiceException = msalException; Assert.AreEqual(MsalError.InvalidClient, msalServiceException.ErrorCode); - Assert.IsTrue(msalServiceException.Message.Contains(MsalErrorMessage.InvalidClient)); + Assert.Contains(MsalErrorMessage.InvalidClient, msalServiceException.Message); ValidateExceptionProductInformation(msalException); } @@ -275,17 +275,17 @@ public void MsalServiceException_HttpResponse_OAuthResponse() // Assert Assert.IsFalse(string.IsNullOrEmpty(piiMessage)); - Assert.IsTrue( - piiMessage.Contains(typeof(MsalClaimsChallengeException).Name), - "The pii message should contain the exception type"); - Assert.IsTrue( - piiMessage.Contains(typeof(NotImplementedException).Name), - "The pii message should have the inner exception type"); - Assert.IsTrue(piiMessage.Contains(ExCode)); - Assert.IsTrue(piiMessage.Contains("6347d33d-941a-4c35-9912-a9cf54fb1b3e")); // Correlation Id - - Assert.IsFalse(piiMessage.Contains(ExMessage)); - Assert.IsFalse(piiMessage.Contains(innerExMsg)); + Assert.Contains( +typeof(MsalClaimsChallengeException).Name, + piiMessage, "The pii message should contain the exception type"); + Assert.Contains( +typeof(NotImplementedException).Name, + piiMessage, "The pii message should have the inner exception type"); + Assert.Contains(ExCode, piiMessage); + Assert.Contains("6347d33d-941a-4c35-9912-a9cf54fb1b3e", piiMessage); // Correlation Id + + Assert.DoesNotContain(ExMessage, piiMessage); + Assert.DoesNotContain(innerExMsg, piiMessage); } [TestMethod] @@ -317,15 +317,15 @@ public void MsalUiRequiredExceptionProperties() // Assert Assert.IsFalse(string.IsNullOrEmpty(piiMessage)); - Assert.IsTrue( - piiMessage.Contains(typeof(MsalUiRequiredException).Name), - "The pii message should contain the exception type"); - Assert.IsTrue( - piiMessage.Contains(typeof(NotImplementedException).Name), - "The pii message should have the inner exception type"); - Assert.IsTrue(piiMessage.Contains(ExCode)); - Assert.IsFalse(piiMessage.Contains(ExMessage)); - Assert.IsFalse(piiMessage.Contains(innerExMsg)); + Assert.Contains( +typeof(MsalUiRequiredException).Name, + piiMessage, "The pii message should contain the exception type"); + Assert.Contains( +typeof(NotImplementedException).Name, + piiMessage, "The pii message should have the inner exception type"); + Assert.Contains(ExCode, piiMessage); + Assert.DoesNotContain(ExMessage, piiMessage); + Assert.DoesNotContain(innerExMsg, piiMessage); } [TestMethod] @@ -386,9 +386,9 @@ public void Exception_ToString() var innerException = new InvalidOperationException("innerMsg"); MsalException ex = new MsalException("errCode", "errMessage", innerException); - Assert.IsTrue(ex.ToString().Contains("errCode")); - Assert.IsTrue(ex.ToString().Contains("errMessage")); - Assert.IsTrue(ex.ToString().Contains("innerMsg")); + Assert.Contains("errCode", ex.ToString()); + Assert.Contains("errMessage", ex.ToString()); + Assert.Contains("innerMsg", ex.ToString()); ValidateExceptionProductInformation(ex); } @@ -417,13 +417,13 @@ public void ServiceException_ToString() "errMessage", httpResponse, innerException); // Assert - Assert.IsTrue(ex.ToString().Contains("errCode")); - Assert.IsTrue(ex.ToString().Contains("errMessage")); - Assert.IsTrue(ex.ToString().Contains("innerExMsg")); - Assert.IsTrue(ex.ToString().Contains("invalid_tenant")); - Assert.IsTrue(ex.ToString().Contains("MySuberror")); - Assert.IsTrue(ex.ToString().Contains("some_claims")); - Assert.IsTrue(ex.ToString().Contains("AADSTS90002")); + Assert.Contains("errCode", ex.ToString()); + Assert.Contains("errMessage", ex.ToString()); + Assert.Contains("innerExMsg", ex.ToString()); + Assert.Contains("invalid_tenant", ex.ToString()); + Assert.Contains("MySuberror", ex.ToString()); + Assert.Contains("some_claims", ex.ToString()); + Assert.Contains("AADSTS90002", ex.ToString()); Assert.IsFalse(ex is MsalUiRequiredException); ValidateExceptionProductInformation(ex); @@ -484,7 +484,7 @@ public async Task CorrelationIdInClientExceptions() .BuildConcrete(); } - var ex = await Assert.ThrowsExceptionAsync(async () => + var ex = await Assert.ThrowsAsync(async () => { await app.AcquireTokenForClient(TestConstants.s_scope) .ExecuteAsync(CancellationToken.None) @@ -529,15 +529,15 @@ public async Task AuthorityInNotFoundExceptions() .WithCertificate(certificate) .BuildConcrete(); - var ex = await Assert.ThrowsExceptionAsync(async () => + var ex = await Assert.ThrowsAsync(async () => { await app.AcquireTokenForClient(TestConstants.s_scope) .ExecuteAsync(CancellationToken.None) .ConfigureAwait(false); }).ConfigureAwait(false); - Assert.IsTrue(ex.Message.Contains("Authority used: https://login.microsoftonline.com/common/")); - Assert.IsTrue(ex.Message.Contains("Token Endpoint: https://login.microsoftonline.com/common/oauth2/v2.0/token")); + Assert.Contains("Authority used: https://login.microsoftonline.com/common/", ex.Message); + Assert.Contains("Token Endpoint: https://login.microsoftonline.com/common/oauth2/v2.0/token", ex.Message); //Validate that the authority is not appended with extra query parameters //Validate that the region is also captured @@ -562,9 +562,9 @@ await app.AcquireTokenForClient(TestConstants.s_scope) .ConfigureAwait(false); }).ConfigureAwait(false); - Assert.IsTrue(ex.Message.Contains("Authority used: https://sts.access.edu/my-utid/")); - Assert.IsTrue(ex.Message.Contains("Token Endpoint: https://centralus.sts.access.edu/my-utid/oauth2/v2.0/token")); - Assert.IsTrue(ex.Message.Contains($"Region Used: {TestConstants.Region}")); + Assert.Contains("Authority used: https://sts.access.edu/my-utid/", ex.Message); + Assert.Contains("Token Endpoint: https://centralus.sts.access.edu/my-utid/oauth2/v2.0/token", ex.Message); + Assert.Contains($"Region Used: {TestConstants.Region}", ex.Message); //harness.HttpManager.AddMockHandler(MockHelpers.CreateInstanceDiscoveryMockHandler(TestConstants.AuthorityCommonTenant + TestConstants.DiscoveryEndPoint)); harness.HttpManager.AddRequestTimeoutResponseMessageMockHandler(HttpMethod.Post); @@ -579,9 +579,9 @@ await app.AcquireTokenForClient(TestConstants.s_scope) .ConfigureAwait(false); }).ConfigureAwait(false); - Assert.IsFalse(ex.Message.Contains("Authority used:")); - Assert.IsFalse(ex.Message.Contains("Token Endpoint:")); - Assert.IsFalse(ex.Message.Contains($"Region Used:")); + Assert.DoesNotContain("Authority used:", ex.Message); + Assert.DoesNotContain("Token Endpoint:", ex.Message); + Assert.DoesNotContain($"Region Used:", ex.Message); } } diff --git a/tests/Microsoft.Identity.Test.Unit/ManagedIdentityTests/AppServiceTests.cs b/tests/Microsoft.Identity.Test.Unit/ManagedIdentityTests/AppServiceTests.cs index 508ace58cc..ccecf1c408 100644 --- a/tests/Microsoft.Identity.Test.Unit/ManagedIdentityTests/AppServiceTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/ManagedIdentityTests/AppServiceTests.cs @@ -36,7 +36,7 @@ public async Task AppServiceInvalidEndpointAsync() var mi = miBuilder.Build(); - MsalServiceException ex = await Assert.ThrowsExceptionAsync(async () => + MsalServiceException ex = await Assert.ThrowsAsync(async () => await mi.AcquireTokenForManagedIdentity(ManagedIdentityTests.Resource) .ExecuteAsync().ConfigureAwait(false)).ConfigureAwait(false); @@ -48,7 +48,7 @@ await mi.AcquireTokenForManagedIdentity(ManagedIdentityTests.Resource) } // Regression test for Bug ID #5077 - ManagedIdentityCredential authentication failed - [DataTestMethod] + [TestMethod] [DataRow("http://127.0.0.1:41564/msi/token/", ManagedIdentitySource.AppService, ManagedIdentitySource.AppService)] [DataRow(AppServiceEndpoint, ManagedIdentitySource.AppService, ManagedIdentitySource.AppService)] [DataRow(MachineLearningEndpoint, ManagedIdentitySource.MachineLearning, ManagedIdentitySource.MachineLearning)] diff --git a/tests/Microsoft.Identity.Test.Unit/ManagedIdentityTests/AzureArcTests.cs b/tests/Microsoft.Identity.Test.Unit/ManagedIdentityTests/AzureArcTests.cs index 2a172aff72..84f586a8d0 100644 --- a/tests/Microsoft.Identity.Test.Unit/ManagedIdentityTests/AzureArcTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/ManagedIdentityTests/AzureArcTests.cs @@ -23,7 +23,7 @@ public class AzureArcTests : TestBase { private const string AzureArc = "Azure Arc"; - [DataTestMethod] + [TestMethod] [DataRow(TestConstants.ClientId, UserAssignedIdentityId.ClientId)] [DataRow("resourceId", UserAssignedIdentityId.ResourceId)] [DataRow(TestConstants.ObjectId, UserAssignedIdentityId.ObjectId)] @@ -39,7 +39,7 @@ public async Task AzureArcUserAssignedManagedIdentityNotSupportedAsync(string us IManagedIdentityApplication mi = miBuilder.Build(); - MsalServiceException ex = await Assert.ThrowsExceptionAsync(async () => + MsalServiceException ex = await Assert.ThrowsAsync(async () => await mi.AcquireTokenForManagedIdentity("scope") .ExecuteAsync().ConfigureAwait(false)).ConfigureAwait(false); @@ -68,7 +68,7 @@ public async Task AzureArcAuthHeaderMissingAsync() httpManager.AddManagedIdentityWSTrustMockHandler(ManagedIdentityTests.AzureArcEndpoint); - MsalServiceException ex = await Assert.ThrowsExceptionAsync(async () => + MsalServiceException ex = await Assert.ThrowsAsync(async () => await mi.AcquireTokenForManagedIdentity("scope") .ExecuteAsync().ConfigureAwait(false)).ConfigureAwait(false); @@ -79,7 +79,7 @@ await mi.AcquireTokenForManagedIdentity("scope") } } - [DataTestMethod] + [TestMethod] [DataRow("somefile=filename", MsalErrorMessage.ManagedIdentityInvalidChallenge)] [DataRow("C:\\ProgramData\\AzureConnectedMachineAgent\\Tokens\\filename.txt", MsalErrorMessage.ManagedIdentityInvalidFile)] [DataRow("C:\\ProgramData\\AzureConnectedMachineAgent\\Tokens\\...\\etc\\filename.key", MsalErrorMessage.ManagedIdentityInvalidFile)] @@ -100,7 +100,7 @@ public async Task AzureArcAuthHeaderInvalidAsync(string filename, string errorMe httpManager.AddManagedIdentityWSTrustMockHandler(ManagedIdentityTests.AzureArcEndpoint, filename); - MsalServiceException ex = await Assert.ThrowsExceptionAsync(async () => + MsalServiceException ex = await Assert.ThrowsAsync(async () => await mi.AcquireTokenForManagedIdentity("scope") .ExecuteAsync().ConfigureAwait(false)).ConfigureAwait(false); @@ -127,7 +127,7 @@ public async Task AzureArcInvalidEndpointAsync() var mi = miBuilder.Build(); - MsalServiceException ex = await Assert.ThrowsExceptionAsync(async () => + MsalServiceException ex = await Assert.ThrowsAsync(async () => await mi.AcquireTokenForManagedIdentity(ManagedIdentityTests.Resource) .ExecuteAsync().ConfigureAwait(false)).ConfigureAwait(false); diff --git a/tests/Microsoft.Identity.Test.Unit/ManagedIdentityTests/CloudShellTests.cs b/tests/Microsoft.Identity.Test.Unit/ManagedIdentityTests/CloudShellTests.cs index 90dd8da152..1d2a23b69b 100644 --- a/tests/Microsoft.Identity.Test.Unit/ManagedIdentityTests/CloudShellTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/ManagedIdentityTests/CloudShellTests.cs @@ -21,7 +21,7 @@ public class CloudShellTests : TestBase { private const string CloudShell = "Cloud Shell"; - [DataTestMethod] + [TestMethod] [DataRow(TestConstants.ClientId, UserAssignedIdentityId.ClientId)] [DataRow("resourceId", UserAssignedIdentityId.ResourceId)] [DataRow(TestConstants.ObjectId, UserAssignedIdentityId.ObjectId)] @@ -37,7 +37,7 @@ public async Task CloudShellUserAssignedManagedIdentityNotSupportedAsync(string IManagedIdentityApplication mi = miBuilder.Build(); - MsalServiceException ex = await Assert.ThrowsExceptionAsync(async () => + MsalServiceException ex = await Assert.ThrowsAsync(async () => await mi.AcquireTokenForManagedIdentity("scope") .ExecuteAsync().ConfigureAwait(false)).ConfigureAwait(false); @@ -64,7 +64,7 @@ public async Task CloudShellInvalidEndpointAsync() var mi = miBuilder.Build(); - MsalServiceException ex = await Assert.ThrowsExceptionAsync(async () => + MsalServiceException ex = await Assert.ThrowsAsync(async () => await mi.AcquireTokenForManagedIdentity(ManagedIdentityTests.Resource) .ExecuteAsync().ConfigureAwait(false)).ConfigureAwait(false); diff --git a/tests/Microsoft.Identity.Test.Unit/ManagedIdentityTests/CsrValidator.cs b/tests/Microsoft.Identity.Test.Unit/ManagedIdentityTests/CsrValidator.cs index 5af70fc059..5f30827eb0 100644 --- a/tests/Microsoft.Identity.Test.Unit/ManagedIdentityTests/CsrValidator.cs +++ b/tests/Microsoft.Identity.Test.Unit/ManagedIdentityTests/CsrValidator.cs @@ -59,8 +59,8 @@ public static void ValidateCsrContent(string rawCsr, string expectedClientId, st var subject = new X500DistinguishedName(certReqInfoSeq.ReadEncodedValue().ToArray()); string subjectString = subject.Name; - Assert.IsTrue(subjectString.Contains($"CN={expectedClientId}"), "Client ID (CN) not found in subject"); - Assert.IsTrue(subjectString.Contains($"DC={expectedTenantId}"), "Tenant ID (DC) not found in subject"); + Assert.Contains($"CN={expectedClientId}", subjectString, "Client ID (CN) not found in subject"); + Assert.Contains($"DC={expectedTenantId}", subjectString, "Tenant ID (DC) not found in subject"); // subjectPKInfo var pkInfoReader = new AsnReader(certReqInfoSeq.ReadEncodedValue().ToArray(), AsnEncodingRules.DER); diff --git a/tests/Microsoft.Identity.Test.Unit/ManagedIdentityTests/DefaultRetryPolicyTests.cs b/tests/Microsoft.Identity.Test.Unit/ManagedIdentityTests/DefaultRetryPolicyTests.cs index 0126093fb4..4cc0e8a32c 100644 --- a/tests/Microsoft.Identity.Test.Unit/ManagedIdentityTests/DefaultRetryPolicyTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/ManagedIdentityTests/DefaultRetryPolicyTests.cs @@ -25,7 +25,7 @@ public class DefaultRetryPolicyTests : TestBase { private readonly TestRetryPolicyFactory _testRetryPolicyFactory = new TestRetryPolicyFactory(); - [DataTestMethod] // see test class header: all sources that allow UAMI + [TestMethod] // see test class header: all sources that allow UAMI [DataRow(ManagedIdentitySource.AppService, TestConstants.AppServiceEndpoint)] [DataRow(ManagedIdentitySource.MachineLearning, TestConstants.MachineLearningEndpoint)] [DataRow(ManagedIdentitySource.ServiceFabric, TestConstants.ServiceFabricEndpoint)] @@ -74,7 +74,7 @@ public async Task UAMIFails500OnceThenSucceeds200Async( await mi.AcquireTokenForManagedIdentity(ManagedIdentityTests.Resource) .ExecuteAsync() .ConfigureAwait(false); - Assert.AreEqual(result.AccessToken, TestConstants.ATSecret); + Assert.AreEqual(TestConstants.ATSecret, result.AccessToken); const int NumRequests = 2; // initial request + 1 retry int requestsMade = NumRequests - httpManager.QueueSize; @@ -82,7 +82,7 @@ await mi.AcquireTokenForManagedIdentity(ManagedIdentityTests.Resource) } } - [DataTestMethod] // see test class header: all sources that allow UAMI + [TestMethod] // see test class header: all sources that allow UAMI [DataRow(ManagedIdentitySource.AppService, TestConstants.AppServiceEndpoint)] [DataRow(ManagedIdentitySource.MachineLearning, TestConstants.MachineLearningEndpoint)] [DataRow(ManagedIdentitySource.ServiceFabric, TestConstants.ServiceFabricEndpoint)] @@ -140,7 +140,7 @@ await mi.AcquireTokenForManagedIdentity(ManagedIdentityTests.Resource) } } - [DataTestMethod] + [TestMethod] [DataRow(ManagedIdentitySource.AppService, TestConstants.AppServiceEndpoint, null)] [DataRow(ManagedIdentitySource.AzureArc, TestConstants.AzureArcEndpoint, null)] [DataRow(ManagedIdentitySource.CloudShell, TestConstants.CloudShellEndpoint, null)] @@ -195,7 +195,7 @@ public async Task SAMIFails500OnceWithVariousRetryAfterHeaderValuesThenSucceeds2 await mi.AcquireTokenForManagedIdentity(ManagedIdentityTests.Resource) .ExecuteAsync() .ConfigureAwait(false); - Assert.AreEqual(result.AccessToken, TestConstants.ATSecret); + Assert.AreEqual(TestConstants.ATSecret, result.AccessToken); const int NumRequests = 2; // initial request + 1 retry int requestsMade = NumRequests - httpManager.QueueSize; @@ -203,7 +203,7 @@ await mi.AcquireTokenForManagedIdentity(ManagedIdentityTests.Resource) } } - [DataTestMethod] // see test class header: all sources allow SAMI + [TestMethod] // see test class header: all sources allow SAMI [DataRow(ManagedIdentitySource.AppService, TestConstants.AppServiceEndpoint)] [DataRow(ManagedIdentitySource.AzureArc, TestConstants.AzureArcEndpoint)] [DataRow(ManagedIdentitySource.CloudShell, TestConstants.CloudShellEndpoint)] @@ -257,7 +257,7 @@ await mi.AcquireTokenForManagedIdentity(ManagedIdentityTests.Resource) } } - [DataTestMethod] // see test class header: all sources allow SAMI + [TestMethod] // see test class header: all sources allow SAMI [DataRow(ManagedIdentitySource.AppService, TestConstants.AppServiceEndpoint)] [DataRow(ManagedIdentitySource.AzureArc, TestConstants.AzureArcEndpoint)] [DataRow(ManagedIdentitySource.CloudShell, TestConstants.CloudShellEndpoint)] @@ -307,7 +307,7 @@ await mi.AcquireTokenForManagedIdentity(ManagedIdentityTests.Resource) } } - [DataTestMethod] // see test class header: all sources allow SAMI + [TestMethod] // see test class header: all sources allow SAMI [DataRow(ManagedIdentitySource.AppService, TestConstants.AppServiceEndpoint)] [DataRow(ManagedIdentitySource.AzureArc, TestConstants.AzureArcEndpoint)] [DataRow(ManagedIdentitySource.CloudShell, TestConstants.CloudShellEndpoint)] diff --git a/tests/Microsoft.Identity.Test.Unit/ManagedIdentityTests/FriendlyNameCodecTests.cs b/tests/Microsoft.Identity.Test.Unit/ManagedIdentityTests/FriendlyNameCodecTests.cs index 8d86534f2a..ff5ca20f66 100644 --- a/tests/Microsoft.Identity.Test.Unit/ManagedIdentityTests/FriendlyNameCodecTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/ManagedIdentityTests/FriendlyNameCodecTests.cs @@ -24,7 +24,7 @@ public void EncodeDecode_RoundTrip_Succeeds() Assert.AreEqual(ep, ep2); } - [DataTestMethod] + [TestMethod] [DataRow("foo|bar", "https://x")] [DataRow("foo\nbar", "https://x")] [DataRow("foo", "https://x|y")] diff --git a/tests/Microsoft.Identity.Test.Unit/ManagedIdentityTests/ImdsTests.cs b/tests/Microsoft.Identity.Test.Unit/ManagedIdentityTests/ImdsTests.cs index 204074482d..43c3872ebe 100644 --- a/tests/Microsoft.Identity.Test.Unit/ManagedIdentityTests/ImdsTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/ManagedIdentityTests/ImdsTests.cs @@ -23,7 +23,7 @@ public class ImdsTests : TestBase { private readonly TestRetryPolicyFactory _testRetryPolicyFactory = new TestRetryPolicyFactory(); - [DataTestMethod] + [TestMethod] [DataRow(null, null)] // SAMI [DataRow(TestConstants.ClientId, UserAssignedIdentityId.ClientId)] // UAMI public async Task ImdsFails404TwiceThenSucceeds200Async( @@ -73,7 +73,7 @@ public async Task ImdsFails404TwiceThenSucceeds200Async( await mi.AcquireTokenForManagedIdentity(ManagedIdentityTests.Resource) .ExecuteAsync() .ConfigureAwait(false); - Assert.AreEqual(result.AccessToken, TestConstants.ATSecret); + Assert.AreEqual(TestConstants.ATSecret, result.AccessToken); const int NumRequests = 1 + Num404Errors; // initial request + 2 retries int requestsMade = NumRequests - httpManager.QueueSize; @@ -81,7 +81,7 @@ await mi.AcquireTokenForManagedIdentity(ManagedIdentityTests.Resource) } } - [DataTestMethod] + [TestMethod] [DataRow(null, null)] // SAMI [DataRow(TestConstants.ClientId, UserAssignedIdentityId.ClientId)] // UAMI public async Task ImdsFails410FourTimesThenSucceeds200Async( @@ -131,7 +131,7 @@ public async Task ImdsFails410FourTimesThenSucceeds200Async( await mi.AcquireTokenForManagedIdentity(ManagedIdentityTests.Resource) .ExecuteAsync() .ConfigureAwait(false); - Assert.AreEqual(result.AccessToken, TestConstants.ATSecret); + Assert.AreEqual(TestConstants.ATSecret, result.AccessToken); const int NumRequests = 1 + Num410Errors; // initial request + 4 retries int requestsMade = NumRequests - httpManager.QueueSize; @@ -139,7 +139,7 @@ await mi.AcquireTokenForManagedIdentity(ManagedIdentityTests.Resource) } } - [DataTestMethod] + [TestMethod] [DataRow(null, null)] // SAMI [DataRow(TestConstants.ClientId, UserAssignedIdentityId.ClientId)] // UAMI public async Task ImdsFails410PermanentlyAsync( @@ -194,7 +194,7 @@ await mi.AcquireTokenForManagedIdentity(ManagedIdentityTests.Resource) } } - [DataTestMethod] + [TestMethod] [DataRow(null, null)] // SAMI [DataRow(TestConstants.ClientId, UserAssignedIdentityId.ClientId)] // UAMI public async Task ImdsFails504PermanentlyAsync( @@ -249,7 +249,7 @@ await mi.AcquireTokenForManagedIdentity(ManagedIdentityTests.Resource) } } - [DataTestMethod] + [TestMethod] [DataRow(null, null)] // SAMI [DataRow(TestConstants.ClientId, UserAssignedIdentityId.ClientId)] // UAMI public async Task ImdsFails400WhichIsNonRetriableAndRetryPolicyIsNotTriggeredAsync( @@ -300,7 +300,7 @@ await mi.AcquireTokenForManagedIdentity(ManagedIdentityTests.Resource) } } - [DataTestMethod] + [TestMethod] [DataRow(null, null)] // SAMI [DataRow(TestConstants.ClientId, UserAssignedIdentityId.ClientId)] // UAMI public async Task ImdsFails500AndRetryPolicyIsDisabledAndNotTriggeredAsync( @@ -381,7 +381,7 @@ public async Task ImdsRetryPolicyLifeTimeIsPerRequestAsync() } MsalServiceException ex = - await Assert.ThrowsExceptionAsync(async () => + await AssertException.TaskThrowsAsync(async () => await mi.AcquireTokenForManagedIdentity(ManagedIdentityTests.Resource) .ExecuteAsync() .ConfigureAwait(false)) @@ -401,7 +401,7 @@ await mi.AcquireTokenForManagedIdentity(ManagedIdentityTests.Resource) statusCode: HttpStatusCode.GatewayTimeout); } - ex = await Assert.ThrowsExceptionAsync(async () => + ex = await AssertException.TaskThrowsAsync(async () => await mi.AcquireTokenForManagedIdentity(ManagedIdentityTests.Resource) .ExecuteAsync() .ConfigureAwait(false)) @@ -422,7 +422,7 @@ await mi.AcquireTokenForManagedIdentity(ManagedIdentityTests.Resource) statusCode: HttpStatusCode.GatewayTimeout); } - ex = await Assert.ThrowsExceptionAsync(async () => + ex = await Assert.ThrowsAsync(async () => await mi.AcquireTokenForManagedIdentity(ManagedIdentityTests.Resource) .ExecuteAsync() .ConfigureAwait(false)) @@ -457,7 +457,7 @@ public async Task ProbeImdsEndpointAsync_TimesOutAfterOneSecond() var miSource = await (managedIdentityApp as ManagedIdentityApplication).GetManagedIdentitySourceAsync(imdsProbesCancellationToken).ConfigureAwait(false); Assert.AreEqual(ManagedIdentitySource.None, miSource); // Probe timed out, no source available - var ex = await Assert.ThrowsExceptionAsync(async () => + var ex = await Assert.ThrowsAsync(async () => await managedIdentityApp.AcquireTokenForManagedIdentity(ManagedIdentityTests.Resource) .ExecuteAsync().ConfigureAwait(false) ).ConfigureAwait(false); diff --git a/tests/Microsoft.Identity.Test.Unit/ManagedIdentityTests/ImdsV2Tests.cs b/tests/Microsoft.Identity.Test.Unit/ManagedIdentityTests/ImdsV2Tests.cs index 7e61d7d908..1f12d6ee0a 100644 --- a/tests/Microsoft.Identity.Test.Unit/ManagedIdentityTests/ImdsV2Tests.cs +++ b/tests/Microsoft.Identity.Test.Unit/ManagedIdentityTests/ImdsV2Tests.cs @@ -160,7 +160,7 @@ private async Task CreateManagedIdentityAsync( } #region Acceptance Tests - [DataTestMethod] + [TestMethod] [DataRow(UserAssignedIdentityId.None, null)] // SAMI [DataRow(UserAssignedIdentityId.ClientId, TestConstants.ClientId)] // UAMI [DataRow(UserAssignedIdentityId.ResourceId, TestConstants.MiResourceId)] // UAMI @@ -185,7 +185,7 @@ public async Task mTLSPopTokenHappyPath( Assert.IsNotNull(result); Assert.IsNotNull(result.AccessToken); - Assert.AreEqual(result.TokenType, MTLSPoP); + Assert.AreEqual(MTLSPoP, result.TokenType); Assert.IsNotNull(result.BindingCertificate); Assert.AreEqual(TokenSource.IdentityProvider, result.AuthenticationResultMetadata.TokenSource); @@ -196,13 +196,13 @@ public async Task mTLSPopTokenHappyPath( Assert.IsNotNull(result); Assert.IsNotNull(result.AccessToken); - Assert.AreEqual(result.TokenType, MTLSPoP); + Assert.AreEqual(MTLSPoP, result.TokenType); Assert.IsNotNull(result.BindingCertificate); Assert.AreEqual(TokenSource.Cache, result.AuthenticationResultMetadata.TokenSource); } } - [DataTestMethod] + [TestMethod] [DataRow(UserAssignedIdentityId.ClientId, TestConstants.ClientId, $"{TestConstants.ClientId}-2")] [DataRow(UserAssignedIdentityId.ResourceId, TestConstants.MiResourceId, $"{TestConstants.MiResourceId}-2")] [DataRow(UserAssignedIdentityId.ObjectId, TestConstants.ObjectId, $"{TestConstants.ObjectId}-2")] @@ -228,7 +228,7 @@ public async Task mTLSPopTokenIsPerIdentity( Assert.IsNotNull(result); Assert.IsNotNull(result.AccessToken); - Assert.AreEqual(result.TokenType, MTLSPoP); + Assert.AreEqual(MTLSPoP, result.TokenType); Assert.IsNotNull(result.BindingCertificate); Assert.AreEqual(TokenSource.IdentityProvider, result.AuthenticationResultMetadata.TokenSource); @@ -238,7 +238,7 @@ public async Task mTLSPopTokenIsPerIdentity( Assert.IsNotNull(result); Assert.IsNotNull(result.AccessToken); - Assert.AreEqual(result.TokenType, MTLSPoP); + Assert.AreEqual(MTLSPoP, result.TokenType); Assert.IsNotNull(result.BindingCertificate); Assert.AreEqual(TokenSource.Cache, result.AuthenticationResultMetadata.TokenSource); #endregion Identity 1 @@ -262,7 +262,7 @@ public async Task mTLSPopTokenIsPerIdentity( Assert.IsNotNull(result2); Assert.IsNotNull(result2.AccessToken); - Assert.AreEqual(result2.TokenType, MTLSPoP); + Assert.AreEqual(MTLSPoP, result2.TokenType); Assert.IsNotNull(result2.BindingCertificate); Assert.AreEqual(TokenSource.IdentityProvider, result2.AuthenticationResultMetadata.TokenSource); @@ -273,7 +273,7 @@ public async Task mTLSPopTokenIsPerIdentity( Assert.IsNotNull(result2); Assert.IsNotNull(result2.AccessToken); - Assert.AreEqual(result2.TokenType, MTLSPoP); + Assert.AreEqual(MTLSPoP, result2.TokenType); Assert.IsNotNull(result2.BindingCertificate); Assert.AreEqual(TokenSource.Cache, result2.AuthenticationResultMetadata.TokenSource); #endregion Identity 2 @@ -282,7 +282,7 @@ public async Task mTLSPopTokenIsPerIdentity( } } - [DataTestMethod] + [TestMethod] [DataRow(UserAssignedIdentityId.None, null)] // SAMI [DataRow(UserAssignedIdentityId.ClientId, TestConstants.ClientId)] // UAMI [DataRow(UserAssignedIdentityId.ResourceId, TestConstants.MiResourceId)] // UAMI @@ -307,7 +307,7 @@ public async Task mTLSPopTokenIsReAcquiredWhenCertificateIsExpired( Assert.IsNotNull(result); Assert.IsNotNull(result.AccessToken); - Assert.AreEqual(result.TokenType, MTLSPoP); + Assert.AreEqual(MTLSPoP, result.TokenType); Assert.IsNotNull(result.BindingCertificate); Assert.AreEqual(TokenSource.IdentityProvider, result.AuthenticationResultMetadata.TokenSource); @@ -331,7 +331,7 @@ public async Task mTLSPopTokenIsReAcquiredWhenCertificateIsExpired( #endregion Acceptance Tests #region Failure Tests - [DataTestMethod] + [TestMethod] [DataRow(UserAssignedIdentityId.None, null)] // SAMI [DataRow(UserAssignedIdentityId.ClientId, TestConstants.ClientId)] // UAMI [DataRow(UserAssignedIdentityId.ResourceId, TestConstants.MiResourceId)] // UAMI @@ -347,7 +347,7 @@ public async Task ImdsV2EndpointsAreNotAvailableButMtlsPopTokenWasRequested( var managedIdentityApp = await CreateManagedIdentityAsync(httpManager, userAssignedIdentityId, userAssignedId, imdsVersion: ImdsVersion.V1).ConfigureAwait(false); - var ex = await Assert.ThrowsExceptionAsync(async () => + var ex = await Assert.ThrowsAsync(async () => await managedIdentityApp.AcquireTokenForManagedIdentity(ManagedIdentityTests.Resource) .WithMtlsProofOfPossession() .ExecuteAsync().ConfigureAwait(false) @@ -357,7 +357,7 @@ await managedIdentityApp.AcquireTokenForManagedIdentity(ManagedIdentityTests.Res } } - [DataTestMethod] + [TestMethod] [DataRow(UserAssignedIdentityId.None, null)] // SAMI [DataRow(UserAssignedIdentityId.ClientId, TestConstants.ClientId)] // UAMI [DataRow(UserAssignedIdentityId.ResourceId, TestConstants.MiResourceId)] // UAMI @@ -388,7 +388,7 @@ public async Task ApplicationsCannotSwitchBetweenImdsVersionsForPreview( .ExecuteAsync().ConfigureAwait(false); Assert.IsNotNull(result); - Assert.AreEqual(result.TokenType, Bearer); + Assert.AreEqual(Bearer, result.TokenType); Assert.AreEqual(TokenSource.IdentityProvider, result.AuthenticationResultMetadata.TokenSource); // even though the app fell back to ImdsV1, the source should still be ImdsV2 @@ -396,7 +396,7 @@ public async Task ApplicationsCannotSwitchBetweenImdsVersionsForPreview( Assert.AreEqual(ManagedIdentitySource.ImdsV2, miSource); // none of the mocks from AddMocksToGetEntraToken are needed since checking the cache occurs before the network requests - var ex = await Assert.ThrowsExceptionAsync(async () => + var ex = await Assert.ThrowsAsync(async () => await managedIdentityApp.AcquireTokenForManagedIdentity(ManagedIdentityTests.Resource) .WithMtlsProofOfPossession() // this will cause an error to be thrown since the app already fell back to ImdsV1 .ExecuteAsync().ConfigureAwait(false) @@ -460,7 +460,7 @@ public async Task ProbeImdsEndpointAsyncFails404WhichIsNonRetriableAndRetryPolic #region Fallback Behavior Tests // Verifies non-mTLS request after IMDSv2 detection falls back per-request to IMDSv1 (Bearer), - [DataTestMethod] + [TestMethod] [DataRow(UserAssignedIdentityId.None, null)] [DataRow(UserAssignedIdentityId.ClientId, TestConstants.ClientId)] public async Task NonMtlsRequest_FallsBackToImdsV1( @@ -536,7 +536,7 @@ public async Task GetCsrMetadataAsyncFailsWithMissingServerHeader() httpManager.AddMockHandler(MockHelpers.MockCsrResponse(responseServerHeader: null)); - var ex = await Assert.ThrowsExceptionAsync(async () => + var ex = await Assert.ThrowsAsync(async () => await managedIdentityApp.AcquireTokenForManagedIdentity(ManagedIdentityTests.Resource) .WithMtlsProofOfPossession() .ExecuteAsync().ConfigureAwait(false) @@ -558,7 +558,7 @@ public async Task GetCsrMetadataAsyncFailsWithInvalidFormat() httpManager.AddMockHandler(MockHelpers.MockCsrResponse(responseServerHeader: "I_MDS/150.870.65.1854")); - var ex = await Assert.ThrowsExceptionAsync(async () => + var ex = await Assert.ThrowsAsync(async () => await managedIdentityApp.AcquireTokenForManagedIdentity(ManagedIdentityTests.Resource) .WithMtlsProofOfPossession() .ExecuteAsync().ConfigureAwait(false) @@ -597,13 +597,13 @@ public void TestCsrGeneration_VmIdAndVmssId() CsrValidator.ValidateCsrContent(csr, TestConstants.ClientId, TestConstants.TenantId, cuid); } - [DataTestMethod] + [TestMethod] [DataRow("Invalid@#$%Certificate!")] [DataRow("")] [DataRow(null)] public void TestCsrGeneration_BadCert_ThrowsMsalServiceException(string badCert) { - Assert.ThrowsException(() => + Assert.Throws(() => CsrValidator.ParseRawCsr(badCert)); } #endregion CSR Generation Tests @@ -619,7 +619,7 @@ public void AttachPrivateKeyToCert_ValidInputs_ReturnsValidCertificate() } } - [DataTestMethod] + [TestMethod] [DataRow("Invalid@#$%Certificate!")] [DataRow("")] [DataRow(null)] @@ -627,7 +627,7 @@ public void AttachPrivateKeyToCert_BadContent_ThrowsMsalServiceException(string { using (RSA rsa = RSA.Create()) { - Assert.ThrowsException(() => + Assert.Throws(() => CommonCryptographyManager.AttachPrivateKeyToCert(badCert, rsa)); } } @@ -635,7 +635,7 @@ public void AttachPrivateKeyToCert_BadContent_ThrowsMsalServiceException(string [TestMethod] public void AttachPrivateKeyToCert_NullPrivateKey_ThrowsArgumentNullException() { - Assert.ThrowsException(() => + Assert.Throws(() => CommonCryptographyManager.AttachPrivateKeyToCert(TestConstants.ValidRawCertificate, null)); } #endregion @@ -654,7 +654,7 @@ public async Task MtlsPop_AttestationProviderMissing_ThrowsClientException() // CreateManagedIdentityAsync does a probe; Add one more CSR response for the actual acquire. httpManager.AddMockHandler(MockHelpers.MockCsrResponse()); - var ex = await Assert.ThrowsExceptionAsync(async () => + var ex = await Assert.ThrowsAsync(async () => await mi.AcquireTokenForManagedIdentity(ManagedIdentityTests.Resource) .WithMtlsProofOfPossession() // Intentionally DO NOT call .WithAttestationProviderForTests(...) @@ -681,7 +681,7 @@ public async Task MtlsPop_AttestationProviderReturnsNull_ThrowsClientException() var nullProvider = new Func>( (input, ct) => Task.FromResult(null)); - var ex = await Assert.ThrowsExceptionAsync(async () => + var ex = await Assert.ThrowsAsync(async () => await mi.AcquireTokenForManagedIdentity(ManagedIdentityTests.Resource) .WithMtlsProofOfPossession() .WithAttestationProviderForTests(nullProvider) @@ -708,7 +708,7 @@ public async Task MtlsPop_AttestationProviderReturnsEmptyToken_ThrowsClientExcep var emptyProvider = new Func>( (input, ct) => Task.FromResult(new AttestationTokenResponse { AttestationToken = " " })); - var ex = await Assert.ThrowsExceptionAsync(async () => + var ex = await Assert.ThrowsAsync(async () => await mi.AcquireTokenForManagedIdentity(ManagedIdentityTests.Resource) .WithMtlsProofOfPossession() .WithAttestationProviderForTests(emptyProvider) @@ -736,7 +736,7 @@ public async Task mTLSPop_RequestedWithoutKeyGuard_ThrowsClientException() // CreateManagedIdentityAsync does a probe; Add one more CSR response for the actual acquire. httpManager.AddMockHandler(MockHelpers.MockCsrResponse()); - var ex = await Assert.ThrowsExceptionAsync(async () => + var ex = await Assert.ThrowsAsync(async () => await managedIdentityApp.AcquireTokenForManagedIdentity(ManagedIdentityTests.Resource) .WithMtlsProofOfPossession() // request PoP on a non-KeyGuard env .ExecuteAsync().ConfigureAwait(false) @@ -802,7 +802,7 @@ public async Task mTLSPop_ForceRefresh_UsesCachedCert_NoIssueCredential_PostsCan } } - [DataTestMethod] + [TestMethod] [DataRow(UserAssignedIdentityId.ClientId, TestConstants.ClientId, TestConstants.ClientId + "-2")] [DataRow(UserAssignedIdentityId.ResourceId, TestConstants.MiResourceId, TestConstants.MiResourceId + "-2")] [DataRow(UserAssignedIdentityId.ObjectId, TestConstants.ObjectId, TestConstants.ObjectId + "-2")] @@ -861,7 +861,7 @@ public async Task mTLSPop_CachedCertIsPerIdentity_OnRefresh_Identity1UsesCache_I #region Cert cache tests - [DataTestMethod] + [TestMethod] [DataRow(UserAssignedIdentityId.None, null, /*isUami*/ false)] // SAMI [DataRow(UserAssignedIdentityId.ClientId, TestConstants.ClientId, /*isUami*/ true)] // UAMI by client_id [DataRow(UserAssignedIdentityId.ResourceId, TestConstants.MiResourceId, /*isUami*/ true)] // UAMI by resource_id @@ -931,7 +931,7 @@ public async Task mTLSPopTokenHappyPath_LongLivedCert_IdentityMapping( /// - One for UAMI (CN=UAMI-20Y) /// Then run mint + cached flows and assert thumbprints. /// - [DataTestMethod] + [TestMethod] [DataRow(UserAssignedIdentityId.None, null, /*aliasLabel*/ "SAMI")] // SAMI [DataRow(UserAssignedIdentityId.ClientId, TestConstants.ClientId, /*aliasLabel*/ "UAMI-ClientId")] [DataRow(UserAssignedIdentityId.ResourceId, TestConstants.MiResourceId,/*aliasLabel*/ "UAMI-ResourceId")] @@ -1093,7 +1093,7 @@ public async Task mTLSPop_LongLivedCerts_SamiAndUami_ThumbprintsDiffer_AndEachCa /// - UAMI (client_id|object_id|resource_id) → CN = TestConstants.ClientId (canonical) /// Both assert DC = TestConstants.TenantId and cert cache reuse. /// - [DataTestMethod] + [TestMethod] [DataRow(UserAssignedIdentityId.None, null, /*label*/ "SAMI", /*isUami*/ false)] [DataRow(UserAssignedIdentityId.ClientId, TestConstants.ClientId, /*label*/ "UAMI-ClientId", /*isUami*/ true)] [DataRow(UserAssignedIdentityId.ObjectId, TestConstants.ObjectId, /*label*/ "UAMI-ObjectId", /*isUami*/ true)] @@ -1210,7 +1210,7 @@ public async Task mTLSPoP_Uami_ClientIdThenObjectId_MintsThenCaches_SubjectCNIsC } } - [DataTestMethod] + [TestMethod] [DataRow(UserAssignedIdentityId.ObjectId, TestConstants.ObjectId, "object_id")] [DataRow(UserAssignedIdentityId.ResourceId, TestConstants.MiResourceId, "resource_id")] public async Task mTLSPoP_Uami_ClientIdThenAlias_MintsThenCaches_SubjectCNIsClientId( @@ -1286,7 +1286,7 @@ public async Task mTLSPoP_Uami_ClientIdThenAlias_MintsThenCaches_SubjectCNIsClie } } - [DataTestMethod] + [TestMethod] [DataRow(UserAssignedIdentityId.ClientId, TestConstants.ClientId, "UAMI-ClientId")] [DataRow(UserAssignedIdentityId.ObjectId, TestConstants.ObjectId, "UAMI-ObjectId")] [DataRow(UserAssignedIdentityId.ResourceId, TestConstants.MiResourceId, "UAMI-ResourceId")] @@ -1340,7 +1340,7 @@ public async Task mTLSPop_ShortLivedCert_LessThan24h_NotCached_ReMints( } } - [DataTestMethod] + [TestMethod] [DataRow(UserAssignedIdentityId.ClientId, TestConstants.ClientId, "UAMI-ClientId")] [DataRow(UserAssignedIdentityId.ObjectId, TestConstants.ObjectId, "UAMI-ObjectId")] [DataRow(UserAssignedIdentityId.ResourceId, TestConstants.MiResourceId, "UAMI-ResourceId")] diff --git a/tests/Microsoft.Identity.Test.Unit/ManagedIdentityTests/InMemoryCertificateCacheTests.cs b/tests/Microsoft.Identity.Test.Unit/ManagedIdentityTests/InMemoryCertificateCacheTests.cs index fe7befba61..0d3cac888c 100644 --- a/tests/Microsoft.Identity.Test.Unit/ManagedIdentityTests/InMemoryCertificateCacheTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/ManagedIdentityTests/InMemoryCertificateCacheTests.cs @@ -140,18 +140,18 @@ public void Validate_Arguments() using var cert = CreateSelfSignedCert(TimeSpan.FromDays(2)); // TryGet - Assert.ThrowsException(() => cache.TryGet(" ", out _)); - Assert.ThrowsException(() => cache.TryGet(null, out _)); + Assert.Throws(() => cache.TryGet(" ", out _)); + Assert.Throws(() => cache.TryGet(null, out _)); // Set - Assert.ThrowsException(() => cache.Set(" ", new CertificateCacheValue(cert, "ep", "cid"))); - Assert.ThrowsException(() => cache.Set("k", new CertificateCacheValue(null, "ep", "cid"))); // This will throw as expected in the test - Assert.ThrowsException(() => cache.Set("k", new CertificateCacheValue(cert, " ", "cid"))); - Assert.ThrowsException(() => cache.Set("k", new CertificateCacheValue(cert, "ep", " "))); + Assert.Throws(() => cache.Set(" ", new CertificateCacheValue(cert, "ep", "cid"))); + Assert.Throws(() => cache.Set("k", new CertificateCacheValue(null, "ep", "cid"))); // This will throw as expected in the test + Assert.Throws(() => cache.Set("k", new CertificateCacheValue(cert, " ", "cid"))); + Assert.Throws(() => cache.Set("k", new CertificateCacheValue(cert, "ep", " "))); // Remove - Assert.ThrowsException(() => cache.Remove("")); - Assert.ThrowsException(() => cache.Remove(null)); + Assert.Throws(() => cache.Remove("")); + Assert.Throws(() => cache.Remove(null)); } [TestMethod] @@ -160,11 +160,11 @@ public void Dispose_Prevents_Use() var cache = new InMemoryCertificateCache(); cache.Dispose(); - Assert.ThrowsException(() => cache.TryGet("k", out _)); + Assert.Throws(() => cache.TryGet("k", out _)); using var cert = CreateSelfSignedCert(TimeSpan.FromDays(2)); - Assert.ThrowsException(() => cache.Set("k", new CertificateCacheValue(cert, "ep", "cid"))); - Assert.ThrowsException(() => cache.Remove("k")); - Assert.ThrowsException(() => cache.Clear()); + Assert.Throws(() => cache.Set("k", new CertificateCacheValue(cert, "ep", "cid"))); + Assert.Throws(() => cache.Remove("k")); + Assert.Throws(() => cache.Clear()); } [TestMethod] @@ -299,17 +299,17 @@ private static X509Certificate2 MakeCert() public void Ctor_Throws_On_Nulls() { // certificate null - Assert.ThrowsException(() => + Assert.Throws(() => new CertificateCacheValue(null, "ep", "cid")); using var cert = MakeCert(); // endpoint null - Assert.ThrowsException(() => + Assert.Throws(() => new CertificateCacheValue(cert, null, "cid")); // clientId null - Assert.ThrowsException(() => + Assert.Throws(() => new CertificateCacheValue(cert, "ep", null)); } diff --git a/tests/Microsoft.Identity.Test.Unit/ManagedIdentityTests/InMemoryManagedIdentityKeyProviderTests.cs b/tests/Microsoft.Identity.Test.Unit/ManagedIdentityTests/InMemoryManagedIdentityKeyProviderTests.cs index ba501fce15..72e8e269a2 100644 --- a/tests/Microsoft.Identity.Test.Unit/ManagedIdentityTests/InMemoryManagedIdentityKeyProviderTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/ManagedIdentityTests/InMemoryManagedIdentityKeyProviderTests.cs @@ -34,7 +34,7 @@ public async Task ReturnsRsa2048_AndCaches_Success() Assert.IsNotNull(k1); Assert.AreSame(k1, k2, "Provider should cache the same ManagedIdentityKeyInfo instance per process."); Assert.IsInstanceOfType(k1.Key, typeof(RSA)); - Assert.IsTrue(k1.Key.KeySize >= Constants.RsaKeySize); + Assert.IsGreaterThanOrEqualTo(Constants.RsaKeySize, k1.Key.KeySize); Assert.AreEqual(ManagedIdentityKeyType.InMemory, k1.Type); } @@ -79,7 +79,7 @@ public async Task Cancellation_BeforeCreation_Throws_And_SubsequentCallSucceeds( { cts.Cancel(); // Pre-cancel so WaitAsync throws TaskCanceledException. - await Assert.ThrowsExceptionAsync( + await Assert.ThrowsAsync( () => keyProvider.GetOrCreateKeyAsync(logger, cts.Token)).ConfigureAwait(false); } diff --git a/tests/Microsoft.Identity.Test.Unit/ManagedIdentityTests/MachineLearningTests.cs b/tests/Microsoft.Identity.Test.Unit/ManagedIdentityTests/MachineLearningTests.cs index 40304cebcd..e5edca24b5 100644 --- a/tests/Microsoft.Identity.Test.Unit/ManagedIdentityTests/MachineLearningTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/ManagedIdentityTests/MachineLearningTests.cs @@ -22,7 +22,7 @@ public class MachineLearningTests : TestBase private const string MachineLearningEndpoint = "http://localhost:7071/msi/token"; internal const string Resource = "https://management.azure.com"; - [DataTestMethod] + [TestMethod] [DataRow(null, null)] // SAMI [DataRow(TestConstants.ClientId, UserAssignedIdentityId.ClientId)] // UAMI public async Task MachineLearningUserAssignedHappyPathAndHasCorrectClientIdQueryParameterAsync( @@ -68,7 +68,7 @@ public async Task MachineLearningUserAssignedHappyPathAndHasCorrectClientIdQuery } } - [DataTestMethod] + [TestMethod] [DataRow(TestConstants.MiResourceId, UserAssignedIdentityId.ResourceId)] [DataRow(TestConstants.MiResourceId, UserAssignedIdentityId.ObjectId)] public async Task MachineLearningUserAssignedNonClientIdThrowsAsync( @@ -88,7 +88,7 @@ public async Task MachineLearningUserAssignedNonClientIdThrowsAsync( var mi = miBuilder.Build(); - MsalServiceException ex = await Assert.ThrowsExceptionAsync(async () => + MsalServiceException ex = await Assert.ThrowsAsync(async () => await mi.AcquireTokenForManagedIdentity(Resource) .ExecuteAsync().ConfigureAwait(false)).ConfigureAwait(false); @@ -114,7 +114,7 @@ public async Task MachineLearningTestsInvalidEndpointAsync() var mi = miBuilder.Build(); - MsalServiceException ex = await Assert.ThrowsExceptionAsync(async () => + MsalServiceException ex = await Assert.ThrowsAsync(async () => await mi.AcquireTokenForManagedIdentity(ManagedIdentityTests.Resource) .ExecuteAsync().ConfigureAwait(false)).ConfigureAwait(false); diff --git a/tests/Microsoft.Identity.Test.Unit/ManagedIdentityTests/ManagedIdentityTests.cs b/tests/Microsoft.Identity.Test.Unit/ManagedIdentityTests/ManagedIdentityTests.cs index a4039d0791..2a00616ea3 100644 --- a/tests/Microsoft.Identity.Test.Unit/ManagedIdentityTests/ManagedIdentityTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/ManagedIdentityTests/ManagedIdentityTests.cs @@ -57,7 +57,7 @@ internal static void MockImdsV1Probe( } } - [DataTestMethod] + [TestMethod] [DataRow("http://127.0.0.1:41564/msi/token/", ManagedIdentitySource.AppService)] [DataRow(AppServiceEndpoint, ManagedIdentitySource.AppService)] [DataRow(ImdsEndpoint, ManagedIdentitySource.Imds)] @@ -96,7 +96,7 @@ public async Task GetManagedIdentityTests( } } - [DataTestMethod] + [TestMethod] [DataRow("http://127.0.0.1:41564/msi/token/", Resource, ManagedIdentitySource.AppService)] [DataRow(AppServiceEndpoint, Resource, ManagedIdentitySource.AppService)] [DataRow(AppServiceEndpoint, ResourceDefaultSuffix, ManagedIdentitySource.AppService)] @@ -148,7 +148,7 @@ public async Task SAMIHappyPathAsync( } } - [DataTestMethod] + [TestMethod] [DataRow(AppServiceEndpoint, ManagedIdentitySource.AppService, TestConstants.ClientId, UserAssignedIdentityId.ClientId)] [DataRow(AppServiceEndpoint, ManagedIdentitySource.AppService, TestConstants.MiResourceId, UserAssignedIdentityId.ResourceId)] [DataRow(AppServiceEndpoint, ManagedIdentitySource.AppService, TestConstants.ObjectId, UserAssignedIdentityId.ObjectId)] @@ -201,7 +201,7 @@ public async Task UAMIHappyPathAsync( } } - [DataTestMethod] + [TestMethod] [DataRow(AppServiceEndpoint, Resource, "https://graph.microsoft.com", ManagedIdentitySource.AppService)] [DataRow(ImdsEndpoint, Resource, "https://graph.microsoft.com", ManagedIdentitySource.Imds)] [DataRow(AzureArcEndpoint, Resource, "https://graph.microsoft.com", ManagedIdentitySource.AzureArc)] @@ -261,7 +261,7 @@ public async Task ManagedIdentityDifferentScopesTestAsync( } } - [DataTestMethod] + [TestMethod] [DataRow(AppServiceEndpoint, Resource, ManagedIdentitySource.AppService)] [DataRow(ImdsEndpoint, Resource, ManagedIdentitySource.Imds)] [DataRow(AzureArcEndpoint, Resource, ManagedIdentitySource.AzureArc)] @@ -321,7 +321,7 @@ public async Task ManagedIdentityForceRefreshTestAsync( } } - [DataTestMethod] + [TestMethod] [DataRow(AppServiceEndpoint, Resource, ManagedIdentitySource.AppService)] [DataRow(ImdsEndpoint, Resource, ManagedIdentitySource.Imds)] [DataRow(AzureArcEndpoint, Resource, ManagedIdentitySource.AzureArc)] @@ -386,7 +386,7 @@ public async Task ManagedIdentityWithClaimsAndCapabilitiesTestAsync( } } - [DataTestMethod] + [TestMethod] [DataRow(AppServiceEndpoint, Resource, ManagedIdentitySource.AppService)] [DataRow(ImdsEndpoint, Resource, ManagedIdentitySource.Imds)] [DataRow(AzureArcEndpoint, Resource, ManagedIdentitySource.AzureArc)] @@ -450,7 +450,7 @@ public async Task ManagedIdentityWithClaimsTestAsync( } } - [DataTestMethod] + [TestMethod] [DataRow("user.read", ManagedIdentitySource.AppService, AppServiceEndpoint)] [DataRow("https://management.core.windows.net//user_impersonation", ManagedIdentitySource.AppService, AppServiceEndpoint)] [DataRow("s", ManagedIdentitySource.AppService, AppServiceEndpoint)] @@ -488,18 +488,18 @@ public async Task ManagedIdentityTestWrongScopeAsync(string resource, ManagedIde httpManager.AddManagedIdentityMockHandler(endpoint, resource, MockHelpers.GetMsiErrorResponse(managedIdentitySource), managedIdentitySource, statusCode: HttpStatusCode.InternalServerError); - MsalServiceException ex = await Assert.ThrowsExceptionAsync(async () => + MsalServiceException ex = await Assert.ThrowsAsync(async () => await mi.AcquireTokenForManagedIdentity(resource) .ExecuteAsync().ConfigureAwait(false)).ConfigureAwait(false); Assert.IsNotNull(ex); Assert.AreEqual(managedIdentitySource.ToString(), ex.AdditionalExceptionData[MsalException.ManagedIdentitySource]); Assert.AreEqual(MsalError.ManagedIdentityRequestFailed, ex.ErrorCode); - Assert.IsFalse(ex.Message.Contains(MsalErrorMessage.ManagedIdentityUnexpectedErrorResponse)); + Assert.DoesNotContain(MsalErrorMessage.ManagedIdentityUnexpectedErrorResponse, ex.Message); } } - [DataTestMethod] + [TestMethod] [DataRow("{\"statusCode\":500,\"message\":\"Error message\",\"correlationId\":\"GUID\"}", new string[] { "Error message", "GUID" })] [DataRow("{\"message\":\"Error message\",\"correlationId\":\"GUID\"}", new string[] { "Error message", "GUID" })] [DataRow("{\"error\":\"errorCode\",\"error_description\":\"Error message\"}", new string[] { "errorCode", "Error message" })] @@ -532,7 +532,7 @@ public async Task ManagedIdentityTestErrorResponseParsing(string errorResponse, httpManager.AddManagedIdentityMockHandler(AppServiceEndpoint, Resource, errorResponse, ManagedIdentitySource.AppService, statusCode: HttpStatusCode.InternalServerError); - MsalServiceException ex = await Assert.ThrowsExceptionAsync(async () => + MsalServiceException ex = await Assert.ThrowsAsync(async () => await mi.AcquireTokenForManagedIdentity(Resource) .ExecuteAsync().ConfigureAwait(false)).ConfigureAwait(false); @@ -542,16 +542,15 @@ await mi.AcquireTokenForManagedIdentity(Resource) foreach (var expectedErrorSubString in expectedInErrorResponse) { - Assert.IsTrue(ex.Message.Contains(expectedErrorSubString), - $"Expected to contain string {expectedErrorSubString}. Actual error message: {ex.Message}"); + Assert.Contains(expectedErrorSubString, +ex.Message, $"Expected to contain string {expectedErrorSubString}. Actual error message: {ex.Message}"); } } } - [DataTestMethod] + [TestMethod] [DataRow("", ManagedIdentitySource.AppService, AppServiceEndpoint)] - [DataRow(null, ManagedIdentitySource.AppService, AppServiceEndpoint)] - [ExpectedException(typeof(ArgumentNullException))] + [DataRow(null, ManagedIdentitySource.AppService, AppServiceEndpoint)] public async Task ManagedIdentityTestNullOrEmptyScopeAsync(string resource, ManagedIdentitySource managedIdentitySource, string endpoint) { using (new EnvVariableContext()) @@ -562,12 +561,13 @@ public async Task ManagedIdentityTestNullOrEmptyScopeAsync(string resource, Mana var mi = ManagedIdentityApplicationBuilder.Create(ManagedIdentityId.SystemAssigned) .WithHttpManager(httpManager).Build(); - await mi.AcquireTokenForManagedIdentity(resource) - .ExecuteAsync().ConfigureAwait(false); + await Assert.ThrowsAsync(async () => await mi.AcquireTokenForManagedIdentity(resource) + .ExecuteAsync().ConfigureAwait(false)) + .ConfigureAwait(false); } } - [DataTestMethod] + [TestMethod] [DataRow(ManagedIdentitySource.AppService, AppServiceEndpoint)] [DataRow(ManagedIdentitySource.Imds, ImdsEndpoint)] [DataRow(ManagedIdentitySource.AzureArc, AzureArcEndpoint)] @@ -597,7 +597,7 @@ public async Task ManagedIdentityErrorResponseNoPayloadTestAsync(ManagedIdentity httpManager.AddManagedIdentityMockHandler(endpoint, "scope", "", managedIdentitySource, statusCode: HttpStatusCode.InternalServerError); - MsalServiceException ex = await Assert.ThrowsExceptionAsync(async () => + MsalServiceException ex = await Assert.ThrowsAsync(async () => await mi.AcquireTokenForManagedIdentity("scope") .ExecuteAsync().ConfigureAwait(false)).ConfigureAwait(false); @@ -608,7 +608,7 @@ await mi.AcquireTokenForManagedIdentity("scope") } } - [DataTestMethod] + [TestMethod] [DataRow(ManagedIdentitySource.AppService, AppServiceEndpoint)] [DataRow(ManagedIdentitySource.Imds, ImdsEndpoint)] [DataRow(ManagedIdentitySource.AzureArc, AzureArcEndpoint)] @@ -636,7 +636,7 @@ public async Task ManagedIdentityNullResponseAsync(ManagedIdentitySource managed managedIdentitySource, statusCode: HttpStatusCode.OK); - MsalServiceException ex = await Assert.ThrowsExceptionAsync(async () => + MsalServiceException ex = await Assert.ThrowsAsync(async () => await mi.AcquireTokenForManagedIdentity(Resource) .ExecuteAsync().ConfigureAwait(false)).ConfigureAwait(false); @@ -647,7 +647,7 @@ await mi.AcquireTokenForManagedIdentity(Resource) } } - [DataTestMethod] + [TestMethod] [DataRow(ManagedIdentitySource.AppService, AppServiceEndpoint)] [DataRow(ManagedIdentitySource.Imds, ImdsEndpoint)] [DataRow(ManagedIdentitySource.AzureArc, AzureArcEndpoint)] @@ -671,7 +671,7 @@ public async Task ManagedIdentityUnreachableNetworkAsync(ManagedIdentitySource m httpManager.AddFailingRequest(new HttpRequestException("A socket operation was attempted to an unreachable network.", new SocketException(10051))); - MsalServiceException ex = await Assert.ThrowsExceptionAsync(async () => + MsalServiceException ex = await Assert.ThrowsAsync(async () => await mi.AcquireTokenForManagedIdentity(Resource) .ExecuteAsync().ConfigureAwait(false)).ConfigureAwait(false); @@ -782,7 +782,7 @@ public async Task ManagedIdentityCacheTestAsync() } } - [DataTestMethod] + [TestMethod] [DataRow(1, false, false)] // Unix timestamp [DataRow(2, false, false)] // Unix timestamp [DataRow(3, true, false)] // Unix timestamp @@ -820,7 +820,6 @@ public async Task ManagedIdentityExpiresOnTestAsync(int expiresInHours, bool ref } [TestMethod] - [ExpectedException(typeof(MsalClientException))] public async Task ManagedIdentityInvalidRefreshOnThrowsAsync() { using (new EnvVariableContext()) @@ -841,7 +840,8 @@ public async Task ManagedIdentityInvalidRefreshOnThrowsAsync() AcquireTokenForManagedIdentityParameterBuilder builder = mi.AcquireTokenForManagedIdentity(Resource); - AuthenticationResult result = await builder.ExecuteAsync().ConfigureAwait(false); + await Assert.ThrowsAsync(builder.ExecuteAsync) + .ConfigureAwait(false); } } @@ -995,7 +995,7 @@ public async Task ParallelRequests_CallTokenEndpointOnceAsync() { // Increment identity hits count Interlocked.Increment(ref identityProviderHits); - Assert.IsTrue(identityProviderHits == 1); + Assert.AreEqual(1, identityProviderHits); } else { @@ -1009,7 +1009,7 @@ public async Task ParallelRequests_CallTokenEndpointOnceAsync() Debug.WriteLine($"Total Identity Hits: {identityProviderHits}"); Debug.WriteLine($"Total Cache Hits: {cacheHits}"); - Assert.IsTrue(cacheHits == 9); + Assert.AreEqual(9, cacheHits); } } @@ -1030,7 +1030,7 @@ await AssertException.TaskThrowsAsync( .ExecuteAsync(tokenSource.Token)).ConfigureAwait(false); } - [DataTestMethod] + [TestMethod] [DataRow(ManagedIdentitySource.Imds, ImdsEndpoint)] [DataRow(ManagedIdentitySource.AppService, AppServiceEndpoint)] [DataRow(ManagedIdentitySource.AzureArc, AzureArcEndpoint)] @@ -1057,7 +1057,7 @@ public async Task InvalidJsonResponseHandling(ManagedIdentitySource managedIdent MockHelpers.GetMsiErrorBadJson(), managedIdentitySource); - MsalServiceException ex = await Assert.ThrowsExceptionAsync(async () => + MsalServiceException ex = await Assert.ThrowsAsync(async () => await mi.AcquireTokenForManagedIdentity("scope") .ExecuteAsync().ConfigureAwait(false)).ConfigureAwait(false); @@ -1067,7 +1067,7 @@ await mi.AcquireTokenForManagedIdentity("scope") } } - [DataTestMethod] + [TestMethod] [DataRow(Resource, "https://graph.microsoft.com", ManagedIdentitySource.AppService, AppServiceEndpoint)] [DataRow(Resource, "https://graph.microsoft.com", ManagedIdentitySource.Imds, ImdsEndpoint)] [DataRow(Resource, "https://graph.microsoft.com", ManagedIdentitySource.AzureArc, AzureArcEndpoint)] @@ -1138,7 +1138,7 @@ public async Task UnsupportedNonImdsManagedIdentitySource_ThrowsExceptionDuringT var mi = miBuilder.Build(); - MsalServiceException ex = await Assert.ThrowsExceptionAsync(async () => + MsalServiceException ex = await Assert.ThrowsAsync(async () => await mi.AcquireTokenForManagedIdentity("https://management.azure.com") .ExecuteAsync() .ConfigureAwait(false)).ConfigureAwait(false); @@ -1164,7 +1164,7 @@ public async Task UnavailableManagedIdentitySource_ThrowsExceptionDuringTokenAcq httpManager.AddMockHandler(MockHelpers.MockImdsProbeFailure(ImdsVersion.V1)); - var ex = await Assert.ThrowsExceptionAsync(async () => + var ex = await Assert.ThrowsAsync(async () => await mi.AcquireTokenForManagedIdentity("https://management.azure.com") .ExecuteAsync() .ConfigureAwait(false)).ConfigureAwait(false); @@ -1243,8 +1243,8 @@ public async Task MixedUserAndSystemAssignedManagedIdentityTestAsync() var userAssignedTokens = userAssignedMI.AppTokenCacheInternal.Accessor.GetAllAccessTokens(); var systemAssignedTokens = systemAssignedMI.AppTokenCacheInternal.Accessor.GetAllAccessTokens(); - Assert.AreEqual(1, userAssignedTokens.Count, "User-assigned cache entry missing."); - Assert.AreEqual(1, systemAssignedTokens.Count, "System-assigned cache entry missing."); + Assert.HasCount(1, userAssignedTokens, "User-assigned cache entry missing."); + Assert.HasCount(1, systemAssignedTokens, "System-assigned cache entry missing."); // Verify the ClientId for each cached entry Assert.AreEqual(UserAssignedClientId, userAssignedTokens[0].ClientId, "User-assigned ClientId mismatch in cache."); @@ -1252,10 +1252,12 @@ public async Task MixedUserAndSystemAssignedManagedIdentityTestAsync() } } - [DataTestMethod] + [TestMethod] [DataRow(ManagedIdentitySource.AppService, AppServiceEndpoint, HttpStatusCode.NotFound)] [DataRow(ManagedIdentitySource.AppService, AppServiceEndpoint, HttpStatusCode.RequestTimeout)] +#pragma warning disable MSTEST0014 // DataRow should be valid [DataRow(ManagedIdentitySource.AppService, AppServiceEndpoint, 429)] // not defined in HttpStatusCode enum +#pragma warning restore MSTEST0014 // DataRow should be valid [DataRow(ManagedIdentitySource.AppService, AppServiceEndpoint, HttpStatusCode.InternalServerError)] [DataRow(ManagedIdentitySource.AppService, AppServiceEndpoint, HttpStatusCode.ServiceUnavailable)] [DataRow(ManagedIdentitySource.AppService, AppServiceEndpoint, HttpStatusCode.GatewayTimeout)] @@ -1292,7 +1294,7 @@ public async Task ManagedIdentityRetryPolicyLifeTimeIsPerRequestAsync( } MsalServiceException ex = - await Assert.ThrowsExceptionAsync(async () => + await Assert.ThrowsAsync(async () => await mi.AcquireTokenForManagedIdentity(Resource) .ExecuteAsync() .ConfigureAwait(false)) @@ -1312,7 +1314,7 @@ await mi.AcquireTokenForManagedIdentity(Resource) statusCode: statusCode); } - ex = await Assert.ThrowsExceptionAsync(async () => + ex = await Assert.ThrowsAsync(async () => await mi.AcquireTokenForManagedIdentity(Resource) .ExecuteAsync() .ConfigureAwait(false)) @@ -1333,7 +1335,7 @@ await mi.AcquireTokenForManagedIdentity(Resource) statusCode: statusCode); } - ex = await Assert.ThrowsExceptionAsync(async () => + ex = await Assert.ThrowsAsync(async () => await mi.AcquireTokenForManagedIdentity(Resource) .ExecuteAsync() .ConfigureAwait(false)) @@ -1346,7 +1348,7 @@ await mi.AcquireTokenForManagedIdentity(Resource) } } - [DataTestMethod] + [TestMethod] [DataRow(AppServiceEndpoint, Resource, ManagedIdentitySource.AppService)] [DataRow(ImdsEndpoint, Resource, ManagedIdentitySource.Imds)] [DataRow(AzureArcEndpoint, Resource, ManagedIdentitySource.AzureArc)] @@ -1395,7 +1397,7 @@ public async Task ManagedIdentityWithCapabilitiesTestAsync( } } - [DataTestMethod] + [TestMethod] [DataRow(ManagedIdentitySource.AppService)] [DataRow(ManagedIdentitySource.AzureArc)] [DataRow(ManagedIdentitySource.CloudShell)] @@ -1540,7 +1542,7 @@ public void WithExtraQueryParameters_MultipleCallsMergeValues() .WithExtraQueryParameters(secondParams); // Verify that parameters are merged - Assert.AreEqual(4, miBuilder.Config.ExtraQueryParameters.Count); + Assert.HasCount(4, miBuilder.Config.ExtraQueryParameters); // Verify merged values Assert.AreEqual("newvalue1", miBuilder.Config.ExtraQueryParameters["param1"]); diff --git a/tests/Microsoft.Identity.Test.Unit/ManagedIdentityTests/PersistentCertificateCacheFactoryTests.cs b/tests/Microsoft.Identity.Test.Unit/ManagedIdentityTests/PersistentCertificateCacheFactoryTests.cs index 5b26ec1ece..bd6f4b4cb0 100644 --- a/tests/Microsoft.Identity.Test.Unit/ManagedIdentityTests/PersistentCertificateCacheFactoryTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/ManagedIdentityTests/PersistentCertificateCacheFactoryTests.cs @@ -16,7 +16,7 @@ public class PersistentCertificateCacheFactoryTests { private const string DisableEnvVar = "MSAL_MI_DISABLE_PERSISTENT_CERT_CACHE"; - [DataTestMethod] + [TestMethod] [DataRow("true")] [DataRow("TRUE")] [DataRow("1")] diff --git a/tests/Microsoft.Identity.Test.Unit/ManagedIdentityTests/PersistentCertificateStoreUnitTests.cs b/tests/Microsoft.Identity.Test.Unit/ManagedIdentityTests/PersistentCertificateStoreUnitTests.cs index 7079c4b490..90c3b9eed0 100644 --- a/tests/Microsoft.Identity.Test.Unit/ManagedIdentityTests/PersistentCertificateStoreUnitTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/ManagedIdentityTests/PersistentCertificateStoreUnitTests.cs @@ -193,7 +193,7 @@ public void Write_NewestWins_SkipOlder() // Selection should return the newer one (by NotAfter) Assert.IsTrue(WaitForFind(alias, out var value), "Expected to find persisted cert."); var delta = Math.Abs((value.Certificate.NotAfter - newer.NotAfter).TotalSeconds); - Assert.IsTrue(delta <= 2, "Newest persisted cert should be selected."); + Assert.IsLessThanOrEqualTo(2, delta, "Newest persisted cert should be selected."); } finally { @@ -224,7 +224,7 @@ public void Write_Skip_Add_When_NewerOrEqual_AlreadyPresent() // Read returns the newer Assert.IsTrue(WaitForFind(alias, out var value), "Expected to find persisted cert."); var delta = Math.Abs((value.Certificate.NotAfter - newer.NotAfter).TotalSeconds); - Assert.IsTrue(delta <= 2); + Assert.IsLessThanOrEqualTo(2, delta); } finally { diff --git a/tests/Microsoft.Identity.Test.Unit/ManagedIdentityTests/ServiceFabricTests.cs b/tests/Microsoft.Identity.Test.Unit/ManagedIdentityTests/ServiceFabricTests.cs index 48c8e6d37a..dee446a4e8 100644 --- a/tests/Microsoft.Identity.Test.Unit/ManagedIdentityTests/ServiceFabricTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/ManagedIdentityTests/ServiceFabricTests.cs @@ -40,7 +40,7 @@ public async Task ServiceFabricInvalidEndpointAsync() var mi = miBuilder.Build(); - MsalServiceException ex = await Assert.ThrowsExceptionAsync(async () => + MsalServiceException ex = await Assert.ThrowsAsync(async () => await mi.AcquireTokenForManagedIdentity(Resource) .ExecuteAsync().ConfigureAwait(false)).ConfigureAwait(false); @@ -51,7 +51,7 @@ await mi.AcquireTokenForManagedIdentity(Resource) } } - [DataTestMethod] + [TestMethod] [DeploymentItem(@"Resources\testCert.crtfile")] [DataRow("invalidThumbprint", SslPolicyErrors.None, true, DisplayName = "ServerCertificateValidationCallback_NoSSLErrors_InvalidThumbprint")] [DataRow("E70C50DA4EA66F94229A594BC112CB4B4FF29EB4", SslPolicyErrors.RemoteCertificateNameMismatch, true, DisplayName = "ServerCertificateValidationCallback_SSLErrors_validThumbprint")] @@ -99,7 +99,7 @@ public async Task SFThrowsWhenGetHttpClientWithValidationIsNotImplementedAsync() var mi = miBuilder.BuildConcrete(); - MsalServiceException ex = await Assert.ThrowsExceptionAsync(async () => + MsalServiceException ex = await Assert.ThrowsAsync(async () => { await mi.AcquireTokenForManagedIdentity(Resource) .ExecuteAsync().ConfigureAwait(false); diff --git a/tests/Microsoft.Identity.Test.Unit/MetricsTests.cs b/tests/Microsoft.Identity.Test.Unit/MetricsTests.cs index 7c8bcf33b9..3f29d6480d 100644 --- a/tests/Microsoft.Identity.Test.Unit/MetricsTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/MetricsTests.cs @@ -51,8 +51,8 @@ public async Task MetricsUpdatedSuccessfully_AcquireTokenForClient_Async() Assert.IsNotNull(result); Assert.AreEqual(TokenSource.IdentityProvider, result.AuthenticationResultMetadata.TokenSource); - Assert.IsTrue(result.AuthenticationResultMetadata.DurationInCacheInMs > 0); - Assert.IsTrue(result.AuthenticationResultMetadata.DurationTotalInMs > 0); + Assert.IsGreaterThan(0, result.AuthenticationResultMetadata.DurationInCacheInMs); + Assert.IsGreaterThan(0, result.AuthenticationResultMetadata.DurationTotalInMs); Assert.AreEqual( "https://login.microsoftonline.com/common/oauth2/v2.0/token", result.AuthenticationResultMetadata.TokenEndpoint); @@ -65,13 +65,13 @@ public async Task MetricsUpdatedSuccessfully_AcquireTokenForClient_Async() Assert.IsNotNull(result); Assert.AreEqual(TokenSource.Cache, result.AuthenticationResultMetadata.TokenSource); - Assert.IsTrue(result.AuthenticationResultMetadata.DurationInCacheInMs > 0); - Assert.IsTrue(result.AuthenticationResultMetadata.DurationInHttpInMs == 0); - Assert.IsTrue(result.AuthenticationResultMetadata.DurationTotalInMs > 0); + Assert.IsGreaterThan(0, result.AuthenticationResultMetadata.DurationInCacheInMs); + Assert.AreEqual(0, result.AuthenticationResultMetadata.DurationInHttpInMs); + Assert.IsGreaterThan(0, result.AuthenticationResultMetadata.DurationTotalInMs); Assert.AreEqual(1, Metrics.TotalAccessTokensFromIdP); Assert.AreEqual(1, Metrics.TotalAccessTokensFromCache); Assert.AreEqual(0, Metrics.TotalAccessTokensFromBroker); - Assert.IsTrue(Metrics.TotalDurationInMs > 0); + Assert.IsGreaterThan(0, Metrics.TotalDurationInMs); Assert.IsNull(result.AuthenticationResultMetadata.TokenEndpoint); } @@ -279,12 +279,12 @@ private async Task TestAcquireTokenInteractive_Async(PublicClientApplication pca Assert.IsNotNull(result); Assert.AreEqual(TokenSource.IdentityProvider, result.AuthenticationResultMetadata.TokenSource); - Assert.IsTrue(result.AuthenticationResultMetadata.DurationInCacheInMs > 0); - Assert.IsTrue(result.AuthenticationResultMetadata.DurationTotalInMs > 0); + Assert.IsGreaterThan(0, result.AuthenticationResultMetadata.DurationInCacheInMs); + Assert.IsGreaterThan(0, result.AuthenticationResultMetadata.DurationTotalInMs); Assert.AreEqual(expectedTokensFromIdp, Metrics.TotalAccessTokensFromIdP); Assert.AreEqual(expectedTokensFromCache, Metrics.TotalAccessTokensFromCache); Assert.AreEqual(expectedTokensFromBroker, Metrics.TotalAccessTokensFromBroker); - Assert.IsTrue(Metrics.TotalDurationInMs > 0); + Assert.IsGreaterThan(0, Metrics.TotalDurationInMs); } private async Task TestAcquireTokenSilent_Async(PublicClientApplication pca, int expectedTokensFromIdp = 0, int expectedTokensFromCache = 0, int expectedTokensFromBroker = 0) @@ -300,12 +300,12 @@ private async Task TestAcquireTokenSilent_Async(PublicClientApplication pca, int Assert.IsNotNull(result); Assert.AreEqual(TokenSource.Cache, result.AuthenticationResultMetadata.TokenSource); - Assert.IsTrue(result.AuthenticationResultMetadata.DurationInCacheInMs > 0); - Assert.IsTrue(result.AuthenticationResultMetadata.DurationTotalInMs > 0); + Assert.IsGreaterThan(0, result.AuthenticationResultMetadata.DurationInCacheInMs); + Assert.IsGreaterThan(0, result.AuthenticationResultMetadata.DurationTotalInMs); Assert.AreEqual(expectedTokensFromIdp, Metrics.TotalAccessTokensFromIdP); Assert.AreEqual(expectedTokensFromCache, Metrics.TotalAccessTokensFromCache); Assert.AreEqual(expectedTokensFromBroker, Metrics.TotalAccessTokensFromBroker); - Assert.IsTrue(Metrics.TotalDurationInMs > 0); + Assert.IsGreaterThan(0, Metrics.TotalDurationInMs); } } } diff --git a/tests/Microsoft.Identity.Test.Unit/ParallelRequestsTests.cs b/tests/Microsoft.Identity.Test.Unit/ParallelRequestsTests.cs index 89f7b7fd16..f708ba688e 100644 --- a/tests/Microsoft.Identity.Test.Unit/ParallelRequestsTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/ParallelRequestsTests.cs @@ -73,7 +73,7 @@ public async Task ExtraQP() AuthenticationResult[] results = await Task.WhenAll(tasks).ConfigureAwait(false); // Assert - Assert.AreEqual(NumberOfRequests, results.Length); + Assert.HasCount(NumberOfRequests, results); } [TestMethod] @@ -109,9 +109,9 @@ public async Task AcquireTokenForClient_ConcurrentTenantRequests_Test() string.IsNullOrEmpty(res.AuthenticationResultMetadata.TokenEndpoint), "TokenEndpoint is null/empty!" ); - Assert.IsTrue( - res.AuthenticationResultMetadata.TokenEndpoint.Contains(tid), - "TokenEndpoint should contain the tenant ID." + Assert.Contains( +tid, + res.AuthenticationResultMetadata.TokenEndpoint, "TokenEndpoint should contain the tenant ID." ); Assert.AreEqual($"token_{tid}", res.AccessToken, "Access token did not match the expected value."); @@ -123,7 +123,7 @@ public async Task AcquireTokenForClient_ConcurrentTenantRequests_Test() AuthenticationResult[] results = await Task.WhenAll(tasks).ConfigureAwait(false); // Assert the total tasks - Assert.AreEqual(NumberOfRequests, results.Length, "Number of AuthenticationResult objects does not match the number of requests."); + Assert.HasCount(NumberOfRequests, results, "Number of AuthenticationResult objects does not match the number of requests."); } [TestMethod] @@ -161,9 +161,9 @@ public async Task AcquireTokenForClient_PerTenantCaching_Test() $"token_{tid}", result.AccessToken, $"First-pass AccessToken mismatch for TID '{tid}'."); - Assert.IsTrue( - result.AuthenticationResultMetadata.TokenEndpoint.Contains(tid), - $"First-pass TokenEndpoint '{result.AuthenticationResultMetadata.TokenEndpoint}' does not contain TID '{tid}'."); + Assert.Contains( +tid, + result.AuthenticationResultMetadata.TokenEndpoint, $"First-pass TokenEndpoint '{result.AuthenticationResultMetadata.TokenEndpoint}' does not contain TID '{tid}'."); return result; })); diff --git a/tests/Microsoft.Identity.Test.Unit/PublicApiTests/AccountIdTest.cs b/tests/Microsoft.Identity.Test.Unit/PublicApiTests/AccountIdTest.cs index 7e4c222ea9..8945c13c6a 100644 --- a/tests/Microsoft.Identity.Test.Unit/PublicApiTests/AccountIdTest.cs +++ b/tests/Microsoft.Identity.Test.Unit/PublicApiTests/AccountIdTest.cs @@ -29,7 +29,7 @@ public void AccountIdPublicApi() new AccountId("adfs"); } - [DataTestMethod] + [TestMethod] [DataRow("uid", "uid", null, DisplayName = "Parse from string with no dot")] [DataRow("uid.utid", "uid", "utid", DisplayName = "Parse from string with one dot")] [DataRow("uid.1.utid", "uid.1", "utid", DisplayName = "Parse from string with 2 dots")] diff --git a/tests/Microsoft.Identity.Test.Unit/PublicApiTests/AccountTests.cs b/tests/Microsoft.Identity.Test.Unit/PublicApiTests/AccountTests.cs index f6611db027..b857d8cb61 100644 --- a/tests/Microsoft.Identity.Test.Unit/PublicApiTests/AccountTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/PublicApiTests/AccountTests.cs @@ -266,7 +266,7 @@ public void TestGetAccounts() app.UserTokenCacheInternal.Accessor.SaveAccount(accountCacheItem); - Assert.AreEqual(2, app.UserTokenCacheInternal.Accessor.GetAllRefreshTokens().Count); + Assert.HasCount(2, app.UserTokenCacheInternal.Accessor.GetAllRefreshTokens()); accounts = app.GetAccountsAsync().Result; Assert.IsNotNull(accounts); Assert.AreEqual(2, accounts.Count()); // scoped by env @@ -284,7 +284,7 @@ public void TestGetAccounts() homeAccountId3); app.UserTokenCacheInternal.Accessor.SaveRefreshToken(rtItem); - Assert.AreEqual(3, app.UserTokenCacheInternal.Accessor.GetAllRefreshTokens().Count); + Assert.HasCount(3, app.UserTokenCacheInternal.Accessor.GetAllRefreshTokens()); accounts = app.GetAccountsAsync().Result; Assert.IsNotNull(accounts); Assert.AreEqual(2, accounts.Count()); @@ -361,8 +361,8 @@ public void GetAccountsAndSignThemOutTest() app.RemoveAsync(user).Wait(); } - Assert.AreEqual(0, app.UserTokenCacheInternal.Accessor.GetAllAccessTokens().Count); - Assert.AreEqual(0, app.UserTokenCacheInternal.Accessor.GetAllRefreshTokens().Count); + Assert.IsEmpty(app.UserTokenCacheInternal.Accessor.GetAllAccessTokens()); + Assert.IsEmpty(app.UserTokenCacheInternal.Accessor.GetAllRefreshTokens()); } [TestMethod] diff --git a/tests/Microsoft.Identity.Test.Unit/PublicApiTests/AcquireTokenSilentTests.cs b/tests/Microsoft.Identity.Test.Unit/PublicApiTests/AcquireTokenSilentTests.cs index 55ef5c9e19..a33aa0481f 100644 --- a/tests/Microsoft.Identity.Test.Unit/PublicApiTests/AcquireTokenSilentTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/PublicApiTests/AcquireTokenSilentTests.cs @@ -89,7 +89,7 @@ public void AcquireTokenSilentScopeAndUserOverloadWithNoMatchingScopesInCacheTes Assert.IsNotNull(result); Assert.AreEqual(TestConstants.DisplayableId, result.Account.Username); Assert.AreEqual(TestConstants.s_scopeForAnotherResource.AsSingleString(), result.Scopes.AsSingleString()); - Assert.AreEqual(2, app.UserTokenCacheInternal.Accessor.GetAllAccessTokens().Count); + Assert.HasCount(2, app.UserTokenCacheInternal.Accessor.GetAllAccessTokens()); cacheAccess.AssertAccessCounts(1, 0); } } @@ -210,8 +210,8 @@ private void RunAcquireTokenSilentCacheOnlyTest(string authority, bool expectNet Assert.AreEqual(TestConstants.DisplayableId, result.Account.Username); Assert.AreEqual(TestConstants.s_scope.AsSingleString(), result.Scopes.AsSingleString()); - Assert.AreEqual(2, app.UserTokenCacheInternal.Accessor.GetAllAccessTokens().Count); - Assert.AreEqual(1, app.UserTokenCacheInternal.Accessor.GetAllRefreshTokens().Count); + Assert.HasCount(2, app.UserTokenCacheInternal.Accessor.GetAllAccessTokens()); + Assert.HasCount(1, app.UserTokenCacheInternal.Accessor.GetAllRefreshTokens()); } } @@ -351,8 +351,8 @@ public void AcquireTokenSilentForceRefreshTest() Assert.AreEqual(TestConstants.DisplayableId, result.Account.Username); Assert.AreEqual(TestConstants.s_scope.ToArray().AsSingleString(), result.Scopes.AsSingleString()); - Assert.AreEqual(1, app.UserTokenCacheInternal.Accessor.GetAllAccessTokens().Count); - Assert.AreEqual(1, app.UserTokenCacheInternal.Accessor.GetAllRefreshTokens().Count); + Assert.HasCount(1, app.UserTokenCacheInternal.Accessor.GetAllAccessTokens()); + Assert.HasCount(1, app.UserTokenCacheInternal.Accessor.GetAllRefreshTokens()); Assert.AreEqual("my-uid.my-utid", cacheAccess.LastAfterAccessNotificationArgs.SuggestedCacheKey); cacheAccess.AssertAccessCounts(1, 1); } @@ -399,8 +399,8 @@ public void AcquireTokenSilentForceRefreshMultipleTenantsTest() Assert.AreEqual(TestConstants.DisplayableId, result.Account.Username); Assert.AreEqual(TestConstants.s_scope.ToArray().AsSingleString(), result.Scopes.AsSingleString()); - Assert.AreEqual(1, app.UserTokenCacheInternal.Accessor.GetAllAccessTokens().Count); - Assert.AreEqual(1, app.UserTokenCacheInternal.Accessor.GetAllRefreshTokens().Count); + Assert.HasCount(1, app.UserTokenCacheInternal.Accessor.GetAllAccessTokens()); + Assert.HasCount(1, app.UserTokenCacheInternal.Accessor.GetAllRefreshTokens()); httpManager.AddMockHandler( new MockHttpMessageHandler() @@ -427,8 +427,8 @@ public void AcquireTokenSilentForceRefreshMultipleTenantsTest() Assert.AreEqual(TestConstants.DisplayableId, result2.Account.Username); Assert.AreEqual(TestConstants.s_scope.ToArray().AsSingleString(), result2.Scopes.AsSingleString()); - Assert.AreEqual(2, app.UserTokenCacheInternal.Accessor.GetAllAccessTokens().Count); - Assert.AreEqual(1, app.UserTokenCacheInternal.Accessor.GetAllRefreshTokens().Count); + Assert.HasCount(2, app.UserTokenCacheInternal.Accessor.GetAllAccessTokens()); + Assert.HasCount(1, app.UserTokenCacheInternal.Accessor.GetAllRefreshTokens()); httpManager.AddMockHandler( new MockHttpMessageHandler() @@ -455,8 +455,8 @@ public void AcquireTokenSilentForceRefreshMultipleTenantsTest() Assert.AreEqual(TestConstants.DisplayableId, result3.Account.Username); Assert.AreEqual(TestConstants.s_scope.ToArray().AsSingleString(), result3.Scopes.AsSingleString()); - Assert.AreEqual(3, app.UserTokenCacheInternal.Accessor.GetAllAccessTokens().Count); - Assert.AreEqual(1, app.UserTokenCacheInternal.Accessor.GetAllRefreshTokens().Count); + Assert.HasCount(3, app.UserTokenCacheInternal.Accessor.GetAllAccessTokens()); + Assert.HasCount(1, app.UserTokenCacheInternal.Accessor.GetAllRefreshTokens()); // Use same authority as above, number of access tokens should remain constant httpManager.AddMockHandler( @@ -482,8 +482,8 @@ public void AcquireTokenSilentForceRefreshMultipleTenantsTest() Assert.AreEqual(TestConstants.DisplayableId, result4.Account.Username); Assert.AreEqual(TestConstants.s_scope.ToArray().AsSingleString(), result4.Scopes.AsSingleString()); - Assert.AreEqual(3, app.UserTokenCacheInternal.Accessor.GetAllAccessTokens().Count); - Assert.AreEqual(1, app.UserTokenCacheInternal.Accessor.GetAllRefreshTokens().Count); + Assert.HasCount(3, app.UserTokenCacheInternal.Accessor.GetAllAccessTokens()); + Assert.HasCount(1, app.UserTokenCacheInternal.Accessor.GetAllRefreshTokens()); } } @@ -517,8 +517,8 @@ public void AcquireTokenSilentForceRefreshFalseMultipleTenantsTest() Assert.AreEqual(TestConstants.s_scope.ToArray().AsSingleString(), result.Scopes.AsSingleString()); Assert.AreEqual(0, httpManager.QueueSize); - Assert.AreEqual(2, app.UserTokenCacheInternal.Accessor.GetAllAccessTokens().Count); - Assert.AreEqual(1, app.UserTokenCacheInternal.Accessor.GetAllRefreshTokens().Count); + Assert.HasCount(2, app.UserTokenCacheInternal.Accessor.GetAllAccessTokens()); + Assert.HasCount(1, app.UserTokenCacheInternal.Accessor.GetAllRefreshTokens()); httpManager.AddInstanceDiscoveryMockHandler(); httpManager.AddMockHandler( @@ -546,8 +546,8 @@ public void AcquireTokenSilentForceRefreshFalseMultipleTenantsTest() Assert.AreEqual(TestConstants.DisplayableId, result2.Account.Username); Assert.AreEqual(TestConstants.s_scope.ToArray().AsSingleString(), result2.Scopes.AsSingleString()); - Assert.AreEqual(3, app.UserTokenCacheInternal.Accessor.GetAllAccessTokens().Count); - Assert.AreEqual(1, app.UserTokenCacheInternal.Accessor.GetAllRefreshTokens().Count); + Assert.HasCount(3, app.UserTokenCacheInternal.Accessor.GetAllAccessTokens()); + Assert.HasCount(1, app.UserTokenCacheInternal.Accessor.GetAllRefreshTokens()); httpManager.AddMockHandler( new MockHttpMessageHandler() @@ -574,8 +574,8 @@ public void AcquireTokenSilentForceRefreshFalseMultipleTenantsTest() Assert.AreEqual(TestConstants.DisplayableId, result3.Account.Username); Assert.AreEqual(TestConstants.s_scope.ToArray().AsSingleString(), result3.Scopes.AsSingleString()); - Assert.AreEqual(4, app.UserTokenCacheInternal.Accessor.GetAllAccessTokens().Count); - Assert.AreEqual(1, app.UserTokenCacheInternal.Accessor.GetAllRefreshTokens().Count); + Assert.HasCount(4, app.UserTokenCacheInternal.Accessor.GetAllAccessTokens()); + Assert.HasCount(1, app.UserTokenCacheInternal.Accessor.GetAllRefreshTokens()); } } @@ -616,7 +616,7 @@ public void AcquireTokenSilentServiceErrorTest() Assert.IsNotNull(ex.InnerException); Assert.IsTrue(ex.InnerException is MsalUiRequiredException); var msalExc = (MsalUiRequiredException)ex.InnerException; - Assert.AreEqual(msalExc.ErrorCode, MsalError.InvalidGrantError); + Assert.AreEqual(MsalError.InvalidGrantError, msalExc.ErrorCode); } } } diff --git a/tests/Microsoft.Identity.Test.Unit/PublicApiTests/AdfsAcceptanceTests.cs b/tests/Microsoft.Identity.Test.Unit/PublicApiTests/AdfsAcceptanceTests.cs index e548be9df3..e796265f4c 100644 --- a/tests/Microsoft.Identity.Test.Unit/PublicApiTests/AdfsAcceptanceTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/PublicApiTests/AdfsAcceptanceTests.cs @@ -16,7 +16,7 @@ public class AdfsAcceptanceTests : TestBase private const string AdfsScope = "https://arm.asz/.default"; // Possible authorities copied from: https://msazure.visualstudio.com/One/_search?action=contents&text=CanAcquireToken_UsingRefreshToken&type=code&lp=code-Project&filters=ProjectFilters%7BOne%7DRepositoryFilters%7BAzureStack-Services-Graph%7D&pageSize=25&result=DefaultCollection/One/AzureStack-Services-Graph/GBmain//src/Identity.Web.Tests/MsalTests.cs - [DataTestMethod] + [TestMethod] [DataRow("https://localhost:3001/adfs")] [DataRow("https://localhost:3001/460afc9d-718d-40c8-8d03-954")] [DataRow("https://localhost:3001/contoso.int.test")] @@ -25,7 +25,7 @@ public async Task AdfsAuthorityVariants_WithAdfsAuthority_Async(string authority await RunAuthCodeFlowAsync(authority, useWithAdfsAuthority: true).ConfigureAwait(false); } - [DataTestMethod] + [TestMethod] [DataRow("https://localhost:3001/adfs")] [DataRow("https://localhost:3001/460afc9d-718d-40c8-8d03-954")] [DataRow("https://localhost:3001/contoso.int.test")] diff --git a/tests/Microsoft.Identity.Test.Unit/PublicApiTests/AuthenticationOperationTests.cs b/tests/Microsoft.Identity.Test.Unit/PublicApiTests/AuthenticationOperationTests.cs index cb48b0ebb6..cdf15c9c51 100644 --- a/tests/Microsoft.Identity.Test.Unit/PublicApiTests/AuthenticationOperationTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/PublicApiTests/AuthenticationOperationTests.cs @@ -261,7 +261,7 @@ public async Task MissingAccessTokenTypeInResponse_Throws_Async() harness.HttpManager.AddResponseMockHandlerForPost(MockHelpers.CreateSuccessResponseMessage(JsonHelper.SerializeToJson(fakeResponse))); await requestParams.AuthorityManager.RunInstanceDiscoveryAndValidationAsync().ConfigureAwait(false); - var ex = await Assert.ThrowsExceptionAsync( + var ex = await Assert.ThrowsAsync( () => tokenClient.SendTokenRequestAsync(new Dictionary())).ConfigureAwait(false); Assert.AreEqual(MsalError.AccessTokenTypeMissing, ex.ErrorCode); } diff --git a/tests/Microsoft.Identity.Test.Unit/PublicApiTests/CacheKeyExtensionTests.cs b/tests/Microsoft.Identity.Test.Unit/PublicApiTests/CacheKeyExtensionTests.cs index cb7659f732..41e967feb8 100644 --- a/tests/Microsoft.Identity.Test.Unit/PublicApiTests/CacheKeyExtensionTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/PublicApiTests/CacheKeyExtensionTests.cs @@ -115,7 +115,7 @@ private async Task RunHappyPathTest(ConfidentialClientApplication app, MockHttpM { if (expectedCacheKeyHash != null) { - Assert.IsTrue(args.SuggestedCacheKey.Contains(expectedCacheKeyHash)); + Assert.Contains(expectedCacheKeyHash, args.SuggestedCacheKey); } }); @@ -142,7 +142,7 @@ private async Task RunHappyPathTest(ConfidentialClientApplication app, MockHttpM Assert.IsNotNull(result); Assert.AreEqual("header.payload.signature", result.AccessToken); - Assert.AreEqual(1, app.AppTokenCacheInternal.Accessor.GetAllAccessTokens().Count); + Assert.HasCount(1, app.AppTokenCacheInternal.Accessor.GetAllAccessTokens()); Assert.AreEqual(TokenSource.Cache, result.AuthenticationResultMetadata.TokenSource); ValidateCacheKeyComponents(app.AppTokenCacheInternal.Accessor.GetAllAccessTokens().First(), _additionalCacheKeys3, expectedCacheKey1); @@ -156,7 +156,7 @@ private async Task RunHappyPathTest(ConfidentialClientApplication app, MockHttpM Assert.IsNotNull(result); Assert.AreEqual("header.payload.signature", result.AccessToken); - Assert.AreEqual(2, app.AppTokenCacheInternal.Accessor.GetAllAccessTokens().Count); + Assert.HasCount(2, app.AppTokenCacheInternal.Accessor.GetAllAccessTokens()); Assert.AreEqual(TokenSource.IdentityProvider, result.AuthenticationResultMetadata.TokenSource); ValidateCacheKeyComponents(app.AppTokenCacheInternal.Accessor.GetAllAccessTokens().Where(x => x.CacheKey.Contains("bns2ytmx5hxkh4fnfixridmezpbbayhnmuh6t4bbghi")).FirstOrDefault(), _additionalCacheKeys1, expectedCacheKey1); ValidateCacheKeyComponents(app.AppTokenCacheInternal.Accessor.GetAllAccessTokens().Where(x => x.CacheKey.Contains("3-rg6_wyjx5bcy0c3cqq7gajtzgsqy3oxqpwj4y8k4u")).FirstOrDefault(), _additionalCacheKeys2, expectedCacheKey2); @@ -214,7 +214,7 @@ public async Task CacheExtEnsureStandardTokensDoNotClashTestAsync() Assert.IsNotNull(result); Assert.AreEqual(TokenSource.IdentityProvider, result.AuthenticationResultMetadata.TokenSource); - Assert.AreEqual(2, app.AppTokenCacheInternal.Accessor.GetAllAccessTokens().Count); + Assert.HasCount(2, app.AppTokenCacheInternal.Accessor.GetAllAccessTokens()); //Ensure that default tokens are retrivable result = await app.AcquireTokenForClient(TestConstants.s_scope.ToArray()) @@ -395,7 +395,7 @@ public async Task CacheExt_WithExtraQueryParameters_NoConflictTestAsync() Assert.AreEqual("token_with_additional_components", result1.AccessToken); Assert.AreEqual(TokenSource.IdentityProvider, result1.AuthenticationResultMetadata.TokenSource); - Assert.AreEqual(1, app.AppTokenCacheInternal.Accessor.GetAllAccessTokens().Count); + Assert.HasCount(1, app.AppTokenCacheInternal.Accessor.GetAllAccessTokens()); // Test 2: Use tuple-based WithExtraQueryParameters only httpManager.AddMockHandlerSuccessfulClientCredentialTokenResponseMessage(token: "token_with_tuple_params"); @@ -410,7 +410,7 @@ public async Task CacheExt_WithExtraQueryParameters_NoConflictTestAsync() Assert.AreEqual("token_with_tuple_params", result2.AccessToken); Assert.AreEqual(TokenSource.IdentityProvider, result2.AuthenticationResultMetadata.TokenSource); - Assert.AreEqual(2, app.AppTokenCacheInternal.Accessor.GetAllAccessTokens().Count); + Assert.HasCount(2, app.AppTokenCacheInternal.Accessor.GetAllAccessTokens()); // Test 3: Use both APIs together - should create a different cache entry httpManager.AddMockHandlerSuccessfulClientCredentialTokenResponseMessage(token: "token_with_both_apis"); @@ -426,7 +426,7 @@ public async Task CacheExt_WithExtraQueryParameters_NoConflictTestAsync() Assert.AreEqual("token_with_both_apis", result3.AccessToken); Assert.AreEqual(TokenSource.IdentityProvider, result3.AuthenticationResultMetadata.TokenSource); - Assert.AreEqual(3, app.AppTokenCacheInternal.Accessor.GetAllAccessTokens().Count); + Assert.HasCount(3, app.AppTokenCacheInternal.Accessor.GetAllAccessTokens()); // Test 4: Retrieve from cache using the same combination var result4 = await app.AcquireTokenForClient(TestConstants.s_scope) @@ -441,7 +441,7 @@ public async Task CacheExt_WithExtraQueryParameters_NoConflictTestAsync() Assert.AreEqual("token_with_both_apis", result4.AccessToken); Assert.AreEqual(TokenSource.Cache, result4.AuthenticationResultMetadata.TokenSource); - Assert.AreEqual(3, app.AppTokenCacheInternal.Accessor.GetAllAccessTokens().Count); + Assert.HasCount(3, app.AppTokenCacheInternal.Accessor.GetAllAccessTokens()); // Test 5: Test with non-cached parameters var result5 = await app.AcquireTokenForClient(TestConstants.s_scope) @@ -457,7 +457,7 @@ public async Task CacheExt_WithExtraQueryParameters_NoConflictTestAsync() Assert.AreEqual("token_with_both_apis", result5.AccessToken); Assert.AreEqual(TokenSource.Cache, result5.AuthenticationResultMetadata.TokenSource); - Assert.AreEqual(3, app.AppTokenCacheInternal.Accessor.GetAllAccessTokens().Count); + Assert.HasCount(3, app.AppTokenCacheInternal.Accessor.GetAllAccessTokens()); // Test 6: Change a parameter that is included in cache key - should get a new token httpManager.AddMockHandlerSuccessfulClientCredentialTokenResponseMessage(token: "token_with_changed_param"); @@ -473,7 +473,7 @@ public async Task CacheExt_WithExtraQueryParameters_NoConflictTestAsync() Assert.AreEqual("token_with_changed_param", result6.AccessToken); Assert.AreEqual(TokenSource.IdentityProvider, result6.AuthenticationResultMetadata.TokenSource); - Assert.AreEqual(4, app.AppTokenCacheInternal.Accessor.GetAllAccessTokens().Count); + Assert.HasCount(4, app.AppTokenCacheInternal.Accessor.GetAllAccessTokens()); // Test 7: Now try with includeInCacheKey=false for a parameter httpManager.AddMockHandlerSuccessfulClientCredentialTokenResponseMessage(token: "token_with_non_cached_param"); @@ -488,7 +488,7 @@ public async Task CacheExt_WithExtraQueryParameters_NoConflictTestAsync() Assert.AreEqual("token_with_non_cached_param", result7.AccessToken); Assert.AreEqual(TokenSource.IdentityProvider, result7.AuthenticationResultMetadata.TokenSource); - Assert.AreEqual(5, app.AppTokenCacheInternal.Accessor.GetAllAccessTokens().Count); + Assert.HasCount(5, app.AppTokenCacheInternal.Accessor.GetAllAccessTokens()); // Test 8: Repeat with same config but change the non-cached parameter value var result8 = await app.AcquireTokenForClient(TestConstants.s_scope) @@ -502,7 +502,7 @@ public async Task CacheExt_WithExtraQueryParameters_NoConflictTestAsync() Assert.AreEqual("token_with_non_cached_param", result8.AccessToken); Assert.AreEqual(TokenSource.Cache, result8.AuthenticationResultMetadata.TokenSource); - Assert.AreEqual(5, app.AppTokenCacheInternal.Accessor.GetAllAccessTokens().Count); + Assert.HasCount(5, app.AppTokenCacheInternal.Accessor.GetAllAccessTokens()); } } diff --git a/tests/Microsoft.Identity.Test.Unit/PublicApiTests/ClientCredentialWithCertTest.cs b/tests/Microsoft.Identity.Test.Unit/PublicApiTests/ClientCredentialWithCertTest.cs index 67490087db..6d0a798f8a 100644 --- a/tests/Microsoft.Identity.Test.Unit/PublicApiTests/ClientCredentialWithCertTest.cs +++ b/tests/Microsoft.Identity.Test.Unit/PublicApiTests/ClientCredentialWithCertTest.cs @@ -72,7 +72,7 @@ private static MockHttpMessageHandler CreateTokenResponseHttpHandlerWithX5CValid if (expectedX5C != null) { Assert.AreEqual("x5c", x5c.Key, "x5c should be present"); - Assert.AreEqual(x5c.Value.ToString(), expectedX5C); + Assert.AreEqual(expectedX5C, x5c.Value.ToString()); } else { @@ -103,7 +103,7 @@ private void SetupMocks(MockHttpManager httpManager, string authority) httpManager.AddInstanceDiscoveryMockHandler(); } - [DataTestMethod] + [TestMethod] [DataRow(true, null, true)] [DataRow(false, null, false)] [DataRow(null, null, false)] // the default is false @@ -155,7 +155,7 @@ public async Task JsonWebTokenWithX509PublicCertSendCertificateTestSendX5cCombin } } - [DataTestMethod] + [TestMethod] [DataRow(true, null, true)] [DataRow(false, null, false)] [DataRow(null, null, false)] // the default is false @@ -328,7 +328,7 @@ private JwtSecurityToken ValidateClientAssertion(HttpRequestMessage request, str var x5c = assertionJwt.Header.FirstOrDefault(header => header.Key == "x5c"); Assert.AreEqual("x5c", x5c.Key, "x5c should be present"); - Assert.AreEqual(x5c.Value.ToString(), expectedX5cValue); + Assert.AreEqual(expectedX5cValue, x5c.Value.ToString()); return assertionJwt; } @@ -552,7 +552,7 @@ public async Task JsonWebTokenWithX509PublicCertSendCertificateSilentTestAsync() } } - [DataTestMethod] + [TestMethod] [DataRow(true, true, true, true)] [DataRow(true, true, true, false)] [DataRow(true, true, false, true)] @@ -598,7 +598,7 @@ public void ClientAssertionTests(bool sendX5C, bool useSha2AndPss, bool addExtra appendDefaultClaims = true; int expectedPayloadClaimsCount = (appendDefaultClaims ? 6 : 0) + (addExtraClaims ? 3 : 0); - Assert.AreEqual(expectedPayloadClaimsCount, decodedToken.Payload.Count); + Assert.HasCount(expectedPayloadClaimsCount, decodedToken.Payload); if (appendDefaultClaims) { Assert.AreEqual("aud", decodedToken.Payload["aud"]); @@ -656,7 +656,7 @@ private static void AssertClientAssertionHeader( { // Wilson is guaranteed to parse the token correctly - use it as baseline - Assert.AreEqual(sendX5c ? 4 : 3, decodedToken.Header.Count); + Assert.HasCount(sendX5c ? 4 : 3, decodedToken.Header); Assert.AreEqual("JWT", decodedToken.Header["typ"]); Assert.AreEqual(useSha2AndPss ? "PS256" : "RS256", decodedToken.Header["alg"]); @@ -751,7 +751,7 @@ public async Task DisposedCert_ThrowsSpecificException_Test() } //Testing client credential flow - var exception = await Assert.ThrowsExceptionAsync(async () => + var exception = await Assert.ThrowsAsync(async () => { await app.AcquireTokenForClient(TestConstants.s_scope) .ExecuteAsync(CancellationToken.None) @@ -762,7 +762,7 @@ await app.AcquireTokenForClient(TestConstants.s_scope) Assert.AreEqual(MsalErrorMessage.CryptographicError, exception.Message); //Testing auth code flow - exception = await Assert.ThrowsExceptionAsync(async () => + exception = await Assert.ThrowsAsync(async () => { await app.AcquireTokenByAuthorizationCode(TestConstants.s_scope, TestConstants.DefaultAuthorizationCode) .ExecuteAsync(CancellationToken.None) @@ -773,7 +773,7 @@ await app.AcquireTokenByAuthorizationCode(TestConstants.s_scope, TestConstants.D Assert.AreEqual(MsalErrorMessage.CryptographicError, exception.Message); //Testing OBO flow - exception = await Assert.ThrowsExceptionAsync(async () => + exception = await Assert.ThrowsAsync(async () => { await app.AcquireTokenOnBehalfOf(TestConstants.s_scope, new UserAssertion(TestConstants.UserAssertion)) .ExecuteAsync(CancellationToken.None) @@ -786,7 +786,7 @@ await app.AcquireTokenByAuthorizationCode(TestConstants.s_scope, TestConstants.D } // regression test for https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/issues/4913 - [DataTestMethod] + [TestMethod] [DataRow(true)] [DataRow(false)] public async Task RopcCcaSendsX5CAsync(bool sendX5C) @@ -1002,7 +1002,7 @@ public void EnsureNullCertDoesNotSetSerialNumberTestAsync() { var certificate = CertHelper.GetOrCreateTestCert(); - var exception = Assert.ThrowsException(() => + var exception = Assert.Throws(() => { var app = ConfidentialClientApplicationBuilder.Create(TestConstants.ClientId) .WithAuthority(new Uri(ClientApplicationBase.DefaultAuthority), true) @@ -1013,7 +1013,7 @@ public void EnsureNullCertDoesNotSetSerialNumberTestAsync() .BuildConcrete(); }); - Assert.IsTrue(exception.Message.Contains("Value cannot be null")); + Assert.Contains("Value cannot be null", exception.Message); } } diff --git a/tests/Microsoft.Identity.Test.Unit/PublicApiTests/ClientCredentialWithRegionTests.cs b/tests/Microsoft.Identity.Test.Unit/PublicApiTests/ClientCredentialWithRegionTests.cs index 7010bbb5aa..319a524945 100644 --- a/tests/Microsoft.Identity.Test.Unit/PublicApiTests/ClientCredentialWithRegionTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/PublicApiTests/ClientCredentialWithRegionTests.cs @@ -134,7 +134,7 @@ public async Task FetchRegionFromLocalImdsCallAsync() Assert.AreEqual(TestConstants.Region, result.ApiEvent.AutoDetectedRegion); Assert.AreEqual(RegionAutodetectionSource.Cache, result.ApiEvent.RegionAutodetectionSource); Assert.AreEqual(RegionOutcome.AutodetectSuccess, result.ApiEvent.RegionOutcome); - Assert.IsTrue(result.AuthenticationResultMetadata.TokenSource == TokenSource.Cache); + Assert.AreEqual(TokenSource.Cache, result.AuthenticationResultMetadata.TokenSource); Assert.AreEqual(region, result.AuthenticationResultMetadata.RegionDetails.RegionUsed); Assert.AreEqual(RegionOutcome.AutodetectSuccess, result.AuthenticationResultMetadata.RegionDetails.RegionOutcome); Assert.IsNull(result.AuthenticationResultMetadata.RegionDetails.AutoDetectionError); @@ -151,7 +151,7 @@ public async Task FetchRegionFromLocalImdsCallAsync() Assert.AreEqual(TestConstants.Region, result.ApiEvent.AutoDetectedRegion); Assert.AreEqual(RegionAutodetectionSource.Cache, result.ApiEvent.RegionAutodetectionSource); Assert.AreEqual(RegionOutcome.AutodetectSuccess, result.ApiEvent.RegionOutcome); - Assert.IsTrue(result.AuthenticationResultMetadata.TokenSource == TokenSource.IdentityProvider); + Assert.AreEqual(TokenSource.IdentityProvider, result.AuthenticationResultMetadata.TokenSource); Assert.AreEqual(region, result.AuthenticationResultMetadata.RegionDetails.RegionUsed); Assert.AreEqual(RegionOutcome.AutodetectSuccess, result.AuthenticationResultMetadata.RegionDetails.RegionOutcome); Assert.IsNull(result.AuthenticationResultMetadata.RegionDetails.AutoDetectionError); @@ -171,7 +171,7 @@ public async Task FetchRegionFromLocalImdsCallAsync() Assert.AreEqual(TestConstants.Region, result.ApiEvent.AutoDetectedRegion); Assert.AreEqual(RegionAutodetectionSource.Cache, result.ApiEvent.RegionAutodetectionSource); Assert.AreEqual(RegionOutcome.AutodetectSuccess, result.ApiEvent.RegionOutcome); - Assert.IsTrue(result.AuthenticationResultMetadata.TokenSource == TokenSource.IdentityProvider); + Assert.AreEqual(TokenSource.IdentityProvider, result.AuthenticationResultMetadata.TokenSource); Assert.AreEqual(region, result.AuthenticationResultMetadata.RegionDetails.RegionUsed); Assert.AreEqual(RegionOutcome.AutodetectSuccess, result.AuthenticationResultMetadata.RegionDetails.RegionOutcome); Assert.IsNull(result.AuthenticationResultMetadata.RegionDetails.AutoDetectionError); @@ -218,11 +218,11 @@ public async Task TokensAreInterchangable_Regional_To_NonRegional_Async() .ExecuteAsync(CancellationToken.None) .ConfigureAwait(false); - Assert.AreEqual(null, result.ApiEvent.RegionUsed); + Assert.IsNull(result.ApiEvent.RegionUsed); Assert.IsNull(result.ApiEvent.AutoDetectedRegion); Assert.AreEqual(RegionAutodetectionSource.None, result.ApiEvent.RegionAutodetectionSource); Assert.AreEqual(RegionOutcome.None, result.ApiEvent.RegionOutcome); - Assert.IsTrue(result.AuthenticationResultMetadata.TokenSource == TokenSource.Cache); + Assert.AreEqual(TokenSource.Cache, result.AuthenticationResultMetadata.TokenSource); Assert.IsNull(result.AuthenticationResultMetadata.RegionDetails.RegionUsed); Assert.AreEqual(RegionOutcome.None, result.AuthenticationResultMetadata.RegionDetails.RegionOutcome); Assert.IsNull(result.AuthenticationResultMetadata.RegionDetails.AutoDetectionError); @@ -286,14 +286,14 @@ public async Task RegionFallbackToGlobalAsync() Assert.IsNotNull(result.AccessToken); - Assert.AreEqual(null, result.ApiEvent.RegionUsed); + Assert.IsNull(result.ApiEvent.RegionUsed); Assert.IsNull(result.ApiEvent.AutoDetectedRegion); Assert.AreEqual(RegionAutodetectionSource.FailedAutoDiscovery, result.ApiEvent.RegionAutodetectionSource); Assert.AreEqual(RegionOutcome.FallbackToGlobal, result.ApiEvent.RegionOutcome); Assert.IsNull(result.AuthenticationResultMetadata.RegionDetails.RegionUsed); Assert.AreEqual(RegionOutcome.FallbackToGlobal, result.AuthenticationResultMetadata.RegionDetails.RegionOutcome); - Assert.IsTrue(result.AuthenticationResultMetadata.RegionDetails.AutoDetectionError - .Contains(TestConstants.RegionDiscoveryIMDSCallFailedMessage)); + Assert.Contains(TestConstants.RegionDiscoveryIMDSCallFailedMessage, result.AuthenticationResultMetadata.RegionDetails.AutoDetectionError +); } } @@ -551,7 +551,7 @@ public async Task OtherCloudWithAuthorityValidationAsync() "Authority validation is made on https://login.microsoftonline.com/ and it validates the auth_endpoint of the non-regional authority"); Assert.AreEqual(EastUsRegion, result.AuthenticationResultMetadata.RegionDetails.RegionUsed); Assert.AreEqual(RegionOutcome.UserProvidedAutodetectionFailed, result.AuthenticationResultMetadata.RegionDetails.RegionOutcome); - Assert.IsTrue(result.AuthenticationResultMetadata.RegionDetails.AutoDetectionError.Contains(imdsError)); + Assert.Contains(imdsError, result.AuthenticationResultMetadata.RegionDetails.AutoDetectionError); result = await app .AcquireTokenForClient(TestConstants.s_scope) @@ -564,12 +564,12 @@ public async Task OtherCloudWithAuthorityValidationAsync() Assert.AreEqual(TokenSource.Cache, result.AuthenticationResultMetadata.TokenSource); Assert.AreEqual(EastUsRegion, result.AuthenticationResultMetadata.RegionDetails.RegionUsed); Assert.AreEqual(RegionOutcome.UserProvidedAutodetectionFailed, result.AuthenticationResultMetadata.RegionDetails.RegionOutcome); - Assert.IsTrue(result.AuthenticationResultMetadata.RegionDetails.AutoDetectionError.Contains(autoDiscoveryError)); + Assert.Contains(autoDiscoveryError, result.AuthenticationResultMetadata.RegionDetails.AutoDetectionError); } } - [DataTestMethod] + [TestMethod] [DataRow(true, true)] [DataRow(true, false)] [DataRow(false, true)] @@ -650,7 +650,7 @@ public async Task OtherCloud_WithValidation_Async(bool validateAuthority, bool a Assert.AreEqual(TokenSource.IdentityProvider, result.AuthenticationResultMetadata.TokenSource); Assert.AreEqual(EastUsRegion, result.AuthenticationResultMetadata.RegionDetails.RegionUsed); Assert.AreEqual(RegionOutcome.UserProvidedValid, result.AuthenticationResultMetadata.RegionDetails.RegionOutcome); - Assert.AreEqual(null, result.AuthenticationResultMetadata.RegionDetails.AutoDetectionError); + Assert.IsNull(result.AuthenticationResultMetadata.RegionDetails.AutoDetectionError); if (validateAuthority) { @@ -669,13 +669,13 @@ public async Task OtherCloud_WithValidation_Async(bool validateAuthority, bool a Assert.AreEqual(EastUsRegion, result.ApiEvent.RegionUsed); Assert.AreEqual(TokenSource.Cache, result.AuthenticationResultMetadata.TokenSource); Assert.AreEqual(EastUsRegion, result.AuthenticationResultMetadata.RegionDetails.RegionUsed); - Assert.AreEqual(null, result.AuthenticationResultMetadata.RegionDetails.AutoDetectionError); + Assert.IsNull(result.AuthenticationResultMetadata.RegionDetails.AutoDetectionError); } } } - [DataTestMethod] + [TestMethod] [DataRow("login.partner.microsoftonline.cn", "login.partner.microsoftonline.cn")] [DataRow("login.chinacloudapi.cn", "login.partner.microsoftonline.cn")] [DataRow("login.microsoftonline.us", "login.microsoftonline.us")] @@ -727,7 +727,7 @@ public async Task PublicAndSovereignCloud_UsesPreferredNetwork_AndNoDiscovery_As Assert.AreEqual(EastUsRegion, result.AuthenticationResultMetadata.RegionDetails.RegionUsed); Assert.AreEqual(TokenSource.Cache, result.AuthenticationResultMetadata.TokenSource); Assert.AreEqual(RegionOutcome.AutodetectSuccess, result.AuthenticationResultMetadata.RegionDetails.RegionOutcome); - Assert.AreEqual(null, result.AuthenticationResultMetadata.RegionDetails.AutoDetectionError); + Assert.IsNull(result.AuthenticationResultMetadata.RegionDetails.AutoDetectionError); } } @@ -754,19 +754,19 @@ public async Task UserRegion_DiscoveryHappensOnce_Async() Assert.AreEqual(TestConstants.Region, result.ApiEvent.RegionUsed); Assert.AreEqual(RegionAutodetectionSource.Imds, result.ApiEvent.RegionAutodetectionSource); Assert.AreEqual(RegionOutcome.UserProvidedValid, result.ApiEvent.RegionOutcome); - Assert.AreEqual(null, result.AuthenticationResultMetadata.RegionDetails.AutoDetectionError); + Assert.IsNull(result.AuthenticationResultMetadata.RegionDetails.AutoDetectionError); Assert.AreEqual(TestConstants.Region, result.AuthenticationResultMetadata.RegionDetails.RegionUsed); Assert.AreEqual(RegionOutcome.UserProvidedValid, result.AuthenticationResultMetadata.RegionDetails.RegionOutcome); - Assert.IsTrue(result.AuthenticationResultMetadata.TokenSource == TokenSource.IdentityProvider); + Assert.AreEqual(TokenSource.IdentityProvider, result.AuthenticationResultMetadata.TokenSource); result = await app .AcquireTokenForClient(TestConstants.s_scope) .ExecuteAsync() .ConfigureAwait(false); - Assert.IsTrue(result.AuthenticationResultMetadata.TokenSource == TokenSource.Cache); - Assert.AreEqual(null, result.AuthenticationResultMetadata.RegionDetails.AutoDetectionError); + Assert.AreEqual(TokenSource.Cache, result.AuthenticationResultMetadata.TokenSource); + Assert.IsNull(result.AuthenticationResultMetadata.RegionDetails.AutoDetectionError); Assert.AreEqual(TestConstants.Region, result.AuthenticationResultMetadata.RegionDetails.RegionUsed); Assert.AreEqual(RegionOutcome.UserProvidedValid, result.AuthenticationResultMetadata.RegionDetails.RegionOutcome); } @@ -820,7 +820,7 @@ public void RegionConfiguredWithCustomInstanceDiscoveryThrowsException() { var httpManager = harness.HttpManager; - var ex = Assert.ThrowsException(() => CreateCca( + var ex = Assert.Throws(() => CreateCca( httpManager, ConfidentialClientApplication.AttemptRegionDiscovery, hasCustomInstanceMetadata: true)); @@ -838,7 +838,7 @@ public void RegionConfiguredWithCustomInstanceDiscoveryUriThrowsException() { var httpManager = harness.HttpManager; - var ex = Assert.ThrowsException(() => CreateCca( + var ex = Assert.Throws(() => CreateCca( httpManager, ConfidentialClientApplication.AttemptRegionDiscovery, hasCustomInstanceMetadataUri: true)); @@ -933,7 +933,7 @@ public void RegionDiscoveryThrowsException_WhenCustomMetadataAndRegionDiscoveryE { var httpManager = harness.HttpManager; - var ex = Assert.ThrowsException(() => CreateCca( + var ex = Assert.Throws(() => CreateCca( httpManager, ConfidentialClientApplication.AttemptRegionDiscovery, hasCustomInstanceMetadata: true)); diff --git a/tests/Microsoft.Identity.Test.Unit/PublicApiTests/ConfidentialClientApplicationTests.cs b/tests/Microsoft.Identity.Test.Unit/PublicApiTests/ConfidentialClientApplicationTests.cs index a20528bc27..c3b30dddbc 100644 --- a/tests/Microsoft.Identity.Test.Unit/PublicApiTests/ConfidentialClientApplicationTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/PublicApiTests/ConfidentialClientApplicationTests.cs @@ -174,7 +174,7 @@ public async Task ClientCreds_MustFilterByTenantId_Async() .WithTenantId(TestConstants.Utid) .ExecuteAsync(CancellationToken.None).ConfigureAwait(false); - Assert.AreEqual(app.AppTokenCacheInternal.Accessor.GetAllAccessTokens().Single().TenantId, TestConstants.Utid); + Assert.AreEqual(TestConstants.Utid, app.AppTokenCacheInternal.Accessor.GetAllAccessTokens().Single().TenantId); string partitionKey = CacheKeyFactory.GetAppTokenCacheItemKey(TestConstants.ClientId, TestConstants.Utid, null); Assert.AreEqual( partitionKey, @@ -187,7 +187,7 @@ public async Task ClientCreds_MustFilterByTenantId_Async() .ExecuteAsync(CancellationToken.None).ConfigureAwait(false); Assert.IsNotNull(app.AppTokenCacheInternal.Accessor.GetAllAccessTokens().Single(at => at.TenantId == TestConstants.Utid2)); - Assert.AreEqual(2, ((InMemoryPartitionedAppTokenCacheAccessor)app.AppTokenCacheInternal.Accessor).AccessTokenCacheDictionary.Count); + Assert.HasCount(2, ((InMemoryPartitionedAppTokenCacheAccessor)app.AppTokenCacheInternal.Accessor).AccessTokenCacheDictionary); string partitionKey2 = CacheKeyFactory.GetAppTokenCacheItemKey(TestConstants.ClientId, TestConstants.Utid2, null); Assert.IsTrue(((InMemoryPartitionedAppTokenCacheAccessor)app.AppTokenCacheInternal.Accessor).AccessTokenCacheDictionary.Keys.Any(k => k.Equals(partitionKey))); @@ -215,12 +215,12 @@ public async Task ClientCreds_UsesDefaultPartitionedCacheCorrectly_Async() .ExecuteAsync(CancellationToken.None).ConfigureAwait(false); // One tenant partition with one token - Assert.AreEqual(1, app.AppTokenCacheInternal.Accessor.GetAllAccessTokens().Count); - Assert.AreEqual(1, ((InMemoryPartitionedAppTokenCacheAccessor)app.AppTokenCacheInternal.Accessor).AccessTokenCacheDictionary.Count); + Assert.HasCount(1, app.AppTokenCacheInternal.Accessor.GetAllAccessTokens()); + Assert.HasCount(1, ((InMemoryPartitionedAppTokenCacheAccessor)app.AppTokenCacheInternal.Accessor).AccessTokenCacheDictionary); string partitionKey = CacheKeyFactory.GetAppTokenCacheItemKey(TestConstants.ClientId, TestConstants.Utid, null); Assert.IsNotNull(((InMemoryPartitionedAppTokenCacheAccessor)app.AppTokenCacheInternal.Accessor).AccessTokenCacheDictionary[partitionKey]); - Assert.AreEqual(1, ((InMemoryPartitionedAppTokenCacheAccessor)app.AppTokenCacheInternal.Accessor).AccessTokenCacheDictionary[partitionKey].Count); + Assert.HasCount(1, ((InMemoryPartitionedAppTokenCacheAccessor)app.AppTokenCacheInternal.Accessor).AccessTokenCacheDictionary[partitionKey]); httpManager.AddMockHandlerSuccessfulClientCredentialTokenResponseMessage(); @@ -229,10 +229,10 @@ public async Task ClientCreds_UsesDefaultPartitionedCacheCorrectly_Async() .ExecuteAsync(CancellationToken.None).ConfigureAwait(false); // One tenant partition with two tokens - Assert.AreEqual(2, app.AppTokenCacheInternal.Accessor.GetAllAccessTokens().Count); - Assert.AreEqual(1, ((InMemoryPartitionedAppTokenCacheAccessor)app.AppTokenCacheInternal.Accessor).AccessTokenCacheDictionary.Count); + Assert.HasCount(2, app.AppTokenCacheInternal.Accessor.GetAllAccessTokens()); + Assert.HasCount(1, ((InMemoryPartitionedAppTokenCacheAccessor)app.AppTokenCacheInternal.Accessor).AccessTokenCacheDictionary); Assert.IsNotNull(((InMemoryPartitionedAppTokenCacheAccessor)app.AppTokenCacheInternal.Accessor).AccessTokenCacheDictionary[partitionKey]); - Assert.AreEqual(2, ((InMemoryPartitionedAppTokenCacheAccessor)app.AppTokenCacheInternal.Accessor).AccessTokenCacheDictionary[partitionKey].Count); + Assert.HasCount(2, ((InMemoryPartitionedAppTokenCacheAccessor)app.AppTokenCacheInternal.Accessor).AccessTokenCacheDictionary[partitionKey]); httpManager.AddMockHandlerSuccessfulClientCredentialTokenResponseMessage(); @@ -241,12 +241,12 @@ public async Task ClientCreds_UsesDefaultPartitionedCacheCorrectly_Async() .ExecuteAsync(CancellationToken.None).ConfigureAwait(false); // Two tenant partitions with three tokens total - Assert.AreEqual(3, app.AppTokenCacheInternal.Accessor.GetAllAccessTokens().Count); + Assert.HasCount(3, app.AppTokenCacheInternal.Accessor.GetAllAccessTokens()); string partitionKey2 = CacheKeyFactory.GetAppTokenCacheItemKey(TestConstants.ClientId, TestConstants.Utid2, null); - Assert.AreEqual(2, ((InMemoryPartitionedAppTokenCacheAccessor)app.AppTokenCacheInternal.Accessor).AccessTokenCacheDictionary.Count); + Assert.HasCount(2, ((InMemoryPartitionedAppTokenCacheAccessor)app.AppTokenCacheInternal.Accessor).AccessTokenCacheDictionary); Assert.IsNotNull(((InMemoryPartitionedAppTokenCacheAccessor)app.AppTokenCacheInternal.Accessor).AccessTokenCacheDictionary[partitionKey2]); - Assert.AreEqual(1, ((InMemoryPartitionedAppTokenCacheAccessor)app.AppTokenCacheInternal.Accessor).AccessTokenCacheDictionary[partitionKey2].Count); + Assert.HasCount(1, ((InMemoryPartitionedAppTokenCacheAccessor)app.AppTokenCacheInternal.Accessor).AccessTokenCacheDictionary[partitionKey2]); } } @@ -302,12 +302,12 @@ public async Task ConfidentialClientUsingSecretTestAsync() Assert.AreEqual(TestConstants.s_scope.AsSingleString(), result.Scopes.AsSingleString()); // make sure user token cache is empty - Assert.AreEqual(0, app.UserTokenCacheInternal.Accessor.GetAllAccessTokens().Count); - Assert.AreEqual(0, app.UserTokenCacheInternal.Accessor.GetAllRefreshTokens().Count); + Assert.IsEmpty(app.UserTokenCacheInternal.Accessor.GetAllAccessTokens()); + Assert.IsEmpty(app.UserTokenCacheInternal.Accessor.GetAllRefreshTokens()); // check app token cache count to be 1 - Assert.AreEqual(1, app.AppTokenCacheInternal.Accessor.GetAllAccessTokens().Count); - Assert.AreEqual(0, app.AppTokenCacheInternal.Accessor.GetAllRefreshTokens().Count); + Assert.HasCount(1, app.AppTokenCacheInternal.Accessor.GetAllAccessTokens()); + Assert.IsEmpty(app.AppTokenCacheInternal.Accessor.GetAllRefreshTokens()); appCacheAccess.AssertAccessCounts(1, 1); userCacheAccess.AssertAccessCounts(0, 0); @@ -319,12 +319,12 @@ public async Task ConfidentialClientUsingSecretTestAsync() Assert.AreEqual(TestConstants.s_scope.AsSingleString(), result.Scopes.AsSingleString()); // make sure user token cache is empty - Assert.AreEqual(0, app.UserTokenCacheInternal.Accessor.GetAllAccessTokens().Count); - Assert.AreEqual(0, app.UserTokenCacheInternal.Accessor.GetAllRefreshTokens().Count); + Assert.IsEmpty(app.UserTokenCacheInternal.Accessor.GetAllAccessTokens()); + Assert.IsEmpty(app.UserTokenCacheInternal.Accessor.GetAllRefreshTokens()); // check app token cache count to be 1 - Assert.AreEqual(1, app.AppTokenCacheInternal.Accessor.GetAllAccessTokens().Count); - Assert.AreEqual(0, app.AppTokenCacheInternal.Accessor.GetAllRefreshTokens().Count); + Assert.HasCount(1, app.AppTokenCacheInternal.Accessor.GetAllAccessTokens()); + Assert.IsEmpty(app.AppTokenCacheInternal.Accessor.GetAllRefreshTokens()); appCacheAccess.AssertAccessCounts(2, 1); userCacheAccess.AssertAccessCounts(0, 0); @@ -369,12 +369,12 @@ public async Task ConfidentialClientUsingAdfsAsync() userCacheAccess.AssertAccessCounts(0, 0); // make sure user token cache is empty - Assert.AreEqual(0, app.UserTokenCacheInternal.Accessor.GetAllAccessTokens().Count); - Assert.AreEqual(0, app.UserTokenCacheInternal.Accessor.GetAllRefreshTokens().Count); + Assert.IsEmpty(app.UserTokenCacheInternal.Accessor.GetAllAccessTokens()); + Assert.IsEmpty(app.UserTokenCacheInternal.Accessor.GetAllRefreshTokens()); // check app token cache count to be 1 - Assert.AreEqual(1, app.AppTokenCacheInternal.Accessor.GetAllAccessTokens().Count); - Assert.AreEqual(0, app.AppTokenCacheInternal.Accessor.GetAllRefreshTokens().Count); // no refresh tokens are returned + Assert.HasCount(1, app.AppTokenCacheInternal.Accessor.GetAllAccessTokens()); + Assert.IsEmpty(app.AppTokenCacheInternal.Accessor.GetAllRefreshTokens()); // no refresh tokens are returned // call AcquireTokenForClientAsync again to get result back from the cache result = await app.AcquireTokenForClient(TestConstants.s_scope.ToArray()).ExecuteAsync().ConfigureAwait(false); @@ -383,12 +383,12 @@ public async Task ConfidentialClientUsingAdfsAsync() Assert.AreEqual(TestConstants.s_scope.AsSingleString(), result.Scopes.AsSingleString()); // make sure user token cache is empty - Assert.AreEqual(0, app.UserTokenCacheInternal.Accessor.GetAllAccessTokens().Count); - Assert.AreEqual(0, app.UserTokenCacheInternal.Accessor.GetAllRefreshTokens().Count); + Assert.IsEmpty(app.UserTokenCacheInternal.Accessor.GetAllAccessTokens()); + Assert.IsEmpty(app.UserTokenCacheInternal.Accessor.GetAllRefreshTokens()); // check app token cache count to be 1 - Assert.AreEqual(1, app.AppTokenCacheInternal.Accessor.GetAllAccessTokens().Count); - Assert.AreEqual(0, app.AppTokenCacheInternal.Accessor.GetAllRefreshTokens().Count); // no refresh tokens are returned + Assert.HasCount(1, app.AppTokenCacheInternal.Accessor.GetAllAccessTokens()); + Assert.IsEmpty(app.AppTokenCacheInternal.Accessor.GetAllRefreshTokens()); // no refresh tokens are returned appCacheAccess.AssertAccessCounts(2, 1); userCacheAccess.AssertAccessCounts(0, 0); @@ -419,7 +419,7 @@ public async Task ClientCreds_And_AAD_LogRequestUri_OnServerError_Async() //Assert Assert.AreEqual(MsalError.ServiceNotAvailable, ex.ErrorCode); - Assert.IsTrue(ex.Message.Contains(ClientApplicationBase.DefaultAuthority + "oauth2/v2.0/token")); + Assert.Contains(ClientApplicationBase.DefaultAuthority + "oauth2/v2.0/token", ex.Message); } } @@ -446,7 +446,7 @@ public async Task ClientCreds_And_ADFS_LogRequestUri_OnServerError_Async() //Assert Assert.AreEqual(MsalError.ServiceNotAvailable, ex.ErrorCode); - Assert.IsTrue(ex.Message.Contains(TestConstants.OnPremiseAuthority + "oauth2/token")); + Assert.Contains(TestConstants.OnPremiseAuthority + "oauth2/token", ex.Message); } } @@ -569,12 +569,12 @@ public async Task ConfidentialClientUsingCertificateTestAsync() userCacheAccess.AssertAccessCounts(0, 0); // make sure user token cache is empty - Assert.AreEqual(0, app.UserTokenCacheInternal.Accessor.GetAllAccessTokens().Count); - Assert.AreEqual(0, app.UserTokenCacheInternal.Accessor.GetAllRefreshTokens().Count); + Assert.IsEmpty(app.UserTokenCacheInternal.Accessor.GetAllAccessTokens()); + Assert.IsEmpty(app.UserTokenCacheInternal.Accessor.GetAllRefreshTokens()); // check app token cache count to be 1 - Assert.AreEqual(1, app.AppTokenCacheInternal.Accessor.GetAllAccessTokens().Count); - Assert.AreEqual(0, app.AppTokenCacheInternal.Accessor.GetAllRefreshTokens().Count); // no RTs are returned + Assert.HasCount(1, app.AppTokenCacheInternal.Accessor.GetAllAccessTokens()); + Assert.IsEmpty(app.AppTokenCacheInternal.Accessor.GetAllRefreshTokens()); // no RTs are returned } } @@ -628,12 +628,12 @@ public async Task ConfidentialClientUsingClientAssertionClaimsTestAsync() userCacheAccess.AssertAccessCounts(0, 0); // make sure user token cache is empty - Assert.AreEqual(0, app.UserTokenCacheInternal.Accessor.GetAllAccessTokens().Count); - Assert.AreEqual(0, app.UserTokenCacheInternal.Accessor.GetAllRefreshTokens().Count); + Assert.IsEmpty(app.UserTokenCacheInternal.Accessor.GetAllAccessTokens()); + Assert.IsEmpty(app.UserTokenCacheInternal.Accessor.GetAllRefreshTokens()); // check app token cache count to be 1 - Assert.AreEqual(1, app.AppTokenCacheInternal.Accessor.GetAllAccessTokens().Count); - Assert.AreEqual(0, app.AppTokenCacheInternal.Accessor.GetAllRefreshTokens().Count); // no RTs are returned + Assert.HasCount(1, app.AppTokenCacheInternal.Accessor.GetAllAccessTokens()); + Assert.IsEmpty(app.AppTokenCacheInternal.Accessor.GetAllRefreshTokens()); // no RTs are returned var actualAssertion = tokenHttpHandler.ActualRequestPostData["client_assertion"]; @@ -667,12 +667,12 @@ public async Task ConfidentialClientUsingSignedClientAssertionTestAsync() Assert.AreEqual(TestConstants.s_scope.AsSingleString(), result.Scopes.AsSingleString()); // make sure user token cache is empty - Assert.AreEqual(0, app.UserTokenCacheInternal.Accessor.GetAllAccessTokens().Count); - Assert.AreEqual(0, app.UserTokenCacheInternal.Accessor.GetAllRefreshTokens().Count); + Assert.IsEmpty(app.UserTokenCacheInternal.Accessor.GetAllAccessTokens()); + Assert.IsEmpty(app.UserTokenCacheInternal.Accessor.GetAllRefreshTokens()); // check app token cache count to be 1 - Assert.AreEqual(1, app.AppTokenCacheInternal.Accessor.GetAllAccessTokens().Count); - Assert.AreEqual(0, app.AppTokenCacheInternal.Accessor.GetAllRefreshTokens().Count); // no RTs are returned + Assert.HasCount(1, app.AppTokenCacheInternal.Accessor.GetAllAccessTokens()); + Assert.IsEmpty(app.AppTokenCacheInternal.Accessor.GetAllRefreshTokens()); // no RTs are returned // assert client credential @@ -698,12 +698,12 @@ public async Task ConfidentialClientUsingSignedClientAssertion_SyncDelegateTestA Assert.AreEqual(TestConstants.s_scope.AsSingleString(), result.Scopes.AsSingleString()); // make sure user token cache is empty - Assert.AreEqual(0, app.UserTokenCacheInternal.Accessor.GetAllAccessTokens().Count); - Assert.AreEqual(0, app.UserTokenCacheInternal.Accessor.GetAllRefreshTokens().Count); + Assert.IsEmpty(app.UserTokenCacheInternal.Accessor.GetAllAccessTokens()); + Assert.IsEmpty(app.UserTokenCacheInternal.Accessor.GetAllRefreshTokens()); // check app token cache count to be 1 - Assert.AreEqual(1, app.AppTokenCacheInternal.Accessor.GetAllAccessTokens().Count); - Assert.AreEqual(0, app.AppTokenCacheInternal.Accessor.GetAllRefreshTokens().Count); // no RTs are returned + Assert.HasCount(1, app.AppTokenCacheInternal.Accessor.GetAllAccessTokens()); + Assert.IsEmpty(app.AppTokenCacheInternal.Accessor.GetAllRefreshTokens()); // no RTs are returned // assert client credential Assert.AreEqual( @@ -867,11 +867,11 @@ public void Constructor_NullDelegate_ThrowsArgumentNullException() Func> nullDelegate = null; // Act &  Assert - Assert.ThrowsException(() => + Assert.Throws(() => new ClientAssertionDelegateCredential(nullDelegate)); } - [DataTestMethod] + [TestMethod] [DataRow(false)] // bearer (no cert) [DataRow(true)] // PoP (with cert) public void Constructor_ValidDelegate_DoesNotThrow(bool withCert) @@ -1049,7 +1049,7 @@ public void GetAuthorizationRequestUrl_WithConsumerInCreate_ReturnsConsumers() .GetResult(); #pragma warning restore CS0618 // Type or member is obsolete - Assert.IsTrue(authorizationRequestUrl.Segments[1].StartsWith(Constants.Common)); + Assert.StartsWith(Constants.Common, authorizationRequestUrl.Segments[1]); } } @@ -1193,7 +1193,7 @@ public async Task IdTokenHasNoOid_ADALSerialization_Async() } } - [DataTestMethod] + [TestMethod] [DataRow(true)] [DataRow(false)] public async Task AcquireTokenByAuthorizationCode_IgnoresRegion_Async(bool autodetectRegion) @@ -1550,8 +1550,8 @@ public async Task AuthorizationCodeRequestTestAsync() .ConfigureAwait(false); Assert.IsNotNull(result); - Assert.AreEqual(1, app.UserTokenCacheInternal.Accessor.GetAllAccessTokens().Count); - Assert.AreEqual(1, app.UserTokenCacheInternal.Accessor.GetAllRefreshTokens().Count); + Assert.HasCount(1, app.UserTokenCacheInternal.Accessor.GetAllAccessTokens()); + Assert.HasCount(1, app.UserTokenCacheInternal.Accessor.GetAllRefreshTokens()); app = ConfidentialClientApplicationBuilder.Create(TestConstants.ClientId) .WithAuthority(new Uri("https://" + TestConstants.ProductionPrefNetworkEnvironment + "/tfp/home/policy"), true) @@ -1666,10 +1666,10 @@ public async Task AcquireTokenByRefreshTokenTestAsync() .ExecuteAsync(CancellationToken.None) .ConfigureAwait(false); - Assert.AreEqual(1, app.UserTokenCacheInternal.Accessor.GetAllAccessTokens().Count); - Assert.AreEqual(1, app.UserTokenCacheInternal.Accessor.GetAllRefreshTokens().Count); + Assert.HasCount(1, app.UserTokenCacheInternal.Accessor.GetAllAccessTokens()); + Assert.HasCount(1, app.UserTokenCacheInternal.Accessor.GetAllRefreshTokens()); Assert.IsNotNull(result.AccessToken); - Assert.AreEqual(result.AccessToken, "some-access-token"); + Assert.AreEqual("some-access-token", result.AccessToken); app.UserTokenCacheInternal.Accessor.Clear(); httpManager.AddSuccessTokenResponseMockHandlerForPost(TestConstants.AuthorityCommonTenant); @@ -1678,10 +1678,10 @@ public async Task AcquireTokenByRefreshTokenTestAsync() .ExecuteAsync(CancellationToken.None) .ConfigureAwait(false); - Assert.AreEqual(1, app.UserTokenCacheInternal.Accessor.GetAllAccessTokens().Count); - Assert.AreEqual(1, app.UserTokenCacheInternal.Accessor.GetAllRefreshTokens().Count); + Assert.HasCount(1, app.UserTokenCacheInternal.Accessor.GetAllAccessTokens()); + Assert.HasCount(1, app.UserTokenCacheInternal.Accessor.GetAllRefreshTokens()); Assert.IsNotNull(result.AccessToken); - Assert.AreEqual(result.AccessToken, "some-access-token"); + Assert.AreEqual("some-access-token", result.AccessToken); } } @@ -1906,11 +1906,11 @@ public async Task AcquireTokenForClientAuthorityCheckTestAsync(string tenant) if (tenant.Equals(TestConstants.AuthorityConsumersTenant)) { - Assert.IsFalse(log.Contains(MsalErrorMessage.ClientCredentialWrongAuthority)); + Assert.DoesNotContain(MsalErrorMessage.ClientCredentialWrongAuthority, log); } else { - Assert.IsTrue(log.Contains(MsalErrorMessage.ClientCredentialWrongAuthority)); + Assert.Contains(MsalErrorMessage.ClientCredentialWrongAuthority, log); } } } @@ -1943,11 +1943,11 @@ public async Task AcquireTokenOboAuthorityCheckTestAsync(string tenant) if (tenant.Equals(TestConstants.AuthorityConsumersTenant)) { - Assert.IsFalse(log.Contains(MsalErrorMessage.OnBehalfOfWrongAuthority)); + Assert.DoesNotContain(MsalErrorMessage.OnBehalfOfWrongAuthority, log); } else { - Assert.IsTrue(log.Contains(MsalErrorMessage.OnBehalfOfWrongAuthority)); + Assert.Contains(MsalErrorMessage.OnBehalfOfWrongAuthority, log); } } } @@ -1990,7 +1990,7 @@ public void AssertionInputIsMutable() [TestMethod] public void ConfidentialClient_WithEmptyClientSecret_ThrowsException() { - Assert.ThrowsException(() => + Assert.Throws(() => { ConfidentialClientApplicationBuilder.Create(TestConstants.ClientId) .WithClientSecret(string.Empty) // or null @@ -2092,7 +2092,7 @@ await AssertException.TaskThrowsAsync( [TestMethod] public void ConfidentialClient_WithInvalidAuthority_ThrowsArgumentException() { - Assert.ThrowsException(() => + Assert.Throws(() => { ConfidentialClientApplicationBuilder .Create(TestConstants.ClientId) @@ -2202,7 +2202,7 @@ public async Task ForceRefreshAndAccessTokenHash_ThrowsException_Async() ).ConfigureAwait(false); Assert.AreEqual(MsalError.ForceRefreshNotCompatibleWithTokenHash, ex.ErrorCode); - Assert.IsTrue(ex.Message.Contains(MsalErrorMessage.ForceRefreshAndTokenHasNotCompatible)); + Assert.Contains(MsalErrorMessage.ForceRefreshAndTokenHasNotCompatible, ex.Message); } [TestMethod] @@ -2318,12 +2318,12 @@ public async Task ConfidentialClient_acquireTokenForClient_ReturnsAuthZTestAsync Assert.AreEqual("[\r\n \"value1\",\r\n \"value2\"\r\n]", result.AdditionalResponseParameters["authz"]); #endif // make sure user token cache is empty - Assert.AreEqual(0, app.UserTokenCacheInternal.Accessor.GetAllAccessTokens().Count); - Assert.AreEqual(0, app.UserTokenCacheInternal.Accessor.GetAllRefreshTokens().Count); + Assert.IsEmpty(app.UserTokenCacheInternal.Accessor.GetAllAccessTokens()); + Assert.IsEmpty(app.UserTokenCacheInternal.Accessor.GetAllRefreshTokens()); // check app token cache count to be 1 - Assert.AreEqual(1, app.AppTokenCacheInternal.Accessor.GetAllAccessTokens().Count); - Assert.AreEqual(0, app.AppTokenCacheInternal.Accessor.GetAllRefreshTokens().Count); + Assert.HasCount(1, app.AppTokenCacheInternal.Accessor.GetAllAccessTokens()); + Assert.IsEmpty(app.AppTokenCacheInternal.Accessor.GetAllRefreshTokens()); appCacheAccess.AssertAccessCounts(1, 1); userCacheAccess.AssertAccessCounts(0, 0); @@ -2340,12 +2340,12 @@ public async Task ConfidentialClient_acquireTokenForClient_ReturnsAuthZTestAsync Assert.AreEqual("[\r\n \"value1\",\r\n \"value2\"\r\n]", result.AdditionalResponseParameters["authz"]); #endif // make sure user token cache is empty - Assert.AreEqual(0, app.UserTokenCacheInternal.Accessor.GetAllAccessTokens().Count); - Assert.AreEqual(0, app.UserTokenCacheInternal.Accessor.GetAllRefreshTokens().Count); + Assert.IsEmpty(app.UserTokenCacheInternal.Accessor.GetAllAccessTokens()); + Assert.IsEmpty(app.UserTokenCacheInternal.Accessor.GetAllRefreshTokens()); // check app token cache count to be 1 - Assert.AreEqual(1, app.AppTokenCacheInternal.Accessor.GetAllAccessTokens().Count); - Assert.AreEqual(0, app.AppTokenCacheInternal.Accessor.GetAllRefreshTokens().Count); + Assert.HasCount(1, app.AppTokenCacheInternal.Accessor.GetAllAccessTokens()); + Assert.IsEmpty(app.AppTokenCacheInternal.Accessor.GetAllRefreshTokens()); appCacheAccess.AssertAccessCounts(2, 1); userCacheAccess.AssertAccessCounts(0, 0); diff --git a/tests/Microsoft.Identity.Test.Unit/PublicApiTests/ExtensiblityTests.cs b/tests/Microsoft.Identity.Test.Unit/PublicApiTests/ExtensiblityTests.cs index 06e9cc74dc..2afc63d860 100644 --- a/tests/Microsoft.Identity.Test.Unit/PublicApiTests/ExtensiblityTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/PublicApiTests/ExtensiblityTests.cs @@ -109,9 +109,9 @@ public async Task CertificateOverrideAsync() Assert.AreEqual("Bearer", result.TokenType); Assert.AreEqual(TokenSource.IdentityProvider, result.AuthenticationResultMetadata.TokenSource); IReadOnlyList ats = (app.AppTokenCache as ITokenCacheInternal).Accessor.GetAllAccessTokens(); - Assert.AreEqual(2, ats.Count); - Assert.IsTrue(ats.Single(at => at.KeyId == "key1") != null); - Assert.IsTrue(ats.Single(at => at.KeyId == null) != null); + Assert.HasCount(2, ats); + Assert.IsNotNull(ats.Single(at => at.KeyId == "key1")); + Assert.IsNotNull(ats.Single(at => at.KeyId == null)); } } @@ -168,7 +168,7 @@ public async Task ValidateAppTokenProviderAsync() var tokens = app.AppTokenCacheInternal.Accessor.GetAllAccessTokens(); - Assert.AreEqual(1, tokens.Count); + Assert.HasCount(1, tokens); var token = tokens.FirstOrDefault(); Assert.IsNotNull(token); @@ -204,7 +204,7 @@ public async Task ValidateAppTokenProviderAsync() Assert.IsNotNull(result.AccessToken); Assert.AreEqual(TestConstants.DefaultAccessToken + differentScopesForAt, result.AccessToken); Assert.AreEqual(TokenSource.IdentityProvider, result.AuthenticationResultMetadata.TokenSource); - Assert.AreEqual(app.AppTokenCacheInternal.Accessor.GetAllAccessTokens().Count, 2); + Assert.HasCount(2, app.AppTokenCacheInternal.Accessor.GetAllAccessTokens()); Assert.AreEqual(3, callbackInvoked); // Acquire token from app provider with claims. Should not use cache @@ -241,7 +241,7 @@ public async Task ValidateAdditionalCacheParametersAreStored() .ConfigureAwait(false); var parameters = app.AppTokenCacheInternal.Accessor.GetAllAccessTokens().Single().PersistedCacheParameters; - Assert.IsTrue(parameters.Count == 5); + Assert.HasCount(5, parameters); parameters.TryGetValue("additional_param1", out string additionalParam1); parameters.TryGetValue("additional_param2", out string additionalParam2); @@ -270,7 +270,7 @@ public async Task ValidateAdditionalCacheParametersAreStored() Assert.AreEqual(TokenSource.Cache, result.AuthenticationResultMetadata.TokenSource); parameters = app.AppTokenCacheInternal.Accessor.GetAllAccessTokens().Single().PersistedCacheParameters; - Assert.IsTrue(parameters.Count == 5); + Assert.HasCount(5, parameters); parameters.TryGetValue("additional_param1", out additionalParam1); parameters.TryGetValue("additional_param2", out additionalParam2); @@ -294,7 +294,7 @@ public async Task ValidateAdditionalCacheParametersAreStored() Assert.AreEqual(TokenSource.Cache, result.AuthenticationResultMetadata.TokenSource); parameters = app.AppTokenCacheInternal.Accessor.GetAllAccessTokens().Single().PersistedCacheParameters; - Assert.IsTrue(parameters.Count == 5); + Assert.HasCount(5, parameters); parameters.TryGetValue("additional_param1", out additionalParam1); parameters.TryGetValue("additional_param2", out additionalParam2); @@ -321,7 +321,7 @@ public async Task ValidateAdditionalCacheParametersAreStored() Assert.AreEqual(TokenSource.IdentityProvider, result.AuthenticationResultMetadata.TokenSource); parameters = app.AppTokenCacheInternal.Accessor.GetAllAccessTokens().Single().PersistedCacheParameters; - Assert.IsTrue(parameters.Count == 5); + Assert.HasCount(5, parameters); parameters.TryGetValue("additional_param1", out additionalParam1); parameters.TryGetValue("additional_param2", out additionalParam2); @@ -353,7 +353,7 @@ public async Task ValidateAdditionalCacheParametersAreStored() .ConfigureAwait(false); parameters = app.AppTokenCacheInternal.Accessor.GetAllAccessTokens().Single().PersistedCacheParameters; - Assert.IsTrue(parameters.Count == 2); + Assert.HasCount(2, parameters); parameters.TryGetValue("additional_param1", out additionalParam1); parameters.TryGetValue("additional_param3", out additionalParam3); @@ -373,7 +373,7 @@ public async Task ValidateAdditionalCacheParametersAreStored() .ConfigureAwait(false); parameters = app.AppTokenCacheInternal.Accessor.GetAllAccessTokens().Single().PersistedCacheParameters; - Assert.IsTrue(parameters == null); + Assert.IsNull(parameters); //Ensure missing cache parameters are not added app = ConfidentialClientApplicationBuilder.Create(TestConstants.ClientId) @@ -392,7 +392,7 @@ public async Task ValidateAdditionalCacheParametersAreStored() parameters = app.AppTokenCacheInternal.Accessor.GetAllAccessTokens().Single().PersistedCacheParameters; parameters.TryGetValue("additional_param1", out string additionalParam); Assert.IsNull(additionalParam); - Assert.IsTrue(result.AdditionalResponseParameters.Count == 5); + Assert.HasCount(5, result.AdditionalResponseParameters); } } diff --git a/tests/Microsoft.Identity.Test.Unit/PublicApiTests/ExtraBodyParametersTests.cs b/tests/Microsoft.Identity.Test.Unit/PublicApiTests/ExtraBodyParametersTests.cs index d03d147c01..4dde6a6734 100644 --- a/tests/Microsoft.Identity.Test.Unit/PublicApiTests/ExtraBodyParametersTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/PublicApiTests/ExtraBodyParametersTests.cs @@ -77,7 +77,7 @@ public async Task ValidateExtraBodyParameters() //Assert Assert.IsNotNull(authResult); - Assert.AreEqual(authResult.AuthenticationResultMetadata.TokenSource, TokenSource.IdentityProvider); + Assert.AreEqual(TokenSource.IdentityProvider, authResult.AuthenticationResultMetadata.TokenSource); //Ensure the extra body parameters are present in the cache key authResult = await confidentialApp.AcquireTokenForClient(new[] { _scope }) @@ -88,7 +88,7 @@ public async Task ValidateExtraBodyParameters() //Assert Assert.IsNotNull(authResult); - Assert.AreEqual(authResult.AuthenticationResultMetadata.TokenSource, TokenSource.Cache); + Assert.AreEqual(TokenSource.Cache, authResult.AuthenticationResultMetadata.TokenSource); //Ensure the same extra body parameters are needed get the cache key httpManager.AddMockHandlerSuccessfulClientCredentialTokenResponseMessage( @@ -108,7 +108,7 @@ public async Task ValidateExtraBodyParameters() //Assert Assert.IsNotNull(authResult); - Assert.AreEqual(authResult.AuthenticationResultMetadata.TokenSource, TokenSource.IdentityProvider); + Assert.AreEqual(TokenSource.IdentityProvider, authResult.AuthenticationResultMetadata.TokenSource); //Ensure the first token can still be retrieved from the cache _expectedParameterHash = "8cY9AFTXo3uSqueI1A_HPiX0j66dJXB-3c3BTDcJVxE"; @@ -120,7 +120,7 @@ public async Task ValidateExtraBodyParameters() //Assert Assert.IsNotNull(authResult); - Assert.AreEqual(authResult.AuthenticationResultMetadata.TokenSource, TokenSource.Cache); + Assert.AreEqual(TokenSource.Cache, authResult.AuthenticationResultMetadata.TokenSource); } } @@ -187,7 +187,7 @@ public async Task ValidateExtraBodyParametersAreCombined() //Assert Assert.IsNotNull(authResult); - Assert.AreEqual(authResult.AuthenticationResultMetadata.TokenSource, TokenSource.IdentityProvider); + Assert.AreEqual(TokenSource.IdentityProvider, authResult.AuthenticationResultMetadata.TokenSource); //Ensure the extra body parameters are present in the cache key authResult = await confidentialApp.AcquireTokenForClient(new[] { scope }) @@ -199,7 +199,7 @@ public async Task ValidateExtraBodyParametersAreCombined() //Assert Assert.IsNotNull(authResult); - Assert.AreEqual(authResult.AuthenticationResultMetadata.TokenSource, TokenSource.Cache); + Assert.AreEqual(TokenSource.Cache, authResult.AuthenticationResultMetadata.TokenSource); //Ensure the same extra body parameters are needed get the cache key httpManager.AddMockHandlerSuccessfulClientCredentialTokenResponseMessage( @@ -219,7 +219,7 @@ public async Task ValidateExtraBodyParametersAreCombined() //Assert Assert.IsNotNull(authResult); - Assert.AreEqual(authResult.AuthenticationResultMetadata.TokenSource, TokenSource.IdentityProvider); + Assert.AreEqual(TokenSource.IdentityProvider, authResult.AuthenticationResultMetadata.TokenSource); httpManager.AddMockHandlerSuccessfulClientCredentialTokenResponseMessage( expectedPostData: new Dictionary @@ -237,7 +237,7 @@ public async Task ValidateExtraBodyParametersAreCombined() //Assert Assert.IsNotNull(authResult); - Assert.AreEqual(authResult.AuthenticationResultMetadata.TokenSource, TokenSource.IdentityProvider); + Assert.AreEqual(TokenSource.IdentityProvider, authResult.AuthenticationResultMetadata.TokenSource); } } @@ -266,7 +266,7 @@ public async Task WithExtraBodyParameters_NullInput_ReturnToken() .ConfigureAwait(false); Assert.IsNotNull(authResult); - Assert.AreEqual(authResult.AuthenticationResultMetadata.TokenSource, TokenSource.IdentityProvider); + Assert.AreEqual(TokenSource.IdentityProvider, authResult.AuthenticationResultMetadata.TokenSource); authResult = await confidentialApp.AcquireTokenForClient(new[] { _scope }) .WithExtraBodyParameters(null) @@ -274,7 +274,7 @@ public async Task WithExtraBodyParameters_NullInput_ReturnToken() .ConfigureAwait(false); Assert.IsNotNull(authResult); - Assert.AreEqual(authResult.AuthenticationResultMetadata.TokenSource, TokenSource.Cache); + Assert.AreEqual(TokenSource.Cache, authResult.AuthenticationResultMetadata.TokenSource); //Ensure that the token can still be retrieved from the cache when the input is an empty dictionary authResult = await confidentialApp.AcquireTokenForClient(new[] { _scope }) @@ -283,7 +283,7 @@ public async Task WithExtraBodyParameters_NullInput_ReturnToken() .ConfigureAwait(false); Assert.IsNotNull(authResult); - Assert.AreEqual(authResult.AuthenticationResultMetadata.TokenSource, TokenSource.Cache); + Assert.AreEqual(TokenSource.Cache, authResult.AuthenticationResultMetadata.TokenSource); } } diff --git a/tests/Microsoft.Identity.Test.Unit/PublicApiTests/ExtraQueryParametersTests.cs b/tests/Microsoft.Identity.Test.Unit/PublicApiTests/ExtraQueryParametersTests.cs index 0d0491d662..d6a74c1a6e 100644 --- a/tests/Microsoft.Identity.Test.Unit/PublicApiTests/ExtraQueryParametersTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/PublicApiTests/ExtraQueryParametersTests.cs @@ -104,9 +104,9 @@ public async Task WithExtraQueryParameters_DeprecatedDoNotAffectTokenCaching_Tes Assert.AreEqual(TokenSource.Cache, silentResult.AuthenticationResultMetadata.TokenSource); // Verify expected cache state - Assert.AreEqual(1, app.AppTokenCacheInternal.Accessor.GetAllAccessTokens().Count); - Assert.AreEqual(1, app.UserTokenCacheInternal.Accessor.GetAllAccessTokens().Count); - Assert.AreEqual(1, app.UserTokenCacheInternal.Accessor.GetAllRefreshTokens().Count); + Assert.HasCount(1, app.AppTokenCacheInternal.Accessor.GetAllAccessTokens()); + Assert.HasCount(1, app.UserTokenCacheInternal.Accessor.GetAllAccessTokens()); + Assert.HasCount(1, app.UserTokenCacheInternal.Accessor.GetAllRefreshTokens()); } } @@ -277,9 +277,9 @@ public async Task WithExtraQueryParameters_TupleVersion_ControlsCaching_TestAsyn Assert.AreEqual(TokenSource.Cache, silentResult1.AuthenticationResultMetadata.TokenSource); // Verify final cache state - Assert.AreEqual(4, app.AppTokenCacheInternal.Accessor.GetAllAccessTokens().Count, "Should have 4 app tokens in cache"); - Assert.AreEqual(1, app.UserTokenCacheInternal.Accessor.GetAllAccessTokens().Count, "Should have 1 user token in cache"); - Assert.AreEqual(1, app.UserTokenCacheInternal.Accessor.GetAllRefreshTokens().Count, "Should have 1 refresh token in cache"); + Assert.HasCount(4, app.AppTokenCacheInternal.Accessor.GetAllAccessTokens(), "Should have 4 app tokens in cache"); + Assert.HasCount(1, app.UserTokenCacheInternal.Accessor.GetAllAccessTokens(), "Should have 1 user token in cache"); + Assert.HasCount(1, app.UserTokenCacheInternal.Accessor.GetAllRefreshTokens(), "Should have 1 refresh token in cache"); } } @@ -311,7 +311,7 @@ public async Task WithExtraQueryParameters_VaryingCacheKeyInclusion_TestAsync() Assert.AreEqual("token_with_both_params", result1.AccessToken); Assert.AreEqual(TokenSource.IdentityProvider, result1.AuthenticationResultMetadata.TokenSource); - Assert.AreEqual(1, app.AppTokenCacheInternal.Accessor.GetAllAccessTokens().Count); + Assert.HasCount(1, app.AppTokenCacheInternal.Accessor.GetAllAccessTokens()); // Step 2: Request with same parameters, but only req_param_1 in the cache key // Cache key is different now (only includes req_param_1), so should make new token request @@ -327,7 +327,7 @@ public async Task WithExtraQueryParameters_VaryingCacheKeyInclusion_TestAsync() Assert.AreEqual("token_with_one_param", result2.AccessToken); Assert.AreEqual(TokenSource.IdentityProvider, result2.AuthenticationResultMetadata.TokenSource); - Assert.AreEqual(2, app.AppTokenCacheInternal.Accessor.GetAllAccessTokens().Count, "Should have 2 different tokens in cache"); + Assert.HasCount(2, app.AppTokenCacheInternal.Accessor.GetAllAccessTokens(), "Should have 2 different tokens in cache"); // Step 3: Request with only req_param_1, included in cache key // Cache key matches step 2, should use cached token @@ -341,7 +341,7 @@ public async Task WithExtraQueryParameters_VaryingCacheKeyInclusion_TestAsync() Assert.AreEqual("token_with_one_param", result3.AccessToken); Assert.AreEqual(TokenSource.Cache, result3.AuthenticationResultMetadata.TokenSource, "Should retrieve from cache since cache key matches step 2"); - Assert.AreEqual(2, app.AppTokenCacheInternal.Accessor.GetAllAccessTokens().Count, "Should still have 2 tokens in cache"); + Assert.HasCount(2, app.AppTokenCacheInternal.Accessor.GetAllAccessTokens(), "Should still have 2 tokens in cache"); } } @@ -372,7 +372,7 @@ public async Task WithExtraQueryParameters_ParameterOrderDoesNotAffectCacheKey_T Assert.AreEqual("token_with_params_order1", result1.AccessToken); Assert.AreEqual(TokenSource.IdentityProvider, result1.AuthenticationResultMetadata.TokenSource); - Assert.AreEqual(1, app.AppTokenCacheInternal.Accessor.GetAllAccessTokens().Count, "Should have 1 token after first request"); + Assert.HasCount(1, app.AppTokenCacheInternal.Accessor.GetAllAccessTokens(), "Should have 1 token after first request"); // Step 3: Make token request with same parameters but in different order: req_param_3, req_param_1, req_param_2 // Same cache key parameters (1 and 3), so should hit cache @@ -391,7 +391,7 @@ public async Task WithExtraQueryParameters_ParameterOrderDoesNotAffectCacheKey_T "Should return same token regardless of parameter order"); Assert.AreEqual(TokenSource.Cache, result2.AuthenticationResultMetadata.TokenSource, "Should retrieve from cache when cache key parameters match (order-independent)"); - Assert.AreEqual(1, app.AppTokenCacheInternal.Accessor.GetAllAccessTokens().Count, + Assert.HasCount(1, app.AppTokenCacheInternal.Accessor.GetAllAccessTokens(), "Should still have only 1 token in cache"); // Step 4: Make another request with a different ordering to triple-check @@ -409,7 +409,7 @@ public async Task WithExtraQueryParameters_ParameterOrderDoesNotAffectCacheKey_T "Should return same token with yet another parameter order"); Assert.AreEqual(TokenSource.Cache, result3.AuthenticationResultMetadata.TokenSource, "Should retrieve from cache (order-independent)"); - Assert.AreEqual(1, app.AppTokenCacheInternal.Accessor.GetAllAccessTokens().Count, + Assert.HasCount(1, app.AppTokenCacheInternal.Accessor.GetAllAccessTokens(), "Should still have only 1 token in cache"); // Step 5: Verify that changing values (not just order) does create a new cache entry @@ -428,7 +428,7 @@ public async Task WithExtraQueryParameters_ParameterOrderDoesNotAffectCacheKey_T "Should get new token when cache key parameter value changes"); Assert.AreEqual(TokenSource.IdentityProvider, result4.AuthenticationResultMetadata.TokenSource, "Should make new request when cache key parameter value is different"); - Assert.AreEqual(2, app.AppTokenCacheInternal.Accessor.GetAllAccessTokens().Count, + Assert.HasCount(2, app.AppTokenCacheInternal.Accessor.GetAllAccessTokens(), "Should now have 2 tokens in cache (different cache keys)"); } } diff --git a/tests/Microsoft.Identity.Test.Unit/PublicApiTests/LoggerTests.cs b/tests/Microsoft.Identity.Test.Unit/PublicApiTests/LoggerTests.cs index b6237043de..2303b189a7 100644 --- a/tests/Microsoft.Identity.Test.Unit/PublicApiTests/LoggerTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/PublicApiTests/LoggerTests.cs @@ -287,7 +287,7 @@ public async Task IdentityLoggerOverridesLegacyLoggerTestAsync() .ConfigureAwait(false); Assert.IsNotNull(result); - Assert.IsTrue(testLogger.StringBuilder.ToString().Contains("AcquireTokenByAuthorizationCode")); + Assert.Contains("AcquireTokenByAuthorizationCode", testLogger.StringBuilder.ToString()); } } @@ -337,13 +337,13 @@ public async Task ExternalMsalLoggerTestAsync(bool piiLogging, bool useCallback) if (piiLogging) { - Assert.IsTrue(stringBuilder.ToString().Contains(TestConstants.PiiSerializeLogMessage)); - Assert.IsTrue(stringBuilder.ToString().Contains(TestConstants.PiiDeserializeLogMessage)); + Assert.Contains(TestConstants.PiiSerializeLogMessage, stringBuilder.ToString()); + Assert.Contains(TestConstants.PiiDeserializeLogMessage, stringBuilder.ToString()); } else { - Assert.IsTrue(stringBuilder.ToString().Contains(TestConstants.SerializeLogMessage)); - Assert.IsTrue(stringBuilder.ToString().Contains(TestConstants.DeserializeLogMessage)); + Assert.Contains(TestConstants.SerializeLogMessage, stringBuilder.ToString()); + Assert.Contains(TestConstants.DeserializeLogMessage, stringBuilder.ToString()); } } } @@ -396,12 +396,12 @@ public async Task ClaimsChallengeErrorLogged_Test(bool piiLogging) var app = appBuilder.Build(); - var ex = await Assert.ThrowsExceptionAsync(async () => + var ex = await Assert.ThrowsAsync(async () => { await app.AcquireTokenForClient(TestConstants.s_scope).ExecuteAsync().ConfigureAwait(false); }).ConfigureAwait(false); - Assert.IsTrue(stringBuilder.ToString().Contains(MsalErrorMessage.ClaimsChallenge)); + Assert.Contains(MsalErrorMessage.ClaimsChallenge, stringBuilder.ToString()); } } diff --git a/tests/Microsoft.Identity.Test.Unit/PublicApiTests/MtlsPopTests.cs b/tests/Microsoft.Identity.Test.Unit/PublicApiTests/MtlsPopTests.cs index 230d3f4954..769b1f9df9 100644 --- a/tests/Microsoft.Identity.Test.Unit/PublicApiTests/MtlsPopTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/PublicApiTests/MtlsPopTests.cs @@ -99,7 +99,7 @@ public async Task MtlsPopWithoutCertificateWithClientClaimsAsync() .Build(); // Expecting an exception because MTLS PoP requires a certificate to sign the claims - MsalClientException ex = await Assert.ThrowsExceptionAsync(() => + MsalClientException ex = await Assert.ThrowsAsync(() => app.AcquireTokenForClient(TestConstants.s_scope) .WithMtlsProofOfPossession() // Enables MTLS PoP .ExecuteAsync()) @@ -117,7 +117,7 @@ public async Task MtlsPopWithoutCertificateWithClientAssertionAsync() .Build(); // Expecting an exception because MTLS PoP requires a certificate to sign the claims - MsalClientException ex = await Assert.ThrowsExceptionAsync(() => + MsalClientException ex = await Assert.ThrowsAsync(() => app.AcquireTokenForClient(TestConstants.s_scope) .WithMtlsProofOfPossession() // Enables MTLS PoP .ExecuteAsync()) @@ -126,7 +126,7 @@ public async Task MtlsPopWithoutCertificateWithClientAssertionAsync() Assert.AreEqual(MsalError.MtlsCertificateNotProvided, ex.ErrorCode); } - [DataTestMethod] + [TestMethod] [DataRow(false)] [DataRow(true)] public async Task MtlsPop_WithoutRegion_ThrowsException(bool setAzureRegion) @@ -525,7 +525,7 @@ public async Task MtlsPop_ThrowsExceptionWhenRegionAutoDetectFailsAsync() .BuildConcrete(); // Expect an MsalServiceException due to missing region for MTLS POP - MsalServiceException ex = await Assert.ThrowsExceptionAsync(async () => + MsalServiceException ex = await Assert.ThrowsAsync(async () => await app.AcquireTokenForClient(TestConstants.s_scope) .WithMtlsProofOfPossession() .ExecuteAsync() @@ -539,7 +539,6 @@ await app.AcquireTokenForClient(TestConstants.s_scope) } [TestMethod] - [DataTestMethod] [DataRow("https://contoso.b2clogin.com/tfp/contoso.onmicrosoft.com/B2C_1_signupsignin", "B2C Authority", typeof(MsalServiceException))] [DataRow("https://contoso.adfs.contoso.com/adfs", "ADFS Authority", typeof(HttpRequestException))] public async Task MtlsPop_NonAadAuthorityAsync(string authorityUrl, string authorityType, Type expectedException) @@ -565,7 +564,7 @@ await app } } - [DataTestMethod] + [TestMethod] [DataRow("https://login.microsoftonline.com", TestConstants.Common, "Public Cloud")] [DataRow("https://login.microsoftonline.com", TestConstants.Organizations, "Public Cloud")] [DataRow("https://login.microsoftonline.us", TestConstants.Common, "Azure Government")] @@ -590,7 +589,7 @@ public async Task MtlsPop_WithUnsupportedNonTenantedAuthorityAsync_ThrowsExcepti .BuildConcrete(); // Expect an exception due to using /common or /organizations with MTLS PoP - MsalClientException ex = await Assert.ThrowsExceptionAsync(async () => + MsalClientException ex = await Assert.ThrowsAsync(async () => await app.AcquireTokenForClient(TestConstants.s_scope) .WithMtlsProofOfPossession() .ExecuteAsync() @@ -658,7 +657,7 @@ public async Task MtlsPop_ValidateExpectedUrlAsync() } } - [DataTestMethod] + [TestMethod] [DataRow("login.microsoftonline.com", "mtlsauth.microsoft.com")] [DataRow("login.microsoftonline.us", "mtlsauth.microsoftonline.us")] [DataRow("login.usgovcloudapi.net", "mtlsauth.microsoftonline.us")] @@ -716,7 +715,7 @@ public async Task PublicAndSovereignCloud_UsesPreferredNetwork_AndNoDiscovery_As Assert.AreEqual(EastUsRegion, result.ApiEvent.RegionUsed); Assert.AreEqual(EastUsRegion, result.AuthenticationResultMetadata.RegionDetails.RegionUsed); Assert.AreEqual(RegionOutcome.AutodetectSuccess, result.AuthenticationResultMetadata.RegionDetails.RegionOutcome); - Assert.AreEqual(null, result.AuthenticationResultMetadata.RegionDetails.AutoDetectionError); + Assert.IsNull(result.AuthenticationResultMetadata.RegionDetails.AutoDetectionError); } } } @@ -810,7 +809,7 @@ public async Task AcquireTokenForClient_WithMtlsPop_Dsts_SuccessAsync() Assert.AreEqual("header.payload.signature", result.AccessToken); Assert.AreEqual(Constants.MtlsPoPAuthHeaderPrefix, result.TokenType); - Assert.AreEqual(null, result.AuthenticationResultMetadata.RegionDetails.RegionUsed); + Assert.IsNull(result.AuthenticationResultMetadata.RegionDetails.RegionUsed); Assert.AreEqual(expectedTokenEndpoint, result.AuthenticationResultMetadata.TokenEndpoint); // Second token acquisition - should retrieve from cache @@ -825,7 +824,7 @@ public async Task AcquireTokenForClient_WithMtlsPop_Dsts_SuccessAsync() } } - [DataTestMethod] + [TestMethod] [DataRow(TestConstants.DstsAuthorityCommon)] [DataRow(TestConstants.DstsAuthorityOrganizations)] public async Task MtlsPop_WithUnsupportedNonTenantedAuthorityAsyncForDsts_ThrowsException(string authorityUrl) diff --git a/tests/Microsoft.Identity.Test.Unit/PublicApiTests/PublicClientApplicationTests.cs b/tests/Microsoft.Identity.Test.Unit/PublicApiTests/PublicClientApplicationTests.cs index e152def6a5..ae3f44539a 100644 --- a/tests/Microsoft.Identity.Test.Unit/PublicApiTests/PublicClientApplicationTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/PublicApiTests/PublicClientApplicationTests.cs @@ -356,7 +356,7 @@ public void AcquireTokenWithDefaultRedirectURITest() #if NETFRAMEWORK Assert.AreEqual(Constants.NativeClientRedirectUri, app.AppConfig.RedirectUri); #else - Assert.AreEqual(app.AppConfig.RedirectUri, "http://localhost"); + Assert.AreEqual("http://localhost", app.AppConfig.RedirectUri); #endif } @@ -492,7 +492,7 @@ public void AcquireTokenDifferentUserReturnedFromServiceTest() }); //Silent flow should fail when different account is returned. - var exception = Assert.ThrowsException(() => + var exception = Assert.Throws(() => result = app .AcquireTokenSilent(TestConstants.s_scope, result.Account) .WithForceRefresh(true) @@ -506,7 +506,7 @@ public void AcquireTokenDifferentUserReturnedFromServiceTest() var users = app.GetAccountsAsync().Result; Assert.AreEqual(2, users.Count()); - Assert.AreEqual(2, app.UserTokenCacheInternal.Accessor.GetAllAccessTokens().Count); + Assert.HasCount(2, app.UserTokenCacheInternal.Accessor.GetAllAccessTokens()); } } @@ -566,7 +566,7 @@ public void AcquireTokenNullUserPassedInAndNewUserReturnedFromServiceTest() Assert.AreEqual(TestConstants.DisplayableId, result.Account.Username); var users = app.GetAccountsAsync().Result; Assert.AreEqual(2, users.Count()); - Assert.AreEqual(2, app.UserTokenCacheInternal.Accessor.GetAllAccessTokens().Count); + Assert.HasCount(2, app.UserTokenCacheInternal.Accessor.GetAllAccessTokens()); } } @@ -915,7 +915,7 @@ private void AssertWamIds(Account account, int count, string wamId = null) else { Assert.IsNotNull(account.WamAccountIds); - Assert.AreEqual(1, account.WamAccountIds.Count); + Assert.HasCount(1, account.WamAccountIds); Assert.AreEqual(wamId, account.WamAccountIds["1d18b3b0-251b-4714-a02a-9956cec86c2d"]); } } @@ -934,10 +934,10 @@ private void AssertTenantProfiles(IEnumerable tenantProfiles, str Assert.IsFalse(tenantProfile2.IsHomeTenant); Assert.IsNotNull(tenantProfile1.ClaimsPrincipal); - Assert.IsTrue(tenantProfile1.ClaimsPrincipal.Claims.Count() > 0); + Assert.IsGreaterThan(0, tenantProfile1.ClaimsPrincipal.Claims.Count()); Assert.IsNotNull(tenantProfile2.ClaimsPrincipal); - Assert.IsTrue(tenantProfile2.ClaimsPrincipal.Claims.Count() > 0); + Assert.IsGreaterThan(0, tenantProfile2.ClaimsPrincipal.Claims.Count()); } /// @@ -1134,7 +1134,7 @@ public void AcquireTokenFromAdfsWithNoLoginHintWithAccountInCacheTest() Assert.AreEqual(TestConstants.OnPremiseUniqueId, result2.UniqueId); Assert.AreEqual(new AccountId(TestConstants.OnPremiseUniqueId), result2.Account.HomeAccountId); Assert.AreEqual(TestConstants.OnPremiseDisplayableId, result2.Account.Username); - Assert.AreEqual(app.UserTokenCacheInternal.Semaphore.CurrentCount, 1); + Assert.AreEqual(1, app.UserTokenCacheInternal.Semaphore.CurrentCount); } } diff --git a/tests/Microsoft.Identity.Test.Unit/PublicApiTests/RefreshInTests.cs b/tests/Microsoft.Identity.Test.Unit/PublicApiTests/RefreshInTests.cs index 2bb77dced0..58f8518bc1 100644 --- a/tests/Microsoft.Identity.Test.Unit/PublicApiTests/RefreshInTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/PublicApiTests/RefreshInTests.cs @@ -56,7 +56,7 @@ public async Task ATS_NonExpired_NeedsRefresh_ValidResponse_Async() // Assert token is proactively refreshed Assert.IsNotNull(result); - Assert.IsTrue(result.AuthenticationResultMetadata.CacheRefreshReason == CacheRefreshReason.ProactivelyRefreshed); + Assert.AreEqual(CacheRefreshReason.ProactivelyRefreshed, result.AuthenticationResultMetadata.CacheRefreshReason); Assert.IsTrue(result.AuthenticationResultMetadata.RefreshOn == refreshOn); // The following can be indeterministic due to background threading nature @@ -80,7 +80,7 @@ public async Task ATS_NonExpired_NeedsRefresh_ValidResponse_Async() .ConfigureAwait(false); Assert.IsNotNull(result); Assert.IsTrue(result.AuthenticationResultMetadata.RefreshOn == ati.RefreshOn); - Assert.IsTrue(result.AuthenticationResultMetadata.CacheRefreshReason == CacheRefreshReason.NotApplicable); + Assert.AreEqual(CacheRefreshReason.NotApplicable, result.AuthenticationResultMetadata.CacheRefreshReason); cacheAccess.WaitTo_AssertAcessCounts(2, 1); } @@ -254,7 +254,7 @@ public void JitterIsAddedToRefreshOn() refreshOnWithJitter.Value, TimeSpan.FromSeconds(Constants.DefaultJitterRangeInSeconds)); } - Assert.IsTrue(refreshOnWithJitterList.Distinct().Count() >= 8, "Jitter is random, so we can only have 1-2 identical values"); + Assert.IsGreaterThanOrEqualTo(8, refreshOnWithJitterList.Distinct().Count(), "Jitter is random, so we can only have 1-2 identical values"); } [TestMethod] @@ -329,14 +329,14 @@ public async Task ClientCredentials_NonExpired_NeedsRefresh_ValidResponse_Async( Assert.AreEqual(0, harness.HttpManager.QueueSize, "MSAL should have refreshed the token because the original AT was marked for refresh"); cacheAccess.WaitTo_AssertAcessCounts(1, 1); - Assert.IsTrue(result.AuthenticationResultMetadata.CacheRefreshReason == CacheRefreshReason.ProactivelyRefreshed); + Assert.AreEqual(CacheRefreshReason.ProactivelyRefreshed, result.AuthenticationResultMetadata.CacheRefreshReason); Assert.IsTrue(result.AuthenticationResultMetadata.RefreshOn == refreshOn); result = await app.AcquireTokenForClient(TestConstants.s_scope) .ExecuteAsync() .ConfigureAwait(false); - Assert.IsTrue(result.AuthenticationResultMetadata.CacheRefreshReason == CacheRefreshReason.NotApplicable); + Assert.AreEqual(CacheRefreshReason.NotApplicable, result.AuthenticationResultMetadata.CacheRefreshReason); } } @@ -369,13 +369,13 @@ public async Task ClientCredentials_OnBehalfOf_NonExpired_NeedsRefresh_ValidResp Assert.AreEqual(0, harness.HttpManager.QueueSize, "MSAL should have refreshed the token because the original AT was marked for refresh"); cacheAccess.WaitTo_AssertAcessCounts(1, 1); - Assert.IsTrue(result.AuthenticationResultMetadata.CacheRefreshReason == CacheRefreshReason.ProactivelyRefreshed); + Assert.AreEqual(CacheRefreshReason.ProactivelyRefreshed, result.AuthenticationResultMetadata.CacheRefreshReason); Assert.IsTrue(result.AuthenticationResultMetadata.RefreshOn == refreshOn); result = await app.AcquireTokenOnBehalfOf(TestConstants.s_scope, new UserAssertion(TestConstants.UserAssertion, "assertiontype")) .ExecuteAsync() .ConfigureAwait(false); - Assert.IsTrue(result.AuthenticationResultMetadata.CacheRefreshReason == CacheRefreshReason.NotApplicable); + Assert.AreEqual(CacheRefreshReason.NotApplicable, result.AuthenticationResultMetadata.CacheRefreshReason); } } diff --git a/tests/Microsoft.Identity.Test.Unit/PublicApiTests/TenantIdTests.cs b/tests/Microsoft.Identity.Test.Unit/PublicApiTests/TenantIdTests.cs index e750c01e7d..f65af09307 100644 --- a/tests/Microsoft.Identity.Test.Unit/PublicApiTests/TenantIdTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/PublicApiTests/TenantIdTests.cs @@ -12,7 +12,7 @@ namespace Microsoft.Identity.Test.Unit.PublicApiTests [TestClass] public class TenantIdTests : TestBase { - [DataTestMethod] + [TestMethod] [DataRow(TestConstants.AuthorityCommonTenant, TestConstants.Common, DisplayName = "Common endpoint")] [DataRow(TestConstants.AuthorityNotKnownCommon, TestConstants.Common, DisplayName = "Common endpoint")] [DataRow(TestConstants.AuthorityHomeTenant, "home", DisplayName = "Home endpoint")] @@ -41,14 +41,14 @@ public void ParseTest_Success(string authorityUrl, string expectedTenantId) Assert.AreEqual(expectedTenantId, tenantId); } - [DataTestMethod] + [TestMethod] [DynamicData(nameof(TestData.GetAuthorityWithExpectedTenantId), typeof(TestData), DynamicDataSourceType.Method)] public void ParseTestDynamic_Success(Uri authorityUrl, string expectedTenantId) { ParseTest_Success(authorityUrl.ToString(), expectedTenantId); } - [DataTestMethod] + [TestMethod] [DataRow(TestConstants.ADFSAuthority, DisplayName = "ADFS Authority")] [DataRow(TestConstants.ADFSAuthority2, DisplayName = "ADFS Authority")] public void ParseTest_NoTenantId(string authorityUrl) diff --git a/tests/Microsoft.Identity.Test.Unit/RequestsTests/DeviceCodeRequestTests.cs b/tests/Microsoft.Identity.Test.Unit/RequestsTests/DeviceCodeRequestTests.cs index 6c8aadc761..c55b066d4b 100644 --- a/tests/Microsoft.Identity.Test.Unit/RequestsTests/DeviceCodeRequestTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/RequestsTests/DeviceCodeRequestTests.cs @@ -290,17 +290,17 @@ public async Task VerifyAuthorizationPendingErrorDoesNotLogError_Async() await request.RunAsync(CancellationToken.None).ConfigureAwait(false); // Ensure we got logs so the log callback is working. - Assert.IsTrue(logCallbacks.Count > 0, "There should be data in logCallbacks"); + Assert.IsNotEmpty(logCallbacks, "There should be data in logCallbacks"); // Ensure we have authorization_pending data in the logs List<_LogData> authPendingLogs = logCallbacks.Where(x => x.Message.Contains(OAuth2Error.AuthorizationPending)).ToList(); - Assert.AreEqual(2, authPendingLogs.Count, "authorization_pending logs should exist"); + Assert.HasCount(2, authPendingLogs, "authorization_pending logs should exist"); // Ensure the authorization_pending logs are Info level and not Error - Assert.AreEqual( + Assert.HasCount( 2, - authPendingLogs.Where(x => x.Level == LogLevel.Info).ToList().Count, + authPendingLogs.Where(x => x.Level == LogLevel.Info).ToList(), "authorization_pending logs should be INFO"); // Ensure we don't have Error level logs in this scenario. diff --git a/tests/Microsoft.Identity.Test.Unit/RequestsTests/FociTests.cs b/tests/Microsoft.Identity.Test.Unit/RequestsTests/FociTests.cs index 3b927d9913..f8f85bcca6 100644 --- a/tests/Microsoft.Identity.Test.Unit/RequestsTests/FociTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/RequestsTests/FociTests.cs @@ -63,7 +63,7 @@ public async Task FociHappyPathAsync() await AssertAccountsAsync().ConfigureAwait(false); // Make sure smth reloads the cache before using the Accessor from the other app (GetAccounts will) - Assert.AreEqual(2, _appA.UserTokenCacheInternal.Accessor.GetAllAppMetadata().Count); + Assert.HasCount(2, _appA.UserTokenCacheInternal.Accessor.GetAllAppMetadata()); Assert.IsTrue(_appA.UserTokenCacheInternal.Accessor.GetAllAppMetadata().All(am => am.FamilyId == "1")); Assert.AreEqual("1", _appA.UserTokenCacheInternal.Accessor.GetAllRefreshTokens().Single().FamilyId); } diff --git a/tests/Microsoft.Identity.Test.Unit/RequestsTests/IntegratedWindowsAuthUsernamePasswordTests.cs b/tests/Microsoft.Identity.Test.Unit/RequestsTests/IntegratedWindowsAuthUsernamePasswordTests.cs index a0d36cb412..0ef9a4fe69 100644 --- a/tests/Microsoft.Identity.Test.Unit/RequestsTests/IntegratedWindowsAuthUsernamePasswordTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/RequestsTests/IntegratedWindowsAuthUsernamePasswordTests.cs @@ -191,7 +191,7 @@ public async Task AcquireTokenByIntegratedWindowsAuthTest_ManagedUserAsync() } [TestMethod] - public async Task AcquireTokenByIntegratedWindowsAuthTest_ManagedUser_DiscoveryFailed_ThrowsExceptionAsync() + public async Task AcquireTokenByIntegratedWindowsAuthTest_ManagedUser_DiscoveryFailed_ThrowsAsync() { // Arrange using (var httpManager = new MockHttpManager()) @@ -790,7 +790,7 @@ public async Task ManagedUsernameIncorrectPasswordAcquireTokenTestAsync() // Call acquire token #pragma warning disable CS0618 // Type or member is obsolete - MsalUiRequiredException result = await Assert.ThrowsExceptionAsync( + MsalUiRequiredException result = await Assert.ThrowsAsync( () => app.AcquireTokenByUsernamePassword( TestConstants.s_scope, TestConstants.s_user.Username, @@ -843,7 +843,7 @@ public async Task UsernamePasswordInvalidClientTestAsync() // Call acquire token #pragma warning disable CS0618 // Type or member is obsolete - MsalServiceException result = await Assert.ThrowsExceptionAsync( + MsalServiceException result = await Assert.ThrowsAsync( () => app.AcquireTokenByUsernamePassword( TestConstants.s_scope, TestConstants.s_user.Username, diff --git a/tests/Microsoft.Identity.Test.Unit/RequestsTests/InteractiveRequestOrchestrationTests.cs b/tests/Microsoft.Identity.Test.Unit/RequestsTests/InteractiveRequestOrchestrationTests.cs index b3415b3b4e..31396c411c 100644 --- a/tests/Microsoft.Identity.Test.Unit/RequestsTests/InteractiveRequestOrchestrationTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/RequestsTests/InteractiveRequestOrchestrationTests.cs @@ -80,7 +80,7 @@ public async Task NoBroker_WebUiOnly_Async() Assert.IsNotNull(result); Assert.AreEqual(TokenSource.IdentityProvider, result.AuthenticationResultMetadata.TokenSource); Assert.IsTrue(!string.IsNullOrEmpty(result.AccessToken)); - Assert.AreEqual(1, cache.Accessor.GetAllAccessTokens().Count); + Assert.HasCount(1, cache.Accessor.GetAllAccessTokens()); // Assert - orchestration Received.InOrder(() => @@ -205,7 +205,7 @@ public async Task Broker_Configured_But_Not_Installed_Async() // Assert - common stuff Assert.IsNotNull(result); Assert.IsTrue(!string.IsNullOrEmpty(result.AccessToken)); - Assert.AreEqual(1, cache.Accessor.GetAllAccessTokens().Count); + Assert.HasCount(1, cache.Accessor.GetAllAccessTokens()); // Assert - orchestration @@ -269,7 +269,7 @@ public async Task Broker_Not_Configured_But_Installed_EvoWantsBroker_Async() // Assert - common stuff Assert.IsNotNull(result); Assert.IsTrue(!string.IsNullOrEmpty(result.AccessToken)); - Assert.AreEqual(1, cache.Accessor.GetAllAccessTokens().Count); + Assert.HasCount(1, cache.Accessor.GetAllAccessTokens()); // Assert - orchestration Received.InOrder(() => diff --git a/tests/Microsoft.Identity.Test.Unit/RequestsTests/InteractiveRequestTests.cs b/tests/Microsoft.Identity.Test.Unit/RequestsTests/InteractiveRequestTests.cs index 2da739a401..b4ae886a5c 100644 --- a/tests/Microsoft.Identity.Test.Unit/RequestsTests/InteractiveRequestTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/RequestsTests/InteractiveRequestTests.cs @@ -107,9 +107,9 @@ public async Task WithExtraQueryParamsAndClaimsAsync() AuthenticationResult result = await request.RunAsync().ConfigureAwait(false); Assert.IsNotNull(result); - Assert.AreEqual(1, ((ITokenCacheInternal)cache).Accessor.GetAllRefreshTokens().Count); - Assert.AreEqual(1, ((ITokenCacheInternal)cache).Accessor.GetAllAccessTokens().Count); - Assert.AreEqual(result.AccessToken, "some-access-token"); + Assert.HasCount(1, ((ITokenCacheInternal)cache).Accessor.GetAllRefreshTokens()); + Assert.HasCount(1, ((ITokenCacheInternal)cache).Accessor.GetAllAccessTokens()); + Assert.AreEqual("some-access-token", result.AccessToken); } } @@ -170,9 +170,9 @@ public async Task NoCacheLookupAsync() AuthenticationResult result = await request.RunAsync().ConfigureAwait(false); - Assert.AreEqual(1, ((ITokenCacheInternal)cache).Accessor.GetAllRefreshTokens().Count); - Assert.AreEqual(2, ((ITokenCacheInternal)cache).Accessor.GetAllAccessTokens().Count); - Assert.AreEqual(result.AccessToken, "some-access-token"); + Assert.HasCount(1, ((ITokenCacheInternal)cache).Accessor.GetAllRefreshTokens()); + Assert.HasCount(2, ((ITokenCacheInternal)cache).Accessor.GetAllAccessTokens()); + Assert.AreEqual("some-access-token", result.AccessToken); } } @@ -205,7 +205,7 @@ public async Task RedirectUriContainsFragmentErrorTestAsync() var ex = await AssertException.TaskThrowsAsync (() => request.RunAsync()).ConfigureAwait(false); - Assert.IsTrue(ex.Message.Contains(MsalErrorMessage.RedirectUriContainsFragment)); + Assert.Contains(MsalErrorMessage.RedirectUriContainsFragment, ex.Message); } } @@ -344,7 +344,7 @@ public void DuplicateQueryParameterErrorTest() } } - [DataTestMethod] + [TestMethod] [DataRow(true)] [DataRow(false)] public async Task WithMultiCloudSupportEnabledAsync(bool multiCloudSupportEnabled) @@ -414,9 +414,9 @@ public async Task WithMultiCloudSupportEnabledAsync(bool multiCloudSupportEnable Assert.AreEqual("https://login.microsoftonline.us/home/oauth2/v2.0/token", result.AuthenticationResultMetadata.TokenEndpoint); else Assert.AreEqual("https://login.microsoftonline.com/home/oauth2/v2.0/token", result.AuthenticationResultMetadata.TokenEndpoint); - Assert.AreEqual(1, ((ITokenCacheInternal)cache).Accessor.GetAllRefreshTokens().Count); - Assert.AreEqual(1, ((ITokenCacheInternal)cache).Accessor.GetAllAccessTokens().Count); - Assert.AreEqual(result.AccessToken, "some-access-token"); + Assert.HasCount(1, ((ITokenCacheInternal)cache).Accessor.GetAllRefreshTokens()); + Assert.HasCount(1, ((ITokenCacheInternal)cache).Accessor.GetAllAccessTokens()); + Assert.AreEqual("some-access-token", result.AccessToken); } } diff --git a/tests/Microsoft.Identity.Test.Unit/RequestsTests/LongRunningOnBehalfOfTests.cs b/tests/Microsoft.Identity.Test.Unit/RequestsTests/LongRunningOnBehalfOfTests.cs index 670a5624de..2e856429f3 100644 --- a/tests/Microsoft.Identity.Test.Unit/RequestsTests/LongRunningOnBehalfOfTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/RequestsTests/LongRunningOnBehalfOfTests.cs @@ -223,7 +223,7 @@ public async Task InitiateLongRunningObo_CacheKeyAlreadyExists_TestAsync() .ConfigureAwait(false); Assert.AreEqual(TestConstants.ATSecret2, result.AccessToken); - Assert.AreEqual(result.AuthenticationResultMetadata.TokenSource, TokenSource.IdentityProvider); + Assert.AreEqual(TokenSource.IdentityProvider, result.AuthenticationResultMetadata.TokenSource); cachedAccessToken = cca.UserTokenCacheInternal.Accessor.GetAllAccessTokens().FirstOrDefault(at => at.Secret.Equals(TestConstants.ATSecret2)); cachedRefreshToken = cca.UserTokenCacheInternal.Accessor.GetAllRefreshTokens().FirstOrDefault(rt => rt.Secret.Equals(TestConstants.RTSecret2)); Assert.AreEqual(oboCacheKey, cachedAccessToken.OboCacheKey); @@ -414,8 +414,8 @@ public async Task NormalOboAndLongRunningObo_WithDifferentKeys_TestAsync() // Cache has 1 partition (user-provided key) with 1 token Assert.AreEqual(TokenSource.IdentityProvider, result.AuthenticationResultMetadata.TokenSource); - Assert.AreEqual(1, cca.UserTokenCacheInternal.Accessor.GetAllAccessTokens().Count); - Assert.AreEqual(1, cca.UserTokenCacheInternal.Accessor.GetAllRefreshTokens().Count); + Assert.HasCount(1, cca.UserTokenCacheInternal.Accessor.GetAllAccessTokens()); + Assert.HasCount(1, cca.UserTokenCacheInternal.Accessor.GetAllRefreshTokens()); MsalAccessTokenCacheItem cachedAccessToken = cca.UserTokenCacheInternal.Accessor.GetAllAccessTokens().First(t => t.OboCacheKey.Equals(oboCacheKey)); MsalRefreshTokenCacheItem cachedRefreshToken = cca.UserTokenCacheInternal.Accessor.GetAllRefreshTokens().First(t => t.OboCacheKey.Equals(oboCacheKey)); Assert.AreEqual("access-token-long-running", result.AccessToken); @@ -436,8 +436,8 @@ public async Task NormalOboAndLongRunningObo_WithDifferentKeys_TestAsync() // Cache has 2 partitions (user-provided key, assertion) with 1 token each Assert.AreEqual(TokenSource.IdentityProvider, result.AuthenticationResultMetadata.TokenSource); - Assert.AreEqual(2, cca.UserTokenCacheInternal.Accessor.GetAllAccessTokens().Count); - Assert.AreEqual(1, cca.UserTokenCacheInternal.Accessor.GetAllRefreshTokens().Count); + Assert.HasCount(2, cca.UserTokenCacheInternal.Accessor.GetAllAccessTokens()); + Assert.HasCount(1, cca.UserTokenCacheInternal.Accessor.GetAllRefreshTokens()); cachedAccessToken = cca.UserTokenCacheInternal.Accessor.GetAllAccessTokens().First(t => t.OboCacheKey.Equals(userAssertion.AssertionHash)); cachedRefreshToken = cca.UserTokenCacheInternal.Accessor.GetAllRefreshTokens().FirstOrDefault(t => t.OboCacheKey.Equals(userAssertion.AssertionHash)); Assert.AreEqual("access-token-normal", result.AccessToken); @@ -491,8 +491,8 @@ public async Task NormalOboAndLongRunningObo_WithTheSameKey_TestAsync() .ExecuteAsync().ConfigureAwait(false); Assert.AreEqual(TokenSource.IdentityProvider, result.AuthenticationResultMetadata.TokenSource); - Assert.AreEqual(1, cca.UserTokenCacheInternal.Accessor.GetAllAccessTokens().Count); - Assert.AreEqual(1, cca.UserTokenCacheInternal.Accessor.GetAllRefreshTokens().Count); + Assert.HasCount(1, cca.UserTokenCacheInternal.Accessor.GetAllAccessTokens()); + Assert.HasCount(1, cca.UserTokenCacheInternal.Accessor.GetAllRefreshTokens()); MsalAccessTokenCacheItem cachedAccessToken = cca.UserTokenCacheInternal.Accessor.GetAllAccessTokens().First(t => t.OboCacheKey.Equals(oboCacheKey)); MsalRefreshTokenCacheItem cachedRefreshToken = cca.UserTokenCacheInternal.Accessor.GetAllRefreshTokens().First(t => t.OboCacheKey.Equals(oboCacheKey)); Assert.AreEqual("access-token-1", result.AccessToken); @@ -529,8 +529,8 @@ public async Task NormalOboAndLongRunningObo_WithTheSameKey_TestAsync() .ExecuteAsync().ConfigureAwait(false); Assert.AreEqual(TokenSource.IdentityProvider, result.AuthenticationResultMetadata.TokenSource); - Assert.AreEqual(1, cca.UserTokenCacheInternal.Accessor.GetAllAccessTokens().Count); - Assert.AreEqual(1, cca.UserTokenCacheInternal.Accessor.GetAllRefreshTokens().Count); + Assert.HasCount(1, cca.UserTokenCacheInternal.Accessor.GetAllAccessTokens()); + Assert.HasCount(1, cca.UserTokenCacheInternal.Accessor.GetAllRefreshTokens()); cachedAccessToken = cca.UserTokenCacheInternal.Accessor.GetAllAccessTokens().First(t => t.OboCacheKey.Equals(oboCacheKey)); cachedRefreshToken = cca.UserTokenCacheInternal.Accessor.GetAllRefreshTokens().First(t => t.OboCacheKey.Equals(oboCacheKey)); Assert.AreEqual("access-token-2", result.AccessToken); @@ -554,8 +554,8 @@ public async Task NormalOboAndLongRunningObo_WithTheSameKey_TestAsync() result = await cca.AcquireTokenInLongRunningProcess(TestConstants.s_scope, oboCacheKey).ExecuteAsync().ConfigureAwait(false); Assert.AreEqual(TokenSource.IdentityProvider, result.AuthenticationResultMetadata.TokenSource); - Assert.AreEqual(1, cca.UserTokenCacheInternal.Accessor.GetAllAccessTokens().Count); - Assert.AreEqual(1, cca.UserTokenCacheInternal.Accessor.GetAllRefreshTokens().Count); + Assert.HasCount(1, cca.UserTokenCacheInternal.Accessor.GetAllAccessTokens()); + Assert.HasCount(1, cca.UserTokenCacheInternal.Accessor.GetAllRefreshTokens()); cachedAccessToken = cca.UserTokenCacheInternal.Accessor.GetAllAccessTokens().First(t => t.OboCacheKey.Equals(oboCacheKey)); cachedRefreshToken = cca.UserTokenCacheInternal.Accessor.GetAllRefreshTokens().First(t => t.OboCacheKey.Equals(oboCacheKey)); Assert.AreEqual("access-token-3", result.AccessToken); @@ -579,8 +579,8 @@ public async Task NormalOboAndLongRunningObo_WithTheSameKey_TestAsync() result = await cca.AcquireTokenOnBehalfOf(TestConstants.s_scope, userAssertion).ExecuteAsync().ConfigureAwait(false); Assert.AreEqual(TokenSource.IdentityProvider, result.AuthenticationResultMetadata.TokenSource); - Assert.AreEqual(1, cca.UserTokenCacheInternal.Accessor.GetAllAccessTokens().Count); - Assert.AreEqual(1, cca.UserTokenCacheInternal.Accessor.GetAllRefreshTokens().Count); + Assert.HasCount(1, cca.UserTokenCacheInternal.Accessor.GetAllAccessTokens()); + Assert.HasCount(1, cca.UserTokenCacheInternal.Accessor.GetAllRefreshTokens()); cachedAccessToken = cca.UserTokenCacheInternal.Accessor.GetAllAccessTokens().First(t => t.OboCacheKey.Equals(oboCacheKey)); cachedRefreshToken = cca.UserTokenCacheInternal.Accessor.GetAllRefreshTokens().First(t => t.OboCacheKey.Equals(oboCacheKey)); Assert.AreEqual("access-token-4", result.AccessToken); @@ -621,8 +621,8 @@ public async Task NormalOboThenLongRunningAcquire_WithTheSameKey_TestAsync() var result = await cca.AcquireTokenOnBehalfOf(TestConstants.s_scope, userAssertion).ExecuteAsync().ConfigureAwait(false); Assert.AreEqual(TokenSource.IdentityProvider, result.AuthenticationResultMetadata.TokenSource); - Assert.AreEqual(1, cca.UserTokenCacheInternal.Accessor.GetAllAccessTokens().Count); - Assert.AreEqual(0, cca.UserTokenCacheInternal.Accessor.GetAllRefreshTokens().Count); + Assert.HasCount(1, cca.UserTokenCacheInternal.Accessor.GetAllAccessTokens()); + Assert.IsEmpty(cca.UserTokenCacheInternal.Accessor.GetAllRefreshTokens()); MsalAccessTokenCacheItem cachedAccessToken = cca.UserTokenCacheInternal.Accessor.GetAllAccessTokens().First(t => t.OboCacheKey.Equals(oboCacheKey)); MsalRefreshTokenCacheItem cachedRefreshToken = cca.UserTokenCacheInternal.Accessor.GetAllRefreshTokens().FirstOrDefault(t => t.OboCacheKey.Equals(oboCacheKey)); Assert.AreEqual("access-token-1", result.AccessToken); @@ -663,8 +663,8 @@ public async Task NormalOboThenLongRunningAcquire_WithTheSameKey_TestAsync() .ExecuteAsync().ConfigureAwait(false); Assert.AreEqual(TokenSource.IdentityProvider, result.AuthenticationResultMetadata.TokenSource); - Assert.AreEqual(1, cca.UserTokenCacheInternal.Accessor.GetAllAccessTokens().Count); - Assert.AreEqual(1, cca.UserTokenCacheInternal.Accessor.GetAllRefreshTokens().Count); + Assert.HasCount(1, cca.UserTokenCacheInternal.Accessor.GetAllAccessTokens()); + Assert.HasCount(1, cca.UserTokenCacheInternal.Accessor.GetAllRefreshTokens()); cachedAccessToken = cca.UserTokenCacheInternal.Accessor.GetAllAccessTokens().First(t => t.OboCacheKey.Equals(oboCacheKey)); cachedRefreshToken = cca.UserTokenCacheInternal.Accessor.GetAllRefreshTokens().First(t => t.OboCacheKey.Equals(oboCacheKey)); Assert.AreEqual("access-token-2", result.AccessToken); @@ -688,8 +688,8 @@ public async Task NormalOboThenLongRunningAcquire_WithTheSameKey_TestAsync() result = await cca.AcquireTokenInLongRunningProcess(TestConstants.s_scope, oboCacheKey).ExecuteAsync().ConfigureAwait(false); Assert.AreEqual(TokenSource.IdentityProvider, result.AuthenticationResultMetadata.TokenSource); - Assert.AreEqual(1, cca.UserTokenCacheInternal.Accessor.GetAllAccessTokens().Count); - Assert.AreEqual(1, cca.UserTokenCacheInternal.Accessor.GetAllRefreshTokens().Count); + Assert.HasCount(1, cca.UserTokenCacheInternal.Accessor.GetAllAccessTokens()); + Assert.HasCount(1, cca.UserTokenCacheInternal.Accessor.GetAllRefreshTokens()); cachedAccessToken = cca.UserTokenCacheInternal.Accessor.GetAllAccessTokens().First(t => t.OboCacheKey.Equals(oboCacheKey)); cachedRefreshToken = cca.UserTokenCacheInternal.Accessor.GetAllRefreshTokens().First(t => t.OboCacheKey.Equals(oboCacheKey)); Assert.AreEqual("access-token-3", result.AccessToken); @@ -730,8 +730,8 @@ public async Task NormalOboThenLongRunningInitiate_WithTheSameKey_TestAsync() var result = await cca.AcquireTokenOnBehalfOf(TestConstants.s_scope, userAssertion).ExecuteAsync().ConfigureAwait(false); Assert.AreEqual(TokenSource.IdentityProvider, result.AuthenticationResultMetadata.TokenSource); - Assert.AreEqual(1, cca.UserTokenCacheInternal.Accessor.GetAllAccessTokens().Count); - Assert.AreEqual(0, cca.UserTokenCacheInternal.Accessor.GetAllRefreshTokens().Count); + Assert.HasCount(1, cca.UserTokenCacheInternal.Accessor.GetAllAccessTokens()); + Assert.IsEmpty(cca.UserTokenCacheInternal.Accessor.GetAllRefreshTokens()); MsalAccessTokenCacheItem cachedAccessToken = cca.UserTokenCacheInternal.Accessor.GetAllAccessTokens().First(t => t.OboCacheKey.Equals(oboCacheKey)); MsalRefreshTokenCacheItem cachedRefreshToken = cca.UserTokenCacheInternal.Accessor.GetAllRefreshTokens().FirstOrDefault(t => t.OboCacheKey.Equals(oboCacheKey)); Assert.AreEqual("access-token-1", result.AccessToken); @@ -772,8 +772,8 @@ public async Task NormalOboThenLongRunningInitiate_WithTheSameKey_TestAsync() .ExecuteAsync().ConfigureAwait(false); Assert.AreEqual(TokenSource.IdentityProvider, result.AuthenticationResultMetadata.TokenSource); - Assert.AreEqual(1, cca.UserTokenCacheInternal.Accessor.GetAllAccessTokens().Count); - Assert.AreEqual(1, cca.UserTokenCacheInternal.Accessor.GetAllRefreshTokens().Count); + Assert.HasCount(1, cca.UserTokenCacheInternal.Accessor.GetAllAccessTokens()); + Assert.HasCount(1, cca.UserTokenCacheInternal.Accessor.GetAllRefreshTokens()); cachedAccessToken = cca.UserTokenCacheInternal.Accessor.GetAllAccessTokens().First(t => t.OboCacheKey.Equals(oboCacheKey)); cachedRefreshToken = cca.UserTokenCacheInternal.Accessor.GetAllRefreshTokens().First(t => t.OboCacheKey.Equals(oboCacheKey)); Assert.AreEqual("access-token-2", result.AccessToken); @@ -797,8 +797,8 @@ public async Task NormalOboThenLongRunningInitiate_WithTheSameKey_TestAsync() result = await cca.AcquireTokenInLongRunningProcess(TestConstants.s_scope, oboCacheKey).ExecuteAsync().ConfigureAwait(false); Assert.AreEqual(TokenSource.IdentityProvider, result.AuthenticationResultMetadata.TokenSource); - Assert.AreEqual(1, cca.UserTokenCacheInternal.Accessor.GetAllAccessTokens().Count); - Assert.AreEqual(1, cca.UserTokenCacheInternal.Accessor.GetAllRefreshTokens().Count); + Assert.HasCount(1, cca.UserTokenCacheInternal.Accessor.GetAllAccessTokens()); + Assert.HasCount(1, cca.UserTokenCacheInternal.Accessor.GetAllRefreshTokens()); cachedAccessToken = cca.UserTokenCacheInternal.Accessor.GetAllAccessTokens().First(t => t.OboCacheKey.Equals(oboCacheKey)); cachedRefreshToken = cca.UserTokenCacheInternal.Accessor.GetAllRefreshTokens().First(t => t.OboCacheKey.Equals(oboCacheKey)); Assert.AreEqual("access-token-3", result.AccessToken); @@ -828,8 +828,8 @@ public async Task LongRunningThenRemoveTokens_TestAsync() { if (validateCacheProperties) { - Assert.AreEqual(true, args.HasTokens); - Assert.AreEqual(false, args.HasStateChanged); + Assert.IsTrue(args.HasTokens); + Assert.IsFalse(args.HasStateChanged); Assert.AreEqual(oboCacheKey, args.SuggestedCacheKey); } }); @@ -838,8 +838,8 @@ public async Task LongRunningThenRemoveTokens_TestAsync() { if (validateCacheProperties) { - Assert.AreEqual(true, args.HasStateChanged); - Assert.AreEqual(false, args.HasTokens); + Assert.IsTrue(args.HasStateChanged); + Assert.IsFalse(args.HasTokens); Assert.AreEqual(oboCacheKey, args.SuggestedCacheKey); } @@ -864,8 +864,8 @@ public async Task LongRunningThenRemoveTokens_TestAsync() .ExecuteAsync().ConfigureAwait(false); Assert.AreEqual(TokenSource.IdentityProvider, result.AuthenticationResultMetadata.TokenSource); - Assert.AreEqual(1, cca.UserTokenCacheInternal.Accessor.GetAllAccessTokens().Count); - Assert.AreEqual(1, cca.UserTokenCacheInternal.Accessor.GetAllRefreshTokens().Count); + Assert.HasCount(1, cca.UserTokenCacheInternal.Accessor.GetAllAccessTokens()); + Assert.HasCount(1, cca.UserTokenCacheInternal.Accessor.GetAllRefreshTokens()); MsalAccessTokenCacheItem cachedAccessToken = cca.UserTokenCacheInternal.Accessor.GetAllAccessTokens().Single(t => t.OboCacheKey.Equals(oboCacheKey)); MsalRefreshTokenCacheItem cachedRefreshToken = cca.UserTokenCacheInternal.Accessor.GetAllRefreshTokens().Single(t => t.OboCacheKey.Equals(oboCacheKey)); Assert.AreEqual("access-token-1", result.AccessToken); @@ -879,8 +879,8 @@ public async Task LongRunningThenRemoveTokens_TestAsync() var cachedAccessTokens = cca.UserTokenCacheInternal.Accessor.GetAllAccessTokens(); var cachedRefreshTokens = cca.UserTokenCacheInternal.Accessor.GetAllRefreshTokens(); - Assert.AreEqual(0, cachedAccessTokens.Count); - Assert.AreEqual(0, cachedRefreshTokens.Count); + Assert.IsEmpty(cachedAccessTokens); + Assert.IsEmpty(cachedRefreshTokens); Assert.IsTrue(tokensRemoved); //validate that no more tokens are removed @@ -889,8 +889,8 @@ public async Task LongRunningThenRemoveTokens_TestAsync() cachedAccessTokens = cca.UserTokenCacheInternal.Accessor.GetAllAccessTokens(); cachedRefreshTokens = cca.UserTokenCacheInternal.Accessor.GetAllRefreshTokens(); - Assert.AreEqual(0, cachedAccessTokens.Count); - Assert.AreEqual(0, cachedRefreshTokens.Count); + Assert.IsEmpty(cachedAccessTokens); + Assert.IsEmpty(cachedRefreshTokens); Assert.IsFalse(tokensRemoved); } } diff --git a/tests/Microsoft.Identity.Test.Unit/RequestsTests/OnBehalfOfTests.cs b/tests/Microsoft.Identity.Test.Unit/RequestsTests/OnBehalfOfTests.cs index 5e37287697..63712d3d5b 100644 --- a/tests/Microsoft.Identity.Test.Unit/RequestsTests/OnBehalfOfTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/RequestsTests/OnBehalfOfTests.cs @@ -131,7 +131,7 @@ public async Task MissMatchUserAssertions_TestAsync() result = await cca.AcquireTokenOnBehalfOf(TestConstants.s_scope, userAssertion).ExecuteAsync().ConfigureAwait(false); Assert.AreEqual(TestConstants.ATSecret, result.AccessToken); - Assert.AreEqual(result.AuthenticationResultMetadata.TokenSource, TokenSource.IdentityProvider); + Assert.AreEqual(TokenSource.IdentityProvider, result.AuthenticationResultMetadata.TokenSource); } } @@ -163,7 +163,7 @@ public async Task AccessTokenInCache_TestAsync() MsalAccessTokenCacheItem cachedAccessToken = cca.UserTokenCacheInternal.Accessor.GetAllAccessTokens().Single(); Assert.AreEqual(userAssertion.AssertionHash, cachedAccessToken.OboCacheKey); - Assert.AreEqual(0, cca.UserTokenCacheInternal.Accessor.GetAllRefreshTokens().Count); + Assert.IsEmpty(cca.UserTokenCacheInternal.Accessor.GetAllRefreshTokens()); } } @@ -238,13 +238,13 @@ public async Task ClaimsChallengeErrorHandling_TestAsync() UserAssertion userAssertion = new UserAssertion(TestConstants.DefaultAccessToken); //Throw exception with claims for OBO: - var ex = await Assert.ThrowsExceptionAsync(async () => + var ex = await Assert.ThrowsAsync(async () => { await cca.AcquireTokenOnBehalfOf(TestConstants.s_scope, userAssertion).ExecuteAsync().ConfigureAwait(false); }).ConfigureAwait(false); Assert.AreEqual(TestConstants.ClaimsChallenge, ex.Claims); - Assert.IsTrue(ex.Message.Contains(MsalErrorMessage.ClaimsChallenge)); + Assert.Contains(MsalErrorMessage.ClaimsChallenge, ex.Message); httpManager.AddMockHandler( new MockHttpMessageHandler @@ -254,13 +254,13 @@ public async Task ClaimsChallengeErrorHandling_TestAsync() }); //Throw exception with claims without OBO: - ex = await Assert.ThrowsExceptionAsync(async () => + ex = await Assert.ThrowsAsync(async () => { await cca.AcquireTokenForClient(TestConstants.s_scope).ExecuteAsync().ConfigureAwait(false); }).ConfigureAwait(false); Assert.AreEqual(TestConstants.ClaimsChallenge, ex.Claims); - Assert.IsTrue(ex.Message.Contains(MsalErrorMessage.ClaimsChallenge)); + Assert.Contains(MsalErrorMessage.ClaimsChallenge, ex.Message); } } diff --git a/tests/Microsoft.Identity.Test.Unit/TelemetryTests/HttpTelemetryTests.cs b/tests/Microsoft.Identity.Test.Unit/TelemetryTests/HttpTelemetryTests.cs index 2f8abee773..608aba7e6f 100644 --- a/tests/Microsoft.Identity.Test.Unit/TelemetryTests/HttpTelemetryTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/TelemetryTests/HttpTelemetryTests.cs @@ -234,7 +234,7 @@ public async Task TelemetryTestExceptionLogAsync() } } - [DataTestMethod] + [TestMethod] [DataRow(true)] [DataRow(false)] public async Task LegacyCacheEnabledTelemetryTestAsync(bool isLegacyCacheEnabled) @@ -738,10 +738,10 @@ private void AssertCurrentTelemetry( string[] telemetryCategories = requestMessage.Headers.GetValues( TelemetryConstants.XClientCurrentTelemetry).Single().Split('|'); - Assert.AreEqual(3, telemetryCategories.Length); - Assert.AreEqual(1, telemetryCategories[0].Split(',').Length); // version - Assert.AreEqual(5, telemetryCategories[1].Split(',').Length); // api_id, cache_info, region_used, region_source, region_outcome - Assert.AreEqual(5, telemetryCategories[2].Split(',').Length); // platform_fields + Assert.HasCount(3, telemetryCategories); + Assert.HasCount(1, telemetryCategories[0].Split(',')); // version + Assert.HasCount(5, telemetryCategories[1].Split(',')); // api_id, cache_info, region_used, region_source, region_outcome + Assert.HasCount(5, telemetryCategories[2].Split(',')); // platform_fields Assert.AreEqual(TelemetryConstants.HttpTelemetrySchemaVersion.ToString(), telemetryCategories[0]); // version diff --git a/tests/Microsoft.Identity.Test.Unit/TelemetryTests/MsalIdHelperTests.cs b/tests/Microsoft.Identity.Test.Unit/TelemetryTests/MsalIdHelperTests.cs index 92505ea86e..5d205e1338 100644 --- a/tests/Microsoft.Identity.Test.Unit/TelemetryTests/MsalIdHelperTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/TelemetryTests/MsalIdHelperTests.cs @@ -48,7 +48,7 @@ public async Task IdHelperAsync() private static void AssertHeaders(MockHttpMessageHandler headers, Guid correlationId) { Assert.IsTrue(!headers.ActualRequestMessage.Headers.GetValues("x-client-os").Single().Contains("6.2.9200")); - Assert.IsTrue(headers.ActualRequestMessage.Headers.GetValues("x-client-os").Single().Contains("Windows")); + Assert.Contains("Windows", headers.ActualRequestMessage.Headers.GetValues("x-client-os").Single()); Assert.AreEqual( typeof(PublicClientApplication).Assembly.GetName().Version.ToString(), headers.ActualRequestMessage.Headers.GetValues("x-client-Ver").Single()); diff --git a/tests/Microsoft.Identity.Test.Unit/TelemetryTests/OTelInstrumentationTests.cs b/tests/Microsoft.Identity.Test.Unit/TelemetryTests/OTelInstrumentationTests.cs index d9b0a1958a..131869ac44 100644 --- a/tests/Microsoft.Identity.Test.Unit/TelemetryTests/OTelInstrumentationTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/TelemetryTests/OTelInstrumentationTests.cs @@ -418,7 +418,7 @@ private void CreateApplication() private void VerifyMetrics(int expectedMetricCount, List exportedMetrics, long expectedSuccessfulRequests, long expectedFailedRequests) { - Assert.AreEqual(expectedMetricCount, exportedMetrics.Count, "Count of metrics recorded is not as expected."); + Assert.HasCount(expectedMetricCount, exportedMetrics, "Count of metrics recorded is not as expected."); foreach (Metric exportedItem in exportedMetrics) { diff --git a/tests/Microsoft.Identity.Test.Unit/TelemetryTests/RegionalTelemetryTests.cs b/tests/Microsoft.Identity.Test.Unit/TelemetryTests/RegionalTelemetryTests.cs index 69ae7e8134..f8137f1eb4 100644 --- a/tests/Microsoft.Identity.Test.Unit/TelemetryTests/RegionalTelemetryTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/TelemetryTests/RegionalTelemetryTests.cs @@ -356,10 +356,10 @@ private static void AssertCurrentTelemetry( string[] telemetryCategories = requestMessage.Headers.GetValues( TelemetryConstants.XClientCurrentTelemetry).Single().Split('|'); - Assert.AreEqual(3, telemetryCategories.Length); - Assert.AreEqual(1, telemetryCategories[0].Split(',').Length); // version - Assert.AreEqual(5, telemetryCategories[1].Split(',').Length); // api_id, cache_info, region_used, region_source, region_outcome - Assert.AreEqual(5, telemetryCategories[2].Split(',').Length); // platform_fields + Assert.HasCount(3, telemetryCategories); + Assert.HasCount(1, telemetryCategories[0].Split(',')); // version + Assert.HasCount(5, telemetryCategories[1].Split(',')); // api_id, cache_info, region_used, region_source, region_outcome + Assert.HasCount(5, telemetryCategories[2].Split(',')); // platform_fields Assert.AreEqual(TelemetryConstants.HttpTelemetrySchemaVersion.ToString(), telemetryCategories[0]); // version diff --git a/tests/Microsoft.Identity.Test.Unit/TestExtensions.cs b/tests/Microsoft.Identity.Test.Unit/TestExtensions.cs index 3ae2f39db1..be84583dde 100644 --- a/tests/Microsoft.Identity.Test.Unit/TestExtensions.cs +++ b/tests/Microsoft.Identity.Test.Unit/TestExtensions.cs @@ -23,11 +23,11 @@ internal static void AssertItemCount( int expectedAccountCount, int expectedAppMetadataCount = 0) { - Assert.AreEqual(expectedAtCount, accessor.GetAllAccessTokens().Count, "Access Tokens"); - Assert.AreEqual(expectedRtCount, accessor.GetAllRefreshTokens().Count, "Refresh Tokens"); - Assert.AreEqual(expectedIdtCount, accessor.GetAllIdTokens().Count, "Id Tokens"); - Assert.AreEqual(expectedAccountCount, accessor.GetAllAccounts().Count, "Accounts"); - Assert.AreEqual(expectedAppMetadataCount, accessor.GetAllAppMetadata().Count, "App Metadata"); + Assert.HasCount(expectedAtCount, accessor.GetAllAccessTokens(), "Access Tokens"); + Assert.HasCount(expectedRtCount, accessor.GetAllRefreshTokens(), "Refresh Tokens"); + Assert.HasCount(expectedIdtCount, accessor.GetAllIdTokens(), "Id Tokens"); + Assert.HasCount(expectedAccountCount, accessor.GetAllAccounts(), "Accounts"); + Assert.HasCount(expectedAppMetadataCount, accessor.GetAllAppMetadata(), "App Metadata"); } public static void InitializeTokenCacheFromFile(this IClientApplicationBase app, string resourceFile, bool updateATExpiry = false) diff --git a/tests/Microsoft.Identity.Test.Unit/Throttling/ThrottlingAcceptanceTests.cs b/tests/Microsoft.Identity.Test.Unit/Throttling/ThrottlingAcceptanceTests.cs index 009cbeccdc..4ccb89921e 100644 --- a/tests/Microsoft.Identity.Test.Unit/Throttling/ThrottlingAcceptanceTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/Throttling/ThrottlingAcceptanceTests.cs @@ -161,7 +161,7 @@ public async Task RetryAfter_LargeTimeoutHeader_DefaultTimeout_IsUsed_Async() var (retryAfterProvider, _, _) = throttlingManager.GetTypedThrottlingProviders(); var singleEntry = retryAfterProvider.ThrottlingCache.CacheForTest.Single().Value; TimeSpan actualExpiration = singleEntry.ExpirationTime - singleEntry.CreationTime; - Assert.AreEqual(actualExpiration, RetryAfterProvider.MaxRetryAfter); + Assert.AreEqual(RetryAfterProvider.MaxRetryAfter, actualExpiration); } } @@ -222,10 +222,10 @@ public async Task RetryAfter_ConfidentialClient_ErrorMessage_Async() () => app.AcquireTokenForClient(TestConstants.s_scope).ExecuteAsync()) .ConfigureAwait(false); - Assert.AreEqual(serverEx.StatusCode, 429); - Assert.AreEqual(serverEx.ErrorCode, MsalError.RequestThrottled); - Assert.AreEqual(serverEx.Message, MsalErrorMessage.AadThrottledError); - Assert.AreEqual(serverEx.ResponseBody, MockHelpers.TooManyRequestsContent); + Assert.AreEqual(429, serverEx.StatusCode); + Assert.AreEqual(MsalError.RequestThrottled, serverEx.ErrorCode); + Assert.AreEqual(MsalErrorMessage.AadThrottledError, serverEx.Message); + Assert.AreEqual(MockHelpers.TooManyRequestsContent, serverEx.ResponseBody); } } #endregion @@ -417,7 +417,7 @@ await app.AcquireTokenSilent(TestConstants.s_scope, account).ExecuteAsync() [TestMethod] public async Task UiRequired_MultipleEntries_Async() { - Assert.AreEqual(2, TestConstants.s_scope.Count, "test error - expecting at least 2 scopes"); + Assert.HasCount(2, TestConstants.s_scope, "test error - expecting at least 2 scopes"); using (var httpManagerAndBundle = new MockHttpAndServiceBundle()) { @@ -526,9 +526,9 @@ private static void AssertThrottlingCacheEntryCount( var (retryAfterProvider, httpStatusProvider, uiRequiredProvider) = throttlingManager.GetTypedThrottlingProviders(); - Assert.AreEqual(retryAfterEntryCount, retryAfterProvider.ThrottlingCache.CacheForTest.Count); - Assert.AreEqual(httpStatusEntryCount, httpStatusProvider.ThrottlingCache.CacheForTest.Count); - Assert.AreEqual(uiRequiredEntryCount, uiRequiredProvider.ThrottlingCache.CacheForTest.Count); + Assert.HasCount(retryAfterEntryCount, retryAfterProvider.ThrottlingCache.CacheForTest); + Assert.HasCount(httpStatusEntryCount, httpStatusProvider.ThrottlingCache.CacheForTest); + Assert.HasCount(uiRequiredEntryCount, uiRequiredProvider.ThrottlingCache.CacheForTest); } private static void AssertInvalidClientEx(MsalServiceException ex) diff --git a/tests/Microsoft.Identity.Test.Unit/UtilTests/DateTimeHelperTests.cs b/tests/Microsoft.Identity.Test.Unit/UtilTests/DateTimeHelperTests.cs index d2fdc9cc3e..3027b146d6 100644 --- a/tests/Microsoft.Identity.Test.Unit/UtilTests/DateTimeHelperTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/UtilTests/DateTimeHelperTests.cs @@ -27,17 +27,17 @@ public void TestGetDurationFromNowInSecondsForUnixTimestampOnly() long currentUnixTimestamp = DateTimeHelpers.CurrDateTimeInUnixTimestamp(); // e.g., 1697490590 string unixTimestampString = currentUnixTimestamp.ToString(CultureInfo.InvariantCulture); long result = DateTimeHelpers.GetDurationFromNowInSeconds(unixTimestampString); - Assert.IsTrue(result >= 0, "Valid Unix timestamp (seconds) failed"); + Assert.IsGreaterThanOrEqualTo(0, result, "Valid Unix timestamp (seconds) failed"); // Example 2: Unix timestamp in the future string futureUnixTimestamp = (currentUnixTimestamp + 3600).ToString(); // 1 hour from now result = DateTimeHelpers.GetDurationFromNowInSeconds(futureUnixTimestamp); - Assert.IsTrue(result > 0, "Future Unix timestamp failed"); + Assert.IsGreaterThan(0, result, "Future Unix timestamp failed"); // Example 3: Unix timestamp in the past string pastUnixTimestamp = (currentUnixTimestamp - 3600).ToString(); // 1 hour ago result = DateTimeHelpers.GetDurationFromNowInSeconds(pastUnixTimestamp); - Assert.IsTrue(result < 0, "Past Unix timestamp failed"); + Assert.IsLessThan(0, result, "Past Unix timestamp failed"); // Example 4: Empty string (should return 0) string emptyString = string.Empty; @@ -54,26 +54,26 @@ public void TestGetDurationFromNowInSecondsFromManagedIdentity() // Example 1: Unix timestamp (seconds since epoch) string unixTimestampInSeconds = DateTimeHelpers.DateTimeToUnixTimestamp(currentTime); // e.g., 1697490590 long result = DateTimeHelpers.GetDurationFromManagedIdentityTimestamp(unixTimestampInSeconds); - Assert.IsTrue(result >= 0, "Unix timestamp (seconds) failed"); + Assert.IsGreaterThanOrEqualTo(0, result, "Unix timestamp (seconds) failed"); // Example 2: ISO 8601 format string iso8601 = currentTime.ToString("o", CultureInfo.InvariantCulture); // e.g., 2024-10-18T19:51:37.0000000+00:00 result = DateTimeHelpers.GetDurationFromManagedIdentityTimestamp(iso8601); - Assert.IsTrue(result >= 0, "ISO 8601 failed"); + Assert.IsGreaterThanOrEqualTo(0, result, "ISO 8601 failed"); // Example 3: Common format (MM/dd/yyyy HH:mm:ss) string commonFormat1 = currentTime.ToString("MM/dd/yyyy HH:mm:ss", CultureInfo.InvariantCulture); // e.g., 10/18/2024 19:51:37 result = DateTimeHelpers.GetDurationFromManagedIdentityTimestamp(commonFormat1); - Assert.IsTrue(result >= 0, "Common Format 1 failed"); + Assert.IsGreaterThanOrEqualTo(0, result, "Common Format 1 failed"); // Example 4: Common format (yyyy-MM-dd HH:mm:ss) string commonFormat2 = currentTime.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture); // e.g., 2024-10-18 19:51:37 result = DateTimeHelpers.GetDurationFromManagedIdentityTimestamp(commonFormat2); - Assert.IsTrue(result >= 0, "Common Format 2 failed"); + Assert.IsGreaterThanOrEqualTo(0, result, "Common Format 2 failed"); // Example 5: Invalid format (should throw an MsalClientException) string invalidFormat = "invalid-date-format"; - Assert.ThrowsException(() => + Assert.Throws(() => { DateTimeHelpers.GetDurationFromManagedIdentityTimestamp(invalidFormat); }, "Invalid format did not throw an exception as expected."); diff --git a/tests/Microsoft.Identity.Test.Unit/UtilTests/HttpHeaderSantizerTests.cs b/tests/Microsoft.Identity.Test.Unit/UtilTests/HttpHeaderSantizerTests.cs index 86b5bc30d3..18ce2fdc28 100644 --- a/tests/Microsoft.Identity.Test.Unit/UtilTests/HttpHeaderSantizerTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/UtilTests/HttpHeaderSantizerTests.cs @@ -29,7 +29,7 @@ public void SantizerAllowsStrangeErrorCodesToBeSentAsHeaders() HttpRequestMessage httpRequest = new HttpRequestMessage(); // newline chars must be followed by spaces - Assert.ThrowsException(() => httpRequest.Headers.Add("x-client-last-telemetry", strangeErrorCode)); + Assert.Throws(() => httpRequest.Headers.Add("x-client-last-telemetry", strangeErrorCode)); string santized = HttpHeaderSanitizer.SanitizeHeader(strangeErrorCode); httpRequest.Headers.Add("x-client-last-telemetry", santized); diff --git a/tests/Microsoft.Identity.Test.Unit/UtilTests/RetryOperationHelperTest.cs b/tests/Microsoft.Identity.Test.Unit/UtilTests/RetryOperationHelperTest.cs index e853a83987..8201f5d753 100644 --- a/tests/Microsoft.Identity.Test.Unit/UtilTests/RetryOperationHelperTest.cs +++ b/tests/Microsoft.Identity.Test.Unit/UtilTests/RetryOperationHelperTest.cs @@ -29,7 +29,7 @@ public void TestExecuteWithRetry_OperationSucceeds() var result = RetryOperationHelper.ExecuteWithRetryAsync(func, numberOfRetriesToAttempt).Result; //Assert - Assert.AreEqual(result, true); + Assert.IsTrue(result); } [TestMethod] @@ -46,7 +46,7 @@ public void TestExecuteWithRetry_OperationFails() Exception ex = AssertException.Throws( () => RetryOperationHelper.ExecuteWithRetryAsync(func, numberOfRetriesToAttempt).Wait()); - Assert.AreEqual(ex.InnerException.Message, "OperationSimulator: Simulating Operation Failure"); + Assert.AreEqual("OperationSimulator: Simulating Operation Failure", ex.InnerException.Message); } [TestMethod] @@ -65,7 +65,7 @@ public void TestExecuteWithRetry_OperationFails_VerifyOnFailureActionIsCalled() Exception ex = AssertException.Throws( () => RetryOperationHelper.ExecuteWithRetryAsync(func, numberOfRetriesToAttempt, retryTimeSpan, actionUponFailure).Wait()); - Assert.AreEqual(ex.InnerException.Message, "OperationSimulator: ThrowException: Exception thrown to identify method"); + Assert.AreEqual("OperationSimulator: ThrowException: Exception thrown to identify method", ex.InnerException.Message); } } diff --git a/tests/Microsoft.Identity.Test.Unit/UtilTests/StopWatchServiceTests.cs b/tests/Microsoft.Identity.Test.Unit/UtilTests/StopWatchServiceTests.cs index 66be747597..42818268c6 100644 --- a/tests/Microsoft.Identity.Test.Unit/UtilTests/StopWatchServiceTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/UtilTests/StopWatchServiceTests.cs @@ -15,12 +15,12 @@ public void MeasureCodeBlock() { MeasureDurationResult result = StopwatchService.MeasureCodeBlock(() => Thread.Sleep(50)); - Assert.IsTrue(result.Milliseconds >= 50, "Measured time is less than expected."); - Assert.IsTrue(result.Milliseconds < 100, "Measured time is too high."); + Assert.IsGreaterThanOrEqualTo(50, result.Milliseconds, "Measured time is less than expected."); + Assert.IsLessThan(100, result.Milliseconds, "Measured time is too high."); long diff = result.Microseconds - (result.Milliseconds * 1000); - Assert.IsTrue(diff >= -1000, "Microseconds is less than expected."); - Assert.IsTrue(diff < 1000, "Microseconds is too high."); + Assert.IsGreaterThanOrEqualTo(-1000, diff, "Microseconds is less than expected."); + Assert.IsLessThan(1000, diff, "Microseconds is too high."); } [TestMethod] @@ -31,12 +31,12 @@ public async Task MeasureCodeBlockAsync() await Task.Delay(50).ConfigureAwait(true); }).ConfigureAwait(true); - Assert.IsTrue(result.Milliseconds >= 50, "Measured time is less than expected."); - Assert.IsTrue(result.Milliseconds < 100, "Measured time is too high."); + Assert.IsGreaterThanOrEqualTo(50, result.Milliseconds, "Measured time is less than expected."); + Assert.IsLessThan(100, result.Milliseconds, "Measured time is too high."); long diff = result.Microseconds - (result.Milliseconds * 1000); - Assert.IsTrue(diff >= -1000, "Microseconds is less than expected."); - Assert.IsTrue(diff < 1000, "Microseconds is too high."); + Assert.IsGreaterThanOrEqualTo(-1000, diff, "Microseconds is less than expected."); + Assert.IsLessThan(1000, diff, "Microseconds is too high."); } [TestMethod] @@ -49,12 +49,12 @@ public async Task MeasureCodeBlockAsyncWithResult() }).ConfigureAwait(true); Assert.AreEqual(42, result.Result, "Result is not as expected."); - Assert.IsTrue(result.Milliseconds >= 50, "Measured time is less than expected."); - Assert.IsTrue(result.Milliseconds < 100, "Measured time is too high."); + Assert.IsGreaterThanOrEqualTo(50, result.Milliseconds, "Measured time is less than expected."); + Assert.IsLessThan(100, result.Milliseconds, "Measured time is too high."); long diff = result.Microseconds - (result.Milliseconds * 1000); - Assert.IsTrue(diff >= -1000, "Microseconds is less than expected."); - Assert.IsTrue(diff < 1000, "Microseconds is too high."); + Assert.IsGreaterThanOrEqualTo(-1000, diff, "Microseconds is less than expected."); + Assert.IsLessThan(1000, diff, "Microseconds is too high."); } } } diff --git a/tests/Microsoft.Identity.Test.Unit/UtilTests/UriBuilderExtensionsTests.cs b/tests/Microsoft.Identity.Test.Unit/UtilTests/UriBuilderExtensionsTests.cs index 9938d5d605..6c8c6b3419 100644 --- a/tests/Microsoft.Identity.Test.Unit/UtilTests/UriBuilderExtensionsTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/UtilTests/UriBuilderExtensionsTests.cs @@ -10,7 +10,7 @@ namespace Microsoft.Identity.Test.Unit.UtilTests [TestClass] public class UriBuilderExtensionsTests { - [DataTestMethod] + [TestMethod] [DataRow("https://microsoft.com/auth?scope=scope1", "response_mode", "form_post", "https://microsoft.com/auth?scope=scope1&response_mode=form_post")] [DataRow("https://microsoft.com/auth?response_mode=query&scope=scope1", "response_mode", "form_post", "https://microsoft.com/auth?response_mode=form_post&scope=scope1")] [DataRow("https://microsoft.com/auth?response_mode=form_post&scope=scope1", "response_mode", "form_post", "https://microsoft.com/auth?response_mode=form_post&scope=scope1")] diff --git a/tests/Microsoft.Identity.Test.Unit/WebUITests/DefaultOsBrowserWebUiTests.cs b/tests/Microsoft.Identity.Test.Unit/WebUITests/DefaultOsBrowserWebUiTests.cs index f65a75fe4c..6f4695e0ec 100644 --- a/tests/Microsoft.Identity.Test.Unit/WebUITests/DefaultOsBrowserWebUiTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/WebUITests/DefaultOsBrowserWebUiTests.cs @@ -303,13 +303,13 @@ private void ValidateResponse(SystemWebViewOptions options, bool successResponse // Assert if (expectedMessage != null) { - Assert.AreEqual(messageAndCode.HttpCode, HttpStatusCode.OK); + Assert.AreEqual(HttpStatusCode.OK, messageAndCode.HttpCode); Assert.IsTrue(messageAndCode.Message.Equals(expectedMessage, StringComparison.OrdinalIgnoreCase)); } if (expectedRedirect != null) { - Assert.AreEqual(messageAndCode.HttpCode, HttpStatusCode.Found); + Assert.AreEqual(HttpStatusCode.Found, messageAndCode.HttpCode); Assert.IsTrue(messageAndCode.Message.Equals(expectedRedirect, StringComparison.OrdinalIgnoreCase)); } } diff --git a/tests/Microsoft.Identity.Test.Unit/WwwAuthenticateParametersTests.cs b/tests/Microsoft.Identity.Test.Unit/WwwAuthenticateParametersTests.cs index 6e6963537b..30e823393f 100644 --- a/tests/Microsoft.Identity.Test.Unit/WwwAuthenticateParametersTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/WwwAuthenticateParametersTests.cs @@ -59,7 +59,7 @@ public void CreateWwwAuthenticateResponse(string resource, string authorizationU // Assert Assert.AreEqual(TestConstants.AuthorityCommonTenant.TrimEnd('/'), authParams.Authority); - Assert.AreEqual(3, authParams.RawParameters.Count); + Assert.HasCount(3, authParams.RawParameters); Assert.IsNull(authParams.Claims); Assert.IsNull(authParams.Error); } @@ -83,7 +83,7 @@ public void EnsureProperlyFormattedHeadersWithToken86DoNotFail(string scheme, st if (scheme == "AuthScheme1") { - Assert.AreEqual(0, authParams.RawParameters.Count); + Assert.IsEmpty(authParams.RawParameters); } else if (scheme == "AuthScheme2") { @@ -149,14 +149,14 @@ public void CreateWwwAuthenticateResponseForUnknownChallenges(string scheme, str } else if (scheme == "WLID1.0") { - Assert.AreEqual(3, authParams.RawParameters.Count); + Assert.HasCount(3, authParams.RawParameters); Assert.AreEqual("WindowsLive", authParams.RawParameters["realm"]); Assert.AreEqual("MBI_SSL", authParams.RawParameters["policy"]); Assert.AreEqual("ssl.live-tst.net", authParams.RawParameters["siteId"]); } else { - Assert.AreEqual(3, authParams.RawParameters.Count); + Assert.HasCount(3, authParams.RawParameters); Assert.AreEqual("WindowsLive", authParams.RawParameters["realm"]); Assert.AreEqual("MBI_SSL", authParams.RawParameters["policy"]); Assert.AreEqual("ssl.live-tst.net - ssl2.live-tst2.net", authParams.RawParameters["siteId"]); @@ -188,7 +188,7 @@ public void CreateFromMalformedAuthInfoResponse(string paramName, string value) httpResponse.Headers.Add(AuthenticationInfoName, $"{paramName}={value}"); // Act - var ex = Assert.ThrowsException(() => + var ex = Assert.Throws(() => AuthenticationInfoParameters.CreateFromResponseHeaders(httpResponse.Headers)); //Assert @@ -220,9 +220,9 @@ public void CreateRawParameters(string resourceHeaderKey, string authorizationUr Assert.IsTrue(authParams.RawParameters.ContainsKey(Realm)); Assert.AreEqual(string.Empty, authParams[Realm]); Assert.AreEqual(GraphGuid, authParams[resourceHeaderKey]); - Assert.ThrowsException( + Assert.Throws( () => authParams[ErrorKey]); - Assert.ThrowsException( + Assert.Throws( () => authParams[ClaimsKey]); } @@ -275,7 +275,7 @@ public void CreateWwwAuthenticateParamsFromWwwAuthenticateHeader(string clientId // Assert Assert.AreEqual(TestConstants.AuthorityCommonTenant.TrimEnd('/'), authParams.Authority); - Assert.AreEqual(3, authParams.RawParameters.Count); + Assert.HasCount(3, authParams.RawParameters); Assert.IsNull(authParams.Claims); Assert.IsNull(authParams.Error); } @@ -321,15 +321,15 @@ public async Task CreateFromResourceResponseAsync_HttpClient_B2C_GetTenantId_Asy var httpClient = new HttpClient(handler); var authParams = await WwwAuthenticateParameters.CreateFromResourceResponseAsync(httpClient, resourceUri).ConfigureAwait(false); - Assert.AreEqual(authParams.GetTenantId(), tenantId); + Assert.AreEqual(tenantId, authParams.GetTenantId()); authParams = await WwwAuthenticateParameters.CreateFromAuthenticationResponseAsync(resourceUri, "Bearer", httpClient, default).ConfigureAwait(false); - Assert.AreEqual(authParams.GetTenantId(), tenantId); + Assert.AreEqual(tenantId, authParams.GetTenantId()); var authParamList = await WwwAuthenticateParameters.CreateFromAuthenticationResponseAsync(resourceUri, httpClient, default).ConfigureAwait(false); - Assert.AreEqual(authParamList.FirstOrDefault().GetTenantId(), tenantId); + Assert.AreEqual(tenantId, authParamList.FirstOrDefault().GetTenantId()); } [TestMethod] @@ -368,15 +368,15 @@ public async Task CreateFromResourceResponseAsync_HttpClient_Null_Async() Func action = () => WwwAuthenticateParameters.CreateFromResourceResponseAsync(null, resourceUri); - await Assert.ThrowsExceptionAsync(action).ConfigureAwait(false); + await Assert.ThrowsAsync(action).ConfigureAwait(false); action = () => WwwAuthenticateParameters.CreateFromAuthenticationResponseAsync(resourceUri, "Bearer", null, default); - await Assert.ThrowsExceptionAsync(action).ConfigureAwait(false); + await Assert.ThrowsAsync(action).ConfigureAwait(false); action = () => WwwAuthenticateParameters.CreateFromAuthenticationResponseAsync(resourceUri, client, default); - await Assert.ThrowsExceptionAsync(action).ConfigureAwait(false); + await Assert.ThrowsAsync(action).ConfigureAwait(false); } [TestMethod] @@ -386,7 +386,7 @@ public async Task CreateFromResourceResponseAsync_Incorrect_ResourceUri_Async(st { Func action = () => WwwAuthenticateParameters.CreateFromResourceResponseAsync(resourceUri); - await Assert.ThrowsExceptionAsync(action).ConfigureAwait(false); + await Assert.ThrowsAsync(action).ConfigureAwait(false); } [TestMethod] @@ -577,7 +577,7 @@ public void ExtractAllAuthinfoParametersFromResponseWithAuthParser() // Assert Assert.IsNotNull(headers.AuthenticationInfoParameters); Assert.AreEqual(TestConstants.Nonce, headers.AuthenticationInfoParameters.NextNonce); - Assert.AreEqual(0, headers.WwwAuthenticateParameters.Count); + Assert.IsEmpty(headers.WwwAuthenticateParameters); } [TestMethod] diff --git a/tests/Microsoft.Identity.Test.Unit/pop/PopAuthenticationOperationTests.cs b/tests/Microsoft.Identity.Test.Unit/pop/PopAuthenticationOperationTests.cs index 221317a3ec..35a9e54869 100644 --- a/tests/Microsoft.Identity.Test.Unit/pop/PopAuthenticationOperationTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/pop/PopAuthenticationOperationTests.cs @@ -87,7 +87,7 @@ public async Task ValidatePopRequestAndToken() Assert.AreEqual("PoP", authenticationScheme.AuthorizationHeaderPrefix); Assert.AreEqual(TelemetryTokenTypeConstants.Pop, authenticationScheme.TelemetryTokenType); Assert.AreEqual(JWT, authenticationScheme.KeyId); - Assert.AreEqual(2, tokenParams.Count); + Assert.HasCount(2, tokenParams); Assert.AreEqual("pop", tokenParams["token_type"]); // This is the base64 URL encoding of the JWK containing only the KeyId @@ -158,7 +158,7 @@ public async Task ValidateKeyExpirationAsync() Assert.AreEqual(GetAccessTokenFromPopToken(result.AccessToken), GetAccessTokenFromPopToken(initialToken)); Assert.AreEqual(GetModulusFromPopToken(result.AccessToken), GetModulusFromPopToken(initialToken)); - Assert.IsTrue(result.AuthenticationResultMetadata.TokenSource == TokenSource.Cache); + Assert.AreEqual(TokenSource.Cache, result.AuthenticationResultMetadata.TokenSource); //Advance time 2 hours. Should be a different key testClock.MoveToFuture(TimeSpan.FromHours(2)); @@ -171,7 +171,7 @@ public async Task ValidateKeyExpirationAsync() Assert.AreNotEqual(GetModulusFromPopToken(result.AccessToken), GetModulusFromPopToken(initialToken)); Assert.AreNotEqual(GetAccessTokenFromPopToken(result.AccessToken), GetAccessTokenFromPopToken(initialToken)); - Assert.IsTrue(result.AuthenticationResultMetadata.TokenSource == TokenSource.IdentityProvider); + Assert.AreEqual(TokenSource.IdentityProvider, result.AuthenticationResultMetadata.TokenSource); } } From cc05ba3ac12855c46ab1c921b3fd497116bed3c6 Mon Sep 17 00:00:00 2001 From: Bogdan Gavril Date: Wed, 17 Dec 2025 15:18:14 +0000 Subject: [PATCH 2/5] Update --- .../ParallelizationSettings.cs | 6 +++ .../ParallelizationSettings.cs | 6 +++ .../HeadlessTests/FmiIntegrationTests.cs | 10 ++-- .../HeadlessTests/GenericAuthorityTests.cs | 4 +- ...UsernamePasswordIntegrationTests.NetFwk.cs | 2 +- ...ticateParametersIntegrationTests.NetFwk.cs | 2 +- .../Infrastructure/PoPValidator.cs | 2 +- .../ParallelizationSettings.cs | 6 +++ .../DeviceCodeFlowIntegrationTest.cs | 10 ++-- .../ParallelizationSettings.cs | 6 +++ .../ParallelizationSettings.cs | 6 +++ .../AppTokenProviderTests.cs | 2 +- .../CacheTests/CacheSyncronizationTests.cs | 2 +- .../CoreTests/CollectionHelperTests.cs | 2 +- .../CoreTests/OAuth2Tests/ClaimsTest.cs | 2 +- .../CoreTests/RegionDiscoveryProviderTests.cs | 8 +++- .../WsTrustTests/WsTrustEndpointTests.cs | 2 +- .../OAuthClientTests.cs | 2 +- .../ParallelizationSettings.cs | 6 +++ .../PublicApiTests/AccountTests.cs | 2 +- .../AuthenticationOperationTests.cs | 6 +-- .../ConfidentialClientApplicationTests.cs | 4 +- .../PublicApiTests/ExtensiblityTests.cs | 2 +- .../PublicClientApplicationTests.cs | 3 +- .../PublicApiTests/TenantIdTests.cs | 3 +- .../RequestsTests/DeviceCodeRequestTests.cs | 5 +- .../RequestsTests/FociTests.cs | 6 +-- ...egratedWindowsAuthUsernamePasswordTests.cs | 48 ++++++++++++------- .../InteractiveRequestOrchestrationTests.cs | 8 ++-- .../InteractiveRequestWithCustomWebUiTests.cs | 2 +- .../TelemetryTests/MsalIdHelperTests.cs | 2 +- .../WebUITests/WebView2WebUiFactoryTests.cs | 1 + .../WwwAuthenticateParametersTests.cs | 4 +- .../pop/PoPTests.cs | 6 +-- 34 files changed, 119 insertions(+), 69 deletions(-) create mode 100644 tests/CacheCompat/CommonCache.Test.Unit/ParallelizationSettings.cs create mode 100644 tests/Microsoft.Identity.Test.E2e/ParallelizationSettings.cs create mode 100644 tests/Microsoft.Identity.Test.Integration.netcore/ParallelizationSettings.cs create mode 100644 tests/Microsoft.Identity.Test.Integration.netfx/ParallelizationSettings.cs create mode 100644 tests/Microsoft.Identity.Test.Performance/ParallelizationSettings.cs create mode 100644 tests/Microsoft.Identity.Test.Unit/ParallelizationSettings.cs diff --git a/tests/CacheCompat/CommonCache.Test.Unit/ParallelizationSettings.cs b/tests/CacheCompat/CommonCache.Test.Unit/ParallelizationSettings.cs new file mode 100644 index 0000000000..eae2596ae8 --- /dev/null +++ b/tests/CacheCompat/CommonCache.Test.Unit/ParallelizationSettings.cs @@ -0,0 +1,6 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using Microsoft.VisualStudio.TestTools.UnitTesting; + +[assembly: DoNotParallelize] diff --git a/tests/Microsoft.Identity.Test.E2e/ParallelizationSettings.cs b/tests/Microsoft.Identity.Test.E2e/ParallelizationSettings.cs new file mode 100644 index 0000000000..eae2596ae8 --- /dev/null +++ b/tests/Microsoft.Identity.Test.E2e/ParallelizationSettings.cs @@ -0,0 +1,6 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using Microsoft.VisualStudio.TestTools.UnitTesting; + +[assembly: DoNotParallelize] diff --git a/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/FmiIntegrationTests.cs b/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/FmiIntegrationTests.cs index 7549760f6e..06dc2c8dc4 100644 --- a/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/FmiIntegrationTests.cs +++ b/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/FmiIntegrationTests.cs @@ -61,7 +61,7 @@ public async Task Flow1_Credential_From_Cert() string expectedFmiPathHash = "zm2n0E62zwTsnNsozptLsoOoB_C7i-GfpxHYQQINJUw"; var expectedExternalCacheKey = $"{RmaClientId}_{TenantId}_{expectedFmiPathHash}_AppTokenCache"; // last part is the SHA256 of the fmi path var appCacheAccess = confidentialApp.AppTokenCache.RecordAccess( - (args) => Assert.AreEqual(args.SuggestedCacheKey, expectedExternalCacheKey)); + (args) => Assert.AreEqual(expectedExternalCacheKey, args.SuggestedCacheKey)); //Acquire Fmi Cred var authResult = await confidentialApp.AcquireTokenForClient(new[] { scope }) @@ -100,7 +100,7 @@ public async Task Flow2_Token_From_CertTest() string expectedFmiPathHash = "zm2n0E62zwTsnNsozptLsoOoB_C7i-GfpxHYQQINJUw"; var expectedExternalCacheKey = $"{RmaClientId}_{TenantId}_{expectedFmiPathHash}_AppTokenCache"; var appCacheAccess = confidentialApp.AppTokenCache.RecordAccess( - (args) => Assert.AreEqual(args.SuggestedCacheKey, expectedExternalCacheKey)); + (args) => Assert.AreEqual(expectedExternalCacheKey, args.SuggestedCacheKey)); var authResult = await confidentialApp.AcquireTokenForClient(new[] { WebApiScope }) .WithFmiPath("SomeFmiPath/FmiCredentialPath") @@ -139,7 +139,7 @@ public async Task Flow3_FmiCredential_From_AnotherFmiCredential() string expectedFmiPathHash = "7CX57Q63os7benQ6ER0sxgJPtNQSv7TGb5zexcidFoI"; var expectedExternalCacheKey = $"{clientId}_{TenantId}_{expectedFmiPathHash}_AppTokenCache"; var appCacheAccess = confidentialApp.AppTokenCache.RecordAccess( - (args) => Assert.AreEqual(args.SuggestedCacheKey, expectedExternalCacheKey)); + (args) => Assert.AreEqual(expectedExternalCacheKey, args.SuggestedCacheKey)); var authResult = await confidentialApp.AcquireTokenForClient(new[] { scope }) .WithFmiPath("SomeFmiPath/Path") @@ -179,7 +179,7 @@ public async Task Flow4_SubRma_FIC_From_FmiCredential() string expectedFmiPathHash = ""; // If you have a value, replace accordingly var expectedExternalCacheKey = $"{clientId}_{TenantId}_{expectedFmiPathHash}_AppTokenCache"; var appCacheAccess = confidentialApp.AppTokenCache.RecordAccess( - (args) => Assert.AreEqual(args.SuggestedCacheKey, expectedExternalCacheKey)); + (args) => Assert.AreEqual(expectedExternalCacheKey, args.SuggestedCacheKey)); var authResult = await confidentialApp.AcquireTokenForClient(new[] { scope }) .WithFmiPath("SomeFmiPath/Path") @@ -217,7 +217,7 @@ public async Task Flow5_FmiToken_From_FmiCred() string expectedFmiPathHash = "7CX57Q63os7benQ6ER0sxgJPtNQSv7TGb5zexcidFoI"; var expectedExternalCacheKey = $"{clientId}_{TenantId}_{expectedFmiPathHash}_AppTokenCache"; var appCacheAccess = confidentialApp.AppTokenCache.RecordAccess( - (args) => Assert.AreEqual(args.SuggestedCacheKey, expectedExternalCacheKey)); + (args) => Assert.AreEqual(expectedExternalCacheKey, args.SuggestedCacheKey)); var authResult = await confidentialApp.AcquireTokenForClient(new[] { WebApiScope }) .WithFmiPath("SomeFmiPath/Path") diff --git a/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/GenericAuthorityTests.cs b/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/GenericAuthorityTests.cs index bb908a1f40..8de3c572c9 100644 --- a/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/GenericAuthorityTests.cs +++ b/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/GenericAuthorityTests.cs @@ -57,8 +57,8 @@ public async Task BadSecret_Duende_Async() var ex = await AssertException.TaskThrowsAsync(() => app.AcquireTokenForClient(new[] { "api" }).ExecuteAsync()).ConfigureAwait(false); - Assert.AreEqual(ex.ErrorCode, "invalid_client"); - Assert.AreEqual(ex.StatusCode, (int)HttpStatusCode.BadRequest); + Assert.AreEqual("invalid_client", ex.ErrorCode); + Assert.AreEqual((int)HttpStatusCode.BadRequest, ex.StatusCode); } /// Based on the publicly available https://demo.duendesoftware.com/ diff --git a/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/UsernamePasswordIntegrationTests.NetFwk.cs b/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/UsernamePasswordIntegrationTests.NetFwk.cs index 3630e6abd8..38b1e57900 100644 --- a/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/UsernamePasswordIntegrationTests.NetFwk.cs +++ b/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/UsernamePasswordIntegrationTests.NetFwk.cs @@ -270,7 +270,7 @@ private void AssertCcsRoutingInformationIsNotSent(HttpSnifferClientFactory facto x.Item1.RequestUri.AbsoluteUri.Contains("oauth2/v2.0/token") && x.Item2.StatusCode == HttpStatusCode.OK); - Assert.IsTrue(!req.Headers.Any(h => h.Key == Constants.CcsRoutingHintHeader)); + Assert.IsFalse(req.Headers.Any(h => h.Key == Constants.CcsRoutingHintHeader)); } private void AssertTenantProfiles(IEnumerable tenantProfiles, string tenantId) diff --git a/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/WwwAuthenticateParametersIntegrationTests.NetFwk.cs b/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/WwwAuthenticateParametersIntegrationTests.NetFwk.cs index 6e22336511..12dfd383cd 100644 --- a/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/WwwAuthenticateParametersIntegrationTests.NetFwk.cs +++ b/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/WwwAuthenticateParametersIntegrationTests.NetFwk.cs @@ -121,7 +121,7 @@ public async Task ExtractNonceFromWwwAuthHeadersAsync() //Assert Assert.IsTrue(parameterList.Any(param => param.AuthenticationScheme == Constants.PoPAuthHeaderPrefix)); Assert.IsNotNull(parameterList.Single(param => param.AuthenticationScheme == Constants.PoPAuthHeaderPrefix).Nonce); - Assert.IsTrue(!popNonce.IsNullOrEmpty()); + Assert.IsFalse(popNonce.IsNullOrEmpty()); await PoPValidator.VerifyPopNonceAsync(popNonce).ConfigureAwait(false); } diff --git a/tests/Microsoft.Identity.Test.Integration.netcore/Infrastructure/PoPValidator.cs b/tests/Microsoft.Identity.Test.Integration.netcore/Infrastructure/PoPValidator.cs index e92822ddc7..aad24aa346 100644 --- a/tests/Microsoft.Identity.Test.Integration.netcore/Infrastructure/PoPValidator.cs +++ b/tests/Microsoft.Identity.Test.Integration.netcore/Infrastructure/PoPValidator.cs @@ -68,7 +68,7 @@ public static async Task VerifyPopNonceAsync(string nonce) var response = await s_httpClient.GetAsync( $"https://testingsts.azurewebsites.net/servernonce/validate?serverNonce={nonce}").ConfigureAwait(false); - Assert.AreEqual(response.StatusCode, System.Net.HttpStatusCode.OK); + Assert.AreEqual(System.Net.HttpStatusCode.OK, response.StatusCode); } } diff --git a/tests/Microsoft.Identity.Test.Integration.netcore/ParallelizationSettings.cs b/tests/Microsoft.Identity.Test.Integration.netcore/ParallelizationSettings.cs new file mode 100644 index 0000000000..eae2596ae8 --- /dev/null +++ b/tests/Microsoft.Identity.Test.Integration.netcore/ParallelizationSettings.cs @@ -0,0 +1,6 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using Microsoft.VisualStudio.TestTools.UnitTesting; + +[assembly: DoNotParallelize] diff --git a/tests/Microsoft.Identity.Test.Integration.netcore/SeleniumTests/DeviceCodeFlowIntegrationTest.cs b/tests/Microsoft.Identity.Test.Integration.netcore/SeleniumTests/DeviceCodeFlowIntegrationTest.cs index ef2c9ddd51..751daabd12 100644 --- a/tests/Microsoft.Identity.Test.Integration.netcore/SeleniumTests/DeviceCodeFlowIntegrationTest.cs +++ b/tests/Microsoft.Identity.Test.Integration.netcore/SeleniumTests/DeviceCodeFlowIntegrationTest.cs @@ -36,7 +36,7 @@ public class DeviceCodeFlow #endregion MSTest Hooks [TestMethod] - [Timeout(2 * 60 * 1000)] // 2 min timeout + [Timeout(2 * 60 * 1000, CooperativeCancellation = true)] // 2 min timeout public async Task DeviceCodeFlowTestAsync() { LabResponse labResponse = await LabUserHelper.GetDefaultUserWithMultiTenantAppAsync().ConfigureAwait(false); @@ -44,7 +44,7 @@ public async Task DeviceCodeFlowTestAsync() } [TestMethod] - [Timeout(2 * 60 * 1000)] // 2 min timeout + [Timeout(2 * 60 * 1000, CooperativeCancellation = true)] // 2 min timeout public async Task SilentTokenAfterDeviceCodeFlowWithBrokerTestAsync() { LabResponse labResponse = await LabUserHelper.GetDefaultUserWithMultiTenantAppAsync().ConfigureAwait(false); @@ -80,7 +80,7 @@ private async Task AcquireTokenWithDeviceCodeFlowAsync(LabResponse labResponse, Assert.IsFalse(userCacheAccess.LastAfterAccessNotificationArgs.IsApplicationCache); Assert.IsNotNull(result); - Assert.IsTrue(!string.IsNullOrEmpty(result.AccessToken)); + Assert.IsFalse(string.IsNullOrEmpty(result.AccessToken)); } private async Task AcquireTokenSilentAfterDeviceCodeFlowWithBrokerAsync(LabResponse labResponse, string userType) @@ -115,11 +115,11 @@ private async Task AcquireTokenSilentAfterDeviceCodeFlowWithBrokerAsync(LabRespo Assert.IsNotNull(result); var account = result.Account as Account; Assert.AreEqual("device_code_flow", account.AccountSource); - Assert.IsTrue(!string.IsNullOrEmpty(result.AccessToken)); + Assert.IsFalse(string.IsNullOrEmpty(result.AccessToken)); var silentTokenResult = await pca.AcquireTokenSilent(s_scopes, result.Account).ExecuteAsync(CancellationToken.None).ConfigureAwait(false); Assert.IsNotNull(silentTokenResult); - Assert.IsTrue(!string.IsNullOrEmpty(silentTokenResult.AccessToken)); + Assert.IsFalse(string.IsNullOrEmpty(silentTokenResult.AccessToken)); } } } diff --git a/tests/Microsoft.Identity.Test.Integration.netfx/ParallelizationSettings.cs b/tests/Microsoft.Identity.Test.Integration.netfx/ParallelizationSettings.cs new file mode 100644 index 0000000000..eae2596ae8 --- /dev/null +++ b/tests/Microsoft.Identity.Test.Integration.netfx/ParallelizationSettings.cs @@ -0,0 +1,6 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using Microsoft.VisualStudio.TestTools.UnitTesting; + +[assembly: DoNotParallelize] diff --git a/tests/Microsoft.Identity.Test.Performance/ParallelizationSettings.cs b/tests/Microsoft.Identity.Test.Performance/ParallelizationSettings.cs new file mode 100644 index 0000000000..eae2596ae8 --- /dev/null +++ b/tests/Microsoft.Identity.Test.Performance/ParallelizationSettings.cs @@ -0,0 +1,6 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using Microsoft.VisualStudio.TestTools.UnitTesting; + +[assembly: DoNotParallelize] diff --git a/tests/Microsoft.Identity.Test.Unit/AppTokenProviderTests.cs b/tests/Microsoft.Identity.Test.Unit/AppTokenProviderTests.cs index 429550e9c2..5424edc8c7 100644 --- a/tests/Microsoft.Identity.Test.Unit/AppTokenProviderTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/AppTokenProviderTests.cs @@ -36,7 +36,7 @@ public async Task ValidateAppTokenProviderAsync() Assert.IsNotNull(parameters.Scopes); Assert.IsNotNull(parameters.CorrelationId); Assert.IsNotNull(parameters.TenantId); - Assert.IsNotNull(parameters.CancellationToken); + Assert.AreEqual(CancellationToken.None, parameters.CancellationToken); if (usingClaims) { diff --git a/tests/Microsoft.Identity.Test.Unit/CacheTests/CacheSyncronizationTests.cs b/tests/Microsoft.Identity.Test.Unit/CacheTests/CacheSyncronizationTests.cs index 002033743f..cf9930adad 100644 --- a/tests/Microsoft.Identity.Test.Unit/CacheTests/CacheSyncronizationTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/CacheTests/CacheSyncronizationTests.cs @@ -18,7 +18,7 @@ public class CacheSyncronizationTests : TestBase { [TestMethod] - [Timeout(2000)] + [Timeout(2000, CooperativeCancellation = true)] public async Task DisableInternalSemaphore_Async() { await RunSemaphoreTestAsync(true).ConfigureAwait(false); diff --git a/tests/Microsoft.Identity.Test.Unit/CoreTests/CollectionHelperTests.cs b/tests/Microsoft.Identity.Test.Unit/CoreTests/CollectionHelperTests.cs index d88c4a9a73..a3619538e4 100644 --- a/tests/Microsoft.Identity.Test.Unit/CoreTests/CollectionHelperTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/CoreTests/CollectionHelperTests.cs @@ -17,7 +17,7 @@ public class CollectionHelperTests public void EmptyStringDictionaryIsImmutable() { (CollectionHelpers.GetEmptyDictionary() as System.Collections.Immutable.ImmutableDictionary).Add("k", "v"); - Assert.IsTrue(!CollectionHelpers.GetEmptyDictionary().Any()); + Assert.IsFalse(CollectionHelpers.GetEmptyDictionary().Any()); Assert.IsNull((CollectionHelpers.GetEmptyDictionary() as Dictionary)); } diff --git a/tests/Microsoft.Identity.Test.Unit/CoreTests/OAuth2Tests/ClaimsTest.cs b/tests/Microsoft.Identity.Test.Unit/CoreTests/OAuth2Tests/ClaimsTest.cs index ee314f40a3..50e6a32c27 100644 --- a/tests/Microsoft.Identity.Test.Unit/CoreTests/OAuth2Tests/ClaimsTest.cs +++ b/tests/Microsoft.Identity.Test.Unit/CoreTests/OAuth2Tests/ClaimsTest.cs @@ -243,7 +243,7 @@ public async Task Claims_Fail_WhenClaimsIsNotJson_Async() } [TestMethod] - [DynamicData(nameof(TestData.GetClaimsAndCapabilities), typeof(TestData), DynamicDataSourceType.Method)] + [DynamicData(nameof(TestData.GetClaimsAndCapabilities), typeof(TestData))] public void ClaimsMerge_Test(string claims, string[] capabilities, string expectedMergedJson) { var mergedJson = ClaimsHelper.GetMergedClaimsAndClientCapabilities(claims, capabilities); diff --git a/tests/Microsoft.Identity.Test.Unit/CoreTests/RegionDiscoveryProviderTests.cs b/tests/Microsoft.Identity.Test.Unit/CoreTests/RegionDiscoveryProviderTests.cs index a564e780b6..891441ea7d 100644 --- a/tests/Microsoft.Identity.Test.Unit/CoreTests/RegionDiscoveryProviderTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/CoreTests/RegionDiscoveryProviderTests.cs @@ -99,6 +99,7 @@ public void MultiThreadSuccessfulResponseFromLocalImds_HasOnlyOneImdsCall() // if the http mock is called more than once, it will fail in dispose as queue will be non-empty AddMockedResponse(MockHelpers.CreateSuccessResponseMessage(TestConstants.Region)); int threadCount = MaxThreadCount; + Exception caughtException = null; #pragma warning disable VSTHRD101 // Avoid unsupported async delegates - acceptable risk (crash the test proj) var result = Parallel.For(0, MaxThreadCount, async (i) => { @@ -114,7 +115,7 @@ public void MultiThreadSuccessfulResponseFromLocalImds_HasOnlyOneImdsCall() } catch (Exception ex) { - Assert.Fail(ex.Message); + Interlocked.CompareExchange(ref caughtException, ex, null); } finally { @@ -129,6 +130,11 @@ public void MultiThreadSuccessfulResponseFromLocalImds_HasOnlyOneImdsCall() Thread.Yield(); } Assert.IsTrue(result.IsCompleted); + + if (caughtException is not null) + { + Assert.Fail(caughtException.Message); + } } [TestMethod] diff --git a/tests/Microsoft.Identity.Test.Unit/CoreTests/WsTrustTests/WsTrustEndpointTests.cs b/tests/Microsoft.Identity.Test.Unit/CoreTests/WsTrustTests/WsTrustEndpointTests.cs index 9e428de69d..8415a9d047 100644 --- a/tests/Microsoft.Identity.Test.Unit/CoreTests/WsTrustTests/WsTrustEndpointTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/CoreTests/WsTrustTests/WsTrustEndpointTests.cs @@ -150,7 +150,7 @@ private void CheckStringEqualityAtEachCharacter(string expected, string actual) { if (expected[i] != actual[i]) { - Assert.IsFalse(true); + Assert.Fail($"Strings differ at index {i}."); } } } diff --git a/tests/Microsoft.Identity.Test.Unit/OAuthClientTests.cs b/tests/Microsoft.Identity.Test.Unit/OAuthClientTests.cs index e298a3a046..3e886fe0c9 100644 --- a/tests/Microsoft.Identity.Test.Unit/OAuthClientTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/OAuthClientTests.cs @@ -220,7 +220,7 @@ private static MockHttpMessageHandler CreateTokenResponseHttpHandlerWithPKeyAuth var authHeader = request.Headers.Authorization?.ToString(); // Check value of pkeyAuth header. - Assert.AreEqual(authHeader, TestConstants.PKeyAuthResponse); + Assert.AreEqual(TestConstants.PKeyAuthResponse, authHeader); } }; } diff --git a/tests/Microsoft.Identity.Test.Unit/ParallelizationSettings.cs b/tests/Microsoft.Identity.Test.Unit/ParallelizationSettings.cs new file mode 100644 index 0000000000..eae2596ae8 --- /dev/null +++ b/tests/Microsoft.Identity.Test.Unit/ParallelizationSettings.cs @@ -0,0 +1,6 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using Microsoft.VisualStudio.TestTools.UnitTesting; + +[assembly: DoNotParallelize] diff --git a/tests/Microsoft.Identity.Test.Unit/PublicApiTests/AccountTests.cs b/tests/Microsoft.Identity.Test.Unit/PublicApiTests/AccountTests.cs index b857d8cb61..877fbf241c 100644 --- a/tests/Microsoft.Identity.Test.Unit/PublicApiTests/AccountTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/PublicApiTests/AccountTests.cs @@ -424,7 +424,7 @@ private async Task ValidateGetAccountsWithDiscoveryAsync(string tokenCacheAsStri // Assert Assert.AreEqual("login.microsoftonline.com", accountsGlobal.Single().Environment); - Assert.IsTrue(!accountsDe.Any()); + Assert.IsFalse(accountsDe.Any()); Assert.AreEqual("login.chinacloudapi.cn", accountsCn.Single().Environment); } } diff --git a/tests/Microsoft.Identity.Test.Unit/PublicApiTests/AuthenticationOperationTests.cs b/tests/Microsoft.Identity.Test.Unit/PublicApiTests/AuthenticationOperationTests.cs index cdf15c9c51..8e80215f80 100644 --- a/tests/Microsoft.Identity.Test.Unit/PublicApiTests/AuthenticationOperationTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/PublicApiTests/AuthenticationOperationTests.cs @@ -241,7 +241,7 @@ public async Task IAsyncOperation2_Async() .WithAuthenticationOperation(new TestOperation()) .ExecuteAsync().ConfigureAwait(false); - Assert.IsTrue(result.AccessToken.StartsWith("IAuthenticationOperation2")); + StringAssert.StartsWith("IAuthenticationOperation2", result.AccessToken); Assert.AreEqual($"TestToken {result.AccessToken}", result.CreateAuthorizationHeader() ); } @@ -345,7 +345,7 @@ public async Task ValidateCachedTokenAsync_WhenValidationFails_CacheIsIgnoredAsy .ConfigureAwait(false); Assert.IsNotNull(result1); - Assert.IsTrue(result1.AccessToken.StartsWith("validated_")); + StringAssert.StartsWith("validated_", result1.AccessToken); Assert.AreEqual(TokenSource.IdentityProvider, result1.AuthenticationResultMetadata.TokenSource); // Second request - validation should fail, so new token should be acquired @@ -403,7 +403,7 @@ public async Task ValidateCachedTokenAsync_WhenValidationSucceeds_CacheIsUsedAsy .ConfigureAwait(false); Assert.IsNotNull(result1); - Assert.IsTrue(result1.AccessToken.StartsWith("validated_")); + StringAssert.StartsWith("validated_", result1.AccessToken); Assert.AreEqual(TokenSource.IdentityProvider, result1.AuthenticationResultMetadata.TokenSource); // Second request - validation should succeed, so cached token should be returned diff --git a/tests/Microsoft.Identity.Test.Unit/PublicApiTests/ConfidentialClientApplicationTests.cs b/tests/Microsoft.Identity.Test.Unit/PublicApiTests/ConfidentialClientApplicationTests.cs index c3b30dddbc..57bb4a260b 100644 --- a/tests/Microsoft.Identity.Test.Unit/PublicApiTests/ConfidentialClientApplicationTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/PublicApiTests/ConfidentialClientApplicationTests.cs @@ -621,7 +621,7 @@ public async Task ConfidentialClientUsingClientAssertionClaimsTestAsync() var userCacheAccess = app.UserTokenCache.RecordAccess(); var result = await app.AcquireTokenForClient(TestConstants.s_scope.ToArray()).ExecuteAsync(CancellationToken.None).ConfigureAwait(false); - Assert.IsNotNull(setup); + Assert.IsNotNull(app); Assert.IsNotNull("header.payload.signature", result.AccessToken); Assert.AreEqual(TestConstants.s_scope.AsSingleString(), result.Scopes.AsSingleString()); appCacheAccess.AssertAccessCounts(1, 1); @@ -1082,7 +1082,7 @@ private static void AssertCcsHint(Uri uri, string ccsHint) } else { - Assert.IsTrue(!qp.ContainsKey(Constants.CcsRoutingHintHeader)); + Assert.IsFalse(qp.ContainsKey(Constants.CcsRoutingHintHeader)); } } diff --git a/tests/Microsoft.Identity.Test.Unit/PublicApiTests/ExtensiblityTests.cs b/tests/Microsoft.Identity.Test.Unit/PublicApiTests/ExtensiblityTests.cs index 2afc63d860..b2373a909c 100644 --- a/tests/Microsoft.Identity.Test.Unit/PublicApiTests/ExtensiblityTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/PublicApiTests/ExtensiblityTests.cs @@ -143,7 +143,7 @@ public async Task ValidateAppTokenProviderAsync() Assert.IsNotNull(parameters.Scopes); Assert.IsNotNull(parameters.CorrelationId); Assert.IsNotNull(parameters.TenantId); - Assert.IsNotNull(parameters.CancellationToken); + Assert.AreEqual(CancellationToken.None, parameters.CancellationToken); if (usingClaims) { diff --git a/tests/Microsoft.Identity.Test.Unit/PublicApiTests/PublicClientApplicationTests.cs b/tests/Microsoft.Identity.Test.Unit/PublicApiTests/PublicClientApplicationTests.cs index ae3f44539a..a1a5678fae 100644 --- a/tests/Microsoft.Identity.Test.Unit/PublicApiTests/PublicClientApplicationTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/PublicApiTests/PublicClientApplicationTests.cs @@ -644,7 +644,7 @@ public void GetAccountTests() .BuildConcrete(); var accounts = app.GetAccountsAsync().Result; - Assert.IsTrue(!accounts.Any()); + Assert.IsFalse(accounts.Any()); var acc = app.GetAccountAsync(null).Result; Assert.IsNull(acc); @@ -1210,7 +1210,6 @@ public void CheckUserProvidedCorrelationIDTest() .ExecuteAsync(CancellationToken.None) .Result; - Assert.IsNotNull(result.CorrelationId); Assert.AreEqual(correlationId.ToString(), result.CorrelationId.ToString()); Assert.IsNotNull(result); Assert.IsNotNull(result.AccessToken); diff --git a/tests/Microsoft.Identity.Test.Unit/PublicApiTests/TenantIdTests.cs b/tests/Microsoft.Identity.Test.Unit/PublicApiTests/TenantIdTests.cs index f65af09307..c345a23ef2 100644 --- a/tests/Microsoft.Identity.Test.Unit/PublicApiTests/TenantIdTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/PublicApiTests/TenantIdTests.cs @@ -27,7 +27,6 @@ public class TenantIdTests : TestBase [DataRow(TestConstants.B2CCustomDomain, TestConstants.CatsAreAwesome, DisplayName = "B2C Custom Domain Tenant Id")] [DataRow(TestConstants.B2CLoginAuthority, TestConstants.SomeTenantId, DisplayName = "B2C Tenant Id")] [DataRow(TestConstants.B2CLoginAuthorityUsGov, TestConstants.SomeTenantId, DisplayName = "B2C US GOV Tenant Id")] - [DataRow(TestConstants.B2CCustomDomain, TestConstants.CatsAreAwesome, DisplayName = "B2C Custom Domain Tenant Id")] [DataRow(TestConstants.B2CLoginAuthorityBlackforest, TestConstants.SomeTenantId, DisplayName = "B2C Blackforest Tenant Id")] [DataRow(TestConstants.B2CLoginAuthorityMoonCake, TestConstants.SomeTenantId, DisplayName = "B2C MoonCake Tenant Id")] [DataRow(TestConstants.AuthoritySovereignCNTenant, TestConstants.TenantId, DisplayName = "Sovereign Tenant Id")] @@ -42,7 +41,7 @@ public void ParseTest_Success(string authorityUrl, string expectedTenantId) } [TestMethod] - [DynamicData(nameof(TestData.GetAuthorityWithExpectedTenantId), typeof(TestData), DynamicDataSourceType.Method)] + [DynamicData(nameof(TestData.GetAuthorityWithExpectedTenantId), typeof(TestData))] public void ParseTestDynamic_Success(Uri authorityUrl, string expectedTenantId) { ParseTest_Success(authorityUrl.ToString(), expectedTenantId); diff --git a/tests/Microsoft.Identity.Test.Unit/RequestsTests/DeviceCodeRequestTests.cs b/tests/Microsoft.Identity.Test.Unit/RequestsTests/DeviceCodeRequestTests.cs index c55b066d4b..6680dd6067 100644 --- a/tests/Microsoft.Identity.Test.Unit/RequestsTests/DeviceCodeRequestTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/RequestsTests/DeviceCodeRequestTests.cs @@ -259,10 +259,7 @@ public async Task VerifyAuthorizationPendingErrorDoesNotLogError_Async() { if (level == LogLevel.Error) { - Assert.Fail( - "Received an error message {0} and the stack trace is {1}", - message, - new StackTrace(true)); + Assert.Fail($"Received an error message {message} and the stack trace is {new StackTrace(true)}"); } logCallbacks.Add( diff --git a/tests/Microsoft.Identity.Test.Unit/RequestsTests/FociTests.cs b/tests/Microsoft.Identity.Test.Unit/RequestsTests/FociTests.cs index f8f85bcca6..c25c558460 100644 --- a/tests/Microsoft.Identity.Test.Unit/RequestsTests/FociTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/RequestsTests/FociTests.cs @@ -151,7 +151,7 @@ public async Task FociDoesNotHideRTRefreshErrorsAsync() () => SilentAsync(_appB, ServerTokenResponse.OtherError)).ConfigureAwait(false); Assert.AreEqual(MsalError.InvalidGrantError, ex.ErrorCode); - Assert.IsTrue(!String.IsNullOrEmpty(ex.CorrelationId)); + Assert.IsFalse(string.IsNullOrEmpty(ex.CorrelationId)); // B performs interactive auth and everything goes back to normal - both A and B can silently sing in await InteractiveAsync(_appB, ServerTokenResponse.FociToken).ConfigureAwait(false); @@ -253,8 +253,8 @@ public async Task TestGetAndRemoveAccountsFociDisabledAsync() var tokens = _appA.UserTokenCacheInternal.Accessor.GetAllRefreshTokens(); - Assert.IsTrue( - !string.IsNullOrEmpty(tokens.Single().FamilyId), + Assert.IsFalse( + string.IsNullOrEmpty(tokens.Single().FamilyId), "The FRT should not be deleted when FOCI is disabled"); Assert.IsFalse( diff --git a/tests/Microsoft.Identity.Test.Unit/RequestsTests/IntegratedWindowsAuthUsernamePasswordTests.cs b/tests/Microsoft.Identity.Test.Unit/RequestsTests/IntegratedWindowsAuthUsernamePasswordTests.cs index 0ef9a4fe69..1e26e92916 100644 --- a/tests/Microsoft.Identity.Test.Unit/RequestsTests/IntegratedWindowsAuthUsernamePasswordTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/RequestsTests/IntegratedWindowsAuthUsernamePasswordTests.cs @@ -310,12 +310,16 @@ public async Task AcquireTokenByIntegratedWindowsAuth3rdPartyIDPTestAsync(string Assert.IsNotNull(result.Account); Assert.AreEqual(TestConstants.DisplayableId, result.Account.Username); Assert.IsNotNull(realmDiscoveryHandler.ActualRequestMessage.Headers); - StringAssert.Contains(realmDiscoveryHandler.ActualRequestMessage.Headers.ToString(), TestConstants.XClientSku, - "Client info header should contain " + TestConstants.XClientSku, - StringComparison.OrdinalIgnoreCase); - StringAssert.Contains(realmDiscoveryHandler.ActualRequestMessage.Headers.ToString(), TestConstants.XClientVer, - "Client info header should contain " + TestConstants.XClientVer, - StringComparison.OrdinalIgnoreCase); + StringAssert.Contains( + realmDiscoveryHandler.ActualRequestMessage.Headers.ToString(), + TestConstants.XClientSku, + StringComparison.OrdinalIgnoreCase, + "Client info header should contain " + TestConstants.XClientSku); + StringAssert.Contains( + realmDiscoveryHandler.ActualRequestMessage.Headers.ToString(), + TestConstants.XClientVer, + StringComparison.OrdinalIgnoreCase, + "Client info header should contain " + TestConstants.XClientVer); } } @@ -353,12 +357,16 @@ public async Task AcquireTokenByIntegratedWindowsAuthMetadataTestAsync() Assert.IsNotNull(result.Account); Assert.AreEqual(TestConstants.DisplayableId, result.Account.Username); Assert.IsNotNull(realmDiscoveryHandler.ActualRequestMessage.Headers); - StringAssert.Contains(realmDiscoveryHandler.ActualRequestMessage.Headers.ToString(), TestConstants.XClientSku, - "Client info header should contain " + TestConstants.XClientSku, - StringComparison.OrdinalIgnoreCase); - StringAssert.Contains(realmDiscoveryHandler.ActualRequestMessage.Headers.ToString(), TestConstants.XClientVer, - "Client info header should contain " + TestConstants.XClientVer, - StringComparison.OrdinalIgnoreCase); + StringAssert.Contains( + realmDiscoveryHandler.ActualRequestMessage.Headers.ToString(), + TestConstants.XClientSku, + StringComparison.OrdinalIgnoreCase, + "Client info header should contain " + TestConstants.XClientSku); + StringAssert.Contains( + realmDiscoveryHandler.ActualRequestMessage.Headers.ToString(), + TestConstants.XClientVer, + StringComparison.OrdinalIgnoreCase, + "Client info header should contain " + TestConstants.XClientVer); // Assert telemetry ApiId Assert.AreEqual(ApiEvent.ApiIds.AcquireTokenByIntegratedWindowsAuth.ToString("D"), mockTokenRequestHttpHandler.ActualRequestMessage.Headers.GetValues(TelemetryConstants.XClientCurrentTelemetry).Single().Split('|')[1].Split(',')[0]); @@ -434,12 +442,16 @@ public async Task FederatedUsernamePasswordAcquireTokenTestAsync() Assert.IsNotNull(result.Account); Assert.AreEqual(TestConstants.s_user.Username, result.Account.Username); Assert.IsNotNull(realmDiscoveryHandler.ActualRequestMessage.Headers); - StringAssert.Contains(realmDiscoveryHandler.ActualRequestMessage.Headers.ToString(), TestConstants.XClientSku, - "Client info header should contain " + TestConstants.XClientSku, - StringComparison.OrdinalIgnoreCase); - StringAssert.Contains(realmDiscoveryHandler.ActualRequestMessage.Headers.ToString(), TestConstants.XClientVer, - "Client info header should contain " + TestConstants.XClientVer, - StringComparison.OrdinalIgnoreCase); + StringAssert.Contains( + realmDiscoveryHandler.ActualRequestMessage.Headers.ToString(), + TestConstants.XClientSku, + StringComparison.OrdinalIgnoreCase, + "Client info header should contain " + TestConstants.XClientSku); + StringAssert.Contains( + realmDiscoveryHandler.ActualRequestMessage.Headers.ToString(), + TestConstants.XClientVer, + StringComparison.OrdinalIgnoreCase, + "Client info header should contain " + TestConstants.XClientVer); } } diff --git a/tests/Microsoft.Identity.Test.Unit/RequestsTests/InteractiveRequestOrchestrationTests.cs b/tests/Microsoft.Identity.Test.Unit/RequestsTests/InteractiveRequestOrchestrationTests.cs index 31396c411c..6c906760ac 100644 --- a/tests/Microsoft.Identity.Test.Unit/RequestsTests/InteractiveRequestOrchestrationTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/RequestsTests/InteractiveRequestOrchestrationTests.cs @@ -79,7 +79,7 @@ public async Task NoBroker_WebUiOnly_Async() // Assert - common stuff Assert.IsNotNull(result); Assert.AreEqual(TokenSource.IdentityProvider, result.AuthenticationResultMetadata.TokenSource); - Assert.IsTrue(!string.IsNullOrEmpty(result.AccessToken)); + Assert.IsFalse(string.IsNullOrEmpty(result.AccessToken)); Assert.HasCount(1, cache.Accessor.GetAllAccessTokens()); // Assert - orchestration @@ -137,7 +137,7 @@ public async Task Broker_Configured_And_Installed_Async() // Assert - common stuff Assert.IsNotNull(result); Assert.AreEqual(TokenSource.Broker, result.AuthenticationResultMetadata.TokenSource); - Assert.IsTrue(!string.IsNullOrEmpty(result.AccessToken)); + Assert.IsFalse(string.IsNullOrEmpty(result.AccessToken)); // Assert - orchestration await _brokerExchangeComponentOverride @@ -204,7 +204,7 @@ public async Task Broker_Configured_But_Not_Installed_Async() // Assert - common stuff Assert.IsNotNull(result); - Assert.IsTrue(!string.IsNullOrEmpty(result.AccessToken)); + Assert.IsFalse(string.IsNullOrEmpty(result.AccessToken)); Assert.HasCount(1, cache.Accessor.GetAllAccessTokens()); // Assert - orchestration @@ -268,7 +268,7 @@ public async Task Broker_Not_Configured_But_Installed_EvoWantsBroker_Async() // Assert - common stuff Assert.IsNotNull(result); - Assert.IsTrue(!string.IsNullOrEmpty(result.AccessToken)); + Assert.IsFalse(string.IsNullOrEmpty(result.AccessToken)); Assert.HasCount(1, cache.Accessor.GetAllAccessTokens()); // Assert - orchestration diff --git a/tests/Microsoft.Identity.Test.Unit/RequestsTests/InteractiveRequestWithCustomWebUiTests.cs b/tests/Microsoft.Identity.Test.Unit/RequestsTests/InteractiveRequestWithCustomWebUiTests.cs index 2c9fe4d99a..a2f43936e2 100644 --- a/tests/Microsoft.Identity.Test.Unit/RequestsTests/InteractiveRequestWithCustomWebUiTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/RequestsTests/InteractiveRequestWithCustomWebUiTests.cs @@ -91,7 +91,7 @@ await ExecuteTestAsync( // Capture the state from the authorizationUri and add it to the result uri var authorizationUri = x[0] as Uri; var state = CoreHelpers.ParseKeyValueList(authorizationUri.Query, '&', true, false, null)["state"]; - Assert.IsTrue(!string.IsNullOrEmpty(state)); + Assert.IsFalse(string.IsNullOrEmpty(state)); return Task.FromResult(new Uri(ExpectedRedirectUri + "?code=some-code&state=" + state)); }); diff --git a/tests/Microsoft.Identity.Test.Unit/TelemetryTests/MsalIdHelperTests.cs b/tests/Microsoft.Identity.Test.Unit/TelemetryTests/MsalIdHelperTests.cs index 5d205e1338..272c1c76f1 100644 --- a/tests/Microsoft.Identity.Test.Unit/TelemetryTests/MsalIdHelperTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/TelemetryTests/MsalIdHelperTests.cs @@ -47,7 +47,7 @@ public async Task IdHelperAsync() private static void AssertHeaders(MockHttpMessageHandler headers, Guid correlationId) { - Assert.IsTrue(!headers.ActualRequestMessage.Headers.GetValues("x-client-os").Single().Contains("6.2.9200")); + Assert.DoesNotContain("6.2.9200", headers.ActualRequestMessage.Headers.GetValues("x-client-os").Single()); Assert.Contains("Windows", headers.ActualRequestMessage.Headers.GetValues("x-client-os").Single()); Assert.AreEqual( typeof(PublicClientApplication).Assembly.GetName().Version.ToString(), diff --git a/tests/Microsoft.Identity.Test.Unit/WebUITests/WebView2WebUiFactoryTests.cs b/tests/Microsoft.Identity.Test.Unit/WebUITests/WebView2WebUiFactoryTests.cs index 18a0839026..a47fd60443 100644 --- a/tests/Microsoft.Identity.Test.Unit/WebUITests/WebView2WebUiFactoryTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/WebUITests/WebView2WebUiFactoryTests.cs @@ -39,6 +39,7 @@ public void IsSystemWebUiAvailable() Assert.IsTrue(webUIFactory.IsSystemWebViewAvailable); } + [TestMethod] [DataRow()] public void WebViewTypeNotConfigured_AAD_WebView1() { diff --git a/tests/Microsoft.Identity.Test.Unit/WwwAuthenticateParametersTests.cs b/tests/Microsoft.Identity.Test.Unit/WwwAuthenticateParametersTests.cs index 30e823393f..193f01bb5e 100644 --- a/tests/Microsoft.Identity.Test.Unit/WwwAuthenticateParametersTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/WwwAuthenticateParametersTests.cs @@ -192,8 +192,8 @@ public void CreateFromMalformedAuthInfoResponse(string paramName, string value) AuthenticationInfoParameters.CreateFromResponseHeaders(httpResponse.Headers)); //Assert - Assert.AreEqual(ex.ErrorCode, MsalError.UnableToParseAuthenticationHeader); - Assert.AreEqual(ex.Message, MsalErrorMessage.UnableToParseAuthenticationHeader + $"Response Headers: {httpResponse.Headers.ToString()} See inner exception for details."); + Assert.AreEqual(MsalError.UnableToParseAuthenticationHeader, ex.ErrorCode); + Assert.AreEqual(MsalErrorMessage.UnableToParseAuthenticationHeader + $"Response Headers: {httpResponse.Headers.ToString()} See inner exception for details.", ex.Message); } [TestMethod] diff --git a/tests/Microsoft.Identity.Test.Unit/pop/PoPTests.cs b/tests/Microsoft.Identity.Test.Unit/pop/PoPTests.cs index 1fb27b4cad..a61d3354d4 100644 --- a/tests/Microsoft.Identity.Test.Unit/pop/PoPTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/pop/PoPTests.cs @@ -79,7 +79,7 @@ public async Task POP_ShrValidation_Async() // access token parsing can be done with MSAL's id token parsing logic var claims = IdToken.Parse(result.AccessToken).ClaimsPrincipal; - Assert.IsTrue(!string.IsNullOrEmpty(claims.FindAll("nonce").Single().Value)); + Assert.IsFalse(string.IsNullOrEmpty(claims.FindAll("nonce").Single().Value)); AssertSingedHttpRequestClaims(provider, claims); } } @@ -607,7 +607,7 @@ public async Task POP_SignatureValidationWithPS256_Async() // access token parsing can be done with MSAL's id token parsing logic var claims = IdToken.Parse(result.AccessToken).ClaimsPrincipal; - Assert.IsTrue(!string.IsNullOrEmpty(claims.FindAll("nonce").Single().Value)); + Assert.IsFalse(string.IsNullOrEmpty(claims.FindAll("nonce").Single().Value)); AssertSingedHttpRequestClaims(provider, claims); } } @@ -675,7 +675,7 @@ public async Task TokenGenerationAndValidation_Async() // Assert Assert.AreEqual("PS256", provider.CryptographicAlgorithm); - Assert.IsTrue(!string.IsNullOrEmpty(claims.FindAll("nonce").Single().Value)); + Assert.IsFalse(string.IsNullOrEmpty(claims.FindAll("nonce").Single().Value)); AssertSingedHttpRequestClaims(provider, claims); } } From ec8d098bafeb5bf5b08d6d05b5aa48f32aa68280 Mon Sep 17 00:00:00 2001 From: Bogdan Gavril Date: Wed, 17 Dec 2025 17:42:57 +0000 Subject: [PATCH 3/5] Remove old assert exception --- .../Core/Helpers/AssertException.cs | 242 ------------------ .../HeadlessTests/CancellationTests.cs | 3 +- .../HeadlessTests/GenericAuthorityTests.cs | 3 +- .../InstanceDiscoveryIntegrationTests.cs | 5 +- .../LongRunningOnBehalfOfTests.cs | 5 +- .../ManagedIdentityTests.NetFwk.cs | 5 +- .../MsalCacheStorageIntegrationTests.cs | 3 +- .../HeadlessTests/OnBehalfOfTests.cs | 9 +- .../HeadlessTests/RuntimeBrokerTests.cs | 9 +- .../SeleniumTests/FociTests.cs | 3 +- .../SeleniumInfrastructureTests.NetFwk.cs | 5 +- .../AcquireTokenInteractiveBuilderTests.cs | 3 +- .../ApiConfigTests/AuthorityTests.cs | 3 +- ...nfidentialClientApplicationBuilderTests.cs | 7 +- .../PublicClientApplicationBuilderTests.cs | 27 +- .../AppTokenProviderTests.cs | 3 +- .../AuthScheme/SSHCertTests.cs | 11 +- .../BrokerTests/BrokerRequestTests.cs | 5 +- .../BrokerTests/RuntimeBrokerTests.cs | 5 +- .../CacheExtension/MsalCacheHelperTests.cs | 9 +- .../CacheExtension/MsalCacheStorageTests.cs | 19 +- .../CacheTests/CacheFailureTests.cs | 3 +- .../CacheTests/InternalCacheOptionsTests.cs | 17 +- .../CacheTests/TokenCacheNotificationTests.cs | 5 +- .../CoreTests/HttpTests/HttpManagerTests.cs | 15 +- .../InstanceTests/AadAuthorityTests.cs | 3 +- .../InstanceTests/GenericAuthorityTests.cs | 9 +- .../InstanceDiscoveryManagerTests.cs | 3 +- .../CoreTests/OAuth2Tests/ClaimsTest.cs | 3 +- .../CoreTests/WsTrustTests/WsTrustTests.cs | 3 +- .../CryptographyTests.cs | 3 +- .../ExperimentalFeatureTests.cs | 3 +- .../ExceptionTests/MsalExceptionTests.cs | 19 +- .../ManagedIdentityTests/ImdsTests.cs | 5 +- .../ManagedIdentityTests.cs | 3 +- .../OAuthClientTests.cs | 3 +- .../PublicApiTests/AcquireTokenSilentTests.cs | 11 +- .../AuthenticationOperationTests.cs | 3 +- .../PublicApiTests/ClientAssertionTests.cs | 9 +- .../ClientCredentialWithRegionTests.cs | 11 +- .../ConfidentialClientApplicationTests.cs | 21 +- .../PublicApiTests/MtlsPopTests.cs | 11 +- .../PublicClientApplicationTests.cs | 7 +- .../PublicClientApplicationTestsWithB2C.cs | 5 +- .../PublicApiTests/RefreshInTests.cs | 5 +- .../RequestsTests/DeviceCodeRequestTests.cs | 5 +- .../RequestsTests/FociTests.cs | 9 +- ...egratedWindowsAuthUsernamePasswordTests.cs | 23 +- .../RequestsTests/InteractiveRequestTests.cs | 13 +- .../InteractiveRequestWithCustomWebUiTests.cs | 9 +- .../LongRunningOnBehalfOfTests.cs | 7 +- .../RequestsTests/SilentRequestTests.cs | 3 +- .../TelemetryTests/HttpTelemetryTests.cs | 9 +- .../OTelInstrumentationTests.cs | 5 +- .../TelemetryTests/RegionalTelemetryTests.cs | 3 +- .../Throttling/ThrottlingAcceptanceTests.cs | 29 ++- .../UtilTests/RetryOperationHelperTest.cs | 5 +- .../WebUITests/DefaultOsBrowserWebUiTests.cs | 7 +- .../HttpListenerInterceptorTests.cs | 7 +- .../WebUITests/NetCoreWebUIFactoryTests.cs | 3 +- .../pop/PoPTests.cs | 13 +- .../pop/PopAuthenticationOperationTests.cs | 9 +- 62 files changed, 271 insertions(+), 452 deletions(-) delete mode 100644 tests/Microsoft.Identity.Test.Common/Core/Helpers/AssertException.cs diff --git a/tests/Microsoft.Identity.Test.Common/Core/Helpers/AssertException.cs b/tests/Microsoft.Identity.Test.Common/Core/Helpers/AssertException.cs deleted file mode 100644 index 82f95c749e..0000000000 --- a/tests/Microsoft.Identity.Test.Common/Core/Helpers/AssertException.cs +++ /dev/null @@ -1,242 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using System; -using System.Diagnostics; -using System.Globalization; -using System.Linq; -using System.Threading.Tasks; -using Microsoft.VisualStudio.TestTools.UnitTesting; - -namespace Microsoft.Identity.Test.Common.Core.Helpers -{ - public static class AssertException - { - public static void DoesNotThrow(Action testCode) - { - var ex = Recorder.Exception(testCode); - if (ex != null) - { - throw new AssertFailedException("DoesNotThrow failed - - an exception was thrown {ex}", ex); - } - } - - public static void DoesNotThrow(Func testCode) - { - var ex = Recorder.Exception(testCode); - if (ex != null) - { - throw new AssertFailedException($"DoesNotThrow failed - an exception was thrown {ex}", ex); - } - } - - public static TException Throws(Action testCode) - where TException : Exception - { - return Throws(testCode, false); - } - - public static TException Throws(Action testCode, bool allowDerived) - where TException : Exception - { - var exception = Recorder.Exception(testCode); - - if (exception == null) - { - throw new AssertFailedException("AssertExtensions.Throws failed. No exception occurred."); - } - - CheckExceptionType(exception, allowDerived); - - return exception; - } - - public static TException Throws(Func testCode) - where TException : Exception - { - return Throws(testCode, false); - } - - public static TException Throws(Func testCode, bool allowDerived) - where TException : Exception - { - var exception = Recorder.Exception(testCode); - - if (exception == null) - { - throw new AssertFailedException("AssertExtensions.Throws failed. No exception occurred."); - } - - CheckExceptionType(exception, allowDerived); - - return exception; - } - - public static async Task TaskThrowsAsync(Func testCode, bool allowDerived = false) - where T : Exception - { - Exception exception = null; - try - { - await testCode().ConfigureAwait(false); - } - catch (Exception ex) - { - exception = ex; - } - - if (exception == null) - { - throw new AssertFailedException("AssertExtensions.TaskThrowsAsync failed. No exception occurred."); - } - - if (exception is AggregateException aggEx) - { - if (aggEx.InnerException.GetType() == typeof(AssertFailedException)) - { - throw aggEx.InnerException; - } - - var exceptionsMatching = aggEx.InnerExceptions.OfType().ToList(); - - if (!exceptionsMatching.Any()) - { - ThrowAssertFailedForExceptionMismatch(typeof(T), exception); - } - - return exceptionsMatching.First(); - } - - CheckExceptionType(exception, allowDerived); - - return (exception as T); - } - - public static void TaskDoesNotThrow(Func testCode) - { - var exception = Recorder.Exception(() => testCode().Wait()); - - if (exception == null) - { - return; - } - - throw new AssertFailedException( - string.Format( - CultureInfo.CurrentCulture, - "AssertExtensions.TaskDoesNotThrow failed. Incorrect exception {0} occurred. Details {1}", - exception.GetType().Name, - exception), - exception); - } - - public static void TaskDoesNotThrow(Func testCode) where T : Exception - { - var exception = Recorder.Exception(() => testCode().Wait()); - - if (exception == null) - { - return; - } - - var exceptionsMatching = exception.InnerExceptions.OfType().ToList(); - - if (!exceptionsMatching.Any()) - { - return; - } - - ThrowAssertFailedForExceptionMismatch(typeof(T), exception); - } - - private static void CheckExceptionType(Exception actualException, bool allowDerived) - { - Type expectedType = typeof(TException); - - if (allowDerived) - { - if (!(actualException is TException)) - { - ThrowAssertFailedForExceptionMismatch(expectedType, actualException); - } - } - else - { - if (!expectedType.Equals(actualException.GetType())) - { - ThrowAssertFailedForExceptionMismatch(expectedType, actualException); - } - } - } - - private static void ThrowAssertFailedForExceptionMismatch(Type expectedExceptionType, Exception actualException) - { - Trace.TraceError("Exception match failed. Actual exception is: " + actualException); - throw new AssertFailedException( - string.Format( - CultureInfo.CurrentCulture, - "Exception types do not match. Expected: {0} Actual: {1}. Actual exception details: {2}", - expectedExceptionType.Name, - actualException.GetType().Name, - actualException), - actualException); - } - - private static class Recorder - { - public static Exception Exception(Action code) - { - try - { - code(); - return null; - } - catch (Exception e) - { - return e; - } - } - - public static TException Exception(Action code) - where TException : Exception - { - try - { - code(); - return null; - } - catch (TException ex) - { - return ex; - } - catch (Exception e) - { - throw new AssertFailedException( - $"Expected to capture a {typeof(TException)} exception but got {e.GetType()}. Details {e}", - e); - } - } - - public static TException Exception(Func code) - where TException : Exception - { - try - { - code(); - return null; - } - catch (TException ex) - { - return ex; - } - catch (Exception e) - { - throw new AssertFailedException( - $"Expected to capture a {typeof(TException)} exception but got {e.GetType()}. Details {e}", - e); - } - } - } - } -} - diff --git a/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/CancellationTests.cs b/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/CancellationTests.cs index 309e88d15a..dd7c11c21c 100644 --- a/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/CancellationTests.cs +++ b/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/CancellationTests.cs @@ -70,7 +70,7 @@ public async Task DefaultOsBrowser_IsCancellable_StartsCancelled_Async() private async Task ValidateOperationCancelledAsync(string redirectUri, CancellationTokenSource cts, System.Runtime.CompilerServices.ConfiguredTaskAwaitable tokenTask) { // Assert - var ex = await AssertException.TaskThrowsAsync(async () => + var ex = await Assert.ThrowsExceptionAsync(async () => { await tokenTask; return; @@ -111,3 +111,4 @@ private void ValidatePortIsFree(int port) } } + diff --git a/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/GenericAuthorityTests.cs b/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/GenericAuthorityTests.cs index 8de3c572c9..1e389263f3 100644 --- a/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/GenericAuthorityTests.cs +++ b/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/GenericAuthorityTests.cs @@ -54,7 +54,7 @@ public async Task BadSecret_Duende_Async() .WithClientSecret("bad_secret") .Build(); - var ex = await AssertException.TaskThrowsAsync(() => + var ex = await Assert.ThrowsExceptionAsync(() => app.AcquireTokenForClient(new[] { "api" }).ExecuteAsync()).ConfigureAwait(false); Assert.AreEqual("invalid_client", ex.ErrorCode); @@ -112,3 +112,4 @@ private Task GetPrivateKeyJwtClientAssertionAsync(string optionsClientId } } } + diff --git a/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/InstanceDiscoveryIntegrationTests.cs b/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/InstanceDiscoveryIntegrationTests.cs index f2e1c90d16..aa906d05c5 100644 --- a/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/InstanceDiscoveryIntegrationTests.cs +++ b/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/InstanceDiscoveryIntegrationTests.cs @@ -81,7 +81,7 @@ public async Task FailedAuthorityValidationTestAsync() Trace.WriteLine("Acquire a token using a not so common authority alias"); #pragma warning disable CS0618 // Type or member is obsolete - MsalServiceException exception = await AssertException.TaskThrowsAsync(() => + MsalServiceException exception = await Assert.ThrowsExceptionAsync(() => pca.AcquireTokenByUsernamePassword( s_scopes, user.Upn, @@ -109,7 +109,7 @@ public async Task AuthorityValidationTestWithFalseValidateAuthorityAsync() Trace.WriteLine("Acquire a token using a not so common authority alias"); #pragma warning disable CS0618 // Type or member is obsolete - _ = await AssertException.TaskThrowsAsync(() => + _ = await Assert.ThrowsExceptionAsync(() => pca.AcquireTokenByUsernamePassword( s_scopes, user.Upn, @@ -182,3 +182,4 @@ public int GetHashCode(InstanceDiscoveryMetadataEntry obj) } } } + diff --git a/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/LongRunningOnBehalfOfTests.cs b/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/LongRunningOnBehalfOfTests.cs index ea81ef5612..9defad54f7 100644 --- a/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/LongRunningOnBehalfOfTests.cs +++ b/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/LongRunningOnBehalfOfTests.cs @@ -285,7 +285,7 @@ public async Task NormalOboThenLongRunningAcquire_WithTheSameKey_TestAsync() TokenCacheHelper.ExpireAllAccessTokens(cca.UserTokenCacheInternal); // AcquireLR - throws because no RT - var exception = await AssertException.TaskThrowsAsync( + var exception = await Assert.ThrowsExceptionAsync( () => cca.AcquireTokenInLongRunningProcess(s_scopes.ToArray(), oboCacheKey) .ExecuteAsync()) .ConfigureAwait(false); @@ -421,7 +421,7 @@ public async Task AcquireTokenInLongRunningObo_WithNoTokensFound_TestAsync() string oboCacheKey = "obo-cache-key"; - var ex = await AssertException.TaskThrowsAsync(async () => + var ex = await Assert.ThrowsExceptionAsync(async () => await cca.AcquireTokenInLongRunningProcess(s_scopes, oboCacheKey).ExecuteAsync().ConfigureAwait(false) ).ConfigureAwait(false); @@ -440,3 +440,4 @@ private ConfidentialClientApplication BuildCCA(string tenantId) } } } + diff --git a/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/ManagedIdentityTests.NetFwk.cs b/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/ManagedIdentityTests.NetFwk.cs index e01683d62e..0d403d7c33 100644 --- a/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/ManagedIdentityTests.NetFwk.cs +++ b/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/ManagedIdentityTests.NetFwk.cs @@ -299,7 +299,7 @@ public async Task ManagedIdentityRequestFailureCheckAsync(MsiAzureResource azure IManagedIdentityApplication mia = CreateMIAWithProxy(uri, userIdentity, userAssignedIdentityId); //Act - MsalServiceException ex = await AssertException.TaskThrowsAsync(async () => + MsalServiceException ex = await Assert.ThrowsExceptionAsync(async () => { await mia .AcquireTokenForManagedIdentity(s_msi_scopes) @@ -341,7 +341,7 @@ public async Task MSIWrongScopesAsync(MsiAzureResource azureResource, string use IManagedIdentityApplication mia = CreateMIAWithProxy(uri, userIdentity, userAssignedIdentityId); //Act - MsalServiceException ex = await AssertException.TaskThrowsAsync(async () => + MsalServiceException ex = await Assert.ThrowsExceptionAsync(async () => { await mia .AcquireTokenForManagedIdentity(s_wrong_msi_scopes) @@ -500,3 +500,4 @@ private IManagedIdentityApplication CreateMIAWithProxy(string url, string userAs } } } + diff --git a/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/MsalCacheStorageIntegrationTests.cs b/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/MsalCacheStorageIntegrationTests.cs index 2f150f76fc..1975a1a458 100644 --- a/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/MsalCacheStorageIntegrationTests.cs +++ b/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/MsalCacheStorageIntegrationTests.cs @@ -196,7 +196,7 @@ public void MsalTestClear() store.ReadData(); var store2 = Storage.Create(s_storageCreationProperties, logger: _logger); - AssertException.Throws(() => store.WriteData(null)); + Assert.ThrowsException(() => store.WriteData(null)); byte[] data = { 2, 2, 3 }; store.WriteData(data); @@ -284,3 +284,4 @@ private static string ExecuteAndCaptureOutput(string cmd) } } } + diff --git a/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/OnBehalfOfTests.cs b/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/OnBehalfOfTests.cs index 27d9c92a6c..5575ed2c09 100644 --- a/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/OnBehalfOfTests.cs +++ b/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/OnBehalfOfTests.cs @@ -90,12 +90,12 @@ public async Task OboAndSilent_ReturnsCorrectTokens_TestAsync(bool serializeCach // Asserts // Silent calls should throw - await AssertException.TaskThrowsAsync(() => + await Assert.ThrowsExceptionAsync(() => cca.AcquireTokenSilent(s_scopes, user1AuthResult.Account) .ExecuteAsync(CancellationToken.None) ).ConfigureAwait(false); - await AssertException.TaskThrowsAsync(() => + await Assert.ThrowsExceptionAsync(() => cca.AcquireTokenSilent(s_scopes, user2AuthResult.Account) .ExecuteAsync(CancellationToken.None) ).ConfigureAwait(false); @@ -135,12 +135,12 @@ await AssertException.TaskThrowsAsync(() => Assert.HasCount(2, oboTokens); // Silent calls should throw - await AssertException.TaskThrowsAsync(() => + await Assert.ThrowsExceptionAsync(() => cca.AcquireTokenSilent(s_scopes, user1AuthResult.Account) .ExecuteAsync(CancellationToken.None) ).ConfigureAwait(false); - await AssertException.TaskThrowsAsync(() => + await Assert.ThrowsExceptionAsync(() => cca.AcquireTokenSilent(s_scopes, user2AuthResult.Account) .ExecuteAsync(CancellationToken.None) ).ConfigureAwait(false); @@ -533,3 +533,4 @@ private ConfidentialClientApplication BuildCca(string tenantId, bool withRegion } } } + diff --git a/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/RuntimeBrokerTests.cs b/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/RuntimeBrokerTests.cs index 8aa09f48cd..c3f23c8d32 100644 --- a/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/RuntimeBrokerTests.cs +++ b/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/RuntimeBrokerTests.cs @@ -157,7 +157,7 @@ public async Task WamInvalidROPC_ThrowsException_TestAsync() .Build(); #pragma warning disable CS0618 // Type or member is obsolete - MsalServiceException ex = await AssertException.TaskThrowsAsync(() => + MsalServiceException ex = await Assert.ThrowsExceptionAsync(() => pca.AcquireTokenByUsernamePassword( scopes, "noUser", @@ -254,7 +254,7 @@ public async Task WamUsernamePasswordRequestAsync() Assert.IsNotNull(accounts); - await AssertException.TaskThrowsAsync( + await Assert.ThrowsExceptionAsync( () => pca.AcquireTokenSilent(scopes, account).ExecuteAsync()) .ConfigureAwait(false); } @@ -468,7 +468,7 @@ public async Task WamAddDefaultScopesWhenNoScopesArePassedAsync(string scopes) // Act if (SharedUtilities.IsLinuxPlatform()) { - var exLinux = await AssertException.TaskThrowsAsync( + var exLinux = await Assert.ThrowsExceptionAsync( () => pca.AcquireTokenSilent(new string[] { scopes }, PublicClientApplication.OperatingSystemAccount) .ExecuteAsync()) .ConfigureAwait(false); @@ -476,7 +476,7 @@ public async Task WamAddDefaultScopesWhenNoScopesArePassedAsync(string scopes) } else { - var ex = await AssertException.TaskThrowsAsync( + var ex = await Assert.ThrowsExceptionAsync( () => pca.AcquireTokenSilent(new string[] { scopes }, PublicClientApplication.OperatingSystemAccount) .ExecuteAsync()) .ConfigureAwait(false); @@ -554,3 +554,4 @@ await pca.AcquireTokenByUsernamePassword(scopes, labResponse.User.Upn, labRespon } } #endif + diff --git a/tests/Microsoft.Identity.Test.Integration.netcore/SeleniumTests/FociTests.cs b/tests/Microsoft.Identity.Test.Integration.netcore/SeleniumTests/FociTests.cs index ebd72d706f..11ad15e438 100644 --- a/tests/Microsoft.Identity.Test.Integration.netcore/SeleniumTests/FociTests.cs +++ b/tests/Microsoft.Identity.Test.Integration.netcore/SeleniumTests/FociTests.cs @@ -87,7 +87,7 @@ public async Task FociSignInSignOutAsync() userCacheAccess3.AssertAccessCounts(0, 0); Trace.WriteLine("Apps that are not part of the family cannot get tokens this way."); - await AssertException.TaskThrowsAsync(() => pca_nonFam + await Assert.ThrowsExceptionAsync(() => pca_nonFam .AcquireTokenSilent(s_scopes, user.Upn) .ExecuteAsync()) .ConfigureAwait(false); @@ -160,3 +160,4 @@ private static void SetCacheSerializationToFile(IPublicClientApplication pca, st } } } + diff --git a/tests/Microsoft.Identity.Test.Integration.netcore/SeleniumTests/SeleniumInfrastructureTests.NetFwk.cs b/tests/Microsoft.Identity.Test.Integration.netcore/SeleniumTests/SeleniumInfrastructureTests.NetFwk.cs index b0c6b46988..346b4027f3 100644 --- a/tests/Microsoft.Identity.Test.Integration.netcore/SeleniumTests/SeleniumInfrastructureTests.NetFwk.cs +++ b/tests/Microsoft.Identity.Test.Integration.netcore/SeleniumTests/SeleniumInfrastructureTests.NetFwk.cs @@ -80,7 +80,7 @@ public async Task FailingTest_SeleniumFailureAsync() // The exception propagated to the test should be Selenium exception, // the test should not wait for the TCP listener to time out - await AssertException.TaskThrowsAsync(() => pca + await Assert.ThrowsExceptionAsync(() => pca .AcquireTokenInteractive(s_scopes) .WithCustomWebUi(seleniumLogic) .ExecuteAsync(CancellationToken.None)) @@ -106,7 +106,7 @@ public async Task FailingTest_ListenerTimesOut_Async() // The exception propagated to the test should be Selenium exception, // the test should not wait for the TCP listener to time out - var ex = await AssertException.TaskThrowsAsync(() => pca + var ex = await Assert.ThrowsExceptionAsync(() => pca .AcquireTokenInteractive(s_scopes) .WithCustomWebUi(seleniumLogic) .ExecuteAsync(new CancellationTokenSource(TimeSpan.FromSeconds(2)).Token)) @@ -120,3 +120,4 @@ public async Task FailingTest_ListenerTimesOut_Async() } } + diff --git a/tests/Microsoft.Identity.Test.Unit/ApiConfigTests/AcquireTokenInteractiveBuilderTests.cs b/tests/Microsoft.Identity.Test.Unit/ApiConfigTests/AcquireTokenInteractiveBuilderTests.cs index c2d677c1e8..dbc1f897a1 100644 --- a/tests/Microsoft.Identity.Test.Unit/ApiConfigTests/AcquireTokenInteractiveBuilderTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/ApiConfigTests/AcquireTokenInteractiveBuilderTests.cs @@ -143,7 +143,7 @@ await AcquireTokenInteractiveParameterBuilder.Create(_harness.Executor, TestCons public async Task TestAcquireTokenInteractive_EmbeddedAndSystemOptions_Async() { var options = new SystemWebViewOptions(); - var ex = await AssertException.TaskThrowsAsync(() => + var ex = await Assert.ThrowsExceptionAsync(() => AcquireTokenInteractiveParameterBuilder.Create(_harness.Executor, TestConstants.s_scope) .WithSystemWebViewOptions(options) @@ -213,3 +213,4 @@ await AcquireTokenInteractiveParameterBuilder.Create(_harness.Executor, TestCons } } } + diff --git a/tests/Microsoft.Identity.Test.Unit/ApiConfigTests/AuthorityTests.cs b/tests/Microsoft.Identity.Test.Unit/ApiConfigTests/AuthorityTests.cs index bf09c87ea3..86f9de9445 100644 --- a/tests/Microsoft.Identity.Test.Unit/ApiConfigTests/AuthorityTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/ApiConfigTests/AuthorityTests.cs @@ -362,7 +362,7 @@ public void VerifyAuthorityTest() public async Task AuthorityMismatchTestAsync() { _testRequestContext.ServiceBundle.Config.Authority = s_utidAuthority; - var ex = await AssertException.TaskThrowsAsync( + var ex = await Assert.ThrowsExceptionAsync( () => Authority.CreateAuthorityForRequestAsync(_testRequestContext, s_b2cAuthority.AuthorityInfo, null)) .ConfigureAwait(false); @@ -475,3 +475,4 @@ private static void VerifyAuthority( } } } + diff --git a/tests/Microsoft.Identity.Test.Unit/AppConfigTests/ConfidentialClientApplicationBuilderTests.cs b/tests/Microsoft.Identity.Test.Unit/AppConfigTests/ConfidentialClientApplicationBuilderTests.cs index baaef1c085..a334ebbf50 100644 --- a/tests/Microsoft.Identity.Test.Unit/AppConfigTests/ConfidentialClientApplicationBuilderTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/AppConfigTests/ConfidentialClientApplicationBuilderTests.cs @@ -399,7 +399,7 @@ public void TestConstructor_WithValidInstanceDicoveryMetadata() public void TestConstructor_InstanceMetadata_ValidateAuthority_MutuallyExclusive() { string instanceMetadataJson = File.ReadAllText(ResourceHelper.GetTestResourceRelativePath("CustomInstanceMetadata.json")); - var ex = AssertException.Throws(() => ConfidentialClientApplicationBuilder.Create(TestConstants.ClientId) + var ex = Assert.ThrowsException(() => ConfidentialClientApplicationBuilder.Create(TestConstants.ClientId) .WithInstanceDiscoveryMetadata(instanceMetadataJson) .WithClientSecret("cats") .WithAuthority("https://some.authority/bogus/", true) @@ -410,7 +410,7 @@ public void TestConstructor_InstanceMetadata_ValidateAuthority_MutuallyExclusive [TestMethod] public void TestConstructor_BadInstanceMetadata() { - var ex = AssertException.Throws(() => ConfidentialClientApplicationBuilder.Create(TestConstants.ClientId) + var ex = Assert.ThrowsException(() => ConfidentialClientApplicationBuilder.Create(TestConstants.ClientId) .WithInstanceDiscoveryMetadata("{bad_json_metadata") .WithClientSecret("cats") .Build()); @@ -501,7 +501,7 @@ public async Task Claims_Fail_WhenClaimsIsNotJson_Async() .WithClientCapabilities(TestConstants.ClientCapabilities) .BuildConcrete(); - var ex = await AssertException.TaskThrowsAsync( + var ex = await Assert.ThrowsExceptionAsync( () => app .AcquireTokenForClient(TestConstants.s_scope) .WithClaims("claims_that_are_not_json") @@ -512,3 +512,4 @@ public async Task Claims_Fail_WhenClaimsIsNotJson_Async() } } } + diff --git a/tests/Microsoft.Identity.Test.Unit/AppConfigTests/PublicClientApplicationBuilderTests.cs b/tests/Microsoft.Identity.Test.Unit/AppConfigTests/PublicClientApplicationBuilderTests.cs index e24cc9ce63..2498473f44 100644 --- a/tests/Microsoft.Identity.Test.Unit/AppConfigTests/PublicClientApplicationBuilderTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/AppConfigTests/PublicClientApplicationBuilderTests.cs @@ -158,7 +158,7 @@ public void TestConstructor_WithValidInstanceDicoveryMetadata() public void TestConstructor_InstanceMetadata_ValidateAuthority_MutuallyExclusive() { string instanceMetadataJson = File.ReadAllText(ResourceHelper.GetTestResourceRelativePath("CustomInstanceMetadata.json")); - var ex = AssertException.Throws(() => PublicClientApplicationBuilder.Create(TestConstants.ClientId) + var ex = Assert.ThrowsException(() => PublicClientApplicationBuilder.Create(TestConstants.ClientId) .WithInstanceDiscoveryMetadata(instanceMetadataJson) .WithAuthority("https://some.authority/bogus/", true) .Build()); @@ -168,7 +168,7 @@ public void TestConstructor_InstanceMetadata_ValidateAuthority_MutuallyExclusive [TestMethod] public void TestConstructor_InstanceMetadataUri_ValidateAuthority_MutuallyExclusive() { - var ex = AssertException.Throws(() => PublicClientApplicationBuilder.Create(TestConstants.ClientId) + var ex = Assert.ThrowsException(() => PublicClientApplicationBuilder.Create(TestConstants.ClientId) .WithInstanceDiscoveryMetadata(new Uri("https://some_uri.com")) .WithAuthority("https://some.authority/bogus/", true) .Build()); @@ -180,7 +180,7 @@ public void TestConstructor_InstanceMetadataUri_ValidateAuthority_MutuallyExclus public void TestConstructor_WithInstanceDiscoveryMetadata_OnlyOneOverload() { string instanceMetadataJson = File.ReadAllText(ResourceHelper.GetTestResourceRelativePath("CustomInstanceMetadata.json")); - var ex = AssertException.Throws(() => PublicClientApplicationBuilder.Create(TestConstants.ClientId) + var ex = Assert.ThrowsException(() => PublicClientApplicationBuilder.Create(TestConstants.ClientId) .WithInstanceDiscoveryMetadata(instanceMetadataJson) .WithInstanceDiscoveryMetadata(new Uri("https://some_uri.com")) .WithAuthority("https://some.authority/bogus/", true) @@ -191,7 +191,7 @@ public void TestConstructor_WithInstanceDiscoveryMetadata_OnlyOneOverload() [TestMethod] public void TestConstructor_BadInstanceMetadata() { - var ex = AssertException.Throws(() => PublicClientApplicationBuilder.Create(TestConstants.ClientId) + var ex = Assert.ThrowsException(() => PublicClientApplicationBuilder.Create(TestConstants.ClientId) .WithInstanceDiscoveryMetadata("{bad_json_metadata") .Build()); @@ -451,39 +451,39 @@ public void TestAuthorityWithTenant() [TestMethod] public void AuthorityNullArgs() { - AssertException.Throws(() => + Assert.ThrowsException(() => PublicClientApplicationBuilder.Create(TestConstants.ClientId) .WithAuthority((Uri)null)); - AssertException.Throws(() => + Assert.ThrowsException(() => PublicClientApplicationBuilder.Create(TestConstants.ClientId) .WithAuthority((string)null)); - AssertException.Throws(() => + Assert.ThrowsException(() => PublicClientApplicationBuilder.Create(TestConstants.ClientId) .WithAuthority(" ")); - AssertException.Throws(() => + Assert.ThrowsException(() => PublicClientApplicationBuilder.Create(TestConstants.ClientId) .WithAuthority(null, "tid")); - AssertException.Throws(() => + Assert.ThrowsException(() => PublicClientApplicationBuilder.Create(TestConstants.ClientId) .WithAuthority("", "tid")); - AssertException.Throws(() => + Assert.ThrowsException(() => PublicClientApplicationBuilder.Create(TestConstants.ClientId) .WithAuthority("", Guid.NewGuid())); - AssertException.Throws(() => + Assert.ThrowsException(() => PublicClientApplicationBuilder.Create(TestConstants.ClientId) .WithAuthority("https://login.microsoftonline.com/", null)); - AssertException.Throws(() => + Assert.ThrowsException(() => PublicClientApplicationBuilder.Create(TestConstants.ClientId) .WithAuthority("https://login.microsoftonline.com/", " ")); - AssertException.Throws(() => + Assert.ThrowsException(() => PublicClientApplicationBuilder.Create(TestConstants.ClientId) .WithAuthority(AzureCloudInstance.AzureChina, "")); } @@ -635,3 +635,4 @@ public void IsBrokerAvailable_NoAuthorityInBuilder() } } } + diff --git a/tests/Microsoft.Identity.Test.Unit/AppTokenProviderTests.cs b/tests/Microsoft.Identity.Test.Unit/AppTokenProviderTests.cs index 5424edc8c7..e8cb8950d5 100644 --- a/tests/Microsoft.Identity.Test.Unit/AppTokenProviderTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/AppTokenProviderTests.cs @@ -240,10 +240,11 @@ public async Task CanceledRequest_ThrowsTaskCanceledExceptionAsync() var tokenSource = new CancellationTokenSource(); tokenSource.Cancel(); - await AssertException.TaskThrowsAsync( + await Assert.ThrowsExceptionAsync( () => app.AcquireTokenForClient(TestConstants.s_scope) .WithForceRefresh(true) .ExecuteAsync(tokenSource.Token)).ConfigureAwait(false); } } } + diff --git a/tests/Microsoft.Identity.Test.Unit/AuthScheme/SSHCertTests.cs b/tests/Microsoft.Identity.Test.Unit/AuthScheme/SSHCertTests.cs index 208f25aa33..f2fa86dad1 100644 --- a/tests/Microsoft.Identity.Test.Unit/AuthScheme/SSHCertTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/AuthScheme/SSHCertTests.cs @@ -18,17 +18,17 @@ public class SSHCertTests [TestMethod] public void NullArgs() { - AssertException.Throws(() => new SSHCertAuthenticationOperation(null, "jwk")); - AssertException.Throws(() => new SSHCertAuthenticationOperation("", "jwk")); - AssertException.Throws(() => new SSHCertAuthenticationOperation("kid", "")); - AssertException.Throws(() => new SSHCertAuthenticationOperation("kid", null)); + Assert.ThrowsException(() => new SSHCertAuthenticationOperation(null, "jwk")); + Assert.ThrowsException(() => new SSHCertAuthenticationOperation("", "jwk")); + Assert.ThrowsException(() => new SSHCertAuthenticationOperation("kid", "")); + Assert.ThrowsException(() => new SSHCertAuthenticationOperation("kid", null)); } [TestMethod] public void NoAuthPrefix() { var scheme = new SSHCertAuthenticationOperation("kid", "jwk"); - MsalClientException ex = AssertException.Throws(() => scheme.AuthorizationHeaderPrefix); + MsalClientException ex = Assert.ThrowsException(() => scheme.AuthorizationHeaderPrefix); Assert.AreEqual(MsalError.SSHCertUsedAsHttpHeader, ex.ErrorCode); } @@ -46,3 +46,4 @@ public void ParamsAndKeyId() } } } + diff --git a/tests/Microsoft.Identity.Test.Unit/BrokerTests/BrokerRequestTests.cs b/tests/Microsoft.Identity.Test.Unit/BrokerTests/BrokerRequestTests.cs index c6a0f5dff8..ae7c6220d9 100644 --- a/tests/Microsoft.Identity.Test.Unit/BrokerTests/BrokerRequestTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/BrokerTests/BrokerRequestTests.cs @@ -268,7 +268,7 @@ public void BrokerGetAccountsAsyncOnUnsupportedPlatformTest() { IBroker broker = harness.ServiceBundle.PlatformProxy.CreateBroker(harness.ServiceBundle.Config, null); - AssertException.TaskThrowsAsync( + Assert.ThrowsExceptionAsync( () => broker.GetAccountsAsync( TestConstants.ClientId, TestConstants.RedirectUri, @@ -286,7 +286,7 @@ public void BrokerRemoveAccountAsyncOnUnsupportedPlatformTest() { IBroker broker = harness.ServiceBundle.PlatformProxy.CreateBroker(harness.ServiceBundle.Config, null); - AssertException.TaskThrowsAsync(() => broker.RemoveAccountAsync( + Assert.ThrowsExceptionAsync(() => broker.RemoveAccountAsync( harness.ServiceBundle.Config, new Account("test", "test", "test"))).ConfigureAwait(false); } } @@ -1013,3 +1013,4 @@ internal static IBroker CreateBroker(Type brokerType) } } + diff --git a/tests/Microsoft.Identity.Test.Unit/BrokerTests/RuntimeBrokerTests.cs b/tests/Microsoft.Identity.Test.Unit/BrokerTests/RuntimeBrokerTests.cs index 3e50cf46b8..a5c27b12aa 100644 --- a/tests/Microsoft.Identity.Test.Unit/BrokerTests/RuntimeBrokerTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/BrokerTests/RuntimeBrokerTests.cs @@ -109,7 +109,7 @@ public async Task ThrowOnNoHandleAsync() var pca = pcaBuilder.Build(); // no window handle - throw - var ex = await AssertException.TaskThrowsAsync( + var ex = await Assert.ThrowsExceptionAsync( () => pca.AcquireTokenInteractive(new[] { "" }).ExecuteAsync()).ConfigureAwait(false); Assert.AreEqual("window_handle_required", ex.ErrorCode); @@ -120,7 +120,7 @@ public async Task ThrowOnNoHandleAsync() [TestMethod] public void HandleInstallUrl_Throws() { - AssertException.Throws(() => _wamBroker.HandleInstallUrl("http://app")); + Assert.ThrowsException(() => _wamBroker.HandleInstallUrl("http://app")); } [TestMethod] @@ -204,3 +204,4 @@ public void LogEventRaised_DoesNotLog_When_NotForLevel(Client.NativeInterop.LogL } } #endif + diff --git a/tests/Microsoft.Identity.Test.Unit/CacheExtension/MsalCacheHelperTests.cs b/tests/Microsoft.Identity.Test.Unit/CacheExtension/MsalCacheHelperTests.cs index a12b570866..14129d8e73 100644 --- a/tests/Microsoft.Identity.Test.Unit/CacheExtension/MsalCacheHelperTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/CacheExtension/MsalCacheHelperTests.cs @@ -80,7 +80,7 @@ public void ImportExport_ThrowException() cacheAccessor.Read().Throws(ex); // Act - var actualEx = AssertException.Throws( + var actualEx = Assert.ThrowsException( () => helper.LoadUnencryptedTokenCache()); // Assert @@ -90,7 +90,7 @@ public void ImportExport_ThrowException() cacheAccessor.WhenForAnyArgs(c => c.Write(default)).Throw(ex); // Act - actualEx = AssertException.Throws( + actualEx = Assert.ThrowsException( () => helper.SaveUnencryptedTokenCache(new byte[0])); // Assert @@ -353,7 +353,7 @@ public async Task RegressionTest_CorruptedCacheIsDeleted_NoEvent_Async() helper.RegisterCache(pca.UserTokenCache); // Act - var ex = await AssertException.TaskThrowsAsync( + var ex = await Assert.ThrowsExceptionAsync( () => pca.GetAccountsAsync()) .ConfigureAwait(false); @@ -540,7 +540,7 @@ public async Task EventNeedsConfigurationAsync() var helper = await MsalCacheHelper.CreateAsync(properties).ConfigureAwait(true); // event is fired asynchronously, test has to wait for it for a while - AssertException.Throws( + Assert.ThrowsException( () => helper.CacheChanged += (_, _) => { Assert.Fail("Should not fire"); @@ -548,3 +548,4 @@ public async Task EventNeedsConfigurationAsync() } } } + diff --git a/tests/Microsoft.Identity.Test.Unit/CacheExtension/MsalCacheStorageTests.cs b/tests/Microsoft.Identity.Test.Unit/CacheExtension/MsalCacheStorageTests.cs index 971de16d09..634b8b9d58 100644 --- a/tests/Microsoft.Identity.Test.Unit/CacheExtension/MsalCacheStorageTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/CacheExtension/MsalCacheStorageTests.cs @@ -52,7 +52,7 @@ public void ReadCanThrowExceptions() var storage = new Storage(s_storageCreationProperties, cacheAccessor, actualLogger); // Assert - AssertException.Throws( + Assert.ThrowsException( () => storage.ReadData()); } @@ -66,7 +66,7 @@ public void WriteCanThrowExceptions() var storage = new Storage(s_storageCreationProperties, cacheAccessor, actualLogger); // Assert - AssertException.Throws( + Assert.ThrowsException( () => storage.WriteData(new byte[0])); } @@ -83,7 +83,7 @@ public void ClearCanThrowExceptions() storage.Clear(ignoreExceptions: true); // Assert - AssertException.Throws( + Assert.ThrowsException( () => storage.Clear(ignoreExceptions: false)); } @@ -150,7 +150,7 @@ public void VerifyPersistenceThrowsInnerExceptions() cacheAccessor.Read().Throws(exception); // Act - var ex = AssertException.Throws( + var ex = Assert.ThrowsException( () => storage.VerifyPersistence()); // Assert @@ -167,7 +167,7 @@ public void VerifyPersistenceThrowsIfDataReadIsEmpty() var storage = new Storage(s_storageCreationProperties, cacheAccessor, actualLogger); // Act - var ex = AssertException.Throws( + var ex = Assert.ThrowsException( () => storage.VerifyPersistence()); // Assert @@ -185,7 +185,7 @@ public void VerifyPersistenceThrowsIfDataReadIsDiffrentFromDataWritten() cacheAccessor.Read().Returns(Encoding.UTF8.GetBytes("other_dummy_data")); // Act - var ex = AssertException.Throws( + var ex = Assert.ThrowsException( () => storage.VerifyPersistence()); // Assert @@ -224,7 +224,7 @@ public void UnprotectedOptionMutuallyExclusiveWithOtherOptions() builder = builder.WithMacKeyChain(serviceName: "Microsoft.Developer.IdentityService", accountName: "MSALCache"); builder.WithUnprotectedFile(); - AssertException.Throws(() => builder.Build()); + Assert.ThrowsException(() => builder.Build()); builder = new StorageCreationPropertiesBuilder( Path.GetFileName(CacheFilePath), @@ -237,7 +237,7 @@ public void UnprotectedOptionMutuallyExclusiveWithOtherOptions() attribute1: new KeyValuePair("MsalClientID", "Microsoft.Developer.IdentityService"), attribute2: new KeyValuePair("MsalClientVersion", "1.0.0.0")); builder.WithUnprotectedFile(); - AssertException.Throws(() => builder.Build()); + Assert.ThrowsException(() => builder.Build()); builder = new StorageCreationPropertiesBuilder( Path.GetFileName(CacheFilePath), @@ -245,8 +245,9 @@ public void UnprotectedOptionMutuallyExclusiveWithOtherOptions() builder.WithLinuxUnprotectedFile(); builder.WithUnprotectedFile(); - AssertException.Throws(() => builder.Build()); + Assert.ThrowsException(() => builder.Build()); } } } + diff --git a/tests/Microsoft.Identity.Test.Unit/CacheTests/CacheFailureTests.cs b/tests/Microsoft.Identity.Test.Unit/CacheTests/CacheFailureTests.cs index 383636d4ec..2c6763638b 100644 --- a/tests/Microsoft.Identity.Test.Unit/CacheTests/CacheFailureTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/CacheTests/CacheFailureTests.cs @@ -40,7 +40,7 @@ public async Task MsalOnly_FailToDeserializeTestsAsync() } }); - var ex = await AssertException.TaskThrowsAsync( + var ex = await Assert.ThrowsExceptionAsync( () => cca.AcquireTokenForClient(TestConstants.s_scope).ExecuteAsync()) .ConfigureAwait(false); @@ -55,3 +55,4 @@ public async Task MsalOnly_FailToDeserializeTestsAsync() } } + diff --git a/tests/Microsoft.Identity.Test.Unit/CacheTests/InternalCacheOptionsTests.cs b/tests/Microsoft.Identity.Test.Unit/CacheTests/InternalCacheOptionsTests.cs index 333255bedd..30c5e446b2 100644 --- a/tests/Microsoft.Identity.Test.Unit/CacheTests/InternalCacheOptionsTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/CacheTests/InternalCacheOptionsTests.cs @@ -43,25 +43,25 @@ public void OptionsAndExternalCacheAreExclusive() .Build(); app3.UserTokenCache.SetAfterAccess((_) => { }); app3.AppTokenCache.SetBeforeAccess((_) => { }); - var ex = AssertException.Throws(() => app3.UserTokenCache.SetCacheOptions(CacheOptions.EnableSharedCacheOptions)); + var ex = Assert.ThrowsException(() => app3.UserTokenCache.SetCacheOptions(CacheOptions.EnableSharedCacheOptions)); Assert.AreEqual(MsalError.StaticCacheWithExternalSerialization, ex.ErrorCode); - ex = AssertException.Throws(() => app3.AppTokenCache.SetCacheOptions(CacheOptions.EnableSharedCacheOptions)); + ex = Assert.ThrowsException(() => app3.AppTokenCache.SetCacheOptions(CacheOptions.EnableSharedCacheOptions)); Assert.AreEqual(MsalError.StaticCacheWithExternalSerialization, ex.ErrorCode); void AssertExclusivity(ITokenCache tokenCache) { - var ex = AssertException.Throws(() => tokenCache.SetAfterAccess((_) => { })); + var ex = Assert.ThrowsException(() => tokenCache.SetAfterAccess((_) => { })); Assert.AreEqual(MsalError.StaticCacheWithExternalSerialization, ex.ErrorCode); - ex = AssertException.Throws(() => tokenCache.SetBeforeAccess((_) => { })); + ex = Assert.ThrowsException(() => tokenCache.SetBeforeAccess((_) => { })); Assert.AreEqual(MsalError.StaticCacheWithExternalSerialization, ex.ErrorCode); - ex = AssertException.Throws(() => tokenCache.SetBeforeWrite((_) => { })); + ex = Assert.ThrowsException(() => tokenCache.SetBeforeWrite((_) => { })); Assert.AreEqual(MsalError.StaticCacheWithExternalSerialization, ex.ErrorCode); - ex = AssertException.Throws(() => tokenCache.SetBeforeAccessAsync((_) => Task.CompletedTask)); + ex = Assert.ThrowsException(() => tokenCache.SetBeforeAccessAsync((_) => Task.CompletedTask)); Assert.AreEqual(MsalError.StaticCacheWithExternalSerialization, ex.ErrorCode); - ex = AssertException.Throws(() => tokenCache.SetAfterAccessAsync((_) => Task.CompletedTask)); + ex = Assert.ThrowsException(() => tokenCache.SetAfterAccessAsync((_) => Task.CompletedTask)); Assert.AreEqual(MsalError.StaticCacheWithExternalSerialization, ex.ErrorCode); - ex = AssertException.Throws(() => tokenCache.SetBeforeWriteAsync((_) => Task.CompletedTask)); + ex = Assert.ThrowsException(() => tokenCache.SetBeforeWriteAsync((_) => Task.CompletedTask)); Assert.AreEqual(MsalError.StaticCacheWithExternalSerialization, ex.ErrorCode); } @@ -190,3 +190,4 @@ private async Task ClientCredsAcquireAndAssertTokenSourceA } } } + diff --git a/tests/Microsoft.Identity.Test.Unit/CacheTests/TokenCacheNotificationTests.cs b/tests/Microsoft.Identity.Test.Unit/CacheTests/TokenCacheNotificationTests.cs index 5757e27a22..32839fc790 100644 --- a/tests/Microsoft.Identity.Test.Unit/CacheTests/TokenCacheNotificationTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/CacheTests/TokenCacheNotificationTests.cs @@ -69,7 +69,7 @@ private static async Task RunAfterAccessFailureAsync( pca.UserTokenCache.SetAfterAccess(_ => { afterAccessCalled = true; }); - await AssertException.TaskThrowsAsync( + await Assert.ThrowsExceptionAsync( operationThatTouchesCache).ConfigureAwait(false); Assert.IsTrue(beforeAccessCalled); @@ -348,7 +348,7 @@ public async Task MsalOperationCanBeCancelledFromTheCacheAsync() throw new OperationCanceledException(); }); - await AssertException.TaskThrowsAsync(() => app.GetAccountsAsync()).ConfigureAwait(false); + await Assert.ThrowsExceptionAsync(() => app.GetAccountsAsync()).ConfigureAwait(false); } } @@ -579,3 +579,4 @@ await cca.AcquireTokenForClient(TestConstants.s_scope) } } } + diff --git a/tests/Microsoft.Identity.Test.Unit/CoreTests/HttpTests/HttpManagerTests.cs b/tests/Microsoft.Identity.Test.Unit/CoreTests/HttpTests/HttpManagerTests.cs index a6cadc8bb0..66b39525d4 100644 --- a/tests/Microsoft.Identity.Test.Unit/CoreTests/HttpTests/HttpManagerTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/CoreTests/HttpTests/HttpManagerTests.cs @@ -351,7 +351,7 @@ public async Task NoResiliencyIfRetryAfterHeaderPresentAsync(bool useTimeSpanRet new System.Net.Http.Headers.RetryConditionHeaderValue(TimeSpan.FromSeconds(1)) : new System.Net.Http.Headers.RetryConditionHeaderValue(DateTimeOffset.UtcNow + TimeSpan.FromMinutes(2)); - var exc = await AssertException.TaskThrowsAsync(() => + var exc = await Assert.ThrowsExceptionAsync(() => httpManager.SendRequestAsync( new Uri(TestConstants.AuthorityHomeTenant + "oauth2/token"), headers: null, @@ -443,7 +443,7 @@ public async Task TestSendPostWithHttp500TypeFailureAsync() httpManager.AddResiliencyMessageMockHandler(HttpMethod.Post, HttpStatusCode.ServiceUnavailable); } - var exc = await AssertException.TaskThrowsAsync(() => + var exc = await Assert.ThrowsExceptionAsync(() => httpManager.SendRequestAsync( new Uri(TestConstants.AuthorityHomeTenant + "oauth2/token"), headers: null, @@ -475,7 +475,7 @@ public async Task TestSendGetWithRetryOnTimeoutFailureAsync() httpManager.AddRequestTimeoutResponseMessageMockHandler(HttpMethod.Get); } - var exc = await AssertException.TaskThrowsAsync(() => + var exc = await Assert.ThrowsExceptionAsync(() => httpManager.SendRequestAsync( new Uri(TestConstants.AuthorityHomeTenant + "oauth2/token"), headers: null, @@ -508,7 +508,7 @@ public async Task TestSendPostWithRetryOnTimeoutFailureAsync() httpManager.AddRequestTimeoutResponseMessageMockHandler(HttpMethod.Post); } - var exc = await AssertException.TaskThrowsAsync(() => + var exc = await Assert.ThrowsExceptionAsync(() => httpManager.SendRequestAsync( new Uri(TestConstants.AuthorityHomeTenant + "oauth2/token"), headers: new Dictionary(), @@ -551,7 +551,7 @@ public async Task TestCorrelationIdWithRetryOnTimeoutFailureAsync(bool addCorrel headers.Add(OAuth2Header.CorrelationId, correlationId.ToString()); } - var exc = await AssertException.TaskThrowsAsync(() => + var exc = await Assert.ThrowsExceptionAsync(() => httpManager.SendRequestAsync( new Uri(TestConstants.AuthorityHomeTenant + "oauth2/token"), headers: headers, @@ -599,7 +599,7 @@ public async Task TestRetryOnTimeoutWithHeadersButNoCorrelationIdAsync() ["some-other-header"] = "some-value" }; - var exc = await AssertException.TaskThrowsAsync(() => + var exc = await Assert.ThrowsExceptionAsync(() => httpManager.SendRequestAsync( new Uri(TestConstants.AuthorityHomeTenant + "oauth2/token"), headers: headers, @@ -646,7 +646,7 @@ public async Task TestWithCorrelationId_RetryOnTimeoutFailureAsync() var userAssertion = new UserAssertion(TestConstants.DefaultAccessToken); // Act - var exc = await AssertException.TaskThrowsAsync(() => + var exc = await Assert.ThrowsExceptionAsync(() => app.AcquireTokenForClient(TestConstants.s_scope) .WithCorrelationId(correlationId) .ExecuteAsync()) @@ -669,3 +669,4 @@ protected override Task SendAsync(HttpRequestMessage reques } } } + diff --git a/tests/Microsoft.Identity.Test.Unit/CoreTests/InstanceTests/AadAuthorityTests.cs b/tests/Microsoft.Identity.Test.Unit/CoreTests/InstanceTests/AadAuthorityTests.cs index bba573706d..a871ed7ba5 100644 --- a/tests/Microsoft.Identity.Test.Unit/CoreTests/InstanceTests/AadAuthorityTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/CoreTests/InstanceTests/AadAuthorityTests.cs @@ -154,7 +154,7 @@ public void MalformedAuthorityInitTest() var host = string.Concat("test", TestConstants.ProductionPrefNetworkEnvironment, "/"); var fullAuthority = string.Concat(host, TestConstants.TenantId); - AssertException.Throws(() => + Assert.ThrowsException(() => { publicClient = PublicClientApplicationBuilder.Create(TestConstants.ClientId) .WithAuthority(fullAuthority) @@ -408,3 +408,4 @@ public async Task CreateAuthorityForRequestAsync_MSAPassthroughAsync() } } + diff --git a/tests/Microsoft.Identity.Test.Unit/CoreTests/InstanceTests/GenericAuthorityTests.cs b/tests/Microsoft.Identity.Test.Unit/CoreTests/InstanceTests/GenericAuthorityTests.cs index a9b7388249..c1db1189d0 100644 --- a/tests/Microsoft.Identity.Test.Unit/CoreTests/InstanceTests/GenericAuthorityTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/CoreTests/InstanceTests/GenericAuthorityTests.cs @@ -314,7 +314,7 @@ public async Task BadOidcResponse_ThrowsException_Async(string badOidcResponseTy var confidentailClientApp = (ConfidentialClientApplication)app; Assert.AreEqual(AuthorityType.Generic, confidentailClientApp.AuthorityInfo.AuthorityType); - var ex = await AssertException.TaskThrowsAsync(() => + var ex = await Assert.ThrowsExceptionAsync(() => app.AcquireTokenForClient(new[] { "api" }) .ExecuteAsync()) .ConfigureAwait(false); @@ -359,7 +359,7 @@ public async Task Oidc_Malformed_Failure_Async() var confidentailClientApp = (ConfidentialClientApplication)app; Assert.AreEqual(AuthorityType.Generic, confidentailClientApp.AuthorityInfo.AuthorityType); - var ex = await AssertException.TaskThrowsAsync(() => + var ex = await Assert.ThrowsExceptionAsync(() => app.AcquireTokenForClient(new[] { "api" }) .ExecuteAsync()) .ConfigureAwait(false); @@ -374,7 +374,7 @@ public async Task Oidc_Malformed_Failure_Async() AadErrorCode: Constants.AadMissingScopeErrorCode, expectedUrl: $"{TestConstants.CiamCUDAuthorityMalformed}/connect/token"); - ex = await AssertException.TaskThrowsAsync(() => + ex = await Assert.ThrowsExceptionAsync(() => app.AcquireTokenForClient(new[] { "api" }) .ExecuteAsync()) .ConfigureAwait(false); @@ -463,7 +463,7 @@ public async Task OidcIssuerValidation_ThrowsForNonMatchingIssuer_Async() ResponseMessage = MockHelpers.CreateSuccessResponseMessage(validOidcDocumentWithWrongIssuer) }); - var ex = await AssertException.TaskThrowsAsync(() => + var ex = await Assert.ThrowsExceptionAsync(() => app.AcquireTokenForClient(new[] { "api" }).ExecuteAsync() ).ConfigureAwait(false); @@ -543,3 +543,4 @@ private static MockHttpMessageHandler CreateOidcHttpHandler(string oidcEndpoint, } } } + diff --git a/tests/Microsoft.Identity.Test.Unit/CoreTests/InstanceTests/InstanceDiscoveryManagerTests.cs b/tests/Microsoft.Identity.Test.Unit/CoreTests/InstanceTests/InstanceDiscoveryManagerTests.cs index 68ff2e638f..ed94dad663 100644 --- a/tests/Microsoft.Identity.Test.Unit/CoreTests/InstanceTests/InstanceDiscoveryManagerTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/CoreTests/InstanceTests/InstanceDiscoveryManagerTests.cs @@ -217,7 +217,7 @@ public async Task AuthorityValidationFailure_IsRethrown_Async() .Do(_ => throw validationException); // Act - var actualException = await AssertException.TaskThrowsAsync(() => + var actualException = await Assert.ThrowsExceptionAsync(() => _discoveryManager.GetMetadataEntryAsync( AuthorityInfo.FromAuthorityUri("https://some_env.com/tid", true), _testRequestContext)) @@ -450,3 +450,4 @@ private static void ValidateSingleEntryMetadata(Uri authority, InstanceDiscovery } } } + diff --git a/tests/Microsoft.Identity.Test.Unit/CoreTests/OAuth2Tests/ClaimsTest.cs b/tests/Microsoft.Identity.Test.Unit/CoreTests/OAuth2Tests/ClaimsTest.cs index 50e6a32c27..c324cb9a38 100644 --- a/tests/Microsoft.Identity.Test.Unit/CoreTests/OAuth2Tests/ClaimsTest.cs +++ b/tests/Microsoft.Identity.Test.Unit/CoreTests/OAuth2Tests/ClaimsTest.cs @@ -232,7 +232,7 @@ public async Task Claims_Fail_WhenClaimsIsNotJson_Async() .WithClientCapabilities(TestConstants.ClientCapabilities) .BuildConcrete(); - var ex = await AssertException.TaskThrowsAsync( + var ex = await Assert.ThrowsExceptionAsync( () => app .AcquireTokenInteractive(TestConstants.s_scope) .WithClaims("claims_that_are_not_json") @@ -251,3 +251,4 @@ public void ClaimsMerge_Test(string claims, string[] capabilities, string expect } } } + diff --git a/tests/Microsoft.Identity.Test.Unit/CoreTests/WsTrustTests/WsTrustTests.cs b/tests/Microsoft.Identity.Test.Unit/CoreTests/WsTrustTests/WsTrustTests.cs index ac1ab08d64..c33a6bd147 100644 --- a/tests/Microsoft.Identity.Test.Unit/CoreTests/WsTrustTests/WsTrustTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/CoreTests/WsTrustTests/WsTrustTests.cs @@ -159,7 +159,7 @@ public async Task WsTrustRequestTokenNotFoundInResponseTestAsync() var message = endpoint.BuildTokenRequestMessageWindowsIntegratedAuth("urn:federation:SomeAudience"); - var ex = await AssertException.TaskThrowsAsync(() => + var ex = await Assert.ThrowsExceptionAsync(() => harness.ServiceBundle.WsTrustWebRequestManager.GetWsTrustResponseAsync(endpoint, message, requestContext)).ConfigureAwait(false); Assert.AreEqual(MsalError.ParsingWsTrustResponseFailed, ex.ErrorCode); @@ -167,3 +167,4 @@ public async Task WsTrustRequestTokenNotFoundInResponseTestAsync() } } } + diff --git a/tests/Microsoft.Identity.Test.Unit/CryptographyTests.cs b/tests/Microsoft.Identity.Test.Unit/CryptographyTests.cs index 057b4368bf..76823ce1d1 100644 --- a/tests/Microsoft.Identity.Test.Unit/CryptographyTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/CryptographyTests.cs @@ -43,7 +43,7 @@ public void SignWithNonRsaCertificate_ThrowsException() var crypto = serviceBundle.PlatformProxy.CryptographyManager; - MsalClientException ex = AssertException.Throws(() => + MsalClientException ex = Assert.ThrowsException(() => { crypto.SignWithCertificate("TEST", cert, RSASignaturePadding.Pkcs1); }); @@ -53,3 +53,4 @@ public void SignWithNonRsaCertificate_ThrowsException() } } } + diff --git a/tests/Microsoft.Identity.Test.Unit/ExceptionTests/ExperimentalFeatureTests.cs b/tests/Microsoft.Identity.Test.Unit/ExceptionTests/ExperimentalFeatureTests.cs index c6603d7ee8..63f491adc0 100644 --- a/tests/Microsoft.Identity.Test.Unit/ExceptionTests/ExperimentalFeatureTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/ExceptionTests/ExperimentalFeatureTests.cs @@ -31,7 +31,7 @@ public async Task ExperimentalFeatureExceptionAsync() .Create(Guid.NewGuid().ToString()) .WithCertificate(CertHelper.GetOrCreateTestCert()).Build(); - MsalClientException ex = await AssertException.TaskThrowsAsync( + MsalClientException ex = await Assert.ThrowsExceptionAsync( () => cca.AcquireTokenForClient(s_scopes) .WithSignedHttpRequestProofOfPossession(popConfig).ExecuteAsync()) .ConfigureAwait(false); @@ -41,3 +41,4 @@ public async Task ExperimentalFeatureExceptionAsync() #endif } } + diff --git a/tests/Microsoft.Identity.Test.Unit/ExceptionTests/MsalExceptionTests.cs b/tests/Microsoft.Identity.Test.Unit/ExceptionTests/MsalExceptionTests.cs index 16162dd9b5..96d31c62f8 100644 --- a/tests/Microsoft.Identity.Test.Unit/ExceptionTests/MsalExceptionTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/ExceptionTests/MsalExceptionTests.cs @@ -39,13 +39,13 @@ public class MsalExceptionTests : TestBase [TestMethod] public void ParamValidation() { - AssertException.Throws(() => new MsalClientException(null, ExMessage)); - AssertException.Throws(() => new MsalClientException(string.Empty, ExMessage)); + Assert.ThrowsException(() => new MsalClientException(null, ExMessage)); + Assert.ThrowsException(() => new MsalClientException(string.Empty, ExMessage)); - AssertException.Throws( + Assert.ThrowsException( () => new MsalServiceException(ExCode, string.Empty)); - AssertException.Throws( + Assert.ThrowsException( () => new MsalServiceException(ExCode, null)); } @@ -444,7 +444,7 @@ public async Task CorrelationIdInServiceExceptions() .Create(TestConstants.ClientId) .WithDefaultRedirectUri() .Build(); - var ex = await AssertException.TaskThrowsAsync(async () => + var ex = await Assert.ThrowsExceptionAsync(async () => { await app.AcquireTokenSilent(TestConstants.s_graphScopes, TestConstants.s_user).ExecuteAsync().ConfigureAwait(false); } @@ -454,7 +454,7 @@ public async Task CorrelationIdInServiceExceptions() Assert.IsFalse(string.IsNullOrEmpty(((MsalException)ex).CorrelationId)); Guid guid = Guid.NewGuid(); - ex = await AssertException.TaskThrowsAsync(async () => + ex = await Assert.ThrowsExceptionAsync(async () => { await app.AcquireTokenSilent(TestConstants.s_graphScopes, TestConstants.s_user).WithCorrelationId(guid).ExecuteAsync().ConfigureAwait(false); } @@ -495,7 +495,7 @@ await app.AcquireTokenForClient(TestConstants.s_scope) Assert.IsFalse(string.IsNullOrEmpty(((MsalException)ex).CorrelationId)); Guid guid = Guid.NewGuid(); - ex = await AssertException.TaskThrowsAsync(async () => + ex = await Assert.ThrowsExceptionAsync(async () => { await app.AcquireTokenForClient(TestConstants.s_scope) .WithCorrelationId(guid) @@ -555,7 +555,7 @@ await app.AcquireTokenForClient(TestConstants.s_scope) .WithCertificate(certificate) .BuildConcrete(); - ex = await AssertException.TaskThrowsAsync(async () => + ex = await Assert.ThrowsExceptionAsync(async () => { await app.AcquireTokenForClient(TestConstants.s_scope) .ExecuteAsync(CancellationToken.None) @@ -571,7 +571,7 @@ await app.AcquireTokenForClient(TestConstants.s_scope) harness.HttpManager.AddRequestTimeoutResponseMessageMockHandler(HttpMethod.Post); //Ensure non 404 error codes do not trigger message - ex = await AssertException.TaskThrowsAsync(async () => + ex = await Assert.ThrowsExceptionAsync(async () => { await app.AcquireTokenForClient(TestConstants.s_scope) .WithForceRefresh(true) @@ -597,3 +597,4 @@ private void AssertPropertyHasPublicGetAndSet(Type t, string propertyName) } } } + diff --git a/tests/Microsoft.Identity.Test.Unit/ManagedIdentityTests/ImdsTests.cs b/tests/Microsoft.Identity.Test.Unit/ManagedIdentityTests/ImdsTests.cs index 43c3872ebe..5a774edad0 100644 --- a/tests/Microsoft.Identity.Test.Unit/ManagedIdentityTests/ImdsTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/ManagedIdentityTests/ImdsTests.cs @@ -381,7 +381,7 @@ public async Task ImdsRetryPolicyLifeTimeIsPerRequestAsync() } MsalServiceException ex = - await AssertException.TaskThrowsAsync(async () => + await Assert.ThrowsExceptionAsync(async () => await mi.AcquireTokenForManagedIdentity(ManagedIdentityTests.Resource) .ExecuteAsync() .ConfigureAwait(false)) @@ -401,7 +401,7 @@ await mi.AcquireTokenForManagedIdentity(ManagedIdentityTests.Resource) statusCode: HttpStatusCode.GatewayTimeout); } - ex = await AssertException.TaskThrowsAsync(async () => + ex = await Assert.ThrowsExceptionAsync(async () => await mi.AcquireTokenForManagedIdentity(ManagedIdentityTests.Resource) .ExecuteAsync() .ConfigureAwait(false)) @@ -467,3 +467,4 @@ await managedIdentityApp.AcquireTokenForManagedIdentity(ManagedIdentityTests.Res } } } + diff --git a/tests/Microsoft.Identity.Test.Unit/ManagedIdentityTests/ManagedIdentityTests.cs b/tests/Microsoft.Identity.Test.Unit/ManagedIdentityTests/ManagedIdentityTests.cs index 2a00616ea3..a1542bf6db 100644 --- a/tests/Microsoft.Identity.Test.Unit/ManagedIdentityTests/ManagedIdentityTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/ManagedIdentityTests/ManagedIdentityTests.cs @@ -1024,7 +1024,7 @@ public async Task CanceledRequest_ThrowsTaskCanceledExceptionAsync() var tokenSource = new CancellationTokenSource(); tokenSource.Cancel(); - await AssertException.TaskThrowsAsync( + await Assert.ThrowsExceptionAsync( () => app.AcquireTokenForManagedIdentity(Resource) .WithForceRefresh(true) .ExecuteAsync(tokenSource.Token)).ConfigureAwait(false); @@ -1552,3 +1552,4 @@ public void WithExtraQueryParameters_MultipleCallsMergeValues() } } } + diff --git a/tests/Microsoft.Identity.Test.Unit/OAuthClientTests.cs b/tests/Microsoft.Identity.Test.Unit/OAuthClientTests.cs index 3e886fe0c9..2155108bda 100644 --- a/tests/Microsoft.Identity.Test.Unit/OAuthClientTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/OAuthClientTests.cs @@ -247,7 +247,7 @@ private async Task ValidateOathClientAsync( harness.HttpManager, null); - Exception ex = await AssertException.TaskThrowsAsync( + Exception ex = await Assert.ThrowsExceptionAsync( () => client.ExecuteRequestAsync( requestUri, HttpMethod.Post, @@ -261,3 +261,4 @@ private async Task ValidateOathClientAsync( } } + diff --git a/tests/Microsoft.Identity.Test.Unit/PublicApiTests/AcquireTokenSilentTests.cs b/tests/Microsoft.Identity.Test.Unit/PublicApiTests/AcquireTokenSilentTests.cs index a33aa0481f..de30a04e73 100644 --- a/tests/Microsoft.Identity.Test.Unit/PublicApiTests/AcquireTokenSilentTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/PublicApiTests/AcquireTokenSilentTests.cs @@ -27,10 +27,10 @@ public async Task NullAccount_EmptyLoginHintAsync() .Create(TestConstants.ClientId) .Build(); - await AssertException.TaskThrowsAsync( + await Assert.ThrowsExceptionAsync( () => app.AcquireTokenSilent(TestConstants.s_scope.ToArray(), (string)null).ExecuteAsync()).ConfigureAwait(false); - var ex = await AssertException.TaskThrowsAsync( + var ex = await Assert.ThrowsExceptionAsync( () => app.AcquireTokenSilent(TestConstants.s_scope.ToArray(), (IAccount)null).ExecuteAsync()).ConfigureAwait(false); Assert.AreEqual(MsalError.UserNullError, ex.ErrorCode); Assert.AreEqual(UiRequiredExceptionClassification.AcquireTokenSilentFailed, ex.Classification); @@ -253,7 +253,7 @@ public async Task AcquireTokenSilent_LoginHint_NoAccountAsync() TokenCacheHelper.PopulateCache(app.UserTokenCacheInternal.Accessor); - var exception = await AssertException.TaskThrowsAsync(() => app.AcquireTokenSilent( + var exception = await Assert.ThrowsExceptionAsync(() => app.AcquireTokenSilent( TestConstants.s_scope.ToArray(), "other_login_hint@contoso.com") .ExecuteAsync()).ConfigureAwait(false); @@ -278,7 +278,7 @@ public async Task AcquireTokenSilent_LoginHint_MultipleAccountsAsync() TokenCacheHelper.PopulateCache(app.UserTokenCacheInternal.Accessor, "uid1", "utid"); TokenCacheHelper.PopulateCache(app.UserTokenCacheInternal.Accessor, "uid2", "utid"); - var exception = await AssertException.TaskThrowsAsync(async () => await app.AcquireTokenSilent( + var exception = await Assert.ThrowsExceptionAsync(async () => await app.AcquireTokenSilent( TestConstants.s_scope.ToArray(), TestConstants.DisplayableId) .ExecuteAsync().ConfigureAwait(false)).ConfigureAwait(false); @@ -302,7 +302,7 @@ public async Task AcquireTokenSilent_Account_NoHomeAccountIDAsync() TokenCacheHelper.PopulateCache(app.UserTokenCacheInternal.Accessor); - var exception = await AssertException.TaskThrowsAsync(() => app.AcquireTokenSilent( + var exception = await Assert.ThrowsExceptionAsync(() => app.AcquireTokenSilent( TestConstants.s_scope.ToArray(), new Account(null, null, null)) .ExecuteAsync()).ConfigureAwait(false); @@ -705,3 +705,4 @@ public async Task AcquireTokenSilent_OverrideWithCommon_Async() } } + diff --git a/tests/Microsoft.Identity.Test.Unit/PublicApiTests/AuthenticationOperationTests.cs b/tests/Microsoft.Identity.Test.Unit/PublicApiTests/AuthenticationOperationTests.cs index 8e80215f80..1bb78d621d 100644 --- a/tests/Microsoft.Identity.Test.Unit/PublicApiTests/AuthenticationOperationTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/PublicApiTests/AuthenticationOperationTests.cs @@ -183,7 +183,7 @@ public async Task WrongTokenType_Async() httpManager.AddSuccessTokenResponseMockHandlerForPost(TestConstants.AuthorityCommonTenant); // Act - var ex = await AssertException.TaskThrowsAsync(() => app + var ex = await Assert.ThrowsExceptionAsync(() => app .AcquireTokenInteractive(TestConstants.s_scope) .WithAuthenticationOperation(authScheme) .ExecuteAsync()).ConfigureAwait(false); @@ -467,3 +467,4 @@ await authScheme.DidNotReceive().ValidateCachedTokenAsync(Arg.Any(() => + await Assert.ThrowsExceptionAsync(() => cca.AcquireTokenForClient(TestConstants.s_scope).ExecuteAsync()) .ConfigureAwait(false); } @@ -458,7 +458,7 @@ public async Task ClientAssertion_CancellationTokenPropagatesAsync() }) .BuildConcrete(); - await AssertException.TaskThrowsAsync(() => + await Assert.ThrowsExceptionAsync(() => cca.AcquireTokenForClient(TestConstants.s_scope) .ExecuteAsync(cts.Token)) .ConfigureAwait(false); @@ -603,7 +603,7 @@ public async Task WithMtlsPop_AfterBearerDelegate_Throws() .WithClientAssertion(BearerDelegate()) .BuildConcrete(); - var ex = await AssertException.TaskThrowsAsync(() => + var ex = await Assert.ThrowsExceptionAsync(() => cca.AcquireTokenForClient(TestConstants.s_scope) .WithMtlsProofOfPossession() .ExecuteAsync()) @@ -659,7 +659,7 @@ public async Task WithMtlsPop_AfterPoPDelegate_NoRegion_ThrowsAsync() .BuildConcrete(); // Act & Assert – should fail because region is missing - var ex = await AssertException.TaskThrowsAsync(async () => + var ex = await Assert.ThrowsExceptionAsync(async () => await cca.AcquireTokenForClient(TestConstants.s_scope) .WithMtlsProofOfPossession() .ExecuteAsync() @@ -695,3 +695,4 @@ private static Func(() => + var ex = await Assert.ThrowsExceptionAsync(() => app .AcquireTokenForClient(TestConstants.s_scope) .WithAuthority("https://login.microsoft.com/17b189bc-2b81-4ec5-aa51-3e628cbc931b") @@ -483,14 +483,14 @@ public async Task MsalForceRegionIsSet_WithRegionIsSetToOptOut_NoRegionIsUsed() [TestMethod] public void WithAzureRegionThrowsOnNullArg() { - AssertException.Throws( + Assert.ThrowsException( () => ConfidentialClientApplicationBuilder .Create(TestConstants.ClientId) .WithAzureRegion(null) .WithClientSecret(TestConstants.ClientSecret) .Build()); - AssertException.Throws( + Assert.ThrowsException( () => ConfidentialClientApplicationBuilder .Create(TestConstants.ClientId) .WithAzureRegion(string.Empty) @@ -630,7 +630,7 @@ public async Task OtherCloud_WithValidation_Async(bool validateAuthority, bool a if (!authorityIsValid && validateAuthority) { - var ex = await AssertException.TaskThrowsAsync(() => app + var ex = await Assert.ThrowsExceptionAsync(() => app .AcquireTokenForClient(TestConstants.s_scope) .WithTenantId("17b189bc-2b81-4ec5-aa51-3e628cbc931b") .ExecuteAsync()).ConfigureAwait(false); @@ -800,7 +800,7 @@ public async Task AuthorityValidationHappensOnNonRegionalAuthorityAsync() .Build(); // Act - var ex = await AssertException.TaskThrowsAsync(() => app + var ex = await Assert.ThrowsExceptionAsync(() => app .AcquireTokenForClient(TestConstants.s_scope) .ExecuteAsync()) .ConfigureAwait(false); @@ -945,3 +945,4 @@ public void RegionDiscoveryThrowsException_WhenCustomMetadataAndRegionDiscoveryE } } + diff --git a/tests/Microsoft.Identity.Test.Unit/PublicApiTests/ConfidentialClientApplicationTests.cs b/tests/Microsoft.Identity.Test.Unit/PublicApiTests/ConfidentialClientApplicationTests.cs index 57bb4a260b..354a559a17 100644 --- a/tests/Microsoft.Identity.Test.Unit/PublicApiTests/ConfidentialClientApplicationTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/PublicApiTests/ConfidentialClientApplicationTests.cs @@ -413,7 +413,7 @@ public async Task ClientCreds_And_AAD_LogRequestUri_OnServerError_Async() httpManager.AddResiliencyMessageMockHandler(HttpMethod.Post, HttpStatusCode.InternalServerError, retryAfter: 0); // Acquire Token - var ex = await AssertException.TaskThrowsAsync( + var ex = await Assert.ThrowsExceptionAsync( () => cca.AcquireTokenForClient(TestConstants.s_scope.ToArray()).ExecuteAsync()) .ConfigureAwait(false); @@ -440,7 +440,7 @@ public async Task ClientCreds_And_ADFS_LogRequestUri_OnServerError_Async() httpManager.AddResiliencyMessageMockHandler(HttpMethod.Post, HttpStatusCode.InternalServerError, retryAfter: 0); // Acquire Token - var ex = await AssertException.TaskThrowsAsync( + var ex = await Assert.ThrowsExceptionAsync( () => cca.AcquireTokenForClient(TestConstants.s_scope.ToArray()).ExecuteAsync()) .ConfigureAwait(false); @@ -590,14 +590,14 @@ public async Task ClientCreds_And_Obo_DoNotAllow_EmptyScopes_Async() .Build(); // OBO - var ex = await AssertException.TaskThrowsAsync( + var ex = await Assert.ThrowsExceptionAsync( () => cca.AcquireTokenOnBehalfOf(null, new UserAssertion("assertion", "assertiontype")).ExecuteAsync()) .ConfigureAwait(false); Assert.AreEqual(MsalError.ScopesRequired, ex.ErrorCode); // Client Creds - ex = await AssertException.TaskThrowsAsync( + ex = await Assert.ThrowsExceptionAsync( () => cca.AcquireTokenForClient(null).ExecuteAsync()) .ConfigureAwait(false); @@ -817,7 +817,7 @@ public async Task ConfidentialClientUsingSignedClientAssertion_AsyncDelegate_Can var app = builder.BuildConcrete(); Assert.IsNull(app.Certificate); - await AssertException.TaskThrowsAsync( + await Assert.ThrowsExceptionAsync( () => app.AcquireTokenForClient(TestConstants.s_scope.ToArray()) .ExecuteAsync(cancellationTokenSource.Token)).ConfigureAwait(false); } @@ -910,7 +910,7 @@ public async Task AcquireTokenForClient_EmptyAssertion_ThrowsArgumentExceptionAs // Act & Assert – the first token request will execute the delegate // and should surface ArgumentException from the credential layer. - await AssertException.TaskThrowsAsync(() => + await Assert.ThrowsExceptionAsync(() => cca.AcquireTokenForClient(TestConstants.s_scope) .ExecuteAsync()) .ConfigureAwait(false); @@ -1441,7 +1441,7 @@ public async Task HttpRequestExceptionIsNotSuppressedAsync() // add mock response bigger than 1MB for HTTP Client httpManager.AddFailingRequest(new InvalidOperationException()); - await AssertException.TaskThrowsAsync( + await Assert.ThrowsExceptionAsync( () => app.AcquireTokenForClient(TestConstants.s_scope.ToArray()).ExecuteAsync(CancellationToken.None)).ConfigureAwait(false); } } @@ -2079,11 +2079,11 @@ public async Task AcquireTokenByAuthorizationCode_NullOrEmptyCode_ThrowsAsync() .BuildConcrete(); // Act & Assert - await AssertException.TaskThrowsAsync( + await Assert.ThrowsExceptionAsync( () => app.AcquireTokenByAuthorizationCode(TestConstants.s_scope, null).ExecuteAsync() ).ConfigureAwait(false); - await AssertException.TaskThrowsAsync( + await Assert.ThrowsExceptionAsync( () => app.AcquireTokenByAuthorizationCode(TestConstants.s_scope, string.Empty).ExecuteAsync() ).ConfigureAwait(false); } @@ -2197,7 +2197,7 @@ public async Task ForceRefreshAndAccessTokenHash_ThrowsException_Async() .WithAccessTokenSha256ToRefresh("dummyHash"); // Act & Assert - MsalClientException ex = await AssertException.TaskThrowsAsync(() => + MsalClientException ex = await Assert.ThrowsExceptionAsync(() => builder.ExecuteAsync() ).ConfigureAwait(false); @@ -2359,3 +2359,4 @@ private static string ComputeSHA256Hex(string token) } } } + diff --git a/tests/Microsoft.Identity.Test.Unit/PublicApiTests/MtlsPopTests.cs b/tests/Microsoft.Identity.Test.Unit/PublicApiTests/MtlsPopTests.cs index 769b1f9df9..4fb9495441 100644 --- a/tests/Microsoft.Identity.Test.Unit/PublicApiTests/MtlsPopTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/PublicApiTests/MtlsPopTests.cs @@ -57,7 +57,7 @@ public async Task MtlsPop_AadAuthorityWithoutCertificateAsync() .WithAuthority("https://login.microsoftonline.com/123456-1234-2345-1234561234") .Build(); - MsalClientException ex = await AssertException.TaskThrowsAsync(() => + MsalClientException ex = await Assert.ThrowsExceptionAsync(() => app.AcquireTokenForClient(TestConstants.s_scope) .WithMtlsProofOfPossession() // Enables MTLS PoP .ExecuteAsync()) @@ -76,7 +76,7 @@ public async Task MtlsPopWithoutCertificateAsync() .Build(); // Set WithMtlsProofOfPossession on the request without a certificate - MsalClientException ex = await AssertException.TaskThrowsAsync(() => + MsalClientException ex = await Assert.ThrowsExceptionAsync(() => app.AcquireTokenForClient(TestConstants.s_scope) .WithMtlsProofOfPossession() // Enables MTLS PoP .ExecuteAsync()) @@ -154,7 +154,7 @@ public async Task MtlsPop_WithoutRegion_ThrowsException(bool setAzureRegion) } // Set WithMtlsProofOfPossession on the request - MsalClientException ex = await AssertException.TaskThrowsAsync(() => + MsalClientException ex = await Assert.ThrowsExceptionAsync(() => app.AcquireTokenForClient(TestConstants.s_scope) .WithMtlsProofOfPossession() // Enables MTLS PoP .ExecuteAsync()) @@ -174,7 +174,7 @@ public async Task MtlsPop_WithUnsupportedNonTenantedAuthorityAsync_ThrowsExcepti .Build(); // Set WithMtlsProofOfPossession on the request without specifying an authority - MsalClientException ex = await AssertException.TaskThrowsAsync(() => + MsalClientException ex = await Assert.ThrowsExceptionAsync(() => app.AcquireTokenForClient(TestConstants.s_scope) .WithMtlsProofOfPossession() .ExecuteAsync()) @@ -836,7 +836,7 @@ public async Task MtlsPop_WithUnsupportedNonTenantedAuthorityAsyncForDsts_Throws .Build(); // Set WithMtlsProofOfPossession on the request specifying an authority - HttpRequestException ex = await AssertException.TaskThrowsAsync(() => + HttpRequestException ex = await Assert.ThrowsExceptionAsync(() => app.AcquireTokenForClient(TestConstants.s_scope) .WithMtlsProofOfPossession() .ExecuteAsync()) @@ -888,3 +888,4 @@ public async Task BindingCertificate_PopulatedForMtlsPop_AndNullForBearerAsync() } } } + diff --git a/tests/Microsoft.Identity.Test.Unit/PublicApiTests/PublicClientApplicationTests.cs b/tests/Microsoft.Identity.Test.Unit/PublicApiTests/PublicClientApplicationTests.cs index a1a5678fae..b982d0a43b 100644 --- a/tests/Microsoft.Identity.Test.Unit/PublicApiTests/PublicClientApplicationTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/PublicApiTests/PublicClientApplicationTests.cs @@ -588,7 +588,7 @@ public async Task HttpRequestExceptionIsNotSuppressedAsync() // add mock response bigger than 1MB for Http Client httpManager.AddFailingRequest(new InvalidOperationException()); - await AssertException.TaskThrowsAsync( + await Assert.ThrowsExceptionAsync( () => app .AcquireTokenInteractive(TestConstants.s_scope.ToArray()).ExecuteAsync(CancellationToken.None)) .ConfigureAwait(false); @@ -687,7 +687,7 @@ public async Task GetAccountByUserFlowTestsAsync() var accounts = app.GetAccountsAsync(TestConstants.B2CSignUpSignIn).Result; Assert.AreEqual(0, accounts.Count()); - await AssertException.TaskThrowsAsync(() => + await Assert.ThrowsExceptionAsync(() => app.GetAccountsAsync(string.Empty)).ConfigureAwait(false); accounts = PopulateB2CTokenCacheAsync(TestConstants.B2CSignUpSignIn, app).Result; @@ -845,7 +845,7 @@ public async Task AcquireTokenSilent_EmptyLoginHint_TestAsync() .Create(TestConstants.ClientId) .Build(); - await AssertException.TaskThrowsAsync(() => + await Assert.ThrowsExceptionAsync(() => app.AcquireTokenSilent(TestConstants.s_scope.ToArray(), string.Empty).ExecuteAsync()) .ConfigureAwait(false); } @@ -1258,3 +1258,4 @@ private Task> PopulateB2CTokenCacheAsync(string userFlow, } } } + diff --git a/tests/Microsoft.Identity.Test.Unit/PublicApiTests/PublicClientApplicationTestsWithB2C.cs b/tests/Microsoft.Identity.Test.Unit/PublicApiTests/PublicClientApplicationTestsWithB2C.cs index fecde47449..7782974f16 100644 --- a/tests/Microsoft.Identity.Test.Unit/PublicApiTests/PublicClientApplicationTestsWithB2C.cs +++ b/tests/Microsoft.Identity.Test.Unit/PublicApiTests/PublicClientApplicationTestsWithB2C.cs @@ -266,7 +266,7 @@ public async Task B2C_NoScopes_NoAccessToken_Async() AssertNoAccessToken(result); Assert.AreEqual(0, httpManager.QueueSize); - var ex = await AssertException.TaskThrowsAsync(() => + var ex = await Assert.ThrowsExceptionAsync(() => app.AcquireTokenSilent(null, result.Account).ExecuteAsync() ).ConfigureAwait(false); @@ -328,7 +328,7 @@ public async Task B2CSomeExceptionAsync() // Act #pragma warning disable CS0618 // Type or member is obsolete - var ex = await AssertException.TaskThrowsAsync(() => + var ex = await Assert.ThrowsExceptionAsync(() => app.AcquireTokenByUsernamePassword(new[] { "user.read" }, "username", "password" ) // no scopes -> no Access Token! .ExecuteAsync()) .ConfigureAwait(false); @@ -375,3 +375,4 @@ private static void ValidateB2CLoginAuthority(MockHttpAndServiceBundle harness, } } } + diff --git a/tests/Microsoft.Identity.Test.Unit/PublicApiTests/RefreshInTests.cs b/tests/Microsoft.Identity.Test.Unit/PublicApiTests/RefreshInTests.cs index 58f8518bc1..0d25df58a6 100644 --- a/tests/Microsoft.Identity.Test.Unit/PublicApiTests/RefreshInTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/PublicApiTests/RefreshInTests.cs @@ -223,7 +223,7 @@ public async Task ATS_Expired_NeedsRefresh_AADInvalidResponse_Async() var account = new Account(TestConstants.s_userIdentifier, TestConstants.DisplayableId, null); // Act - MsalServiceException ex = await AssertException.TaskThrowsAsync(() => app + MsalServiceException ex = await Assert.ThrowsExceptionAsync(() => app .AcquireTokenSilent( TestConstants.s_scope.ToArray(), account) @@ -492,7 +492,7 @@ public async Task ClientCredentials_Expired_NeedsRefresh_AADInvalidResponse_Asyn harness.HttpManager.AddTokenResponse(TokenResponseType.Invalid_AADUnavailable503); // Act - MsalServiceException ex = await AssertException.TaskThrowsAsync(() => app + MsalServiceException ex = await Assert.ThrowsExceptionAsync(() => app .AcquireTokenForClient(TestConstants.s_scope) .ExecuteAsync()) .ConfigureAwait(false); @@ -539,3 +539,4 @@ void LocalLogCallback(LogLevel level, string message, bool containsPii) #endregion } } + diff --git a/tests/Microsoft.Identity.Test.Unit/RequestsTests/DeviceCodeRequestTests.cs b/tests/Microsoft.Identity.Test.Unit/RequestsTests/DeviceCodeRequestTests.cs index 6680dd6067..d811a3a178 100644 --- a/tests/Microsoft.Identity.Test.Unit/RequestsTests/DeviceCodeRequestTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/RequestsTests/DeviceCodeRequestTests.cs @@ -154,7 +154,7 @@ public async Task DeviceCodeExceptionsOn200OKAsync() var request = new DeviceCodeRequest(harness.ServiceBundle, parameters, deviceCodeParameters); - var ex = await AssertException.TaskThrowsAsync( + var ex = await Assert.ThrowsExceptionAsync( () => request.RunAsync(CancellationToken.None)).ConfigureAwait(false); } } @@ -241,7 +241,7 @@ public async Task TestDeviceCodeCancelAsync() // We setup the cancel before calling the RunAsync operation since we don't check the cancel // until later and the mock network calls run insanely fast for us to timeout for them. cancellationSource.Cancel(); - await AssertException.TaskThrowsAsync(() => request.RunAsync(cancellationSource.Token)).ConfigureAwait(false); + await Assert.ThrowsExceptionAsync(() => request.RunAsync(cancellationSource.Token)).ConfigureAwait(false); } } @@ -401,3 +401,4 @@ private class _LogData } } } + diff --git a/tests/Microsoft.Identity.Test.Unit/RequestsTests/FociTests.cs b/tests/Microsoft.Identity.Test.Unit/RequestsTests/FociTests.cs index c25c558460..16cd4dba3d 100644 --- a/tests/Microsoft.Identity.Test.Unit/RequestsTests/FociTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/RequestsTests/FociTests.cs @@ -95,7 +95,7 @@ public async Task NoFociForCca() Assert.IsNull(appCAccount); // Act - var ex = await AssertException.TaskThrowsAsync( + var ex = await Assert.ThrowsExceptionAsync( () => appC.AcquireTokenSilent(TestConstants.s_scope, appAAccount).ExecuteAsync()).ConfigureAwait(false); Assert.AreEqual(MsalError.NoTokensFoundError, ex.ErrorCode); @@ -116,7 +116,7 @@ public async Task FociAndNonFociAppsCoexistAsync() await InteractiveAsync(_appA, ServerTokenResponse.FociToken).ConfigureAwait(false); // B cannot acquire a token interactively, but will try to use FRT - var ex = await AssertException.TaskThrowsAsync( + var ex = await Assert.ThrowsExceptionAsync( () => SilentAsync(_appB, ServerTokenResponse.ErrorClientMismatch)).ConfigureAwait(false); Assert.AreEqual(MsalError.NoTokensFoundError, ex.ErrorCode); @@ -147,7 +147,7 @@ public async Task FociDoesNotHideRTRefreshErrorsAsync() await InteractiveAsync(_appA, ServerTokenResponse.FociToken).ConfigureAwait(false); // B cannot acquire a token interactively, but will try to use FRT - var ex = await AssertException.TaskThrowsAsync( + var ex = await Assert.ThrowsExceptionAsync( () => SilentAsync(_appB, ServerTokenResponse.OtherError)).ConfigureAwait(false); Assert.AreEqual(MsalError.InvalidGrantError, ex.ErrorCode); @@ -211,7 +211,7 @@ public async Task FociAppLeavesFamilyAsync() await SilentAsync(_appB, ServerTokenResponse.FociToken).ConfigureAwait(false); // B leaves the family -> STS will not refresh its token based on the FRT - await AssertException.TaskThrowsAsync(() => SilentAsync(_appB, ServerTokenResponse.ErrorClientMismatch)).ConfigureAwait(false); + await Assert.ThrowsExceptionAsync(() => SilentAsync(_appB, ServerTokenResponse.ErrorClientMismatch)).ConfigureAwait(false); // B can resume acquiring tokens silently via the normal RT, after an interactive flow await InteractiveAsync(_appB, ServerTokenResponse.NonFociToken).ConfigureAwait(false); @@ -447,3 +447,4 @@ private void AssertAppHasRT(PublicClientApplication app) } } } + diff --git a/tests/Microsoft.Identity.Test.Unit/RequestsTests/IntegratedWindowsAuthUsernamePasswordTests.cs b/tests/Microsoft.Identity.Test.Unit/RequestsTests/IntegratedWindowsAuthUsernamePasswordTests.cs index 1e26e92916..0cfee2ef3c 100644 --- a/tests/Microsoft.Identity.Test.Unit/RequestsTests/IntegratedWindowsAuthUsernamePasswordTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/RequestsTests/IntegratedWindowsAuthUsernamePasswordTests.cs @@ -178,7 +178,7 @@ public async Task AcquireTokenByIntegratedWindowsAuthTest_ManagedUserAsync() .BuildConcrete(); // Act - MsalClientException exception = await AssertException.TaskThrowsAsync( + MsalClientException exception = await Assert.ThrowsExactlyAsync( async () => await app .AcquireTokenByIntegratedWindowsAuth(TestConstants.s_scope) .WithUsername(TestConstants.s_user.Username) @@ -219,7 +219,7 @@ public async Task AcquireTokenByIntegratedWindowsAuthTest_ManagedUser_DiscoveryF .BuildConcrete(); // Act - MsalServiceException exception = await AssertException.TaskThrowsAsync( + MsalServiceException exception = await Assert.ThrowsExceptionAsync( async () => await app .AcquireTokenByIntegratedWindowsAuth(TestConstants.s_scope) .WithUsername(TestConstants.s_user.Username) @@ -259,7 +259,7 @@ public async Task AcquireTokenByIntegratedWindowsAuthTest_UnknownUserAsync() .BuildConcrete(); // Act - MsalClientException exception = await AssertException.TaskThrowsAsync( + MsalClientException exception = await Assert.ThrowsExceptionAsync( async () => await app .AcquireTokenByIntegratedWindowsAuth(TestConstants.s_scope) .WithUsername(TestConstants.s_user.Username) @@ -403,7 +403,7 @@ public async Task AcquireTokenByIntegratedWindowsAuthInvalidClientTestAsync() .WithExtraQueryParameters(TestConstants.ExtraQueryParametersNoAffectOnCacheKeys) .BuildConcrete(); - MsalServiceException result = await AssertException.TaskThrowsAsync( + MsalServiceException result = await Assert.ThrowsExceptionAsync( async () => await app.AcquireTokenByIntegratedWindowsAuth(TestConstants.s_scope) .WithClaims(TestConstants.Claims) .WithUsername(TestConstants.s_user.Username) @@ -485,7 +485,7 @@ public async Task MexEndpointFailsToResolveTestAsync() // Call acquire token, Mex parser fails #pragma warning disable CS0618 // Type or member is obsolete - MsalClientException result = await AssertException.TaskThrowsAsync( + MsalClientException result = await Assert.ThrowsExceptionAsync( async () => await app.AcquireTokenByUsernamePassword( TestConstants.s_scope, TestConstants.s_user.Username, @@ -520,7 +520,7 @@ public async Task MexDoesNotReturnAuthEndpointTestAsync() .BuildConcrete(); // Call acquire token, endpoint not found - MsalClientException result = await AssertException.TaskThrowsAsync( + MsalClientException result = await Assert.ThrowsExceptionAsync( #pragma warning disable CS0618 // Type or member is obsolete async () => await app.AcquireTokenByUsernamePassword( TestConstants.s_scope, @@ -553,7 +553,7 @@ public async Task MexParsingFailsTestAsync() .BuildConcrete(); // Call acquire token - MsalServiceException result = await AssertException.TaskThrowsAsync( + MsalServiceException result = await Assert.ThrowsExceptionAsync( #pragma warning disable CS0618 // Type or member is obsolete async () => await app.AcquireTokenByUsernamePassword( TestConstants.s_scope, @@ -593,7 +593,7 @@ public async Task FederatedUsernameNullPasswordTestAsync() .BuildConcrete(); // Call acquire token - MsalClientException result = await AssertException.TaskThrowsAsync( + MsalClientException result = await Assert.ThrowsExceptionAsync( #pragma warning disable CS0618 // Type or member is obsolete async () => await app.AcquireTokenByUsernamePassword( TestConstants.s_scope, @@ -636,7 +636,7 @@ public async Task FederatedUsernamePasswordCommonAuthorityTestAsync() .BuildConcrete(); // Call acquire token - MsalServiceException result = await AssertException.TaskThrowsAsync( + MsalServiceException result = await Assert.ThrowsExceptionAsync( #pragma warning disable CS0618 // Type or member is obsolete async () => await app.AcquireTokenByUsernamePassword( TestConstants.s_scope, @@ -687,7 +687,7 @@ public async Task ManagedUsernamePasswordCommonAuthorityTestAsync() .BuildConcrete(); // Call acquire token - MsalServiceException result = await AssertException.TaskThrowsAsync( + MsalServiceException result = await Assert.ThrowsExceptionAsync( #pragma warning disable CS0618 // Type or member is obsolete async () => await app.AcquireTokenByUsernamePassword( TestConstants.s_scope, @@ -758,7 +758,7 @@ public async Task ManagedUsernameNoPasswordAcquireTokenTestAsync() // Call acquire token #pragma warning disable CS0618 // Type or member is obsolete - MsalClientException result = await AssertException.TaskThrowsAsync( + MsalClientException result = await Assert.ThrowsExceptionAsync( async () => await app.AcquireTokenByUsernamePassword( TestConstants.s_scope, TestConstants.s_user.Username, @@ -870,3 +870,4 @@ public async Task UsernamePasswordInvalidClientTestAsync() } } } + diff --git a/tests/Microsoft.Identity.Test.Unit/RequestsTests/InteractiveRequestTests.cs b/tests/Microsoft.Identity.Test.Unit/RequestsTests/InteractiveRequestTests.cs index b4ae886a5c..7a7c42a88b 100644 --- a/tests/Microsoft.Identity.Test.Unit/RequestsTests/InteractiveRequestTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/RequestsTests/InteractiveRequestTests.cs @@ -41,9 +41,9 @@ public void NullArgs() ExtraScopesToConsent = TestConstants.s_scopeForAnotherResource.ToArray(), }; - AssertException.Throws(() => + Assert.ThrowsException(() => new InteractiveRequest(null, interactiveParameters)); - AssertException.Throws(() => + Assert.ThrowsException(() => new InteractiveRequest(requestParams, null)); } } @@ -202,7 +202,7 @@ public async Task RedirectUriContainsFragmentErrorTestAsync() var request = new InteractiveRequest( parameters, interactiveParameters); - var ex = await AssertException.TaskThrowsAsync + var ex = await Assert.ThrowsExceptionAsync (() => request.RunAsync()).ConfigureAwait(false); Assert.Contains(MsalErrorMessage.RedirectUriContainsFragment, ex.Message); @@ -239,7 +239,7 @@ public async Task VerifyAuthorizationResultTestAsync() parameters, interactiveParameters); - var ex = await AssertException.TaskThrowsAsync( + var ex = await Assert.ThrowsExceptionAsync( () => request.RunAsync()) .ConfigureAwait(false); @@ -262,7 +262,7 @@ public async Task VerifyAuthorizationResultTestAsync() parameters, interactiveParameters); - var ex2 = await AssertException.TaskThrowsAsync( + var ex2 = await Assert.ThrowsExceptionAsync( () => request.RunAsync()) .ConfigureAwait(false); @@ -295,7 +295,7 @@ public async Task VerifyAuthorizationResult_NoErrorDescription_Async() parameters, new AcquireTokenInteractiveParameters()); - var ex = await AssertException.TaskThrowsAsync( + var ex = await Assert.ThrowsExceptionAsync( () => request.RunAsync(CancellationToken.None)) .ConfigureAwait(false); @@ -427,3 +427,4 @@ private static void MockInstanceDiscoveryAndOpenIdRequest(MockHttpManager mockHt } } + diff --git a/tests/Microsoft.Identity.Test.Unit/RequestsTests/InteractiveRequestWithCustomWebUiTests.cs b/tests/Microsoft.Identity.Test.Unit/RequestsTests/InteractiveRequestWithCustomWebUiTests.cs index a2f43936e2..073531b99e 100644 --- a/tests/Microsoft.Identity.Test.Unit/RequestsTests/InteractiveRequestWithCustomWebUiTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/RequestsTests/InteractiveRequestWithCustomWebUiTests.cs @@ -111,7 +111,7 @@ await ExecuteTestAsync( .ReturnsForAnyArgs(Task.FromResult(new Uri("http://blech"))), async request => { - var ex = await AssertException.TaskThrowsAsync( + var ex = await Assert.ThrowsExceptionAsync( () => request.RunAsync(CancellationToken.None)).ConfigureAwait(false); Assert.AreEqual(MsalError.CustomWebUiReturnedInvalidUri, ex.ErrorCode); }).ConfigureAwait(false); @@ -127,7 +127,7 @@ await ExecuteTestAsync( .ReturnsForAnyArgs(_ => { throw new InvalidOperationException(); }), async request => { - await AssertException.TaskThrowsAsync( + await Assert.ThrowsExceptionAsync( () => request.RunAsync(CancellationToken.None)).ConfigureAwait(false); }).ConfigureAwait(false); } @@ -142,7 +142,7 @@ await ExecuteTestAsync( .ReturnsForAnyArgs(Task.FromResult(new Uri(ExpectedRedirectUri))), async request => { - var ex = await AssertException.TaskThrowsAsync( + var ex = await Assert.ThrowsExceptionAsync( () => request.RunAsync(CancellationToken.None)).ConfigureAwait(false); Assert.AreEqual(MsalError.CustomWebUiReturnedInvalidUri, ex.ErrorCode); }).ConfigureAwait(false); @@ -161,10 +161,11 @@ await ExecuteTestAsync( }, async request => { - var ex = await AssertException.TaskThrowsAsync( + var ex = await Assert.ThrowsExceptionAsync( () => request.RunAsync(CancellationToken.None)).ConfigureAwait(false); Assert.AreEqual(MsalError.StateMismatchError, ex.ErrorCode); }).ConfigureAwait(false); } } } + diff --git a/tests/Microsoft.Identity.Test.Unit/RequestsTests/LongRunningOnBehalfOfTests.cs b/tests/Microsoft.Identity.Test.Unit/RequestsTests/LongRunningOnBehalfOfTests.cs index 2e856429f3..1504111d4e 100644 --- a/tests/Microsoft.Identity.Test.Unit/RequestsTests/LongRunningOnBehalfOfTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/RequestsTests/LongRunningOnBehalfOfTests.cs @@ -345,7 +345,7 @@ public async Task AcquireTokenInLongRunningObo_CacheKeyDoesNotExist_TestAsync() string oboCacheKey = "obo-cache-key"; // If token with OBO cache key provided does not exist in the cache throw error - var exception = await AssertException.TaskThrowsAsync( + var exception = await Assert.ThrowsExceptionAsync( () => cca.AcquireTokenInLongRunningProcess(TestConstants.s_scope.ToArray(), oboCacheKey) .ExecuteAsync()) .ConfigureAwait(false); @@ -375,7 +375,7 @@ await cca.InitiateLongRunningProcessInWebApi(TestConstants.s_scope, TestConstant Assert.AreEqual(new UserAssertion(TestConstants.DefaultAccessToken).AssertionHash, cacheKey); // Cache key is required in this method - await AssertException.TaskThrowsAsync( + await Assert.ThrowsExceptionAsync( () => cca.AcquireTokenInLongRunningProcess(TestConstants.s_scope, null) .ExecuteAsync()) .ConfigureAwait(false); @@ -638,7 +638,7 @@ public async Task NormalOboThenLongRunningAcquire_WithTheSameKey_TestAsync() TokenCacheHelper.ExpireAllAccessTokens(cca.UserTokenCacheInternal); // AcquireLR - throws because no RT - var exception = await AssertException.TaskThrowsAsync( + var exception = await Assert.ThrowsExceptionAsync( () => cca.AcquireTokenInLongRunningProcess(TestConstants.s_scope.ToArray(), oboCacheKey) .ExecuteAsync()) .ConfigureAwait(false); @@ -961,3 +961,4 @@ private ConfidentialClientApplication BuildCCA(IHttpManager httpManager, LogCall } } } + diff --git a/tests/Microsoft.Identity.Test.Unit/RequestsTests/SilentRequestTests.cs b/tests/Microsoft.Identity.Test.Unit/RequestsTests/SilentRequestTests.cs index 7218fbff17..cdea6a2de8 100644 --- a/tests/Microsoft.Identity.Test.Unit/RequestsTests/SilentRequestTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/RequestsTests/SilentRequestTests.cs @@ -151,7 +151,7 @@ public void RequestParamsNullArg() { using (var harness = new MockHttpTestHarness(TestConstants.AuthorityHomeTenant)) { - AssertException.Throws(() => harness.CreateRequestParams( + Assert.ThrowsException(() => harness.CreateRequestParams( null, TestConstants.s_scope, authorityOverride: AuthorityInfo.FromAuthorityUri(TestConstants.AuthorityHomeTenant, false))); @@ -297,3 +297,4 @@ public AuthenticationRequestParameters CreateRequestParams( } } } + diff --git a/tests/Microsoft.Identity.Test.Unit/TelemetryTests/HttpTelemetryTests.cs b/tests/Microsoft.Identity.Test.Unit/TelemetryTests/HttpTelemetryTests.cs index 608aba7e6f..067aa055fb 100644 --- a/tests/Microsoft.Identity.Test.Unit/TelemetryTests/HttpTelemetryTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/TelemetryTests/HttpTelemetryTests.cs @@ -577,7 +577,7 @@ private enum AcquireTokenInteractiveOutcome Task.FromException(new MsalClientException("user_cancelled"))); _app.ServiceBundle.ConfigureMockWebUI(ui); - var ex = await AssertException.TaskThrowsAsync(() => + var ex = await Assert.ThrowsExceptionAsync(() => _app .AcquireTokenInteractive(TestConstants.s_scope) .WithCorrelationId(correlationId) @@ -607,7 +607,7 @@ private enum AcquireTokenInteractiveOutcome _harness.HttpManager.AddMockHandler(tokenRequestHandler2); _harness.HttpManager.AddMockHandler(tokenRequestHandler); - var serviceEx = await AssertException.TaskThrowsAsync(() => + var serviceEx = await Assert.ThrowsExceptionAsync(() => _app .AcquireTokenInteractive(TestConstants.s_scope) .WithCorrelationId(correlationId) @@ -623,7 +623,7 @@ private enum AcquireTokenInteractiveOutcome cts.Cancel(true); CancellationToken token = cts.Token; - var operationCanceledException = await AssertException.TaskThrowsAsync(() => + var operationCanceledException = await Assert.ThrowsExceptionAsync(() => _app .AcquireTokenInteractive(TestConstants.s_scope) .WithCorrelationId(correlationId) @@ -713,7 +713,7 @@ private enum AcquireTokenInteractiveOutcome TestConstants.AuthorityUtidTenant, correlationId.ToString()); - var ex = await AssertException.TaskThrowsAsync( + var ex = await Assert.ThrowsExceptionAsync( () => request.WithCorrelationId(correlationId).ExecuteAsync(), allowDerived: true) .ConfigureAwait(false); @@ -763,3 +763,4 @@ private void AssertCurrentTelemetry( } } } + diff --git a/tests/Microsoft.Identity.Test.Unit/TelemetryTests/OTelInstrumentationTests.cs b/tests/Microsoft.Identity.Test.Unit/TelemetryTests/OTelInstrumentationTests.cs index 131869ac44..51fb4bce22 100644 --- a/tests/Microsoft.Identity.Test.Unit/TelemetryTests/OTelInstrumentationTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/TelemetryTests/OTelInstrumentationTests.cs @@ -381,7 +381,7 @@ private async Task AcquireTokenMsalServiceExceptionAsync() _harness.HttpManager.AddTokenResponse(TokenResponseType.InvalidClient); //Test for MsalServiceException - MsalServiceException ex = await AssertException.TaskThrowsAsync( + MsalServiceException ex = await Assert.ThrowsExceptionAsync( () => _cca.AcquireTokenForClient(TestConstants.s_scopeForAnotherResource) .WithExtraQueryParameters(extraQueryParams) .WithTenantId(TestConstants.Utid) @@ -394,7 +394,7 @@ private async Task AcquireTokenMsalServiceExceptionAsync() private async Task AcquireTokenMsalClientExceptionAsync() { //Test for MsalClientException - MsalClientException exClient = await AssertException.TaskThrowsAsync( + MsalClientException exClient = await Assert.ThrowsExceptionAsync( () => _cca.AcquireTokenForClient(null) // null scope -> client exception .WithExtraQueryParameters(extraQueryParams) .WithTenantId(TestConstants.Utid) @@ -607,3 +607,4 @@ private void AssertTags(ReadOnlyTagCollection tags, List expectedTags, b } } } + diff --git a/tests/Microsoft.Identity.Test.Unit/TelemetryTests/RegionalTelemetryTests.cs b/tests/Microsoft.Identity.Test.Unit/TelemetryTests/RegionalTelemetryTests.cs index f8137f1eb4..f0d7eedb6e 100644 --- a/tests/Microsoft.Identity.Test.Unit/TelemetryTests/RegionalTelemetryTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/TelemetryTests/RegionalTelemetryTests.cs @@ -326,7 +326,7 @@ private enum AcquireTokenForClientOutcome _harness.HttpManager.AddMockHandler(tokenRequestHandler2); _harness.HttpManager.AddMockHandler(tokenRequestHandler); - var serviceEx = await AssertException.TaskThrowsAsync(() => + var serviceEx = await Assert.ThrowsExceptionAsync(() => app5 .AcquireTokenForClient(TestConstants.s_scope) .WithForceRefresh(true) @@ -380,3 +380,4 @@ private static void AssertCurrentTelemetry( } } } + diff --git a/tests/Microsoft.Identity.Test.Unit/Throttling/ThrottlingAcceptanceTests.cs b/tests/Microsoft.Identity.Test.Unit/Throttling/ThrottlingAcceptanceTests.cs index 4ccb89921e..a3b6c786b7 100644 --- a/tests/Microsoft.Identity.Test.Unit/Throttling/ThrottlingAcceptanceTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/Throttling/ThrottlingAcceptanceTests.cs @@ -45,7 +45,7 @@ public async Task Http400_RetryAfter_ThrottleForDuration_AcceptanceTest_Async() AssertThrottlingCacheEntryCount(throttlingManager, retryAfterEntryCount: 1); Trace.WriteLine("3. Second call - request is throttled"); - var ex = await AssertException.TaskThrowsAsync( + var ex = await Assert.ThrowsExceptionAsync( () => app.AcquireTokenSilent(TestConstants.s_scope, account).ExecuteAsync()) .ConfigureAwait(false); AssertInvalidClientEx(ex); @@ -89,7 +89,7 @@ public async Task Http429_RetryAfter_ThrottleForDuration_Async(int httpStatusCod AssertThrottlingCacheEntryCount(throttlingManager, retryAfterEntryCount: 1); Trace.WriteLine("3. Second call - request is throttled"); - var ex = await AssertException.TaskThrowsAsync( + var ex = await Assert.ThrowsExceptionAsync( () => app.AcquireTokenSilent(TestConstants.s_scope, account).ExecuteAsync()) .ConfigureAwait(false); Assert.AreEqual(httpStatusCode, ex.StatusCode); @@ -126,7 +126,7 @@ public async Task SimilarRequests_AreThrottled_RetryAfter_Async() AssertThrottlingCacheEntryCount(throttlingManager, retryAfterEntryCount: 1); Trace.WriteLine("A similar request, e.g. with a claims challenge, will be throttled"); - var ex = await AssertException.TaskThrowsAsync( + var ex = await Assert.ThrowsExceptionAsync( () => app.AcquireTokenSilent(TestConstants.s_scope, account) .WithClaims(TestConstants.Claims) // claims are not part of the strict thumbprint .ExecuteAsync()) @@ -185,14 +185,14 @@ public async Task RetryAfter_ConfidentialClient_Async() const int RetryAfterInSeconds = 10; UpdateStatusCodeAndHeaders(tokenResponse.ResponseMessage, 429, RetryAfterInSeconds); - var ex = await AssertException.TaskThrowsAsync( + var ex = await Assert.ThrowsExceptionAsync( () => app.AcquireTokenForClient(TestConstants.s_scope).ExecuteAsync()) .ConfigureAwait(false); Assert.AreEqual(429, ex.StatusCode); AssertThrottlingCacheEntryCount(throttlingManager, retryAfterEntryCount: 1); - var ex2 = await AssertException.TaskThrowsAsync( + var ex2 = await Assert.ThrowsExceptionAsync( () => app.AcquireTokenForClient(TestConstants.s_scope).ExecuteAsync()) .ConfigureAwait(false); Assert.AreEqual(429, ex2.StatusCode); @@ -218,7 +218,7 @@ public async Task RetryAfter_ConfidentialClient_ErrorMessage_Async() httpManager.AddInstanceDiscoveryMockHandler(); var tokenResponse = httpManager.AddMockHandlerForThrottledResponseMessage(); - var serverEx = await AssertException.TaskThrowsAsync( + var serverEx = await Assert.ThrowsExceptionAsync( () => app.AcquireTokenForClient(TestConstants.s_scope).ExecuteAsync()) .ConfigureAwait(false); @@ -249,7 +249,7 @@ public async Task Http429_And503_WithoutRetryAfter_AreThrottled_ByDefaultTimeout var throttlingManager = (httpManagerAndBundle.ServiceBundle.ThrottlingManager as SingletonThrottlingManager); Trace.WriteLine("3. Second call - request is throttled"); - var ex = await AssertException.TaskThrowsAsync( + var ex = await Assert.ThrowsExceptionAsync( () => app.AcquireTokenSilent(TestConstants.s_scope, account).ExecuteAsync()) .ConfigureAwait(false); Assert.AreEqual(httpStatusCode, ex.StatusCode); @@ -286,7 +286,7 @@ public async Task SimilarRequests_AreThrottled_HttpStatus_Async() AssertThrottlingCacheEntryCount(throttlingManager, httpStatusEntryCount: 1); Trace.WriteLine("A similar request, e.g. with a claims challenge, will be throttled"); - var ex = await AssertException.TaskThrowsAsync( + var ex = await Assert.ThrowsExceptionAsync( () => app.AcquireTokenSilent(TestConstants.s_scope, account) .WithClaims(TestConstants.Claims) // claims are not part of the strict thumbprint .ExecuteAsync()) @@ -307,7 +307,7 @@ await app.AcquireTokenSilent(new[] { "Other.Scopes" }, account).ExecuteAsync() pca2.UserTokenCacheInternal.Accessor, expiredAccessTokens: true); - await AssertException.TaskThrowsAsync( + await Assert.ThrowsExceptionAsync( () => pca2.AcquireTokenSilent(TestConstants.s_scope, account) .ExecuteAsync()) .ConfigureAwait(false); @@ -342,7 +342,7 @@ public async Task UiRequiredThrottling_Async() AssertThrottlingCacheEntryCount(throttlingManager, uiRequiredEntryCount: 1); Trace.WriteLine("A similar request will be throttled"); - var ex = await AssertException.TaskThrowsAsync( + var ex = await Assert.ThrowsExceptionAsync( () => app.AcquireTokenSilent(TestConstants.s_scope, account) .ExecuteAsync()) .ConfigureAwait(false); @@ -351,7 +351,7 @@ public async Task UiRequiredThrottling_Async() Trace.WriteLine("And again..."); - ex = await AssertException.TaskThrowsAsync( + ex = await Assert.ThrowsExceptionAsync( () => app.AcquireTokenSilent(TestConstants.s_scope, account) .ExecuteAsync()) .ConfigureAwait(false); @@ -395,7 +395,7 @@ public async Task UiRequired_BypassRt_Async() AssertThrottlingCacheEntryCount(throttlingManager, uiRequiredEntryCount: 1); Trace.WriteLine("A similar request will be throttled"); - var ex = await AssertException.TaskThrowsAsync( + var ex = await Assert.ThrowsExceptionAsync( () => app.AcquireTokenSilent(TestConstants.s_scope, account) .ExecuteAsync()) .ConfigureAwait(false); @@ -438,7 +438,7 @@ public async Task UiRequired_MultipleEntries_Async() Trace.WriteLine("Make another failing request, but with fewer scopes - should not be throttled."); var singleScope = TestConstants.s_scope.Take(1); var account = (await app.GetAccountsAsync().ConfigureAwait(false)).Single(); - var ex = await AssertException.TaskThrowsAsync( + var ex = await Assert.ThrowsExceptionAsync( () => app.AcquireTokenSilent(singleScope, account).ExecuteAsync()) .ConfigureAwait(false); @@ -492,7 +492,7 @@ private async Task SetupAndAcquireOnceAsync( var account = (await app.GetAccountsAsync().ConfigureAwait(false)).Single(); Trace.WriteLine("2. First failing call "); - var ex = await AssertException.TaskThrowsAsync( + var ex = await Assert.ThrowsExceptionAsync( () => app.AcquireTokenSilent(TestConstants.s_scope, account).ExecuteAsync(), allowDerived: true) .ConfigureAwait(false); @@ -539,3 +539,4 @@ private static void AssertInvalidClientEx(MsalServiceException ex) } } } + diff --git a/tests/Microsoft.Identity.Test.Unit/UtilTests/RetryOperationHelperTest.cs b/tests/Microsoft.Identity.Test.Unit/UtilTests/RetryOperationHelperTest.cs index 8201f5d753..128d86fd6b 100644 --- a/tests/Microsoft.Identity.Test.Unit/UtilTests/RetryOperationHelperTest.cs +++ b/tests/Microsoft.Identity.Test.Unit/UtilTests/RetryOperationHelperTest.cs @@ -43,7 +43,7 @@ public void TestExecuteWithRetry_OperationFails() Func> func = () => operationSimulator.SimulateOperationWithFailuresAsync(); //Act - Exception ex = AssertException.Throws( + Exception ex = Assert.ThrowsException( () => RetryOperationHelper.ExecuteWithRetryAsync(func, numberOfRetriesToAttempt).Wait()); Assert.AreEqual("OperationSimulator: Simulating Operation Failure", ex.InnerException.Message); @@ -63,7 +63,7 @@ public void TestExecuteWithRetry_OperationFails_VerifyOnFailureActionIsCalled() //Act - Exception ex = AssertException.Throws( + Exception ex = Assert.ThrowsException( () => RetryOperationHelper.ExecuteWithRetryAsync(func, numberOfRetriesToAttempt, retryTimeSpan, actionUponFailure).Wait()); Assert.AreEqual("OperationSimulator: ThrowException: Exception thrown to identify method", ex.InnerException.Message); } @@ -101,3 +101,4 @@ public void ThrowException(int numberOfPreviousFailures, Exception exception) } } } + diff --git a/tests/Microsoft.Identity.Test.Unit/WebUITests/DefaultOsBrowserWebUiTests.cs b/tests/Microsoft.Identity.Test.Unit/WebUITests/DefaultOsBrowserWebUiTests.cs index 6f4695e0ec..fcf384beea 100644 --- a/tests/Microsoft.Identity.Test.Unit/WebUITests/DefaultOsBrowserWebUiTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/WebUITests/DefaultOsBrowserWebUiTests.cs @@ -99,7 +99,7 @@ public async Task HttpListenerException_Cancellation_Async() }); // Act - await AssertException.TaskThrowsAsync( + await Assert.ThrowsExceptionAsync( () => webUI.AcquireAuthorizationAsync( new Uri(TestAuthorizationRequestUri), new Uri(TestRedirectUri), @@ -154,7 +154,7 @@ public async Task DefaultOsBrowserWebUi_ReturnUriInvalid_Async() { string differentPortRedirectUri = TestAuthorizationResponseUri.Replace(TestRedirectUri, "http://localhost:1111"); - MsalClientException ex = await AssertException.TaskThrowsAsync( + MsalClientException ex = await Assert.ThrowsExceptionAsync( () => AcquireAuthCodeAsync(CreateTestWebUI(), responseUriString: differentPortRedirectUri)) .ConfigureAwait(false); @@ -316,7 +316,7 @@ private void ValidateResponse(SystemWebViewOptions options, bool successResponse private static void AssertInvalidRedirectUri(IWebUI webUI, string uri) { - var ex = AssertException.Throws(() => webUI.UpdateRedirectUri(new Uri(uri))); + var ex = Assert.ThrowsException(() => webUI.UpdateRedirectUri(new Uri(uri))); Assert.AreEqual(MsalError.LoopbackRedirectUri, ex.ErrorCode); } @@ -347,3 +347,4 @@ private static void AssertPortIsFree(int port) } } } + diff --git a/tests/Microsoft.Identity.Test.Unit/WebUITests/HttpListenerInterceptorTests.cs b/tests/Microsoft.Identity.Test.Unit/WebUITests/HttpListenerInterceptorTests.cs index 48ddb7bd5b..b36e03a5c9 100644 --- a/tests/Microsoft.Identity.Test.Unit/WebUITests/HttpListenerInterceptorTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/WebUITests/HttpListenerInterceptorTests.cs @@ -57,7 +57,7 @@ public async Task Cancellation_BeforeTopLevelCall_Async() int port = FindFreeLocalhostPort(); // Start the listener in the background - await AssertException.TaskThrowsAsync( + await Assert.ThrowsExceptionAsync( () => listenerInterceptor.ListenToSingleRequestAndRespondAsync( port, string.Empty, @@ -78,7 +78,7 @@ public async Task Cancellation_BeforeStart_Async() listenerInterceptor.TestBeforeStart = (_) => cts.Cancel(); // Start the listener in the background - await AssertException.TaskThrowsAsync( + await Assert.ThrowsExceptionAsync( () => listenerInterceptor.ListenToSingleRequestAndRespondAsync( port, string.Empty, @@ -151,7 +151,7 @@ public async Task Cancellation_BeforeGetContext_Async() listenerInterceptor.TestBeforeGetContext = () => cts.Cancel(); // Start the listener in the background - await AssertException.TaskThrowsAsync( + await Assert.ThrowsExceptionAsync( () => listenerInterceptor.ListenToSingleRequestAndRespondAsync( port, string.Empty, @@ -194,3 +194,4 @@ private static int FindFreeLocalhostPort() } } } + diff --git a/tests/Microsoft.Identity.Test.Unit/WebUITests/NetCoreWebUIFactoryTests.cs b/tests/Microsoft.Identity.Test.Unit/WebUITests/NetCoreWebUIFactoryTests.cs index d8882515d5..0eb56c6bb8 100644 --- a/tests/Microsoft.Identity.Test.Unit/WebUITests/NetCoreWebUIFactoryTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/WebUITests/NetCoreWebUIFactoryTests.cs @@ -43,7 +43,7 @@ public void NetCoreFactory_Embedded() // Arrange // Act - var ex = AssertException.Throws( + var ex = Assert.ThrowsException( ()=> _webUIFactory.CreateAuthenticationDialog( _parent, WebViewPreference.Embedded, @@ -74,3 +74,4 @@ public void NetCoreFactory_System() } } #endif + diff --git a/tests/Microsoft.Identity.Test.Unit/pop/PoPTests.cs b/tests/Microsoft.Identity.Test.Unit/pop/PoPTests.cs index a61d3354d4..3df5ce5cba 100644 --- a/tests/Microsoft.Identity.Test.Unit/pop/PoPTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/pop/PoPTests.cs @@ -169,14 +169,14 @@ public async Task POP_WithMissingNonceForPCA_Async() HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, new Uri(ProtectedUrl)); - await AssertException.TaskThrowsAsync(() => + await Assert.ThrowsExceptionAsync(() => app.AcquireTokenInteractive(TestConstants.s_scope.ToArray()) .WithTenantId(TestConstants.Utid) .WithProofOfPossession(null, HttpMethod.Get, new Uri(app.Authority)) .ExecuteAsync()) .ConfigureAwait(false); - await AssertException.TaskThrowsAsync(() => + await Assert.ThrowsExceptionAsync(() => app.AcquireTokenSilent(TestConstants.s_scope.ToArray(), "loginHint") .WithTenantId(TestConstants.Utid) .WithProofOfPossession(null, HttpMethod.Get, new Uri(app.Authority)) @@ -211,7 +211,7 @@ public async Task PopWhenBrokerIsNotAvailableTest_Async() pca.ServiceBundle.ConfigureMockWebUI(); // Act - var exception = await AssertException.TaskThrowsAsync(async () => + var exception = await Assert.ThrowsExceptionAsync(async () => { await pca.AcquireTokenInteractive(TestConstants.s_graphScopes) .WithProofOfPossession(TestConstants.Nonce, HttpMethod.Get, new Uri(TestConstants.AuthorityCommonTenant)) @@ -242,7 +242,7 @@ public async Task PopWhenBrokerDoesNotSupportPop_Async() pca.ServiceBundle.Config.BrokerCreatorFunc = (_, _, _) => mockBroker; // Act - MsalClientException ex = await AssertException.TaskThrowsAsync(async () => + MsalClientException ex = await Assert.ThrowsExceptionAsync(async () => await pca.AcquireTokenInteractive(TestConstants.s_graphScopes) .WithProofOfPossession(TestConstants.Nonce, HttpMethod.Get, new Uri(TestConstants.AuthorityCommonTenant)) .ExecuteAsync() @@ -280,7 +280,7 @@ public async Task PopWhithAdfsUserAndBroker_Async() pca.ServiceBundle.Config.BrokerCreatorFunc = (_, _, _) => mockBroker; // Act - MsalClientException ex = await AssertException.TaskThrowsAsync(async () => + MsalClientException ex = await Assert.ThrowsExceptionAsync(async () => await pca.AcquireTokenSilent(TestConstants.s_graphScopes, TestConstants.DisplayableId) .WithProofOfPossession(TestConstants.Nonce, HttpMethod.Get, new Uri(TestConstants.AuthorityCommonTenant)) .ExecuteAsync() @@ -498,7 +498,7 @@ public async Task PopWhenBrokerIsNotEnabledForATS_Async() // Act - MsalClientException ex = await AssertException.TaskThrowsAsync(async () => + MsalClientException ex = await Assert.ThrowsExceptionAsync(async () => await pca.AcquireTokenSilent(TestConstants.s_graphScopes, TestConstants.LocalAccountId) .WithProofOfPossession(TestConstants.Nonce, HttpMethod.Get, new Uri(TestConstants.AuthorityCommonTenant)) .ExecuteAsync() @@ -697,3 +697,4 @@ public void ValidateCanonicalJwkFormat() } } } + diff --git a/tests/Microsoft.Identity.Test.Unit/pop/PopAuthenticationOperationTests.cs b/tests/Microsoft.Identity.Test.Unit/pop/PopAuthenticationOperationTests.cs index 35a9e54869..52c6044f2e 100644 --- a/tests/Microsoft.Identity.Test.Unit/pop/PopAuthenticationOperationTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/pop/PopAuthenticationOperationTests.cs @@ -37,14 +37,14 @@ public void NullArgsTest() Uri uri = new Uri("https://www.contoso.com/path1/path2?queryParam1=a&queryParam2=b"); PoPAuthenticationConfiguration config = null; - AssertException.Throws(() => new PopAuthenticationOperation(config, harness.ServiceBundle)); + Assert.ThrowsException(() => new PopAuthenticationOperation(config, harness.ServiceBundle)); config = new PoPAuthenticationConfiguration(uri); config.PopCryptoProvider = new InMemoryCryptoProvider(); - AssertException.Throws(() => new PopAuthenticationOperation(config, null)); - AssertException.Throws(() => new PoPAuthenticationConfiguration((HttpRequestMessage)null)); - AssertException.Throws(() => new PoPAuthenticationConfiguration((Uri)null)); + Assert.ThrowsException(() => new PopAuthenticationOperation(config, null)); + Assert.ThrowsException(() => new PoPAuthenticationConfiguration((HttpRequestMessage)null)); + Assert.ThrowsException(() => new PoPAuthenticationConfiguration((Uri)null)); } } @@ -203,3 +203,4 @@ private static string AssertSimpleClaim(JwtSecurityToken jwt, string expectedKey } } } + From f0e19694b92c33a0f5de8dcf2da69a28151c8e11 Mon Sep 17 00:00:00 2001 From: Bogdan Gavril Date: Wed, 17 Dec 2025 18:04:43 +0000 Subject: [PATCH 4/5] Various fixes --- .../HeadlessTests/CancellationTests.cs | 4 +--- .../HeadlessTests/GenericAuthorityTests.cs | 2 +- .../HeadlessTests/InstanceDiscoveryIntegrationTests.cs | 4 ++-- .../HeadlessTests/LongRunningOnBehalfOfTests.cs | 4 ++-- .../HeadlessTests/ManagedIdentityTests.NetFwk.cs | 4 ++-- .../HeadlessTests/MsalCacheStorageIntegrationTests.cs | 2 +- .../HeadlessTests/OnBehalfOfTests.cs | 8 ++++---- .../HeadlessTests/RuntimeBrokerTests.cs | 8 ++++---- .../SeleniumTests/FociTests.cs | 2 +- .../SeleniumTests/SeleniumInfrastructureTests.NetFwk.cs | 4 ++-- tests/devapps/Directory.Packages.props | 2 +- 11 files changed, 21 insertions(+), 23 deletions(-) diff --git a/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/CancellationTests.cs b/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/CancellationTests.cs index dd7c11c21c..c726af3ecd 100644 --- a/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/CancellationTests.cs +++ b/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/CancellationTests.cs @@ -70,7 +70,7 @@ public async Task DefaultOsBrowser_IsCancellable_StartsCancelled_Async() private async Task ValidateOperationCancelledAsync(string redirectUri, CancellationTokenSource cts, System.Runtime.CompilerServices.ConfiguredTaskAwaitable tokenTask) { // Assert - var ex = await Assert.ThrowsExceptionAsync(async () => + var ex = await Assert.ThrowsAsync(async () => { await tokenTask; return; @@ -110,5 +110,3 @@ private void ValidatePortIsFree(int port) } } } - - diff --git a/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/GenericAuthorityTests.cs b/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/GenericAuthorityTests.cs index 1e389263f3..8609e142f7 100644 --- a/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/GenericAuthorityTests.cs +++ b/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/GenericAuthorityTests.cs @@ -54,7 +54,7 @@ public async Task BadSecret_Duende_Async() .WithClientSecret("bad_secret") .Build(); - var ex = await Assert.ThrowsExceptionAsync(() => + var ex = await Assert.ThrowsExactlyAsync(() => app.AcquireTokenForClient(new[] { "api" }).ExecuteAsync()).ConfigureAwait(false); Assert.AreEqual("invalid_client", ex.ErrorCode); diff --git a/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/InstanceDiscoveryIntegrationTests.cs b/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/InstanceDiscoveryIntegrationTests.cs index aa906d05c5..0cd237aa73 100644 --- a/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/InstanceDiscoveryIntegrationTests.cs +++ b/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/InstanceDiscoveryIntegrationTests.cs @@ -81,7 +81,7 @@ public async Task FailedAuthorityValidationTestAsync() Trace.WriteLine("Acquire a token using a not so common authority alias"); #pragma warning disable CS0618 // Type or member is obsolete - MsalServiceException exception = await Assert.ThrowsExceptionAsync(() => + MsalServiceException exception = await Assert.ThrowsExactlyAsync(() => pca.AcquireTokenByUsernamePassword( s_scopes, user.Upn, @@ -109,7 +109,7 @@ public async Task AuthorityValidationTestWithFalseValidateAuthorityAsync() Trace.WriteLine("Acquire a token using a not so common authority alias"); #pragma warning disable CS0618 // Type or member is obsolete - _ = await Assert.ThrowsExceptionAsync(() => + _ = await Assert.ThrowsExactlyAsync(() => pca.AcquireTokenByUsernamePassword( s_scopes, user.Upn, diff --git a/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/LongRunningOnBehalfOfTests.cs b/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/LongRunningOnBehalfOfTests.cs index 9defad54f7..951bd5ff81 100644 --- a/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/LongRunningOnBehalfOfTests.cs +++ b/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/LongRunningOnBehalfOfTests.cs @@ -285,7 +285,7 @@ public async Task NormalOboThenLongRunningAcquire_WithTheSameKey_TestAsync() TokenCacheHelper.ExpireAllAccessTokens(cca.UserTokenCacheInternal); // AcquireLR - throws because no RT - var exception = await Assert.ThrowsExceptionAsync( + var exception = await Assert.ThrowsExactlyAsync( () => cca.AcquireTokenInLongRunningProcess(s_scopes.ToArray(), oboCacheKey) .ExecuteAsync()) .ConfigureAwait(false); @@ -421,7 +421,7 @@ public async Task AcquireTokenInLongRunningObo_WithNoTokensFound_TestAsync() string oboCacheKey = "obo-cache-key"; - var ex = await Assert.ThrowsExceptionAsync(async () => + var ex = await Assert.ThrowsExactlyAsync(async () => await cca.AcquireTokenInLongRunningProcess(s_scopes, oboCacheKey).ExecuteAsync().ConfigureAwait(false) ).ConfigureAwait(false); diff --git a/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/ManagedIdentityTests.NetFwk.cs b/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/ManagedIdentityTests.NetFwk.cs index 0d403d7c33..fb02984b02 100644 --- a/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/ManagedIdentityTests.NetFwk.cs +++ b/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/ManagedIdentityTests.NetFwk.cs @@ -299,7 +299,7 @@ public async Task ManagedIdentityRequestFailureCheckAsync(MsiAzureResource azure IManagedIdentityApplication mia = CreateMIAWithProxy(uri, userIdentity, userAssignedIdentityId); //Act - MsalServiceException ex = await Assert.ThrowsExceptionAsync(async () => + MsalServiceException ex = await Assert.ThrowsExactlyAsync(async () => { await mia .AcquireTokenForManagedIdentity(s_msi_scopes) @@ -341,7 +341,7 @@ public async Task MSIWrongScopesAsync(MsiAzureResource azureResource, string use IManagedIdentityApplication mia = CreateMIAWithProxy(uri, userIdentity, userAssignedIdentityId); //Act - MsalServiceException ex = await Assert.ThrowsExceptionAsync(async () => + MsalServiceException ex = await Assert.ThrowsExactlyAsync(async () => { await mia .AcquireTokenForManagedIdentity(s_wrong_msi_scopes) diff --git a/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/MsalCacheStorageIntegrationTests.cs b/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/MsalCacheStorageIntegrationTests.cs index 1975a1a458..ba019f468d 100644 --- a/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/MsalCacheStorageIntegrationTests.cs +++ b/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/MsalCacheStorageIntegrationTests.cs @@ -196,7 +196,7 @@ public void MsalTestClear() store.ReadData(); var store2 = Storage.Create(s_storageCreationProperties, logger: _logger); - Assert.ThrowsException(() => store.WriteData(null)); + Assert.ThrowsExactly(() => store.WriteData(null)); byte[] data = { 2, 2, 3 }; store.WriteData(data); diff --git a/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/OnBehalfOfTests.cs b/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/OnBehalfOfTests.cs index 5575ed2c09..19c8a8aa09 100644 --- a/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/OnBehalfOfTests.cs +++ b/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/OnBehalfOfTests.cs @@ -90,12 +90,12 @@ public async Task OboAndSilent_ReturnsCorrectTokens_TestAsync(bool serializeCach // Asserts // Silent calls should throw - await Assert.ThrowsExceptionAsync(() => + await Assert.ThrowsExactlyAsync(() => cca.AcquireTokenSilent(s_scopes, user1AuthResult.Account) .ExecuteAsync(CancellationToken.None) ).ConfigureAwait(false); - await Assert.ThrowsExceptionAsync(() => + await Assert.ThrowsExactlyAsync(() => cca.AcquireTokenSilent(s_scopes, user2AuthResult.Account) .ExecuteAsync(CancellationToken.None) ).ConfigureAwait(false); @@ -135,12 +135,12 @@ await Assert.ThrowsExceptionAsync(() => Assert.HasCount(2, oboTokens); // Silent calls should throw - await Assert.ThrowsExceptionAsync(() => + await Assert.ThrowsExactlyAsync(() => cca.AcquireTokenSilent(s_scopes, user1AuthResult.Account) .ExecuteAsync(CancellationToken.None) ).ConfigureAwait(false); - await Assert.ThrowsExceptionAsync(() => + await Assert.ThrowsExactlyAsync(() => cca.AcquireTokenSilent(s_scopes, user2AuthResult.Account) .ExecuteAsync(CancellationToken.None) ).ConfigureAwait(false); diff --git a/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/RuntimeBrokerTests.cs b/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/RuntimeBrokerTests.cs index c3f23c8d32..0ff4fe19c7 100644 --- a/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/RuntimeBrokerTests.cs +++ b/tests/Microsoft.Identity.Test.Integration.netcore/HeadlessTests/RuntimeBrokerTests.cs @@ -157,7 +157,7 @@ public async Task WamInvalidROPC_ThrowsException_TestAsync() .Build(); #pragma warning disable CS0618 // Type or member is obsolete - MsalServiceException ex = await Assert.ThrowsExceptionAsync(() => + MsalServiceException ex = await Assert.ThrowsExactlyAsync(() => pca.AcquireTokenByUsernamePassword( scopes, "noUser", @@ -254,7 +254,7 @@ public async Task WamUsernamePasswordRequestAsync() Assert.IsNotNull(accounts); - await Assert.ThrowsExceptionAsync( + await Assert.ThrowsExactlyAsync( () => pca.AcquireTokenSilent(scopes, account).ExecuteAsync()) .ConfigureAwait(false); } @@ -468,7 +468,7 @@ public async Task WamAddDefaultScopesWhenNoScopesArePassedAsync(string scopes) // Act if (SharedUtilities.IsLinuxPlatform()) { - var exLinux = await Assert.ThrowsExceptionAsync( + var exLinux = await Assert.ThrowsExactlyAsync( () => pca.AcquireTokenSilent(new string[] { scopes }, PublicClientApplication.OperatingSystemAccount) .ExecuteAsync()) .ConfigureAwait(false); @@ -476,7 +476,7 @@ public async Task WamAddDefaultScopesWhenNoScopesArePassedAsync(string scopes) } else { - var ex = await Assert.ThrowsExceptionAsync( + var ex = await Assert.ThrowsExactlyAsync( () => pca.AcquireTokenSilent(new string[] { scopes }, PublicClientApplication.OperatingSystemAccount) .ExecuteAsync()) .ConfigureAwait(false); diff --git a/tests/Microsoft.Identity.Test.Integration.netcore/SeleniumTests/FociTests.cs b/tests/Microsoft.Identity.Test.Integration.netcore/SeleniumTests/FociTests.cs index 11ad15e438..4e1956a22d 100644 --- a/tests/Microsoft.Identity.Test.Integration.netcore/SeleniumTests/FociTests.cs +++ b/tests/Microsoft.Identity.Test.Integration.netcore/SeleniumTests/FociTests.cs @@ -87,7 +87,7 @@ public async Task FociSignInSignOutAsync() userCacheAccess3.AssertAccessCounts(0, 0); Trace.WriteLine("Apps that are not part of the family cannot get tokens this way."); - await Assert.ThrowsExceptionAsync(() => pca_nonFam + await Assert.ThrowsExactlyAsync(() => pca_nonFam .AcquireTokenSilent(s_scopes, user.Upn) .ExecuteAsync()) .ConfigureAwait(false); diff --git a/tests/Microsoft.Identity.Test.Integration.netcore/SeleniumTests/SeleniumInfrastructureTests.NetFwk.cs b/tests/Microsoft.Identity.Test.Integration.netcore/SeleniumTests/SeleniumInfrastructureTests.NetFwk.cs index 346b4027f3..7f615a0b89 100644 --- a/tests/Microsoft.Identity.Test.Integration.netcore/SeleniumTests/SeleniumInfrastructureTests.NetFwk.cs +++ b/tests/Microsoft.Identity.Test.Integration.netcore/SeleniumTests/SeleniumInfrastructureTests.NetFwk.cs @@ -80,7 +80,7 @@ public async Task FailingTest_SeleniumFailureAsync() // The exception propagated to the test should be Selenium exception, // the test should not wait for the TCP listener to time out - await Assert.ThrowsExceptionAsync(() => pca + await Assert.ThrowsExactlyAsync(() => pca .AcquireTokenInteractive(s_scopes) .WithCustomWebUi(seleniumLogic) .ExecuteAsync(CancellationToken.None)) @@ -106,7 +106,7 @@ public async Task FailingTest_ListenerTimesOut_Async() // The exception propagated to the test should be Selenium exception, // the test should not wait for the TCP listener to time out - var ex = await Assert.ThrowsExceptionAsync(() => pca + var ex = await Assert.ThrowsExactlyAsync(() => pca .AcquireTokenInteractive(s_scopes) .WithCustomWebUi(seleniumLogic) .ExecuteAsync(new CancellationTokenSource(TimeSpan.FromSeconds(2)).Token)) diff --git a/tests/devapps/Directory.Packages.props b/tests/devapps/Directory.Packages.props index c5d4656b94..55979ffdd7 100644 --- a/tests/devapps/Directory.Packages.props +++ b/tests/devapps/Directory.Packages.props @@ -3,7 +3,7 @@ false true - + $(NoWarn);MSTest0001 From 497f73b002901505b73aab5e8876f51fe590ebfb Mon Sep 17 00:00:00 2001 From: Bogdan Gavril Date: Wed, 17 Dec 2025 18:46:56 +0000 Subject: [PATCH 5/5] fixes? --- .../AcquireTokenInteractiveBuilderTests.cs | 2 +- .../ApiConfigTests/AuthorityTests.cs | 2 +- ...nfidentialClientApplicationBuilderTests.cs | 6 ++-- .../PublicClientApplicationBuilderTests.cs | 26 ++++++++-------- .../AppTokenProviderTests.cs | 2 +- .../AuthScheme/SSHCertTests.cs | 10 +++--- .../BrokerTests/BrokerRequestTests.cs | 4 +-- .../BrokerTests/RuntimeBrokerTests.cs | 4 +-- .../CacheExtension/MsalCacheHelperTests.cs | 8 ++--- .../CacheExtension/MsalCacheStorageTests.cs | 18 +++++------ .../CacheTests/CacheFailureTests.cs | 2 +- .../CacheTests/InternalCacheOptionsTests.cs | 16 +++++----- .../CacheTests/TokenCacheNotificationTests.cs | 4 +-- .../CoreTests/HttpTests/HttpManagerTests.cs | 14 ++++----- .../InstanceTests/AadAuthorityTests.cs | 2 +- .../InstanceTests/GenericAuthorityTests.cs | 8 ++--- .../InstanceDiscoveryManagerTests.cs | 2 +- .../CoreTests/OAuth2Tests/ClaimsTest.cs | 2 +- .../CoreTests/WsTrustTests/WsTrustTests.cs | 2 +- .../CryptographyTests.cs | 2 +- .../ExperimentalFeatureTests.cs | 2 +- .../ExceptionTests/MsalExceptionTests.cs | 18 +++++------ .../ManagedIdentityTests/ImdsTests.cs | 4 +-- .../ManagedIdentityTests.cs | 2 +- .../OAuthClientTests.cs | 5 ++- .../PublicApiTests/AcquireTokenSilentTests.cs | 10 +++--- .../AuthenticationOperationTests.cs | 2 +- .../PublicApiTests/ClientAssertionTests.cs | 8 ++--- .../ClientCredentialWithRegionTests.cs | 10 +++--- .../ConfidentialClientApplicationTests.cs | 20 ++++++------ .../PublicApiTests/MtlsPopTests.cs | 10 +++--- .../PublicClientApplicationTests.cs | 6 ++-- .../PublicClientApplicationTestsWithB2C.cs | 4 +-- .../PublicApiTests/RefreshInTests.cs | 4 +-- .../RequestsTests/DeviceCodeRequestTests.cs | 4 +-- .../RequestsTests/FociTests.cs | 8 ++--- ...egratedWindowsAuthUsernamePasswordTests.cs | 20 ++++++------ .../RequestsTests/InteractiveRequestTests.cs | 12 +++---- .../InteractiveRequestWithCustomWebUiTests.cs | 8 ++--- .../LongRunningOnBehalfOfTests.cs | 6 ++-- .../RequestsTests/SilentRequestTests.cs | 2 +- .../TelemetryTests/HttpTelemetryTests.cs | 14 ++++----- .../OTelInstrumentationTests.cs | 4 +-- .../TelemetryTests/RegionalTelemetryTests.cs | 2 +- .../Throttling/ThrottlingAcceptanceTests.cs | 31 +++++++++---------- .../UtilTests/RetryOperationHelperTest.cs | 4 +-- .../WebUITests/DefaultOsBrowserWebUiTests.cs | 6 ++-- .../HttpListenerInterceptorTests.cs | 6 ++-- .../WebUITests/NetCoreWebUIFactoryTests.cs | 2 +- .../pop/PoPTests.cs | 12 +++---- .../pop/PopAuthenticationOperationTests.cs | 8 ++--- .../NetCoreTestApp/NetCoreTestApp.csproj | 1 + 52 files changed, 194 insertions(+), 197 deletions(-) diff --git a/tests/Microsoft.Identity.Test.Unit/ApiConfigTests/AcquireTokenInteractiveBuilderTests.cs b/tests/Microsoft.Identity.Test.Unit/ApiConfigTests/AcquireTokenInteractiveBuilderTests.cs index dbc1f897a1..5f7e873b94 100644 --- a/tests/Microsoft.Identity.Test.Unit/ApiConfigTests/AcquireTokenInteractiveBuilderTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/ApiConfigTests/AcquireTokenInteractiveBuilderTests.cs @@ -143,7 +143,7 @@ await AcquireTokenInteractiveParameterBuilder.Create(_harness.Executor, TestCons public async Task TestAcquireTokenInteractive_EmbeddedAndSystemOptions_Async() { var options = new SystemWebViewOptions(); - var ex = await Assert.ThrowsExceptionAsync(() => + var ex = await Assert.ThrowsExactlyAsync(() => AcquireTokenInteractiveParameterBuilder.Create(_harness.Executor, TestConstants.s_scope) .WithSystemWebViewOptions(options) diff --git a/tests/Microsoft.Identity.Test.Unit/ApiConfigTests/AuthorityTests.cs b/tests/Microsoft.Identity.Test.Unit/ApiConfigTests/AuthorityTests.cs index 86f9de9445..083b81742a 100644 --- a/tests/Microsoft.Identity.Test.Unit/ApiConfigTests/AuthorityTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/ApiConfigTests/AuthorityTests.cs @@ -362,7 +362,7 @@ public void VerifyAuthorityTest() public async Task AuthorityMismatchTestAsync() { _testRequestContext.ServiceBundle.Config.Authority = s_utidAuthority; - var ex = await Assert.ThrowsExceptionAsync( + var ex = await Assert.ThrowsExactlyAsync( () => Authority.CreateAuthorityForRequestAsync(_testRequestContext, s_b2cAuthority.AuthorityInfo, null)) .ConfigureAwait(false); diff --git a/tests/Microsoft.Identity.Test.Unit/AppConfigTests/ConfidentialClientApplicationBuilderTests.cs b/tests/Microsoft.Identity.Test.Unit/AppConfigTests/ConfidentialClientApplicationBuilderTests.cs index a334ebbf50..0d999c5bb3 100644 --- a/tests/Microsoft.Identity.Test.Unit/AppConfigTests/ConfidentialClientApplicationBuilderTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/AppConfigTests/ConfidentialClientApplicationBuilderTests.cs @@ -399,7 +399,7 @@ public void TestConstructor_WithValidInstanceDicoveryMetadata() public void TestConstructor_InstanceMetadata_ValidateAuthority_MutuallyExclusive() { string instanceMetadataJson = File.ReadAllText(ResourceHelper.GetTestResourceRelativePath("CustomInstanceMetadata.json")); - var ex = Assert.ThrowsException(() => ConfidentialClientApplicationBuilder.Create(TestConstants.ClientId) + var ex = Assert.ThrowsExactly(() => ConfidentialClientApplicationBuilder.Create(TestConstants.ClientId) .WithInstanceDiscoveryMetadata(instanceMetadataJson) .WithClientSecret("cats") .WithAuthority("https://some.authority/bogus/", true) @@ -410,7 +410,7 @@ public void TestConstructor_InstanceMetadata_ValidateAuthority_MutuallyExclusive [TestMethod] public void TestConstructor_BadInstanceMetadata() { - var ex = Assert.ThrowsException(() => ConfidentialClientApplicationBuilder.Create(TestConstants.ClientId) + var ex = Assert.ThrowsExactly(() => ConfidentialClientApplicationBuilder.Create(TestConstants.ClientId) .WithInstanceDiscoveryMetadata("{bad_json_metadata") .WithClientSecret("cats") .Build()); @@ -501,7 +501,7 @@ public async Task Claims_Fail_WhenClaimsIsNotJson_Async() .WithClientCapabilities(TestConstants.ClientCapabilities) .BuildConcrete(); - var ex = await Assert.ThrowsExceptionAsync( + var ex = await Assert.ThrowsExactlyAsync( () => app .AcquireTokenForClient(TestConstants.s_scope) .WithClaims("claims_that_are_not_json") diff --git a/tests/Microsoft.Identity.Test.Unit/AppConfigTests/PublicClientApplicationBuilderTests.cs b/tests/Microsoft.Identity.Test.Unit/AppConfigTests/PublicClientApplicationBuilderTests.cs index 2498473f44..2d999d4cd0 100644 --- a/tests/Microsoft.Identity.Test.Unit/AppConfigTests/PublicClientApplicationBuilderTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/AppConfigTests/PublicClientApplicationBuilderTests.cs @@ -158,7 +158,7 @@ public void TestConstructor_WithValidInstanceDicoveryMetadata() public void TestConstructor_InstanceMetadata_ValidateAuthority_MutuallyExclusive() { string instanceMetadataJson = File.ReadAllText(ResourceHelper.GetTestResourceRelativePath("CustomInstanceMetadata.json")); - var ex = Assert.ThrowsException(() => PublicClientApplicationBuilder.Create(TestConstants.ClientId) + var ex = Assert.ThrowsExactly(() => PublicClientApplicationBuilder.Create(TestConstants.ClientId) .WithInstanceDiscoveryMetadata(instanceMetadataJson) .WithAuthority("https://some.authority/bogus/", true) .Build()); @@ -168,7 +168,7 @@ public void TestConstructor_InstanceMetadata_ValidateAuthority_MutuallyExclusive [TestMethod] public void TestConstructor_InstanceMetadataUri_ValidateAuthority_MutuallyExclusive() { - var ex = Assert.ThrowsException(() => PublicClientApplicationBuilder.Create(TestConstants.ClientId) + var ex = Assert.ThrowsExactly(() => PublicClientApplicationBuilder.Create(TestConstants.ClientId) .WithInstanceDiscoveryMetadata(new Uri("https://some_uri.com")) .WithAuthority("https://some.authority/bogus/", true) .Build()); @@ -180,7 +180,7 @@ public void TestConstructor_InstanceMetadataUri_ValidateAuthority_MutuallyExclus public void TestConstructor_WithInstanceDiscoveryMetadata_OnlyOneOverload() { string instanceMetadataJson = File.ReadAllText(ResourceHelper.GetTestResourceRelativePath("CustomInstanceMetadata.json")); - var ex = Assert.ThrowsException(() => PublicClientApplicationBuilder.Create(TestConstants.ClientId) + var ex = Assert.ThrowsExactly(() => PublicClientApplicationBuilder.Create(TestConstants.ClientId) .WithInstanceDiscoveryMetadata(instanceMetadataJson) .WithInstanceDiscoveryMetadata(new Uri("https://some_uri.com")) .WithAuthority("https://some.authority/bogus/", true) @@ -191,7 +191,7 @@ public void TestConstructor_WithInstanceDiscoveryMetadata_OnlyOneOverload() [TestMethod] public void TestConstructor_BadInstanceMetadata() { - var ex = Assert.ThrowsException(() => PublicClientApplicationBuilder.Create(TestConstants.ClientId) + var ex = Assert.ThrowsExactly(() => PublicClientApplicationBuilder.Create(TestConstants.ClientId) .WithInstanceDiscoveryMetadata("{bad_json_metadata") .Build()); @@ -451,39 +451,39 @@ public void TestAuthorityWithTenant() [TestMethod] public void AuthorityNullArgs() { - Assert.ThrowsException(() => + Assert.ThrowsExactly(() => PublicClientApplicationBuilder.Create(TestConstants.ClientId) .WithAuthority((Uri)null)); - Assert.ThrowsException(() => + Assert.ThrowsExactly(() => PublicClientApplicationBuilder.Create(TestConstants.ClientId) .WithAuthority((string)null)); - Assert.ThrowsException(() => + Assert.ThrowsExactly(() => PublicClientApplicationBuilder.Create(TestConstants.ClientId) .WithAuthority(" ")); - Assert.ThrowsException(() => + Assert.ThrowsExactly(() => PublicClientApplicationBuilder.Create(TestConstants.ClientId) .WithAuthority(null, "tid")); - Assert.ThrowsException(() => + Assert.ThrowsExactly(() => PublicClientApplicationBuilder.Create(TestConstants.ClientId) .WithAuthority("", "tid")); - Assert.ThrowsException(() => + Assert.ThrowsExactly(() => PublicClientApplicationBuilder.Create(TestConstants.ClientId) .WithAuthority("", Guid.NewGuid())); - Assert.ThrowsException(() => + Assert.ThrowsExactly(() => PublicClientApplicationBuilder.Create(TestConstants.ClientId) .WithAuthority("https://login.microsoftonline.com/", null)); - Assert.ThrowsException(() => + Assert.ThrowsExactly(() => PublicClientApplicationBuilder.Create(TestConstants.ClientId) .WithAuthority("https://login.microsoftonline.com/", " ")); - Assert.ThrowsException(() => + Assert.ThrowsExactly(() => PublicClientApplicationBuilder.Create(TestConstants.ClientId) .WithAuthority(AzureCloudInstance.AzureChina, "")); } diff --git a/tests/Microsoft.Identity.Test.Unit/AppTokenProviderTests.cs b/tests/Microsoft.Identity.Test.Unit/AppTokenProviderTests.cs index e8cb8950d5..b969891a0a 100644 --- a/tests/Microsoft.Identity.Test.Unit/AppTokenProviderTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/AppTokenProviderTests.cs @@ -240,7 +240,7 @@ public async Task CanceledRequest_ThrowsTaskCanceledExceptionAsync() var tokenSource = new CancellationTokenSource(); tokenSource.Cancel(); - await Assert.ThrowsExceptionAsync( + await Assert.ThrowsExactlyAsync( () => app.AcquireTokenForClient(TestConstants.s_scope) .WithForceRefresh(true) .ExecuteAsync(tokenSource.Token)).ConfigureAwait(false); diff --git a/tests/Microsoft.Identity.Test.Unit/AuthScheme/SSHCertTests.cs b/tests/Microsoft.Identity.Test.Unit/AuthScheme/SSHCertTests.cs index f2fa86dad1..234b9e8efe 100644 --- a/tests/Microsoft.Identity.Test.Unit/AuthScheme/SSHCertTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/AuthScheme/SSHCertTests.cs @@ -18,17 +18,17 @@ public class SSHCertTests [TestMethod] public void NullArgs() { - Assert.ThrowsException(() => new SSHCertAuthenticationOperation(null, "jwk")); - Assert.ThrowsException(() => new SSHCertAuthenticationOperation("", "jwk")); - Assert.ThrowsException(() => new SSHCertAuthenticationOperation("kid", "")); - Assert.ThrowsException(() => new SSHCertAuthenticationOperation("kid", null)); + Assert.ThrowsExactly(() => new SSHCertAuthenticationOperation(null, "jwk")); + Assert.ThrowsExactly(() => new SSHCertAuthenticationOperation("", "jwk")); + Assert.ThrowsExactly(() => new SSHCertAuthenticationOperation("kid", "")); + Assert.ThrowsExactly(() => new SSHCertAuthenticationOperation("kid", null)); } [TestMethod] public void NoAuthPrefix() { var scheme = new SSHCertAuthenticationOperation("kid", "jwk"); - MsalClientException ex = Assert.ThrowsException(() => scheme.AuthorizationHeaderPrefix); + MsalClientException ex = Assert.ThrowsExactly(() => scheme.AuthorizationHeaderPrefix); Assert.AreEqual(MsalError.SSHCertUsedAsHttpHeader, ex.ErrorCode); } diff --git a/tests/Microsoft.Identity.Test.Unit/BrokerTests/BrokerRequestTests.cs b/tests/Microsoft.Identity.Test.Unit/BrokerTests/BrokerRequestTests.cs index ae7c6220d9..63f3664d78 100644 --- a/tests/Microsoft.Identity.Test.Unit/BrokerTests/BrokerRequestTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/BrokerTests/BrokerRequestTests.cs @@ -268,7 +268,7 @@ public void BrokerGetAccountsAsyncOnUnsupportedPlatformTest() { IBroker broker = harness.ServiceBundle.PlatformProxy.CreateBroker(harness.ServiceBundle.Config, null); - Assert.ThrowsExceptionAsync( + Assert.ThrowsExactlyAsync( () => broker.GetAccountsAsync( TestConstants.ClientId, TestConstants.RedirectUri, @@ -286,7 +286,7 @@ public void BrokerRemoveAccountAsyncOnUnsupportedPlatformTest() { IBroker broker = harness.ServiceBundle.PlatformProxy.CreateBroker(harness.ServiceBundle.Config, null); - Assert.ThrowsExceptionAsync(() => broker.RemoveAccountAsync( + Assert.ThrowsExactlyAsync(() => broker.RemoveAccountAsync( harness.ServiceBundle.Config, new Account("test", "test", "test"))).ConfigureAwait(false); } } diff --git a/tests/Microsoft.Identity.Test.Unit/BrokerTests/RuntimeBrokerTests.cs b/tests/Microsoft.Identity.Test.Unit/BrokerTests/RuntimeBrokerTests.cs index a5c27b12aa..47cdfe4015 100644 --- a/tests/Microsoft.Identity.Test.Unit/BrokerTests/RuntimeBrokerTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/BrokerTests/RuntimeBrokerTests.cs @@ -109,7 +109,7 @@ public async Task ThrowOnNoHandleAsync() var pca = pcaBuilder.Build(); // no window handle - throw - var ex = await Assert.ThrowsExceptionAsync( + var ex = await Assert.ThrowsExactlyAsync( () => pca.AcquireTokenInteractive(new[] { "" }).ExecuteAsync()).ConfigureAwait(false); Assert.AreEqual("window_handle_required", ex.ErrorCode); @@ -120,7 +120,7 @@ public async Task ThrowOnNoHandleAsync() [TestMethod] public void HandleInstallUrl_Throws() { - Assert.ThrowsException(() => _wamBroker.HandleInstallUrl("http://app")); + Assert.ThrowsExactly(() => _wamBroker.HandleInstallUrl("http://app")); } [TestMethod] diff --git a/tests/Microsoft.Identity.Test.Unit/CacheExtension/MsalCacheHelperTests.cs b/tests/Microsoft.Identity.Test.Unit/CacheExtension/MsalCacheHelperTests.cs index 14129d8e73..3779d65d3e 100644 --- a/tests/Microsoft.Identity.Test.Unit/CacheExtension/MsalCacheHelperTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/CacheExtension/MsalCacheHelperTests.cs @@ -80,7 +80,7 @@ public void ImportExport_ThrowException() cacheAccessor.Read().Throws(ex); // Act - var actualEx = Assert.ThrowsException( + var actualEx = Assert.ThrowsExactly( () => helper.LoadUnencryptedTokenCache()); // Assert @@ -90,7 +90,7 @@ public void ImportExport_ThrowException() cacheAccessor.WhenForAnyArgs(c => c.Write(default)).Throw(ex); // Act - actualEx = Assert.ThrowsException( + actualEx = Assert.ThrowsExactly( () => helper.SaveUnencryptedTokenCache(new byte[0])); // Assert @@ -353,7 +353,7 @@ public async Task RegressionTest_CorruptedCacheIsDeleted_NoEvent_Async() helper.RegisterCache(pca.UserTokenCache); // Act - var ex = await Assert.ThrowsExceptionAsync( + var ex = await Assert.ThrowsExactlyAsync( () => pca.GetAccountsAsync()) .ConfigureAwait(false); @@ -540,7 +540,7 @@ public async Task EventNeedsConfigurationAsync() var helper = await MsalCacheHelper.CreateAsync(properties).ConfigureAwait(true); // event is fired asynchronously, test has to wait for it for a while - Assert.ThrowsException( + Assert.ThrowsExactly( () => helper.CacheChanged += (_, _) => { Assert.Fail("Should not fire"); diff --git a/tests/Microsoft.Identity.Test.Unit/CacheExtension/MsalCacheStorageTests.cs b/tests/Microsoft.Identity.Test.Unit/CacheExtension/MsalCacheStorageTests.cs index 634b8b9d58..fc67c5134d 100644 --- a/tests/Microsoft.Identity.Test.Unit/CacheExtension/MsalCacheStorageTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/CacheExtension/MsalCacheStorageTests.cs @@ -52,7 +52,7 @@ public void ReadCanThrowExceptions() var storage = new Storage(s_storageCreationProperties, cacheAccessor, actualLogger); // Assert - Assert.ThrowsException( + Assert.ThrowsExactly( () => storage.ReadData()); } @@ -66,7 +66,7 @@ public void WriteCanThrowExceptions() var storage = new Storage(s_storageCreationProperties, cacheAccessor, actualLogger); // Assert - Assert.ThrowsException( + Assert.ThrowsExactly( () => storage.WriteData(new byte[0])); } @@ -83,7 +83,7 @@ public void ClearCanThrowExceptions() storage.Clear(ignoreExceptions: true); // Assert - Assert.ThrowsException( + Assert.ThrowsExactly( () => storage.Clear(ignoreExceptions: false)); } @@ -150,7 +150,7 @@ public void VerifyPersistenceThrowsInnerExceptions() cacheAccessor.Read().Throws(exception); // Act - var ex = Assert.ThrowsException( + var ex = Assert.ThrowsExactly( () => storage.VerifyPersistence()); // Assert @@ -167,7 +167,7 @@ public void VerifyPersistenceThrowsIfDataReadIsEmpty() var storage = new Storage(s_storageCreationProperties, cacheAccessor, actualLogger); // Act - var ex = Assert.ThrowsException( + var ex = Assert.ThrowsExactly( () => storage.VerifyPersistence()); // Assert @@ -185,7 +185,7 @@ public void VerifyPersistenceThrowsIfDataReadIsDiffrentFromDataWritten() cacheAccessor.Read().Returns(Encoding.UTF8.GetBytes("other_dummy_data")); // Act - var ex = Assert.ThrowsException( + var ex = Assert.ThrowsExactly( () => storage.VerifyPersistence()); // Assert @@ -224,7 +224,7 @@ public void UnprotectedOptionMutuallyExclusiveWithOtherOptions() builder = builder.WithMacKeyChain(serviceName: "Microsoft.Developer.IdentityService", accountName: "MSALCache"); builder.WithUnprotectedFile(); - Assert.ThrowsException(() => builder.Build()); + Assert.ThrowsExactly(() => builder.Build()); builder = new StorageCreationPropertiesBuilder( Path.GetFileName(CacheFilePath), @@ -237,7 +237,7 @@ public void UnprotectedOptionMutuallyExclusiveWithOtherOptions() attribute1: new KeyValuePair("MsalClientID", "Microsoft.Developer.IdentityService"), attribute2: new KeyValuePair("MsalClientVersion", "1.0.0.0")); builder.WithUnprotectedFile(); - Assert.ThrowsException(() => builder.Build()); + Assert.ThrowsExactly(() => builder.Build()); builder = new StorageCreationPropertiesBuilder( Path.GetFileName(CacheFilePath), @@ -245,7 +245,7 @@ public void UnprotectedOptionMutuallyExclusiveWithOtherOptions() builder.WithLinuxUnprotectedFile(); builder.WithUnprotectedFile(); - Assert.ThrowsException(() => builder.Build()); + Assert.ThrowsExactly(() => builder.Build()); } } diff --git a/tests/Microsoft.Identity.Test.Unit/CacheTests/CacheFailureTests.cs b/tests/Microsoft.Identity.Test.Unit/CacheTests/CacheFailureTests.cs index 2c6763638b..2339330fc1 100644 --- a/tests/Microsoft.Identity.Test.Unit/CacheTests/CacheFailureTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/CacheTests/CacheFailureTests.cs @@ -40,7 +40,7 @@ public async Task MsalOnly_FailToDeserializeTestsAsync() } }); - var ex = await Assert.ThrowsExceptionAsync( + var ex = await Assert.ThrowsExactlyAsync( () => cca.AcquireTokenForClient(TestConstants.s_scope).ExecuteAsync()) .ConfigureAwait(false); diff --git a/tests/Microsoft.Identity.Test.Unit/CacheTests/InternalCacheOptionsTests.cs b/tests/Microsoft.Identity.Test.Unit/CacheTests/InternalCacheOptionsTests.cs index 30c5e446b2..f00056f51a 100644 --- a/tests/Microsoft.Identity.Test.Unit/CacheTests/InternalCacheOptionsTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/CacheTests/InternalCacheOptionsTests.cs @@ -43,25 +43,25 @@ public void OptionsAndExternalCacheAreExclusive() .Build(); app3.UserTokenCache.SetAfterAccess((_) => { }); app3.AppTokenCache.SetBeforeAccess((_) => { }); - var ex = Assert.ThrowsException(() => app3.UserTokenCache.SetCacheOptions(CacheOptions.EnableSharedCacheOptions)); + var ex = Assert.ThrowsExactly(() => app3.UserTokenCache.SetCacheOptions(CacheOptions.EnableSharedCacheOptions)); Assert.AreEqual(MsalError.StaticCacheWithExternalSerialization, ex.ErrorCode); - ex = Assert.ThrowsException(() => app3.AppTokenCache.SetCacheOptions(CacheOptions.EnableSharedCacheOptions)); + ex = Assert.ThrowsExactly(() => app3.AppTokenCache.SetCacheOptions(CacheOptions.EnableSharedCacheOptions)); Assert.AreEqual(MsalError.StaticCacheWithExternalSerialization, ex.ErrorCode); void AssertExclusivity(ITokenCache tokenCache) { - var ex = Assert.ThrowsException(() => tokenCache.SetAfterAccess((_) => { })); + var ex = Assert.ThrowsExactly(() => tokenCache.SetAfterAccess((_) => { })); Assert.AreEqual(MsalError.StaticCacheWithExternalSerialization, ex.ErrorCode); - ex = Assert.ThrowsException(() => tokenCache.SetBeforeAccess((_) => { })); + ex = Assert.ThrowsExactly(() => tokenCache.SetBeforeAccess((_) => { })); Assert.AreEqual(MsalError.StaticCacheWithExternalSerialization, ex.ErrorCode); - ex = Assert.ThrowsException(() => tokenCache.SetBeforeWrite((_) => { })); + ex = Assert.ThrowsExactly(() => tokenCache.SetBeforeWrite((_) => { })); Assert.AreEqual(MsalError.StaticCacheWithExternalSerialization, ex.ErrorCode); - ex = Assert.ThrowsException(() => tokenCache.SetBeforeAccessAsync((_) => Task.CompletedTask)); + ex = Assert.ThrowsExactly(() => tokenCache.SetBeforeAccessAsync((_) => Task.CompletedTask)); Assert.AreEqual(MsalError.StaticCacheWithExternalSerialization, ex.ErrorCode); - ex = Assert.ThrowsException(() => tokenCache.SetAfterAccessAsync((_) => Task.CompletedTask)); + ex = Assert.ThrowsExactly(() => tokenCache.SetAfterAccessAsync((_) => Task.CompletedTask)); Assert.AreEqual(MsalError.StaticCacheWithExternalSerialization, ex.ErrorCode); - ex = Assert.ThrowsException(() => tokenCache.SetBeforeWriteAsync((_) => Task.CompletedTask)); + ex = Assert.ThrowsExactly(() => tokenCache.SetBeforeWriteAsync((_) => Task.CompletedTask)); Assert.AreEqual(MsalError.StaticCacheWithExternalSerialization, ex.ErrorCode); } diff --git a/tests/Microsoft.Identity.Test.Unit/CacheTests/TokenCacheNotificationTests.cs b/tests/Microsoft.Identity.Test.Unit/CacheTests/TokenCacheNotificationTests.cs index 32839fc790..c6e92c6f3b 100644 --- a/tests/Microsoft.Identity.Test.Unit/CacheTests/TokenCacheNotificationTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/CacheTests/TokenCacheNotificationTests.cs @@ -69,7 +69,7 @@ private static async Task RunAfterAccessFailureAsync( pca.UserTokenCache.SetAfterAccess(_ => { afterAccessCalled = true; }); - await Assert.ThrowsExceptionAsync( + await Assert.ThrowsExactlyAsync( operationThatTouchesCache).ConfigureAwait(false); Assert.IsTrue(beforeAccessCalled); @@ -348,7 +348,7 @@ public async Task MsalOperationCanBeCancelledFromTheCacheAsync() throw new OperationCanceledException(); }); - await Assert.ThrowsExceptionAsync(() => app.GetAccountsAsync()).ConfigureAwait(false); + await Assert.ThrowsExactlyAsync(() => app.GetAccountsAsync()).ConfigureAwait(false); } } diff --git a/tests/Microsoft.Identity.Test.Unit/CoreTests/HttpTests/HttpManagerTests.cs b/tests/Microsoft.Identity.Test.Unit/CoreTests/HttpTests/HttpManagerTests.cs index 66b39525d4..c14b44042a 100644 --- a/tests/Microsoft.Identity.Test.Unit/CoreTests/HttpTests/HttpManagerTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/CoreTests/HttpTests/HttpManagerTests.cs @@ -351,7 +351,7 @@ public async Task NoResiliencyIfRetryAfterHeaderPresentAsync(bool useTimeSpanRet new System.Net.Http.Headers.RetryConditionHeaderValue(TimeSpan.FromSeconds(1)) : new System.Net.Http.Headers.RetryConditionHeaderValue(DateTimeOffset.UtcNow + TimeSpan.FromMinutes(2)); - var exc = await Assert.ThrowsExceptionAsync(() => + var exc = await Assert.ThrowsExactlyAsync(() => httpManager.SendRequestAsync( new Uri(TestConstants.AuthorityHomeTenant + "oauth2/token"), headers: null, @@ -443,7 +443,7 @@ public async Task TestSendPostWithHttp500TypeFailureAsync() httpManager.AddResiliencyMessageMockHandler(HttpMethod.Post, HttpStatusCode.ServiceUnavailable); } - var exc = await Assert.ThrowsExceptionAsync(() => + var exc = await Assert.ThrowsExactlyAsync(() => httpManager.SendRequestAsync( new Uri(TestConstants.AuthorityHomeTenant + "oauth2/token"), headers: null, @@ -475,7 +475,7 @@ public async Task TestSendGetWithRetryOnTimeoutFailureAsync() httpManager.AddRequestTimeoutResponseMessageMockHandler(HttpMethod.Get); } - var exc = await Assert.ThrowsExceptionAsync(() => + var exc = await Assert.ThrowsExactlyAsync(() => httpManager.SendRequestAsync( new Uri(TestConstants.AuthorityHomeTenant + "oauth2/token"), headers: null, @@ -508,7 +508,7 @@ public async Task TestSendPostWithRetryOnTimeoutFailureAsync() httpManager.AddRequestTimeoutResponseMessageMockHandler(HttpMethod.Post); } - var exc = await Assert.ThrowsExceptionAsync(() => + var exc = await Assert.ThrowsExactlyAsync(() => httpManager.SendRequestAsync( new Uri(TestConstants.AuthorityHomeTenant + "oauth2/token"), headers: new Dictionary(), @@ -551,7 +551,7 @@ public async Task TestCorrelationIdWithRetryOnTimeoutFailureAsync(bool addCorrel headers.Add(OAuth2Header.CorrelationId, correlationId.ToString()); } - var exc = await Assert.ThrowsExceptionAsync(() => + var exc = await Assert.ThrowsExactlyAsync(() => httpManager.SendRequestAsync( new Uri(TestConstants.AuthorityHomeTenant + "oauth2/token"), headers: headers, @@ -599,7 +599,7 @@ public async Task TestRetryOnTimeoutWithHeadersButNoCorrelationIdAsync() ["some-other-header"] = "some-value" }; - var exc = await Assert.ThrowsExceptionAsync(() => + var exc = await Assert.ThrowsExactlyAsync(() => httpManager.SendRequestAsync( new Uri(TestConstants.AuthorityHomeTenant + "oauth2/token"), headers: headers, @@ -646,7 +646,7 @@ public async Task TestWithCorrelationId_RetryOnTimeoutFailureAsync() var userAssertion = new UserAssertion(TestConstants.DefaultAccessToken); // Act - var exc = await Assert.ThrowsExceptionAsync(() => + var exc = await Assert.ThrowsExactlyAsync(() => app.AcquireTokenForClient(TestConstants.s_scope) .WithCorrelationId(correlationId) .ExecuteAsync()) diff --git a/tests/Microsoft.Identity.Test.Unit/CoreTests/InstanceTests/AadAuthorityTests.cs b/tests/Microsoft.Identity.Test.Unit/CoreTests/InstanceTests/AadAuthorityTests.cs index a871ed7ba5..f55dbf166b 100644 --- a/tests/Microsoft.Identity.Test.Unit/CoreTests/InstanceTests/AadAuthorityTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/CoreTests/InstanceTests/AadAuthorityTests.cs @@ -154,7 +154,7 @@ public void MalformedAuthorityInitTest() var host = string.Concat("test", TestConstants.ProductionPrefNetworkEnvironment, "/"); var fullAuthority = string.Concat(host, TestConstants.TenantId); - Assert.ThrowsException(() => + Assert.ThrowsExactly(() => { publicClient = PublicClientApplicationBuilder.Create(TestConstants.ClientId) .WithAuthority(fullAuthority) diff --git a/tests/Microsoft.Identity.Test.Unit/CoreTests/InstanceTests/GenericAuthorityTests.cs b/tests/Microsoft.Identity.Test.Unit/CoreTests/InstanceTests/GenericAuthorityTests.cs index c1db1189d0..c1a0637b83 100644 --- a/tests/Microsoft.Identity.Test.Unit/CoreTests/InstanceTests/GenericAuthorityTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/CoreTests/InstanceTests/GenericAuthorityTests.cs @@ -314,7 +314,7 @@ public async Task BadOidcResponse_ThrowsException_Async(string badOidcResponseTy var confidentailClientApp = (ConfidentialClientApplication)app; Assert.AreEqual(AuthorityType.Generic, confidentailClientApp.AuthorityInfo.AuthorityType); - var ex = await Assert.ThrowsExceptionAsync(() => + var ex = await Assert.ThrowsExactlyAsync(() => app.AcquireTokenForClient(new[] { "api" }) .ExecuteAsync()) .ConfigureAwait(false); @@ -359,7 +359,7 @@ public async Task Oidc_Malformed_Failure_Async() var confidentailClientApp = (ConfidentialClientApplication)app; Assert.AreEqual(AuthorityType.Generic, confidentailClientApp.AuthorityInfo.AuthorityType); - var ex = await Assert.ThrowsExceptionAsync(() => + var ex = await Assert.ThrowsExactlyAsync(() => app.AcquireTokenForClient(new[] { "api" }) .ExecuteAsync()) .ConfigureAwait(false); @@ -374,7 +374,7 @@ public async Task Oidc_Malformed_Failure_Async() AadErrorCode: Constants.AadMissingScopeErrorCode, expectedUrl: $"{TestConstants.CiamCUDAuthorityMalformed}/connect/token"); - ex = await Assert.ThrowsExceptionAsync(() => + ex = await Assert.ThrowsExactlyAsync(() => app.AcquireTokenForClient(new[] { "api" }) .ExecuteAsync()) .ConfigureAwait(false); @@ -463,7 +463,7 @@ public async Task OidcIssuerValidation_ThrowsForNonMatchingIssuer_Async() ResponseMessage = MockHelpers.CreateSuccessResponseMessage(validOidcDocumentWithWrongIssuer) }); - var ex = await Assert.ThrowsExceptionAsync(() => + var ex = await Assert.ThrowsExactlyAsync(() => app.AcquireTokenForClient(new[] { "api" }).ExecuteAsync() ).ConfigureAwait(false); diff --git a/tests/Microsoft.Identity.Test.Unit/CoreTests/InstanceTests/InstanceDiscoveryManagerTests.cs b/tests/Microsoft.Identity.Test.Unit/CoreTests/InstanceTests/InstanceDiscoveryManagerTests.cs index ed94dad663..4c3346e295 100644 --- a/tests/Microsoft.Identity.Test.Unit/CoreTests/InstanceTests/InstanceDiscoveryManagerTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/CoreTests/InstanceTests/InstanceDiscoveryManagerTests.cs @@ -217,7 +217,7 @@ public async Task AuthorityValidationFailure_IsRethrown_Async() .Do(_ => throw validationException); // Act - var actualException = await Assert.ThrowsExceptionAsync(() => + var actualException = await Assert.ThrowsExactlyAsync(() => _discoveryManager.GetMetadataEntryAsync( AuthorityInfo.FromAuthorityUri("https://some_env.com/tid", true), _testRequestContext)) diff --git a/tests/Microsoft.Identity.Test.Unit/CoreTests/OAuth2Tests/ClaimsTest.cs b/tests/Microsoft.Identity.Test.Unit/CoreTests/OAuth2Tests/ClaimsTest.cs index c324cb9a38..c0f5ff3e3c 100644 --- a/tests/Microsoft.Identity.Test.Unit/CoreTests/OAuth2Tests/ClaimsTest.cs +++ b/tests/Microsoft.Identity.Test.Unit/CoreTests/OAuth2Tests/ClaimsTest.cs @@ -232,7 +232,7 @@ public async Task Claims_Fail_WhenClaimsIsNotJson_Async() .WithClientCapabilities(TestConstants.ClientCapabilities) .BuildConcrete(); - var ex = await Assert.ThrowsExceptionAsync( + var ex = await Assert.ThrowsExactlyAsync( () => app .AcquireTokenInteractive(TestConstants.s_scope) .WithClaims("claims_that_are_not_json") diff --git a/tests/Microsoft.Identity.Test.Unit/CoreTests/WsTrustTests/WsTrustTests.cs b/tests/Microsoft.Identity.Test.Unit/CoreTests/WsTrustTests/WsTrustTests.cs index c33a6bd147..62403abaca 100644 --- a/tests/Microsoft.Identity.Test.Unit/CoreTests/WsTrustTests/WsTrustTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/CoreTests/WsTrustTests/WsTrustTests.cs @@ -159,7 +159,7 @@ public async Task WsTrustRequestTokenNotFoundInResponseTestAsync() var message = endpoint.BuildTokenRequestMessageWindowsIntegratedAuth("urn:federation:SomeAudience"); - var ex = await Assert.ThrowsExceptionAsync(() => + var ex = await Assert.ThrowsExactlyAsync(() => harness.ServiceBundle.WsTrustWebRequestManager.GetWsTrustResponseAsync(endpoint, message, requestContext)).ConfigureAwait(false); Assert.AreEqual(MsalError.ParsingWsTrustResponseFailed, ex.ErrorCode); diff --git a/tests/Microsoft.Identity.Test.Unit/CryptographyTests.cs b/tests/Microsoft.Identity.Test.Unit/CryptographyTests.cs index 76823ce1d1..a381507b2f 100644 --- a/tests/Microsoft.Identity.Test.Unit/CryptographyTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/CryptographyTests.cs @@ -43,7 +43,7 @@ public void SignWithNonRsaCertificate_ThrowsException() var crypto = serviceBundle.PlatformProxy.CryptographyManager; - MsalClientException ex = Assert.ThrowsException(() => + MsalClientException ex = Assert.ThrowsExactly(() => { crypto.SignWithCertificate("TEST", cert, RSASignaturePadding.Pkcs1); }); diff --git a/tests/Microsoft.Identity.Test.Unit/ExceptionTests/ExperimentalFeatureTests.cs b/tests/Microsoft.Identity.Test.Unit/ExceptionTests/ExperimentalFeatureTests.cs index 63f491adc0..bfef53ea63 100644 --- a/tests/Microsoft.Identity.Test.Unit/ExceptionTests/ExperimentalFeatureTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/ExceptionTests/ExperimentalFeatureTests.cs @@ -31,7 +31,7 @@ public async Task ExperimentalFeatureExceptionAsync() .Create(Guid.NewGuid().ToString()) .WithCertificate(CertHelper.GetOrCreateTestCert()).Build(); - MsalClientException ex = await Assert.ThrowsExceptionAsync( + MsalClientException ex = await Assert.ThrowsExactlyAsync( () => cca.AcquireTokenForClient(s_scopes) .WithSignedHttpRequestProofOfPossession(popConfig).ExecuteAsync()) .ConfigureAwait(false); diff --git a/tests/Microsoft.Identity.Test.Unit/ExceptionTests/MsalExceptionTests.cs b/tests/Microsoft.Identity.Test.Unit/ExceptionTests/MsalExceptionTests.cs index 96d31c62f8..873de60ae3 100644 --- a/tests/Microsoft.Identity.Test.Unit/ExceptionTests/MsalExceptionTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/ExceptionTests/MsalExceptionTests.cs @@ -39,13 +39,13 @@ public class MsalExceptionTests : TestBase [TestMethod] public void ParamValidation() { - Assert.ThrowsException(() => new MsalClientException(null, ExMessage)); - Assert.ThrowsException(() => new MsalClientException(string.Empty, ExMessage)); + Assert.ThrowsExactly(() => new MsalClientException(null, ExMessage)); + Assert.ThrowsExactly(() => new MsalClientException(string.Empty, ExMessage)); - Assert.ThrowsException( + Assert.ThrowsExactly( () => new MsalServiceException(ExCode, string.Empty)); - Assert.ThrowsException( + Assert.ThrowsExactly( () => new MsalServiceException(ExCode, null)); } @@ -444,7 +444,7 @@ public async Task CorrelationIdInServiceExceptions() .Create(TestConstants.ClientId) .WithDefaultRedirectUri() .Build(); - var ex = await Assert.ThrowsExceptionAsync(async () => + var ex = await Assert.ThrowsExactlyAsync(async () => { await app.AcquireTokenSilent(TestConstants.s_graphScopes, TestConstants.s_user).ExecuteAsync().ConfigureAwait(false); } @@ -454,7 +454,7 @@ public async Task CorrelationIdInServiceExceptions() Assert.IsFalse(string.IsNullOrEmpty(((MsalException)ex).CorrelationId)); Guid guid = Guid.NewGuid(); - ex = await Assert.ThrowsExceptionAsync(async () => + ex = await Assert.ThrowsExactlyAsync(async () => { await app.AcquireTokenSilent(TestConstants.s_graphScopes, TestConstants.s_user).WithCorrelationId(guid).ExecuteAsync().ConfigureAwait(false); } @@ -495,7 +495,7 @@ await app.AcquireTokenForClient(TestConstants.s_scope) Assert.IsFalse(string.IsNullOrEmpty(((MsalException)ex).CorrelationId)); Guid guid = Guid.NewGuid(); - ex = await Assert.ThrowsExceptionAsync(async () => + ex = await Assert.ThrowsExactlyAsync(async () => { await app.AcquireTokenForClient(TestConstants.s_scope) .WithCorrelationId(guid) @@ -555,7 +555,7 @@ await app.AcquireTokenForClient(TestConstants.s_scope) .WithCertificate(certificate) .BuildConcrete(); - ex = await Assert.ThrowsExceptionAsync(async () => + ex = await Assert.ThrowsExactlyAsync(async () => { await app.AcquireTokenForClient(TestConstants.s_scope) .ExecuteAsync(CancellationToken.None) @@ -571,7 +571,7 @@ await app.AcquireTokenForClient(TestConstants.s_scope) harness.HttpManager.AddRequestTimeoutResponseMessageMockHandler(HttpMethod.Post); //Ensure non 404 error codes do not trigger message - ex = await Assert.ThrowsExceptionAsync(async () => + ex = await Assert.ThrowsExactlyAsync(async () => { await app.AcquireTokenForClient(TestConstants.s_scope) .WithForceRefresh(true) diff --git a/tests/Microsoft.Identity.Test.Unit/ManagedIdentityTests/ImdsTests.cs b/tests/Microsoft.Identity.Test.Unit/ManagedIdentityTests/ImdsTests.cs index 5a774edad0..af3833ba87 100644 --- a/tests/Microsoft.Identity.Test.Unit/ManagedIdentityTests/ImdsTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/ManagedIdentityTests/ImdsTests.cs @@ -381,7 +381,7 @@ public async Task ImdsRetryPolicyLifeTimeIsPerRequestAsync() } MsalServiceException ex = - await Assert.ThrowsExceptionAsync(async () => + await Assert.ThrowsExactlyAsync(async () => await mi.AcquireTokenForManagedIdentity(ManagedIdentityTests.Resource) .ExecuteAsync() .ConfigureAwait(false)) @@ -401,7 +401,7 @@ await mi.AcquireTokenForManagedIdentity(ManagedIdentityTests.Resource) statusCode: HttpStatusCode.GatewayTimeout); } - ex = await Assert.ThrowsExceptionAsync(async () => + ex = await Assert.ThrowsExactlyAsync(async () => await mi.AcquireTokenForManagedIdentity(ManagedIdentityTests.Resource) .ExecuteAsync() .ConfigureAwait(false)) diff --git a/tests/Microsoft.Identity.Test.Unit/ManagedIdentityTests/ManagedIdentityTests.cs b/tests/Microsoft.Identity.Test.Unit/ManagedIdentityTests/ManagedIdentityTests.cs index a1542bf6db..cc4a7a55c8 100644 --- a/tests/Microsoft.Identity.Test.Unit/ManagedIdentityTests/ManagedIdentityTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/ManagedIdentityTests/ManagedIdentityTests.cs @@ -1024,7 +1024,7 @@ public async Task CanceledRequest_ThrowsTaskCanceledExceptionAsync() var tokenSource = new CancellationTokenSource(); tokenSource.Cancel(); - await Assert.ThrowsExceptionAsync( + await Assert.ThrowsExactlyAsync( () => app.AcquireTokenForManagedIdentity(Resource) .WithForceRefresh(true) .ExecuteAsync(tokenSource.Token)).ConfigureAwait(false); diff --git a/tests/Microsoft.Identity.Test.Unit/OAuthClientTests.cs b/tests/Microsoft.Identity.Test.Unit/OAuthClientTests.cs index 2155108bda..e6b9751282 100644 --- a/tests/Microsoft.Identity.Test.Unit/OAuthClientTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/OAuthClientTests.cs @@ -247,12 +247,11 @@ private async Task ValidateOathClientAsync( harness.HttpManager, null); - Exception ex = await Assert.ThrowsExceptionAsync( + Exception ex = await Assert.ThrowsAsync( () => client.ExecuteRequestAsync( requestUri, HttpMethod.Post, - new RequestContext(harness.ServiceBundle, Guid.NewGuid(), null)), - allowDerived: true) + new RequestContext(harness.ServiceBundle, Guid.NewGuid(), null)) ) .ConfigureAwait(false); validationHandler(ex); diff --git a/tests/Microsoft.Identity.Test.Unit/PublicApiTests/AcquireTokenSilentTests.cs b/tests/Microsoft.Identity.Test.Unit/PublicApiTests/AcquireTokenSilentTests.cs index de30a04e73..5a67bc36d3 100644 --- a/tests/Microsoft.Identity.Test.Unit/PublicApiTests/AcquireTokenSilentTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/PublicApiTests/AcquireTokenSilentTests.cs @@ -27,10 +27,10 @@ public async Task NullAccount_EmptyLoginHintAsync() .Create(TestConstants.ClientId) .Build(); - await Assert.ThrowsExceptionAsync( + await Assert.ThrowsExactlyAsync( () => app.AcquireTokenSilent(TestConstants.s_scope.ToArray(), (string)null).ExecuteAsync()).ConfigureAwait(false); - var ex = await Assert.ThrowsExceptionAsync( + var ex = await Assert.ThrowsExactlyAsync( () => app.AcquireTokenSilent(TestConstants.s_scope.ToArray(), (IAccount)null).ExecuteAsync()).ConfigureAwait(false); Assert.AreEqual(MsalError.UserNullError, ex.ErrorCode); Assert.AreEqual(UiRequiredExceptionClassification.AcquireTokenSilentFailed, ex.Classification); @@ -253,7 +253,7 @@ public async Task AcquireTokenSilent_LoginHint_NoAccountAsync() TokenCacheHelper.PopulateCache(app.UserTokenCacheInternal.Accessor); - var exception = await Assert.ThrowsExceptionAsync(() => app.AcquireTokenSilent( + var exception = await Assert.ThrowsExactlyAsync(() => app.AcquireTokenSilent( TestConstants.s_scope.ToArray(), "other_login_hint@contoso.com") .ExecuteAsync()).ConfigureAwait(false); @@ -278,7 +278,7 @@ public async Task AcquireTokenSilent_LoginHint_MultipleAccountsAsync() TokenCacheHelper.PopulateCache(app.UserTokenCacheInternal.Accessor, "uid1", "utid"); TokenCacheHelper.PopulateCache(app.UserTokenCacheInternal.Accessor, "uid2", "utid"); - var exception = await Assert.ThrowsExceptionAsync(async () => await app.AcquireTokenSilent( + var exception = await Assert.ThrowsExactlyAsync(async () => await app.AcquireTokenSilent( TestConstants.s_scope.ToArray(), TestConstants.DisplayableId) .ExecuteAsync().ConfigureAwait(false)).ConfigureAwait(false); @@ -302,7 +302,7 @@ public async Task AcquireTokenSilent_Account_NoHomeAccountIDAsync() TokenCacheHelper.PopulateCache(app.UserTokenCacheInternal.Accessor); - var exception = await Assert.ThrowsExceptionAsync(() => app.AcquireTokenSilent( + var exception = await Assert.ThrowsExactlyAsync(() => app.AcquireTokenSilent( TestConstants.s_scope.ToArray(), new Account(null, null, null)) .ExecuteAsync()).ConfigureAwait(false); diff --git a/tests/Microsoft.Identity.Test.Unit/PublicApiTests/AuthenticationOperationTests.cs b/tests/Microsoft.Identity.Test.Unit/PublicApiTests/AuthenticationOperationTests.cs index 1bb78d621d..c41c25de5b 100644 --- a/tests/Microsoft.Identity.Test.Unit/PublicApiTests/AuthenticationOperationTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/PublicApiTests/AuthenticationOperationTests.cs @@ -183,7 +183,7 @@ public async Task WrongTokenType_Async() httpManager.AddSuccessTokenResponseMockHandlerForPost(TestConstants.AuthorityCommonTenant); // Act - var ex = await Assert.ThrowsExceptionAsync(() => app + var ex = await Assert.ThrowsExactlyAsync(() => app .AcquireTokenInteractive(TestConstants.s_scope) .WithAuthenticationOperation(authScheme) .ExecuteAsync()).ConfigureAwait(false); diff --git a/tests/Microsoft.Identity.Test.Unit/PublicApiTests/ClientAssertionTests.cs b/tests/Microsoft.Identity.Test.Unit/PublicApiTests/ClientAssertionTests.cs index 949e796255..f9f61a85c6 100644 --- a/tests/Microsoft.Identity.Test.Unit/PublicApiTests/ClientAssertionTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/PublicApiTests/ClientAssertionTests.cs @@ -436,7 +436,7 @@ public async Task ClientAssertion_EmptyJwt_ThrowsAsync() Task.FromResult(new ClientSignedAssertion { Assertion = string.Empty })) .BuildConcrete(); - await Assert.ThrowsExceptionAsync(() => + await Assert.ThrowsExactlyAsync(() => cca.AcquireTokenForClient(TestConstants.s_scope).ExecuteAsync()) .ConfigureAwait(false); } @@ -458,7 +458,7 @@ public async Task ClientAssertion_CancellationTokenPropagatesAsync() }) .BuildConcrete(); - await Assert.ThrowsExceptionAsync(() => + await Assert.ThrowsExactlyAsync(() => cca.AcquireTokenForClient(TestConstants.s_scope) .ExecuteAsync(cts.Token)) .ConfigureAwait(false); @@ -603,7 +603,7 @@ public async Task WithMtlsPop_AfterBearerDelegate_Throws() .WithClientAssertion(BearerDelegate()) .BuildConcrete(); - var ex = await Assert.ThrowsExceptionAsync(() => + var ex = await Assert.ThrowsExactlyAsync(() => cca.AcquireTokenForClient(TestConstants.s_scope) .WithMtlsProofOfPossession() .ExecuteAsync()) @@ -659,7 +659,7 @@ public async Task WithMtlsPop_AfterPoPDelegate_NoRegion_ThrowsAsync() .BuildConcrete(); // Act & Assert – should fail because region is missing - var ex = await Assert.ThrowsExceptionAsync(async () => + var ex = await Assert.ThrowsExactlyAsync(async () => await cca.AcquireTokenForClient(TestConstants.s_scope) .WithMtlsProofOfPossession() .ExecuteAsync() diff --git a/tests/Microsoft.Identity.Test.Unit/PublicApiTests/ClientCredentialWithRegionTests.cs b/tests/Microsoft.Identity.Test.Unit/PublicApiTests/ClientCredentialWithRegionTests.cs index 266817cc59..6b17bf5f7f 100644 --- a/tests/Microsoft.Identity.Test.Unit/PublicApiTests/ClientCredentialWithRegionTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/PublicApiTests/ClientCredentialWithRegionTests.cs @@ -39,7 +39,7 @@ public async Task AuthorityOverrideAndRegionalAsync() .Build(); #pragma warning disable CS0618 // Type or member is obsolete - var ex = await Assert.ThrowsExceptionAsync(() => + var ex = await Assert.ThrowsExactlyAsync(() => app .AcquireTokenForClient(TestConstants.s_scope) .WithAuthority("https://login.microsoft.com/17b189bc-2b81-4ec5-aa51-3e628cbc931b") @@ -483,14 +483,14 @@ public async Task MsalForceRegionIsSet_WithRegionIsSetToOptOut_NoRegionIsUsed() [TestMethod] public void WithAzureRegionThrowsOnNullArg() { - Assert.ThrowsException( + Assert.ThrowsExactly( () => ConfidentialClientApplicationBuilder .Create(TestConstants.ClientId) .WithAzureRegion(null) .WithClientSecret(TestConstants.ClientSecret) .Build()); - Assert.ThrowsException( + Assert.ThrowsExactly( () => ConfidentialClientApplicationBuilder .Create(TestConstants.ClientId) .WithAzureRegion(string.Empty) @@ -630,7 +630,7 @@ public async Task OtherCloud_WithValidation_Async(bool validateAuthority, bool a if (!authorityIsValid && validateAuthority) { - var ex = await Assert.ThrowsExceptionAsync(() => app + var ex = await Assert.ThrowsExactlyAsync(() => app .AcquireTokenForClient(TestConstants.s_scope) .WithTenantId("17b189bc-2b81-4ec5-aa51-3e628cbc931b") .ExecuteAsync()).ConfigureAwait(false); @@ -800,7 +800,7 @@ public async Task AuthorityValidationHappensOnNonRegionalAuthorityAsync() .Build(); // Act - var ex = await Assert.ThrowsExceptionAsync(() => app + var ex = await Assert.ThrowsExactlyAsync(() => app .AcquireTokenForClient(TestConstants.s_scope) .ExecuteAsync()) .ConfigureAwait(false); diff --git a/tests/Microsoft.Identity.Test.Unit/PublicApiTests/ConfidentialClientApplicationTests.cs b/tests/Microsoft.Identity.Test.Unit/PublicApiTests/ConfidentialClientApplicationTests.cs index 354a559a17..540216e335 100644 --- a/tests/Microsoft.Identity.Test.Unit/PublicApiTests/ConfidentialClientApplicationTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/PublicApiTests/ConfidentialClientApplicationTests.cs @@ -413,7 +413,7 @@ public async Task ClientCreds_And_AAD_LogRequestUri_OnServerError_Async() httpManager.AddResiliencyMessageMockHandler(HttpMethod.Post, HttpStatusCode.InternalServerError, retryAfter: 0); // Acquire Token - var ex = await Assert.ThrowsExceptionAsync( + var ex = await Assert.ThrowsExactlyAsync( () => cca.AcquireTokenForClient(TestConstants.s_scope.ToArray()).ExecuteAsync()) .ConfigureAwait(false); @@ -440,7 +440,7 @@ public async Task ClientCreds_And_ADFS_LogRequestUri_OnServerError_Async() httpManager.AddResiliencyMessageMockHandler(HttpMethod.Post, HttpStatusCode.InternalServerError, retryAfter: 0); // Acquire Token - var ex = await Assert.ThrowsExceptionAsync( + var ex = await Assert.ThrowsExactlyAsync( () => cca.AcquireTokenForClient(TestConstants.s_scope.ToArray()).ExecuteAsync()) .ConfigureAwait(false); @@ -590,14 +590,14 @@ public async Task ClientCreds_And_Obo_DoNotAllow_EmptyScopes_Async() .Build(); // OBO - var ex = await Assert.ThrowsExceptionAsync( + var ex = await Assert.ThrowsExactlyAsync( () => cca.AcquireTokenOnBehalfOf(null, new UserAssertion("assertion", "assertiontype")).ExecuteAsync()) .ConfigureAwait(false); Assert.AreEqual(MsalError.ScopesRequired, ex.ErrorCode); // Client Creds - ex = await Assert.ThrowsExceptionAsync( + ex = await Assert.ThrowsExactlyAsync( () => cca.AcquireTokenForClient(null).ExecuteAsync()) .ConfigureAwait(false); @@ -817,7 +817,7 @@ public async Task ConfidentialClientUsingSignedClientAssertion_AsyncDelegate_Can var app = builder.BuildConcrete(); Assert.IsNull(app.Certificate); - await Assert.ThrowsExceptionAsync( + await Assert.ThrowsExactlyAsync( () => app.AcquireTokenForClient(TestConstants.s_scope.ToArray()) .ExecuteAsync(cancellationTokenSource.Token)).ConfigureAwait(false); } @@ -910,7 +910,7 @@ public async Task AcquireTokenForClient_EmptyAssertion_ThrowsArgumentExceptionAs // Act & Assert – the first token request will execute the delegate // and should surface ArgumentException from the credential layer. - await Assert.ThrowsExceptionAsync(() => + await Assert.ThrowsExactlyAsync(() => cca.AcquireTokenForClient(TestConstants.s_scope) .ExecuteAsync()) .ConfigureAwait(false); @@ -1441,7 +1441,7 @@ public async Task HttpRequestExceptionIsNotSuppressedAsync() // add mock response bigger than 1MB for HTTP Client httpManager.AddFailingRequest(new InvalidOperationException()); - await Assert.ThrowsExceptionAsync( + await Assert.ThrowsExactlyAsync( () => app.AcquireTokenForClient(TestConstants.s_scope.ToArray()).ExecuteAsync(CancellationToken.None)).ConfigureAwait(false); } } @@ -2079,11 +2079,11 @@ public async Task AcquireTokenByAuthorizationCode_NullOrEmptyCode_ThrowsAsync() .BuildConcrete(); // Act & Assert - await Assert.ThrowsExceptionAsync( + await Assert.ThrowsExactlyAsync( () => app.AcquireTokenByAuthorizationCode(TestConstants.s_scope, null).ExecuteAsync() ).ConfigureAwait(false); - await Assert.ThrowsExceptionAsync( + await Assert.ThrowsExactlyAsync( () => app.AcquireTokenByAuthorizationCode(TestConstants.s_scope, string.Empty).ExecuteAsync() ).ConfigureAwait(false); } @@ -2197,7 +2197,7 @@ public async Task ForceRefreshAndAccessTokenHash_ThrowsException_Async() .WithAccessTokenSha256ToRefresh("dummyHash"); // Act & Assert - MsalClientException ex = await Assert.ThrowsExceptionAsync(() => + MsalClientException ex = await Assert.ThrowsExactlyAsync(() => builder.ExecuteAsync() ).ConfigureAwait(false); diff --git a/tests/Microsoft.Identity.Test.Unit/PublicApiTests/MtlsPopTests.cs b/tests/Microsoft.Identity.Test.Unit/PublicApiTests/MtlsPopTests.cs index 4fb9495441..65ce4f3692 100644 --- a/tests/Microsoft.Identity.Test.Unit/PublicApiTests/MtlsPopTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/PublicApiTests/MtlsPopTests.cs @@ -57,7 +57,7 @@ public async Task MtlsPop_AadAuthorityWithoutCertificateAsync() .WithAuthority("https://login.microsoftonline.com/123456-1234-2345-1234561234") .Build(); - MsalClientException ex = await Assert.ThrowsExceptionAsync(() => + MsalClientException ex = await Assert.ThrowsExactlyAsync(() => app.AcquireTokenForClient(TestConstants.s_scope) .WithMtlsProofOfPossession() // Enables MTLS PoP .ExecuteAsync()) @@ -76,7 +76,7 @@ public async Task MtlsPopWithoutCertificateAsync() .Build(); // Set WithMtlsProofOfPossession on the request without a certificate - MsalClientException ex = await Assert.ThrowsExceptionAsync(() => + MsalClientException ex = await Assert.ThrowsExactlyAsync(() => app.AcquireTokenForClient(TestConstants.s_scope) .WithMtlsProofOfPossession() // Enables MTLS PoP .ExecuteAsync()) @@ -154,7 +154,7 @@ public async Task MtlsPop_WithoutRegion_ThrowsException(bool setAzureRegion) } // Set WithMtlsProofOfPossession on the request - MsalClientException ex = await Assert.ThrowsExceptionAsync(() => + MsalClientException ex = await Assert.ThrowsExactlyAsync(() => app.AcquireTokenForClient(TestConstants.s_scope) .WithMtlsProofOfPossession() // Enables MTLS PoP .ExecuteAsync()) @@ -174,7 +174,7 @@ public async Task MtlsPop_WithUnsupportedNonTenantedAuthorityAsync_ThrowsExcepti .Build(); // Set WithMtlsProofOfPossession on the request without specifying an authority - MsalClientException ex = await Assert.ThrowsExceptionAsync(() => + MsalClientException ex = await Assert.ThrowsExactlyAsync(() => app.AcquireTokenForClient(TestConstants.s_scope) .WithMtlsProofOfPossession() .ExecuteAsync()) @@ -836,7 +836,7 @@ public async Task MtlsPop_WithUnsupportedNonTenantedAuthorityAsyncForDsts_Throws .Build(); // Set WithMtlsProofOfPossession on the request specifying an authority - HttpRequestException ex = await Assert.ThrowsExceptionAsync(() => + HttpRequestException ex = await Assert.ThrowsExactlyAsync(() => app.AcquireTokenForClient(TestConstants.s_scope) .WithMtlsProofOfPossession() .ExecuteAsync()) diff --git a/tests/Microsoft.Identity.Test.Unit/PublicApiTests/PublicClientApplicationTests.cs b/tests/Microsoft.Identity.Test.Unit/PublicApiTests/PublicClientApplicationTests.cs index b982d0a43b..8c7a509e0c 100644 --- a/tests/Microsoft.Identity.Test.Unit/PublicApiTests/PublicClientApplicationTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/PublicApiTests/PublicClientApplicationTests.cs @@ -588,7 +588,7 @@ public async Task HttpRequestExceptionIsNotSuppressedAsync() // add mock response bigger than 1MB for Http Client httpManager.AddFailingRequest(new InvalidOperationException()); - await Assert.ThrowsExceptionAsync( + await Assert.ThrowsExactlyAsync( () => app .AcquireTokenInteractive(TestConstants.s_scope.ToArray()).ExecuteAsync(CancellationToken.None)) .ConfigureAwait(false); @@ -687,7 +687,7 @@ public async Task GetAccountByUserFlowTestsAsync() var accounts = app.GetAccountsAsync(TestConstants.B2CSignUpSignIn).Result; Assert.AreEqual(0, accounts.Count()); - await Assert.ThrowsExceptionAsync(() => + await Assert.ThrowsExactlyAsync(() => app.GetAccountsAsync(string.Empty)).ConfigureAwait(false); accounts = PopulateB2CTokenCacheAsync(TestConstants.B2CSignUpSignIn, app).Result; @@ -845,7 +845,7 @@ public async Task AcquireTokenSilent_EmptyLoginHint_TestAsync() .Create(TestConstants.ClientId) .Build(); - await Assert.ThrowsExceptionAsync(() => + await Assert.ThrowsExactlyAsync(() => app.AcquireTokenSilent(TestConstants.s_scope.ToArray(), string.Empty).ExecuteAsync()) .ConfigureAwait(false); } diff --git a/tests/Microsoft.Identity.Test.Unit/PublicApiTests/PublicClientApplicationTestsWithB2C.cs b/tests/Microsoft.Identity.Test.Unit/PublicApiTests/PublicClientApplicationTestsWithB2C.cs index 7782974f16..c66e25b521 100644 --- a/tests/Microsoft.Identity.Test.Unit/PublicApiTests/PublicClientApplicationTestsWithB2C.cs +++ b/tests/Microsoft.Identity.Test.Unit/PublicApiTests/PublicClientApplicationTestsWithB2C.cs @@ -266,7 +266,7 @@ public async Task B2C_NoScopes_NoAccessToken_Async() AssertNoAccessToken(result); Assert.AreEqual(0, httpManager.QueueSize); - var ex = await Assert.ThrowsExceptionAsync(() => + var ex = await Assert.ThrowsExactlyAsync(() => app.AcquireTokenSilent(null, result.Account).ExecuteAsync() ).ConfigureAwait(false); @@ -328,7 +328,7 @@ public async Task B2CSomeExceptionAsync() // Act #pragma warning disable CS0618 // Type or member is obsolete - var ex = await Assert.ThrowsExceptionAsync(() => + var ex = await Assert.ThrowsExactlyAsync(() => app.AcquireTokenByUsernamePassword(new[] { "user.read" }, "username", "password" ) // no scopes -> no Access Token! .ExecuteAsync()) .ConfigureAwait(false); diff --git a/tests/Microsoft.Identity.Test.Unit/PublicApiTests/RefreshInTests.cs b/tests/Microsoft.Identity.Test.Unit/PublicApiTests/RefreshInTests.cs index 0d25df58a6..e6505c1835 100644 --- a/tests/Microsoft.Identity.Test.Unit/PublicApiTests/RefreshInTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/PublicApiTests/RefreshInTests.cs @@ -223,7 +223,7 @@ public async Task ATS_Expired_NeedsRefresh_AADInvalidResponse_Async() var account = new Account(TestConstants.s_userIdentifier, TestConstants.DisplayableId, null); // Act - MsalServiceException ex = await Assert.ThrowsExceptionAsync(() => app + MsalServiceException ex = await Assert.ThrowsExactlyAsync(() => app .AcquireTokenSilent( TestConstants.s_scope.ToArray(), account) @@ -492,7 +492,7 @@ public async Task ClientCredentials_Expired_NeedsRefresh_AADInvalidResponse_Asyn harness.HttpManager.AddTokenResponse(TokenResponseType.Invalid_AADUnavailable503); // Act - MsalServiceException ex = await Assert.ThrowsExceptionAsync(() => app + MsalServiceException ex = await Assert.ThrowsExactlyAsync(() => app .AcquireTokenForClient(TestConstants.s_scope) .ExecuteAsync()) .ConfigureAwait(false); diff --git a/tests/Microsoft.Identity.Test.Unit/RequestsTests/DeviceCodeRequestTests.cs b/tests/Microsoft.Identity.Test.Unit/RequestsTests/DeviceCodeRequestTests.cs index d811a3a178..9e11fb58a8 100644 --- a/tests/Microsoft.Identity.Test.Unit/RequestsTests/DeviceCodeRequestTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/RequestsTests/DeviceCodeRequestTests.cs @@ -154,7 +154,7 @@ public async Task DeviceCodeExceptionsOn200OKAsync() var request = new DeviceCodeRequest(harness.ServiceBundle, parameters, deviceCodeParameters); - var ex = await Assert.ThrowsExceptionAsync( + var ex = await Assert.ThrowsExactlyAsync( () => request.RunAsync(CancellationToken.None)).ConfigureAwait(false); } } @@ -241,7 +241,7 @@ public async Task TestDeviceCodeCancelAsync() // We setup the cancel before calling the RunAsync operation since we don't check the cancel // until later and the mock network calls run insanely fast for us to timeout for them. cancellationSource.Cancel(); - await Assert.ThrowsExceptionAsync(() => request.RunAsync(cancellationSource.Token)).ConfigureAwait(false); + await Assert.ThrowsExactlyAsync(() => request.RunAsync(cancellationSource.Token)).ConfigureAwait(false); } } diff --git a/tests/Microsoft.Identity.Test.Unit/RequestsTests/FociTests.cs b/tests/Microsoft.Identity.Test.Unit/RequestsTests/FociTests.cs index 16cd4dba3d..3422ea445a 100644 --- a/tests/Microsoft.Identity.Test.Unit/RequestsTests/FociTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/RequestsTests/FociTests.cs @@ -95,7 +95,7 @@ public async Task NoFociForCca() Assert.IsNull(appCAccount); // Act - var ex = await Assert.ThrowsExceptionAsync( + var ex = await Assert.ThrowsExactlyAsync( () => appC.AcquireTokenSilent(TestConstants.s_scope, appAAccount).ExecuteAsync()).ConfigureAwait(false); Assert.AreEqual(MsalError.NoTokensFoundError, ex.ErrorCode); @@ -116,7 +116,7 @@ public async Task FociAndNonFociAppsCoexistAsync() await InteractiveAsync(_appA, ServerTokenResponse.FociToken).ConfigureAwait(false); // B cannot acquire a token interactively, but will try to use FRT - var ex = await Assert.ThrowsExceptionAsync( + var ex = await Assert.ThrowsExactlyAsync( () => SilentAsync(_appB, ServerTokenResponse.ErrorClientMismatch)).ConfigureAwait(false); Assert.AreEqual(MsalError.NoTokensFoundError, ex.ErrorCode); @@ -147,7 +147,7 @@ public async Task FociDoesNotHideRTRefreshErrorsAsync() await InteractiveAsync(_appA, ServerTokenResponse.FociToken).ConfigureAwait(false); // B cannot acquire a token interactively, but will try to use FRT - var ex = await Assert.ThrowsExceptionAsync( + var ex = await Assert.ThrowsExactlyAsync( () => SilentAsync(_appB, ServerTokenResponse.OtherError)).ConfigureAwait(false); Assert.AreEqual(MsalError.InvalidGrantError, ex.ErrorCode); @@ -211,7 +211,7 @@ public async Task FociAppLeavesFamilyAsync() await SilentAsync(_appB, ServerTokenResponse.FociToken).ConfigureAwait(false); // B leaves the family -> STS will not refresh its token based on the FRT - await Assert.ThrowsExceptionAsync(() => SilentAsync(_appB, ServerTokenResponse.ErrorClientMismatch)).ConfigureAwait(false); + await Assert.ThrowsExactlyAsync(() => SilentAsync(_appB, ServerTokenResponse.ErrorClientMismatch)).ConfigureAwait(false); // B can resume acquiring tokens silently via the normal RT, after an interactive flow await InteractiveAsync(_appB, ServerTokenResponse.NonFociToken).ConfigureAwait(false); diff --git a/tests/Microsoft.Identity.Test.Unit/RequestsTests/IntegratedWindowsAuthUsernamePasswordTests.cs b/tests/Microsoft.Identity.Test.Unit/RequestsTests/IntegratedWindowsAuthUsernamePasswordTests.cs index 0cfee2ef3c..edc180ccc1 100644 --- a/tests/Microsoft.Identity.Test.Unit/RequestsTests/IntegratedWindowsAuthUsernamePasswordTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/RequestsTests/IntegratedWindowsAuthUsernamePasswordTests.cs @@ -219,7 +219,7 @@ public async Task AcquireTokenByIntegratedWindowsAuthTest_ManagedUser_DiscoveryF .BuildConcrete(); // Act - MsalServiceException exception = await Assert.ThrowsExceptionAsync( + MsalServiceException exception = await Assert.ThrowsExactlyAsync( async () => await app .AcquireTokenByIntegratedWindowsAuth(TestConstants.s_scope) .WithUsername(TestConstants.s_user.Username) @@ -259,7 +259,7 @@ public async Task AcquireTokenByIntegratedWindowsAuthTest_UnknownUserAsync() .BuildConcrete(); // Act - MsalClientException exception = await Assert.ThrowsExceptionAsync( + MsalClientException exception = await Assert.ThrowsExactlyAsync( async () => await app .AcquireTokenByIntegratedWindowsAuth(TestConstants.s_scope) .WithUsername(TestConstants.s_user.Username) @@ -403,7 +403,7 @@ public async Task AcquireTokenByIntegratedWindowsAuthInvalidClientTestAsync() .WithExtraQueryParameters(TestConstants.ExtraQueryParametersNoAffectOnCacheKeys) .BuildConcrete(); - MsalServiceException result = await Assert.ThrowsExceptionAsync( + MsalServiceException result = await Assert.ThrowsExactlyAsync( async () => await app.AcquireTokenByIntegratedWindowsAuth(TestConstants.s_scope) .WithClaims(TestConstants.Claims) .WithUsername(TestConstants.s_user.Username) @@ -485,7 +485,7 @@ public async Task MexEndpointFailsToResolveTestAsync() // Call acquire token, Mex parser fails #pragma warning disable CS0618 // Type or member is obsolete - MsalClientException result = await Assert.ThrowsExceptionAsync( + MsalClientException result = await Assert.ThrowsExactlyAsync( async () => await app.AcquireTokenByUsernamePassword( TestConstants.s_scope, TestConstants.s_user.Username, @@ -520,7 +520,7 @@ public async Task MexDoesNotReturnAuthEndpointTestAsync() .BuildConcrete(); // Call acquire token, endpoint not found - MsalClientException result = await Assert.ThrowsExceptionAsync( + MsalClientException result = await Assert.ThrowsExactlyAsync( #pragma warning disable CS0618 // Type or member is obsolete async () => await app.AcquireTokenByUsernamePassword( TestConstants.s_scope, @@ -553,7 +553,7 @@ public async Task MexParsingFailsTestAsync() .BuildConcrete(); // Call acquire token - MsalServiceException result = await Assert.ThrowsExceptionAsync( + MsalServiceException result = await Assert.ThrowsExactlyAsync( #pragma warning disable CS0618 // Type or member is obsolete async () => await app.AcquireTokenByUsernamePassword( TestConstants.s_scope, @@ -593,7 +593,7 @@ public async Task FederatedUsernameNullPasswordTestAsync() .BuildConcrete(); // Call acquire token - MsalClientException result = await Assert.ThrowsExceptionAsync( + MsalClientException result = await Assert.ThrowsExactlyAsync( #pragma warning disable CS0618 // Type or member is obsolete async () => await app.AcquireTokenByUsernamePassword( TestConstants.s_scope, @@ -636,7 +636,7 @@ public async Task FederatedUsernamePasswordCommonAuthorityTestAsync() .BuildConcrete(); // Call acquire token - MsalServiceException result = await Assert.ThrowsExceptionAsync( + MsalServiceException result = await Assert.ThrowsExactlyAsync( #pragma warning disable CS0618 // Type or member is obsolete async () => await app.AcquireTokenByUsernamePassword( TestConstants.s_scope, @@ -687,7 +687,7 @@ public async Task ManagedUsernamePasswordCommonAuthorityTestAsync() .BuildConcrete(); // Call acquire token - MsalServiceException result = await Assert.ThrowsExceptionAsync( + MsalServiceException result = await Assert.ThrowsExactlyAsync( #pragma warning disable CS0618 // Type or member is obsolete async () => await app.AcquireTokenByUsernamePassword( TestConstants.s_scope, @@ -758,7 +758,7 @@ public async Task ManagedUsernameNoPasswordAcquireTokenTestAsync() // Call acquire token #pragma warning disable CS0618 // Type or member is obsolete - MsalClientException result = await Assert.ThrowsExceptionAsync( + MsalClientException result = await Assert.ThrowsExactlyAsync( async () => await app.AcquireTokenByUsernamePassword( TestConstants.s_scope, TestConstants.s_user.Username, diff --git a/tests/Microsoft.Identity.Test.Unit/RequestsTests/InteractiveRequestTests.cs b/tests/Microsoft.Identity.Test.Unit/RequestsTests/InteractiveRequestTests.cs index 7a7c42a88b..f9704b6158 100644 --- a/tests/Microsoft.Identity.Test.Unit/RequestsTests/InteractiveRequestTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/RequestsTests/InteractiveRequestTests.cs @@ -41,9 +41,9 @@ public void NullArgs() ExtraScopesToConsent = TestConstants.s_scopeForAnotherResource.ToArray(), }; - Assert.ThrowsException(() => + Assert.ThrowsExactly(() => new InteractiveRequest(null, interactiveParameters)); - Assert.ThrowsException(() => + Assert.ThrowsExactly(() => new InteractiveRequest(requestParams, null)); } } @@ -202,7 +202,7 @@ public async Task RedirectUriContainsFragmentErrorTestAsync() var request = new InteractiveRequest( parameters, interactiveParameters); - var ex = await Assert.ThrowsExceptionAsync + var ex = await Assert.ThrowsExactlyAsync (() => request.RunAsync()).ConfigureAwait(false); Assert.Contains(MsalErrorMessage.RedirectUriContainsFragment, ex.Message); @@ -239,7 +239,7 @@ public async Task VerifyAuthorizationResultTestAsync() parameters, interactiveParameters); - var ex = await Assert.ThrowsExceptionAsync( + var ex = await Assert.ThrowsExactlyAsync( () => request.RunAsync()) .ConfigureAwait(false); @@ -262,7 +262,7 @@ public async Task VerifyAuthorizationResultTestAsync() parameters, interactiveParameters); - var ex2 = await Assert.ThrowsExceptionAsync( + var ex2 = await Assert.ThrowsExactlyAsync( () => request.RunAsync()) .ConfigureAwait(false); @@ -295,7 +295,7 @@ public async Task VerifyAuthorizationResult_NoErrorDescription_Async() parameters, new AcquireTokenInteractiveParameters()); - var ex = await Assert.ThrowsExceptionAsync( + var ex = await Assert.ThrowsExactlyAsync( () => request.RunAsync(CancellationToken.None)) .ConfigureAwait(false); diff --git a/tests/Microsoft.Identity.Test.Unit/RequestsTests/InteractiveRequestWithCustomWebUiTests.cs b/tests/Microsoft.Identity.Test.Unit/RequestsTests/InteractiveRequestWithCustomWebUiTests.cs index 073531b99e..0da0d68676 100644 --- a/tests/Microsoft.Identity.Test.Unit/RequestsTests/InteractiveRequestWithCustomWebUiTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/RequestsTests/InteractiveRequestWithCustomWebUiTests.cs @@ -111,7 +111,7 @@ await ExecuteTestAsync( .ReturnsForAnyArgs(Task.FromResult(new Uri("http://blech"))), async request => { - var ex = await Assert.ThrowsExceptionAsync( + var ex = await Assert.ThrowsExactlyAsync( () => request.RunAsync(CancellationToken.None)).ConfigureAwait(false); Assert.AreEqual(MsalError.CustomWebUiReturnedInvalidUri, ex.ErrorCode); }).ConfigureAwait(false); @@ -127,7 +127,7 @@ await ExecuteTestAsync( .ReturnsForAnyArgs(_ => { throw new InvalidOperationException(); }), async request => { - await Assert.ThrowsExceptionAsync( + await Assert.ThrowsExactlyAsync( () => request.RunAsync(CancellationToken.None)).ConfigureAwait(false); }).ConfigureAwait(false); } @@ -142,7 +142,7 @@ await ExecuteTestAsync( .ReturnsForAnyArgs(Task.FromResult(new Uri(ExpectedRedirectUri))), async request => { - var ex = await Assert.ThrowsExceptionAsync( + var ex = await Assert.ThrowsExactlyAsync( () => request.RunAsync(CancellationToken.None)).ConfigureAwait(false); Assert.AreEqual(MsalError.CustomWebUiReturnedInvalidUri, ex.ErrorCode); }).ConfigureAwait(false); @@ -161,7 +161,7 @@ await ExecuteTestAsync( }, async request => { - var ex = await Assert.ThrowsExceptionAsync( + var ex = await Assert.ThrowsExactlyAsync( () => request.RunAsync(CancellationToken.None)).ConfigureAwait(false); Assert.AreEqual(MsalError.StateMismatchError, ex.ErrorCode); }).ConfigureAwait(false); diff --git a/tests/Microsoft.Identity.Test.Unit/RequestsTests/LongRunningOnBehalfOfTests.cs b/tests/Microsoft.Identity.Test.Unit/RequestsTests/LongRunningOnBehalfOfTests.cs index 1504111d4e..f550c1e20b 100644 --- a/tests/Microsoft.Identity.Test.Unit/RequestsTests/LongRunningOnBehalfOfTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/RequestsTests/LongRunningOnBehalfOfTests.cs @@ -345,7 +345,7 @@ public async Task AcquireTokenInLongRunningObo_CacheKeyDoesNotExist_TestAsync() string oboCacheKey = "obo-cache-key"; // If token with OBO cache key provided does not exist in the cache throw error - var exception = await Assert.ThrowsExceptionAsync( + var exception = await Assert.ThrowsExactlyAsync( () => cca.AcquireTokenInLongRunningProcess(TestConstants.s_scope.ToArray(), oboCacheKey) .ExecuteAsync()) .ConfigureAwait(false); @@ -375,7 +375,7 @@ await cca.InitiateLongRunningProcessInWebApi(TestConstants.s_scope, TestConstant Assert.AreEqual(new UserAssertion(TestConstants.DefaultAccessToken).AssertionHash, cacheKey); // Cache key is required in this method - await Assert.ThrowsExceptionAsync( + await Assert.ThrowsExactlyAsync( () => cca.AcquireTokenInLongRunningProcess(TestConstants.s_scope, null) .ExecuteAsync()) .ConfigureAwait(false); @@ -638,7 +638,7 @@ public async Task NormalOboThenLongRunningAcquire_WithTheSameKey_TestAsync() TokenCacheHelper.ExpireAllAccessTokens(cca.UserTokenCacheInternal); // AcquireLR - throws because no RT - var exception = await Assert.ThrowsExceptionAsync( + var exception = await Assert.ThrowsExactlyAsync( () => cca.AcquireTokenInLongRunningProcess(TestConstants.s_scope.ToArray(), oboCacheKey) .ExecuteAsync()) .ConfigureAwait(false); diff --git a/tests/Microsoft.Identity.Test.Unit/RequestsTests/SilentRequestTests.cs b/tests/Microsoft.Identity.Test.Unit/RequestsTests/SilentRequestTests.cs index cdea6a2de8..3cc57994f5 100644 --- a/tests/Microsoft.Identity.Test.Unit/RequestsTests/SilentRequestTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/RequestsTests/SilentRequestTests.cs @@ -151,7 +151,7 @@ public void RequestParamsNullArg() { using (var harness = new MockHttpTestHarness(TestConstants.AuthorityHomeTenant)) { - Assert.ThrowsException(() => harness.CreateRequestParams( + Assert.ThrowsExactly(() => harness.CreateRequestParams( null, TestConstants.s_scope, authorityOverride: AuthorityInfo.FromAuthorityUri(TestConstants.AuthorityHomeTenant, false))); diff --git a/tests/Microsoft.Identity.Test.Unit/TelemetryTests/HttpTelemetryTests.cs b/tests/Microsoft.Identity.Test.Unit/TelemetryTests/HttpTelemetryTests.cs index 067aa055fb..f9b448a461 100644 --- a/tests/Microsoft.Identity.Test.Unit/TelemetryTests/HttpTelemetryTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/TelemetryTests/HttpTelemetryTests.cs @@ -577,7 +577,7 @@ private enum AcquireTokenInteractiveOutcome Task.FromException(new MsalClientException("user_cancelled"))); _app.ServiceBundle.ConfigureMockWebUI(ui); - var ex = await Assert.ThrowsExceptionAsync(() => + var ex = await Assert.ThrowsExactlyAsync(() => _app .AcquireTokenInteractive(TestConstants.s_scope) .WithCorrelationId(correlationId) @@ -607,7 +607,7 @@ private enum AcquireTokenInteractiveOutcome _harness.HttpManager.AddMockHandler(tokenRequestHandler2); _harness.HttpManager.AddMockHandler(tokenRequestHandler); - var serviceEx = await Assert.ThrowsExceptionAsync(() => + var serviceEx = await Assert.ThrowsExactlyAsync(() => _app .AcquireTokenInteractive(TestConstants.s_scope) .WithCorrelationId(correlationId) @@ -623,12 +623,11 @@ private enum AcquireTokenInteractiveOutcome cts.Cancel(true); CancellationToken token = cts.Token; - var operationCanceledException = await Assert.ThrowsExceptionAsync(() => + var operationCanceledException = await Assert.ThrowsExactlyAsync(() => _app .AcquireTokenInteractive(TestConstants.s_scope) .WithCorrelationId(correlationId) - .ExecuteAsync(token), - allowDerived: true) // do not catch TaskCanceledException + .ExecuteAsync(token)) // do not catch TaskCanceledException .ConfigureAwait(false); @@ -713,9 +712,8 @@ private enum AcquireTokenInteractiveOutcome TestConstants.AuthorityUtidTenant, correlationId.ToString()); - var ex = await Assert.ThrowsExceptionAsync( - () => request.WithCorrelationId(correlationId).ExecuteAsync(), - allowDerived: true) + var ex = await Assert.ThrowsExactlyAsync( + () => request.WithCorrelationId(correlationId).ExecuteAsync()) .ConfigureAwait(false); Assert.AreEqual( diff --git a/tests/Microsoft.Identity.Test.Unit/TelemetryTests/OTelInstrumentationTests.cs b/tests/Microsoft.Identity.Test.Unit/TelemetryTests/OTelInstrumentationTests.cs index 51fb4bce22..9dcf227070 100644 --- a/tests/Microsoft.Identity.Test.Unit/TelemetryTests/OTelInstrumentationTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/TelemetryTests/OTelInstrumentationTests.cs @@ -381,7 +381,7 @@ private async Task AcquireTokenMsalServiceExceptionAsync() _harness.HttpManager.AddTokenResponse(TokenResponseType.InvalidClient); //Test for MsalServiceException - MsalServiceException ex = await Assert.ThrowsExceptionAsync( + MsalServiceException ex = await Assert.ThrowsExactlyAsync( () => _cca.AcquireTokenForClient(TestConstants.s_scopeForAnotherResource) .WithExtraQueryParameters(extraQueryParams) .WithTenantId(TestConstants.Utid) @@ -394,7 +394,7 @@ private async Task AcquireTokenMsalServiceExceptionAsync() private async Task AcquireTokenMsalClientExceptionAsync() { //Test for MsalClientException - MsalClientException exClient = await Assert.ThrowsExceptionAsync( + MsalClientException exClient = await Assert.ThrowsExactlyAsync( () => _cca.AcquireTokenForClient(null) // null scope -> client exception .WithExtraQueryParameters(extraQueryParams) .WithTenantId(TestConstants.Utid) diff --git a/tests/Microsoft.Identity.Test.Unit/TelemetryTests/RegionalTelemetryTests.cs b/tests/Microsoft.Identity.Test.Unit/TelemetryTests/RegionalTelemetryTests.cs index f0d7eedb6e..5ab2f77d2d 100644 --- a/tests/Microsoft.Identity.Test.Unit/TelemetryTests/RegionalTelemetryTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/TelemetryTests/RegionalTelemetryTests.cs @@ -326,7 +326,7 @@ private enum AcquireTokenForClientOutcome _harness.HttpManager.AddMockHandler(tokenRequestHandler2); _harness.HttpManager.AddMockHandler(tokenRequestHandler); - var serviceEx = await Assert.ThrowsExceptionAsync(() => + var serviceEx = await Assert.ThrowsExactlyAsync(() => app5 .AcquireTokenForClient(TestConstants.s_scope) .WithForceRefresh(true) diff --git a/tests/Microsoft.Identity.Test.Unit/Throttling/ThrottlingAcceptanceTests.cs b/tests/Microsoft.Identity.Test.Unit/Throttling/ThrottlingAcceptanceTests.cs index a3b6c786b7..1d4d49d88a 100644 --- a/tests/Microsoft.Identity.Test.Unit/Throttling/ThrottlingAcceptanceTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/Throttling/ThrottlingAcceptanceTests.cs @@ -45,7 +45,7 @@ public async Task Http400_RetryAfter_ThrottleForDuration_AcceptanceTest_Async() AssertThrottlingCacheEntryCount(throttlingManager, retryAfterEntryCount: 1); Trace.WriteLine("3. Second call - request is throttled"); - var ex = await Assert.ThrowsExceptionAsync( + var ex = await Assert.ThrowsExactlyAsync( () => app.AcquireTokenSilent(TestConstants.s_scope, account).ExecuteAsync()) .ConfigureAwait(false); AssertInvalidClientEx(ex); @@ -89,7 +89,7 @@ public async Task Http429_RetryAfter_ThrottleForDuration_Async(int httpStatusCod AssertThrottlingCacheEntryCount(throttlingManager, retryAfterEntryCount: 1); Trace.WriteLine("3. Second call - request is throttled"); - var ex = await Assert.ThrowsExceptionAsync( + var ex = await Assert.ThrowsExactlyAsync( () => app.AcquireTokenSilent(TestConstants.s_scope, account).ExecuteAsync()) .ConfigureAwait(false); Assert.AreEqual(httpStatusCode, ex.StatusCode); @@ -126,7 +126,7 @@ public async Task SimilarRequests_AreThrottled_RetryAfter_Async() AssertThrottlingCacheEntryCount(throttlingManager, retryAfterEntryCount: 1); Trace.WriteLine("A similar request, e.g. with a claims challenge, will be throttled"); - var ex = await Assert.ThrowsExceptionAsync( + var ex = await Assert.ThrowsExactlyAsync( () => app.AcquireTokenSilent(TestConstants.s_scope, account) .WithClaims(TestConstants.Claims) // claims are not part of the strict thumbprint .ExecuteAsync()) @@ -185,14 +185,14 @@ public async Task RetryAfter_ConfidentialClient_Async() const int RetryAfterInSeconds = 10; UpdateStatusCodeAndHeaders(tokenResponse.ResponseMessage, 429, RetryAfterInSeconds); - var ex = await Assert.ThrowsExceptionAsync( + var ex = await Assert.ThrowsExactlyAsync( () => app.AcquireTokenForClient(TestConstants.s_scope).ExecuteAsync()) .ConfigureAwait(false); Assert.AreEqual(429, ex.StatusCode); AssertThrottlingCacheEntryCount(throttlingManager, retryAfterEntryCount: 1); - var ex2 = await Assert.ThrowsExceptionAsync( + var ex2 = await Assert.ThrowsExactlyAsync( () => app.AcquireTokenForClient(TestConstants.s_scope).ExecuteAsync()) .ConfigureAwait(false); Assert.AreEqual(429, ex2.StatusCode); @@ -218,7 +218,7 @@ public async Task RetryAfter_ConfidentialClient_ErrorMessage_Async() httpManager.AddInstanceDiscoveryMockHandler(); var tokenResponse = httpManager.AddMockHandlerForThrottledResponseMessage(); - var serverEx = await Assert.ThrowsExceptionAsync( + var serverEx = await Assert.ThrowsExactlyAsync( () => app.AcquireTokenForClient(TestConstants.s_scope).ExecuteAsync()) .ConfigureAwait(false); @@ -249,7 +249,7 @@ public async Task Http429_And503_WithoutRetryAfter_AreThrottled_ByDefaultTimeout var throttlingManager = (httpManagerAndBundle.ServiceBundle.ThrottlingManager as SingletonThrottlingManager); Trace.WriteLine("3. Second call - request is throttled"); - var ex = await Assert.ThrowsExceptionAsync( + var ex = await Assert.ThrowsExactlyAsync( () => app.AcquireTokenSilent(TestConstants.s_scope, account).ExecuteAsync()) .ConfigureAwait(false); Assert.AreEqual(httpStatusCode, ex.StatusCode); @@ -286,7 +286,7 @@ public async Task SimilarRequests_AreThrottled_HttpStatus_Async() AssertThrottlingCacheEntryCount(throttlingManager, httpStatusEntryCount: 1); Trace.WriteLine("A similar request, e.g. with a claims challenge, will be throttled"); - var ex = await Assert.ThrowsExceptionAsync( + var ex = await Assert.ThrowsExactlyAsync( () => app.AcquireTokenSilent(TestConstants.s_scope, account) .WithClaims(TestConstants.Claims) // claims are not part of the strict thumbprint .ExecuteAsync()) @@ -307,7 +307,7 @@ await app.AcquireTokenSilent(new[] { "Other.Scopes" }, account).ExecuteAsync() pca2.UserTokenCacheInternal.Accessor, expiredAccessTokens: true); - await Assert.ThrowsExceptionAsync( + await Assert.ThrowsExactlyAsync( () => pca2.AcquireTokenSilent(TestConstants.s_scope, account) .ExecuteAsync()) .ConfigureAwait(false); @@ -342,7 +342,7 @@ public async Task UiRequiredThrottling_Async() AssertThrottlingCacheEntryCount(throttlingManager, uiRequiredEntryCount: 1); Trace.WriteLine("A similar request will be throttled"); - var ex = await Assert.ThrowsExceptionAsync( + var ex = await Assert.ThrowsExactlyAsync( () => app.AcquireTokenSilent(TestConstants.s_scope, account) .ExecuteAsync()) .ConfigureAwait(false); @@ -351,7 +351,7 @@ public async Task UiRequiredThrottling_Async() Trace.WriteLine("And again..."); - ex = await Assert.ThrowsExceptionAsync( + ex = await Assert.ThrowsExactlyAsync( () => app.AcquireTokenSilent(TestConstants.s_scope, account) .ExecuteAsync()) .ConfigureAwait(false); @@ -395,7 +395,7 @@ public async Task UiRequired_BypassRt_Async() AssertThrottlingCacheEntryCount(throttlingManager, uiRequiredEntryCount: 1); Trace.WriteLine("A similar request will be throttled"); - var ex = await Assert.ThrowsExceptionAsync( + var ex = await Assert.ThrowsExactlyAsync( () => app.AcquireTokenSilent(TestConstants.s_scope, account) .ExecuteAsync()) .ConfigureAwait(false); @@ -438,7 +438,7 @@ public async Task UiRequired_MultipleEntries_Async() Trace.WriteLine("Make another failing request, but with fewer scopes - should not be throttled."); var singleScope = TestConstants.s_scope.Take(1); var account = (await app.GetAccountsAsync().ConfigureAwait(false)).Single(); - var ex = await Assert.ThrowsExceptionAsync( + var ex = await Assert.ThrowsExactlyAsync( () => app.AcquireTokenSilent(singleScope, account).ExecuteAsync()) .ConfigureAwait(false); @@ -492,9 +492,8 @@ private async Task SetupAndAcquireOnceAsync( var account = (await app.GetAccountsAsync().ConfigureAwait(false)).Single(); Trace.WriteLine("2. First failing call "); - var ex = await Assert.ThrowsExceptionAsync( - () => app.AcquireTokenSilent(TestConstants.s_scope, account).ExecuteAsync(), - allowDerived: true) + var ex = await Assert.ThrowsExactlyAsync( + () => app.AcquireTokenSilent(TestConstants.s_scope, account).ExecuteAsync()) .ConfigureAwait(false); Assert.AreEqual(0, httpManager.QueueSize, "No more requests expected"); diff --git a/tests/Microsoft.Identity.Test.Unit/UtilTests/RetryOperationHelperTest.cs b/tests/Microsoft.Identity.Test.Unit/UtilTests/RetryOperationHelperTest.cs index 128d86fd6b..5d0e4dfb0f 100644 --- a/tests/Microsoft.Identity.Test.Unit/UtilTests/RetryOperationHelperTest.cs +++ b/tests/Microsoft.Identity.Test.Unit/UtilTests/RetryOperationHelperTest.cs @@ -43,7 +43,7 @@ public void TestExecuteWithRetry_OperationFails() Func> func = () => operationSimulator.SimulateOperationWithFailuresAsync(); //Act - Exception ex = Assert.ThrowsException( + Exception ex = Assert.ThrowsExactly( () => RetryOperationHelper.ExecuteWithRetryAsync(func, numberOfRetriesToAttempt).Wait()); Assert.AreEqual("OperationSimulator: Simulating Operation Failure", ex.InnerException.Message); @@ -63,7 +63,7 @@ public void TestExecuteWithRetry_OperationFails_VerifyOnFailureActionIsCalled() //Act - Exception ex = Assert.ThrowsException( + Exception ex = Assert.ThrowsExactly( () => RetryOperationHelper.ExecuteWithRetryAsync(func, numberOfRetriesToAttempt, retryTimeSpan, actionUponFailure).Wait()); Assert.AreEqual("OperationSimulator: ThrowException: Exception thrown to identify method", ex.InnerException.Message); } diff --git a/tests/Microsoft.Identity.Test.Unit/WebUITests/DefaultOsBrowserWebUiTests.cs b/tests/Microsoft.Identity.Test.Unit/WebUITests/DefaultOsBrowserWebUiTests.cs index fcf384beea..325abff6b6 100644 --- a/tests/Microsoft.Identity.Test.Unit/WebUITests/DefaultOsBrowserWebUiTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/WebUITests/DefaultOsBrowserWebUiTests.cs @@ -99,7 +99,7 @@ public async Task HttpListenerException_Cancellation_Async() }); // Act - await Assert.ThrowsExceptionAsync( + await Assert.ThrowsExactlyAsync( () => webUI.AcquireAuthorizationAsync( new Uri(TestAuthorizationRequestUri), new Uri(TestRedirectUri), @@ -154,7 +154,7 @@ public async Task DefaultOsBrowserWebUi_ReturnUriInvalid_Async() { string differentPortRedirectUri = TestAuthorizationResponseUri.Replace(TestRedirectUri, "http://localhost:1111"); - MsalClientException ex = await Assert.ThrowsExceptionAsync( + MsalClientException ex = await Assert.ThrowsExactlyAsync( () => AcquireAuthCodeAsync(CreateTestWebUI(), responseUriString: differentPortRedirectUri)) .ConfigureAwait(false); @@ -316,7 +316,7 @@ private void ValidateResponse(SystemWebViewOptions options, bool successResponse private static void AssertInvalidRedirectUri(IWebUI webUI, string uri) { - var ex = Assert.ThrowsException(() => webUI.UpdateRedirectUri(new Uri(uri))); + var ex = Assert.ThrowsExactly(() => webUI.UpdateRedirectUri(new Uri(uri))); Assert.AreEqual(MsalError.LoopbackRedirectUri, ex.ErrorCode); } diff --git a/tests/Microsoft.Identity.Test.Unit/WebUITests/HttpListenerInterceptorTests.cs b/tests/Microsoft.Identity.Test.Unit/WebUITests/HttpListenerInterceptorTests.cs index b36e03a5c9..8a551bd530 100644 --- a/tests/Microsoft.Identity.Test.Unit/WebUITests/HttpListenerInterceptorTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/WebUITests/HttpListenerInterceptorTests.cs @@ -57,7 +57,7 @@ public async Task Cancellation_BeforeTopLevelCall_Async() int port = FindFreeLocalhostPort(); // Start the listener in the background - await Assert.ThrowsExceptionAsync( + await Assert.ThrowsAsync( () => listenerInterceptor.ListenToSingleRequestAndRespondAsync( port, string.Empty, @@ -78,7 +78,7 @@ public async Task Cancellation_BeforeStart_Async() listenerInterceptor.TestBeforeStart = (_) => cts.Cancel(); // Start the listener in the background - await Assert.ThrowsExceptionAsync( + await Assert.ThrowsAsync( () => listenerInterceptor.ListenToSingleRequestAndRespondAsync( port, string.Empty, @@ -151,7 +151,7 @@ public async Task Cancellation_BeforeGetContext_Async() listenerInterceptor.TestBeforeGetContext = () => cts.Cancel(); // Start the listener in the background - await Assert.ThrowsExceptionAsync( + await Assert.ThrowsAsync( () => listenerInterceptor.ListenToSingleRequestAndRespondAsync( port, string.Empty, diff --git a/tests/Microsoft.Identity.Test.Unit/WebUITests/NetCoreWebUIFactoryTests.cs b/tests/Microsoft.Identity.Test.Unit/WebUITests/NetCoreWebUIFactoryTests.cs index 0eb56c6bb8..8f9a70df82 100644 --- a/tests/Microsoft.Identity.Test.Unit/WebUITests/NetCoreWebUIFactoryTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/WebUITests/NetCoreWebUIFactoryTests.cs @@ -43,7 +43,7 @@ public void NetCoreFactory_Embedded() // Arrange // Act - var ex = Assert.ThrowsException( + var ex = Assert.ThrowsExactly( ()=> _webUIFactory.CreateAuthenticationDialog( _parent, WebViewPreference.Embedded, diff --git a/tests/Microsoft.Identity.Test.Unit/pop/PoPTests.cs b/tests/Microsoft.Identity.Test.Unit/pop/PoPTests.cs index 3df5ce5cba..d4afb0b06c 100644 --- a/tests/Microsoft.Identity.Test.Unit/pop/PoPTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/pop/PoPTests.cs @@ -169,14 +169,14 @@ public async Task POP_WithMissingNonceForPCA_Async() HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, new Uri(ProtectedUrl)); - await Assert.ThrowsExceptionAsync(() => + await Assert.ThrowsExactlyAsync(() => app.AcquireTokenInteractive(TestConstants.s_scope.ToArray()) .WithTenantId(TestConstants.Utid) .WithProofOfPossession(null, HttpMethod.Get, new Uri(app.Authority)) .ExecuteAsync()) .ConfigureAwait(false); - await Assert.ThrowsExceptionAsync(() => + await Assert.ThrowsExactlyAsync(() => app.AcquireTokenSilent(TestConstants.s_scope.ToArray(), "loginHint") .WithTenantId(TestConstants.Utid) .WithProofOfPossession(null, HttpMethod.Get, new Uri(app.Authority)) @@ -211,7 +211,7 @@ public async Task PopWhenBrokerIsNotAvailableTest_Async() pca.ServiceBundle.ConfigureMockWebUI(); // Act - var exception = await Assert.ThrowsExceptionAsync(async () => + var exception = await Assert.ThrowsExactlyAsync(async () => { await pca.AcquireTokenInteractive(TestConstants.s_graphScopes) .WithProofOfPossession(TestConstants.Nonce, HttpMethod.Get, new Uri(TestConstants.AuthorityCommonTenant)) @@ -242,7 +242,7 @@ public async Task PopWhenBrokerDoesNotSupportPop_Async() pca.ServiceBundle.Config.BrokerCreatorFunc = (_, _, _) => mockBroker; // Act - MsalClientException ex = await Assert.ThrowsExceptionAsync(async () => + MsalClientException ex = await Assert.ThrowsExactlyAsync(async () => await pca.AcquireTokenInteractive(TestConstants.s_graphScopes) .WithProofOfPossession(TestConstants.Nonce, HttpMethod.Get, new Uri(TestConstants.AuthorityCommonTenant)) .ExecuteAsync() @@ -280,7 +280,7 @@ public async Task PopWhithAdfsUserAndBroker_Async() pca.ServiceBundle.Config.BrokerCreatorFunc = (_, _, _) => mockBroker; // Act - MsalClientException ex = await Assert.ThrowsExceptionAsync(async () => + MsalClientException ex = await Assert.ThrowsExactlyAsync(async () => await pca.AcquireTokenSilent(TestConstants.s_graphScopes, TestConstants.DisplayableId) .WithProofOfPossession(TestConstants.Nonce, HttpMethod.Get, new Uri(TestConstants.AuthorityCommonTenant)) .ExecuteAsync() @@ -498,7 +498,7 @@ public async Task PopWhenBrokerIsNotEnabledForATS_Async() // Act - MsalClientException ex = await Assert.ThrowsExceptionAsync(async () => + MsalClientException ex = await Assert.ThrowsExactlyAsync(async () => await pca.AcquireTokenSilent(TestConstants.s_graphScopes, TestConstants.LocalAccountId) .WithProofOfPossession(TestConstants.Nonce, HttpMethod.Get, new Uri(TestConstants.AuthorityCommonTenant)) .ExecuteAsync() diff --git a/tests/Microsoft.Identity.Test.Unit/pop/PopAuthenticationOperationTests.cs b/tests/Microsoft.Identity.Test.Unit/pop/PopAuthenticationOperationTests.cs index 52c6044f2e..0ac46a2843 100644 --- a/tests/Microsoft.Identity.Test.Unit/pop/PopAuthenticationOperationTests.cs +++ b/tests/Microsoft.Identity.Test.Unit/pop/PopAuthenticationOperationTests.cs @@ -37,14 +37,14 @@ public void NullArgsTest() Uri uri = new Uri("https://www.contoso.com/path1/path2?queryParam1=a&queryParam2=b"); PoPAuthenticationConfiguration config = null; - Assert.ThrowsException(() => new PopAuthenticationOperation(config, harness.ServiceBundle)); + Assert.ThrowsExactly(() => new PopAuthenticationOperation(config, harness.ServiceBundle)); config = new PoPAuthenticationConfiguration(uri); config.PopCryptoProvider = new InMemoryCryptoProvider(); - Assert.ThrowsException(() => new PopAuthenticationOperation(config, null)); - Assert.ThrowsException(() => new PoPAuthenticationConfiguration((HttpRequestMessage)null)); - Assert.ThrowsException(() => new PoPAuthenticationConfiguration((Uri)null)); + Assert.ThrowsExactly(() => new PopAuthenticationOperation(config, null)); + Assert.ThrowsExactly(() => new PoPAuthenticationConfiguration((HttpRequestMessage)null)); + Assert.ThrowsExactly(() => new PoPAuthenticationConfiguration((Uri)null)); } } diff --git a/tests/devapps/NetCoreTestApp/NetCoreTestApp.csproj b/tests/devapps/NetCoreTestApp/NetCoreTestApp.csproj index e382a9d779..e23bca9be4 100644 --- a/tests/devapps/NetCoreTestApp/NetCoreTestApp.csproj +++ b/tests/devapps/NetCoreTestApp/NetCoreTestApp.csproj @@ -4,6 +4,7 @@ Exe net8.0 Debug;Release;Debug + MobileApps + $(NoWarn);MSTest0001